@easbot/codebase 0.3.21 → 0.3.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.en.md +46 -0
  2. package/README.md +46 -0
  3. package/dist/chunks/{chunk-AGZFRKQ4.mjs → chunk-22NIJF4D.mjs} +12 -12
  4. package/dist/chunks/chunk-2DGOSNEH.mjs +34 -0
  5. package/dist/chunks/{chunk-BEQN3CKO.cjs → chunk-HRFLFP6O.cjs} +1 -1
  6. package/dist/chunks/{chunk-YYF5OQDS.cjs → chunk-MRPT44H3.cjs} +22 -22
  7. package/dist/chunks/{chunk-WXWENWCY.mjs → chunk-QQXDOGRV.mjs} +1 -1
  8. package/dist/chunks/chunk-R26JQOPF.mjs +47 -0
  9. package/dist/chunks/{chunk-22PKTMO5.mjs → chunk-T2ZV7FU4.mjs} +19 -19
  10. package/dist/chunks/chunk-VF3U3DPM.cjs +34 -0
  11. package/dist/chunks/{chunk-JWTI3BWI.cjs → chunk-ZCH5GLXA.cjs} +19 -19
  12. package/dist/chunks/{chunk-VFTVDTEY.cjs → chunk-ZK7YSBLG.cjs} +12 -12
  13. package/dist/chunks/cli-handler-2PSSL33N.mjs +1 -0
  14. package/dist/chunks/cli-handler-EYQH2TDL.cjs +1 -0
  15. package/dist/chunks/code-base-2ACRJ2UT.cjs +1 -0
  16. package/dist/chunks/code-base-SNQ2LWU6.mjs +1 -0
  17. package/dist/chunks/database-manager-MG7JMWGN.mjs +1 -0
  18. package/dist/chunks/database-manager-ZDJSRVBR.cjs +1 -0
  19. package/dist/chunks/file-watcher-HVST5PAC.cjs +1 -0
  20. package/dist/chunks/file-watcher-LCQ55MPE.mjs +1 -0
  21. package/dist/chunks/{interfaces-5HZADUYB.mjs → interfaces-DPFLQBQ6.mjs} +1 -1
  22. package/dist/chunks/{interfaces-ORRCH4XV.cjs → interfaces-YX56SVRQ.cjs} +1 -1
  23. package/dist/chunks/{llm-MPD7FHPM.mjs → llm-ADBGTSCV.mjs} +1 -1
  24. package/dist/chunks/{llm-JQV6XWGD.cjs → llm-BDMNIGOH.cjs} +1 -1
  25. package/dist/chunks/stdio-server-7CFU5X3T.cjs +47 -0
  26. package/dist/chunks/stdio-server-UNJPQYXA.mjs +47 -0
  27. package/dist/cli.cjs +1 -1
  28. package/dist/cli.mjs +1 -1
  29. package/dist/index.cjs +1 -1
  30. package/dist/index.d.cts +35 -3
  31. package/dist/index.d.ts +35 -3
  32. package/dist/index.mjs +1 -1
  33. package/package.json +10 -10
  34. package/dist/chunks/chunk-CSMSBVAG.mjs +0 -34
  35. package/dist/chunks/chunk-R74KIJM2.cjs +0 -34
  36. package/dist/chunks/chunk-TR3DFBJH.mjs +0 -47
  37. package/dist/chunks/cli-handler-3I5JC3HY.cjs +0 -1
  38. package/dist/chunks/cli-handler-IJ2PNNTK.mjs +0 -1
  39. package/dist/chunks/code-base-6TM7JDJ6.cjs +0 -1
  40. package/dist/chunks/code-base-BSRUQYXN.mjs +0 -1
  41. package/dist/chunks/database-manager-26PY6VTD.mjs +0 -1
  42. package/dist/chunks/database-manager-U7D7QIHC.cjs +0 -1
  43. package/dist/chunks/file-watcher-GHRFHOQF.cjs +0 -1
  44. package/dist/chunks/file-watcher-OORREWFV.mjs +0 -1
  45. package/dist/chunks/stdio-server-2GBPZY6J.cjs +0 -47
  46. package/dist/chunks/stdio-server-BZYPM34X.mjs +0 -47
  47. /package/dist/chunks/{chunk-TMICZT3L.mjs → chunk-2YMB6W5S.mjs} +0 -0
  48. /package/dist/chunks/{chunk-NVGACA7W.cjs → chunk-M2YU5LAI.cjs} +0 -0
@@ -1,4 +1,4 @@
1
- import {a}from'./chunk-TMICZT3L.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}}},g=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}}},u=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"}),p=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 (
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}}},R=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,
@@ -64,22 +64,22 @@ import {a}from'./chunk-TMICZT3L.mjs';import {Log,Filesystem}from'@easbot/utils';
64
64
  message TEXT NOT NULL,
65
65
  line INTEGER,
66
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 X(o,e=p,t={}){o.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
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(a=>a.id)),n={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(a=>a.id)),targetVersion:e};for(let a of V){if(a.id>e)break;if(r.has(a.id)){n.pending.push(a.id);continue}if(t.dryRun){n.applied.push(a.id);continue}try{o.execBatch([...a.up]),o.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(a.id),r.add(a.id),n.applied.push(a.id),D.info("migration applied",{id:a.id,description:a.description});}catch(i){let l=i instanceof Error?i.message:String(i),T=a.up[0]??"";n.errors.push({migrationId:a.id,sql:T,error:l}),D.warn("migration step failed (may be idempotent)",{id:a.id,error:l,sqlCount:a.up.length});}}return n}function H(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 c=Filesystem.toUnixPath,E=Log.create({service:"codebase-database"}),m=2,$=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:5e3}),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=H(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{X(this.db,p);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){throw 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}),new u("Failed to create database schema",e instanceof Error?[e.message]:[String(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:c(e.file_path)};this.db.prepare(`
70
+ )`);let s=o.prepare("SELECT id FROM schema_migrations").all(),r=new Set(s.map(n=>n.id)),i={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(n=>n.id)),targetVersion:e};for(let n of V){if(n.id>e)break;if(r.has(n.id)){i.pending.push(n.id);continue}if(t.dryRun){i.applied.push(n.id);continue}try{o.execBatch([...n.up]),o.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(n.id),r.add(n.id),i.applied.push(n.id),D.info("migration applied",{id:n.id,description:n.description});}catch(a){let u=a instanceof Error?a.message:String(a),E=n.up[0]??"";i.errors.push({migrationId:n.id,sql:E,error:u}),D.warn("migration step failed (may be idempotent)",{id:n.id,error:u,sqlCount:n.up.length});}}return i}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 c=Filesystem.toUnixPath,l=Log.create({service:"codebase-database"}),N=2,$=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:5e3}),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: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){throw l.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}),new R("Failed to create database schema",e instanceof Error?[e.message]:[String(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:c(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(n=>({...n,file_path:c(n.file_path)})),s=this.db.prepare(`
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(i=>({...i,file_path:c(i.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(n=>{for(let a of n)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(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 a=s.get(n.id);a&&t.run(a.rowid),r.run(n.id,n.name,n.ast_type,n.language,n.file_path,n.text);}catch(a){E.warn("FTS update failed for node",{nodeId:n.id,error:String(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){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(a=>{for(let i of a)try{let l=s.get(i.id);l&&t.run(l.rowid),r.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.text);}catch(l){E.warn("FTS update failed for node",{nodeId:i.id,error:String(l)});}})(e);}insertEdge(e){this.db.prepare(`
76
+ `);this.db.transaction(i=>{for(let n of i)s.run(n.id,n.name,n.ast_type,n.language,n.file_path,n.start_line,n.start_col,n.end_line,n.end_col,n.text,n.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(i);})(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 i of e)try{let n=s.get(i.id);n&&t.run(n.rowid),r.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.text);}catch(n){l.warn("FTS update failed for node",{nodeId:i.id,error:String(n)});}}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: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(n=>{for(let a of n)try{let u=s.get(a.id);u&&t.run(u.rowid),r.run(a.id,a.name,a.ast_type,a.language,a.file_path,a.text);}catch(u){l.warn("FTS update failed for node",{nodeId:a.id,error:String(u)});}})(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 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(`%${c(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 g("Failed to query nodes","queryNodes",n instanceof Error?n:new Error(String(n)))}}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 g("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 g("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(i=>`${i}*`).join(" ");E.debug("searchNodesFts query",{ftsQuery:s});let a=this.db.prepare(`
82
+ `);this.db.transaction(r=>{for(let i of r)t.run(i.id,i.source,i.target,i.relation,i.created_at);})(e);}queryNodes(e){let t=[],s=[];e.filePath&&(t.push("file_path LIKE ?"),s.push(`%${c(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(i){throw new p("Failed to query nodes","queryNodes",i instanceof Error?i:new Error(String(i)))}}findNodesByName(e){if(!e.name)return [];let t=e.limit??50,s=e.file?`%${c(e.file)}%`:null,r=e.kind?`%${e.kind.toLowerCase()}%`:null,i=new Set,n=[],a=(E,g)=>{i.has(E.id)||(i.add(E.id),n.push({node:E,matchKind:g}));},u=(E,g)=>{s&&(E.push("file_path LIKE ?"),g.push(s)),r&&(E.push("LOWER(ast_type) LIKE ?"),g.push(r));};try{let E=["name = ?"],g=[e.name];u(E,g),g.push(t);let T=this.db.prepare(`SELECT * FROM nodes WHERE ${E.join(" AND ")} LIMIT ?`).all(...g);for(let h of T)a(h,"exact");if(T.length>0&&e.file)return n.slice(0,t);if(n.length<t){let h=this.db.prepare("SELECT * FROM nodes WHERE name LIKE ? LIMIT ?").all(`%${e.name}%`,t);for(let m of h)a(m,"qualified");}if(n.length>0&&e.file)return n.slice(0,t);if(n.length===0&&e.name){let h=["name LIKE ?"],m=[`%${e.name}%`];s&&(h.push("file_path LIKE ?"),m.push(s)),r&&(h.push("LOWER(ast_type) LIKE ?"),m.push(r)),h.push("?"),m.push(t);let f=this.db.prepare(`SELECT * FROM nodes WHERE ${h.join(" AND ")}`).all(...m);for(let _ of f)a(_,"substring");}return n.slice(0,t)}catch(E){throw new p("Failed to find nodes by name","findNodesByName",E instanceof Error?E:new Error(String(E)))}}queryEdges(e){let t=[],s=[];if(e.sourceOrTarget&&e.sourceOrTarget.length>0){let i=e.sourceOrTarget.map(()=>"?").join(",");t.push(`(source IN (${i}) OR target IN (${i}))`),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(i){throw new p("Failed to query edges","queryEdges",i instanceof Error?i:new Error(String(i)))}}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(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(a=>`${a}*`).join(" ");l.debug("searchNodesFts query",{ftsQuery:s});let n=this.db.prepare(`
83
83
  SELECT
84
84
  nodes_fts.id,
85
85
  nodes_fts.name,
@@ -97,33 +97,33 @@ import {a}from'./chunk-TMICZT3L.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 E.debug("searchNodesFts done",{resultCount:a.length}),a}catch(s){return E.warn("searchNodesFts failed",{error:String(s)}),[]}}deleteNodesByFile(e){let t=c(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=c(e);return this.db.prepare(`
100
+ `).all(s,t);return l.debug("searchNodesFts done",{resultCount:n.length}),n}catch(s){return l.warn("searchNodesFts failed",{error:String(s)}),[]}}deleteNodesByFile(e){let t=c(e);if(this.ftsAvailable)try{let r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let i of r)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(i.rowid);}catch(r){l.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=c(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
104
  `).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(c(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(c(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(c(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}checkIntegrity(){let e=h=>this.db.prepare(h).get().c,t=h=>e(h),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"),meta:t("SELECT COUNT(*) as c FROM meta")},r=[],n=t(`
107
+ `).run(c(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(c(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}checkIntegrity(){let e=b=>this.db.prepare(b).get().c,t=b=>e(b),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=[],i=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
- `);n>0&&r.push({severity:"error",message:`orphan node_embeddings: ${n}`});let a=t(`
110
+ `);i>0&&r.push({severity:"error",message:`orphan node_embeddings: ${i}`});let n=t(`
111
111
  SELECT COUNT(*) as c FROM edges e WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.source)
112
- `);a>0&&r.push({severity:"error",message:`orphan edges (source): ${a}`});let i=t(`
112
+ `);n>0&&r.push({severity:"error",message:`orphan edges (source): ${n}`});let a=t(`
113
113
  SELECT COUNT(*) as c FROM edges e WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.target)
114
- `);i>0&&r.push({severity:"error",message:`orphan edges (target): ${i}`});let l=t("SELECT COUNT(*) as c FROM edges WHERE source = target");l>0&&r.push({severity:"error",message:`self-loop edges: ${l} \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 f=t(`
114
+ `);a>0&&r.push({severity:"error",message:`orphan edges (target): ${a}`});let u=t("SELECT COUNT(*) as c FROM edges WHERE source = target");u>0&&r.push({severity:"error",message:`self-loop edges: ${u} \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 g=t(`
115
115
  SELECT COUNT(*) as c FROM file_hashes fh
116
116
  WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.file_path = fh.file_path)
117
- `);f>0&&r.push({severity:"warn",message:`orphan file_hashes (no nodes): ${f} \u2014 run \`easbot codebase sync\` to cleanup`});let _=t(`
117
+ `);g>0&&r.push({severity:"warn",message:`orphan file_hashes (no nodes): ${g} \u2014 run \`easbot codebase sync\` to cleanup`});let T=t(`
118
118
  SELECT COUNT(DISTINCT n.file_path) as c FROM nodes n
119
119
  WHERE NOT EXISTS (SELECT 1 FROM file_hashes fh WHERE fh.file_path = n.file_path)
120
- `);_>0&&r.push({severity:"warn",message:`node files without hash: ${_}`});let R=t("SELECT COUNT(*) as c FROM nodes WHERE name IS NULL OR name = ''");R>0&&r.push({severity:"error",message:`nodes with null/empty name: ${R}`});let S=t("SELECT COUNT(*) as c FROM nodes WHERE ast_type IS NULL OR ast_type = ''");S>0&&r.push({severity:"error",message:`nodes with null/empty ast_type: ${S}`});let b=t("SELECT COUNT(*) as c FROM nodes WHERE language IS NULL OR language = ''");b>0&&r.push({severity:"error",message:`nodes with null/empty language: ${b}`});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(`
120
+ `);T>0&&r.push({severity:"warn",message:`node files without hash: ${T}`});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 m=t("SELECT COUNT(*) as c FROM nodes WHERE ast_type IS NULL OR ast_type = ''");m>0&&r.push({severity:"error",message:`nodes with null/empty ast_type: ${m}`});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 _=t("SELECT COUNT(*) as c FROM nodes WHERE file_path IS NULL OR file_path = ''");_>0&&r.push({severity:"error",message:`nodes with null/empty file_path: ${_}`});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
121
  SELECT COUNT(*) as c FROM nodes
122
122
  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(),n={};for(let a of r)n[a.key]=a.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(`
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(),i={};for(let n of r)i[n.key]=n.value;return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:s?.c??0,dbPath:this.dbPath,meta:i,indexState:this.getIndexState(),extractionVersion:parseInt(this.getMeta("indexed_with_extraction_version")??"0",10),isStale:this.isIndexStale()}}setLastSync(){this.db.prepare(`
124
124
  INSERT OR REPLACE INTO meta (key, value)
125
125
  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(m)),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<m}detectAndMarkStaleOnInit(){if(this.isIndexStale()){let e=this.getMeta("indexed_with_extraction_version");E.warn("codebase db is stale",{recorded:e??"(none)",current:String(m),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(`
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(N)),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<N}detectAndMarkStaleOnInit(){if(this.isIndexStale()){let e=this.getMeta("indexed_with_extraction_version");l.warn("codebase db is stale",{recorded:e??"(none)",current:String(N),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
127
  SELECT embedding FROM embedding_cache WHERE content_hash = ?
128
128
  `).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
129
  INSERT OR REPLACE INTO embedding_cache (content_hash, embedding)
@@ -133,7 +133,7 @@ import {a}from'./chunk-TMICZT3L.mjs';import {Log,Filesystem}from'@easbot/utils';
133
133
  `).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
134
  INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
135
135
  VALUES (?, ?, ?)
136
- `);this.db.transaction(r=>{for(let n of r)try{t.run(n.nodeId,n.embeddingText,n.embedding);}catch(a){E.warn("Failed to store embedding for node",{nodeId:n.nodeId,error:String(a)});}})(e);}insertParseError(e){return this.db.prepare(`
136
+ `);this.db.transaction(r=>{for(let i of r)try{t.run(i.nodeId,i.embeddingText,i.embedding);}catch(n){l.warn("Failed to store embedding for node",{nodeId:i.nodeId,error:String(n)});}})(e);}insertParseError(e){return this.db.prepare(`
137
137
  INSERT INTO parse_errors (file_path, language, stage, message, line)
138
138
  VALUES (?, ?, ?, ?, ?)
139
139
  `).run(c(e.filePath),e.language,e.stage,e.message,e.line??null).changes}insertUnresolvedRef(e){return this.db.prepare(`
@@ -144,11 +144,11 @@ import {a}from'./chunk-TMICZT3L.mjs';import {Log,Filesystem}from'@easbot/utils';
144
144
  INSERT INTO unresolved_refs
145
145
  (from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
146
146
  VALUES ${e.map(()=>"(?, ?, ?, ?, ?, ?, ?, ?)").join(", ")}
147
- `,r=[];for(let i of e)r.push(i.fromNodeId??null,i.referenceName,i.referenceKind,i.line??null,i.col??null,c(i.filePath),i.language,i.candidates?JSON.stringify(i.candidates):null);return this.db.prepare(s).run(...r).changes}insertNameSegment(e,t){return this.db.prepare(`
147
+ `,r=[];for(let a of e)r.push(a.fromNodeId??null,a.referenceName,a.referenceKind,a.line??null,a.col??null,c(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
148
  INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES (?, ?)
149
149
  `).run(e,t).changes}insertNameSegmentsBatch(e){if(e.length===0)return 0;let s=`
150
150
  INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES ${e.map(()=>"(?, ?)").join(", ")}
151
- `,r=[];for(let i of e)r.push(i.segment,i.name);return this.db.prepare(s).run(...r).changes}setProjectMetadata(e,t){let s=e==="worktree"||e==="project"?c(t):t;return this.db.prepare(`
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"?c(t):t;return this.db.prepare(`
152
152
  INSERT OR REPLACE INTO project_metadata (key, value, updated_at)
153
153
  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(a=>{for(let i of a)r.run(i);})(s),s.length}initialize(){if(this.closed)throw new g("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,g as b,M as c,u as d,A as e,v as f,x as g,w as h,p as i,V as j,X as k,H as l,m,$ as n,se as o,re as p,ne as q};
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(n=>{for(let a of n)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){l.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,R 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,N as m,$ as n,se as o,re as p,ne as q};
@@ -0,0 +1,34 @@
1
+ 'use strict';var chunkZK7YSBLG_cjs=require('./chunk-ZK7YSBLG.cjs'),chunkM2YU5LAI_cjs=require('./chunk-M2YU5LAI.cjs'),utils=require('@easbot/utils'),types=require('@easbot/types');var C=class extends Error{constructor(n,l,c){super(n);chunkM2YU5LAI_cjs.a(this,"code",l);chunkM2YU5LAI_cjs.a(this,"details",c);this.name="ServiceError";}},T=class extends C{constructor(t,n=[]){super(`Node not found: ${t}`,"NOT_FOUND",{name:t,candidates:n});}},L=class extends C{constructor(t,n){super(`Ambiguous name "${t}" \u2014 ${n.length} candidates`,"AMBIGUOUS",{name:t,candidates:n});}};var ge=utils.Log.create({service:"codebase-service"}),N=utils.Filesystem.toUnixPath;function fe(e,t){let n={exact:1,qualified:.85,substring:.5}[e];return t?Math.min(1,n+.2):n}async function F(e,t,n){if(n.nodeId){let a=e.getNode(n.nodeId);if(!a)throw new T(`nodeId=${n.nodeId}`);return {node:a,candidates:[]}}if(!n.name)throw new C("Either name or nodeId is required","NOT_FOUND",n);let c=e.getDatabase().findNodesByName({name:n.name,file:n.file,kind:n.kind,limit:50});if(c.length===0)throw new T(n.name);let o=!!n.file,d=n.file?N(n.file):null,s=c.map(a=>{let p=d?N(a.node.file_path).endsWith(d)||N(a.node.file_path).includes(d):false;return {node:a.node,score:fe(a.matchKind,p),matchKind:a.matchKind,inFile:p}});if(s.sort((a,p)=>p.score-a.score),s.length===1)return {node:s[0].node,candidates:s.map(a=>({node:a.node,score:a.score}))};let i=s[0].score,r=s.filter(a=>a.score===i);if(r.length===1)return {node:r[0].node,candidates:s.slice(0,10).map(a=>({node:a.node,score:a.score}))};if(o&&r.length>1){let a=r.filter(p=>p.inFile);if(a.length===1)return {node:a[0].node,candidates:s.slice(0,10).map(p=>({node:p.node,score:p.score}))}}throw new L(n.name,s.slice(0,10).map(a=>({node:a.node,score:a.score})))}async function R(e){let t=chunkZK7YSBLG_cjs.c(e.rootDir),n=new chunkZK7YSBLG_cjs.s({workspaceDir:e.workspaceDir,database:{path:t,walMode:true},embedding:types.DEFAULT_EMBEDDING_CONFIG,indexer:types.DEFAULT_INDEXER_CONFIG,parser:types.DEFAULT_PARSER_CONFIG,search:types.DEFAULT_SEARCH_CONFIG,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});return await n.initialize(),n}function X(e,t,n,l){let c=l==="in"?e.source:e.target,o=n.getNodeById(c);return o?{id:o.id,name:o.name,astType:o.ast_type,filePath:N(o.file_path),startLine:o.start_line??0,relation:e.relation}:null}async function V(e,t){let n=Date.now(),d=await(await R(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 i=t.kind.toLowerCase();d=d.filter(r=>r.ast_type.includes(i)||r.name.toLowerCase().includes(i));}if(t.file){let i=N(t.file);d=d.filter(r=>N(r.file_path).endsWith(i)||N(r.file_path).includes(i));}let s=d.map(i=>({nodeId:i.id,name:i.name,kind:i.ast_type??"unknown",filePath:N(i.file_path),startLine:i.start_line,endLine:i.end_line,edges:i.edges??[],source:"basic",score:0,snippet:(i.text??"").slice(0,200).replace(/\s+/g," ").trim()}));return {total:s.length,hits:s,durationMs:Date.now()-n,truncated:false}}async function he(e,t){let n=await R(e),l=n.getQuery(),c=n.getDatabase(),{node:o}=await F(l,e,t),d=[];if(t.includeEdges){let s=t.edgesLimit??50;d=c.queryEdges({sourceOrTarget:[o.id],limit:s});}return {node:o,edges:d}}var ye=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"];async function be(e,t){let n=await R(e),l=n.getQuery(),c=n.getDatabase(),{node:o}=await F(l,e,t);if(!o)return {root:null,nodes:[],edges:[],truncated:false,totalNodes:0,totalEdges:0};let d=t.depth??2,s=t.maxNodes??100,i=t.direction??"both",r=new Map,a=[{nodeId:o.id,depth:0}];r.set(o.id,0);let p=[],u=false;for(;a.length>0;){let f=a.shift();if(f.depth>=d)continue;if(r.size>=s){u=true;break}let h=l.queryNeighbors(f.nodeId,{direction:i,relationTypes:t.relationTypes??ye,limit:s-r.size+1});for(let y of h.edges){p.push(y);let $=y.source===f.nodeId?y.target:y.source;if(!r.has($)&&(r.set($,f.depth+1),a.push({nodeId:$,depth:f.depth+1}),r.size>=s)){u=true;break}}if(u)break}let m=Array.from(r.keys()),x=m.length>0?c.queryNodes({ids:m}):[],g=new Map(x.map(f=>[f.id,f])),b=[];for(let[f,h]of r.entries()){let y=g.get(f);y&&b.push({node:y,depth:h});}return {root:o,nodes:b,edges:p,truncated:u,totalNodes:b.length,totalEdges:p.length}}var xe=["CALLS","IMPORTS","TYPE_REFERENCES"];async function Ee(e,t){let n=await R(e),l=n.getQuery(),c=n.getDatabase(),{node:o}=await F(l,e,t);if(!o)return {root:null,totalImpacted:0,buckets:[]};let d=t.depth??2,s=t.maxResults??50,i=t.relationTypes??xe,r=new Set([o.id]),a=[],p=[o.id];for(let u=1;u<=d&&!(p.length===0||r.size-1>=s);u++){let m=p.map(()=>"?").join(","),x=i.map(()=>"?").join(","),g=c.queryAll(`SELECT source, target, relation FROM edges WHERE target IN (${m}) AND relation IN (${x})`,[...p,...i]),b=[],f=new Set;for(let h of g)if(!r.has(h.source)&&!f.has(h.source)&&(f.add(h.source),r.add(h.source),b.push(h.source),r.size-1>=s))break;if(b.length>0){let h=b.slice(0,10),y=c.queryNodes({ids:h}),$=new Map(y.map(E=>[E.id,E])),q=new Map;for(let E of g)q.has(E.source)||q.set(E.source,E.relation);let ae=h.map(E=>{let B=$.get(E);return {id:E,name:B?.name??"(unknown)",filePath:B?N(B.file_path):"(unknown)",relation:q.get(E)??"CALLS"}});a.push({depth:u,count:b.length,sample:ae});}p=b;}return a.length===0&&ge.warn("impact: no incoming edges found",{root:o.name,depth:d,relationTypes:i}),{root:o,totalImpacted:r.size-1,buckets:a}}var J=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","METHOD_OVERRIDES"];async function Ne(e,t){return Z(e,t)}async function Re(e,t){return ee(e,t)}async function Z(e,t){let n=await R(e),l=n.getQuery(),c=n.getDatabase(),{node:o}=await F(l,e,t);if(!o)return {root:null,callers:[],truncated:false};let d=t.maxResults??20,s=t.relationTypes??J,i=l.queryNeighbors(o.id,{direction:"incoming",relationTypes:s,limit:d+1}),r=[];for(let p of i.edges){let u=X(p,o.id,c,"in");u&&r.push(u);}let a=r.length>d;return {root:o,callers:a?r.slice(0,d):r,truncated:a}}async function ee(e,t){let n=await R(e),l=n.getQuery(),c=n.getDatabase(),{node:o}=await F(l,e,t);if(!o)return {root:null,callees:[],truncated:false};let d=t.maxResults??20,s=t.relationTypes??J,i=l.queryNeighbors(o.id,{direction:"outgoing",relationTypes:s,limit:d+1}),r=[];for(let p of i.edges){let u=X(p,o.id,c,"out");u&&r.push(u);}let a=r.length>d;return {root:o,callees:a?r.slice(0,d):r,truncated:a}}async function Pe(e,t){if(!t.query)throw new C("explore requires a non-empty query","NOT_FOUND",{query:t.query});let l=await R(e);l.getQuery();let o=l.getDatabase(),s=(await V(e,{query:t.query,file:t.file,kind:t.kind,intent:t.intent,maxResults:t.maxFiles??5,enableFts:true,enableEmbedding:true})).hits,i=new Map;for(let p of s){let u=N(p.filePath),m=i.get(u);m?m.push(p):i.set(u,[p]);}let r=t.maxSymbols??3,a=[];for(let[p,u]of i){let m=u.slice(0,r),x=[];for(let g of m){let b=await Z(e,{name:g.name,file:p,kind:t.kind,maxResults:5}),f=await ee(e,{name:g.name,file:p,kind:t.kind,maxResults:5});x.push({node:(()=>{let h={id:g.nodeId,name:g.name,ast_type:g.kind,language:"ts",file_path:g.filePath,start_line:g.startLine??0,end_line:g.endLine??0};try{let y=o.getNodeById(g.nodeId);return {...h,text:y?.text??""}}catch{return {...h,text:""}}})(),callers:b.callers,callees:f.callees});}a.push({file:p,symbols:x});}return {query:t.query,entryPoints:a,totalHits:s.length}}async function Ce(e,t){return await(await R(e)).getStatus()}async function Se(e,t){return await(await R(e)).healthCheck()}var te=utils.Filesystem.toUnixPath;function Ie(e){let t=e.text??"";if(!t)return false;let n=t.slice(0,80);return /\bexport\s/.test(n)||/\bpublic\s/.test(n)?true:(false)}function $e(e){let t=e.text??"";if(!t)return [];let n=t.slice(0,80),l=[];return /\basync\s/.test(n)&&l.push("async"),/\bstatic\s/.test(n)&&l.push("static"),/\babstract\s/.test(n)&&l.push("abstract"),/\breadonly\s/.test(n)&&l.push("readonly"),/\bconst\s/.test(n)&&l.push("const"),/\blet\s/.test(n)&&l.push("let"),l}function P(e){return {id:e.id,name:e.name,astType:e.ast_type,language:e.language,filePath:te(e.file_path),startLine:e.start_line??0,endLine:e.end_line??0,isExported:Ie(e),modifiers:$e(e)}}function I(e,t){return {id:e.id,source:e.source,target:e.target,relation:e.relation,direction:t}}function G(e){return e.map(t=>({node:{id:t.nodeId,name:t.name,astType:t.kind,language:"typescript",filePath:te(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(n=>I({...n}))}))}function K(){return {id:"",name:"",astType:"",language:"",filePath:"",startLine:0,endLine:0,isExported:false,modifiers:[]}}var Fe=utils.Log.create({service:"codebase-format-truncate"}),j="**`",we="**",re=24e3,oe=25e3;async function O(e,t={}){let n=t.softLimit??re,l=t.hardCeiling??oe,c=t.toolName??"codebase",o=t.writeToDisk!==false;if(e.length<=n)return {content:e,truncated:false};let d=e.slice(0,l),s=d.lastIndexOf(`
2
+ ${j}`),i=d.lastIndexOf(`
3
+ `),r;s>l*.5?r=s:i>0?r=i:r=-1;let a=r>0?d.slice(0,r):d,u=a+"\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(!o)return {content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-a.length}/${e.length} characters truncated ...`};try{let m=await utils.TruncateContent.truncate(e,{maxChars:a.length,direction:"head",label:`${c}-output`});return m.truncated?{content:u,truncated:!0,outputPath:m.outputPath,hint:utils.TruncateContent.formatHint(m),info:`... ${m.removedLength}/${m.originalLength} characters truncated ...`}:{content:u,truncated:!0,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-a.length}/${e.length} characters truncated ...`}}catch(m){return Fe.warn("TruncateContent.truncate failed, returning without disk hint",{error:m instanceof Error?m.message:String(m)}),{content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-a.length}/${e.length} characters truncated ...`}}}function _(e,t={}){let n=t.softLimit??re,l=t.hardCeiling??oe;if(e.length<=n)return {content:e,truncated:false};let c=e.slice(0,l),o=c.lastIndexOf(`
4
+ ${j}`),d=c.lastIndexOf(`
5
+ `),s;o>l*.5?s=o:d>0?s=d:s=-1;let i=s>0?c.slice(0,s):c;return {content:i+`
6
+
7
+ ... (output truncated; tail dropped at section boundary)`,truncated:true,outputPath:"",hint:"",info:`... ${e.length-i.length}/${e.length} characters truncated ...`}}function ke(e,t=Date.now()){let n=Math.max(0,Math.floor((t-e)/1e3));return n>60?">60s ago":`${n}s ago`}function D(e,t){if(!e||e.length===0)return null;let n=e.filter(c=>t.has(c.path));return n.length===0?null:`\u26A0\uFE0F Index may be stale for: ${n.map(c=>`${c.path} (edited ${ke(c.lastEventAt)})`).join(", ")}
8
+
9
+ `}function w(e,t,n={}){return (se[e]??se.default).replace(/<(\w+)>/g,(c,o)=>o==="tool"?t:n[o]??`<${o}>`)}var se={search:`---
10
+
11
+ > **Complete source for N files is included above \u2014 do NOT re-read them.**
12
+ > 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:`---
13
+
14
+ > **Output truncated to budget; the content above is the source of truth.**
15
+ > For more detail, call \`<tool>\` with refined parameters.`};async function v(e,t){let{pendingFiles:n,toolName:l,sync:c=false}=t;if(e.length===0)return k(l,"No matches found.","Try broader search terms, or use `explore` to read source.");let o=Oe(e),d=new Set(o.keys()),s=[];s.push(D(n,d)??"");let i="[[codebase-search-summary]]";s.push(i+`
16
+ `);let r=e.length;s.push(`**Files with matches:** ${o.size}
17
+ `);for(let[m,x]of o){let g=x.map(y=>y.node.name),b=g.slice(0,5).join(", "),f=g.length>5?`, +${g.length-5} more`:"";s.push(`**\`${m}\`** \u2014 ${b}${f}
18
+ `);let h=x[0]?.node.language??"";s.push("```"+h);for(let y of x)s.push(`L${y.node.startLine} ${y.snippet}`);s.push("```\n");}s.push(w("search",l,{}));let a=s.join(`
19
+ `),p=`Found ${r} symbol${r===1?"":"s"} across ${o.size} file${o.size===1?"":"s"}.`,u=a.replace(i,p);return A(u,t,c)}async function H(e,t,n){let{pendingFiles:l,toolName:c,sync:o=false}=n;if(t.length===0||t.every(r=>r.count===0))return k(c,`No incoming edges for \`${e.name}\`.`,"This symbol has no callers \u2014 safe to refactor.");let d=t.reduce((r,a)=>r+a.count,0),s=Ae(d),i=[];i.push(D(l,new Set([e.filePath]))??""),i.push(`**Impact for \`${e.name}\`** (root: ${e.filePath}:${e.startLine}, total impacted: ${d})
20
+ `);for(let r of t){i.push(`- **d=${r.depth}** (${r.count} nodes) \u2014 ${r.riskLabel}`);for(let a of r.samples.slice(0,5))i.push(` - \`${a.name}\` ${a.file}:${a.line} [${a.relation}]`);r.samples.length>5&&i.push(` - ... and ${r.samples.length-5} more`);}return i.push(w("impact",c,{root:e.name,riskLevel:s})),A(i.join(`
21
+ `),n,o)}function Ae(e){return e>=100?"CRITICAL":e>=50?"HIGH":e>=10?"MEDIUM":"LOW"}function Q(e){return e===1?"WILL BREAK (direct callers)":e===2?"LIKELY AFFECTED (indirect)":"MAY NEED TESTING (transitive)"}async function z(e,t){let{root:n,incoming:l,outgoing:c,neighbors:o}=e,{pendingFiles:d,toolName:s,sync:i=false}=t;if(l.length===0&&c.length===0&&o.length===0)return k(s,`No relations found for \`${n.name}\`.`,"This is a leaf node.");let r=[];r.push(D(d,new Set([n.filePath]))??""),r.push(`**Context for \`${n.name}\`** (${n.astType}, ${n.language}, ${n.filePath}:${n.startLine})
22
+ `),r.push(`**Incoming** (${l.length}):`);for(let a of l.slice(0,10))r.push(`- ${a.source} \u2192 [${a.relation}] \u2192 \`${n.name}\``);l.length>10&&r.push(`- ... and ${l.length-10} more`),r.push(""),r.push(`**Outgoing** (${c.length}):`);for(let a of c.slice(0,10))r.push(`- \`${n.name}\` \u2192 [${a.relation}] \u2192 ${a.target}`);if(c.length>10&&r.push(`- ... and ${c.length-10} more`),r.push(""),o.length>0){r.push(`**Neighbors** (${o.length}):`);for(let a of o.slice(0,20))r.push(`- [d=${a.depth}] \`${a.node.name}\` (${a.node.astType}) ${a.node.filePath}:${a.node.startLine}`);o.length>20&&r.push(`- ... and ${o.length-20} more`),r.push("");}return r.push(w("context",s,{})),A(r.join(`
23
+ `),t,i)}async function M(e,t,n){let{pendingFiles:l,toolName:c,sync:o=false}=n;if(!e.id)return k(c,"Node not found.","Check the node ID or use `search` to find it.");let d=t.filter(r=>r.direction==="in"),s=t.filter(r=>r.direction==="out"),i=[];i.push(D(l,new Set([e.filePath]))??""),i.push(`**Node: \`${e.name}\`**
24
+ `),i.push(`- ID: \`${e.id}\``),i.push(`- Kind: ${e.astType}`),i.push(`- Language: ${e.language}`),i.push(`- Location: ${e.filePath}:${e.startLine}-${e.endLine}`),i.push(`- Exported: ${e.isExported}`),e.modifiers.length>0&&i.push(`- Modifiers: ${e.modifiers.join(", ")}`),i.push(""),i.push(`**Edges** (incoming: ${d.length} / outgoing: ${s.length}):`);for(let r of d.slice(0,5))i.push(`- \u2190 [${r.relation}] ${r.source}`);for(let r of s.slice(0,5))i.push(`- \u2192 [${r.relation}] ${r.target}`);return t.length>10&&i.push(`- ... and ${t.length-10} more`),i.push(w("default",c,{})),A(i.join(`
25
+ `),n,o)}async function ie(e,t){let{entryPoints:n,totalHits:l,query:c}=e,{toolName:o,sync:d=false}=t;if(n.length===0)return k(o,`No matches for \`${c}\`.`,"Try broader search terms, or use `callers` / `callees` to traverse from a known symbol.");let s=[];s.push(`## Code Context
26
+ `),s.push(`**Query:** ${c} `),s.push(`**Total hits:** ${l} `),s.push(`**Entry points:** ${n.length}
27
+ `);for(let i of n){s.push(`**\`${i.file}\`** \u2014 ${i.symbols.length} symbol${i.symbols.length===1?"":"s"}
28
+ `);for(let r of i.symbols){let a=(r.source??"").trim()||"(source not included)",p=r.node.language;if(s.push("```"+p),s.push(`L${r.node.startLine}-L${r.node.endLine} ${r.node.name} (${r.node.astType}${r.node.modifiers.length>0?`, ${r.node.modifiers.join(" ")}`:""})`),s.push(""),s.push(a),s.push("```\n"),r.callers.length>0){s.push(`**Callers of \`${r.node.name}\` (${r.callers.length}):**`);for(let u of r.callers.slice(0,5))s.push(`- [${u.relation}] \`${u.name}\` ${u.filePath}:${u.startLine}`);r.callers.length>5&&s.push(`- ... and ${r.callers.length-5} more`),s.push("");}if(r.callees.length>0){s.push(`**Callees of \`${r.node.name}\` (${r.callees.length}):**`);for(let u of r.callees.slice(0,5))s.push(`- [${u.relation}] \`${u.name}\` ${u.filePath}:${u.startLine}`);r.callees.length>5&&s.push(`- ... and ${r.callees.length-5} more`),s.push("");}}}return s.push(`---
29
+ `),s.push(w("context",o,{})),A(s.join(`
30
+ `),t,d)}function Oe(e){let t=new Map;for(let n of e){let l=n.node.filePath,c=t.get(l);c?c.push(n):t.set(l,[n]);}return t}function k(e,t,n){return `**${e}**
31
+
32
+ ${t}
33
+
34
+ > **Tip:** ${n}`}async function A(e,t,n){let l={softLimit:t.softLimit,hardCeiling:t.hardCeiling,toolName:t.toolName,writeToDisk:n?false:t.writeToDisk};return (n?_(e,l):await O(e,l)).content}var De=utils.Log.create({service:"codebase-format-render"});async function ve(e,t){if(e.length===0)return v([],t);let n=G(e);return v(n,t)}async function He(e,t,n){if(t.length===0)return H(P(e),[],n);let l=[{depth:1,count:t.length,riskLabel:Q(1),samples:t.slice(0,10).map(c=>({name:c.source.name,file:P(c.source).filePath,line:c.source.start_line??0,relation:c.relation}))}];return H(P(e),l,n)}async function Me(e,t,n,l,c){let o=P(e),d=t.map(r=>I(r,"in")),s=n.map(r=>I(r,"out")),i=l.map(r=>({node:P(r),depth:1}));return z({root:o,incoming:d,outgoing:s,neighbors:i},c)}async function qe(e,t,n){if(!e)return M(K(),[],n);let l=P(e),c=t.map(o=>{let d=o.target===e.id?"in":"out";return I(o,d)});return M(l,c,n)}async function Be(e,t){let n={query:e.query,totalHits:e.totalHits,entryPoints:e.entryPoints.map(l=>({file:l.file,symbols:l.symbols.map(c=>({node:P(c.node),source:c.node.text??"",callers:c.callers.map(o=>({name:o.name,filePath:o.filePath,startLine:o.startLine,relation:o.relation})),callees:c.callees.map(o=>({name:o.name,filePath:o.filePath,startLine:o.startLine,relation:o.relation}))}))}))};return ie(n,t)}De.debug("format/render.ts loaded");exports.A=He;exports.B=Me;exports.C=qe;exports.D=Be;exports.a=C;exports.b=T;exports.c=L;exports.d=V;exports.e=he;exports.f=be;exports.g=Ee;exports.h=Ne;exports.i=Re;exports.j=Pe;exports.k=Ce;exports.l=Se;exports.m=P;exports.n=I;exports.o=G;exports.p=K;exports.q=j;exports.r=we;exports.s=O;exports.t=_;exports.u=v;exports.v=H;exports.w=Q;exports.x=z;exports.y=M;exports.z=ve;
@@ -1,4 +1,4 @@
1
- 'use strict';var chunkNVGACA7W_cjs=require('./chunk-NVGACA7W.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database');var F=class o extends Error{constructor(t,s,r){super(t);chunkNVGACA7W_cjs.a(this,"name","ParserError");chunkNVGACA7W_cjs.a(this,"filePath");chunkNVGACA7W_cjs.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}}},g=class o extends Error{constructor(t,s,r){super(t);chunkNVGACA7W_cjs.a(this,"name","DatabaseError");chunkNVGACA7W_cjs.a(this,"operation");chunkNVGACA7W_cjs.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);chunkNVGACA7W_cjs.a(this,"name","FileSystemError");chunkNVGACA7W_cjs.a(this,"filePath");chunkNVGACA7W_cjs.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}}},u=class o extends Error{constructor(t,s){super(t);chunkNVGACA7W_cjs.a(this,"name","SchemaError");chunkNVGACA7W_cjs.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);chunkNVGACA7W_cjs.a(this,"name","ConfigError");chunkNVGACA7W_cjs.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);chunkNVGACA7W_cjs.a(this,"name","IndexError");chunkNVGACA7W_cjs.a(this,"filePath");chunkNVGACA7W_cjs.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);chunkNVGACA7W_cjs.a(this,"name","QueryError");chunkNVGACA7W_cjs.a(this,"params");chunkNVGACA7W_cjs.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}`);chunkNVGACA7W_cjs.a(this,"name","UnsupportedLanguageError");chunkNVGACA7W_cjs.a(this,"extension");chunkNVGACA7W_cjs.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 P=utils.Log.create({service:"codebase-schema-migrations"}),p=1,W=[{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 (
1
+ 'use strict';var chunkM2YU5LAI_cjs=require('./chunk-M2YU5LAI.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database');var F=class o extends Error{constructor(t,s,r){super(t);chunkM2YU5LAI_cjs.a(this,"name","ParserError");chunkM2YU5LAI_cjs.a(this,"filePath");chunkM2YU5LAI_cjs.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);chunkM2YU5LAI_cjs.a(this,"name","DatabaseError");chunkM2YU5LAI_cjs.a(this,"operation");chunkM2YU5LAI_cjs.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);chunkM2YU5LAI_cjs.a(this,"name","FileSystemError");chunkM2YU5LAI_cjs.a(this,"filePath");chunkM2YU5LAI_cjs.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}}},R=class o extends Error{constructor(t,s){super(t);chunkM2YU5LAI_cjs.a(this,"name","SchemaError");chunkM2YU5LAI_cjs.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);chunkM2YU5LAI_cjs.a(this,"name","ConfigError");chunkM2YU5LAI_cjs.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);chunkM2YU5LAI_cjs.a(this,"name","IndexError");chunkM2YU5LAI_cjs.a(this,"filePath");chunkM2YU5LAI_cjs.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);chunkM2YU5LAI_cjs.a(this,"name","QueryError");chunkM2YU5LAI_cjs.a(this,"params");chunkM2YU5LAI_cjs.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}`);chunkM2YU5LAI_cjs.a(this,"name","UnsupportedLanguageError");chunkM2YU5LAI_cjs.a(this,"extension");chunkM2YU5LAI_cjs.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 P=utils.Log.create({service:"codebase-schema-migrations"}),S=1,W=[{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,
@@ -64,22 +64,22 @@
64
64
  message TEXT NOT NULL,
65
65
  line INTEGER,
66
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(o,e=p,t={}){o.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
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(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(a=>a.id)),n={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(a=>a.id)),targetVersion:e};for(let a of W){if(a.id>e)break;if(r.has(a.id)){n.pending.push(a.id);continue}if(t.dryRun){n.applied.push(a.id);continue}try{o.execBatch([...a.up]),o.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(a.id),r.add(a.id),n.applied.push(a.id),P.info("migration applied",{id:a.id,description:a.description});}catch(i){let l=i instanceof Error?i.message:String(i),T=a.up[0]??"";n.errors.push({migrationId:a.id,sql:T,error:l}),P.warn("migration step failed (may be idempotent)",{id:a.id,error:l,sqlCount:a.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 c=utils.Filesystem.toUnixPath,E=utils.Log.create({service:"codebase-database"}),m=2,H=class{constructor(e){chunkNVGACA7W_cjs.a(this,"db");chunkNVGACA7W_cjs.a(this,"dbPath");chunkNVGACA7W_cjs.a(this,"closed",false);chunkNVGACA7W_cjs.a(this,"ftsAvailable",false);this.dbPath=e===":memory:"?e:utils.Filesystem.normalize(e),this.db=database.createSyncSqliteConnection({path:this.dbPath,backend:"better-sqlite3",walMode:true,foreignKeys:true,busyTimeoutMs:5e3}),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{D(this.db,p);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){throw 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}),new u("Failed to create database schema",e instanceof Error?[e.message]:[String(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:c(e.file_path)};this.db.prepare(`
70
+ )`);let s=o.prepare("SELECT id FROM schema_migrations").all(),r=new Set(s.map(n=>n.id)),i={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(n=>n.id)),targetVersion:e};for(let n of W){if(n.id>e)break;if(r.has(n.id)){i.pending.push(n.id);continue}if(t.dryRun){i.applied.push(n.id);continue}try{o.execBatch([...n.up]),o.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(n.id),r.add(n.id),i.applied.push(n.id),P.info("migration applied",{id:n.id,description:n.description});}catch(a){let u=a instanceof Error?a.message:String(a),E=n.up[0]??"";i.errors.push({migrationId:n.id,sql:E,error:u}),P.warn("migration step failed (may be idempotent)",{id:n.id,error:u,sqlCount:n.up.length});}}return i}function H(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 c=utils.Filesystem.toUnixPath,l=utils.Log.create({service:"codebase-database"}),N=2,X=class{constructor(e){chunkM2YU5LAI_cjs.a(this,"db");chunkM2YU5LAI_cjs.a(this,"dbPath");chunkM2YU5LAI_cjs.a(this,"closed",false);chunkM2YU5LAI_cjs.a(this,"ftsAvailable",false);this.dbPath=e===":memory:"?e:utils.Filesystem.normalize(e),this.db=database.createSyncSqliteConnection({path:this.dbPath,backend:"better-sqlite3",walMode:true,foreignKeys:true,busyTimeoutMs:5e3}),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:String(t)});}try{this.ensureSchema();let t=H(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,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){throw l.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}),new R("Failed to create database schema",e instanceof Error?[e.message]:[String(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:c(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(n=>({...n,file_path:c(n.file_path)})),s=this.db.prepare(`
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(i=>({...i,file_path:c(i.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(n=>{for(let a of n)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(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 a=s.get(n.id);a&&t.run(a.rowid),r.run(n.id,n.name,n.ast_type,n.language,n.file_path,n.text);}catch(a){E.warn("FTS update failed for node",{nodeId:n.id,error:String(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){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(a=>{for(let i of a)try{let l=s.get(i.id);l&&t.run(l.rowid),r.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.text);}catch(l){E.warn("FTS update failed for node",{nodeId:i.id,error:String(l)});}})(e);}insertEdge(e){this.db.prepare(`
76
+ `);this.db.transaction(i=>{for(let n of i)s.run(n.id,n.name,n.ast_type,n.language,n.file_path,n.start_line,n.start_col,n.end_line,n.end_col,n.text,n.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(i);})(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 i of e)try{let n=s.get(i.id);n&&t.run(n.rowid),r.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.text);}catch(n){l.warn("FTS update failed for node",{nodeId:i.id,error:String(n)});}}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: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(n=>{for(let a of n)try{let u=s.get(a.id);u&&t.run(u.rowid),r.run(a.id,a.name,a.ast_type,a.language,a.file_path,a.text);}catch(u){l.warn("FTS update failed for node",{nodeId:a.id,error:String(u)});}})(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 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(`%${c(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 g("Failed to query nodes","queryNodes",n instanceof Error?n:new Error(String(n)))}}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 g("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 g("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(i=>`${i}*`).join(" ");E.debug("searchNodesFts query",{ftsQuery:s});let a=this.db.prepare(`
82
+ `);this.db.transaction(r=>{for(let i of r)t.run(i.id,i.source,i.target,i.relation,i.created_at);})(e);}queryNodes(e){let t=[],s=[];e.filePath&&(t.push("file_path LIKE ?"),s.push(`%${c(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(i){throw new p("Failed to query nodes","queryNodes",i instanceof Error?i:new Error(String(i)))}}findNodesByName(e){if(!e.name)return [];let t=e.limit??50,s=e.file?`%${c(e.file)}%`:null,r=e.kind?`%${e.kind.toLowerCase()}%`:null,i=new Set,n=[],a=(E,g)=>{i.has(E.id)||(i.add(E.id),n.push({node:E,matchKind:g}));},u=(E,g)=>{s&&(E.push("file_path LIKE ?"),g.push(s)),r&&(E.push("LOWER(ast_type) LIKE ?"),g.push(r));};try{let E=["name = ?"],g=[e.name];u(E,g),g.push(t);let T=this.db.prepare(`SELECT * FROM nodes WHERE ${E.join(" AND ")} LIMIT ?`).all(...g);for(let h of T)a(h,"exact");if(T.length>0&&e.file)return n.slice(0,t);if(n.length<t){let h=this.db.prepare("SELECT * FROM nodes WHERE name LIKE ? LIMIT ?").all(`%${e.name}%`,t);for(let m of h)a(m,"qualified");}if(n.length>0&&e.file)return n.slice(0,t);if(n.length===0&&e.name){let h=["name LIKE ?"],m=[`%${e.name}%`];s&&(h.push("file_path LIKE ?"),m.push(s)),r&&(h.push("LOWER(ast_type) LIKE ?"),m.push(r)),h.push("?"),m.push(t);let f=this.db.prepare(`SELECT * FROM nodes WHERE ${h.join(" AND ")}`).all(...m);for(let _ of f)a(_,"substring");}return n.slice(0,t)}catch(E){throw new p("Failed to find nodes by name","findNodesByName",E instanceof Error?E:new Error(String(E)))}}queryEdges(e){let t=[],s=[];if(e.sourceOrTarget&&e.sourceOrTarget.length>0){let i=e.sourceOrTarget.map(()=>"?").join(",");t.push(`(source IN (${i}) OR target IN (${i}))`),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(i){throw new p("Failed to query edges","queryEdges",i instanceof Error?i:new Error(String(i)))}}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(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(a=>`${a}*`).join(" ");l.debug("searchNodesFts query",{ftsQuery:s});let n=this.db.prepare(`
83
83
  SELECT
84
84
  nodes_fts.id,
85
85
  nodes_fts.name,
@@ -97,33 +97,33 @@
97
97
  WHERE nodes_fts.text MATCH ?
98
98
  ORDER BY score DESC
99
99
  LIMIT ?
100
- `).all(s,t);return E.debug("searchNodesFts done",{resultCount:a.length}),a}catch(s){return E.warn("searchNodesFts failed",{error:String(s)}),[]}}deleteNodesByFile(e){let t=c(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=c(e);return this.db.prepare(`
100
+ `).all(s,t);return l.debug("searchNodesFts done",{resultCount:n.length}),n}catch(s){return l.warn("searchNodesFts failed",{error:String(s)}),[]}}deleteNodesByFile(e){let t=c(e);if(this.ftsAvailable)try{let r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let i of r)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(i.rowid);}catch(r){l.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=c(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
104
  `).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(c(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(c(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(c(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}checkIntegrity(){let e=h=>this.db.prepare(h).get().c,t=h=>e(h),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"),meta:t("SELECT COUNT(*) as c FROM meta")},r=[],n=t(`
107
+ `).run(c(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(c(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}checkIntegrity(){let e=b=>this.db.prepare(b).get().c,t=b=>e(b),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=[],i=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
- `);n>0&&r.push({severity:"error",message:`orphan node_embeddings: ${n}`});let a=t(`
110
+ `);i>0&&r.push({severity:"error",message:`orphan node_embeddings: ${i}`});let n=t(`
111
111
  SELECT COUNT(*) as c FROM edges e WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.source)
112
- `);a>0&&r.push({severity:"error",message:`orphan edges (source): ${a}`});let i=t(`
112
+ `);n>0&&r.push({severity:"error",message:`orphan edges (source): ${n}`});let a=t(`
113
113
  SELECT COUNT(*) as c FROM edges e WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.target)
114
- `);i>0&&r.push({severity:"error",message:`orphan edges (target): ${i}`});let l=t("SELECT COUNT(*) as c FROM edges WHERE source = target");l>0&&r.push({severity:"error",message:`self-loop edges: ${l} \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 f=t(`
114
+ `);a>0&&r.push({severity:"error",message:`orphan edges (target): ${a}`});let u=t("SELECT COUNT(*) as c FROM edges WHERE source = target");u>0&&r.push({severity:"error",message:`self-loop edges: ${u} \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 g=t(`
115
115
  SELECT COUNT(*) as c FROM file_hashes fh
116
116
  WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.file_path = fh.file_path)
117
- `);f>0&&r.push({severity:"warn",message:`orphan file_hashes (no nodes): ${f} \u2014 run \`easbot codebase sync\` to cleanup`});let _=t(`
117
+ `);g>0&&r.push({severity:"warn",message:`orphan file_hashes (no nodes): ${g} \u2014 run \`easbot codebase sync\` to cleanup`});let T=t(`
118
118
  SELECT COUNT(DISTINCT n.file_path) as c FROM nodes n
119
119
  WHERE NOT EXISTS (SELECT 1 FROM file_hashes fh WHERE fh.file_path = n.file_path)
120
- `);_>0&&r.push({severity:"warn",message:`node files without hash: ${_}`});let R=t("SELECT COUNT(*) as c FROM nodes WHERE name IS NULL OR name = ''");R>0&&r.push({severity:"error",message:`nodes with null/empty name: ${R}`});let S=t("SELECT COUNT(*) as c FROM nodes WHERE ast_type IS NULL OR ast_type = ''");S>0&&r.push({severity:"error",message:`nodes with null/empty ast_type: ${S}`});let b=t("SELECT COUNT(*) as c FROM nodes WHERE language IS NULL OR language = ''");b>0&&r.push({severity:"error",message:`nodes with null/empty language: ${b}`});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(`
120
+ `);T>0&&r.push({severity:"warn",message:`node files without hash: ${T}`});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 m=t("SELECT COUNT(*) as c FROM nodes WHERE ast_type IS NULL OR ast_type = ''");m>0&&r.push({severity:"error",message:`nodes with null/empty ast_type: ${m}`});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 _=t("SELECT COUNT(*) as c FROM nodes WHERE file_path IS NULL OR file_path = ''");_>0&&r.push({severity:"error",message:`nodes with null/empty file_path: ${_}`});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
121
  SELECT COUNT(*) as c FROM nodes
122
122
  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(),n={};for(let a of r)n[a.key]=a.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(`
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(),i={};for(let n of r)i[n.key]=n.value;return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:s?.c??0,dbPath:this.dbPath,meta:i,indexState:this.getIndexState(),extractionVersion:parseInt(this.getMeta("indexed_with_extraction_version")??"0",10),isStale:this.isIndexStale()}}setLastSync(){this.db.prepare(`
124
124
  INSERT OR REPLACE INTO meta (key, value)
125
125
  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(m)),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<m}detectAndMarkStaleOnInit(){if(this.isIndexStale()){let e=this.getMeta("indexed_with_extraction_version");E.warn("codebase db is stale",{recorded:e??"(none)",current:String(m),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(`
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(N)),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<N}detectAndMarkStaleOnInit(){if(this.isIndexStale()){let e=this.getMeta("indexed_with_extraction_version");l.warn("codebase db is stale",{recorded:e??"(none)",current:String(N),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
127
  SELECT embedding FROM embedding_cache WHERE content_hash = ?
128
128
  `).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
129
  INSERT OR REPLACE INTO embedding_cache (content_hash, embedding)
@@ -133,7 +133,7 @@
133
133
  `).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
134
  INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
135
135
  VALUES (?, ?, ?)
136
- `);this.db.transaction(r=>{for(let n of r)try{t.run(n.nodeId,n.embeddingText,n.embedding);}catch(a){E.warn("Failed to store embedding for node",{nodeId:n.nodeId,error:String(a)});}})(e);}insertParseError(e){return this.db.prepare(`
136
+ `);this.db.transaction(r=>{for(let i of r)try{t.run(i.nodeId,i.embeddingText,i.embedding);}catch(n){l.warn("Failed to store embedding for node",{nodeId:i.nodeId,error:String(n)});}})(e);}insertParseError(e){return this.db.prepare(`
137
137
  INSERT INTO parse_errors (file_path, language, stage, message, line)
138
138
  VALUES (?, ?, ?, ?, ?)
139
139
  `).run(c(e.filePath),e.language,e.stage,e.message,e.line??null).changes}insertUnresolvedRef(e){return this.db.prepare(`
@@ -144,11 +144,11 @@
144
144
  INSERT INTO unresolved_refs
145
145
  (from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
146
146
  VALUES ${e.map(()=>"(?, ?, ?, ?, ?, ?, ?, ?)").join(", ")}
147
- `,r=[];for(let i of e)r.push(i.fromNodeId??null,i.referenceName,i.referenceKind,i.line??null,i.col??null,c(i.filePath),i.language,i.candidates?JSON.stringify(i.candidates):null);return this.db.prepare(s).run(...r).changes}insertNameSegment(e,t){return this.db.prepare(`
147
+ `,r=[];for(let a of e)r.push(a.fromNodeId??null,a.referenceName,a.referenceKind,a.line??null,a.col??null,c(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
148
  INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES (?, ?)
149
149
  `).run(e,t).changes}insertNameSegmentsBatch(e){if(e.length===0)return 0;let s=`
150
150
  INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES ${e.map(()=>"(?, ?)").join(", ")}
151
- `,r=[];for(let i of e)r.push(i.segment,i.name);return this.db.prepare(s).run(...r).changes}setProjectMetadata(e,t){let s=e==="worktree"||e==="project"?c(t):t;return this.db.prepare(`
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"?c(t):t;return this.db.prepare(`
152
152
  INSERT OR REPLACE INTO project_metadata (key, value, updated_at)
153
153
  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(a=>{for(let i of a)r.run(i);})(s),s.length}initialize(){if(this.closed)throw new g("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 te(o){return o.isClosed()}function se(o){return o.getDbPath()}function re(o,e){return o.transaction(e)}exports.a=F;exports.b=g;exports.c=M;exports.d=u;exports.e=A;exports.f=v;exports.g=x;exports.h=w;exports.i=p;exports.j=W;exports.k=D;exports.l=X;exports.m=m;exports.n=H;exports.o=te;exports.p=se;exports.q=re;
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(n=>{for(let a of n)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){l.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 te(o){return o.isClosed()}function se(o){return o.getDbPath()}function re(o,e){return o.transaction(e)}exports.a=F;exports.b=p;exports.c=M;exports.d=R;exports.e=A;exports.f=v;exports.g=x;exports.h=w;exports.i=S;exports.j=W;exports.k=D;exports.l=H;exports.m=N;exports.n=X;exports.o=te;exports.p=se;exports.q=re;