@easbot/codebase 0.3.23 → 0.3.24

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 (42) hide show
  1. package/dist/chunks/chunk-4HJ7RFP7.cjs +1 -0
  2. package/dist/chunks/{chunk-UAWXUGY5.cjs → chunk-5E5YY2J3.cjs} +22 -22
  3. package/dist/chunks/{chunk-XXH7ZLAJ.mjs → chunk-AIUVBWJX.mjs} +22 -22
  4. package/dist/chunks/{chunk-GWR5LCUV.mjs → chunk-EWVG3S6R.mjs} +22 -22
  5. package/dist/chunks/chunk-NF6CVHEK.cjs +203 -0
  6. package/dist/chunks/{chunk-3NTIN3AN.cjs → chunk-PLI6SXTS.cjs} +22 -22
  7. package/dist/chunks/chunk-SQJ64NFE.mjs +58 -0
  8. package/dist/chunks/chunk-STDI2Q67.mjs +203 -0
  9. package/dist/chunks/chunk-WC5CUSXD.cjs +58 -0
  10. package/dist/chunks/chunk-ZPEE2LSX.mjs +1 -0
  11. package/dist/chunks/cli-handler-SF3CJR3N.mjs +1 -0
  12. package/dist/chunks/cli-handler-WMBILZ4H.cjs +1 -0
  13. package/dist/chunks/code-base-DJZICYWH.cjs +1 -0
  14. package/dist/chunks/{code-base-HAX5SGRL.mjs → code-base-Y6HLPDF3.mjs} +1 -1
  15. package/dist/chunks/database-manager-MOJW62MZ.cjs +1 -0
  16. package/dist/chunks/database-manager-X7H4U45I.mjs +1 -0
  17. package/dist/chunks/file-watcher-QS442D52.cjs +1 -0
  18. package/dist/chunks/file-watcher-X56TEWNY.mjs +1 -0
  19. package/dist/chunks/stdio-server-OHQSGNMK.cjs +47 -0
  20. package/dist/chunks/stdio-server-OJGV4CSS.mjs +47 -0
  21. package/dist/cli.cjs +1 -1
  22. package/dist/cli.mjs +1 -1
  23. package/dist/index.cjs +1 -1
  24. package/dist/index.d.cts +13 -1
  25. package/dist/index.d.ts +13 -1
  26. package/dist/index.mjs +1 -1
  27. package/package.json +8 -8
  28. package/dist/chunks/chunk-A4EAKE3M.mjs +0 -49
  29. package/dist/chunks/chunk-DHH2XXGJ.mjs +0 -203
  30. package/dist/chunks/chunk-HRFLFP6O.cjs +0 -1
  31. package/dist/chunks/chunk-KU6UZET2.cjs +0 -49
  32. package/dist/chunks/chunk-QQXDOGRV.mjs +0 -1
  33. package/dist/chunks/chunk-YY3Z7NGV.cjs +0 -203
  34. package/dist/chunks/cli-handler-7XFZK7GK.cjs +0 -1
  35. package/dist/chunks/cli-handler-H6VHMEHB.mjs +0 -1
  36. package/dist/chunks/code-base-E5TX7O7M.cjs +0 -1
  37. package/dist/chunks/database-manager-WTV3TBJS.cjs +0 -1
  38. package/dist/chunks/database-manager-YGQQHLYR.mjs +0 -1
  39. package/dist/chunks/file-watcher-HVST5PAC.cjs +0 -1
  40. package/dist/chunks/file-watcher-LCQ55MPE.mjs +0 -1
  41. package/dist/chunks/stdio-server-2QHQ7ESX.cjs +0 -47
  42. package/dist/chunks/stdio-server-5YSJE5E5.mjs +0 -47
@@ -1,4 +1,4 @@
1
- import {a}from'./chunk-2YMB6W5S.mjs';import {Log,Filesystem}from'@easbot/utils';import {createSyncSqliteConnection}from'@easbot/database';var F=class o extends Error{constructor(t,s,r){super(t);a(this,"name","ParserError");a(this,"filePath");a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `ParserError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},p=class o extends Error{constructor(t,s,r){super(t);a(this,"name","DatabaseError");a(this,"operation");a(this,"cause");this.operation=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `DatabaseError: ${this.message} during ${this.operation}${t}`}toJSON(){return {name:this.name,message:this.message,operation:this.operation,cause:this.cause?.message}}},M=class o extends Error{constructor(t,s,r){super(t);a(this,"name","FileSystemError");a(this,"filePath");a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `FileSystemError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},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 (
1
+ import {a}from'./chunk-2YMB6W5S.mjs';import {Log,Filesystem}from'@easbot/utils';import {createSyncSqliteConnection}from'@easbot/database';var F=class o extends Error{constructor(t,s,r){super(t);a(this,"name","ParserError");a(this,"filePath");a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `ParserError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},p=class o extends Error{constructor(t,s,r){super(t);a(this,"name","DatabaseError");a(this,"operation");a(this,"cause");this.operation=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `DatabaseError: ${this.message} during ${this.operation}${t}`}toJSON(){return {name:this.name,message:this.message,operation:this.operation,cause:this.cause?.message}}},M=class o extends Error{constructor(t,s,r){super(t);a(this,"name","FileSystemError");a(this,"filePath");a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `FileSystemError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},_=class o extends Error{constructor(t,s){super(t);a(this,"name","SchemaError");a(this,"missing");this.missing=s,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.missing?` (missing: ${this.missing.join(", ")})`:"";return `SchemaError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,missing:this.missing}}},A=class o extends Error{constructor(t,s){super(t);a(this,"name","ConfigError");a(this,"field");this.field=s,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.field?` (field: ${this.field})`:"";return `ConfigError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,field:this.field}}},v=class o extends Error{constructor(t,s,r){super(t);a(this,"name","IndexError");a(this,"filePath");a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=[this.message];return this.filePath&&t.push(`at ${this.filePath}`),this.cause&&t.push(`(caused by: ${this.cause.message})`),`IndexError: ${t.join(" ")}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},x=class o extends Error{constructor(t,s,r){super(t);a(this,"name","QueryError");a(this,"params");a(this,"cause");this.params=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.params?` (params: ${JSON.stringify(this.params)})`:"",s=this.cause?` (caused by: ${this.cause.message})`:"";return `QueryError: ${this.message}${t}${s}`}toJSON(){return {name:this.name,message:this.message,params:this.params,cause:this.cause?.message}}},w=class o extends Error{constructor(t,s){super(`Unsupported language: ${t}`);a(this,"name","UnsupportedLanguageError");a(this,"extension");a(this,"filePath");this.extension=t,this.filePath=s,Object.setPrototypeOf(this,o.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var D=Log.create({service:"codebase-schema-migrations"}),S=1,V=[{id:1,description:"v1 baseline: nodes / edges / file_hashes / nodes_fts / meta / embedding_cache / node_embeddings + unresolved_refs / name_segment_vocab / project_metadata / parse_errors + \u6027\u80FD index (nodes.file_path / edges.source/target)",up:[`CREATE TABLE IF NOT EXISTS nodes (
2
2
  id TEXT PRIMARY KEY,
3
3
  name TEXT NOT NULL,
4
4
  ast_type TEXT NOT NULL,
@@ -67,19 +67,19 @@ import {a}from'./chunk-2YMB6W5S.mjs';import {Log,Filesystem}from'@easbot/utils';
67
67
  )`,"CREATE INDEX IF NOT EXISTS idx_parse_errors_file_path ON parse_errors(file_path)","CREATE INDEX IF NOT EXISTS idx_nodes_file_path ON nodes(file_path)","CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)"]}];function H(o,e=S,t={}){o.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
68
68
  id INTEGER PRIMARY KEY,
69
69
  applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
70
- )`);let s=o.prepare("SELECT id FROM schema_migrations").all(),r=new Set(s.map(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=3,$=class{constructor(e){a(this,"db");a(this,"dbPath");a(this,"closed",false);a(this,"ftsAvailable",false);this.dbPath=e===":memory:"?e:Filesystem.normalize(e),this.db=createSyncSqliteConnection({path:this.dbPath,backend:"better-sqlite3",walMode:true,foreignKeys:true,busyTimeoutMs: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(`
70
+ )`);let s=o.prepare("SELECT id FROM schema_migrations").all(),r=new Set(s.map(i=>i.id)),n={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(i=>i.id)),targetVersion:e};for(let i of V){if(i.id>e)break;if(r.has(i.id)){n.pending.push(i.id);continue}if(t.dryRun){n.applied.push(i.id);continue}try{o.execBatch([...i.up]),o.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(i.id),r.add(i.id),n.applied.push(i.id),D.info("migration applied",{id:i.id,description:i.description});}catch(a){let c=a instanceof Error?a.message:String(a),u=i.up[0]??"";n.errors.push({migrationId:i.id,sql:u,error:c}),D.warn("migration step failed (may be idempotent)",{id:i.id,error:c,sqlCount:i.up.length});}}return n}function X(o){try{let e=o.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(t=>t.id))}catch{return 0}}var l=Filesystem.toUnixPath,E=Log.create({service:"codebase-database"}),b=3,$=class{constructor(e){a(this,"db");a(this,"dbPath");a(this,"closed",false);a(this,"ftsAvailable",false);this.dbPath=e===":memory:"?e:Filesystem.normalize(e),this.db=createSyncSqliteConnection({path:this.dbPath,backend:"better-sqlite3",walMode:true,foreignKeys:true,busyTimeoutMs:3e4}),this.db.initialize();try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("foreign_keys = ON");}catch(t){E.warn("Failed to apply codebase PRAGMAs (synchronous / cache_size / foreign_keys)",{error:String(t)});}try{this.ensureSchema();let t=X(this.db);t>0&&this.setMeta("schema_version",String(t)),this.ftsAvailable=this.checkFtsAvailability(),this.detectAndMarkStaleOnInit();}catch(t){try{this.db.close();}catch{}throw this.closed=true,t}}ensureSchema(){try{H(this.db,S);let e=[["version","1.0.0"],["createdAt",new Date().toISOString()],["index_state","uninitialized"],["indexed_with_version","unknown"]],t=this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[s,r]of e)t.run(s,r);}catch(e){E.error("ensureSchema failed",{message:e instanceof Error?e.message:String(e),cause:e instanceof Error?e.cause:void 0,stack:e instanceof Error?e.stack:void 0});let t=e instanceof Error?e.message:String(e),s=e instanceof Error?e.cause:void 0,r=s!==void 0?String(s):"",n=r&&r!==t?` (cause: ${r})`:"";throw new _(`Failed to create database schema: ${t}${n}`,e instanceof Error?[t,r].filter(Boolean):[t])}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:l(e.file_path)};this.db.prepare(`
71
71
  INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
72
72
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
73
- `).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(i=>({...i,file_path:c(i.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(n=>({...n,file_path:l(n.file_path)})),s=this.db.prepare(`
74
74
  INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
75
75
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
76
- `);this.db.transaction(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(`
76
+ `);this.db.transaction(n=>{for(let i of n)s.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.start_line,i.start_col,i.end_line,i.end_col,i.text,i.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(n);})(t);}updateFtsNodesInternal(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),r=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");for(let n of e)try{let i=s.get(n.id);i&&t.run(i.rowid),r.run(n.id,n.name,n.ast_type,n.language,n.file_path,n.text);}catch(i){E.warn("FTS update failed for node",{nodeId:n.id,error:String(i)});}}updateFtsNode(e){try{let t=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?").get(e.id);t&&this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(t.rowid),this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.ast_type,e.language,e.file_path,e.text);}catch(t){E.warn("FTS update failed for node",{nodeId:e.id,error:String(t)});}}updateFtsNodes(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),r=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");this.db.transaction(i=>{for(let a of i)try{let c=s.get(a.id);c&&t.run(c.rowid),r.run(a.id,a.name,a.ast_type,a.language,a.file_path,a.text);}catch(c){E.warn("FTS update failed for node",{nodeId:a.id,error:String(c)});}})(e);}insertEdge(e){this.db.prepare(`
77
77
  INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
78
78
  VALUES (?, ?, ?, ?, ?)
79
79
  `).run(e.id,e.source,e.target,e.relation,e.created_at);}insertEdges(e){if(e.length===0)return;let t=this.db.prepare(`
80
80
  INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
81
81
  VALUES (?, ?, ?, ?, ?)
82
- `);this.db.transaction(r=>{for(let 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(`
82
+ `);this.db.transaction(r=>{for(let n of r)t.run(n.id,n.source,n.target,n.relation,n.created_at);})(e);}queryNodes(e){let t=[],s=[];e.filePath&&(t.push("file_path LIKE ?"),s.push(`%${l(e.filePath)}%`)),e.astType&&(t.push("ast_type = ?"),s.push(e.astType)),e.name&&(t.push("name = ?"),s.push(e.name)),e.language&&(t.push("language = ?"),s.push(e.language));let r="SELECT * FROM nodes";t.length>0&&(r+=` WHERE ${t.join(" AND ")}`),r+=" ORDER BY file_path, start_line",e.limit&&(r+=" LIMIT ?",s.push(e.limit)),e.offset&&(r+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(r).all(...s)}catch(n){throw new p("Failed to query nodes","queryNodes",n instanceof Error?n:new Error(String(n)))}}findNodesByName(e){if(!e.name)return [];let t=e.limit??50,s=e.kind?`%${e.kind.toLowerCase()}%`:null,r=new Set,n=[],i=(c,u)=>{r.has(c.id)||(r.add(c.id),n.push({node:c,matchKind:u}));},a=(c,u)=>{e.file&&(e.file.includes("/")?(c.push("file_path = ?"),u.push(e.file)):(c.push("file_path LIKE '%/' || ?"),u.push(e.file))),s&&(c.push("LOWER(ast_type) LIKE ?"),u.push(s));};try{let c=["name = ?"],u=[e.name];a(c,u),u.push(t);let m=this.db.prepare(`SELECT * FROM nodes WHERE ${c.join(" AND ")} LIMIT ?`).all(...u);for(let g of m)i(g,"exact");if(m.length>0&&e.file)return n.slice(0,t);if(n.length<t){let g=this.db.prepare("SELECT * FROM nodes WHERE name LIKE ? LIMIT ?").all(`%${e.name}%`,t);for(let h of g)i(h,"qualified");}if(n.length>0&&e.file)return n.slice(0,t);if(n.length===0&&e.name){let g=["name LIKE ?"],h=[`%${e.name}%`];e.file&&(e.file.includes("/")?(g.push("file_path = ?"),h.push(e.file)):(g.push("file_path LIKE '%/' || ?"),h.push(e.file))),s&&(g.push("LOWER(ast_type) LIKE ?"),h.push(s)),g.push("?"),h.push(t);let T=this.db.prepare(`SELECT * FROM nodes WHERE ${g.join(" AND ")}`).all(...h);for(let f of T)i(f,"substring");}return n.slice(0,t)}catch(c){throw new p("Failed to find nodes by name","findNodesByName",c instanceof Error?c:new Error(String(c)))}}queryEdges(e){let t=[],s=[];if(e.sourceOrTarget&&e.sourceOrTarget.length>0){let n=e.sourceOrTarget.map(()=>"?").join(",");t.push(`(source IN (${n}) OR target IN (${n}))`),s.push(...e.sourceOrTarget,...e.sourceOrTarget);}else e.source&&(t.push("source = ?"),s.push(e.source)),e.target&&(t.push("target = ?"),s.push(e.target));e.relation&&(t.push("relation = ?"),s.push(e.relation));let r="SELECT * FROM edges";t.length>0&&(r+=` WHERE ${t.join(" AND ")}`),r+=" ORDER BY created_at DESC",e.limit&&(r+=" LIMIT ?",s.push(e.limit)),e.offset&&(r+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(r).all(...s)}catch(n){throw new p("Failed to query edges","queryEdges",n instanceof Error?n:new Error(String(n)))}}queryAll(e,t){try{let s=this.db.prepare(e);return t?s.all(...t):s.all()}catch(s){throw new p("Failed to execute query","queryAll",s instanceof Error?s:new Error(String(s)))}}searchNodesFts(e,t=20){if(E.debug("searchNodesFts start",{query:e,limit:t,ftsAvailable:this.ftsAvailable}),!this.ftsAvailable)return E.debug("searchNodesFts skip - FTS not available"),[];try{let s=e.split(/\s+/).map(a=>`${a}*`).join(" ");E.debug("searchNodesFts query",{ftsQuery:s});let i=this.db.prepare(`
83
83
  SELECT
84
84
  nodes_fts.id,
85
85
  nodes_fts.name,
@@ -97,58 +97,58 @@ import {a}from'./chunk-2YMB6W5S.mjs';import {Log,Filesystem}from'@easbot/utils';
97
97
  WHERE nodes_fts.text MATCH ?
98
98
  ORDER BY score DESC
99
99
  LIMIT ?
100
- `).all(s,t);return 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(`
100
+ `).all(s,t);return E.debug("searchNodesFts done",{resultCount:i.length}),i}catch(s){return E.warn("searchNodesFts failed",{error:String(s)}),[]}}deleteNodesByFile(e){let t=l(e);if(this.ftsAvailable)try{let r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let n of r)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(n.rowid);}catch(r){E.warn("FTS delete failed for file",{filePath:t,error:String(r)});}return this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t).changes}deleteEdgesByFile(e){let t=l(e);return this.db.prepare(`
101
101
  DELETE FROM edges
102
102
  WHERE source IN (SELECT id FROM nodes WHERE file_path = ?)
103
103
  OR target IN (SELECT id FROM nodes WHERE file_path = ?)
104
- `).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(c(e))?.content_hash??null}setFileHash(e,t){this.db.prepare(`
104
+ `).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(l(e))?.content_hash??null}setFileHash(e,t){this.db.prepare(`
105
105
  INSERT OR REPLACE INTO file_hashes (file_path, content_hash, last_modified)
106
106
  VALUES (?, ?, ?)
107
- `).run(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(`
107
+ `).run(l(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(l(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}checkIntegrity(){let e=R=>this.db.prepare(R).get().c,t=R=>e(R),s={nodes:t("SELECT COUNT(*) as c FROM nodes"),edges:t("SELECT COUNT(*) as c FROM edges"),file_hashes:t("SELECT COUNT(*) as c FROM file_hashes"),fts:t("SELECT COUNT(*) as c FROM nodes_fts"),node_embeddings:t("SELECT COUNT(*) as c FROM node_embeddings"),embedding_cache:t("SELECT COUNT(*) as c FROM embedding_cache"),parse_errors:t("SELECT COUNT(*) as c FROM parse_errors"),unresolved_refs:t("SELECT COUNT(*) as c FROM unresolved_refs"),name_segment_vocab:t("SELECT COUNT(*) as c FROM name_segment_vocab"),project_metadata:t("SELECT COUNT(*) as c FROM project_metadata"),schema_migrations:t("SELECT COUNT(*) as c FROM schema_migrations"),meta:t("SELECT COUNT(*) as c FROM meta")},r=[],n=t(`
108
108
  SELECT COUNT(*) as c FROM node_embeddings e
109
109
  LEFT JOIN nodes n ON n.id = e.node_id WHERE n.id IS NULL
110
- `);i>0&&r.push({severity:"error",message:`orphan node_embeddings: ${i}`});let n=t(`
110
+ `);n>0&&r.push({severity:"error",message:`orphan node_embeddings: ${n}`});let i=t(`
111
111
  SELECT COUNT(*) as c FROM edges e WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.source)
112
- `);n>0&&r.push({severity:"error",message:`orphan edges (source): ${n}`});let a=t(`
112
+ `);i>0&&r.push({severity:"error",message:`orphan edges (source): ${i}`});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
- `);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(`
114
+ `);a>0&&r.push({severity:"error",message:`orphan edges (target): ${a}`});let c=t("SELECT COUNT(*) as c FROM edges WHERE source = target");c>0&&r.push({severity:"error",message:`self-loop edges: ${c} \u2014 re-run \`easbot codebase sync\` to filter (fixed in Wave 4 R3-2)`});t("SELECT COUNT(DISTINCT file_path) as c FROM nodes");let m=t(`
115
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
- `);g>0&&r.push({severity:"warn",message:`orphan file_hashes (no nodes): ${g} \u2014 run \`easbot codebase sync\` to cleanup`});let T=t(`
117
+ `);m>0&&r.push({severity:"warn",message:`orphan file_hashes (no nodes): ${m} \u2014 run \`easbot codebase sync\` to cleanup`});let g=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
- `);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(`
120
+ `);g>0&&r.push({severity:"warn",message:`node files without hash: ${g}`});let h=t("SELECT COUNT(*) as c FROM nodes WHERE name IS NULL OR name = ''");h>0&&r.push({severity:"error",message:`nodes with null/empty name: ${h}`});let T=t("SELECT COUNT(*) as c FROM nodes WHERE ast_type IS NULL OR ast_type = ''");T>0&&r.push({severity:"error",message:`nodes with null/empty ast_type: ${T}`});let f=t("SELECT COUNT(*) as c FROM nodes WHERE language IS NULL OR language = ''");f>0&&r.push({severity:"error",message:`nodes with null/empty language: ${f}`});let N=t("SELECT COUNT(*) as c FROM nodes WHERE file_path IS NULL OR file_path = ''");N>0&&r.push({severity:"error",message:`nodes with null/empty file_path: ${N}`});let O=this.db.prepare("SELECT id, COUNT(*) as c FROM nodes GROUP BY id HAVING c > 1").all().length;O>0&&r.push({severity:"error",message:`duplicate node ids: ${O}`});let I=t("SELECT COUNT(*) as c FROM nodes WHERE file_path LIKE '%\\\\%'");I>0&&r.push({severity:"warn",message:`nodes with backslash in file_path: ${I}`});let L=t(`
121
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(),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(`
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 i of r)n[i.key]=i.value;return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:s?.c??0,dbPath:this.dbPath,meta:n,indexState:this.getIndexState(),extractionVersion:parseInt(this.getMeta("indexed_with_extraction_version")??"0",10),isStale:this.isIndexStale()}}setLastSync(){this.db.prepare(`
124
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(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(`
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(b)),this.setMeta("index_state","complete"),this.setMeta("last_index_state_change",new Date().toISOString());}isIndexStale(){let e=this.getMeta("indexed_with_extraction_version");if(!e)return false;let t=parseInt(e,10);return Number.isNaN(t)||t<b}detectAndMarkStaleOnInit(){if(this.isIndexStale()){let e=this.getMeta("indexed_with_extraction_version");E.warn("codebase db is stale",{recorded:e??"(none)",current:String(b),hint:"run `easbot codebase recreate` or `easbot codebase index --force` to rebuild"});let t=this.getIndexState();(t==="complete"||t==="partial")&&this.setIndexState("stale");}}getNodeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM nodes").get()?.c??0}getEdgeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM edges").get()?.c??0}getFileCount(){return this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get()?.c??0}getNodeById(e){return this.db.prepare("SELECT * FROM nodes WHERE id = ?").get(e)??null}getEdgeById(e){return this.db.prepare("SELECT * FROM edges WHERE id = ?").get(e)??null}clearAll(e={}){this.db.exec("DELETE FROM nodes"),this.db.exec("DELETE FROM edges"),this.db.exec("DELETE FROM file_hashes"),this.db.exec("DELETE FROM meta"),e.keepEmbeddings||(this.db.exec("DELETE FROM node_embeddings"),this.db.exec("DELETE FROM embedding_cache")),this.ftsAvailable&&this.db.exec("DELETE FROM nodes_fts");try{this.db.exec("DELETE FROM sqlite_sequence WHERE name IN ('nodes', 'edges', 'file_hashes', 'meta')");}catch{}}getCachedEmbedding(e){let s=this.db.prepare(`
127
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)
130
130
  VALUES (?, ?)
131
- `).run(e,t);}deleteEmbeddingsByFile(e){let t=c(e);return this.db.prepare(`
131
+ `).run(e,t);}deleteEmbeddingsByFile(e){let t=l(e);return this.db.prepare(`
132
132
  DELETE FROM node_embeddings WHERE node_id IN (SELECT id FROM nodes WHERE file_path = ?)
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 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(`
136
+ `);this.db.transaction(r=>{for(let n of r)try{t.run(n.nodeId,n.embeddingText,n.embedding);}catch(i){E.warn("Failed to store embedding for node",{nodeId:n.nodeId,error:String(i)});}})(e);}insertParseError(e){return this.db.prepare(`
137
137
  INSERT INTO parse_errors (file_path, language, stage, message, line)
138
138
  VALUES (?, ?, ?, ?, ?)
139
- `).run(c(e.filePath),e.language,e.stage,e.message,e.line??null).changes}insertUnresolvedRef(e){return this.db.prepare(`
139
+ `).run(l(e.filePath),e.language,e.stage,e.message,e.line??null).changes}insertUnresolvedRef(e){return this.db.prepare(`
140
140
  INSERT INTO unresolved_refs
141
141
  (from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
142
142
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
143
- `).run(e.fromNodeId??null,e.referenceName,e.referenceKind,e.line??null,e.col??null,c(e.filePath),e.language,e.candidates?JSON.stringify(e.candidates):null).changes}insertUnresolvedRefsBatch(e){if(e.length===0)return 0;let s=`
143
+ `).run(e.fromNodeId??null,e.referenceName,e.referenceKind,e.line??null,e.col??null,l(e.filePath),e.language,e.candidates?JSON.stringify(e.candidates):null).changes}insertUnresolvedRefsBatch(e){if(e.length===0)return 0;let s=`
144
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 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(`
147
+ `,r=[];for(let a of e)r.push(a.fromNodeId??null,a.referenceName,a.referenceKind,a.line??null,a.col??null,l(a.filePath),a.language,a.candidates?JSON.stringify(a.candidates):null);return this.db.prepare(s).run(...r).changes}insertNameSegment(e,t){return this.db.prepare(`
148
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 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(`
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"?l(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(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};
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(i=>{for(let a of i)r.run(a);})(s),s.length}initialize(){if(this.closed)throw new p("Cannot initialize closed database","initialize")}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){E.warn("Database close error",{error:String(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}countSqliteObjects(){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT COUNT(*) as n FROM sqlite_master WHERE type IN ('table', 'index', 'trigger', 'view')").get()?.n??0}deleteMeta(e){if(!this.db)throw new Error("Database not initialized");this.db.prepare("DELETE FROM meta WHERE key = ?").run(e);}};function se(o){return o.isClosed()}function re(o){return o.getDbPath()}function ne(o,e){return o.transaction(e)}export{F as a,p as b,M as c,_ as d,A as e,v as f,x as g,w as h,S as i,V as j,H as k,X as l,b as m,$ as n,se as o,re as p,ne as q};