@easbot/codebase 0.3.29 → 0.3.32

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 (73) hide show
  1. package/README.en.md +55 -1
  2. package/README.md +55 -1
  3. package/dist/chunks/cache-D7NVUXB2.mjs +1 -0
  4. package/dist/chunks/cache-LSQZJEDR.cjs +1 -0
  5. package/dist/chunks/{chunk-4XKCGYFF.mjs → chunk-33DIOGLJ.mjs} +22 -22
  6. package/dist/chunks/chunk-37KKG3UK.mjs +48 -0
  7. package/dist/chunks/chunk-43WAI4Z7.mjs +1 -0
  8. package/dist/chunks/chunk-CLUGDJA5.cjs +62 -0
  9. package/dist/chunks/chunk-EH2QTB6S.cjs +37 -0
  10. package/dist/chunks/chunk-ESA2CL57.mjs +37 -0
  11. package/dist/chunks/chunk-ETCTXAXR.mjs +1 -0
  12. package/dist/chunks/chunk-H4VZF3ZQ.mjs +1 -0
  13. package/dist/chunks/chunk-J7Z3MIR7.cjs +1 -0
  14. package/dist/chunks/chunk-JEHVBEBS.cjs +1 -0
  15. package/dist/chunks/chunk-KFESJR3T.cjs +1 -0
  16. package/dist/chunks/chunk-KR6BQNY6.mjs +203 -0
  17. package/dist/chunks/chunk-KTSR5VPT.mjs +1 -0
  18. package/dist/chunks/chunk-OJK5EFPD.cjs +48 -0
  19. package/dist/chunks/{chunk-YJK7F6NJ.cjs → chunk-OZYQQS63.cjs} +22 -22
  20. package/dist/chunks/chunk-PRPBK7D6.mjs +62 -0
  21. package/dist/chunks/chunk-T6KJWYTV.mjs +1 -0
  22. package/dist/chunks/chunk-TBDAGLC4.cjs +203 -0
  23. package/dist/chunks/chunk-TMQVJU4I.mjs +1 -0
  24. package/dist/chunks/chunk-VZCOLSBF.cjs +1 -0
  25. package/dist/chunks/chunk-W5SMGCKO.cjs +1 -0
  26. package/dist/chunks/chunk-Y7JDLK56.cjs +1 -0
  27. package/dist/chunks/cli-handler-IQ6ZNLEJ.mjs +1 -0
  28. package/dist/chunks/cli-handler-WTEPKO4E.cjs +1 -0
  29. package/dist/chunks/code-base-5BXR4FUU.cjs +1 -0
  30. package/dist/chunks/code-base-M4EMTQTG.mjs +1 -0
  31. package/dist/chunks/database-manager-KM7BOISA.mjs +1 -0
  32. package/dist/chunks/database-manager-LTHK7MM6.cjs +1 -0
  33. package/dist/chunks/file-watcher-2MUX5MO5.cjs +1 -0
  34. package/dist/chunks/file-watcher-ABFT22GS.mjs +1 -0
  35. package/dist/chunks/{interfaces-S7TJGWWS.mjs → interfaces-43SSCG3E.mjs} +1 -1
  36. package/dist/chunks/interfaces-LUHDPZOT.cjs +1 -0
  37. package/dist/chunks/llm-S6D5ICOO.cjs +1 -0
  38. package/dist/chunks/llm-WS3XKT46.mjs +1 -0
  39. package/dist/chunks/{stdio-server-DFKFFRSM.cjs → stdio-server-KA3JQB7C.cjs} +2 -2
  40. package/dist/chunks/stdio-server-QP63TXGI.mjs +30 -0
  41. package/dist/cli.cjs +1 -1
  42. package/dist/cli.mjs +1 -1
  43. package/dist/index.cjs +1 -1
  44. package/dist/index.d.cts +149 -41
  45. package/dist/index.d.ts +149 -41
  46. package/dist/index.mjs +1 -1
  47. package/package.json +8 -9
  48. package/dist/chunks/chunk-23YR2LAM.cjs +0 -1
  49. package/dist/chunks/chunk-2YMB6W5S.mjs +0 -1
  50. package/dist/chunks/chunk-3RVRPGJC.mjs +0 -1
  51. package/dist/chunks/chunk-3UGOMK4F.cjs +0 -62
  52. package/dist/chunks/chunk-5M2N7JFP.cjs +0 -1
  53. package/dist/chunks/chunk-A4YJ5ZVE.cjs +0 -203
  54. package/dist/chunks/chunk-J7AIRI5N.mjs +0 -203
  55. package/dist/chunks/chunk-LLO6DDXU.mjs +0 -48
  56. package/dist/chunks/chunk-LQVKXVBS.mjs +0 -51
  57. package/dist/chunks/chunk-LZLPJAB6.mjs +0 -62
  58. package/dist/chunks/chunk-M2YU5LAI.cjs +0 -1
  59. package/dist/chunks/chunk-MZHDSOD7.mjs +0 -1
  60. package/dist/chunks/chunk-OGTQ7MWV.cjs +0 -51
  61. package/dist/chunks/chunk-V6PHJ4DG.cjs +0 -48
  62. package/dist/chunks/cli-handler-B7WPIZRE.cjs +0 -1
  63. package/dist/chunks/cli-handler-EJX27R4Q.mjs +0 -1
  64. package/dist/chunks/code-base-FSOSU46G.mjs +0 -1
  65. package/dist/chunks/code-base-OWYMNEQG.cjs +0 -1
  66. package/dist/chunks/database-manager-7D7NDXJK.mjs +0 -1
  67. package/dist/chunks/database-manager-X4DMAUWC.cjs +0 -1
  68. package/dist/chunks/file-watcher-E2JROVI7.cjs +0 -1
  69. package/dist/chunks/file-watcher-KSLBUUPP.mjs +0 -1
  70. package/dist/chunks/interfaces-URUTHSR2.cjs +0 -1
  71. package/dist/chunks/llm-R2ZLKZDO.cjs +0 -1
  72. package/dist/chunks/llm-U57HNTZO.mjs +0 -1
  73. package/dist/chunks/stdio-server-NV5YAXJD.mjs +0 -30
@@ -1,4 +1,4 @@
1
- 'use strict';var chunkM2YU5LAI_cjs=require('./chunk-M2YU5LAI.cjs'),i=require('zod'),utils=require('@easbot/utils'),database=require('@easbot/database');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var i__default=/*#__PURE__*/_interopDefault(i);exports.b=void 0;(E=>(E.ParserError=utils.NamedError.create("CodebaseParserError",i__default.default.object({message:i__default.default.string(),filePath:i__default.default.string()})),E.DatabaseError=utils.NamedError.create("CodebaseDatabaseError",i__default.default.object({message:i__default.default.string(),operation:i__default.default.string()})),E.SchemaError=utils.NamedError.create("CodebaseSchemaError",i__default.default.object({message:i__default.default.string(),missing:i__default.default.array(i__default.default.string()).optional()})),E.FileSystemError=utils.NamedError.create("CodebaseFileSystemError",i__default.default.object({message:i__default.default.string(),filePath:i__default.default.string()})),E.IndexError=utils.NamedError.create("CodebaseIndexError",i__default.default.object({message:i__default.default.string(),filePath:i__default.default.string().optional()})),E.ConfigError=utils.NamedError.create("CodebaseConfigError",i__default.default.object({message:i__default.default.string(),field:i__default.default.string().optional()})),E.QueryError=utils.NamedError.create("CodebaseQueryError",i__default.default.object({message:i__default.default.string(),params:i__default.default.record(i__default.default.string(),i__default.default.unknown()).optional()})),E.UnsupportedLanguageError=utils.NamedError.create("CodebaseUnsupportedLanguageError",i__default.default.object({extension:i__default.default.string(),filePath:i__default.default.string()})),E.NotFoundError=utils.NamedError.create("CodebaseNotFoundError",i__default.default.object({message:i__default.default.string(),name:i__default.default.string(),candidates:i__default.default.array(i__default.default.object({node:i__default.default.unknown(),score:i__default.default.number()})).optional()})),E.AmbiguousError=utils.NamedError.create("CodebaseAmbiguousError",i__default.default.object({message:i__default.default.string(),name:i__default.default.string(),candidates:i__default.default.array(i__default.default.object({node:i__default.default.unknown(),score:i__default.default.number()}))}))))(exports.b||(exports.b={}));var W=new Set(["NOT_FOUND","AMBIGUOUS","INTERNAL","NOT_INDEXED"]),k={NOT_FOUND:"codebase node not found; run codebase_query first to discover the symbol (by name / kind / file)",AMBIGUOUS:"multiple nodes match the name; pass either nodeId OR name+file to disambiguate (file is the strongest disambiguation signal)",NOT_INDEXED:"codebase index not ready; run `easbot codebase sync` first, then retry"};async function z(){await utils.ServiceErrorBus.register("codebase",W,k);}var U=utils.Log.create({service:"codebase-schema-migrations"}),O=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
+ 'use strict';var chunkW5SMGCKO_cjs=require('./chunk-W5SMGCKO.cjs'),chunkKFESJR3T_cjs=require('./chunk-KFESJR3T.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database');var A=utils.Log.create({service:"codebase.database.migrations"}),N=1,X=[{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 w(c,e=O,t={}){c.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 v(E,e=N,t={}){E.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=c.prepare("SELECT id FROM schema_migrations").all(),n=new Set(s.map(a=>a.id)),r={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(a=>a.id)),targetVersion:e};for(let a of V){if(a.id>e)break;if(n.has(a.id)){r.pending.push(a.id);continue}if(t.dryRun){r.applied.push(a.id);continue}try{c.execBatch([...a.up]),c.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(a.id),n.add(a.id),r.applied.push(a.id),U.debug("migration applied",{id:a.id,description:a.description});}catch(o){let d=utils.errorMeta(o).message,u=a.up[0]??"";r.errors.push({migrationId:a.id,sql:u,error:d}),U.warn("migration step failed (may be idempotent)",{id:a.id,error:utils.errorMeta(o),sqlCount:a.up.length});}}return r}function D(c){try{let e=c.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(t=>t.id))}catch{return 0}}var g=utils.Filesystem.toUnixPath,l=utils.Log.create({service:"codebase-database"}),I=3,P=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:3e4}),this.db.initialize();try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("foreign_keys = ON");}catch(t){l.warn("Failed to apply codebase PRAGMAs (synchronous / cache_size / foreign_keys)",{error:utils.errorMeta(t)});}try{this.ensureSchema();let t=D(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{w(this.db,O);let e=[["version","1.0.0"],["createdAt",new Date().toISOString()],["index_state","uninitialized"],["indexed_with_version","unknown"]],t=this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[s,n]of e)t.run(s,n);}catch(e){l.error("ensureSchema failed",{error:utils.errorMeta(e)});let t=utils.errorMeta(e).message,s=e instanceof Error?e.cause:void 0,n=s!==void 0?String(s):"",r=n&&n!==t?` (cause: ${n})`:"";throw new exports.b.SchemaError({message:`Failed to create database schema: ${t}${r}`,missing:e instanceof Error?[t,n].filter(Boolean):[t]},{cause:e})}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:g(e.file_path)};this.db.prepare(`
70
+ )`);let s=E.prepare("SELECT id FROM schema_migrations").all(),n=new Set(s.map(a=>a.id)),r={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(a=>a.id)),targetVersion:e};for(let a of X){if(a.id>e)break;if(n.has(a.id)){r.pending.push(a.id);continue}if(t.dryRun){r.applied.push(a.id);continue}try{E.execBatch([...a.up]),E.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(a.id),n.add(a.id),r.applied.push(a.id),A.debug("migration applied",{id:a.id,description:a.description});}catch(i){let o=utils.errorMeta(i).message,c=a.up[0]??"";r.errors.push({migrationId:a.id,sql:c,error:o}),A.warn("migration step failed (may be idempotent)",{id:a.id,error:utils.errorMeta(i),sqlCount:a.up.length});}}return r}function w(E){try{let e=E.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(t=>t.id))}catch{return 0}}var l=utils.Filesystem.toUnixPath,d=utils.Log.create({service:"codebase.database"}),S=3,U=class{constructor(e){chunkKFESJR3T_cjs.a(this,"db");chunkKFESJR3T_cjs.a(this,"dbPath");chunkKFESJR3T_cjs.a(this,"closed",false);chunkKFESJR3T_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:3e4}),this.db.initialize();try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("foreign_keys = ON");}catch(t){d.warn("Failed to apply codebase PRAGMAs (synchronous / cache_size / foreign_keys)",{error:utils.errorMeta(t)});}try{this.ensureSchema();let t=w(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{v(this.db,N);let e=[["version","1.0.0"],["createdAt",new Date().toISOString()],["index_state","uninitialized"],["indexed_with_version","unknown"]],t=this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[s,n]of e)t.run(s,n);}catch(e){d.error("ensureSchema failed",{error:utils.errorMeta(e)});let t=utils.errorMeta(e).message,s=e instanceof Error?e.cause:void 0,n=s!==void 0?String(s):"",r=n&&n!==t?` (cause: ${n})`:"";throw new chunkW5SMGCKO_cjs.b.SchemaError({message:`Failed to create database schema: ${t}${r}`,missing:e instanceof Error?[t,n].filter(Boolean):[t]},{cause:e})}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path: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(r=>({...r,file_path:g(r.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(r=>({...r,file_path:l(r.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(r=>{for(let a of r)s.run(a.id,a.name,a.ast_type,a.language,a.file_path,a.start_line,a.start_col,a.end_line,a.end_col,a.text,a.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(r);})(t);}updateFtsNodesInternal(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),n=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");for(let r of e)try{let a=s.get(r.id);a&&t.run(a.rowid),n.run(r.id,r.name,r.ast_type,r.language,r.file_path,r.text);}catch(a){l.warn("FTS update failed for node",{nodeId:r.id,error:utils.errorMeta(a)});}}updateFtsNode(e){try{let t=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?").get(e.id);t&&this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(t.rowid),this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.ast_type,e.language,e.file_path,e.text);}catch(t){l.warn("FTS update failed for node",{nodeId:e.id,error:utils.errorMeta(t)});}}updateFtsNodes(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),n=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");this.db.transaction(a=>{for(let o of a)try{let d=s.get(o.id);d&&t.run(d.rowid),n.run(o.id,o.name,o.ast_type,o.language,o.file_path,o.text);}catch(d){l.warn("FTS update failed for node",{nodeId:o.id,error:utils.errorMeta(d)});}})(e);}insertEdge(e){this.db.prepare(`
76
+ `);this.db.transaction(r=>{for(let a of r)s.run(a.id,a.name,a.ast_type,a.language,a.file_path,a.start_line,a.start_col,a.end_line,a.end_col,a.text,a.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(r);})(t);}updateFtsNodesInternal(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),n=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");for(let r of e)try{let a=s.get(r.id);a&&t.run(a.rowid),n.run(r.id,r.name,r.ast_type,r.language,r.file_path,r.text);}catch(a){d.warn("FTS update failed for node",{nodeId:r.id,error:utils.errorMeta(a)});}}updateFtsNode(e){try{let t=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?").get(e.id);t&&this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(t.rowid),this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.ast_type,e.language,e.file_path,e.text);}catch(t){d.warn("FTS update failed for node",{nodeId:e.id,error:utils.errorMeta(t)});}}updateFtsNodes(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),n=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");this.db.transaction(a=>{for(let i of a)try{let o=s.get(i.id);o&&t.run(o.rowid),n.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.text);}catch(o){d.warn("FTS update failed for node",{nodeId:i.id,error:utils.errorMeta(o)});}})(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(n=>{for(let r of n)t.run(r.id,r.source,r.target,r.relation,r.created_at);})(e);}queryNodes(e){let t=[],s=[];e.filePath&&(t.push("file_path LIKE ?"),s.push(`%${g(e.filePath)}%`)),e.astType&&(t.push("ast_type = ?"),s.push(e.astType)),e.name&&(t.push("name = ?"),s.push(e.name)),e.language&&(t.push("language = ?"),s.push(e.language));let n="SELECT * FROM nodes";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY file_path, start_line",e.limit&&(n+=" LIMIT ?",s.push(e.limit)),e.offset&&(n+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(n).all(...s)}catch(r){throw new exports.b.DatabaseError({message:"Failed to query nodes",operation:"queryNodes"},{cause:r})}}findNodesByName(e){if(!e.name)return [];let t=e.limit??50,s=e.kind?`%${e.kind.toLowerCase()}%`:null,n=new Set,r=[],a=(d,u)=>{n.has(d.id)||(n.add(d.id),r.push({node:d,matchKind:u}));},o=(d,u)=>{e.file&&(e.file.includes("/")?(d.push("file_path = ?"),u.push(e.file)):(d.push("file_path LIKE '%/' || ?"),u.push(e.file))),s&&(d.push("LOWER(ast_type) LIKE ?"),u.push(s));};try{let d=["name = ?"],u=[e.name];o(d,u),u.push(t);let E=this.db.prepare(`SELECT * FROM nodes WHERE ${d.join(" AND ")} LIMIT ?`).all(...u);for(let h of E)a(h,"exact");if(E.length>0&&e.file)return r.slice(0,t);if(r.length<t){let h=this.db.prepare("SELECT * FROM nodes WHERE name LIKE ? LIMIT ?").all(`%${e.name}%`,t);for(let p of h)a(p,"qualified");}if(r.length>0&&e.file)return r.slice(0,t);if(r.length===0&&e.name){let h=["name LIKE ?"],p=[`%${e.name}%`];e.file&&(e.file.includes("/")?(h.push("file_path = ?"),p.push(e.file)):(h.push("file_path LIKE '%/' || ?"),p.push(e.file))),s&&(h.push("LOWER(ast_type) LIKE ?"),p.push(s)),h.push("?"),p.push(t);let b=this.db.prepare(`SELECT * FROM nodes WHERE ${h.join(" AND ")}`).all(...p);for(let N of b)a(N,"substring");}return r.slice(0,t)}catch(d){throw new exports.b.DatabaseError({message:"Failed to find nodes by name",operation:"findNodesByName"},{cause:d})}}queryEdges(e){let t=[],s=[];if(e.sourceOrTarget&&e.sourceOrTarget.length>0){let r=e.sourceOrTarget.map(()=>"?").join(",");t.push(`(source IN (${r}) OR target IN (${r}))`),s.push(...e.sourceOrTarget,...e.sourceOrTarget);}else e.source&&(t.push("source = ?"),s.push(e.source)),e.target&&(t.push("target = ?"),s.push(e.target));e.relation&&(t.push("relation = ?"),s.push(e.relation));let n="SELECT * FROM edges";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY created_at DESC",e.limit&&(n+=" LIMIT ?",s.push(e.limit)),e.offset&&(n+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(n).all(...s)}catch(r){throw new exports.b.DatabaseError({message:"Failed to query edges",operation:"queryEdges"},{cause:r})}}queryAll(e,t){try{let s=this.db.prepare(e);return t?s.all(...t):s.all()}catch(s){throw new exports.b.DatabaseError({message:"Failed to execute query",operation:"queryAll"},{cause:s})}}searchNodesFts(e,t=20){if(l.debug("searchNodesFts start",{query:e,limit:t,ftsAvailable:this.ftsAvailable}),!this.ftsAvailable)return l.debug("searchNodesFts skip - FTS not available"),[];try{let s=e.split(/\s+/).map(o=>`${o}*`).join(" ");l.debug("searchNodesFts query",{ftsQuery:s});let a=this.db.prepare(`
82
+ `);this.db.transaction(n=>{for(let r of n)t.run(r.id,r.source,r.target,r.relation,r.created_at);})(e);}queryNodes(e){let t=[],s=[];e.filePath&&(t.push("file_path LIKE ?"),s.push(`%${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 n="SELECT * FROM nodes";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY file_path, start_line",e.limit&&(n+=" LIMIT ?",s.push(e.limit)),e.offset&&(n+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(n).all(...s)}catch(r){throw new chunkW5SMGCKO_cjs.b.DatabaseError({message:"Failed to query nodes",operation:"queryNodes"},{cause:r})}}findNodesByName(e){if(!e.name)return [];let t=e.limit??50,s=e.kind?`%${e.kind.toLowerCase()}%`:null,n=new Set,r=[],a=(o,c)=>{n.has(o.id)||(n.add(o.id),r.push({node:o,matchKind:c}));},i=(o,c)=>{e.file&&(e.file.includes("/")?(o.push("file_path = ?"),c.push(e.file)):(o.push("file_path LIKE '%/' || ?"),c.push(e.file))),s&&(o.push("LOWER(ast_type) LIKE ?"),c.push(s));};try{let o=["name = ?"],c=[e.name];i(o,c),c.push(t);let p=this.db.prepare(`SELECT * FROM nodes WHERE ${o.join(" AND ")} LIMIT ?`).all(...c);for(let u of p)a(u,"exact");if(p.length>0&&e.file)return r.slice(0,t);if(r.length<t){let u=this.db.prepare("SELECT * FROM nodes WHERE name LIKE ? LIMIT ?").all(`%${e.name}%`,t);for(let g of u)a(g,"qualified");}if(r.length>0&&e.file)return r.slice(0,t);if(r.length===0&&e.name){let u=["name LIKE ?"],g=[`%${e.name}%`];e.file&&(e.file.includes("/")?(u.push("file_path = ?"),g.push(e.file)):(u.push("file_path LIKE '%/' || ?"),g.push(e.file))),s&&(u.push("LOWER(ast_type) LIKE ?"),g.push(s)),u.push("?"),g.push(t);let f=this.db.prepare(`SELECT * FROM nodes WHERE ${u.join(" AND ")}`).all(...g);for(let _ of f)a(_,"substring");}return r.slice(0,t)}catch(o){throw new chunkW5SMGCKO_cjs.b.DatabaseError({message:"Failed to find nodes by name",operation:"findNodesByName"},{cause:o})}}queryEdges(e){let t=[],s=[];if(e.sourceOrTarget&&e.sourceOrTarget.length>0){let r=e.sourceOrTarget.map(()=>"?").join(",");t.push(`(source IN (${r}) OR target IN (${r}))`),s.push(...e.sourceOrTarget,...e.sourceOrTarget);}else e.source&&(t.push("source = ?"),s.push(e.source)),e.target&&(t.push("target = ?"),s.push(e.target));e.relation&&(t.push("relation = ?"),s.push(e.relation));let n="SELECT * FROM edges";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY created_at DESC",e.limit&&(n+=" LIMIT ?",s.push(e.limit)),e.offset&&(n+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(n).all(...s)}catch(r){throw new chunkW5SMGCKO_cjs.b.DatabaseError({message:"Failed to query edges",operation:"queryEdges"},{cause:r})}}queryAll(e,t){try{let s=this.db.prepare(e);return t?s.all(...t):s.all()}catch(s){throw new chunkW5SMGCKO_cjs.b.DatabaseError({message:"Failed to execute query",operation:"queryAll"},{cause:s})}}searchNodesFts(e,t=20){if(d.debug("searchNodesFts start",{query:e,limit:t,ftsAvailable:this.ftsAvailable}),!this.ftsAvailable)return d.debug("searchNodesFts skip - FTS not available"),[];try{let s=e.split(/\s+/).map(i=>`${i}*`).join(" ");d.debug("searchNodesFts query",{ftsQuery:s});let a=this.db.prepare(`
83
83
  SELECT
84
84
  nodes_fts.id,
85
85
  nodes_fts.name,
@@ -97,62 +97,62 @@
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:a.length}),a}catch(s){return l.warn("searchNodesFts failed",{error:utils.errorMeta(s)}),[]}}deleteNodesByFile(e){let t=g(e);if(this.ftsAvailable)try{let n=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let r of n)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(r.rowid);}catch(n){l.warn("FTS delete failed for file",{filePath:t,error:utils.errorMeta(n)});}return this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t).changes}deleteEdgesByFile(e){let t=g(e);return this.db.prepare(`
100
+ `).all(s,t);return d.debug("searchNodesFts done",{resultCount:a.length}),a}catch(s){return d.warn("searchNodesFts failed",{error:utils.errorMeta(s)}),[]}}deleteNodesByFile(e){let t=l(e);if(this.ftsAvailable)try{let n=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let r of n)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(r.rowid);}catch(n){d.warn("FTS delete failed for file",{filePath:t,error:utils.errorMeta(n)});}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(g(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(g(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(g(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}checkIntegrity(){let e=S=>this.db.prepare(S).get().c,t=S=>e(S),s={nodes:t("SELECT COUNT(*) as c FROM nodes"),edges:t("SELECT COUNT(*) as c FROM edges"),file_hashes:t("SELECT COUNT(*) as c FROM file_hashes"),fts:t("SELECT COUNT(*) as c FROM nodes_fts"),node_embeddings:t("SELECT COUNT(*) as c FROM node_embeddings"),embedding_cache:t("SELECT COUNT(*) as c FROM embedding_cache"),parse_errors:t("SELECT COUNT(*) as c FROM parse_errors"),unresolved_refs:t("SELECT COUNT(*) as c FROM unresolved_refs"),name_segment_vocab:t("SELECT COUNT(*) as c FROM name_segment_vocab"),project_metadata:t("SELECT COUNT(*) as c FROM project_metadata"),schema_migrations:t("SELECT COUNT(*) as c FROM schema_migrations"),meta:t("SELECT COUNT(*) as c FROM meta")},n=[],r=t(`
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=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")},n=[],r=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
110
  `);r>0&&n.push({severity:"error",message:`orphan node_embeddings: ${r}`});let a=t(`
111
111
  SELECT COUNT(*) as c FROM edges e
112
112
  WHERE e.relation != 'IMPORTS'
113
113
  AND NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.source)
114
- `);a>0&&n.push({severity:"error",message:`orphan edges (source): ${a}`});let o=t(`
114
+ `);a>0&&n.push({severity:"error",message:`orphan edges (source): ${a}`});let i=t(`
115
115
  SELECT COUNT(*) as c FROM edges e
116
116
  WHERE e.relation NOT IN ('CALLS', 'IMPORTS')
117
117
  AND NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.target)
118
- `);o>0&&n.push({severity:"error",message:`orphan edges (target): ${o}`});let d=t("SELECT COUNT(*) as c FROM edges WHERE source = target");d>0&&n.push({severity:"error",message:`self-loop edges: ${d} \u2014 re-run \`easbot codebase sync\` to filter (fixed in Wave 4 R3-2)`});t("SELECT COUNT(DISTINCT file_path) as c FROM nodes");let E=t(`
118
+ `);i>0&&n.push({severity:"error",message:`orphan edges (target): ${i}`});let o=t("SELECT COUNT(*) as c FROM edges WHERE source = target");o>0&&n.push({severity:"error",message:`self-loop edges: ${o} \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 p=t(`
119
119
  SELECT COUNT(*) as c FROM file_hashes fh
120
120
  WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.file_path = fh.file_path)
121
- `);E>0&&n.push({severity:"warn",message:`orphan file_hashes (no nodes): ${E} \u2014 run \`easbot codebase sync\` to cleanup`});let h=t(`
121
+ `);p>0&&n.push({severity:"warn",message:`orphan file_hashes (no nodes): ${p} \u2014 run \`easbot codebase sync\` to cleanup`});let u=t(`
122
122
  SELECT COUNT(DISTINCT n.file_path) as c FROM nodes n
123
123
  WHERE NOT EXISTS (SELECT 1 FROM file_hashes fh WHERE fh.file_path = n.file_path)
124
- `);h>0&&n.push({severity:"warn",message:`node files without hash: ${h}`});let p=t("SELECT COUNT(*) as c FROM nodes WHERE name IS NULL OR name = ''");p>0&&n.push({severity:"error",message:`nodes with null/empty name: ${p}`});let b=t("SELECT COUNT(*) as c FROM nodes WHERE ast_type IS NULL OR ast_type = ''");b>0&&n.push({severity:"error",message:`nodes with null/empty ast_type: ${b}`});let N=t("SELECT COUNT(*) as c FROM nodes WHERE language IS NULL OR language = ''");N>0&&n.push({severity:"error",message:`nodes with null/empty language: ${N}`});let L=t("SELECT COUNT(*) as c FROM nodes WHERE file_path IS NULL OR file_path = ''");L>0&&n.push({severity:"error",message:`nodes with null/empty file_path: ${L}`});let F=this.db.prepare("SELECT id, COUNT(*) as c FROM nodes GROUP BY id HAVING c > 1").all().length;F>0&&n.push({severity:"error",message:`duplicate node ids: ${F}`});let C=t("SELECT COUNT(*) as c FROM nodes WHERE file_path LIKE '%\\\\%'");C>0&&n.push({severity:"warn",message:`nodes with backslash in file_path: ${C}`});let y=t(`
124
+ `);u>0&&n.push({severity:"warn",message:`node files without hash: ${u}`});let g=t("SELECT COUNT(*) as c FROM nodes WHERE name IS NULL OR name = ''");g>0&&n.push({severity:"error",message:`nodes with null/empty name: ${g}`});let f=t("SELECT COUNT(*) as c FROM nodes WHERE ast_type IS NULL OR ast_type = ''");f>0&&n.push({severity:"error",message:`nodes with null/empty ast_type: ${f}`});let _=t("SELECT COUNT(*) as c FROM nodes WHERE language IS NULL OR language = ''");_>0&&n.push({severity:"error",message:`nodes with null/empty language: ${_}`});let O=t("SELECT COUNT(*) as c FROM nodes WHERE file_path IS NULL OR file_path = ''");O>0&&n.push({severity:"error",message:`nodes with null/empty file_path: ${O}`});let I=this.db.prepare("SELECT id, COUNT(*) as c FROM nodes GROUP BY id HAVING c > 1").all().length;I>0&&n.push({severity:"error",message:`duplicate node ids: ${I}`});let L=t("SELECT COUNT(*) as c FROM nodes WHERE file_path LIKE '%\\\\%'");L>0&&n.push({severity:"warn",message:`nodes with backslash in file_path: ${L}`});let C=t(`
125
125
  SELECT COUNT(*) as c FROM nodes
126
126
  WHERE start_line IS NOT NULL AND end_line IS NOT NULL AND start_line > end_line
127
- `);y>0&&n.push({severity:"error",message:`invalid line ranges: ${y}`});let M=this.db.prepare("SELECT id, COUNT(*) as c FROM edges GROUP BY id HAVING c > 1").all().length;M>0&&n.push({severity:"error",message:`duplicate edge ids: ${M}`});let A=t("SELECT COUNT(*) as c FROM nodes_fts_content");return A!==s.nodes&&n.push({severity:"error",message:`FTS content desync: ${A} vs ${s.nodes} (run \`easbot codebase recreate\` to rebuild)`}),s.parse_errors>100&&n.push({severity:"warn",message:`parse_errors > 100 (${s.parse_errors}) \u2014\u2014 many files failed to parse`}),{issues:n,stats:s}}getStatus(){let e=this.db.prepare("SELECT COUNT(*) as c FROM nodes").get(),t=this.db.prepare("SELECT COUNT(*) as c FROM edges").get(),s=this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get(),n=this.db.prepare("SELECT key, value FROM meta").all(),r={};for(let a of n)r[a.key]=a.value;return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:s?.c??0,dbPath:this.dbPath,meta:r,indexState:this.getIndexState(),extractionVersion:parseInt(this.getMeta("indexed_with_extraction_version")??"0",10),isStale:this.isIndexStale()}}setLastSync(){this.db.prepare(`
127
+ `);C>0&&n.push({severity:"error",message:`invalid line ranges: ${C}`});let F=this.db.prepare("SELECT id, COUNT(*) as c FROM edges GROUP BY id HAVING c > 1").all().length;F>0&&n.push({severity:"error",message:`duplicate edge ids: ${F}`});let M=t("SELECT COUNT(*) as c FROM nodes_fts_content");return M!==s.nodes&&n.push({severity:"error",message:`FTS content desync: ${M} vs ${s.nodes} (run \`easbot codebase recreate\` to rebuild)`}),s.parse_errors>100&&n.push({severity:"warn",message:`parse_errors > 100 (${s.parse_errors}) \u2014\u2014 many files failed to parse`}),{issues:n,stats:s}}getStatus(){let e=this.db.prepare("SELECT COUNT(*) as c FROM nodes").get(),t=this.db.prepare("SELECT COUNT(*) as c FROM edges").get(),s=this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get(),n=this.db.prepare("SELECT key, value FROM meta").all(),r={};for(let a of n)r[a.key]=a.value;return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:s?.c??0,dbPath:this.dbPath,meta:r,indexState:this.getIndexState(),extractionVersion:parseInt(this.getMeta("indexed_with_extraction_version")??"0",10),isStale:this.isIndexStale()}}setLastSync(){this.db.prepare(`
128
128
  INSERT OR REPLACE INTO meta (key, value)
129
129
  VALUES ('lastSync', ?)
130
- `).run(new Date().toISOString());}getIndexState(){return this.getMeta("index_state")??"uninitialized"}setIndexState(e){this.setMeta("index_state",e),this.setMeta("last_index_state_change",new Date().toISOString());}markIndexed(e){this.setMeta("indexed_with_version",e),this.setMeta("indexed_with_extraction_version",String(I)),this.setMeta("index_state","complete"),this.setMeta("last_index_state_change",new Date().toISOString());}isIndexStale(){let e=this.getMeta("indexed_with_extraction_version");if(!e)return false;let t=parseInt(e,10);return Number.isNaN(t)||t<I}detectAndMarkStaleOnInit(){if(this.isIndexStale()){let e=this.getMeta("indexed_with_extraction_version");l.warn("codebase db is stale",{recorded:e??"(none)",current:String(I),hint:"run `easbot codebase recreate` or `easbot codebase index --force` to rebuild"});let t=this.getIndexState();(t==="complete"||t==="partial")&&this.setIndexState("stale");}}getNodeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM nodes").get()?.c??0}getEdgeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM edges").get()?.c??0}getFileCount(){return this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get()?.c??0}getNodeById(e){return this.db.prepare("SELECT * FROM nodes WHERE id = ?").get(e)??null}getEdgeById(e){return this.db.prepare("SELECT * FROM edges WHERE id = ?").get(e)??null}clearAll(e={}){this.db.exec("DELETE FROM nodes"),this.db.exec("DELETE FROM edges"),this.db.exec("DELETE FROM file_hashes"),this.db.exec("DELETE FROM meta"),e.keepEmbeddings||(this.db.exec("DELETE FROM node_embeddings"),this.db.exec("DELETE FROM embedding_cache")),this.ftsAvailable&&this.db.exec("DELETE FROM nodes_fts");try{this.db.exec("DELETE FROM sqlite_sequence WHERE name IN ('nodes', 'edges', 'file_hashes', 'meta')");}catch{}}getCachedEmbedding(e){let s=this.db.prepare(`
130
+ `).run(new Date().toISOString());}getIndexState(){return this.getMeta("index_state")??"uninitialized"}setIndexState(e){this.setMeta("index_state",e),this.setMeta("last_index_state_change",new Date().toISOString());}markIndexed(e){this.setMeta("indexed_with_version",e),this.setMeta("indexed_with_extraction_version",String(S)),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<S}detectAndMarkStaleOnInit(){if(this.isIndexStale()){let e=this.getMeta("indexed_with_extraction_version");d.warn("codebase db is stale",{recorded:e??"(none)",current:String(S),hint:"run `easbot codebase recreate` or `easbot codebase index --force` to rebuild"});let t=this.getIndexState();(t==="complete"||t==="partial")&&this.setIndexState("stale");}}getNodeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM nodes").get()?.c??0}getEdgeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM edges").get()?.c??0}getFileCount(){return this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get()?.c??0}getNodeById(e){return this.db.prepare("SELECT * FROM nodes WHERE id = ?").get(e)??null}getEdgeById(e){return this.db.prepare("SELECT * FROM edges WHERE id = ?").get(e)??null}clearAll(e={}){this.db.exec("DELETE FROM nodes"),this.db.exec("DELETE FROM edges"),this.db.exec("DELETE FROM file_hashes"),this.db.exec("DELETE FROM meta"),e.keepEmbeddings||(this.db.exec("DELETE FROM node_embeddings"),this.db.exec("DELETE FROM embedding_cache")),this.ftsAvailable&&this.db.exec("DELETE FROM nodes_fts");try{this.db.exec("DELETE FROM sqlite_sequence WHERE name IN ('nodes', 'edges', 'file_hashes', 'meta')");}catch{}}getCachedEmbedding(e){let s=this.db.prepare(`
131
131
  SELECT embedding FROM embedding_cache WHERE content_hash = ?
132
132
  `).get(e);return s?new Float32Array(s.embedding.buffer,s.embedding.byteOffset,s.embedding.length/4):null}getVectorDims(){let e=this.db.prepare("SELECT value FROM meta WHERE key = ?").get("vectorDims");return e?parseInt(e.value,10):void 0}ensureVectorDims(e){this.db.prepare("SELECT value FROM meta WHERE key = ?").get("vectorDims")||this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)").run("vectorDims",String(e));}cacheEmbedding(e,t){if(this.db.prepare("SELECT embedding FROM embedding_cache WHERE content_hash = ?").get(e))return;this.ensureVectorDims(t.length),this.db.prepare(`
133
133
  INSERT OR REPLACE INTO embedding_cache (content_hash, embedding)
134
134
  VALUES (?, ?)
135
- `).run(e,t);}deleteEmbeddingsByFile(e){let t=g(e);return this.db.prepare(`
135
+ `).run(e,t);}deleteEmbeddingsByFile(e){let t=l(e);return this.db.prepare(`
136
136
  DELETE FROM node_embeddings WHERE node_id IN (SELECT id FROM nodes WHERE file_path = ?)
137
137
  `).run(t).changes}getAllNodeEmbeddings(){return this.db.prepare("SELECT node_id, embedding FROM node_embeddings").all()}storeNodeEmbeddings(e){if(e.length===0)return;this.ensureVectorDims(e[0].embedding.length);let t=this.db.prepare(`
138
138
  INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
139
139
  VALUES (?, ?, ?)
140
- `);this.db.transaction(n=>{for(let r of n)try{t.run(r.nodeId,r.embeddingText,r.embedding);}catch(a){l.warn("Failed to store embedding for node",{nodeId:r.nodeId,error:utils.errorMeta(a)});}})(e);}insertParseError(e){return this.db.prepare(`
140
+ `);this.db.transaction(n=>{for(let r of n)try{t.run(r.nodeId,r.embeddingText,r.embedding);}catch(a){d.warn("Failed to store embedding for node",{nodeId:r.nodeId,error:utils.errorMeta(a)});}})(e);}insertParseError(e){return this.db.prepare(`
141
141
  INSERT INTO parse_errors (file_path, language, stage, message, line)
142
142
  VALUES (?, ?, ?, ?, ?)
143
- `).run(g(e.filePath),e.language,e.stage,e.message,e.line??null).changes}insertUnresolvedRef(e){return this.db.prepare(`
143
+ `).run(l(e.filePath),e.language,e.stage,e.message,e.line??null).changes}insertUnresolvedRef(e){return this.db.prepare(`
144
144
  INSERT INTO unresolved_refs
145
145
  (from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
146
146
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
147
- `).run(e.fromNodeId??null,e.referenceName,e.referenceKind,e.line??null,e.col??null,g(e.filePath),e.language,e.candidates?JSON.stringify(e.candidates):null).changes}insertUnresolvedRefsBatch(e){if(e.length===0)return 0;let s=`
147
+ `).run(e.fromNodeId??null,e.referenceName,e.referenceKind,e.line??null,e.col??null,l(e.filePath),e.language,e.candidates?JSON.stringify(e.candidates):null).changes}insertUnresolvedRefsBatch(e){if(e.length===0)return 0;let s=`
148
148
  INSERT INTO unresolved_refs
149
149
  (from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
150
150
  VALUES ${e.map(()=>"(?, ?, ?, ?, ?, ?, ?, ?)").join(", ")}
151
- `,n=[];for(let o of e)n.push(o.fromNodeId??null,o.referenceName,o.referenceKind,o.line??null,o.col??null,g(o.filePath),o.language,o.candidates?JSON.stringify(o.candidates):null);return this.db.prepare(s).run(...n).changes}insertNameSegment(e,t){return this.db.prepare(`
151
+ `,n=[];for(let i of e)n.push(i.fromNodeId??null,i.referenceName,i.referenceKind,i.line??null,i.col??null,l(i.filePath),i.language,i.candidates?JSON.stringify(i.candidates):null);return this.db.prepare(s).run(...n).changes}insertNameSegment(e,t){return this.db.prepare(`
152
152
  INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES (?, ?)
153
153
  `).run(e,t).changes}insertNameSegmentsBatch(e){if(e.length===0)return 0;let s=`
154
154
  INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES ${e.map(()=>"(?, ?)").join(", ")}
155
- `,n=[];for(let o of e)n.push(o.segment,o.name);return this.db.prepare(s).run(...n).changes}setProjectMetadata(e,t){let s=e==="worktree"||e==="project"?g(t):t;return this.db.prepare(`
155
+ `,n=[];for(let i of e)n.push(i.segment,i.name);return this.db.prepare(s).run(...n).changes}setProjectMetadata(e,t){let s=e==="worktree"||e==="project"?l(t):t;return this.db.prepare(`
156
156
  INSERT OR REPLACE INTO project_metadata (key, value, updated_at)
157
157
  VALUES (?, ?, CURRENT_TIMESTAMP)
158
- `).run(e,s).changes}getNodeIdsByFile(e){let t=e.replace(/\\/g,"/");return this.db.prepare("SELECT id FROM nodes WHERE file_path = ?").all(t).map(n=>n.id)}deleteFtsByFile(e){let t=e.replace(/\\/g,"/"),s=this.getNodeIdsByFile(t);if(s.length===0)return 0;let n=this.db.prepare("DELETE FROM nodes_fts WHERE id = ?");return this.db.transaction(a=>{for(let o of a)n.run(o);})(s),s.length}initialize(){if(this.closed)throw new exports.b.DatabaseError({message:"Cannot initialize closed database",operation:"initialize"})}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){l.warn("Database close error",{error:utils.errorMeta(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new utils.NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new utils.NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}countSqliteObjects(){if(!this.db)throw new utils.NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});return this.db.prepare("SELECT COUNT(*) as n FROM sqlite_master WHERE type IN ('table', 'index', 'trigger', 'view')").get()?.n??0}deleteMeta(e){if(!this.db)throw new utils.NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});this.db.prepare("DELETE FROM meta WHERE key = ?").run(e);}};function ae(c){return c.isClosed()}function ie(c){return c.getDbPath()}function oe(c,e){return c.transaction(e)}Object.defineProperty(exports,"a",{enumerable:true,get:function(){return utils.ServiceError}});exports.c=W;exports.d=k;exports.e=z;exports.f=O;exports.g=V;exports.h=w;exports.i=D;exports.j=I;exports.k=P;exports.l=ae;exports.m=ie;exports.n=oe;
158
+ `).run(e,s).changes}getNodeIdsByFile(e){let t=e.replace(/\\/g,"/");return this.db.prepare("SELECT id FROM nodes WHERE file_path = ?").all(t).map(n=>n.id)}deleteFtsByFile(e){let t=e.replace(/\\/g,"/"),s=this.getNodeIdsByFile(t);if(s.length===0)return 0;let n=this.db.prepare("DELETE FROM nodes_fts WHERE id = ?");return this.db.transaction(a=>{for(let i of a)n.run(i);})(s),s.length}initialize(){if(this.closed)throw new chunkW5SMGCKO_cjs.b.DatabaseError({message:"Cannot initialize closed database",operation:"initialize"})}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){d.warn("Database close error",{error:utils.errorMeta(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new utils.NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new utils.NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}countSqliteObjects(){if(!this.db)throw new utils.NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});return this.db.prepare("SELECT COUNT(*) as n FROM sqlite_master WHERE type IN ('table', 'index', 'trigger', 'view')").get()?.n??0}deleteMeta(e){if(!this.db)throw new utils.NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});this.db.prepare("DELETE FROM meta WHERE key = ?").run(e);}};function z(E){return E.isClosed()}function G(E){return E.getDbPath()}function j(E,e){return E.transaction(e)}exports.a=N;exports.b=X;exports.c=v;exports.d=w;exports.e=S;exports.f=U;exports.g=z;exports.h=G;exports.i=j;
@@ -0,0 +1,62 @@
1
+ import {b,c,r}from'./chunk-KR6BQNY6.mjs';import {e}from'./chunk-KTSR5VPT.mjs';import {Log,Filesystem,ServiceError,ServiceErrorBus,TruncateContent,errorMeta}from'@easbot/utils';import {resolveSqlTextLimit,SQL_TEXT_LIMIT_DEFAULT}from'@easbot/database';import {DEFAULT_SEARCH_CONFIG,DEFAULT_PARSER_CONFIG,DEFAULT_INDEXER_CONFIG,DEFAULT_EMBEDDING_CONFIG}from'@easbot/types';import {existsSync,statSync}from'fs';var te=Log.create({service:"codebase.services.codebase"}),N=Filesystem.toUnixPath;function Re(e,t){let n={exact:1,qualified:.85,substring:.5}[e];return t?Math.min(1,n+.2):n}function Se(e,t){if(!t)return false;if(e===t)return true;let n=e.split(/[/\\]/).pop()??"",s=t.split(/[/\\]/).pop()??"";return !!(n&&s&&n===s||t.includes("/")&&e.endsWith("/"+t))}async function _(e,t,n){if(n.nodeId){let o=e.getNode(n.nodeId);if(!o)throw new ServiceError({code:"NOT_FOUND",message:`Node not found: nodeId=${n.nodeId}`,details:{name:n.nodeId}});return {node:o,candidates:[]}}if(!n.name)throw new ServiceError({code:"NOT_FOUND",message:"Either name or nodeId is required",details:{...n}});let l=e.getDatabase().findNodesByName({name:n.name,file:n.file,kind:n.kind,limit:50});if(l.length===0)throw new ServiceError({code:"NOT_FOUND",message:`Node not found: ${n.name}`,details:{name:n.name,candidates:[]}});let a=!!n.file,c=n.file?N(n.file):null,i=l.map(o=>{let u=c?Se(N(o.node.file_path),c):false;return {node:o.node,score:Re(o.matchKind,u),matchKind:o.matchKind,inFile:u}});if(i.sort((o,u)=>u.score-o.score),i.length===1)return {node:i[0].node,candidates:i.map(o=>({node:o.node,score:o.score}))};let d=i[0].score,r=i.filter(o=>o.score===d);if(r.length===1)return {node:r[0].node,candidates:i.slice(0,10).map(o=>({node:o.node,score:o.score}))};if(a&&r.length>1){let o=r.filter(u=>u.inFile);if(o.length===1)return {node:o[0].node,candidates:i.slice(0,10).map(u=>({node:u.node,score:u.score}))}}throw new ServiceError({code:"AMBIGUOUS",message:`Ambiguous name "${n.name}" \u2014 ${i.length} candidates`,details:{name:n.name,candidates:i.slice(0,10).map(o=>({node:o.node,score:o.score}))}})}async function P(e){let t=c(e.rootDir),n=new r({workspaceDir:e.workspaceDir,database:{path:t,walMode:true},embedding:DEFAULT_EMBEDDING_CONFIG,indexer:DEFAULT_INDEXER_CONFIG,parser:DEFAULT_PARSER_CONFIG,search:DEFAULT_SEARCH_CONFIG,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});return await n.initialize(),n}function z(e,t,n,s){let l=n.map(()=>"?").join(","),a=t.name.split("@")[0]??t.name,c=a.includes(".")?a.split(".").pop()??a:a,i=new Set([`${t.language}:*:*:${a}`]);c!==a&&i.add(`${t.language}:*:*:${c}`);let d=[];c!==a&&d.push(`${t.language}:*:*:%${c}`);let r=Array.from(i),o=r.map(()=>"?").join(","),g=d.length>0?"OR LOWER(target) LIKE LOWER(?)":"";r.length>1&&te.warn("queryIncomingEdgesWithWildcard: multi-variant wildcards (bare+namespaced)",{rootName:t.name,wildcards:r,hint:"\u540C\u540D\u540C namespace \u4E0D\u540C file \u7684\u65B9\u6CD5\u53EF\u80FD\u90FD\u88AB\u547D\u4E2D\uFF0CLLM \u63A8\u7406\u8BF7\u7528 file \u8FC7\u6EE4\u8F85\u4F50"});let m=`
2
+ SELECT id, source, target, relation, created_at FROM edges
3
+ WHERE relation IN (${l})
4
+ AND source != target
5
+ AND (
6
+ target = ?
7
+ OR target IN (${o})
8
+ ${g}
9
+ )
10
+ GROUP BY id
11
+ LIMIT ?
12
+ `;return e.queryAll(m,[...n,t.id,...r,...d,s])}function Ce(e){return e==="class_declaration"||e==="class_definition"||e==="interface_declaration"||e==="struct_declaration"||e==="struct_specifier"||e==="record_declaration"}function Ie(e,t,n,s,l){let c=e.queryAll("SELECT id FROM nodes WHERE file_path = ? AND start_line >= ? AND end_line <= ? AND ast_type IN ('method_definition', 'method_declaration') LIMIT 1000",[t.file_path,t.start_line,t.end_line]).map(r=>r.id),i=new Set,d=[];for(let r of n)r.id&&!i.has(r.id)&&(i.add(r.id),d.push(r));if(c.length>0){let r=s.map(()=>"?").join(","),o=c.map(()=>"?").join(","),u=`
13
+ SELECT id, source, target, relation, created_at FROM edges
14
+ WHERE relation IN (${r})
15
+ AND source != target
16
+ AND source IN (${o})
17
+ GROUP BY id
18
+ LIMIT ?
19
+ `,g=e.queryAll(u,[...s,...c,l]);for(let m of g)m.id&&!i.has(m.id)&&(i.add(m.id),d.push(m));}return d.slice(0,l)}function ne(e,t,n,s){let a=`
20
+ SELECT id, source, target, relation, created_at FROM edges
21
+ WHERE relation IN (${n.map(()=>"?").join(",")})
22
+ AND source != target
23
+ AND source = ?
24
+ LIMIT ?
25
+ `;return e.queryAll(a,[...n,t.id,s])}function re(e,t,n,s){let l=s==="in"?e.source:e.target;t.id;let c=n.getNodeById(l);if(!c&&l.includes(":*:")){let i=l.split(":").pop()??l,d=i.split("@")[0]??i;if(d&&d!==l){let r=n.findNodesByName({name:d}),o=t.file_path??"",u=o.split(/[/\\]/).pop()??"",g=o.split(/[/\\]/).filter(Boolean),m=r.find(p=>p.node.file_path?p.node.file_path===o:false)??r.find(p=>!p.node.file_path||!u?false:p.node.file_path.split(/[/\\]/).pop()===u)??r.find(p=>{if(!p.node.file_path)return false;let f=p.node.file_path.split(/[/\\]/).filter(Boolean);return g.length<2||f.length<2?false:g[0]===f[0]&&g[1]===f[1]})??null;m&&(c=m.node);}}if(!c){let i=l.split(":").pop()??l;return {id:l,name:i,astType:"unresolved",filePath:"(unresolved)",startLine:0,relation:e.relation}}return {id:c.id,name:c.name,astType:c.ast_type,filePath:N(c.file_path),startLine:c.start_line??0,relation:e.relation}}async function oe(e,t){let n=Date.now(),l=(await P(e)).getQuery(),a=resolveSqlTextLimit(t.snippetMaxChars??SQL_TEXT_LIMIT_DEFAULT),i=await l.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,snippetMaxChars:a});if(t.kind){let o=t.kind.toLowerCase();i=i.filter(u=>u.ast_type.includes(o)||u.name.toLowerCase().includes(o));}if(t.file){let o=N(t.file);i=i.filter(u=>N(u.file_path).endsWith(o)||N(u.file_path).includes(o));}let d=t.maxEdgesPerNode??10,r=i.map(o=>({nodeId:o.id,name:o.name,kind:o.ast_type??"unknown",filePath:N(o.file_path),startLine:o.start_line,endLine:o.end_line,edges:(o.edges??[]).slice(0,d),source:"basic",score:0,snippet:(o.text??"").slice(0,a).replace(/\s+/g," ").trim()}));return {total:r.length,hits:r,durationMs:Date.now()-n,truncated:false}}async function Le(e,t){let n=await P(e),s=n.getQuery(),l=n.getDatabase(),{node:a}=await _(s,e,t),c=[];if(t.includeEdges){let i=t.maxEdgesPerNode??10,d=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"],r=z(l,a,d,i+1),o=ne(l,a,d,i+1),u=new Set,g=[];for(let m of [...r,...o])m.id&&!u.has(m.id)&&(u.add(m.id),g.push(m));c=g.slice(0,i);}return {node:a,edges:c}}var Te=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"];async function $e(e,t){let n=await P(e),s=n.getQuery(),l=n.getDatabase(),{node:a}=await _(s,e,t);if(!a)return {root:null,nodes:[],edges:[],truncated:false,totalNodes:0,totalEdges:0};let c=t.depth??2,i=t.maxNodes??100,d=t.direction??"both";t.maxEdgesPerNode??10;let o=new Map,u=[{nodeId:a.id,depth:0}];o.set(a.id,0);let g=[],m=false;for(;u.length>0;){let y=u.shift();if(y.depth>=c)continue;if(o.size>=i){m=true;break}let L=s.queryNeighbors(y.nodeId,{direction:d,relationTypes:t.relationTypes??Te,limit:i-o.size+1});for(let b of L.edges){g.push(b);let T=b.source===y.nodeId?b.target:b.source;if(!o.has(T)&&(o.set(T,y.depth+1),u.push({nodeId:T,depth:y.depth+1}),o.size>=i)){m=true;break}}if(m)break}let p=new Set,f=[];for(let y of g)!y.id||p.has(y.id)||(p.add(y.id),f.push(y));let E=Array.from(o.keys()),h=E.length>0?l.queryNodes({ids:E}):[],I=new Map(h.map(y=>[y.id,y])),x=[];for(let[y,L]of o.entries()){let b=I.get(y);b&&x.push({node:b,depth:L});}return {root:a,nodes:x,edges:f,truncated:m,totalNodes:x.length,totalEdges:g.length}}var _e=["CALLS","IMPORTS","TYPE_REFERENCES"];async function we(e,t){let n=await P(e),s=n.getQuery(),l=n.getDatabase(),{node:a}=await _(s,e,t);if(!a)return {root:null,totalImpacted:0,buckets:[]};let c=t.depth??2,i=t.maxResults??10,d=t.relationTypes??_e,r=t.maxEdgesPerNode??10,o=new Set([a.id]),u=[],g=[a.id];for(let m=1;m<=c&&!(g.length===0||o.size-1>=i);m++){let p=z(l,a,d,r+1),f=[],E=new Set;for(let h of p)if(!o.has(h.source)&&!E.has(h.source)&&(E.add(h.source),o.add(h.source),f.push(h.source),o.size-1>=i))break;if(f.length>0){let h=f.slice(0,10),I=l.queryNodes({ids:h}),x=new Map(I.map(b=>[b.id,b])),y=new Map;for(let b of p)y.has(b.source)||y.set(b.source,b.relation);let L=h.map(b=>{let T=x.get(b);return {id:b,name:T?.name??"(unknown)",filePath:T?N(T.file_path):"(unknown)",relation:y.get(b)??"CALLS"}});u.push({depth:m,count:f.length,sample:L});}g=f;}return u.length===0&&te.warn("impact: no incoming edges found",{root:a.name,depth:c,relationTypes:d}),{root:a,totalImpacted:o.size-1,buckets:u}}var se=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","METHOD_OVERRIDES"];async function Fe(e,t){return ie(e,t)}async function Ae(e,t){return ae(e,t)}async function ie(e,t){let n=await P(e),s=n.getQuery(),l=n.getDatabase(),{node:a}=await _(s,e,t);if(!a)return {root:null,callers:[],truncated:false};let c=t.maxResults??10,i=t.maxEdgesPerNode??c,d=t.relationTypes??se,r=z(l,a,d,i+1),o=[];for(let g of r){let m=re(g,a,l,"in");m&&o.push(m);}let u=o.length>c;return {root:a,callers:u?o.slice(0,c):o,truncated:u}}async function ae(e,t){let n=await P(e),s=n.getQuery(),l=n.getDatabase(),{node:a}=await _(s,e,t);if(!a)return {root:null,callees:[],truncated:false};let c=t.maxResults??10,i=t.maxEdgesPerNode??c,d=t.relationTypes??se,r=ne(l,a,d,i+1),o=Ce(a.ast_type)?Ie(l,a,r,d,i+1):r,u=[];for(let m of o){let p=re(m,a,l,"out");p&&u.push(p);}let g=u.length>c;return {root:a,callees:g?u.slice(0,c):u,truncated:g}}async function De(e,t){if(!t.query)throw new ServiceError({code:"NOT_FOUND",message:"explore requires a non-empty query",details:{query:t.query}});let s=await P(e),l=s.getQuery(),a=s.getDatabase(),c=resolveSqlTextLimit(t.snippetMaxChars??SQL_TEXT_LIMIT_DEFAULT),d=(await oe(e,{query:t.query,file:t.file,kind:t.kind,intent:t.intent,maxResults:t.maxFiles??5,enableFts:true,enableEmbedding:true,snippetMaxChars:c})).hits;if(t.file||t.kind)try{let m=await _(l,e,{name:t.query,file:t.file,kind:t.kind});if(m?.node){let p={nodeId:m.node.id,name:m.node.name,kind:m.node.ast_type,filePath:N(m.node.file_path),startLine:m.node.start_line,endLine:m.node.end_line,edges:[],source:"basic",score:0,snippet:(m.node.text??"").slice(0,c).replace(/\s+/g," ").trim()},f=d.filter(E=>E.nodeId!==p.nodeId);d=[p,...f];}}catch{}let r=new Map;for(let m of d){let p=N(m.filePath),f=r.get(p);f?f.push(m):r.set(p,[m]);}let o=t.maxSymbols??3,u=t.maxEdgesPerNode??10,g=[];for(let[m,p]of r){let f=p.slice(0,o),E=[];for(let h of f){let I=await ie(e,{name:h.name,file:m,kind:t.kind,maxResults:u,maxEdgesPerNode:u}),x=await ae(e,{name:h.name,file:m,kind:t.kind,maxResults:u,maxEdgesPerNode:u});E.push({node:(()=>{let y={id:h.nodeId,name:h.name,ast_type:h.kind,language:"ts",file_path:h.filePath,start_line:h.startLine??0,end_line:h.endLine??0};try{let L=a.getNodeById(h.nodeId);return {...y,text:L?.text??""}}catch{return {...y,text:""}}})(),callers:I.callers,callees:x.callees});}g.push({file:m,symbols:E});}return {query:t.query,entryPoints:g,totalHits:d.length}}async function Oe(e,t){let s=await(await P(e)).getStatus();s.package="codebase",s.workspaceDir=e.workspaceDir;let l=b(e.workspaceDir),a=existsSync(l),c=existsSync(s.dbPath),i;if(c)try{i=statSync(s.dbPath).size;}catch{}s.configPath=l,s.configExists=a,s.dbExists=c,s.dbSize=i,s.vectorEnabled=s.meta?.vector_enabled==="true"||s.meta?.vector_enabled==="1";let d=s.meta?.embeddingDims;d&&Number.isFinite(Number.parseInt(d,10))&&(s.embeddingDims=Number.parseInt(d,10));let r={initialized:false,capabilities:{embedding:false,evaluation:false}};try{let{Llm:o}=await import('./llm-WS3XKT46.mjs');if(o.isInitialized()){r.initialized=!0;let u=o.capabilities();r.capabilities={embedding:u.embedding===!0,evaluation:u.evaluation===!0},r.embeddingModel=r.capabilities.embedding?"configured":void 0,r.evaluationModel=r.capabilities.evaluation?"configured":void 0;}}catch{}s.llm=r;try{let{DatabaseManager:o}=await import('./database-manager-KM7BOISA.mjs'),u=new o(s.dbPath);try{let{stats:g}=u.checkIntegrity();s.dbStats=g,s.ftsAvailable=u.isFtsAvailable();}finally{u.close();}}catch{}return s}async function ke(e,t){return await(await P(e)).healthCheck()}var He=Log.create({service:"codebase.services.init"}),le=false;async function qe(){le||(le=true,He.info("codebase service init"),await ServiceErrorBus.init(),await e());}var ze=200,de=Filesystem.toUnixPath;function Ke(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 je(e){let t=e.text??"";if(!t)return [];let n=t.slice(0,80),s=[];return /\basync\s/.test(n)&&s.push("async"),/\bstatic\s/.test(n)&&s.push("static"),/\babstract\s/.test(n)&&s.push("abstract"),/\breadonly\s/.test(n)&&s.push("readonly"),/\bconst\s/.test(n)&&s.push("const"),/\blet\s/.test(n)&&s.push("let"),s}function R(e){return {id:e.id,name:e.name,astType:e.ast_type,language:e.language,filePath:de(e.file_path),startLine:e.start_line??0,endLine:e.end_line??0,isExported:Ke(e),modifiers:je(e)}}function w(e,t){return {id:e.id,source:e.source,target:e.target,relation:e.relation,direction:t}}function K(e){return e.map(t=>({node:{id:t.nodeId,name:t.name,astType:t.kind,language:"typescript",filePath:de(t.filePath),startLine:t.startLine??0,endLine:t.endLine??0,isExported:false,modifiers:[]},source:t.source,score:t.score,snippet:(t.snippet??"").slice(0,resolveSqlTextLimit(ze)),edges:(t.edges??[]).slice(0,10).map(n=>w({...n}))}))}function j(){return {id:"",name:"",astType:"",language:"",filePath:"",startLine:0,endLine:0,isExported:false,modifiers:[]}}var Qe=Log.create({service:"codebase.format.truncate"}),W="**`",Ye="**",ue=24e3,me=25e3;async function O(e,t={}){let n=t.softLimit??ue,s=t.hardCeiling??me,l=t.toolName??"codebase",a=t.writeToDisk!==false;if(e.length<=n)return {content:e,truncated:false};let c=e.slice(0,s),i=c.lastIndexOf(`
26
+ ${W}`),d=c.lastIndexOf(`
27
+ `),r;i>s*.5?r=i:d>0?r=d:r=-1;let o=r>0?c.slice(0,r):c,g=o+"\n\n... (output truncated to budget; the source above is complete and verbatim \u2014 treat it as already Read. For any area not covered, make ANOTHER `<tool>` targeting those names \u2014 do NOT Read these files.)";if(!a)return {content:g,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-o.length}/${e.length} characters truncated ...`};try{let m=await TruncateContent.truncate(e,{maxChars:o.length,direction:"head",label:`${l}-output`});return m.truncated?{content:g,truncated:!0,outputPath:m.outputPath,hint:TruncateContent.formatHint(m),info:`... ${m.removedLength}/${m.originalLength} characters truncated ...`}:{content:g,truncated:!0,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-o.length}/${e.length} characters truncated ...`}}catch(m){return Qe.warn("TruncateContent.truncate failed, returning without disk hint",{error:errorMeta(m)}),{content:g,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-o.length}/${e.length} characters truncated ...`}}}function k(e,t={}){let n=t.softLimit??ue,s=t.hardCeiling??me;if(e.length<=n)return {content:e,truncated:false};let l=e.slice(0,s),a=l.lastIndexOf(`
28
+ ${W}`),c=l.lastIndexOf(`
29
+ `),i;a>s*.5?i=a:c>0?i=c:i=-1;let d=i>0?l.slice(0,i):l;return {content:d+`
30
+
31
+ ... (output truncated; tail dropped at section boundary)`,truncated:true,outputPath:"",hint:"",info:`... ${e.length-d.length}/${e.length} characters truncated ...`}}function Ve(e,t=Date.now()){let n=Math.max(0,Math.floor((t-e)/1e3));return n>60?">60s ago":`${n}s ago`}function v(e,t){if(!e||e.length===0)return null;let n=e.filter(l=>t.has(l.path));return n.length===0?null:`\u26A0\uFE0F Index may be stale for: ${n.map(l=>`${l.path} (edited ${Ve(l.lastEventAt)})`).join(", ")}
32
+
33
+ `}function D(e,t,n={}){return (ge[e]??ge.default).replace(/<(\w+)>/g,(l,a)=>a==="tool"?t:n[a]??`<${a}>`)}var ge={search:`---
34
+
35
+ > **Complete source for N files is included above \u2014 do NOT re-read them.**
36
+ > If your question also needs files/symbols listed under "Not shown above" (or any area this call didn't cover), make ANOTHER \`<tool>\` targeting those names \u2014 it returns the same source with line numbers and is cheaper and more complete than reading.`,impact:"---\n\n> **Risk: <riskLevel>**. Before editing `<root>`, review d=1 first \u2014 those WILL BREAK.\n> Use `<tool>` to read full source of any direct caller.",context:"---\n\n> **Use `impact` for blast-radius analysis. Use `explore` to read source.**",default:`---
37
+
38
+ > **Output truncated to budget; the content above is the source of truth.**
39
+ > For more detail, call \`<tool>\` with refined parameters.`};async function M(e,t){let{pendingFiles:n,toolName:s,sync:l=false}=t;if(e.length===0)return F(s,"No matches found.","Try broader search terms, or use `explore` to read source.");let a=Je(e),c=new Set(a.keys()),i=[];i.push(v(n,c)??"");let d="[[codebase-search-summary]]";i.push(d+`
40
+ `);let r=e.length;i.push(`**Files with matches:** ${a.size}
41
+ `);for(let[m,p]of a){let f=p.map(x=>x.node.name),E=f.slice(0,5).join(", "),h=f.length>5?`, +${f.length-5} more`:"";i.push(`**\`${m}\`** \u2014 ${E}${h}
42
+ `);let I=p[0]?.node.language??"";i.push("```"+I);for(let x of p)i.push(`L${x.node.startLine} ${x.snippet}`);i.push("```\n");}i.push(D("search",s,{}));let o=i.join(`
43
+ `),u=`Found ${r} symbol${r===1?"":"s"} across ${a.size} file${a.size===1?"":"s"}.`,g=o.replace(d,u);return A(g,t,l)}async function H(e,t,n){let{pendingFiles:s,toolName:l,sync:a=false}=n;if(t.length===0||t.every(r=>r.count===0))return F(l,`No incoming edges for \`${e.name}\`.`,"This symbol has no callers \u2014 safe to refactor.");let c=t.reduce((r,o)=>r+o.count,0),i=Xe(c),d=[];d.push(v(s,new Set([e.filePath]))??""),d.push(`**Impact for \`${e.name}\`** (root: ${e.filePath}:${e.startLine}, total impacted: ${c})
44
+ `);for(let r of t){d.push(`- **d=${r.depth}** (${r.count} nodes) \u2014 ${r.riskLabel}`);for(let o of r.samples.slice(0,5))d.push(` - \`${o.name}\` ${o.file}:${o.line} [${o.relation}]`);r.samples.length>5&&d.push(` - ... and ${r.samples.length-5} more`);}return d.push(D("impact",l,{root:e.name,riskLevel:i})),A(d.join(`
45
+ `),n,a)}function Xe(e){return e>=100?"CRITICAL":e>=50?"HIGH":e>=10?"MEDIUM":"LOW"}function G(e){return e===1?"WILL BREAK (direct callers)":e===2?"LIKELY AFFECTED (indirect)":"MAY NEED TESTING (transitive)"}async function Q(e,t){let{root:n,incoming:s,outgoing:l,neighbors:a}=e,{pendingFiles:c,toolName:i,sync:d=false}=t;if(s.length===0&&l.length===0&&a.length===0)return F(i,`No relations found for \`${n.name}\`.`,"This is a leaf node.");let r=[];r.push(v(c,new Set([n.filePath]))??""),r.push(`**Context for \`${n.name}\`** (${n.astType}, ${n.language}, ${n.filePath}:${n.startLine})
46
+ `),r.push(`**Incoming** (${s.length}):`);for(let o of s.slice(0,10))r.push(`- ${o.source} \u2192 [${o.relation}] \u2192 \`${n.name}\``);s.length>10&&r.push(`- ... and ${s.length-10} more`),r.push(""),r.push(`**Outgoing** (${l.length}):`);for(let o of l.slice(0,10))r.push(`- \`${n.name}\` \u2192 [${o.relation}] \u2192 ${o.target}`);if(l.length>10&&r.push(`- ... and ${l.length-10} more`),r.push(""),a.length>0){r.push(`**Neighbors** (${a.length}):`);for(let o of a.slice(0,20))r.push(`- [d=${o.depth}] \`${o.node.name}\` (${o.node.astType}) ${o.node.filePath}:${o.node.startLine}`);a.length>20&&r.push(`- ... and ${a.length-20} more`),r.push("");}return r.push(D("context",i,{})),A(r.join(`
47
+ `),t,d)}async function q(e,t,n){let{pendingFiles:s,toolName:l,sync:a=false}=n;if(!e.id)return F(l,"Node not found.","Check the node ID or use `search` to find it.");let c=t.filter(r=>r.direction==="in"),i=t.filter(r=>r.direction==="out"),d=[];d.push(v(s,new Set([e.filePath]))??""),d.push(`**Node: \`${e.name}\`**
48
+ `),d.push(`- ID: \`${e.id}\``),d.push(`- Kind: ${e.astType}`),d.push(`- Language: ${e.language}`),d.push(`- Location: ${e.filePath}:${e.startLine}-${e.endLine}`),d.push(`- Exported: ${e.isExported}`),e.modifiers.length>0&&d.push(`- Modifiers: ${e.modifiers.join(", ")}`),d.push(""),d.push(`**Edges** (incoming: ${c.length} / outgoing: ${i.length}):`);for(let r of c.slice(0,5))d.push(`- \u2190 [${r.relation}] ${r.source}`);for(let r of i.slice(0,5))d.push(`- \u2192 [${r.relation}] ${r.target}`);return t.length>10&&d.push(`- ... and ${t.length-10} more`),d.push(D("default",l,{})),A(d.join(`
49
+ `),n,a)}async function B(e,t,n,s,l){let{toolName:a,sync:c=false}=l,i=n==="callers"?"Callers":"Callees",d="of",r=n==="callers"?"Use `node <name>` to read full source of any caller.":"Use `node <name>` to read full source of any callee.",o=t?.name??"?";if(e.length===0)return F(a,`**${i} ${d} \`${o}\`** (0)`,n==="callers"?"This symbol has no callers \u2014 safe to refactor.":"This symbol has no outgoing calls \u2014 leaf node.");let u=[];u.push(`**${i} ${d} \`${o}\`** (${e.length}${s?"+":""})
50
+ `);for(let g of e.slice(0,10)){let m=g.filePath==="(unresolved)",p=m?g.filePath:`${g.filePath}:${g.startLine}`,f=m?" _(wildcard)_":"";u.push(`- [${g.relation}] \`${g.name}\` ${p}${f}`);}return e.length>10&&u.push(`- ... and ${e.length-10} more`),u.push(`
51
+ ---
52
+ > ${r}`),A(u.join(`
53
+ `),l,c)}async function pe(e,t){let{entryPoints:n,totalHits:s,query:l}=e,{toolName:a,sync:c=false}=t;if(n.length===0)return F(a,`No matches for \`${l}\`.`,"Try broader search terms, or use `callers` / `callees` to traverse from a known symbol.");let i=[];i.push(`## Code Context
54
+ `),i.push(`**Query:** ${l} `),i.push(`**Total hits:** ${s} `),i.push(`**Entry points:** ${n.length}
55
+ `);for(let d of n){i.push(`**\`${d.file}\`** \u2014 ${d.symbols.length} symbol${d.symbols.length===1?"":"s"}
56
+ `);for(let r of d.symbols){let o=(r.source??"").trim()||"(source not included)",u=r.node.language;if(i.push("```"+u),i.push(`L${r.node.startLine}-L${r.node.endLine} ${r.node.name} (${r.node.astType}${r.node.modifiers.length>0?`, ${r.node.modifiers.join(" ")}`:""})`),i.push(""),i.push(o),i.push("```\n"),r.callers.length>0){i.push(`**Callers of \`${r.node.name}\` (${r.callers.length}):**`);for(let g of r.callers.slice(0,5))i.push(`- [${g.relation}] \`${g.name}\` ${g.filePath}:${g.startLine}`);r.callers.length>5&&i.push(`- ... and ${r.callers.length-5} more`),i.push("");}if(r.callees.length>0){i.push(`**Callees of \`${r.node.name}\` (${r.callees.length}):**`);for(let g of r.callees.slice(0,5))i.push(`- [${g.relation}] \`${g.name}\` ${g.filePath}:${g.startLine}`);r.callees.length>5&&i.push(`- ... and ${r.callees.length-5} more`),i.push("");}}}return i.push(`---
57
+ `),i.push(D("context",a,{})),A(i.join(`
58
+ `),t,c)}function Je(e){let t=new Map;for(let n of e){let s=n.node.filePath,l=t.get(s);l?l.push(n):t.set(s,[n]);}return t}function F(e,t,n){return `**${e}**
59
+
60
+ ${t}
61
+
62
+ > **Tip:** ${n}`}async function A(e,t,n){let s={softLimit:t.softLimit,hardCeiling:t.hardCeiling,toolName:t.toolName,writeToDisk:n?false:t.writeToDisk};return (n?k(e,s):await O(e,s)).content}var et=Log.create({service:"codebase.format.render"});async function tt(e,t){if(e.length===0)return M([],t);let n=K(e);return M(n,t)}async function nt(e,t,n){if(t.length===0)return H(R(e),[],n);let s=[{depth:1,count:t.length,riskLabel:G(1),samples:t.slice(0,10).map(l=>({name:l.source.name,file:R(l.source).filePath,line:l.source.start_line??0,relation:l.relation}))}];return H(R(e),s,n)}async function rt(e,t,n,s,l){let a=R(e),c=t.map(r=>w(r,"in")),i=n.map(r=>w(r,"out")),d=s.map(r=>({node:R(r),depth:1}));return Q({root:a,incoming:c,outgoing:i,neighbors:d},l)}async function ot(e,t){return B(e.callers,e.root,"callers",e.truncated,t)}async function st(e,t){return B(e.callees,e.root,"callees",e.truncated,t)}async function it(e,t){let{renderKnowledgeStatus:n}=await import('@easbot/terminal');return n({packageName:"codebase",rootDir:e.workspaceDir,configPath:e.configPath??"",configExists:typeof e.configExists=="boolean"?e.configExists:false,dbPath:e.dbPath,dbExists:typeof e.dbExists=="boolean"?e.dbExists:true,dbSize:e.dbSize,indexState:e.indexState,schemaVersion:(()=>{let s=e.meta?.schema_version;return s&&Number.isFinite(Number.parseInt(s,10))?Number.parseInt(s,10):void 0})(),extractionVersion:e.extractionVersion,lastSyncAt:e.lastSync,vectorEnabled:typeof e.vectorEnabled=="boolean"?e.vectorEnabled:false,embeddingDims:typeof e.embeddingDims=="number"?e.embeddingDims:void 0,llm:e.llm??{initialized:false,capabilities:{}},healthy:e.healthy,dbStats:e.dbStats,extras:(()=>{let s={};if(e.isStale===true&&(s.stale="yes \u2014 reindex recommended"),typeof e.ftsAvailable=="boolean"&&(s.fts_available=e.ftsAvailable?"yes":"no"),e.meta&&typeof e.meta=="object")for(let[l,a]of Object.entries(e.meta))a!=null&&(s[`meta/${l}`]=String(a));return Object.keys(s).length>0?s:void 0})()})}async function at(e,t,n){if(!e)return q(j(),[],n);let s=R(e),l=t.map(a=>{let c=a.target===e.id?"in":"out";return w(a,c)});return q(s,l,n)}async function lt(e,t){let n={query:e.query,totalHits:e.totalHits,entryPoints:e.entryPoints.map(s=>({file:s.file,symbols:s.symbols.map(l=>({node:R(l.node),source:l.node.text??"",callers:l.callers.map(a=>({name:a.name,filePath:a.filePath,startLine:a.startLine,relation:a.relation})),callees:l.callees.map(a=>({name:a.name,filePath:a.filePath,startLine:a.startLine,relation:a.relation}))}))}))};return pe(n,t)}et.debug("format/render.ts loaded");export{rt as A,ot as B,st as C,it as D,at as E,lt as F,oe as a,Le as b,$e as c,we as d,Fe as e,Ae as f,De as g,Oe as h,ke as i,qe as j,R as k,w as l,K as m,j as n,W as o,Ye as p,O as q,k as r,M as s,H as t,G as u,Q as v,q as w,B as x,tt as y,nt as z};
@@ -0,0 +1 @@
1
+ import d from'path';import {fileURLToPath}from'url';var s=Object.defineProperty;var f=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),l=e=>{throw TypeError(e)};var _=(e,t,o)=>t in e?s(e,t,{enumerable:true,configurable:true,writable:true,value:o}):e[t]=o;var u=(e,t,o)=>_(e,typeof t!="symbol"?t+"":t,o);var D=(e,t,o)=>{if(t!=null){typeof t!="object"&&typeof t!="function"&&l("Object expected");var r,i;o&&(r=t[f("asyncDispose")]),r===void 0&&(r=t[f("dispose")],o&&(i=r)),typeof r!="function"&&l("Object not disposable"),i&&(r=function(){try{i.call(this);}catch(n){return Promise.reject(n)}}),e.push([o,r,t]);}else o&&e.push([o]);return t},F=(e,t,o)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(m,c,a,p){return p=Error(a),p.name="SuppressedError",p.error=m,p.suppressed=c,p},i=m=>t=o?new r(m,t,"An error was suppressed during disposal"):(o=true,m),n=m=>{for(;m=e.pop();)try{var c=m[1]&&m[1].call(m[2]);if(m[0])return Promise.resolve(c).then(n,a=>(i(a),n()))}catch(a){i(a);}if(o)throw t};return n()};var h=()=>fileURLToPath(import.meta.url),x=()=>d.dirname(h()),T=x();export{u as a,D as b,F as c,T as d};