@easbot/codebase 0.3.16 → 0.3.19

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 (45) hide show
  1. package/README.en.md +100 -0
  2. package/README.md +109 -1
  3. package/dist/chunks/{chunk-P6QT72IP.mjs → chunk-22PKTMO5.mjs} +14 -14
  4. package/dist/chunks/chunk-AGZFRKQ4.mjs +188 -0
  5. package/dist/chunks/{chunk-W2JWBAHR.mjs → chunk-CSMSBVAG.mjs} +1 -1
  6. package/dist/chunks/chunk-GWCRGM4D.mjs +51 -0
  7. package/dist/chunks/{chunk-UTPNELRD.cjs → chunk-JWTI3BWI.cjs} +14 -14
  8. package/dist/chunks/{chunk-6ENRFRCH.cjs → chunk-R74KIJM2.cjs} +1 -1
  9. package/dist/chunks/chunk-TR3DFBJH.mjs +47 -0
  10. package/dist/chunks/chunk-VFTVDTEY.cjs +188 -0
  11. package/dist/chunks/chunk-VPWALTY7.cjs +51 -0
  12. package/dist/chunks/chunk-YYF5OQDS.cjs +47 -0
  13. package/dist/chunks/cli-handler-3I5JC3HY.cjs +1 -0
  14. package/dist/chunks/cli-handler-IJ2PNNTK.mjs +1 -0
  15. package/dist/chunks/code-base-6TM7JDJ6.cjs +1 -0
  16. package/dist/chunks/code-base-BSRUQYXN.mjs +1 -0
  17. package/dist/chunks/database-manager-26PY6VTD.mjs +1 -0
  18. package/dist/chunks/database-manager-U7D7QIHC.cjs +1 -0
  19. package/dist/chunks/llm-JQV6XWGD.cjs +1 -0
  20. package/dist/chunks/llm-MPD7FHPM.mjs +1 -0
  21. package/dist/chunks/{stdio-server-EQGSXAMO.cjs → stdio-server-2GBPZY6J.cjs} +6 -6
  22. package/dist/chunks/{stdio-server-OFN76NZA.mjs → stdio-server-BZYPM34X.mjs} +1 -1
  23. package/dist/cli.cjs +1 -1
  24. package/dist/cli.mjs +1 -1
  25. package/dist/index.cjs +1 -1
  26. package/dist/index.d.cts +62 -1
  27. package/dist/index.d.ts +62 -1
  28. package/dist/index.mjs +1 -1
  29. package/package.json +9 -8
  30. package/dist/chunks/chunk-6CD6Y4F7.cjs +0 -48
  31. package/dist/chunks/chunk-7XCIIOM6.cjs +0 -1
  32. package/dist/chunks/chunk-BUHCT5PM.mjs +0 -48
  33. package/dist/chunks/chunk-CS4EBN3N.mjs +0 -2
  34. package/dist/chunks/chunk-K5CRL5DC.cjs +0 -234
  35. package/dist/chunks/chunk-LFH3RTD3.mjs +0 -234
  36. package/dist/chunks/chunk-UTKA3WG3.mjs +0 -1
  37. package/dist/chunks/chunk-WSFETZ24.cjs +0 -2
  38. package/dist/chunks/cli-handler-IDMIMEKA.cjs +0 -1
  39. package/dist/chunks/cli-handler-ZLJJGHMV.mjs +0 -1
  40. package/dist/chunks/code-base-2TXG4VK3.mjs +0 -1
  41. package/dist/chunks/code-base-32T6G2FF.cjs +0 -1
  42. package/dist/chunks/database-manager-YEWLT7QF.mjs +0 -1
  43. package/dist/chunks/database-manager-YNQZSUVP.cjs +0 -1
  44. package/dist/chunks/sync-6CALMRLC.mjs +0 -1
  45. package/dist/chunks/sync-TICACY4G.cjs +0 -1
@@ -67,19 +67,19 @@
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 D(o,e=p,t={}){o.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
68
68
  id INTEGER PRIMARY KEY,
69
69
  applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
70
- )`);let s=o.prepare("SELECT id FROM schema_migrations").all(),r=new Set(s.map(a=>a.id)),n={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(a=>a.id)),targetVersion:e};for(let a of W){if(a.id>e)break;if(r.has(a.id)){n.pending.push(a.id);continue}if(t.dryRun){n.applied.push(a.id);continue}try{o.execBatch([...a.up]),o.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(a.id),r.add(a.id),n.applied.push(a.id),P.info("migration applied",{id:a.id,description:a.description});}catch(i){let c=i instanceof Error?i.message:String(i),T=a.up[0]??"";n.errors.push({migrationId:a.id,sql:T,error:c}),P.warn("migration step failed (may be idempotent)",{id:a.id,error:c,sqlCount:a.up.length});}}return n}function X(o){try{let e=o.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(t=>t.id))}catch{return 0}}var l=utils.Filesystem.toUnixPath,E=utils.Log.create({service:"codebase-database"}),m=2,H=class{constructor(e){chunkNVGACA7W_cjs.a(this,"db");chunkNVGACA7W_cjs.a(this,"dbPath");chunkNVGACA7W_cjs.a(this,"closed",false);chunkNVGACA7W_cjs.a(this,"ftsAvailable",false);this.dbPath=e===":memory:"?e:utils.Filesystem.normalize(e),this.db=database.createSyncSqliteConnection({path:this.dbPath,backend:"better-sqlite3",walMode:true,foreignKeys:true,busyTimeoutMs:5e3}),this.db.initialize();try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("foreign_keys = ON");}catch(t){E.warn("Failed to apply codebase PRAGMAs (synchronous / cache_size / foreign_keys)",{error:String(t)});}try{this.ensureSchema();let t=X(this.db);t>0&&this.setMeta("schema_version",String(t)),this.ftsAvailable=this.checkFtsAvailability(),this.detectAndMarkStaleOnInit();}catch(t){try{this.db.close();}catch{}throw this.closed=true,t}}ensureSchema(){try{D(this.db,p);let e=[["version","1.0.0"],["createdAt",new Date().toISOString()],["index_state","uninitialized"],["indexed_with_version","unknown"]],t=this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[s,r]of e)t.run(s,r);}catch(e){throw E.error("ensureSchema failed",{message:e instanceof Error?e.message:String(e),cause:e instanceof Error?e.cause:void 0,stack:e instanceof Error?e.stack:void 0}),new u("Failed to create database schema",e instanceof Error?[e.message]:[String(e)])}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:l(e.file_path)};this.db.prepare(`
70
+ )`);let s=o.prepare("SELECT id FROM schema_migrations").all(),r=new Set(s.map(a=>a.id)),n={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(a=>a.id)),targetVersion:e};for(let a of W){if(a.id>e)break;if(r.has(a.id)){n.pending.push(a.id);continue}if(t.dryRun){n.applied.push(a.id);continue}try{o.execBatch([...a.up]),o.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(a.id),r.add(a.id),n.applied.push(a.id),P.info("migration applied",{id:a.id,description:a.description});}catch(i){let l=i instanceof Error?i.message:String(i),T=a.up[0]??"";n.errors.push({migrationId:a.id,sql:T,error:l}),P.warn("migration step failed (may be idempotent)",{id:a.id,error:l,sqlCount:a.up.length});}}return n}function X(o){try{let e=o.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(t=>t.id))}catch{return 0}}var c=utils.Filesystem.toUnixPath,E=utils.Log.create({service:"codebase-database"}),m=2,H=class{constructor(e){chunkNVGACA7W_cjs.a(this,"db");chunkNVGACA7W_cjs.a(this,"dbPath");chunkNVGACA7W_cjs.a(this,"closed",false);chunkNVGACA7W_cjs.a(this,"ftsAvailable",false);this.dbPath=e===":memory:"?e:utils.Filesystem.normalize(e),this.db=database.createSyncSqliteConnection({path:this.dbPath,backend:"better-sqlite3",walMode:true,foreignKeys:true,busyTimeoutMs:5e3}),this.db.initialize();try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("foreign_keys = ON");}catch(t){E.warn("Failed to apply codebase PRAGMAs (synchronous / cache_size / foreign_keys)",{error:String(t)});}try{this.ensureSchema();let t=X(this.db);t>0&&this.setMeta("schema_version",String(t)),this.ftsAvailable=this.checkFtsAvailability(),this.detectAndMarkStaleOnInit();}catch(t){try{this.db.close();}catch{}throw this.closed=true,t}}ensureSchema(){try{D(this.db,p);let e=[["version","1.0.0"],["createdAt",new Date().toISOString()],["index_state","uninitialized"],["indexed_with_version","unknown"]],t=this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[s,r]of e)t.run(s,r);}catch(e){throw E.error("ensureSchema failed",{message:e instanceof Error?e.message:String(e),cause:e instanceof Error?e.cause:void 0,stack:e instanceof Error?e.stack:void 0}),new u("Failed to create database schema",e instanceof Error?[e.message]:[String(e)])}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:c(e.file_path)};this.db.prepare(`
71
71
  INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
72
72
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
73
- `).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(n=>({...n,file_path:l(n.file_path)})),s=this.db.prepare(`
73
+ `).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(n=>({...n,file_path:c(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(n=>{for(let a of n)s.run(a.id,a.name,a.ast_type,a.language,a.file_path,a.start_line,a.start_col,a.end_line,a.end_col,a.text,a.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(n);})(t);}updateFtsNodesInternal(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),r=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");for(let n of e)try{let a=s.get(n.id);a&&t.run(a.rowid),r.run(n.id,n.name,n.ast_type,n.language,n.file_path,n.text);}catch(a){E.warn("FTS update failed for node",{nodeId:n.id,error:String(a)});}}updateFtsNode(e){try{let t=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?").get(e.id);t&&this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(t.rowid),this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.ast_type,e.language,e.file_path,e.text);}catch(t){E.warn("FTS update failed for node",{nodeId:e.id,error:String(t)});}}updateFtsNodes(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),r=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");this.db.transaction(a=>{for(let i of a)try{let c=s.get(i.id);c&&t.run(c.rowid),r.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.text);}catch(c){E.warn("FTS update failed for node",{nodeId:i.id,error:String(c)});}})(e);}insertEdge(e){this.db.prepare(`
76
+ `);this.db.transaction(n=>{for(let a of n)s.run(a.id,a.name,a.ast_type,a.language,a.file_path,a.start_line,a.start_col,a.end_line,a.end_col,a.text,a.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(n);})(t);}updateFtsNodesInternal(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),r=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");for(let n of e)try{let a=s.get(n.id);a&&t.run(a.rowid),r.run(n.id,n.name,n.ast_type,n.language,n.file_path,n.text);}catch(a){E.warn("FTS update failed for node",{nodeId:n.id,error:String(a)});}}updateFtsNode(e){try{let t=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?").get(e.id);t&&this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(t.rowid),this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.ast_type,e.language,e.file_path,e.text);}catch(t){E.warn("FTS update failed for node",{nodeId:e.id,error:String(t)});}}updateFtsNodes(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),r=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");this.db.transaction(a=>{for(let i of a)try{let l=s.get(i.id);l&&t.run(l.rowid),r.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.text);}catch(l){E.warn("FTS update failed for node",{nodeId:i.id,error:String(l)});}})(e);}insertEdge(e){this.db.prepare(`
77
77
  INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
78
78
  VALUES (?, ?, ?, ?, ?)
79
79
  `).run(e.id,e.source,e.target,e.relation,e.created_at);}insertEdges(e){if(e.length===0)return;let t=this.db.prepare(`
80
80
  INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
81
81
  VALUES (?, ?, ?, ?, ?)
82
- `);this.db.transaction(r=>{for(let n of r)t.run(n.id,n.source,n.target,n.relation,n.created_at);})(e);}queryNodes(e){let t=[],s=[];e.filePath&&(t.push("file_path LIKE ?"),s.push(`%${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 g("Failed to query nodes","queryNodes",n instanceof Error?n:new Error(String(n)))}}queryEdges(e){let t=[],s=[];if(e.sourceOrTarget&&e.sourceOrTarget.length>0){let n=e.sourceOrTarget.map(()=>"?").join(",");t.push(`(source IN (${n}) OR target IN (${n}))`),s.push(...e.sourceOrTarget,...e.sourceOrTarget);}else e.source&&(t.push("source = ?"),s.push(e.source)),e.target&&(t.push("target = ?"),s.push(e.target));e.relation&&(t.push("relation = ?"),s.push(e.relation));let r="SELECT * FROM edges";t.length>0&&(r+=` WHERE ${t.join(" AND ")}`),r+=" ORDER BY created_at DESC",e.limit&&(r+=" LIMIT ?",s.push(e.limit)),e.offset&&(r+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(r).all(...s)}catch(n){throw new g("Failed to query edges","queryEdges",n instanceof Error?n:new Error(String(n)))}}queryAll(e,t){try{let s=this.db.prepare(e);return t?s.all(...t):s.all()}catch(s){throw new g("Failed to execute query","queryAll",s instanceof Error?s:new Error(String(s)))}}searchNodesFts(e,t=20){if(E.debug("searchNodesFts start",{query:e,limit:t,ftsAvailable:this.ftsAvailable}),!this.ftsAvailable)return E.debug("searchNodesFts skip - FTS not available"),[];try{let s=e.split(/\s+/).map(i=>`${i}*`).join(" ");E.debug("searchNodesFts query",{ftsQuery:s});let a=this.db.prepare(`
82
+ `);this.db.transaction(r=>{for(let n of r)t.run(n.id,n.source,n.target,n.relation,n.created_at);})(e);}queryNodes(e){let t=[],s=[];e.filePath&&(t.push("file_path LIKE ?"),s.push(`%${c(e.filePath)}%`)),e.astType&&(t.push("ast_type = ?"),s.push(e.astType)),e.name&&(t.push("name = ?"),s.push(e.name)),e.language&&(t.push("language = ?"),s.push(e.language));let r="SELECT * FROM nodes";t.length>0&&(r+=` WHERE ${t.join(" AND ")}`),r+=" ORDER BY file_path, start_line",e.limit&&(r+=" LIMIT ?",s.push(e.limit)),e.offset&&(r+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(r).all(...s)}catch(n){throw new g("Failed to query nodes","queryNodes",n instanceof Error?n:new Error(String(n)))}}queryEdges(e){let t=[],s=[];if(e.sourceOrTarget&&e.sourceOrTarget.length>0){let n=e.sourceOrTarget.map(()=>"?").join(",");t.push(`(source IN (${n}) OR target IN (${n}))`),s.push(...e.sourceOrTarget,...e.sourceOrTarget);}else e.source&&(t.push("source = ?"),s.push(e.source)),e.target&&(t.push("target = ?"),s.push(e.target));e.relation&&(t.push("relation = ?"),s.push(e.relation));let r="SELECT * FROM edges";t.length>0&&(r+=` WHERE ${t.join(" AND ")}`),r+=" ORDER BY created_at DESC",e.limit&&(r+=" LIMIT ?",s.push(e.limit)),e.offset&&(r+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(r).all(...s)}catch(n){throw new g("Failed to query edges","queryEdges",n instanceof Error?n:new Error(String(n)))}}queryAll(e,t){try{let s=this.db.prepare(e);return t?s.all(...t):s.all()}catch(s){throw new g("Failed to execute query","queryAll",s instanceof Error?s:new Error(String(s)))}}searchNodesFts(e,t=20){if(E.debug("searchNodesFts start",{query:e,limit:t,ftsAvailable:this.ftsAvailable}),!this.ftsAvailable)return E.debug("searchNodesFts skip - FTS not available"),[];try{let s=e.split(/\s+/).map(i=>`${i}*`).join(" ");E.debug("searchNodesFts query",{ftsQuery:s});let a=this.db.prepare(`
83
83
  SELECT
84
84
  nodes_fts.id,
85
85
  nodes_fts.name,
@@ -97,21 +97,21 @@
97
97
  WHERE nodes_fts.text MATCH ?
98
98
  ORDER BY score DESC
99
99
  LIMIT ?
100
- `).all(s,t);return E.debug("searchNodesFts done",{resultCount:a.length}),a}catch(s){return E.warn("searchNodesFts failed",{error:String(s)}),[]}}deleteNodesByFile(e){let t=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(`
100
+ `).all(s,t);return E.debug("searchNodesFts done",{resultCount:a.length}),a}catch(s){return E.warn("searchNodesFts failed",{error:String(s)}),[]}}deleteNodesByFile(e){let t=c(e);if(this.ftsAvailable)try{let r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let n of r)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(n.rowid);}catch(r){E.warn("FTS delete failed for file",{filePath:t,error:String(r)});}return this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t).changes}deleteEdgesByFile(e){let t=c(e);return this.db.prepare(`
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(l(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(c(e))?.content_hash??null}setFileHash(e,t){this.db.prepare(`
105
105
  INSERT OR REPLACE INTO file_hashes (file_path, content_hash, last_modified)
106
106
  VALUES (?, ?, ?)
107
- `).run(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=h=>this.db.prepare(h).get().c,t=h=>e(h),s={nodes:t("SELECT COUNT(*) as c FROM nodes"),edges:t("SELECT COUNT(*) as c FROM edges"),file_hashes:t("SELECT COUNT(*) as c FROM file_hashes"),fts:t("SELECT COUNT(*) as c FROM nodes_fts"),node_embeddings:t("SELECT COUNT(*) as c FROM node_embeddings"),embedding_cache:t("SELECT COUNT(*) as c FROM embedding_cache"),parse_errors:t("SELECT COUNT(*) as c FROM parse_errors"),unresolved_refs:t("SELECT COUNT(*) as c FROM unresolved_refs"),name_segment_vocab:t("SELECT COUNT(*) as c FROM name_segment_vocab"),project_metadata:t("SELECT COUNT(*) as c FROM project_metadata"),meta:t("SELECT COUNT(*) as c FROM meta")},r=[],n=t(`
107
+ `).run(c(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(c(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}checkIntegrity(){let e=h=>this.db.prepare(h).get().c,t=h=>e(h),s={nodes:t("SELECT COUNT(*) as c FROM nodes"),edges:t("SELECT COUNT(*) as c FROM edges"),file_hashes:t("SELECT COUNT(*) as c FROM file_hashes"),fts:t("SELECT COUNT(*) as c FROM nodes_fts"),node_embeddings:t("SELECT COUNT(*) as c FROM node_embeddings"),embedding_cache:t("SELECT COUNT(*) as c FROM embedding_cache"),parse_errors:t("SELECT COUNT(*) as c FROM parse_errors"),unresolved_refs:t("SELECT COUNT(*) as c FROM unresolved_refs"),name_segment_vocab:t("SELECT COUNT(*) as c FROM name_segment_vocab"),project_metadata:t("SELECT COUNT(*) as c FROM project_metadata"),meta:t("SELECT COUNT(*) as c FROM meta")},r=[],n=t(`
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
  `);n>0&&r.push({severity:"error",message:`orphan node_embeddings: ${n}`});let a=t(`
111
111
  SELECT COUNT(*) as c FROM edges e WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.source)
112
112
  `);a>0&&r.push({severity:"error",message:`orphan edges (source): ${a}`});let i=t(`
113
113
  SELECT COUNT(*) as c FROM edges e WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.target)
114
- `);i>0&&r.push({severity:"error",message:`orphan edges (target): ${i}`});let 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 f=t(`
114
+ `);i>0&&r.push({severity:"error",message:`orphan edges (target): ${i}`});let l=t("SELECT COUNT(*) as c FROM edges WHERE source = target");l>0&&r.push({severity:"error",message:`self-loop edges: ${l} \u2014 re-run \`easbot codebase sync\` to filter (fixed in Wave 4 R3-2)`});t("SELECT COUNT(DISTINCT file_path) as c FROM nodes");let f=t(`
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
117
  `);f>0&&r.push({severity:"warn",message:`orphan file_hashes (no nodes): ${f} \u2014 run \`easbot codebase sync\` to cleanup`});let _=t(`
@@ -128,7 +128,7 @@
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=l(e);return this.db.prepare(`
131
+ `).run(e,t);}deleteEmbeddingsByFile(e){let t=c(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)
@@ -136,19 +136,19 @@
136
136
  `);this.db.transaction(r=>{for(let n of r)try{t.run(n.nodeId,n.embeddingText,n.embedding);}catch(a){E.warn("Failed to store embedding for node",{nodeId:n.nodeId,error:String(a)});}})(e);}insertParseError(e){return this.db.prepare(`
137
137
  INSERT INTO parse_errors (file_path, language, stage, message, line)
138
138
  VALUES (?, ?, ?, ?, ?)
139
- `).run(e.filePath.replace(/\\/g,"/"),e.language,e.stage,e.message,e.line??null).changes}insertUnresolvedRef(e){return this.db.prepare(`
139
+ `).run(c(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,e.filePath.replace(/\\/g,"/"),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,c(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 i of e)r.push(i.fromNodeId??null,i.referenceName,i.referenceKind,i.line??null,i.col??null,i.filePath.replace(/\\/g,"/"),i.language,i.candidates?JSON.stringify(i.candidates):null);return this.db.prepare(s).run(...r).changes}insertNameSegment(e,t){return this.db.prepare(`
147
+ `,r=[];for(let i of e)r.push(i.fromNodeId??null,i.referenceName,i.referenceKind,i.line??null,i.col??null,c(i.filePath),i.language,i.candidates?JSON.stringify(i.candidates):null);return this.db.prepare(s).run(...r).changes}insertNameSegment(e,t){return this.db.prepare(`
148
148
  INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES (?, ?)
149
149
  `).run(e,t).changes}insertNameSegmentsBatch(e){if(e.length===0)return 0;let s=`
150
150
  INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES ${e.map(()=>"(?, ?)").join(", ")}
151
- `,r=[];for(let i of e)r.push(i.segment,i.name);return this.db.prepare(s).run(...r).changes}setProjectMetadata(e,t){return this.db.prepare(`
151
+ `,r=[];for(let i of e)r.push(i.segment,i.name);return this.db.prepare(s).run(...r).changes}setProjectMetadata(e,t){let s=e==="worktree"||e==="project"?c(t):t;return this.db.prepare(`
152
152
  INSERT OR REPLACE INTO project_metadata (key, value, updated_at)
153
153
  VALUES (?, ?, CURRENT_TIMESTAMP)
154
- `).run(e,t).changes}getNodeIdsByFile(e){let t=e.replace(/\\/g,"/");return this.db.prepare("SELECT id FROM nodes WHERE file_path = ?").all(t).map(r=>r.id)}deleteFtsByFile(e){let t=e.replace(/\\/g,"/"),s=this.getNodeIdsByFile(t);if(s.length===0)return 0;let r=this.db.prepare("DELETE FROM nodes_fts WHERE id = ?");return this.db.transaction(a=>{for(let i of a)r.run(i);})(s),s.length}initialize(){if(this.closed)throw new g("Cannot initialize closed database","initialize")}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){E.warn("Database close error",{error:String(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}deleteMeta(e){if(!this.db)throw new Error("Database not initialized");this.db.prepare("DELETE FROM meta WHERE key = ?").run(e);}};function te(o){return o.isClosed()}function se(o){return o.getDbPath()}function re(o,e){return o.transaction(e)}exports.a=F;exports.b=g;exports.c=M;exports.d=u;exports.e=A;exports.f=v;exports.g=x;exports.h=w;exports.i=p;exports.j=W;exports.k=D;exports.l=X;exports.m=m;exports.n=H;exports.o=te;exports.p=se;exports.q=re;
154
+ `).run(e,s).changes}getNodeIdsByFile(e){let t=e.replace(/\\/g,"/");return this.db.prepare("SELECT id FROM nodes WHERE file_path = ?").all(t).map(r=>r.id)}deleteFtsByFile(e){let t=e.replace(/\\/g,"/"),s=this.getNodeIdsByFile(t);if(s.length===0)return 0;let r=this.db.prepare("DELETE FROM nodes_fts WHERE id = ?");return this.db.transaction(a=>{for(let i of a)r.run(i);})(s),s.length}initialize(){if(this.closed)throw new g("Cannot initialize closed database","initialize")}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){E.warn("Database close error",{error:String(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}countSqliteObjects(){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT COUNT(*) as n FROM sqlite_master WHERE type IN ('table', 'index', 'trigger', 'view')").get()?.n??0}deleteMeta(e){if(!this.db)throw new Error("Database not initialized");this.db.prepare("DELETE FROM meta WHERE key = ?").run(e);}};function te(o){return o.isClosed()}function se(o){return o.getDbPath()}function re(o,e){return o.transaction(e)}exports.a=F;exports.b=g;exports.c=M;exports.d=u;exports.e=A;exports.f=v;exports.g=x;exports.h=w;exports.i=p;exports.j=W;exports.k=D;exports.l=X;exports.m=m;exports.n=H;exports.o=te;exports.p=se;exports.q=re;
@@ -1,4 +1,4 @@
1
- 'use strict';var chunkK5CRL5DC_cjs=require('./chunk-K5CRL5DC.cjs'),chunk7XCIIOM6_cjs=require('./chunk-7XCIIOM6.cjs'),chunkNVGACA7W_cjs=require('./chunk-NVGACA7W.cjs'),utils=require('@easbot/utils'),types=require('@easbot/types');var R=class extends Error{constructor(n,l,a){super(n);chunkNVGACA7W_cjs.a(this,"code",l);chunkNVGACA7W_cjs.a(this,"details",a);this.name="ServiceError";}},P=class extends R{constructor(t,n=[]){super(`Node not found: ${t}`,"NOT_FOUND",{name:t,candidates:n});}},L=class extends R{constructor(t,n){super(`Ambiguous name "${t}" \u2014 ${n.length} candidates`,"AMBIGUOUS",{name:t,candidates:n});}};utils.Log.create({service:"codebase-service"});var E=utils.Filesystem.toUnixPath;async function O(e,t,n){if(n.nodeId){let o=e.getNode(n.nodeId);if(!o)throw new P(`nodeId=${n.nodeId}`);return {node:o,candidates:[]}}if(!n.name)throw new R("Either name or nodeId is required","NOT_FOUND",n);let a=e.queryNodes({limit:5e3});if(n.file){let o=E(n.file),r=a.filter(d=>E(d.file_path).endsWith(o)||E(d.file_path).includes(o));r.length>0&&(a=r);}if(n.kind){let o=n.kind.toLowerCase(),r=a.filter(d=>d.ast_type.includes(o));r.length>0&&(a=r);}let i=a.find(o=>o.name===n.name||o.id.split(":").pop()===n.name);if(i)return {node:i,candidates:[]};let c=chunkK5CRL5DC_cjs.l(n.name,a,{limit:10,minScore:.5});if(c.length===0)throw new P(n.name);if(c.length===1){let o=e.getNode(c[0].nodeId);if(!o)throw new P(n.name);return {node:o,candidates:c.map(r=>({node:o,score:r.score}))}}let s=[];for(let o of c){let r=e.getNode(o.nodeId);r&&s.push({node:r,score:o.score});}throw s.length===0?new P(n.name):new L(n.name,s)}async function S(e){let t=chunk7XCIIOM6_cjs.c(e.rootDir),n=new chunkK5CRL5DC_cjs.o({workspaceDir:e.workspaceDir,database:{path:t,walMode:true},embedding:types.DEFAULT_EMBEDDING_CONFIG,indexer:types.DEFAULT_INDEXER_CONFIG,parser:types.DEFAULT_PARSER_CONFIG,search:types.DEFAULT_SEARCH_CONFIG,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});return await n.initialize(),n}function ue(e,t,n,l){let a=l==="in"?e.source:e.target,i=n.getNodeById(a);return i?{id:i.id,name:i.name,astType:i.ast_type,filePath:E(i.file_path),startLine:i.start_line??0,relation:e.relation}:null}async function V(e,t){let n=Date.now(),c=await(await S(e)).getQuery().search(t.query??"",{maxResults:t.maxResults??10,language:t.language,filePath:t.file,astType:t.astType,includeEdges:true,enableFts:t.enableFts!==false,enableEmbedding:t.enableEmbedding!==false});if(t.kind){let o=t.kind.toLowerCase();c=c.filter(r=>r.ast_type.includes(o)||r.name.toLowerCase().includes(o));}if(t.file){let o=E(t.file);c=c.filter(r=>E(r.file_path).endsWith(o)||E(r.file_path).includes(o));}let s=c.map(o=>({nodeId:o.id,name:o.name,kind:o.ast_type??"unknown",filePath:E(o.file_path),startLine:o.start_line,endLine:o.end_line,edges:o.edges??[],source:"basic",score:0,snippet:(o.text??"").slice(0,200).replace(/\s+/g," ").trim()}));return {total:s.length,hits:s,durationMs:Date.now()-n,truncated:false}}async function pe(e,t){let n=await S(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await O(l,e,t),c=[];if(t.includeEdges){let s=t.edgesLimit??50;c=a.queryEdges({sourceOrTarget:[i.id],limit:s});}return {node:i,edges:c}}var me=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"];async function ge(e,t){let n=await S(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await O(l,e,t);if(!i)return {root:null,nodes:[],edges:[],truncated:false,totalNodes:0,totalEdges:0};let c=t.depth??2,s=t.maxNodes??100,o=t.direction??"both",r=new Map,d=[{nodeId:i.id,depth:0}];r.set(i.id,0);let p=[],u=false;for(;d.length>0;){let g=d.shift();if(g.depth>=c)continue;if(r.size>=s){u=true;break}let h=l.queryNeighbors(g.nodeId,{direction:o,relationTypes:t.relationTypes??me,limit:s-r.size+1});for(let y of h.edges){p.push(y);let T=y.source===g.nodeId?y.target:y.source;if(!r.has(T)&&(r.set(T,g.depth+1),d.push({nodeId:T,depth:g.depth+1}),r.size>=s)){u=true;break}}if(u)break}let m=Array.from(r.keys()),b=m.length>0?a.queryNodes({ids:m}):[],f=new Map(b.map(g=>[g.id,g])),x=[];for(let[g,h]of r.entries()){let y=f.get(g);y&&x.push({node:y,depth:h});}return {root:i,nodes:x,edges:p,truncated:u,totalNodes:x.length,totalEdges:p.length}}var fe=["CALLS","IMPORTS","TYPE_REFERENCES"];async function he(e,t){let n=await S(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await O(l,e,t);if(!i)return {root:null,totalImpacted:0,buckets:[]};let c=t.depth??2,s=t.maxResults??50,o=t.relationTypes??fe,r=new Set([i.id]),d=[],p=[i.id];for(let u=1;u<=c&&!(p.length===0||r.size-1>=s);u++){let m=p.map(()=>"?").join(","),b=o.map(()=>"?").join(","),f=a.queryAll(`SELECT source, target, relation FROM edges WHERE target IN (${m}) AND relation IN (${b})`,[...p,...o]),x=[],g=new Set;for(let h of f)if(!r.has(h.source)&&!g.has(h.source)&&(g.add(h.source),r.add(h.source),x.push(h.source),r.size-1>=s))break;if(x.length>0){let h=x.slice(0,10),y=a.queryNodes({ids:h}),T=new Map(y.map($=>[$.id,$])),oe=h.map($=>{let B=T.get($);return {id:$,name:B?.name??"(unknown)",filePath:B?E(B.file_path):"(unknown)",relation:"CALLS"}});d.push({depth:u,count:x.length,sample:oe});}p=x;}return {root:i,totalImpacted:r.size-1,buckets:d}}var ye=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","METHOD_OVERRIDES"];async function be(e,t){return A(e,t,"incoming")}async function xe(e,t){return A(e,t,"outgoing")}async function A(e,t,n,l){let a=await S(e),i=a.getQuery(),c=a.getDatabase(),{node:s}=await O(i,e,t);if(!s)return {root:null,callers:[],truncated:false};let o=t.maxResults??20,r=t.relationTypes??ye,d=i.queryNeighbors(s.id,{direction:n,relationTypes:r,limit:o+1}),p=[];for(let m of d.edges){let b=ue(m,s.id,c,n==="incoming"?"in":"out");b&&p.push(b);}let u=p.length>o;return {root:s,callers:u?p.slice(0,o):p,truncated:u}}async function Ee(e,t){if(!t.query)throw new R("explore requires a non-empty query","NOT_FOUND",{query:t.query});let l=await S(e);l.getQuery();l.getDatabase();let s=(await V(e,{query:t.query,file:t.file,kind:t.kind,intent:t.intent,maxResults:t.maxFiles??5,enableFts:true,enableEmbedding:true})).hits,o=new Map;for(let p of s){let u=E(p.filePath),m=o.get(u);m?m.push(p):o.set(u,[p]);}let r=t.maxSymbols??3,d=[];for(let[p,u]of o){let m=u.slice(0,r),b=[];for(let f of m){let x=await A(e,{name:f.name,file:p,kind:t.kind,maxResults:5},"incoming"),g=await A(e,{name:f.name,file:p,kind:t.kind,maxResults:5},"outgoing");b.push({node:{id:f.nodeId,name:f.name,ast_type:f.kind,language:"ts",file_path:f.filePath,start_line:f.startLine??0,end_line:f.endLine??0,text:""},callers:x.callers,callees:g.callers});}d.push({file:p,symbols:b});}return {query:t.query,entryPoints:d,totalHits:s.length}}async function Ne(e,t){return await(await S(e)).getStatus()}async function Re(e,t){return await(await S(e)).healthCheck()}var J=utils.Filesystem.toUnixPath;function Se(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 Ce(e){let t=e.text??"";if(!t)return [];let n=t.slice(0,80),l=[];return /\basync\s/.test(n)&&l.push("async"),/\bstatic\s/.test(n)&&l.push("static"),/\babstract\s/.test(n)&&l.push("abstract"),/\breadonly\s/.test(n)&&l.push("readonly"),/\bconst\s/.test(n)&&l.push("const"),/\blet\s/.test(n)&&l.push("let"),l}function N(e){return {id:e.id,name:e.name,astType:e.ast_type,language:e.language,filePath:J(e.file_path),startLine:e.start_line??0,endLine:e.end_line??0,isExported:Se(e),modifiers:Ce(e)}}function I(e,t){return {id:e.id,source:e.source,target:e.target,relation:e.relation,direction:t}}function G(e){return e.map(t=>({node:{id:t.nodeId,name:t.name,astType:t.kind,language:"typescript",filePath:J(t.filePath),startLine:t.startLine??0,endLine:t.endLine??0,isExported:false,modifiers:[]},source:t.source,score:t.score,snippet:(t.snippet??"").slice(0,200),edges:(t.edges??[]).slice(0,10).map(n=>I({...n}))}))}function K(){return {id:"",name:"",astType:"",language:"",filePath:"",startLine:0,endLine:0,isExported:false,modifiers:[]}}var Te=utils.Log.create({service:"codebase-format-truncate"}),j="**`",$e="**",ee=24e3,te=25e3;async function _(e,t={}){let n=t.softLimit??ee,l=t.hardCeiling??te,a=t.toolName??"codebase",i=t.writeToDisk!==false;if(e.length<=n)return {content:e,truncated:false};let c=e.slice(0,l),s=c.lastIndexOf(`
1
+ 'use strict';var chunkVFTVDTEY_cjs=require('./chunk-VFTVDTEY.cjs'),chunkNVGACA7W_cjs=require('./chunk-NVGACA7W.cjs'),utils=require('@easbot/utils'),types=require('@easbot/types');var R=class extends Error{constructor(n,l,a){super(n);chunkNVGACA7W_cjs.a(this,"code",l);chunkNVGACA7W_cjs.a(this,"details",a);this.name="ServiceError";}},P=class extends R{constructor(t,n=[]){super(`Node not found: ${t}`,"NOT_FOUND",{name:t,candidates:n});}},L=class extends R{constructor(t,n){super(`Ambiguous name "${t}" \u2014 ${n.length} candidates`,"AMBIGUOUS",{name:t,candidates:n});}};utils.Log.create({service:"codebase-service"});var E=utils.Filesystem.toUnixPath;async function O(e,t,n){if(n.nodeId){let o=e.getNode(n.nodeId);if(!o)throw new P(`nodeId=${n.nodeId}`);return {node:o,candidates:[]}}if(!n.name)throw new R("Either name or nodeId is required","NOT_FOUND",n);let a=e.queryNodes({limit:5e3});if(n.file){let o=E(n.file),r=a.filter(d=>E(d.file_path).endsWith(o)||E(d.file_path).includes(o));r.length>0&&(a=r);}if(n.kind){let o=n.kind.toLowerCase(),r=a.filter(d=>d.ast_type.includes(o));r.length>0&&(a=r);}let i=a.find(o=>o.name===n.name||o.id.split(":").pop()===n.name);if(i)return {node:i,candidates:[]};let c=chunkVFTVDTEY_cjs.p(n.name,a,{limit:10,minScore:.5});if(c.length===0)throw new P(n.name);if(c.length===1){let o=e.getNode(c[0].nodeId);if(!o)throw new P(n.name);return {node:o,candidates:c.map(r=>({node:o,score:r.score}))}}let s=[];for(let o of c){let r=e.getNode(o.nodeId);r&&s.push({node:r,score:o.score});}throw s.length===0?new P(n.name):new L(n.name,s)}async function S(e){let t=chunkVFTVDTEY_cjs.c(e.rootDir),n=new chunkVFTVDTEY_cjs.s({workspaceDir:e.workspaceDir,database:{path:t,walMode:true},embedding:types.DEFAULT_EMBEDDING_CONFIG,indexer:types.DEFAULT_INDEXER_CONFIG,parser:types.DEFAULT_PARSER_CONFIG,search:types.DEFAULT_SEARCH_CONFIG,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});return await n.initialize(),n}function ue(e,t,n,l){let a=l==="in"?e.source:e.target,i=n.getNodeById(a);return i?{id:i.id,name:i.name,astType:i.ast_type,filePath:E(i.file_path),startLine:i.start_line??0,relation:e.relation}:null}async function V(e,t){let n=Date.now(),c=await(await S(e)).getQuery().search(t.query??"",{maxResults:t.maxResults??10,language:t.language,filePath:t.file,astType:t.astType,includeEdges:true,enableFts:t.enableFts!==false,enableEmbedding:t.enableEmbedding!==false});if(t.kind){let o=t.kind.toLowerCase();c=c.filter(r=>r.ast_type.includes(o)||r.name.toLowerCase().includes(o));}if(t.file){let o=E(t.file);c=c.filter(r=>E(r.file_path).endsWith(o)||E(r.file_path).includes(o));}let s=c.map(o=>({nodeId:o.id,name:o.name,kind:o.ast_type??"unknown",filePath:E(o.file_path),startLine:o.start_line,endLine:o.end_line,edges:o.edges??[],source:"basic",score:0,snippet:(o.text??"").slice(0,200).replace(/\s+/g," ").trim()}));return {total:s.length,hits:s,durationMs:Date.now()-n,truncated:false}}async function pe(e,t){let n=await S(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await O(l,e,t),c=[];if(t.includeEdges){let s=t.edgesLimit??50;c=a.queryEdges({sourceOrTarget:[i.id],limit:s});}return {node:i,edges:c}}var me=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"];async function ge(e,t){let n=await S(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await O(l,e,t);if(!i)return {root:null,nodes:[],edges:[],truncated:false,totalNodes:0,totalEdges:0};let c=t.depth??2,s=t.maxNodes??100,o=t.direction??"both",r=new Map,d=[{nodeId:i.id,depth:0}];r.set(i.id,0);let p=[],u=false;for(;d.length>0;){let g=d.shift();if(g.depth>=c)continue;if(r.size>=s){u=true;break}let h=l.queryNeighbors(g.nodeId,{direction:o,relationTypes:t.relationTypes??me,limit:s-r.size+1});for(let y of h.edges){p.push(y);let T=y.source===g.nodeId?y.target:y.source;if(!r.has(T)&&(r.set(T,g.depth+1),d.push({nodeId:T,depth:g.depth+1}),r.size>=s)){u=true;break}}if(u)break}let m=Array.from(r.keys()),b=m.length>0?a.queryNodes({ids:m}):[],f=new Map(b.map(g=>[g.id,g])),x=[];for(let[g,h]of r.entries()){let y=f.get(g);y&&x.push({node:y,depth:h});}return {root:i,nodes:x,edges:p,truncated:u,totalNodes:x.length,totalEdges:p.length}}var fe=["CALLS","IMPORTS","TYPE_REFERENCES"];async function he(e,t){let n=await S(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await O(l,e,t);if(!i)return {root:null,totalImpacted:0,buckets:[]};let c=t.depth??2,s=t.maxResults??50,o=t.relationTypes??fe,r=new Set([i.id]),d=[],p=[i.id];for(let u=1;u<=c&&!(p.length===0||r.size-1>=s);u++){let m=p.map(()=>"?").join(","),b=o.map(()=>"?").join(","),f=a.queryAll(`SELECT source, target, relation FROM edges WHERE target IN (${m}) AND relation IN (${b})`,[...p,...o]),x=[],g=new Set;for(let h of f)if(!r.has(h.source)&&!g.has(h.source)&&(g.add(h.source),r.add(h.source),x.push(h.source),r.size-1>=s))break;if(x.length>0){let h=x.slice(0,10),y=a.queryNodes({ids:h}),T=new Map(y.map($=>[$.id,$])),oe=h.map($=>{let B=T.get($);return {id:$,name:B?.name??"(unknown)",filePath:B?E(B.file_path):"(unknown)",relation:"CALLS"}});d.push({depth:u,count:x.length,sample:oe});}p=x;}return {root:i,totalImpacted:r.size-1,buckets:d}}var ye=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","METHOD_OVERRIDES"];async function be(e,t){return A(e,t,"incoming")}async function xe(e,t){return A(e,t,"outgoing")}async function A(e,t,n,l){let a=await S(e),i=a.getQuery(),c=a.getDatabase(),{node:s}=await O(i,e,t);if(!s)return {root:null,callers:[],truncated:false};let o=t.maxResults??20,r=t.relationTypes??ye,d=i.queryNeighbors(s.id,{direction:n,relationTypes:r,limit:o+1}),p=[];for(let m of d.edges){let b=ue(m,s.id,c,n==="incoming"?"in":"out");b&&p.push(b);}let u=p.length>o;return {root:s,callers:u?p.slice(0,o):p,truncated:u}}async function Ee(e,t){if(!t.query)throw new R("explore requires a non-empty query","NOT_FOUND",{query:t.query});let l=await S(e);l.getQuery();l.getDatabase();let s=(await V(e,{query:t.query,file:t.file,kind:t.kind,intent:t.intent,maxResults:t.maxFiles??5,enableFts:true,enableEmbedding:true})).hits,o=new Map;for(let p of s){let u=E(p.filePath),m=o.get(u);m?m.push(p):o.set(u,[p]);}let r=t.maxSymbols??3,d=[];for(let[p,u]of o){let m=u.slice(0,r),b=[];for(let f of m){let x=await A(e,{name:f.name,file:p,kind:t.kind,maxResults:5},"incoming"),g=await A(e,{name:f.name,file:p,kind:t.kind,maxResults:5},"outgoing");b.push({node:{id:f.nodeId,name:f.name,ast_type:f.kind,language:"ts",file_path:f.filePath,start_line:f.startLine??0,end_line:f.endLine??0,text:""},callers:x.callers,callees:g.callers});}d.push({file:p,symbols:b});}return {query:t.query,entryPoints:d,totalHits:s.length}}async function Ne(e,t){return await(await S(e)).getStatus()}async function Re(e,t){return await(await S(e)).healthCheck()}var J=utils.Filesystem.toUnixPath;function Se(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 Ce(e){let t=e.text??"";if(!t)return [];let n=t.slice(0,80),l=[];return /\basync\s/.test(n)&&l.push("async"),/\bstatic\s/.test(n)&&l.push("static"),/\babstract\s/.test(n)&&l.push("abstract"),/\breadonly\s/.test(n)&&l.push("readonly"),/\bconst\s/.test(n)&&l.push("const"),/\blet\s/.test(n)&&l.push("let"),l}function N(e){return {id:e.id,name:e.name,astType:e.ast_type,language:e.language,filePath:J(e.file_path),startLine:e.start_line??0,endLine:e.end_line??0,isExported:Se(e),modifiers:Ce(e)}}function I(e,t){return {id:e.id,source:e.source,target:e.target,relation:e.relation,direction:t}}function G(e){return e.map(t=>({node:{id:t.nodeId,name:t.name,astType:t.kind,language:"typescript",filePath:J(t.filePath),startLine:t.startLine??0,endLine:t.endLine??0,isExported:false,modifiers:[]},source:t.source,score:t.score,snippet:(t.snippet??"").slice(0,200),edges:(t.edges??[]).slice(0,10).map(n=>I({...n}))}))}function K(){return {id:"",name:"",astType:"",language:"",filePath:"",startLine:0,endLine:0,isExported:false,modifiers:[]}}var Te=utils.Log.create({service:"codebase-format-truncate"}),j="**`",$e="**",ee=24e3,te=25e3;async function _(e,t={}){let n=t.softLimit??ee,l=t.hardCeiling??te,a=t.toolName??"codebase",i=t.writeToDisk!==false;if(e.length<=n)return {content:e,truncated:false};let c=e.slice(0,l),s=c.lastIndexOf(`
2
2
  ${j}`),o=c.lastIndexOf(`
3
3
  `),r;s>l*.5?r=s:o>0?r=o:r=-1;let d=r>0?c.slice(0,r):c,u=d+"\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(!i)return {content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-d.length}/${e.length} characters truncated ...`};try{let m=await utils.TruncateContent.truncate(e,{maxChars:d.length,direction:"head",label:`${a}-output`});return m.truncated?{content:u,truncated:!0,outputPath:m.outputPath,hint:utils.TruncateContent.formatHint(m),info:`... ${m.removedLength}/${m.originalLength} characters truncated ...`}:{content:u,truncated:!0,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-d.length}/${e.length} characters truncated ...`}}catch(m){return Te.warn("TruncateContent.truncate failed, returning without disk hint",{error:m instanceof Error?m.message:String(m)}),{content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-d.length}/${e.length} characters truncated ...`}}}function D(e,t={}){let n=t.softLimit??ee,l=t.hardCeiling??te;if(e.length<=n)return {content:e,truncated:false};let a=e.slice(0,l),i=a.lastIndexOf(`
4
4
  ${j}`),c=a.lastIndexOf(`
@@ -0,0 +1,47 @@
1
+ import {l}from'./chunk-34CU2EU4.mjs';import {c,e,a as a$1,d}from'./chunk-WXWENWCY.mjs';import {j,D,i,h,e as e$1}from'./chunk-CSMSBVAG.mjs';import {a,c as c$1,b,e as e$2,d as d$1}from'./chunk-AGZFRKQ4.mjs';import {j as j$1,m,k,i as i$1,l as l$1,n}from'./chunk-22PKTMO5.mjs';import {a as a$2}from'./chunk-GWCRGM4D.mjs';import {existsSync,readFileSync,copyFileSync,mkdirSync,rmSync,statSync,writeFileSync}from'fs';import {isAbsolute,join,dirname}from'path';import {readFile}from'fs/promises';import {probeEmbeddingDims,syncMeta}from'@easbot/llm';import {createRequire}from'module';import {EMBEDDING_DIMS_CONSISTENCY_CHECK}from'@easbot/types';import {emitJsonOk,printHuman,formatKnowledgeDoctor,formatKnowledgeStatus,formatKnowledgeInit,registerActiveProgressLine,clearActiveProgressLine,unregisterActiveProgressLine}from'@easbot/terminal';import {Log,resolveLocaleLang}from'@easbot/utils';import {fileURLToPath}from'url';import {ServerTransportType}from'@easbot/mcp';function ye(o){let t={},n=[];for(let e of o)e==="--force"||e==="-f"?t.force=true:e==="--help"||e==="-h"?t.help=true:e==="--json"?t.json=true:e.startsWith("-")||n.push(e);return t.dir=n[0],t}async function I(o){let t=o.dir&&isAbsolute(o.dir)?o.dir:join(l(),o.dir??".");try{let u=await e$2(),{Log:l}=await import('@easbot/utils'),E=l.create({service:"codebase.init"});u.source==="monorepo"?E.debug("better-sqlite3 resolved (monorepo)",{path:u.absolutePath}):E.info("better-sqlite3 auto-installed to cache",{source:u.source,path:u.absolutePath});}catch(u){let{Log:l}=await import('@easbot/utils');l.create({service:"codebase.init"}).warn("better-sqlite3 resolve / install failed; index/sync/mcp may still fail later",{error:u instanceof Error?u.message:String(u),hint:"Run `npm i -g better-sqlite3` then retry, or set EASBOT_CACHE_PATH to a writable directory before running `easbot codebase init`."});}let n$1=a(t),e=b(t),s=c$1(t);if(existsSync(e)&&!o.force)return {configPath:e,dbPath:s,created:false,skipped:true,backend:"better-sqlite3",schemaVersion:i$1,migrationsApplied:0,tablesCreated:0,durationMs:0};existsSync(n$1)||mkdirSync(n$1,{recursive:true});let a$1={version:1,schema_version:i$1,extraction_version:m,backend:"better-sqlite3",created_at:new Date().toISOString()};if(writeFileSync(e,JSON.stringify(a$1,null,2),"utf-8"),o.force)try{rmSync(s,{force:!0});}catch{}d$1(t);let i=false,r=0,c=0,b$1=Date.now(),p=new n(s);try{let u=p.getMeta("index_state"),l=p.getMeta("createdAt"),E=p.getMeta("version"),d=p.getMeta("indexed_with_version");i=u!==null&&l!==null&&E!==null&&d!==null;try{r=p.countSqliteObjects();}catch{}let m=p.getMeta("schema_version");c=m?Number.parseInt(m,10)||i$1:i$1;}finally{p.close();}let f=Date.now()-b$1;return {configPath:e,dbPath:s,created:true,skipped:false,metaInitialized:i,backend:"better-sqlite3",schemaVersion:i$1,migrationsApplied:c,tablesCreated:r,durationMs:f}}async function z(o){let t=o.dir&&isAbsolute(o.dir)?o.dir:join(l(),o.dir??"."),e=b(t),s=c$1(t),a=existsSync(e),i=existsSync(s),r;if(i)try{r=statSync(s).size;}catch{}let c={initialized:false,capabilities:{embedding:false,graphLlm:false}},b$1={},p={},f,u,l$1,E=0,d=0,m,S,g,y=false,h;if(a)try{let w=JSON.parse(await readFile(e,"utf-8"));f=w.index_state,S=w.schema_version,u=w.extraction_version,m=w.backend;}catch{}if(i&&s)try{let{DatabaseManager:w}=await import('./database-manager-26PY6VTD.mjs'),T=new w(s);try{let R=T.getStatus();f=R.indexState??f,u=R.extractionVersion??u,l$1=R.isStale,E=R.nodeCount,d=R.edgeCount,b$1.nodes=R.nodeCount,b$1.edges=R.edgeCount,b$1.files=R.indexedFiles;for(let[A,io]of Object.entries(R.meta))p[A]=io;h=R.meta.lastSyncAt,S=parseInt(R.meta.schema_version??"",10)||S,m=R.meta.backend??m,y=R.meta.vector_enabled==="true"||R.meta.vector_enabled==="1",g=parseInt(R.meta.embeddingDims??"",10)||void 0;}finally{T.close();}}catch{}let C=a$2.isInitialized();if(C){c.initialized=true;let w=a$2.capabilities();c.capabilities={embedding:w.embedding===true,graphLlm:w.graphLlm===true},c.embeddingModel=c.capabilities.embedding?"configured":void 0,c.graphModel=c.capabilities.graphLlm?"configured":void 0;}if(C&&c.capabilities.embedding&&s)try{let w=a$2.getEmbeddingLlm();if(w){let T=await probeEmbeddingDims(w,{timeoutMs:5e3});if(typeof T=="number"){g=T;try{let{DatabaseManager:R}=await import('./database-manager-26PY6VTD.mjs'),A=new R(s);try{syncMeta(A,[["embeddingDims",String(T)]]);}finally{A.close();}}catch{}}}}catch{}let k=i&&a&&!l$1&&f!=="failed"&&f!=="stale",D;return a?i?f==="failed"?D="Last sync failed \u2014 run `easbot codebase index` to retry.":l$1?D="Index is stale (extraction version mismatch) \u2014 run `easbot codebase recreate` to rebuild.":f==="uninitialized"?D="Config exists but index never built \u2014 run `easbot codebase index` to populate.":f==="partial"&&(D="Last sync partially succeeded \u2014 re-run `easbot codebase index` to fill missing files."):D="Run `easbot codebase index` to build the index.":D="Run `easbot codebase init` to initialize the configuration.",{package:"codebase",rootDir:t,dbPath:s,dbSize:r,configPath:e,configExists:a,schemaVersion:S,extractionVersion:u,lastSyncAt:h,indexState:f,vectorEnabled:y,embeddingDims:g,llm:c,backend:m,counts:b$1,meta:p,recommendation:D,healthy:k,dbExists:i,nodeCount:E,edgeCount:d}}var F=()=>Date.now();async function Se(o){let t=F(),n=await z({dir:o.dir}),e=[],s,a=F(),i;if(n.dbExists?n.configExists?i=O("database","ok",`db readable at ${n.dbPath}`,Date.now()-a):i=O("database","warn","config not found \u2014 run `easbot codebase init` first",Date.now()-a):i=O("database","info","db not initialized \u2014 run `easbot codebase index` to build",Date.now()-a),e.push(i),n.dbExists){let d=F();e.push(O("fts","ok","fts sync checked in integrity pass",Date.now()-d));}if(n.dbExists){let d=F();e.push(O("vector",n.vectorEnabled?"ok":"info",n.vectorEnabled?`vector index enabled (dims=${n.embeddingDims??"unknown"})`:"vector index disabled (set config.vector.enabled to enable)",Date.now()-d));}if(n.dbExists){let d=F();e.push(O("schema",n.isStale===true?"warn":"ok",n.isStale===true?`extraction_version mismatch (current=${n.extractionVersion??0})`:`schema_version=${n.schemaVersion??"unknown"}`,Date.now()-d));}e.push(O("lock","ok","no lock contention observed",0)),e.push(O("disk_space","ok","no disk space check (v0.5.1 placeholder)",0));let r=F(),c={"better-sqlite3":false,"node:sqlite":false,"@tursodatabase/database":false},b=createRequire(import.meta.url);try{b.resolve("better-sqlite3"),c["better-sqlite3"]=!0;}catch{}c["node:sqlite"]=typeof process.versions.sqlite=="string";try{b.resolve("@tursodatabase/database"),c["@tursodatabase/database"]=!0;}catch{}let p="ok",f=`backend available: ${n.backend??"unknown"}`;!c["better-sqlite3"]&&!c["node:sqlite"]?(p="error",f="no SQLite backend available (install better-sqlite3 or use Node 22.5+)"):n.configExists&&n.backend&&!c[n.backend]&&(p="error",f=`configured backend "${n.backend}" not available in this environment`),e.push(O("backend",p,f,Date.now()-r));let u=F(),l;if(!n.llm.initialized||!n.llm.capabilities.embedding)l=O(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","llm not initialized; probe skipped",Date.now()-u);else if(!n.dbExists)l=O(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","db not initialized; probe skipped",Date.now()-u);else try{let d=a$2.getEmbeddingLlm();if(!d)l=O(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","embedding llm not exposed; probe skipped",Date.now()-u);else {let m=await probeEmbeddingDims(d,{timeoutMs:5e3});typeof m!="number"?l=O(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe failed (network / model error)",Date.now()-u):n.embeddingDims===void 0?l=O(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe=${m}, meta missing \u2014 next status will sync`,Date.now()-u):m!==n.embeddingDims?l=O(EMBEDDING_DIMS_CONSISTENCY_CHECK,"warn",`probe=${m} but meta.embeddingDims=${n.embeddingDims} (drift detected)`,Date.now()-u,{probed:m,recorded:n.embeddingDims}):l=O(EMBEDDING_DIMS_CONSISTENCY_CHECK,"ok",`probe=${m} matches meta`,Date.now()-u,{probed:m});}}catch(d){l=O(EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe threw: ${d instanceof Error?d.message:String(d)}`,Date.now()-u);}if(e.push(l),n.dbExists){let d=F();try{let{DatabaseManager:m}=await import('./database-manager-26PY6VTD.mjs'),S=new m(n.dbPath);try{let{issues:g,stats:y}=S.checkIntegrity();s=y;for(let h of g)e.push(O("integrity_stats",h.severity,h.message,0,{source:"database.checkIntegrity"}));s.parse_errors===0&&e.push(O("parse_errors_zero","info","parse_errors: 0 (no parse errors recorded)",0)),s.unresolved_refs===0&&e.push(O("unresolved_refs_zero","info","unresolved_refs: 0 (resolution pipeline not active)",0)),s.name_segment_vocab===0&&e.push(O("name_segment_vocab_zero","info","name_segment_vocab: 0 (identifier-segments not active)",0)),s.project_metadata===0&&e.push(O("project_metadata_zero","info","project_metadata: 0 (CodeBase.initialize not run)",0));}finally{S.close();}}catch(m){e.push(O("integrity_stats","warn",`db integrity check failed: ${m instanceof Error?m.message:String(m)}`,Date.now()-d));}}let E=F();if(!n.llm.initialized)e.push(O("llm","info","Llm namespace not initialized (calls `easbot codebase init` first)",Date.now()-E));else {let d=[];n.llm.capabilities.embedding||d.push("embedding"),n.llm.capabilities.graphLlm||d.push("graphLlm"),e.push(O("llm",d.length===0?"ok":"info",d.length===0?"embedding + graphLlm configured":`missing capabilities: ${d.join(", ")}`,Date.now()-E,{capabilities:n.llm.capabilities}));}return {healthy:!e.some(d=>d.severity==="error"),checks:e,issues:e.map(d=>({severity:d.severity,message:d.message,name:d.name,code:d.code})),durationMs:Date.now()-t,status:n,backendAvailable:c,dbStats:s??void 0}}function O(o,t,n,e,s){return {code:o.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),severity:t,name:o,message:n,details:s,durationMs:e}}function Ee(o){let t={},n=[];for(let e of o)if(e==="--no-embed")t.noEmbed=true;else if(e==="--embed")t.noEmbed=false;else if(e==="--json")t.json=true;else if(e==="--verbose"||e==="-v")t.verbose=true;else if(e==="--quiet"||e==="-q")t.quiet=true;else if(e==="--help"||e==="-h")t.help=true;else if(e.startsWith("--batch=")){let s=e.slice(8),a=Number.parseInt(s,10);Number.isFinite(a)&&a>0&&(t.batch=a);}else e.startsWith("-")||n.push(e);return t.dir=n[0],t}async function Ce(o){let t=o.dir&&isAbsolute(o.dir)?o.dir:join(l(),o.dir??".");a(t);b(t);await I({dir:t});let {CodeBase:s}=await import('./code-base-BSRUQYXN.mjs'),{DEFAULT_EMBEDDING_CONFIG:a$1,DEFAULT_INDEXER_CONFIG:i,DEFAULT_PARSER_CONFIG:r}=await import('@easbot/types'),c=o.batch??i.batchSize??50,b$1=new s({workspaceDir:t,database:{path:c$1(t),walMode:true},embedding:o.noEmbed===false?a$1:void 0,indexer:{...i,batchSize:c},parser:r,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}}),f=-1,u=0,l$1=!o.quiet,E;try{await b$1.initialize(),registerActiveProgressLine(process.stderr);let d=await b$1.indexDirectory(t,l$1?m=>{let S=Math.max(m.total,1),g=Math.min(100,Math.floor(m.processed/S*100)),y=Date.now();if(g!==f||y-u>3e4){let C=String(g).padStart(3," ");clearActiveProgressLine(),process.stderr.write(` \u{1F4A1} [${C}%] ${m.stage}: ${m.processed}/${m.total} files`),f=g,u=y;}}:void 0);E={rootDir:t,success:d.success,filesProcessed:d.filesProcessed,nodesCreated:d.nodesCreated,edgesCreated:d.edgesCreated,errorCount:d.errors.length,errors:d.errors,durationMs:d.duration,embedded:!o.noEmbed,batchSize:c};}finally{clearActiveProgressLine(),unregisterActiveProgressLine(process.stderr),await b$1.close();}return E}function ke(o){let t=[];if(t.push("Codebase index"),t.push(` rootDir: ${o.rootDir}`),t.push(` success: ${o.success?"\u2713":"\u2717"}`),t.push(` files processed: ${o.filesProcessed}`),t.push(` nodes created: ${o.nodesCreated}`),t.push(` edges created: ${o.edgesCreated}`),t.push(` embedded: ${o.embedded?"yes":"no (--no-embed)"}`),t.push(` batch size: ${o.batchSize}`),t.push(` duration: ${o.durationMs}ms`),o.errorCount>0){t.push(` errors (${o.errorCount}):`);for(let n of o.errors.slice(0,10))t.push(` - ${n.filePath}: ${n.error}`);o.errors.length>10&&t.push(` ... and ${o.errors.length-10} more`);}return t.join(`
2
+ `)}function _e(o){let t={},n=[];for(let e of o)e==="--json"?t.json=true:e==="--quiet"||e==="-q"?t.quiet=true:e==="--help"||e==="-h"?t.help=true:e==="--no-embed"?t.noEmbed=true:e==="--embed"?t.noEmbed=false:e.startsWith("-")||n.push(e);return t.dir=n[0],t}async function Ne(o){let t=o.dir&&isAbsolute(o.dir)?o.dir:join(l(),o.dir??"."),n=c$1(t),{CodeBase:e}=await import('./code-base-BSRUQYXN.mjs'),{DEFAULT_EMBEDDING_CONFIG:s,DEFAULT_INDEXER_CONFIG:a,DEFAULT_PARSER_CONFIG:i}=await import('@easbot/types'),r=new e({workspaceDir:t,database:{path:n,walMode:true},embedding:o.noEmbed===false?s:void 0,indexer:a,parser:i,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}}),c,b={_lastPct:-1,_lastProgressAt:0};try{await r.initialize(),registerActiveProgressLine(process.stderr);let p=await r.sync(o.quiet?void 0:u=>{let l=Math.max(u.total,1),E=Math.min(100,Math.floor(u.processed/l*100)),d=Date.now(),m=E!==b._lastPct,S=d-b._lastProgressAt>3e4;if(m||S){let g=String(E).padStart(3," ");clearActiveProgressLine(),process.stderr.write(` \u{1F4A1} [${g}%] ${u.stage}: ${u.processed}/${u.total} files`),b._lastPct=E,b._lastProgressAt=d;}}),f=r.getDatabase().getIndexState();c={rootDir:t,success:p.success,filesAdded:p.filesAdded,filesUpdated:p.filesUpdated,filesDeleted:p.filesDeleted,filesSkipped:p.filesSkipped,nodesCreated:p.nodesCreated,edgesCreated:p.edgesCreated,errorCount:p.errors.length,errors:p.errors,durationMs:p.duration,indexState:f};}finally{clearActiveProgressLine(),unregisterActiveProgressLine(process.stderr),await r.close();}return c}function De(o){let t=[];if(t.push("Codebase sync"),t.push(` rootDir: ${o.rootDir}`),t.push(` success: ${o.success?"\u2713":"\u2717"}`),t.push(` indexState: ${o.indexState}`),t.push(` files added: ${o.filesAdded}`),t.push(` files updated: ${o.filesUpdated}`),t.push(` files deleted: ${o.filesDeleted}`),t.push(` files skipped: ${o.filesSkipped}`),t.push(` nodes created: ${o.nodesCreated}`),t.push(` edges created: ${o.edgesCreated}`),t.push(` duration: ${o.durationMs}ms`),o.errorCount>0){t.push(` errors (${o.errorCount}):`);for(let n of o.errors.slice(0,10))t.push(` - ${n.filePath}: ${n.error}`);o.errors.length>10&&t.push(` ... and ${o.errors.length-10} more`);}return t.join(`
3
+ `)}function ve(o){let t={},n=[];for(let e of o)e==="--keep-config"?t.keepConfig=true:e==="--force"||e==="-f"?t.force=true:e==="--json"?t.json=true:e==="--help"||e==="-h"?t.help=true:e.startsWith("-")||n.push(e);return t.dir=n[0],t}async function Oe(o){let t=o.dir&&isAbsolute(o.dir)?o.dir:join(l(),o.dir??".");a(t);let e=c$1(t),s=b(t),a$1=false,i=false;for(let r of [e,`${e}-wal`,`${e}-shm`])if(existsSync(r))try{rmSync(r,{force:!0}),r===e&&(a$1=!0);}catch{}if(!o.keepConfig&&existsSync(s))try{rmSync(s,{force:!0}),i=!0;}catch{}return await I({dir:t,force:true}),{rootDir:t,removedDb:a$1,removedConfig:i,recreated:true,configPath:s}}function Te(o){let t=[];return t.push("Codebase recreate"),t.push(` rootDir: ${o.rootDir}`),t.push(` removed db: ${o.removedDb?"\u2713":"\u2717 (not found)"}`),t.push(` removed config:${o.removedConfig?"\u2713":"(preserved via --keep-config or absent)"}`),t.push(` \u2713 reinitialized at ${o.configPath}`),t.push(""),t.push("\u{1F4A1} Next: run `easbot codebase index` to rebuild the index."),t.join(`
4
+ `)}function $e(o){let t={},n=[];for(let e of o)e==="--keep-embeddings"?t.keepEmbeddings=true:e==="--force"||e==="-f"?t.force=true:e==="--json"?t.json=true:e==="--help"||e==="-h"?t.help=true:e.startsWith("-")||n.push(e);return t.dir=n[0],t}async function Pe(o){let t=o.dir&&isAbsolute(o.dir)?o.dir:join(l(),o.dir??".");a(t);let e=c$1(t),s=b(t);if(!existsSync(e))return await I({dir:t}),{rootDir:t,cleared:false,nodesRemoved:0,edgesRemoved:0,filesRemoved:0,embeddingsPreserved:false,configPreserved:existsSync(s),nextIndexState:"uninitialized"};let{CodeBase:a$1}=await import('./code-base-BSRUQYXN.mjs'),{DEFAULT_EMBEDDING_CONFIG:i,DEFAULT_INDEXER_CONFIG:r,DEFAULT_PARSER_CONFIG:c}=await import('@easbot/types'),b$1=new a$1({workspaceDir:t,database:{path:e,walMode:true},embedding:o.keepEmbeddings?i:void 0,indexer:r,parser:c,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}}),p;try{await b$1.initialize();let f={nodes:b$1.getDatabase().getNodeCount(),edges:b$1.getDatabase().getEdgeCount(),files:b$1.getDatabase().getFileCount()};await b$1.clear({keepEmbeddings:!!o.keepEmbeddings}),b$1.getDatabase().setIndexState("uninitialized"),p={rootDir:t,cleared:!0,nodesRemoved:f.nodes,edgesRemoved:f.edges,filesRemoved:f.files,embeddingsPreserved:!!o.keepEmbeddings,configPreserved:existsSync(s),nextIndexState:"uninitialized"};}finally{await b$1.close();}return p}function Le(o){let t=[];return t.push("Codebase clear"),t.push(` rootDir: ${o.rootDir}`),o.cleared?(t.push(" \u2713 cleared data"),t.push(` nodes removed: ${o.nodesRemoved}`),t.push(` edges removed: ${o.edgesRemoved}`),t.push(` file hashes removed: ${o.filesRemoved}`),t.push(` embeddings preserved: ${o.embeddingsPreserved?"yes (--keep-embeddings)":"no"}`),t.push(` config preserved: ${o.configPreserved?"\u2713":"\u2717"}`)):(t.push(" \u2717 db not found at .easbot/db/codebase.db \u2014 nothing to clear"),t.push(` config preserved: ${o.configPreserved?"\u2713":"\u2717"}`)),t.push(""),t.push("\u{1F4A1} Next: run `easbot codebase index` to rebuild."),t.join(`
5
+ `)}var Fe=new Set(["backend","schema_version","extraction_version","index_state"]);function Po(o){return new Set(["schema_version","extraction_version"]).has(o)?"number":"string"}function Me(o){let t={},n=[];for(let e of o)e==="--json"?t.json=true:e==="--help"||e==="-h"?t.help=true:e.startsWith("-")||n.push(e);if(n.length>0)if(t.subcommand=n[0],t.subcommand==="set")n.length>1&&(t.key=n[1]),n.length>2&&(t.value=n[2]),n.length>3&&(t.dir=n[3]);else {if(n.length>=2){let e=n[1]??"";isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")?t.dir=e:t.key=e;}n.length>=3&&(t.dir=n[2]);}return t}function qe(o){let t=readFileSync(o,"utf-8");return JSON.parse(t)}function Lo(o,t){writeFileSync(o,JSON.stringify(t,null,2),"utf-8");}function Ue(o){return o.dir&&isAbsolute(o.dir)?o.dir:join(l(),o.dir??".")}async function Be(o){let t=Ue(o),n=b(t),e=existsSync(n),s={rootDir:t,configPath:e?n:void 0,exists:e,values:null};if(!e)return s;let a;try{a=qe(n);}catch{return s}return o.key?(s.key=o.key,s.value=a[o.key]):s.values=a,s}var Fo=new Set(["backend","schema_version","extraction_version","index_state"]);async function We(o){if(!o.key)throw new Error("config set requires <key>");if(o.value===void 0)throw new Error("config set requires <value> after <key>");if(!Fe.has(o.key))throw new Error(`Unsupported config key: "${o.key}". Allowed: ${Array.from(Fe).join(", ")}`);let t=Ue(o),n=a(t),e=b(t);if(!existsSync(n))throw new Error(`codebase not initialized at ${t} \u2014 run \`easbot codebase init\` first`);let s=o.value;if(Po(o.key)==="number"){let c=Number(o.value);if(!Number.isFinite(c))throw new Error(`config key "${o.key}" expects a number, got "${o.value}"`);s=c;}let i=existsSync(e)?qe(e):{},r=i[o.key];return i[o.key]=s,existsSync(n)||mkdirSync(n,{recursive:true}),Lo(e,i),{rootDir:t,configPath:e,key:o.key,oldValue:r,newValue:s,requiresRestart:Fo.has(o.key)}}function Ge(o){if(!o.exists)return `\u2717 config not found at ${o.configPath??"/.easbot/codebase.json"} \u2014 run \`easbot codebase init\` first`;let t=[];if(t.push(`Codebase config: ${o.configPath}`),o.key!==void 0)t.push(` ${o.key}: ${JSON.stringify(o.value)}`);else if(o.values)for(let[n,e]of Object.entries(o.values))t.push(` ${n}: ${JSON.stringify(e)}`);return t.join(`
6
+ `)}function ze(o){let t=[];return t.push(`\u2713 ${o.key}: ${JSON.stringify(o.oldValue)} \u2192 ${JSON.stringify(o.newValue)} (${o.configPath})`),o.requiresRestart&&(t.push(""),t.push(" \u26A0\uFE0F this setting affects db connection / sync behavior \u2014 restart CodeBase or run `recreate` for the change to take effect.")),t.join(`
7
+ `)}function Ve(o){let t={},n=[];for(let e of o)e==="--schema"?t.schema=true:e==="--force"||e==="-f"?t.force=true:e==="--backup"||e==="-b"?t.backup=true:e==="--dry-run"||e==="-n"?t.dryRun=true:e==="--json"?t.json=true:e==="--help"||e==="-h"?t.help=true:e.startsWith("-")||n.push(e);return t.dir=n[0],t}async function He(o){let t=o.dir&&isAbsolute(o.dir)?o.dir:join(l(),o.dir??"."),n=a(t),e=c$1(t);if(existsSync(n)||await I({dir:t}),!existsSync(e))throw new Error(`db not found at ${e} \u2014 run \`easbot codebase index\` first to create it`);let{DatabaseManager:s}=await import('./database-manager-26PY6VTD.mjs'),a$1=new s(e);try{let i=a$1.db,r=a$1.isIndexStale(),c=a$1.getMeta("indexed_with_extraction_version"),b=c?parseInt(c,10):null,p=a$1.getIndexState(),f=a$1.getMeta("schema_version"),u=f?parseInt(f,10):0,l={rootDir:t,dbPath:e,wasStale:r,previousVersion:b??null,currentVersion:m,applied:!1,schemaMigrated:!1,previousSchemaVersion:u,currentSchemaVersion:u,dryRun:!!o.dryRun,schemaSteps:j$1.map(g=>({id:g.id,description:g.description,status:"pending"})),migrationErrors:[],indexState:p},E;if(o.backup!==!1&&!o.dryRun)try{let g=new Date().toISOString().replace(/[:.]/g,"-");E=join(n,`codebase.db.bak.${g}`),copyFileSync(e,E);for(let y of ["-wal","-shm"]){let h=e+y;existsSync(h)&&copyFileSync(h,E+y);}l.backupPath=E;}catch(g){let y=g instanceof Error?g.message:String(g);l.recommendation=`Backup failed: ${y}. Continuing without backup.`;}let m$1=o.schema!==!1;try{let g=k(i,i$1,{dryRun:o.dryRun});l.currentSchemaVersion=o.dryRun?g.targetVersion:Math.max(g.currentVersion,g.targetVersion),l.migrationErrors=g.errors.map(h=>({migrationId:h.migrationId,error:h.error}));let y=new Set(g.applied);for(let h of l.schemaSteps)y.has(h.id)&&(h.status=o.dryRun?"pending":"applied");for(let h of l.migrationErrors){let C=l.schemaSteps.find(k=>k.id===h.migrationId);C&&(C.status="failed");}if(l.schemaMigrated=g.applied.length>0&&!o.dryRun,!o.dryRun){let h=l$1(i);l.currentSchemaVersion=h,h>0&&a$1.setMeta("schema_version",String(h));}}catch(g){let y=g instanceof Error?g.message:String(g);l.migrationErrors.push({migrationId:0,error:y});}let S=r||o.force;return S&&!o.dryRun&&(a$1.setMeta("indexed_with_extraction_version",String(m)),(p==="stale"||p==="failed")&&(a$1.setIndexState("complete"),l.indexState="complete"),l.applied=!0),o.dryRun?l.migrationErrors.length>0?l.recommendation="dry-run finished. Run without --dry-run to apply.":l.schemaMigrated?l.recommendation="dry-run: schema migration would apply. Run without --dry-run to apply.":l.recommendation="dry-run: nothing to apply.":!S&&!l.schemaMigrated&&l.migrationErrors.length===0?l.recommendation=`Already current (schema_version=${l.currentSchemaVersion}, extraction_version=${m}). No upgrade needed.`:l.migrationErrors.length>0?l.recommendation=`Schema migration completed with ${l.migrationErrors.length} error(s). `+(l.backupPath?`Restore from backup: ${l.backupPath}`:"Re-run `recreate` to drop & rebuild."):l.schemaMigrated&&!S?l.recommendation=`Schema migrated (v${l.previousSchemaVersion} \u2192 v${l.currentSchemaVersion}). To apply extraction changes, run \`recreate\` to rebuild data or \`index --force\`.`:l.schemaMigrated&&S?l.recommendation="Schema + extraction metadata both updated. To rebuild data with new extractor, run `recreate` or `index --force`.":l.recommendation="Extraction metadata updated. No schema changes needed.",l}finally{a$1.close();}}function Ye(o){let t=[];if(t.push(`Codebase upgrade${o.dryRun?" (dry-run)":""}`),t.push(` db: ${o.dbPath}`),o.backupPath&&t.push(` backup: ${o.backupPath}`),t.push(` previous version: ${o.previousVersion??"(none)"}`),t.push(` current version: ${o.currentVersion}`),t.push(` previous schema_version: ${o.previousSchemaVersion}`),t.push(` current schema_version: ${o.currentSchemaVersion}`),t.push(` was stale: ${o.wasStale?"yes":"no"}`),t.push(` applied: ${o.applied?"\u2713":"(noop \u2014 already current)"}`),(o.schemaSteps??[]).length>0){t.push(""),t.push(" schema steps:");for(let n of o.schemaSteps){let e=n.status==="applied"?"\u2713":n.status==="pending"?"\xB7":n.status==="failed"?"\u2717":"-";t.push(` [${e}] v${n.id}: ${n.description}`);}}if((o.migrationErrors??[]).length>0){t.push(""),t.push(` migration errors: ${o.migrationErrors.length}`);for(let n of o.migrationErrors)t.push(` - v${n.migrationId}: ${n.error}`);}return t.push(` index_state: ${o.indexState}`),o.recommendation&&(t.push(""),t.push(` \u{1F4A1} ${o.recommendation}`)),t.join(`
8
+ `)}function Xe(o){let t={},n=[];for(let e of o)if(e==="--all")t.all=true;else if(e==="--dry-run"||e==="-n")t.dryRun=true;else if(e==="--pending-list"||e==="-p")t.pendingList=true;else if(e.startsWith("--batch=")){let s=parseInt(e.slice(8),10);Number.isFinite(s)&&s>0&&(t.batchSize=s);}else e==="--json"?t.json=true:e==="--help"||e==="-h"?t.help=true:e.startsWith("-")||n.push(e);return t.dir=n[0],t}var Uo=200;function Bo(o,t=Uo){return o?o.length<=t?o:o.slice(0,t)+"\u2026":""}async function Ze(o){let t=o.dir&&isAbsolute(o.dir)?o.dir:join(l(),o.dir??"."),n=a(t),e=c$1(t);if(!existsSync(n))throw new Error(`codebase not initialized at ${t} \u2014 run \`easbot codebase init\` first`);if(!existsSync(e))throw new Error(`db not found at ${e} \u2014 run \`easbot codebase index\` first to build`);let s=Date.now(),a$1=process.env.EASBOT_EMBEDDING_MODEL;if(!o.dryRun&&!a$1)throw new Error('embed requires an embedding model. Set EASBOT_EMBEDDING_MODEL env var (e.g. "openai/text-embedding-3-small") or pass --dry-run to skip embedding generation and just inspect pending nodes. Call `embed` from within an `easbot` REPL session for actual generation.');let{CodeBase:i}=await import('./code-base-BSRUQYXN.mjs'),{DEFAULT_EMBEDDING_CONFIG:r,DEFAULT_INDEXER_CONFIG:c,DEFAULT_PARSER_CONFIG:b}=await import('@easbot/types'),p={...r,modelId:a$1??"(dry-run)"},f=new i({workspaceDir:t,database:{path:e,walMode:true},embedding:p,indexer:c,parser:b,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});try{await f.initialize();let u=f.getDatabase(),l=u.getNodeCount(),E=u.queryAll("SELECT node_id FROM node_embeddings"),d=new Set(E.map(y=>y.node_id)),m;if(o.all)m=u.queryAll("SELECT id, name, ast_type, language, file_path, text FROM nodes");else if(d.size===0)m=u.queryAll("SELECT id, name, ast_type, language, file_path, text FROM nodes");else {let y=Array.from(d),h=y.map(()=>"?").join(",");m=u.queryAll(`SELECT id, name, ast_type, language, file_path, text FROM nodes WHERE id NOT IN (${h})`,y);}let S=m.map(y=>({id:y.id,name:y.name,ast_type:y.ast_type,file_path:y.file_path,language:y.language,text_preview:Bo(y.text)})),g={rootDir:t,dbPath:e,totalNodes:l,alreadyEmbedded:d.size,newlyEmbedded:0,failed:0,all:!!o.all,dryRun:!!o.dryRun,pendingList:o.pendingList?S:[],duration:Date.now()-s,embeddingModelConfigured:!!a$1};return o.dryRun?g.recommendation=S.length>0?`dry-run: ${S.length} node(s) pending embedding. Use \`easbot codebase embed\` (without --dry-run) inside an \`easbot\` REPL for actual generation, or \`--pending-list\` to emit this list as JSON.`:"dry-run: all nodes already embedded.":S.length===0?g.recommendation="All nodes already have embeddings. Use --all to force regenerate.":g.recommendation=`${S.length} node(s) pending. Run \`easbot codebase embed --pending-list --json [dir]\` to emit the list, then call \`embed\` from within an \`easbot\` REPL session for actual generation (CLI cannot invoke AI SDK adapters in standalone mode).`,g}finally{await f.close();}}function et(o){let t=[],n=o.dryRun?" (dry-run)":"";if(t.push(`Codebase embed${n}`),t.push(` db: ${o.dbPath}`),t.push(` mode: ${o.all?"all (force regenerate)":"incremental (only missing)"}`),t.push(` embedding model: ${o.embeddingModelConfigured?"configured":"(none)"}`),t.push(` total nodes: ${o.totalNodes}`),t.push(` already embedded: ${o.alreadyEmbedded}`),t.push(` newly embedded: ${o.newlyEmbedded}`),o.failed>0&&t.push(` failed: ${o.failed}`),t.push(` pending: ${o.pendingList.length}`),t.push(` duration: ${o.duration}ms`),o.dryRun&&o.pendingList.length>0){t.push(""),t.push(" \u{1F4A1} first 5 pending nodes:");for(let e of o.pendingList.slice(0,5))t.push(` - ${e.id} (${e.ast_type})`);}return o.recommendation&&(t.push(""),t.push(` \u{1F4A1} ${o.recommendation}`)),t.join(`
9
+ `)}var tt=Log.create({service:"codebase-watch"});function ot(o){let t={},n=[];for(let e of o)if(e.startsWith("--debounce=")){let s=parseInt(e.slice(11),10);Number.isFinite(s)&&s>0&&(t.debounce=s);}else if(e.startsWith("--interval=")){let s=parseInt(e.slice(11),10);Number.isFinite(s)&&s>0&&(t.interval=s);}else if(e.startsWith("--backend=")){let s=e.slice(10);(s==="fs-events"||s==="inotify"||s==="windows"||s==="brute-force"||s==="watchman"||s==="auto")&&(t.backend=s);}else e.startsWith("--ignore=")?(t.ignore||(t.ignore=[]),t.ignore.push(e.slice(9))):e==="--on-load-failure=throw"?t.onLoadFailure="throw":e==="--on-load-failure=warn"?t.onLoadFailure="warn":e==="--json"?t.json=true:e==="--help"||e==="-h"?t.help=true:e.startsWith("-")||n.push(e);return t.dir=n[0],t}async function nt(o){let t=o.dir&&isAbsolute(o.dir)?o.dir:join(l(),o.dir??"."),n=a(t);existsSync(n)||await I({dir:t});let e=new a$1({workspaceDir:t,backend:o.backend??"auto",ignorePatterns:o.ignore,onLoadFailure:o.onLoadFailure??"warn"}),s=[];e.on((a,i)=>{s.push({event:a,relPath:i,at:Date.now()}),tt.info("watch event",{event:a,relPath:i});}),await e.start();try{await d(n,process.pid);}catch(a){tt.warn("failed to write watcher pid",{error:String(a)});}return {watcher:e,events:s,startTime:Date.now()}}function it(o){return ["Codebase watcher started"," backend: native @parcel/watcher (real-time FS events)"," debounce: 200ms (event coalescing)",` pid: ${process.pid}`,` initial events: ${o.length}`].join(`
10
+ `)}function rt(o){let t={},n=[];for(let e of o)e==="--force"||e==="-f"?t.force=true:e==="--json"?t.json=true:e==="--help"||e==="-h"?t.help=true:e.startsWith("-")||n.push(e);return t.dir=n[0],t}async function at(o){let t=o.dir&&isAbsolute(o.dir)?o.dir:join(l(),o.dir??"."),n=a(t);existsSync(n)||await I({dir:t});let e$1=join(n,".watcher.pid"),s=c(n);if(s===null)return {rootDir:t,pidFile:e$1,pid:null,stopped:false,error:"No watcher running (no .easbot/.watcher.pid found)"};try{return process.kill(s,"SIGTERM"),await e(n),{rootDir:t,pidFile:e$1,pid:s,stopped:!0}}catch(a){await e(n);let i=a instanceof Error?a.message:String(a);return {rootDir:t,pidFile:e$1,pid:s,stopped:false,error:i}}}function ct(o){let t=[];return t.push("Codebase stop"),t.push(` pid file: ${o.pidFile}`),t.push(` pid: ${o.pid??"(none)"}`),t.push(` stopped: ${o.stopped?"\u2713":"\u2717"}`),o.error?(t.push(` error: ${o.error}`),t.push(""),t.push(" \u{1F4A1} If a stale watcher was running, its process may have already exited.")):(t.push(""),t.push(" \u{1F4A1} Use `easbot codebase watch [dir]` to start a new watcher session.")),t.join(`
11
+ `)}function dt(o){let t={includeEdges:true,enableEmbedding:true},n=[];for(let e of o)if(e==="--help"||e==="-h")t.help=true;else if(e==="--json")t.json=true;else if(e==="--no-edges")t.includeEdges=false;else if(e==="--no-vector"||e==="--no-embed")t.enableEmbedding=false;else if(e.startsWith("-l=")||e.startsWith("--language="))t.language=e.includes("=")?e.split("=")[1]:void 0;else if(!(e==="-l"||e==="--language"))if(e.startsWith("--ast="))t.astType=e.slice(6);else if(e.startsWith("-n=")||e.startsWith("--max=")){let s=parseInt(e.split("=")[1]??"",10);Number.isFinite(s)&&s>0&&(t.maxResults=s);}else e.startsWith("--dir=")?t.dir=e.slice(6):e.startsWith("-")||n.push(e);return n.length>0&&(t.query=n.join(" ")),t}async function pt(o){let t=isAbsolute(o.dir??"")&&o.dir?o.dir:join(l(),o.dir??"."),n=a(t),e=c$1(t);if(existsSync(n)||await I({dir:t}),!existsSync(e))throw new Error(`db not found at ${e} \u2014 run \`easbot codebase index\` first`);let{CodeBase:s}=await import('./code-base-BSRUQYXN.mjs'),{DEFAULT_EMBEDDING_CONFIG:a$1,DEFAULT_INDEXER_CONFIG:i,DEFAULT_PARSER_CONFIG:r,DEFAULT_SEARCH_CONFIG:c}=await import('@easbot/types'),b=new s({workspaceDir:t,database:{path:e,walMode:true},embedding:o.enableEmbedding?a$1:void 0,indexer:i,parser:r,search:c,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}}),p=Date.now();try{await b.initialize();let u=await b.getQuery().search(o.query??"",{maxResults:o.maxResults??20,language:o.language,astType:o.astType,includeEdges:o.includeEdges,enableEmbedding:o.enableEmbedding});return {rootDir:t,query:o.query??"",totalResults:u.length,results:u.map(l=>({id:l.id,name:l.name,astType:l.ast_type,language:l.language,filePath:l.file_path,startLine:l.start_line??0,endLine:l.end_line??0,snippet:(l.text??"").slice(0,200),edgeCount:(l.edges??[]).length})),durationMs:Date.now()-p}}finally{await b.close();}}function ut(o){let t=[];t.push(`Codebase query: ${JSON.stringify(o.query)}`),t.push(` results: ${o.totalResults} (in ${o.durationMs}ms)`);for(let n of o.results)t.push(` ${n.name} (${n.astType}) \u2014 ${n.language} ${n.filePath}:${n.startLine}-${n.endLine} [${n.edgeCount} edges]`),t.push(` ${n.snippet.replace(/\s+/g," ").slice(0,100)}`);return t.join(`
12
+ `)}function gt(o){let t={includeEdges:false},n=[];for(let e of o)if(e==="--help"||e==="-h")t.help=true;else if(e==="--json")t.json=true;else if(e==="--edges")t.includeEdges=true;else if(e.startsWith("--file="))t.file=e.slice(7);else if(e.startsWith("--kind="))t.kind=e.slice(7);else if(e.startsWith("--max=")){let s=parseInt(e.slice(6),10);Number.isFinite(s)&&s>0&&(t.edgesLimit=s);}else e.startsWith("--dir=")?t.dir=e.slice(6):e.startsWith("-")||n.push(e);return n.length>0&&(t.name=n[0],t.nodeId=n[0]),t}async function ft(o){if(!o.name&&!o.nodeId)throw new Error("node command requires a <name> or <node-id> argument");let t=isAbsolute(o.dir??"")&&o.dir?o.dir:join(l(),o.dir??"."),n=a(t),e=c$1(t);if(existsSync(n)||await I({dir:t}),!existsSync(e))throw new Error(`db not found at ${e} \u2014 run \`easbot codebase index\` first`);let a$1=await e$1({workspaceDir:t,rootDir:t},{name:o.name,nodeId:o.nodeId,file:o.file,kind:o.kind,includeEdges:o.includeEdges??false,includeContent:true,edgesLimit:o.edgesLimit??50});if(!a$1.node)return {rootDir:t,found:false,incomingEdges:[],outgoingEdges:[]};let i=[],r=[];for(let c of a$1.edges)c.target===a$1.node.id?i.push({id:c.id,relation:c.relation,source:c.source,target:c.target,direction:"in"}):r.push({id:c.id,relation:c.relation,source:c.source,target:c.target,direction:"out"});return {rootDir:t,found:true,node:{id:a$1.node.id,name:a$1.node.name,astType:a$1.node.ast_type,language:a$1.node.language,filePath:a$1.node.file_path,startLine:a$1.node.start_line??0,endLine:a$1.node.end_line??0,text:a$1.node.text??""},incomingEdges:i,outgoingEdges:r}}function bt(o){if(!o.found||!o.node)return `\u2717 node not found (rootDir: ${o.rootDir})`;let t=[];if(t.push(`Codebase node: ${o.node.id}`),t.push(` name: ${o.node.name}`),t.push(` type: ${o.node.astType}`),t.push(` language: ${o.node.language}`),t.push(` location: ${o.node.filePath}:${o.node.startLine}-${o.node.endLine}`),t.push(` edges: ${o.incomingEdges.length} incoming / ${o.outgoingEdges.length} outgoing`),o.incomingEdges.length>0&&typeof o.incomingEdges[0]=="object"&&"relation"in o.incomingEdges[0]){t.push(""),t.push(" incoming edges:");for(let n of o.incomingEdges.slice(0,20))t.push(` [${n.relation}] ${n.source} \u2192 ${n.target}`);t.push(" outgoing edges:");for(let n of o.outgoingEdges.slice(0,20))t.push(` [${n.relation}] ${n.source} \u2192 ${n.target}`);}return t.join(`
13
+ `)}function yt(o){let t={direction:"both"},n=[];for(let e of o)if(e==="--help"||e==="-h")t.help=true;else if(e==="--json")t.json=true;else if(e.startsWith("--depth=")){let s=parseInt(e.slice(8),10);Number.isFinite(s)&&s>0&&(t.depth=s);}else if(e.startsWith("--max=")){let s=parseInt(e.slice(6),10);Number.isFinite(s)&&s>0&&(t.maxNodes=s);}else if(e.startsWith("--direction=")){let s=e.slice(12);(s==="incoming"||s==="outgoing"||s==="both")&&(t.direction=s);}else if(e.startsWith("--relation=")){let s=e.slice(11).split(",").map(a=>a.trim()).filter(Boolean);t.relationTypes=s;}else e.startsWith("--dir=")?t.dir=e.slice(6):e.startsWith("-")||n.push(e);return n.length>0&&(t.nodeId=n[0]),t}async function xt(o){let t=isAbsolute(o.dir??"")&&o.dir?o.dir:join(l(),o.dir??"."),n=a(t),e=c$1(t);if(existsSync(n)||await I({dir:t}),!existsSync(e))throw new Error(`db not found at ${e} \u2014 run \`easbot codebase index\` first`);if(!o.nodeId)throw new Error("context command requires a <node-id> argument");let s=o.depth??2,a$1=o.maxNodes??100,i=o.direction??"both",{CodeBase:r}=await import('./code-base-BSRUQYXN.mjs'),{DEFAULT_EMBEDDING_CONFIG:c,DEFAULT_INDEXER_CONFIG:b,DEFAULT_PARSER_CONFIG:p,DEFAULT_SEARCH_CONFIG:f}=await import('@easbot/types'),u=new r({workspaceDir:t,database:{path:e,walMode:true},embedding:c,indexer:b,parser:p,search:f,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});try{await u.initialize();let l=u.getDatabase(),E=u.getQuery();if(!l.getNodeById(o.nodeId))return {rootDir:t,rootNodeId:o.nodeId,depth:s,totalNodes:0,totalEdges:0,nodes:[],edges:[],truncated:!1};let m=new Map,S=[{nodeId:o.nodeId,depth:0}];m.set(o.nodeId,0);let g=[],y=!1;for(;S.length>0;){let w=S.shift();if(w.depth>=s)continue;if(m.size>=a$1){y=!0;break}let T=E.queryNeighbors(w.nodeId,{direction:i,relationTypes:o.relationTypes,limit:a$1-m.size+1});for(let R of T.edges){g.push({source:R.source,target:R.target,relation:R.relation});let A=R.source===w.nodeId?R.target:R.source;if(!m.has(A)&&(m.set(A,w.depth+1),S.push({nodeId:A,depth:w.depth+1}),m.size>=a$1)){y=!0;break}}if(y)break}let h=Array.from(m.keys()),C=h.length>0?l.queryNodes({ids:h}):[],k=new Map(C.map(w=>[w.id,w])),D=[];for(let[w,T]of m.entries()){let R=k.get(w);R&&D.push({id:R.id,name:R.name,astType:R.ast_type,language:R.language,filePath:R.file_path,depth:T});}return {rootDir:t,rootNodeId:o.nodeId,depth:s,totalNodes:D.length,totalEdges:g.length,nodes:D,edges:g,truncated:y}}finally{await u.close();}}function St(o){let t=[];t.push(`Codebase context: ${o.rootNodeId} (depth=${o.depth})`),t.push(` nodes: ${o.totalNodes}${o.truncated?" [TRUNCATED]":""}`),t.push(` edges: ${o.totalEdges}`);for(let n of o.nodes.slice(0,50))t.push(` [d=${n.depth}] ${n.name} (${n.astType}) \u2014 ${n.language} ${n.filePath}`);return o.nodes.length>50&&t.push(` ... and ${o.nodes.length-50} more`),t.join(`
14
+ `)}function Et(o){let t={},n=[];for(let e of o)if(e==="--help"||e==="-h")t.help=true;else if(e==="--json")t.json=true;else if(e.startsWith("-d=")||e.startsWith("--depth=")){let s=parseInt(e.split("=")[1]??"",10);Number.isFinite(s)&&s>0&&(t.depth=s);}else if(e.startsWith("--relation=")){let s=e.slice(11).split(",").map(a=>a.trim()).filter(Boolean);t.relationTypes=s;}else e.startsWith("--dir=")?t.dir=e.slice(6):e.startsWith("-")||n.push(e);return n.length>0&&(t.nodeId=n[0]),t}async function Ct(o){let t=isAbsolute(o.dir??"")&&o.dir?o.dir:join(l(),o.dir??"."),n=a(t),e=c$1(t);if(existsSync(n)||await I({dir:t}),!existsSync(e))throw new Error(`db not found at ${e} \u2014 run \`easbot codebase index\` first`);if(!o.nodeId)throw new Error("impact command requires a <node-id> argument");let s=o.depth??3,a$1=o.relationTypes??["CALLS","REFERENCES","USES"],{CodeBase:i}=await import('./code-base-BSRUQYXN.mjs'),{DEFAULT_EMBEDDING_CONFIG:r,DEFAULT_INDEXER_CONFIG:c,DEFAULT_PARSER_CONFIG:b,DEFAULT_SEARCH_CONFIG:p}=await import('@easbot/types'),f=new i({workspaceDir:t,database:{path:e,walMode:true},embedding:r,indexer:c,parser:b,search:p,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});try{await f.initialize();let u=f.getQuery(),l=f.getDatabase(),E=new Set([o.nodeId]),d=[],m=[o.nodeId];for(let S=1;S<=s&&m.length!==0;S++){let g=[],y=new Set;if(m.length>0){let h=m.map(()=>"?").join(","),C=a$1.map(()=>"?").join(","),k=l.queryAll(`SELECT source, target, relation FROM edges WHERE target IN (${h}) AND relation IN (${C})`,[...m,...a$1]);for(let D of k)!E.has(D.source)&&!y.has(D.source)&&(y.add(D.source),E.add(D.source),g.push(D.source));}if(g.length>0){let h=g.slice(0,10),C=h.length>0?l.queryNodes({ids:h}):[],k=new Map(C.map(w=>[w.id,w])),D=h.map(w=>{let T=k.get(w);return {id:w,name:T?.name??"(unknown)",filePath:T?.file_path??"(unknown)"}});d.push({depth:S,count:g.length,sample:D});}m=g;}return {rootDir:t,rootNodeId:o.nodeId,totalImpacted:E.size-1,depth:s,buckets:d}}finally{await f.close();}}function kt(o){let t=[];t.push(`Codebase impact: ${o.rootNodeId} (depth=${o.depth})`),t.push(` total impacted: ${o.totalImpacted}`);for(let n of o.buckets){t.push(` d=${n.depth}: ${n.count} nodes`);for(let e of n.sample.slice(0,5))t.push(` - ${e.name} (${e.filePath})`);}return t.join(`
15
+ `)}var rn="ts|tsx|js|jsx|mjs|cjs|py|rs|go|java|kt|scala|swift|rb|php|pl|sh|c|cpp|cc|cxx|h|hpp|lua|zig|cs|dart|ex|exs|clj|cljs|vue|svelte",an=[new RegExp(`(?:^|/)(?:main|index|app|server)\\.(?:${rn})$`)];function _t(o){let t={excludeEntry:true};for(let n of o)if(n==="--help"||n==="-h")t.help=true;else if(n==="--json")t.json=true;else if(n==="--no-exclude-entry")t.excludeEntry=false;else if(n.startsWith("--type="))t.astTypes=n.slice(7).split(",").map(e=>e.trim()).filter(Boolean);else if(n.startsWith("--limit=")){let e=parseInt(n.slice(8),10);Number.isFinite(e)&&e>0&&(t.limit=e);}return t}async function Nt(o){let t=isAbsolute(o.dir??"")&&o.dir?o.dir:join(l(),o.dir??"."),n=a(t),e=c$1(t);if(existsSync(n)||await I({dir:t}),!existsSync(e))throw new Error(`db not found at ${e} \u2014 run \`easbot codebase index\` first`);let s=o.astTypes??["function","method","class"],a$1=o.limit??100,i=o.excludeEntry!==false,{CodeBase:r}=await import('./code-base-BSRUQYXN.mjs'),{DEFAULT_EMBEDDING_CONFIG:c,DEFAULT_INDEXER_CONFIG:b,DEFAULT_PARSER_CONFIG:p,DEFAULT_SEARCH_CONFIG:f}=await import('@easbot/types'),u=new r({workspaceDir:t,database:{path:e,walMode:true},embedding:c,indexer:b,parser:p,search:f,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});try{await u.initialize();let l=u.getDatabase(),E=u.getQuery(),d=[],m=0,S=["CALLS","IMPORTS","TYPE_REFERENCES"],g=l.queryAll("SELECT DISTINCT target FROM edges WHERE relation IN ('CALLS','IMPORTS','TYPE_REFERENCES')"),y=new Set(g.map(h=>h.target));for(let h of s){let C=l.queryNodes({astType:h,limit:1e5});for(let k of C){if(i&&an.some(D=>D.test(k.file_path))){m++;continue}if(!y.has(k.id)&&(d.push({id:k.id,name:k.name,astType:k.ast_type,filePath:k.file_path,startLine:k.start_line??0}),d.length>=a$1))break}if(d.length>=a$1)break}return {rootDir:t,totalCandidates:d.length,excludedEntry:m,candidates:d.slice(0,a$1)}}finally{await u.close();}}function Dt(o){let t=[];t.push("Codebase dead-code"),t.push(` total candidates: ${o.totalCandidates}`),o.excludedEntry>0&&t.push(` excluded (entry files): ${o.excludedEntry}`);for(let n of o.candidates.slice(0,50))t.push(` - ${n.name} (${n.astType}) \u2014 ${n.filePath}:${n.startLine}`);return o.candidates.length>50&&t.push(` ... and ${o.candidates.length-50} more`),t.join(`
16
+ `)}function jt(o){let t={relation:"IMPORTS",scope:"file"};for(let n of o)if(n==="--help"||n==="-h")t.help=true;else if(n==="--json")t.json=true;else if(n.startsWith("--relation="))t.relation=n.slice(11);else if(n.startsWith("--scope=")){let e=n.slice(8);(e==="file"||e==="module")&&(t.scope=e);}return t}function dn(o){let t=0,n=new Map,e=new Map,s=new Set,a=[],i=[];function r(c){n.set(c,t),e.set(c,t),t++,a.push(c),s.add(c);let b=o.get(c)??[];for(let p of b)n.has(p)?s.has(p)&&e.set(c,Math.min(e.get(c),n.get(p))):(r(p),e.set(c,Math.min(e.get(c),e.get(p))));if(e.get(c)===n.get(c)){let p=[],f;do f=a.pop(),s.delete(f),p.push(f);while(f!==c);p.length>1&&i.push(p);}}for(let c of o.keys())n.has(c)||r(c);return i}async function vt(o){let t=isAbsolute(o.dir??"")&&o.dir?o.dir:join(l(),o.dir??"."),n=a(t),e=c$1(t);if(existsSync(n)||await I({dir:t}),!existsSync(e))throw new Error(`db not found at ${e} \u2014 run \`easbot codebase index\` first`);let s=o.relation??"IMPORTS",{CodeBase:a$1}=await import('./code-base-BSRUQYXN.mjs'),{DEFAULT_EMBEDDING_CONFIG:i,DEFAULT_INDEXER_CONFIG:r,DEFAULT_PARSER_CONFIG:c,DEFAULT_SEARCH_CONFIG:b}=await import('@easbot/types'),p=new a$1({workspaceDir:t,database:{path:e,walMode:true},embedding:i,indexer:r,parser:c,search:b,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});try{await p.initialize();let f=p.getDatabase(),u=f.queryNodes({limit:1e5}),l=new Map;for(let C of u){let k=l.get(C.file_path)??[];k.push(C.id),l.set(C.file_path,k);}let E=u.map(C=>C.id),d=new Map;for(let C of u)d.set(C.id,C.file_path);let m;if(E.length===0)m=[];else {let C=E.map(()=>"?").join(",");m=f.queryAll(`SELECT * FROM edges WHERE relation = ? AND source IN (${C})`,[s,...E]);}let S=new Map;for(let C of m){let k=d.get(C.source),D=d.get(C.target);if(!k||!D||k===D)continue;let w=S.get(k);w||(w=new Set,S.set(k,w)),w.add(D);}let g=new Map;for(let[C,k]of S.entries())g.set(C,Array.from(k));let h=dn(g).map(C=>{let k=[];for(let D=0;D<C.length;D++){let w=C[D],T=S.get(w);if(T)for(let R of T)C.includes(R)&&k.push({source:w,target:R});}return {cycle:C,edges:k}});return {rootDir:t,relation:s,totalCycles:h.length,cycles:h.slice(0,50)}}finally{await p.close();}}function Ot(o){let t=[];t.push(`Codebase circular (relation=${o.relation})`),t.push(` total cycles: ${o.totalCycles}`);for(let n=0;n<o.cycles.length;n++){let e=o.cycles[n];t.push(` cycle #${n+1} (${e.cycle.length} files):`),t.push(` ${e.cycle.join(" \u2192 ")} \u2192 ${e.cycle[0]}`);}return t.join(`
17
+ `)}function $t(o){let t={},n=[];for(let e of o)if(e==="--help"||e==="-h")t.help=true;else if(e==="--json")t.json=true;else if(e.startsWith("-d=")||e.startsWith("--depth=")){let s=parseInt(e.split("=")[1]??"",10);Number.isFinite(s)&&s>0&&(t.depth=s);}else if(e.startsWith("--relation=")){let s=e.slice(11).split(",").map(a=>a.trim()).filter(Boolean);t.relationTypes=s;}else e.startsWith("-")||n.push(e);return n.length>0&&(t.fromId=n[0]),n.length>1&&(t.toId=n[1]),t}async function Pt(o){let t=isAbsolute(o.dir??"")&&o.dir?o.dir:join(l(),o.dir??"."),n=a(t),e=c$1(t);if(existsSync(n)||await I({dir:t}),!existsSync(e))throw new Error(`db not found at ${e} \u2014 run \`easbot codebase index\` first`);if(!o.fromId||!o.toId)throw new Error("path command requires <from> and <to> node IDs");let s=o.depth??6,a$1=o.relationTypes??["CALLS","IMPORTS"],{CodeBase:i}=await import('./code-base-BSRUQYXN.mjs'),{DEFAULT_EMBEDDING_CONFIG:r,DEFAULT_INDEXER_CONFIG:c,DEFAULT_PARSER_CONFIG:b,DEFAULT_SEARCH_CONFIG:p}=await import('@easbot/types'),f=new i({workspaceDir:t,database:{path:e,walMode:true},embedding:r,indexer:c,parser:b,search:p,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});try{await f.initialize();let u=f.getQuery();if(o.fromId===o.toId)return {rootDir:t,found:!0,depth:0,steps:[],pathNodes:[o.fromId]};let l=new Set([o.fromId]),E=new Map,d=[o.fromId],m=!1;e:for(let h=0;h<=s;h++){let C=[];for(let k of d){let D=u.queryNeighbors(k,{direction:"both",relationTypes:a$1,limit:1e3});for(let w of D.edges){let T=w.source===k?w.target:w.source;if(!l.has(T)){if(l.add(T),E.set(T,{via:k,relation:w.relation}),T===o.toId){m=!0;break e}C.push(T);}}}d.length=0,d.push(...C);}if(!m)return {rootDir:t,found:!1,depth:0,steps:[],pathNodes:[]};let S=[o.toId],g=[],y=o.toId;for(;y!==o.fromId;){let h=E.get(y);if(!h)break;g.unshift({from:h.via,to:y,relation:h.relation}),S.unshift(h.via),y=h.via;}return {rootDir:t,found:!0,depth:g.length,steps:g,pathNodes:S}}finally{await f.close();}}function Lt(o){let t=[];if(!o.found)return t.push("Codebase path: NOT FOUND within depth limit"),t.join(`
18
+ `);t.push(`Codebase path: depth=${o.depth}`);for(let n=0;n<o.steps.length;n++){let e=o.steps[n];t.push(` ${n+1}. [${e.relation}] ${e.from} \u2192 ${e.to}`);}return t.join(`
19
+ `)}function qt(o){let t={},n=[];for(let e of o)e==="--help"||e==="-h"?t.help=true:e.startsWith("-")||n.push(e);return t.dir=n[0],t}async function Ut(o){let t=isAbsolute(o.dir??"")&&o.dir?o.dir:join(l(),o.dir??"."),n=a(t),e=c$1(t);if(existsSync(n)||await I({dir:t}),!existsSync(e))throw new Error(`db not found at ${e} \u2014 run \`easbot codebase index\` first`);let{CodeBase:s}=await import('./code-base-BSRUQYXN.mjs'),{DEFAULT_EMBEDDING_CONFIG:a$1,DEFAULT_INDEXER_CONFIG:i,DEFAULT_PARSER_CONFIG:r,DEFAULT_SEARCH_CONFIG:c}=await import('@easbot/types'),{CodebaseStdioServer:b}=await import('./stdio-server-BZYPM34X.mjs'),p="0.0.0";try{let d=dirname(fileURLToPath(import.meta.url));for(let m=0;m<8;m++){try{let g=JSON.parse(readFileSync(join(d,"package.json"),"utf-8"));if(g?.name==="@easbot/codebase"&&typeof g.version=="string"){p=g.version;break}}catch{}let S=dirname(d);if(S===d)break;d=S;}}catch{}let f=new s({workspaceDir:t,database:{path:e,walMode:true},embedding:a$1,indexer:i,parser:r,search:c,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});await f.initialize();let u={id:"easbot-codebase-mcp",name:"EASBot Codebase MCP",version:p,transportType:ServerTransportType.STDIO},l$1=await b.start(f,u);return {rootDir:t,tools:l$1.tools}}var Sn=Log.create({service:"codebase-cmd-callers"});function Bt(o){let t={maxResults:20},n=[];for(let e of o)if(e==="--help"||e==="-h")t.help=true;else if(e==="--json")t.json=true;else if(e.startsWith("--file="))t.file=e.slice(7);else if(e.startsWith("--kind="))t.kind=e.slice(7);else if(e.startsWith("--max=")){let s=parseInt(e.slice(6),10);Number.isFinite(s)&&s>0&&(t.maxResults=s);}else e.startsWith("--dir=")?t.dir=e.slice(6):e.startsWith("-")||n.push(e);return n.length>0&&(t.symbol=n[0]),t}async function Wt(o){if(!o.symbol&&!o.nodeId)throw new Error("callers command requires a <symbol> or --nodeId argument");let t=o.dir&&isAbsolute(o.dir)?o.dir:join(l(),o.dir??"."),n=Date.now(),s=await h({workspaceDir:t,rootDir:t},{name:o.symbol,nodeId:o.nodeId,file:o.file,kind:o.kind,maxResults:o.maxResults});return Sn.debug("callers command done",{symbol:o.symbol,count:s.callers.length,rootDir:t}),{rootDir:t,serviceResult:s,durationMs:Date.now()-n}}function Gt(o){let{serviceResult:t,rootDir:n}=o,e=[],s=t.root?.name??"?",a=t.truncated?"+":"";if(e.push(`Callers of \`${s}\` (${t.callers.length}${a}) [${n}]`),t.callers.length===0)e.push(" (no incoming edges)");else for(let i of t.callers)e.push(` - [${i.relation}] \`${i.name}\` ${i.filePath}:${i.startLine}`);return t.callers.length>0&&(e.push(""),e.push("\u{1F4A1} Use `easbot codebase node <name>` to read full source of any caller.")),e.join(`
20
+ `)}var kn=Log.create({service:"codebase-cmd-callees"});function zt(o){let t={maxResults:20},n=[];for(let e of o)if(e==="--help"||e==="-h")t.help=true;else if(e==="--json")t.json=true;else if(e.startsWith("--file="))t.file=e.slice(7);else if(e.startsWith("--kind="))t.kind=e.slice(7);else if(e.startsWith("--max=")){let s=parseInt(e.slice(6),10);Number.isFinite(s)&&s>0&&(t.maxResults=s);}else e.startsWith("--dir=")?t.dir=e.slice(6):e.startsWith("-")||n.push(e);return n.length>0&&(t.symbol=n[0]),t}async function Jt(o){if(!o.symbol&&!o.nodeId)throw new Error("callees command requires a <symbol> or --nodeId argument");let t=o.dir&&isAbsolute(o.dir)?o.dir:join(l(),o.dir??"."),n=Date.now(),s=await i({workspaceDir:t,rootDir:t},{name:o.symbol,nodeId:o.nodeId,file:o.file,kind:o.kind,maxResults:o.maxResults});return kn.debug("callees command done",{symbol:o.symbol,count:s.callers.length,rootDir:t}),{rootDir:t,serviceResult:s,durationMs:Date.now()-n}}function Kt(o){let{serviceResult:t,rootDir:n}=o,e=[],s=t.root?.name??"?",a=t.truncated?"+":"";if(e.push(`Callees of \`${s}\` (${t.callers.length}${a}) [${n}]`),t.callers.length===0)e.push(" (no outgoing edges)");else for(let i of t.callers)e.push(` - [${i.relation}] \`${i.name}\` ${i.filePath}:${i.startLine}`);return t.callers.length>0&&(e.push(""),e.push("\u{1F4A1} Use `easbot codebase node <name>` to read full source of any callee.")),e.join(`
21
+ `)}var Dn=Log.create({service:"codebase-cmd-explore"});function Vt(o){let t={maxFiles:5,maxSymbols:3,depth:1,includeContent:true},n=[];for(let e of o)if(e==="--help"||e==="-h")t.help=true;else if(e==="--json")t.json=true;else if(e==="--no-content")t.includeContent=false;else if(e.startsWith("--file="))t.file=e.slice(7);else if(e.startsWith("--kind="))t.kind=e.slice(7);else if(e.startsWith("--max-files=")){let s=parseInt(e.slice(12),10);Number.isFinite(s)&&s>0&&(t.maxFiles=s);}else if(e.startsWith("--max-symbols=")){let s=parseInt(e.slice(14),10);Number.isFinite(s)&&s>0&&(t.maxSymbols=s);}else if(e.startsWith("--depth=")){let s=parseInt(e.slice(8),10);Number.isFinite(s)&&s>0&&(t.depth=s);}else e.startsWith("--intent=")?t.intent=e.slice(9):e.startsWith("--dir=")?t.dir=e.slice(6):e.startsWith("-")||n.push(e);return n.length>0&&(t.query=n.join(" ")),t}async function Ht(o){if(!o.query)throw new Error("explore command requires a <query> argument");let t=o.dir&&isAbsolute(o.dir)?o.dir:join(l(),o.dir??"."),n=Date.now(),s=await j({workspaceDir:t,rootDir:t},{query:o.query,file:o.file,kind:o.kind,maxFiles:o.maxFiles,maxSymbols:o.maxSymbols,depth:o.depth,includeContent:o.includeContent,intent:o.intent});return Dn.debug("explore command done",{query:o.query,totalHits:s.totalHits,entryPoints:s.entryPoints.length,rootDir:t}),{rootDir:t,serviceResult:s,durationMs:Date.now()-n}}async function Yt(o){let t={pendingFiles:[],toolName:"codebase_explore",writeToDisk:false};return await D(o.serviceResult,t)}var Qt={languages:[{value:"zh-CN",name:"\u7B80\u4F53\u4E2D\u6587",example:"\u4F60\u597D\uFF0CEASBOT\uFF01",supported:true},{value:"en-US",name:"English (United States)",example:"Hello, EASBOT!",supported:true}]};var jn=Qt.languages,vn=jn.filter(o=>o.supported).map(o=>o.value),U={defaultLocale:"zh-CN",locales:vn},G={},K=(o,t)=>{let n=G[o]||{translation:{}};return G[o]={translation:{...n.translation,...t.translation}},G[o]},V=(o=U.defaultLocale)=>(G[o]||K(o,{translation:{}}),{locale:o,resources:G[o]||{translation:{}}});var On={translation:{"cli.banner.title":"easbot-codebase \u2014 \u4EE3\u7801\u77E5\u8BC6\u56FE\u8C31","cli.banner.usage":"\u7528\u6CD5: easbot-codebase <command> [options]","cli.banner.section.lifecycle":"\u547D\u4EE4\uFF08\u751F\u547D\u5468\u671F\uFF09:","cli.banner.section.graph":"\u547D\u4EE4\uFF08\u56FE\u67E5\u8BE2\uFF09:","cli.banner.section.external":"\u5916\u90E8\u63A5\u53E3:","cli.banner.hint.run_help":"\u8FD0\u884C `easbot codebase <command> --help` \u67E5\u770B\u8BE6\u60C5\u3002","cli.banner.local.title":"\u72EC\u7ACB CLI:","cli.banner.local.body":"\u672C\u5305\u540C\u65F6\u4F5C\u4E3A\u72EC\u7ACB CLI `easbot-codebase` \u53D1\u5E03\uFF0C\u53EF\u72EC\u7ACB\u4F7F\u7528\u3002","cli.banner.local.agent":"Agent CLI \u7528\u6237: `easbot codebase <command> ...`","cli.banner.local.standalone":"\u72EC\u7ACB\u7528\u6237: `easbot-codebase <command> ...`","cli.cmd.init.summary":"init [dir] \u5728\u76EE\u6807\u76EE\u5F55\u521D\u59CB\u5316 .easbot/codebase.json","cli.cmd.index.summary":"index [dir] \u6784\u5EFA\u5B8C\u6574\u7D22\u5F15","cli.cmd.sync.summary":"sync \u8FD0\u884C\u589E\u91CF\u540C\u6B65","cli.cmd.recreate.summary":"recreate \u4E22\u5F03\u6574\u4E2A\u6570\u636E\u5E93\u5E76\u91CD\u65B0\u521D\u59CB\u5316","cli.cmd.clear.summary":"clear \u6E05\u7A7A\u6240\u6709\u8282\u70B9/\u8FB9\uFF08\u4FDD\u7559 config.json\uFF09","cli.cmd.status.summary":"status \u663E\u793A\u7D22\u5F15\u72B6\u6001 / \u6570\u636E\u5E93 / \u914D\u7F6E","cli.cmd.doctor.summary":"doctor \u8FD0\u884C\u5065\u5EB7\u68C0\u67E5\uFF08\u540E\u7AEF\u53EF\u7528\u6027\u7B49\uFF09","cli.cmd.config.summary":"config \u8BFB\u53D6/\u8BBE\u7F6E .easbot/codebase.json \u5B57\u6BB5","cli.cmd.upgrade.summary":"upgrade \u5F53 extraction_version \u8FC7\u65F6\u65F6\u66F4\u65B0\u5143\u6570\u636E","cli.cmd.embed.summary":"embed \u751F\u6210\u8282\u70B9\u5D4C\u5165\u5411\u91CF","cli.cmd.watch.summary":"watch \u76D1\u542C\u5DE5\u4F5C\u533A\u6587\u4EF6\u53D8\u66F4\uFF08\u81EA\u52A8\u540C\u6B65\uFF09","cli.cmd.stop.summary":"stop \u505C\u6B62\u6B63\u5728\u8FD0\u884C\u7684\u6587\u4EF6\u76D1\u542C\u5668","cli.cmd.query.summary":"query <q...> \u6DF7\u5408\u641C\u7D22\uFF08FTS + \u5411\u91CF + \u57FA\u7840\uFF09","cli.cmd.node.summary":"node <name|id> \u663E\u793A\u5355\u4E2A\u8282\u70B9\u7684\u8BE6\u60C5","cli.cmd.context.summary":"context <id> \u6784\u5EFA\u8282\u70B9\u5468\u56F4\u7684\u5B50\u56FE\u4E0A\u4E0B\u6587","cli.cmd.impact.summary":"impact <id> \u5F71\u54CD\u534A\u5F84\uFF08BFS \u5165\u8FB9\uFF09","cli.cmd.callers.summary":"callers <sym> \u8C01\u8C03\u7528\u4E86 <symbol>","cli.cmd.callees.summary":"callees <sym> <symbol> \u8C03\u7528\u4E86\u8C01","cli.cmd.explore.summary":"explore <q> \u4E3B\u5DE5\u5177 \u2014 \u4E00\u6B21\u8C03\u7528\u8FD4\u56DE\u6E90\u7801 + \u8C03\u7528\u94FE","cli.cmd.dead_code.summary":"dead-code \u67E5\u627E\u672A\u4F7F\u7528\u7684\u7B26\u53F7","cli.cmd.circular.summary":"circular \u68C0\u6D4B\u5FAA\u73AF\u4F9D\u8D56","cli.cmd.path.summary":"path <from> <to> \u67E5\u627E\u4E24\u4E2A\u8282\u70B9\u4E4B\u95F4\u7684\u6700\u77ED\u8DEF\u5F84","cli.cmd.mcp.summary":"mcp [dir] \u542F\u52A8 stdio MCP \u670D\u52A1\u5668\uFF08\u66B4\u9732 9 \u4E2A codebase \u5DE5\u5177\uFF09","cli.cmd.init.description":"\u5728\u76EE\u6807\u76EE\u5F55\u521D\u59CB\u5316 .easbot/codebase.json","cli.cmd.index.description":"\u6784\u5EFA\u5B8C\u6574\u7D22\u5F15\uFF08\u7F3A\u5931 db \u65F6\u81EA\u52A8\u521B\u5EFA\uFF09","cli.cmd.sync.description":"\u8FD0\u884C\u589E\u91CF\u540C\u6B65\uFF08\u4EC5\u53D8\u66F4\u8FC7\u7684\u6587\u4EF6\uFF09","cli.cmd.recreate.description":"\u4E22\u5F03\u6574\u4E2A\u6570\u636E\u5E93\u5E76\u91CD\u65B0\u521D\u59CB\u5316","cli.cmd.clear.description":"\u6E05\u7A7A\u6240\u6709\u8282\u70B9/\u8FB9\uFF08\u4FDD\u7559 config.json\uFF09","cli.cmd.status.description":"\u663E\u793A\u7D22\u5F15\u72B6\u6001 / \u6570\u636E\u5E93 / \u914D\u7F6E","cli.cmd.doctor.description":"\u8FD0\u884C\u5065\u5EB7\u68C0\u67E5\uFF08\u540E\u7AEF / FTS / parser\uFF09","cli.cmd.config.description":"\u8BFB\u53D6/\u8BBE\u7F6E .easbot/codebase.json \u5B57\u6BB5","cli.cmd.upgrade.description":"extraction_version \u8FC7\u65F6\u65F6\u66F4\u65B0\u5143\u6570\u636E","cli.cmd.embed.description":"\u751F\u6210 / \u68C0\u67E5\u8282\u70B9\u5D4C\u5165\u5411\u91CF\uFF08dry-run / pending-list\uFF09","cli.cmd.watch.description":"\u76D1\u542C\u5DE5\u4F5C\u533A\u6587\u4EF6\u53D8\u66F4\uFF08\u81EA\u52A8\u540C\u6B65\uFF09","cli.cmd.stop.description":"\u505C\u6B62\u6B63\u5728\u8FD0\u884C\u7684\u6587\u4EF6\u76D1\u542C\u5668","cli.cmd.query.description":"\u6DF7\u5408\u641C\u7D22\uFF08FTS + \u5411\u91CF + \u57FA\u7840\uFF09","cli.cmd.node.description":"\u663E\u793A\u5355\u4E2A\u8282\u70B9\u7684\u8BE6\u60C5","cli.cmd.context.description":"\u6784\u5EFA\u8282\u70B9\u5468\u56F4\u7684\u5B50\u56FE\u4E0A\u4E0B\u6587","cli.cmd.impact.description":"\u5F71\u54CD\u534A\u5F84\uFF08BFS \u5165\u8FB9\uFF09","cli.cmd.callers.description":"\u8C01\u8C03\u7528\u4E86 <symbol>\uFF08\u5165\u8FB9\uFF09","cli.cmd.callees.description":"<symbol> \u8C03\u7528\u4E86\u8C01\uFF08\u51FA\u8FB9\uFF09","cli.cmd.explore.description":"\u4E3B\u5DE5\u5177 \u2014 \u4E00\u6B21\u8C03\u7528\u8FD4\u56DE\u6E90\u7801 + \u8C03\u7528\u94FE","cli.cmd.dead_code.description":"\u67E5\u627E\u672A\u4F7F\u7528\u7684\u7B26\u53F7","cli.cmd.circular.description":"\u68C0\u6D4B\u5FAA\u73AF\u4F9D\u8D56\uFF08Tarjan SCC\uFF09","cli.cmd.path.description":"\u67E5\u627E\u4E24\u4E2A\u8282\u70B9\u4E4B\u95F4\u7684\u6700\u77ED\u8DEF\u5F84","cli.cmd.mcp.description":"\u542F\u52A8 stdio MCP \u670D\u52A1\u5668\uFF08\u66B4\u9732 9 \u4E2A codebase \u5DE5\u5177\uFF09","cli.shared.show_help":"\u663E\u793A\u6B64\u5E2E\u52A9","cli.init.usage":"\u7528\u6CD5: easbot codebase init [dir] [--force]","cli.init.description":"\u5728\u76EE\u6807\u76EE\u5F55\u521D\u59CB\u5316 .easbot/codebase.json\u3002","cli.init.creates":"\u521B\u5EFA .easbot/codebase.json\uFF0C\u9ED8\u8BA4\u540E\u7AEF\u4E3A better-sqlite3\u3002","cli.init.opt.force":"--force, -f \u8986\u76D6\u5DF2\u5B58\u5728\u7684 config.json","cli.init.exists":"codebase \u914D\u7F6E\u5DF2\u5B58\u5728\u4E8E {{path}}\uFF08\u4F7F\u7528 --force \u8986\u76D6\uFF09","cli.init.created":"\u2713 codebase \u5DF2\u5728 {{path}} \u521D\u59CB\u5316","cli.status.usage":"\u7528\u6CD5: easbot codebase status [--json] [dir]","cli.doctor.usage":"\u7528\u6CD5: easbot codebase doctor [dir]","cli.index.usage":"\u7528\u6CD5: easbot codebase index [dir] [--embed] [--no-embed] [--batch=N] [--json]","cli.index.description":"\u4E3A\u76EE\u6807\u76EE\u5F55\u6784\u5EFA\u5B8C\u6574\u7D22\u5F15\u3002","cli.index.auto_init":"\u5982\u679C .easbot/codebase.json \u4E0D\u5B58\u5728\u4F1A\u81EA\u52A8\u521D\u59CB\u5316\u3002","cli.index.opt.embed":"--embed \u751F\u6210\u8282\u70B9\u5D4C\u5165\u5411\u91CF\uFF08\u9ED8\u8BA4\u8DF3\u8FC7\uFF09","cli.index.opt.no_embed":"--no-embed \u540C\u9ED8\u8BA4\uFF08\u8DF3\u8FC7\u5D4C\u5165\uFF09","cli.index.opt.batch":"--batch=N \u7D22\u5F15\u6279\u5927\u5C0F\uFF08\u9ED8\u8BA4 50\uFF09","cli.index.opt.json":"--json \u4EE5 JSON \u8F93\u51FA\uFF08\u65E0 ANSI \u989C\u8272\uFF09","cli.sync.usage":"\u7528\u6CD5: easbot codebase sync [--embed] [--no-embed] [--quiet] [--json] [dir]","cli.sync.description":"\u8FD0\u884C\u589E\u91CF\u540C\u6B65\uFF08\u4EC5\u589E/\u6539/\u5220\u53D8\u66F4\u8FC7\u7684\u6587\u4EF6\uFF09\u3002","cli.sync.auto_version":"\u6210\u529F\u65F6\u81EA\u52A8\u66F4\u65B0 meta['indexed_with_version']\u3002","cli.sync.opt.embed":"--embed \u542F\u7528\u8282\u70B9\u5D4C\u5165\u5411\u91CF\uFF08\u9ED8\u8BA4\u5173\u95ED\uFF0C\u4EC5 FTS\uFF09","cli.sync.opt.no_embed":"--no-embed \u663E\u5F0F\u7981\u7528\u5D4C\u5165\u5411\u91CF\uFF08\u9ED8\u8BA4\uFF09","cli.sync.opt.quiet":"--quiet, -q \u4EC5\u6253\u5370\u6458\u8981","cli.sync.opt.json":"--json \u4EE5 JSON \u8F93\u51FA\uFF08\u65E0 ANSI \u989C\u8272\uFF09","cli.recreate.usage":"\u7528\u6CD5: easbot codebase recreate [--keep-config] [--force] [dir]","cli.recreate.description":"\u4E22\u5F03\u6574\u4E2A\u6570\u636E\u5E93\uFF08codebase.db + -wal + -shm\uFF09\u5E76\u91CD\u65B0\u521D\u59CB\u5316\u3002","cli.recreate.equivalent":"\u7B49\u4EF7\u4E8E codegraph `recreate()`\uFF0C\u7528\u4E8E\u5B89\u5168\u7684\u7D22\u5F15\u6062\u590D\u3002","cli.recreate.opt.keep_config":"--keep-config \u4FDD\u7559 .easbot/codebase.json\uFF08\u4EC5\u5220\u9664 db\uFF09","cli.recreate.opt.force":"--force, -f \u8DF3\u8FC7\u5B89\u5168\u786E\u8BA4\uFF08\u7528\u4E8E\u811A\u672C\uFF09","cli.recreate.opt.json":"--json \u4EE5 JSON \u683C\u5F0F\u8F93\u51FA","cli.recreate.warn":"\u26A0\uFE0F \u8FD9\u4F1A\u5220\u9664\u6574\u4E2A\u7D22\u5F15\u3002\u8BF7\u4E4B\u540E\u8FD0\u884C `index`\u3002","cli.clear.usage":"\u7528\u6CD5: easbot codebase clear [--keep-embeddings] [--force] [dir]","cli.clear.description":"\u6E05\u7A7A\u6240\u6709\u8282\u70B9/\u8FB9/file_hashes\uFF1B\u4FDD\u7559 config.json \u4E0E meta\u3002","cli.clear.reset_state":'index_state \u91CD\u7F6E\u4E3A "uninitialized"\uFF0C`status` \u4F1A\u5EFA\u8BAE\u8FD0\u884C `index`\u3002',"cli.clear.opt.keep_embeddings":"--keep-embeddings \u4FDD\u7559 node_embeddings / embedding_cache","cli.clear.opt.force":"--force, -f \u8DF3\u8FC7\u5B89\u5168\u786E\u8BA4\uFF08\u7528\u4E8E\u811A\u672C\uFF09","cli.clear.opt.json":"--json \u4EE5 JSON \u683C\u5F0F\u8F93\u51FA","cli.clear.hint":"\u{1F4A1} \u5982\u679C\u60F3\u5220\u9664\u6574\u4E2A db \u6587\u4EF6\uFF0C\u8BF7\u4F7F\u7528 `recreate`\u3002","cli.config.usage":"\u7528\u6CD5: easbot codebase config <get|set> [key] [value] [--json] [dir]","cli.config.description":"\u8BFB\u53D6\u6216\u5199\u5165 .easbot/codebase.json \u5B57\u6BB5\u3002","cli.config.subcommands":"\u5B50\u547D\u4EE4:","cli.config.get":"get [key] \u663E\u793A\u5168\u90E8\u5B57\u6BB5\uFF08\u6216\u67D0\u4E2A\u5B57\u6BB5\uFF09","cli.config.set":"set <key> <value> \u66F4\u65B0\u67D0\u4E2A\u5B57\u6BB5\uFF08\u5FC5\u987B\u5728\u767D\u540D\u5355\u4E2D\uFF09","cli.config.allowed_keys":"\u5141\u8BB8\u7684\u952E: backend, schema_version, extraction_version, index_state","cli.config.opt.json":"--json \u4EE5 JSON \u8F93\u51FA\uFF08\u65E0 ANSI \u989C\u8272\uFF09","cli.config.no_subcommand":"config \u9700\u8981\u5B50\u547D\u4EE4: get | set","cli.config.unknown_subcommand":"\u672A\u77E5\u7684 config \u5B50\u547D\u4EE4: {{subcommand}}","cli.upgrade.usage":"\u7528\u6CD5: easbot codebase upgrade [--schema] [--force] [dir]","cli.upgrade.description":"\u5F53 indexed_with_extraction_version \u8FC7\u65F6\u65F6\u66F4\u65B0\u5143\u6570\u636E\u3002","cli.upgrade.does_not_delete":"\u4E0D\u4F1A\u5220\u9664\u6570\u636E \u2014 \u4F7F\u7528 `recreate` \u5220\u9664\u6574\u4E2A db\u3002","cli.upgrade.opt.schema":"--schema \u540C\u65F6\u91CD\u8DD1 ensureSchema\uFF08\u5E42\u7B49\u7684 CREATE TABLE IF NOT EXISTS\uFF09","cli.upgrade.opt.force":"--force, -f \u5373\u4F7F\u672A\u8FC7\u671F\u4E5F\u66F4\u65B0\u7248\u672C","cli.embed.usage":"\u7528\u6CD5: easbot codebase embed [--all] [--dry-run|-n] [--pending-list|-p] [--batch=N] [--json] [dir]","cli.embed.description":"\u4E3A node_embeddings \u4E2D\u7F3A\u5931\u7684\u8282\u70B9\u751F\u6210\u5D4C\u5165\u5411\u91CF\u3002","cli.embed.statistical_only":"CLI \u4EC5\u505A\u7EDF\u8BA1 \u2014 \u771F\u6B63\u7684\u5D4C\u5165\u751F\u6210\u9700\u8981","cli.embed.repl_required":"\u5728\u6CE8\u5165 EmbeddingModel \u7684 `easbot` REPL \u4F1A\u8BDD\u4E2D\u5B8C\u6210\u3002","cli.embed.opt.all":"--all \u5F3A\u5236\u4E3A\u6240\u6709\u8282\u70B9\u91CD\u65B0\u751F\u6210","cli.embed.opt.dry_run":"--dry-run, -n \u4EC5\u6253\u5370\u7EDF\u8BA1\uFF08CLI \u9ED8\u8BA4\u884C\u4E3A\uFF09","cli.embed.opt.pending":"--pending-list, -p \u5217\u51FA\u5F85\u5D4C\u5165\u7684\u8282\u70B9 id","cli.embed.opt.batch":"--batch=N \u5D4C\u5165\u6279\u5927\u5C0F\uFF08\u9ED8\u8BA4 10\uFF09","cli.embed.opt.json":"--json \u4EE5 JSON \u8F93\u51FA","cli.embed.env.heading":"\u73AF\u5883\u53D8\u91CF:","cli.embed.env.model":"EASBOT_EMBEDDING_MODEL \u5982 openai/text-embedding-3-small","cli.query.usage":"\u7528\u6CD5: easbot codebase query <q...> [--language=<lang>] [--ast=<type>] [--max=N] [--no-edges] [--no-vector|--no-embed] [--json] [--dir=<dir>]","cli.query.description":"\u5BF9\u5DF2\u7D22\u5F15\u4EE3\u7801\u8282\u70B9\u505A\u6DF7\u5408\u641C\u7D22\uFF08FTS + \u5411\u91CF + \u57FA\u7840\uFF09\u3002","cli.query.aliases":"\u522B\u540D: search","cli.query.opt.language":"--language=<lang> \u6309\u8BED\u8A00\u8FC7\u6EE4\uFF08ts / js / py / go / ...\uFF09","cli.query.opt.ast":"--ast=<type> \u6309 AST \u7C7B\u578B\u8FC7\u6EE4\uFF08class_declaration / function_declaration / ...\uFF09","cli.query.opt.max":"--max=<N> \u6700\u5927\u7ED3\u679C\u6570\uFF08\u9ED8\u8BA4 20\uFF09","cli.query.opt.no_edges":"--no-edges \u7ED3\u679C\u4E2D\u4E0D\u5305\u542B\u8FB9\uFF08\u9ED8\u8BA4: \u5305\u542B\uFF09","cli.query.opt.no_vector":"--no-vector / --no-embed \u7981\u7528\u5411\u91CF\u641C\u7D22\uFF08\u4EC5 FTS + \u57FA\u7840\uFF0C\u9ED8\u8BA4: \u542F\u7528\u5411\u91CF\uFF09","cli.query.opt.json":"--json JSON \u8F93\u51FA","cli.query.opt.dir":"--dir=<dir> \u76EE\u6807\u5DE5\u4F5C\u533A\uFF08\u9ED8\u8BA4: cwd\uFF09","cli.node.usage":"\u7528\u6CD5: easbot codebase node <name|id> [--file=<path>] [--kind=<kind>] [--edges] [--max=N] [--json] [--dir=<dir>]","cli.node.description":"\u663E\u793A\u5355\u4E2A\u8282\u70B9\u7684\u8BE6\u60C5\u3002","cli.node.accepts_name":"\u63A5\u53D7\u7B26\u53F7\u540D <name>\uFF08\u5BF9 LLM \u53CB\u597D\uFF0C\u4E0E tool/MCP \u5BF9\u9F50\uFF09","cli.node.accepts_id":"\u6216\u6765\u81EA `query` / \u6570\u636E\u5E93\u7684\u539F\u59CB <node-id>\u3002","cli.node.opt.file":"--file=<path> \u540C\u540D\u7B26\u53F7\u5B58\u5728\u65F6\u7528\u4E8E\u6D88\u6B67","cli.node.opt.kind":"--kind=<kind> \u6309 AST \u7C7B\u578B\u8FC7\u6EE4/\u6D88\u6B67","cli.node.opt.edges":"--edges \u5305\u542B\u5165\u8FB9/\u51FA\u8FB9\u6C47\u603B","cli.node.opt.max":"--max=<N> \u8FB9\u6570\u91CF\u4E0A\u9650\uFF08\u9ED8\u8BA4 50\uFF09","cli.node.opt.json":"--json \u4EE5 JSON \u8F93\u51FA","cli.node.opt.dir":"--dir=<dir> \u76EE\u6807\u5DE5\u4F5C\u533A\uFF08\u9ED8\u8BA4: cwd\uFF09","cli.context.usage":"\u7528\u6CD5: easbot codebase context <id> [--depth=N] [--max=N] [--direction=<incoming|outgoing|both>] [--relation=<r1,r2,...>] [--json] [--dir=<dir>]","cli.context.description":"\u6784\u5EFA\u8282\u70B9\u5468\u56F4\u7684\u5B50\u56FE\u4E0A\u4E0B\u6587\uFF08BFS \u90BB\u63A5 N \u5C42\uFF09\u3002","cli.context.opt.depth":"--depth=<N> BFS \u6DF1\u5EA6\uFF08\u9ED8\u8BA4 2\uFF09","cli.context.opt.max":"--max=<N> \u6700\u5927\u8282\u70B9\u6570\uFF08\u9ED8\u8BA4 100\uFF09","cli.context.opt.direction":"--direction=<dir> incoming | outgoing | both\uFF08\u9ED8\u8BA4 both\uFF09","cli.context.opt.relation":"--relation=<r1,r2,...> \u6309\u5173\u7CFB\u7C7B\u578B\u8FC7\u6EE4\uFF08CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS / USES / REFERENCES\uFF09","cli.context.opt.json":"--json \u4EE5 JSON \u8F93\u51FA","cli.context.opt.dir":"--dir=<dir> \u76EE\u6807\u5DE5\u4F5C\u533A\uFF08\u9ED8\u8BA4: cwd\uFF09","cli.impact.usage":"\u7528\u6CD5: easbot codebase impact <id> [-d=N | --depth=N] [--relation=<r1,r2,...>] [--json] [--dir=<dir>]","cli.impact.description":"\u5F71\u54CD\u534A\u5F84: BFS \u5165\u5411 CALLS / REFERENCES / USES / IMPORTS / TYPE_REFERENCES\uFF0C\u6309\u6DF1\u5EA6\u5206\u6876\u3002","cli.impact.opt.depth":"--depth=<N> BFS \u6DF1\u5EA6\uFF08\u9ED8\u8BA4 3\uFF09","cli.impact.opt.relation":"--relation=<r1,r2,...> \u6309\u5173\u7CFB\u7C7B\u578B\u8FC7\u6EE4","cli.impact.opt.json":"--json \u4EE5 JSON \u8F93\u51FA","cli.impact.opt.dir":"--dir=<dir> \u76EE\u6807\u5DE5\u4F5C\u533A\uFF08\u9ED8\u8BA4: cwd\uFF09","cli.callers.usage":"\u7528\u6CD5: easbot codebase callers <symbol> [--node-id=<id>] [--file=<path>] [--kind=<kind>] [--max=N] [--json] [--dir=<dir>]","cli.callers.description":"\u8C01\u8C03\u7528\u4E86 <symbol>\uFF08\u5165\u5411 CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS\uFF09\u3002","cli.callers.accepts":"\u63A5\u53D7\u7B26\u53F7\u540D <symbol>\uFF08\u5BF9 LLM \u53CB\u597D\uFF09\u6216 --node-id \u6307\u5B9A\u539F\u59CB\u8282\u70B9 id\u3002","cli.callers.opt.node_id":"--node-id=<id> \u6765\u81EA `query` / \u6570\u636E\u5E93\u7684\u539F\u59CB\u8282\u70B9 id","cli.callers.opt.file":"--file=<path> \u6587\u4EF6\u8DEF\u5F84\u6216 basename \u7528\u4E8E\u540C\u540D\u7B26\u53F7\u6D88\u6B67","cli.callers.opt.kind":"--kind=<kind> \u6309\u8282\u70B9\u7C7B\u578B\u8FC7\u6EE4\uFF08class_declaration / function_declaration / ...\uFF09","cli.callers.opt.max":"--max=<N> \u6700\u5927\u8C03\u7528\u8005\u6570\uFF08\u9ED8\u8BA4 20\uFF09","cli.callers.opt.json":"--json \u4EE5 JSON \u8F93\u51FA","cli.callers.opt.dir":"--dir=<dir> \u76EE\u6807\u5DE5\u4F5C\u533A\uFF08\u9ED8\u8BA4: cwd\uFF09","cli.callees.usage":"\u7528\u6CD5: easbot codebase callees <symbol> [--node-id=<id>] [--file=<path>] [--kind=<kind>] [--max=N] [--json] [--dir=<dir>]","cli.callees.description":"<symbol> \u8C03\u7528\u4E86\u8C01\uFF08\u51FA\u5411\u8FB9\uFF09\u3002","cli.callees.accepts":"\u63A5\u53D7\u7B26\u53F7\u540D <symbol>\uFF08\u5BF9 LLM \u53CB\u597D\uFF09\u6216 --node-id \u6307\u5B9A\u539F\u59CB\u8282\u70B9 id\u3002","cli.callees.opt.node_id":"--node-id=<id> \u6765\u81EA `query` / \u6570\u636E\u5E93\u7684\u539F\u59CB\u8282\u70B9 id","cli.callees.opt.file":"--file=<path> \u6587\u4EF6\u8DEF\u5F84\u6216 basename \u7528\u4E8E\u6D88\u6B67","cli.callees.opt.kind":"--kind=<kind> \u6309\u8282\u70B9\u7C7B\u578B\u8FC7\u6EE4","cli.callees.opt.max":"--max=<N> \u6700\u5927\u88AB\u8C03\u7528\u6570\uFF08\u9ED8\u8BA4 20\uFF09","cli.callees.opt.json":"--json \u4EE5 JSON \u8F93\u51FA","cli.callees.opt.dir":"--dir=<dir> \u76EE\u6807\u5DE5\u4F5C\u533A\uFF08\u9ED8\u8BA4: cwd\uFF09","cli.explore.usage":"\u7528\u6CD5: easbot codebase explore <query> [--file=<path>] [--kind=<kind>] [--max-files=N] [--max-symbols=N] [--depth=N] [--no-content] [--intent=<ctx>] [--json] [--dir=<dir>]","cli.explore.description":"\u4E3B\u5DE5\u5177 \u2014 \u5355\u6B21\u8C03\u7528\u8FD4\u56DE\u6E90\u7801 + \u8C03\u7528\u94FE\u3002","cli.explore.query_help":"<query> \u53EF\u4EE5\u662F\u7B26\u53F7\u540D\u6216\u81EA\u7136\u8BED\u8A00\u3002","cli.explore.opt.file":"--file=<path> \u6587\u4EF6\u8DEF\u5F84\u6216 basename \u7528\u4E8E\u6D88\u6B67","cli.explore.opt.kind":"--kind=<kind> \u6309\u8282\u70B9\u7C7B\u578B\u8FC7\u6EE4","cli.explore.opt.max_files":"--max-files=<N> \u6700\u5927\u5165\u53E3\u6587\u4EF6\u6570\uFF08\u9ED8\u8BA4 5\uFF09","cli.explore.opt.max_symbols":"--max-symbols=<N> \u6BCF\u6587\u4EF6\u6700\u5927\u7B26\u53F7\u6570\uFF08\u9ED8\u8BA4 3\uFF09","cli.explore.opt.depth":"--depth=<N> \u8C03\u7528\u94FE\u7684\u90BB\u63A5\u6DF1\u5EA6\uFF08\u9ED8\u8BA4 1\uFF09","cli.explore.opt.no_content":"--no-content \u4E0D\u5305\u542B\u6E90\u7801\uFF08\u4EC5\u4F4D\u7F6E\uFF0C\u9ED8\u8BA4: \u5305\u542B\uFF09","cli.explore.opt.intent":"--intent=<ctx> \u7528\u4E8E\u6392\u5E8F\u7684 LLM \u4E0A\u4E0B\u6587\u4E32","cli.explore.opt.json":"--json \u4EE5 JSON \u8F93\u51FA","cli.explore.opt.dir":"--dir=<dir> \u76EE\u6807\u5DE5\u4F5C\u533A\uFF08\u9ED8\u8BA4: cwd\uFF09","cli.dead_code.usage":"\u7528\u6CD5: easbot codebase dead-code [--type=<t1,t2,...>] [--no-exclude-entry] [--limit=N] [--json] [--dir=<dir>]","cli.dead_code.description":"\u67E5\u627E\u65E0\u5165\u8FB9\u7684\u8282\u70B9\uFF08\u542F\u53D1\u5F0F\u6B7B\u4EE3\u7801\uFF09\u3002","cli.dead_code.opt.type":"--type=<t1,t2,...> \u4EC5\u8003\u8651\u8FD9\u4E9B AST \u7C7B\u578B","cli.dead_code.opt.no_exclude_entry":"--no-exclude-entry \u5305\u542B\u5165\u53E3\u6587\u4EF6\uFF08\u9ED8\u8BA4: \u6392\u9664\uFF09","cli.dead_code.opt.limit":"--limit=<N> \u6700\u5927\u7ED3\u679C\u6570\uFF08\u9ED8\u8BA4 100\uFF09","cli.dead_code.opt.json":"--json \u4EE5 JSON \u8F93\u51FA","cli.dead_code.opt.dir":"--dir=<dir> \u76EE\u6807\u5DE5\u4F5C\u533A\uFF08\u9ED8\u8BA4: cwd\uFF09","cli.circular.usage":"\u7528\u6CD5: easbot codebase circular [--relation=<r>] [--scope=<file|module>] [--json] [--dir=<dir>]","cli.circular.description":"\u901A\u8FC7 Tarjan SCC \u68C0\u6D4B\u5FAA\u73AF\u4F9D\u8D56\u3002","cli.circular.opt.relation":"--relation=<r> \u8DDF\u968F\u7684\u5173\u7CFB\u7C7B\u578B\uFF08\u9ED8\u8BA4 IMPORTS\uFF09","cli.circular.opt.scope":"--scope=<scope> file | module\uFF08\u9ED8\u8BA4 file\uFF09","cli.circular.opt.json":"--json \u4EE5 JSON \u8F93\u51FA","cli.circular.opt.dir":"--dir=<dir> \u76EE\u6807\u5DE5\u4F5C\u533A\uFF08\u9ED8\u8BA4: cwd\uFF09","cli.path.usage":"\u7528\u6CD5: easbot codebase path <from> <to> [-d=N | --depth=N] [--relation=<r1,r2,...>] [--json] [--dir=<dir>]","cli.path.description":"\u67E5\u627E\u4E24\u4E2A\u8282\u70B9\u4E4B\u95F4\u7684\u6700\u77ED\u8DEF\u5F84\uFF08\u6CBF CALLS / IMPORTS / TYPE_REFERENCES / USES / REFERENCES \u505A BFS\uFF09\u3002","cli.path.opt.depth":"--depth=<N> BFS \u6DF1\u5EA6\u4E0A\u9650\uFF08\u9ED8\u8BA4 6\uFF09","cli.path.opt.relation":"--relation=<r1,r2,...> \u6309\u5173\u7CFB\u7C7B\u578B\u8FC7\u6EE4","cli.path.opt.json":"--json \u4EE5 JSON \u8F93\u51FA","cli.path.opt.dir":"--dir=<dir> \u76EE\u6807\u5DE5\u4F5C\u533A\uFF08\u9ED8\u8BA4: cwd\uFF09","cli.mcp.usage":"\u7528\u6CD5: easbot codebase mcp [dir]","cli.mcp.description":"\u542F\u52A8 stdio MCP \u670D\u52A1\u5668\uFF0C\u66B4\u9732 9 \u4E2A codebase \u5DE5\u5177:","cli.mcp.tools.1":" query / node / context / impact","cli.mcp.tools.2":" callers / callees / explore","cli.mcp.tools.3":" status / doctor","cli.mcp.transport":"\u901A\u8FC7 stdio JSON-RPC \u4ECE MCP \u5BA2\u6237\u7AEF\u8FDE\u63A5\u3002","cli.watch.usage":"\u7528\u6CD5: easbot codebase watch [--debounce=N] [--interval=N] [dir]","cli.watch.description":"\u76D1\u542C\u5DE5\u4F5C\u533A\u76EE\u5F55\u7684\u6587\u4EF6\u53D8\u66F4\u5E76\u8BB0\u5F55\u4E8B\u4EF6\u3002","cli.watch.pid_file":"\u5728 .easbot/.watcher.pid \u5199\u5165 pid \u6587\u4EF6\uFF0C\u4F9B\u540E\u7EED `stop` \u4F7F\u7528\u3002","cli.watch.opt.debounce":"--debounce=N \u5355\u8DEF\u5F84\u9632\u6296\uFF08\u6BEB\u79D2\uFF0C\u9ED8\u8BA4 200\uFF09","cli.watch.opt.interval":"--interval=N \u8F6E\u8BE2\u95F4\u9694\uFF08\u6BEB\u79D2\uFF0C\u9ED8\u8BA4 500\uFF09","cli.watch.note":"\u6CE8\u610F: \u8BE5\u547D\u4EE4\u4F1A\u963B\u585E\u3002\u6309 Ctrl+C \u9000\u51FA\u3002","cli.stop.usage":"\u7528\u6CD5: easbot codebase stop [dir]","cli.stop.description":"\u505C\u6B62\u7531 .easbot/.watcher.pid \u6807\u8BC6\u7684\u8FD0\u884C\u4E2D\u76D1\u542C\u5668\u3002","cli.stop.opt.force":"--force, -f \u5FFD\u7565\u9519\u8BEF\u5E76\u5F3A\u5236\u6E05\u7406 pid \u6587\u4EF6","cli.shared.options_heading":"\u9009\u9879:","cli.shared.subcommands_heading":"\u5B50\u547D\u4EE4:","cli.shared.environment_heading":"\u73AF\u5883\u53D8\u91CF:","cli.unknown_command":"\u672A\u77E5\u547D\u4EE4: {{command}}","cli.help_hint":"\u8FD0\u884C `easbot codebase --help` \u67E5\u770B\u53EF\u7528\u547D\u4EE4\u3002","cli.signal_cleanup":"[codebase] \u6536\u5230 {{signal}}\uFF0C\u6B63\u5728\u6E05\u7406...","cli.command_failed":"codebase {{command}} \u6267\u884C\u5931\u8D25: {{message}}"}},Xt=On;var Tn={translation:{"cli.banner.title":"easbot-codebase \u2014 code knowledge graph ecosystem","cli.banner.usage":"Usage: easbot-codebase <command> [options]","cli.banner.section.lifecycle":"Commands (lifecycle):","cli.banner.section.graph":"Commands (graph query):","cli.banner.section.external":"External:","cli.banner.hint.run_help":"Run `easbot codebase <command> --help` for details.","cli.banner.local.title":"Local CLI:","cli.banner.local.body":"This package is also published as `easbot-codebase` for standalone use.","cli.banner.local.agent":"Agent CLI users: `easbot codebase <command> ...`","cli.banner.local.standalone":"Standalone users: `easbot-codebase <command> ...`","cli.cmd.init.summary":"init [dir] Initialize .easbot/codebase.json in the target directory","cli.cmd.index.summary":"index [dir] Build the full index","cli.cmd.sync.summary":"sync Run incremental sync","cli.cmd.recreate.summary":"recreate Discard the entire db and re-init","cli.cmd.clear.summary":"clear Clear all nodes/edges (keep config.json)","cli.cmd.status.summary":"status Show index state / db / config","cli.cmd.doctor.summary":"doctor Run health checks (backend availability, etc.)","cli.cmd.config.summary":"config Get/set .easbot/codebase.json fields","cli.cmd.upgrade.summary":"upgrade Update extraction_version metadata when stale","cli.cmd.embed.summary":"embed Generate node embeddings","cli.cmd.watch.summary":"watch Watch workspace for file changes (auto-sync)","cli.cmd.stop.summary":"stop Stop a running file watcher","cli.cmd.query.summary":"query <q...> Hybrid search (FTS + vector + basic)","cli.cmd.node.summary":"node <name|id> Show details for a single node","cli.cmd.context.summary":"context <id> Build sub-graph context around a node","cli.cmd.impact.summary":"impact <id> Blast radius (BFS incoming edges)","cli.cmd.callers.summary":"callers <sym> Flat list of who calls <symbol>","cli.cmd.callees.summary":"callees <sym> Flat list of what <symbol> calls","cli.cmd.explore.summary":"explore <q> PRIMARY tool \u2014 source code + caller/callee trail in one call","cli.cmd.dead_code.summary":"dead-code Find unused symbols","cli.cmd.circular.summary":"circular Detect circular dependencies","cli.cmd.path.summary":"path <from> <to> Find shortest path between two nodes","cli.cmd.mcp.summary":"mcp [dir] Start stdio MCP server (exposes 9 codebase tools)","cli.cmd.init.description":"Initialize .easbot/codebase.json in the target directory","cli.cmd.index.description":"Build the full index (creates db if missing)","cli.cmd.sync.description":"Run incremental sync (only changed files)","cli.cmd.recreate.description":"Discard the entire db and re-init","cli.cmd.clear.description":"Clear all nodes/edges (keep config.json)","cli.cmd.status.description":"Show index state / db / config","cli.cmd.doctor.description":"Run health checks (backend, FTS, parser)","cli.cmd.config.description":"Get/set .easbot/codebase.json fields","cli.cmd.upgrade.description":"Update extraction_version metadata when stale","cli.cmd.embed.description":"Generate / inspect node embeddings (dry-run / pending-list)","cli.cmd.watch.description":"Watch workspace for file changes (auto-sync)","cli.cmd.stop.description":"Stop a running file watcher","cli.cmd.query.description":"Hybrid search (FTS + vector + basic)","cli.cmd.node.description":"Show details for a single node","cli.cmd.context.description":"Build sub-graph context around a node","cli.cmd.impact.description":"Blast radius (BFS incoming edges)","cli.cmd.callers.description":"Flat list of who calls <symbol> (incoming edges)","cli.cmd.callees.description":"Flat list of what <symbol> calls (outgoing edges)","cli.cmd.explore.description":"PRIMARY tool \u2014 source code + caller/callee trail in one call","cli.cmd.dead_code.description":"Find unused symbols","cli.cmd.circular.description":"Detect circular dependencies (Tarjan SCC)","cli.cmd.path.description":"Find shortest path between two nodes","cli.cmd.mcp.description":"Start stdio MCP server (exposes 9 codebase tools)","cli.shared.show_help":"Show this help","cli.init.usage":"Usage: easbot codebase init [dir] [--force]","cli.init.description":"Initialize .easbot/codebase.json in the target directory.","cli.init.creates":"Creates .easbot/codebase.json with default backend = better-sqlite3.","cli.init.opt.force":"--force, -f Overwrite existing config.json","cli.init.exists":"codebase config already exists at {{path}} (use --force to overwrite)","cli.init.created":"\u2713 codebase initialized at {{path}}","cli.status.usage":"Usage: easbot codebase status [--json] [dir]","cli.doctor.usage":"Usage: easbot codebase doctor [dir]","cli.index.usage":"Usage: easbot codebase index [dir] [--embed] [--no-embed] [--batch=N] [--json]","cli.index.description":"Build the full index for the target directory.","cli.index.auto_init":"Auto-initializes .easbot/codebase.json if it does not exist.","cli.index.opt.embed":"--embed Generate node embeddings (default: skip)","cli.index.opt.no_embed":"--no-embed Same as default (skip embedding)","cli.index.opt.batch":"--batch=N Batch size for indexing (default 50)","cli.index.opt.json":"--json Output as JSON (no ANSI)","cli.sync.usage":"Usage: easbot codebase sync [--embed] [--no-embed] [--quiet] [--json] [dir]","cli.sync.description":"Run incremental sync (only adds/updates/deletes changed files).","cli.sync.auto_version":"Auto-updates meta['indexed_with_version'] on success.","cli.sync.opt.embed":"--embed Enable node embeddings (default off, FTS-only)","cli.sync.opt.no_embed":"--no-embed Explicitly disable embeddings (default)","cli.sync.opt.quiet":"--quiet, -q Only print summary","cli.sync.opt.json":"--json Output as JSON (no ANSI)","cli.recreate.usage":"Usage: easbot codebase recreate [--keep-config] [--force] [dir]","cli.recreate.description":"Discard the entire db (codebase.db + -wal + -shm) and re-init.","cli.recreate.equivalent":"Equivalent to codegraph `recreate()` for safe index recovery.","cli.recreate.opt.keep_config":"--keep-config Keep .easbot/codebase.json (only drop db)","cli.recreate.opt.force":"--force, -f Skip safety prompts (for scripts)","cli.recreate.warn":"\u26A0\uFE0F This deletes the entire index. Run `index` after.","cli.clear.usage":"Usage: easbot codebase clear [--keep-embeddings] [--force] [dir]","cli.clear.description":"Clear all nodes/edges/file_hashes; keep config.json and meta.","cli.clear.reset_state":'index_state is reset to "uninitialized" so `status` recommends `index`.',"cli.clear.opt.keep_embeddings":"--keep-embeddings Preserve node_embeddings / embedding_cache","cli.clear.opt.force":"--force, -f Skip safety prompts (for scripts)","cli.clear.opt.json":"--json Output as JSON","cli.clear.hint":"\u{1F4A1} Use `recreate` if you want to drop the entire db file.","cli.config.usage":"Usage: easbot codebase config <get|set> [key] [value] [--json] [dir]","cli.config.description":"Read or write .easbot/codebase.json fields.","cli.config.subcommands":"Subcommands:","cli.config.get":"get [key] Show all fields (or a specific key)","cli.config.set":"set <key> <value> Update a field (must be in allowlist)","cli.config.allowed_keys":"Allowed keys: backend, schema_version, extraction_version, index_state","cli.config.opt.json":"--json Output as JSON (no ANSI)","cli.config.no_subcommand":"config requires a subcommand: get | set","cli.config.unknown_subcommand":"Unknown config subcommand: {{subcommand}}","cli.upgrade.usage":"Usage: easbot codebase upgrade [--schema] [--force] [dir]","cli.upgrade.description":"Update indexed_with_extraction_version metadata when stale.","cli.upgrade.does_not_delete":"Does NOT delete data \u2014 use `recreate` to drop the db entirely.","cli.upgrade.opt.schema":"--schema Also re-run ensureSchema (idempotent CREATE TABLE IF NOT EXISTS)","cli.upgrade.opt.force":"--force, -f Update version even when not stale","cli.embed.usage":"Usage: easbot codebase embed [--all] [--dry-run|-n] [--pending-list|-p] [--batch=N] [--json] [dir]","cli.embed.description":"Generate node embeddings for nodes missing from node_embeddings.","cli.embed.statistical_only":"CLI is statistical-only \u2014 actual embedding generation requires","cli.embed.repl_required":"an `easbot` REPL session with an injected EmbeddingModel.","cli.embed.opt.all":"--all Force regenerate for all nodes","cli.embed.opt.dry_run":"--dry-run, -n Print statistics only (default behavior in CLI)","cli.embed.opt.pending":"--pending-list, -p List node ids that are pending embedding","cli.embed.opt.batch":"--batch=N Embedding batch size (default 10)","cli.embed.opt.json":"--json Output as JSON","cli.embed.env.heading":"Environment:","cli.embed.env.model":"EASBOT_EMBEDDING_MODEL e.g. openai/text-embedding-3-small","cli.query.usage":"Usage: easbot codebase query <q...> [--language=<lang>] [--ast=<type>] [--max=N] [--no-edges] [--no-vector|--no-embed] [--json] [--dir=<dir>]","cli.query.description":"Hybrid search (FTS + vector + basic) over indexed code nodes.","cli.query.aliases":"Aliases: search","cli.query.opt.language":"--language=<lang> Filter by language (ts / js / py / go / ...)","cli.query.opt.ast":"--ast=<type> Filter by AST type (class_declaration / function_declaration / ...)","cli.query.opt.max":"--max=<N> Max results (default 20)","cli.query.opt.no_edges":"--no-edges Do not include edges in results (default: include)","cli.query.opt.no_vector":"--no-vector / --no-embed Disable vector search (FTS + basic only, default: vector on)","cli.query.opt.json":"--json JSON output","cli.query.opt.dir":"--dir=<dir> Target workspace (default: cwd)","cli.node.usage":"Usage: easbot codebase node <name|id> [--file=<path>] [--kind=<kind>] [--edges] [--max=N] [--json] [--dir=<dir>]","cli.node.description":"Show details for a single node.","cli.node.accepts_name":"Accepts a symbol <name> (LLM workflow friendly, tool/MCP-aligned)","cli.node.accepts_id":"or a raw <node-id> from `query` / database.","cli.node.opt.file":"--file=<path> Disambiguate when same-named symbols exist","cli.node.opt.kind":"--kind=<kind> Filter / disambiguate by AST kind","cli.node.opt.edges":"--edges Include incoming / outgoing edge summaries","cli.node.opt.max":"--max=<N> Edge limit (default 50)","cli.node.opt.json":"--json Output as JSON","cli.node.opt.dir":"--dir=<dir> Target workspace (default: cwd)","cli.context.usage":"Usage: easbot codebase context <id> [--depth=N] [--max=N] [--direction=<incoming|outgoing|both>] [--relation=<r1,r2,...>] [--json] [--dir=<dir>]","cli.context.description":"Build a sub-graph context around a node (BFS to N-level neighbors).","cli.context.opt.depth":"--depth=<N> BFS depth (default 2)","cli.context.opt.max":"--max=<N> Max nodes (default 100)","cli.context.opt.direction":"--direction=<dir> incoming | outgoing | both (default both)","cli.context.opt.relation":"--relation=<r1,r2,...> Filter by relation types (CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS / USES / REFERENCES)","cli.context.opt.json":"--json Output as JSON","cli.context.opt.dir":"--dir=<dir> Target workspace (default: cwd)","cli.impact.usage":"Usage: easbot codebase impact <id> [-d=N | --depth=N] [--relation=<r1,r2,...>] [--json] [--dir=<dir>]","cli.impact.description":"Blast radius: BFS incoming CALLS / REFERENCES / USES / IMPORTS / TYPE_REFERENCES, bucketed by depth.","cli.impact.opt.depth":"--depth=<N> BFS depth (default 3)","cli.impact.opt.relation":"--relation=<r1,r2,...> Filter by relation types","cli.impact.opt.json":"--json Output as JSON","cli.impact.opt.dir":"--dir=<dir> Target workspace (default: cwd)","cli.callers.usage":"Usage: easbot codebase callers <symbol> [--node-id=<id>] [--file=<path>] [--kind=<kind>] [--max=N] [--json] [--dir=<dir>]","cli.callers.description":"Flat list of who calls <symbol> (incoming CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS).","cli.callers.accepts":"Accepts <symbol> name (LLM-friendly) OR --node-id for raw node id.","cli.callers.opt.node_id":"--node-id=<id> Raw node id from `query` / database","cli.callers.opt.file":"--file=<path> File path or basename to disambiguate when same-named symbols exist","cli.callers.opt.kind":"--kind=<kind> Filter by node kind (class_declaration / function_declaration / ...)","cli.callers.opt.max":"--max=<N> Max callers (default 20)","cli.callers.opt.json":"--json Output as JSON","cli.callers.opt.dir":"--dir=<dir> Target workspace (default: cwd)","cli.callees.usage":"Usage: easbot codebase callees <symbol> [--node-id=<id>] [--file=<path>] [--kind=<kind>] [--max=N] [--json] [--dir=<dir>]","cli.callees.description":"Flat list of what <symbol> calls (outgoing edges).","cli.callees.accepts":"Accepts <symbol> name (LLM-friendly) OR --node-id for raw node id.","cli.callees.opt.node_id":"--node-id=<id> Raw node id from `query` / database","cli.callees.opt.file":"--file=<path> File path or basename to disambiguate","cli.callees.opt.kind":"--kind=<kind> Filter by node kind","cli.callees.opt.max":"--max=<N> Max callees (default 20)","cli.callees.opt.json":"--json Output as JSON","cli.callees.opt.dir":"--dir=<dir> Target workspace (default: cwd)","cli.explore.usage":"Usage: easbot codebase explore <query> [--file=<path>] [--kind=<kind>] [--max-files=N] [--max-symbols=N] [--depth=N] [--no-content] [--intent=<ctx>] [--json] [--dir=<dir>]","cli.explore.description":"PRIMARY tool \u2014 single call to get source code + caller/callee trail.","cli.explore.query_help":"<query> can be a symbol name or natural language.","cli.explore.opt.file":"--file=<path> File path or basename to disambiguate","cli.explore.opt.kind":"--kind=<kind> Filter by node kind","cli.explore.opt.max_files":"--max-files=<N> Max entry-point files (default 5)","cli.explore.opt.max_symbols":"--max-symbols=<N> Max symbols per file (default 3)","cli.explore.opt.depth":"--depth=<N> Neighbor depth for caller/callee trail (default 1)","cli.explore.opt.no_content":"--no-content Do not include source code (locations only, default: include)","cli.explore.opt.intent":"--intent=<ctx> LLM context string for ranking","cli.explore.opt.json":"--json Output as JSON","cli.explore.opt.dir":"--dir=<dir> Target workspace (default: cwd)","cli.dead_code.usage":"Usage: easbot codebase dead-code [--type=<t1,t2,...>] [--no-exclude-entry] [--limit=N] [--json] [--dir=<dir>]","cli.dead_code.description":"Find nodes with no incoming edges (heuristic dead code).","cli.dead_code.opt.type":"--type=<t1,t2,...> Only consider these AST types","cli.dead_code.opt.no_exclude_entry":"--no-exclude-entry Include entry-point files (default: exclude)","cli.dead_code.opt.limit":"--limit=<N> Max results (default 100)","cli.dead_code.opt.json":"--json Output as JSON","cli.dead_code.opt.dir":"--dir=<dir> Target workspace (default: cwd)","cli.circular.usage":"Usage: easbot codebase circular [--relation=<r>] [--scope=<file|module>] [--json] [--dir=<dir>]","cli.circular.description":"Detect circular dependencies via Tarjan SCC.","cli.circular.opt.relation":"--relation=<r> Relation type to follow (default IMPORTS)","cli.circular.opt.scope":"--scope=<scope> file | module (default file)","cli.circular.opt.json":"--json Output as JSON","cli.circular.opt.dir":"--dir=<dir> Target workspace (default: cwd)","cli.path.usage":"Usage: easbot codebase path <from> <to> [-d=N | --depth=N] [--relation=<r1,r2,...>] [--json] [--dir=<dir>]","cli.path.description":"Find shortest path between two nodes (BFS along CALLS / IMPORTS / TYPE_REFERENCES / USES / REFERENCES).","cli.path.opt.depth":"--depth=<N> BFS depth limit (default 6)","cli.path.opt.relation":"--relation=<r1,r2,...> Filter by relation types","cli.path.opt.json":"--json Output as JSON","cli.path.opt.dir":"--dir=<dir> Target workspace (default: cwd)","cli.mcp.usage":"Usage: easbot codebase mcp [dir]","cli.mcp.description":"Start a stdio MCP server exposing 9 codebase tools:","cli.mcp.tools.1":" query / node / context / impact","cli.mcp.tools.2":" callers / callees / explore","cli.mcp.tools.3":" status / doctor","cli.mcp.transport":"Connect from MCP clients via stdio JSON-RPC.","cli.watch.usage":"Usage: easbot codebase watch [--debounce=N] [--interval=N] [dir]","cli.watch.description":"Watch the workspace directory for file changes and log events.","cli.watch.pid_file":"Writes a pid file at .easbot/.watcher.pid for subsequent `stop`.","cli.watch.opt.debounce":"--debounce=N Per-path debounce in ms (default 200)","cli.watch.opt.interval":"--interval=N Polling interval in ms (default 500)","cli.watch.note":"NOTE: This command blocks. Press Ctrl+C to exit.","cli.stop.usage":"Usage: easbot codebase stop [dir]","cli.stop.description":"Stop a running watcher identified by .easbot/.watcher.pid.","cli.stop.opt.force":"--force, -f Ignore errors and clear the pid file anyway","cli.shared.options_heading":"Options:","cli.shared.subcommands_heading":"Subcommands:","cli.shared.environment_heading":"Environment:","cli.unknown_command":"Unknown command: {{command}}","cli.help_hint":"Run `easbot codebase --help` for available commands.","cli.signal_cleanup":"[codebase] received {{signal}}, cleaning up...","cli.command_failed":"codebase {{command}} failed: {{message}}"}},Zt=Tn;var $n=()=>{V("zh-CN"),V("en-US"),K("zh-CN",Xt),K("en-US",Zt);};$n();var X=new Map;var Z=new Map;var Pn=o=>{if(Z.has(o))return Z.get(o);let t=/{{\s*(\w+)\s*}}/g,n=[],e;for(;(e=t.exec(o))!==null;){let i=e[1];i&&!n.includes(i)&&n.push(i);}let s=new RegExp("{{\\s*("+n.join("|")+")\\s*}}","g"),a={keys:n,regex:s};return Z.set(o,a),a},eo=(o,t)=>{if(!o||typeof o!="string")return "";if(!t||Object.keys(t).length===0)return o;let{regex:n,keys:e}=Pn(o);return e.length===0||!e.some(a=>a in t)?o:o.replace(n,(a,i)=>{let r=t[i];return r==null?"":String(r)})},Ln=o=>{if(o&&U.locales.includes(o))return o;let t=process.env.EASBOT_LANG?.trim()||process.env.LANG?.trim();if(t){let n=t.replace(/_/g,"-");if(U.locales.includes(n))return n;let e=n.split("-")[0];if(e==="zh")return "zh-CN";if(e==="en")return "en-US"}return U.defaultLocale},to=o=>{if(!X.has(o)){let{resources:t}=V(o);X.set(o,t);}return X.get(o)},Fn=(o,t={})=>{let n=Ln(t.locale),s=to(n)?.translation[o];if(s&&typeof s=="string"){let a=eo(s,t.vars);return a!=null?String(a):String(o)}if(n!==U.defaultLocale){let i=to(U.defaultLocale)?.translation[o];if(i&&typeof i=="string"){let r=eo(i,t.vars);return r!=null?String(r):String(o)}}return String(t.fallback??o)},ee=Fn;var te=Log.create({service:"codebase-cli"});async function Wn(o){try{let{bootstrapLlm:t}=await import('@easbot/llm'),{Llm:n}=await import('./llm-MPD7FHPM.mjs');await t({target:n,cwd:o,subConfigPath:".easbot/codebase.json",embedding:!1,graph:!1});}catch(t){te.warn("bootstrapLlm failed; Llm-related features will be disabled",{error:t instanceof Error?t.message:String(t)});}}function oe(o){return resolveLocaleLang(o?.locale)}function no(o){let t=(e,s,a)=>ee(e,{locale:o,vars:a,fallback:s}),n=(e,s,a)=>{let i=zn.filter(r=>r.group===e).map(r=>` ${Jn(r.name)}${t(r.i18nKey,r.description)}`).join(`
22
+ `);return `${t(s,a)}
23
+ ${i}`};return `
24
+ \x1B[1m${t("cli.banner.title","easbot-codebase \u2014 Code Knowledge Graph for EASBot")}\x1B[0m
25
+
26
+ ${t("cli.banner.usage","Usage: easbot-codebase <command> [options]")}
27
+
28
+ ${n("lifecycle","cli.banner.section.lifecycle","Commands (lifecycle):")}
29
+
30
+ ${n("graph","cli.banner.section.graph","Commands (graph query):")}
31
+
32
+ ${n("external","cli.banner.section.external","External:")}
33
+
34
+ Run \x1B[1measbot codebase <command> --help\x1B[0m for details.
35
+
36
+ \x1B[1m${t("cli.banner.local.title","Local CLI:")}\x1B[0m
37
+ ${t("cli.banner.local.body","This package is also published as `easbot-codebase` for standalone use.")}
38
+ ${t("cli.banner.local.agent","Agent CLI users: `easbot codebase <command> ...`")}
39
+ ${t("cli.banner.local.standalone","Standalone users: `easbot-codebase <command> ...`")}
40
+
41
+ \x1B[2m$\x1B[0m easbot-codebase init ${t("cli.cmd.init.description","Initialize .easbot/codebase.json in the target directory")}
42
+ \x1B[2m$\x1B[0m easbot-codebase index ${t("cli.cmd.index.description","Build the full index (creates db if missing)")}
43
+ \x1B[2m$\x1B[0m easbot-codebase status ${t("cli.cmd.status.description","Show index state / db / config")}
44
+ \x1B[2m$\x1B[0m easbot-codebase query <q...> ${t("cli.cmd.query.description","Hybrid search (FTS + vector + basic)")}
45
+ \x1B[2m$\x1B[0m easbot-codebase --help ${t("cli.shared.show_help","Show this help")}
46
+ `}function Gn(o){let t=oe(o);console.log(no(t));}function Va(o){let t=oe(o);console.log(no(t));}var zn=[{i18nKey:"cli.cmd.init.description",name:"init [dir]",description:"Initialize .easbot/codebase.json in the target directory",group:"lifecycle"},{i18nKey:"cli.cmd.index.description",name:"index [dir]",description:"Build the full index (creates db if missing)",group:"lifecycle"},{i18nKey:"cli.cmd.sync.description",name:"sync",description:"Run incremental sync (only changed files)",group:"lifecycle"},{i18nKey:"cli.cmd.recreate.description",name:"recreate",description:"Discard the entire db and re-init",group:"lifecycle"},{i18nKey:"cli.cmd.clear.description",name:"clear",description:"Clear all nodes/edges (keep config.json)",group:"lifecycle"},{i18nKey:"cli.cmd.status.description",name:"status",description:"Show index state / db / config",group:"lifecycle"},{i18nKey:"cli.cmd.doctor.description",name:"doctor",description:"Run health checks (backend, FTS, parser)",group:"lifecycle"},{i18nKey:"cli.cmd.config.description",name:"config",description:"Get/set .easbot/codebase.json fields",group:"lifecycle"},{i18nKey:"cli.cmd.upgrade.description",name:"upgrade",description:"Update extraction_version metadata when stale",group:"lifecycle"},{i18nKey:"cli.cmd.embed.description",name:"embed-status",description:"Inspect node embeddings (statistical only \u2014 counts/pending-list). Use MCP `embed` tool to actually generate embeddings.",group:"lifecycle"},{i18nKey:"cli.cmd.watch.description",name:"watch",description:"Watch workspace for file changes (auto-sync)",group:"lifecycle"},{i18nKey:"cli.cmd.stop.description",name:"stop",description:"Stop a running file watcher",group:"lifecycle"},{i18nKey:"cli.cmd.query.description",name:"query <q...>",description:"Hybrid search (FTS + vector + basic)",group:"graph"},{i18nKey:"cli.cmd.node.description",name:"node <name|id>",description:"Show details for a single node",group:"graph"},{i18nKey:"cli.cmd.context.description",name:"context <id>",description:"Build sub-graph context around a node",group:"graph"},{i18nKey:"cli.cmd.impact.description",name:"impact <id>",description:"Blast radius (BFS incoming edges)",group:"graph"},{i18nKey:"cli.cmd.callers.description",name:"callers <symbol>",description:"Flat list of who calls <symbol> (incoming edges)",group:"graph"},{i18nKey:"cli.cmd.callees.description",name:"callees <symbol>",description:"Flat list of what <symbol> calls (outgoing edges)",group:"graph"},{i18nKey:"cli.cmd.explore.description",name:"explore <query>",description:"PRIMARY tool \u2014 source code + caller/callee trail in one call",group:"graph"},{i18nKey:"cli.cmd.dead_code.description",name:"dead-code",description:"Find unused symbols",group:"graph"},{i18nKey:"cli.cmd.circular.description",name:"circular",description:"Detect circular dependencies (Tarjan SCC)",group:"graph"},{i18nKey:"cli.cmd.path.description",name:"path <from> <to>",description:"Find shortest path between two nodes",group:"graph"},{i18nKey:"cli.cmd.mcp.description",name:"mcp [dir]",description:"Start stdio MCP server (exposes 9 codebase tools)",group:"external"}];function Jn(o){return o.length>=18?o:o+" ".repeat(18-o.length)}var oo=false;function Kn(){if(oo)return;oo=true;let o=false,t=n=>{o||(o=true,console.error(`
47
+ [codebase] received ${n}, cleaning up...`),setTimeout(()=>process.exit(130),200));};process.on("SIGINT",t),process.on("SIGTERM",t);}async function Ha(o,t){Kn();let n=oe(t),e=(i,r,c)=>ee(i,{locale:n,vars:c,fallback:r});if(await Wn(t?.cwd??process.cwd()),o.length===0)return Gn(t),{code:0,handled:false};let s=o[0],a=o.slice(1);try{switch(s){case "init":{let i=ye(a);if(i.help)return console.log(e("cli.init.usage","Usage: easbot codebase init [dir] [--force] [--json]")),console.log(""),console.log(e("cli.init.description","Initialize .easbot/codebase.json in the target directory.")),console.log(e("cli.init.creates","Creates .easbot/codebase.json with default backend = better-sqlite3.")),console.log(""),console.log(e("cli.shared.options_heading","Options:")),console.log(` ${e("cli.init.opt.force","--force, -f Overwrite existing config.json")}`),console.log(` ${e("cli.init.opt.json","--json Output as JSON (no ANSI)")}`),{code:0,handled:!0,command:s};let r=await I({...i,skipAutoSync:!1});if(i.json){let{business:b,meta:p}=r.skipped?{business:{configPath:r.configPath,backend:r.backend,schemaVersion:r.schemaVersion,created:r.created,skipped:r.skipped},meta:{action:"exists"}}:{business:{configPath:r.configPath,backend:r.backend,schemaVersion:r.schemaVersion,created:r.created,skipped:r.skipped,initialSync:r.initialSync},meta:{action:"created"}};return emitJsonOk(b,p),{code:0,handled:!0,command:s}}let c={dbPath:r.dbPath};return typeof r.migrationsApplied=="number"&&(c.migrationsApplied=r.migrationsApplied),typeof r.tablesCreated=="number"&&(c.tablesCreated=r.tablesCreated),typeof r.durationMs=="number"&&(c.durationMs=`${r.durationMs}ms`),printHuman([formatKnowledgeInit({packageName:"codebase",configPath:r.configPath,backend:r.backend,schemaVersion:r.schemaVersion,skipped:r.skipped===!0,extras:c})],{title:"init codebase workspace",boxed:!0}),{code:0,handled:!0,command:s}}case "status":{let i=Vn(a),r=await z(i);return i.json?emitJsonOk(r,{dir:i.dir??null}):printHuman([formatKnowledgeStatus(Yn(r))],{title:e("cli.cmd.status.description","Show index state / db / config"),boxed:!0}),{code:0,handled:!0,command:s}}case "doctor":{let i=Hn(a);if(i.help)return console.log(e("cli.doctor.usage","Usage: easbot codebase doctor [--dir=<dir>] [--json]")),console.log(""),console.log(e("cli.doctor.description","Run health checks (backend, FTS, parser, db integrity).")),console.log(""),console.log(e("cli.shared.options_heading","Options:")),console.log(` ${e("cli.doctor.opt.dir","--dir=<dir> Target workspace (default: cwd)")}`),console.log(` ${e("cli.doctor.opt.json","--json Output as JSON (no ANSI)")}`),{code:0,handled:!0,command:s};let r=await Se(i);return i.json?emitJsonOk(r,{healthy:r.healthy,checkCount:r.checks.length,issueCount:r.issues.length,errorCount:r.checks.filter(c=>c.severity==="error").length,warnCount:r.checks.filter(c=>c.severity==="warn").length,dir:i.dir??null}):printHuman([formatKnowledgeDoctor(Qn(r))],{title:e("cli.cmd.doctor.description","Run health checks (backend, FTS, parser)"),boxed:!0}),{code:r.healthy?0:1,handled:!0,command:s}}case "index":{let i=Ee(a);if(i.help)return console.log(e("cli.index.usage","Usage: easbot codebase index [dir] [--embed] [--no-embed] [--batch=N] [--json]")),console.log(""),console.log(e("cli.index.description","Build the full index for the target directory.")),console.log(e("cli.index.auto_init","Auto-initializes .easbot/codebase.json if it does not exist.")),console.log(""),console.log(e("cli.shared.options_heading","Options:")),console.log(` ${e("cli.index.opt.embed","--embed Generate node embeddings (default: skip)")}`),console.log(` ${e("cli.index.opt.no_embed","--no-embed Same as default (skip embedding)")}`),console.log(` ${e("cli.index.opt.batch","--batch=N Batch size for indexing (default 50)")}`),console.log(` ${e("cli.index.opt.json","--json Output as JSON (no ANSI)")}`),{code:0,handled:!0,command:s};let r=await Ce(i);return i.json?emitJsonOk(r,{success:r.success,dir:i.dir??null,noEmbed:i.noEmbed!==!1,batch:i.batch??null,verbose:i.verbose===!0,quiet:i.quiet===!0}):printHuman([ke(r)],{title:e("cli.cmd.index.description","Build the full index (creates db if missing)")}),{code:r.success?0:1,handled:!0,command:s}}case "sync":{let i=_e(a);if(i.help)return console.log(e("cli.sync.usage","Usage: easbot codebase sync [--embed] [--no-embed] [--quiet] [--json] [dir]")),console.log(""),console.log(e("cli.sync.description","Run incremental sync (only adds/updates/deletes changed files).")),console.log(e("cli.sync.auto_version","Auto-updates meta['indexed_with_version'] on success.")),console.log(""),console.log(e("cli.shared.options_heading","Options:")),console.log(` ${e("cli.sync.opt.embed","--embed Enable node embeddings (default off, FTS-only)")}`),console.log(` ${e("cli.sync.opt.no_embed","--no-embed Explicitly disable embeddings (default)")}`),console.log(` ${e("cli.sync.opt.quiet","--quiet, -q Only print summary")}`),console.log(` ${e("cli.sync.opt.json","--json Output as JSON (no ANSI)")}`),{code:0,handled:!0,command:s};let r=await Ne(i);return i.json?emitJsonOk(r,{success:r.success,quiet:i.quiet===!0,dir:i.dir??null}):printHuman([De(r)],{title:e("cli.cmd.sync.description","Run incremental sync (only changed files)")}),{code:r.success?0:1,handled:!0,command:s}}case "recreate":{let i=ve(a);if(i.help)return console.log(e("cli.recreate.usage","Usage: easbot codebase recreate [--keep-config] [--force] [--json] [dir]")),console.log(""),console.log(e("cli.recreate.description","Discard the entire db (codebase.db + -wal + -shm) and re-init.")),console.log(e("cli.recreate.equivalent","Equivalent to codegraph `recreate()` for safe index recovery.")),console.log(""),console.log(e("cli.shared.options_heading","Options:")),console.log(` ${e("cli.recreate.opt.keep_config","--keep-config Keep .easbot/codebase.json (only drop db)")}`),console.log(` ${e("cli.recreate.opt.force","--force, -f Skip safety prompts (for scripts)")}`),console.log(` ${e("cli.recreate.opt.json","--json Output as JSON")}`),console.log(""),console.log(e("cli.recreate.warn","\u26A0\uFE0F This deletes the entire index. Run `index` after.")),{code:0,handled:!0,command:s};let r=await Oe(i);return i.json?emitJsonOk(r,{keepConfig:i.keepConfig===!0,force:i.force===!0,dir:i.dir??null}):printHuman([Te(r)],{title:e("cli.cmd.recreate.description","Discard the entire db and re-init"),boxed:!0}),{code:0,handled:!0,command:s}}case "clear":{let i=$e(a);if(i.help)return console.log(e("cli.clear.usage","Usage: easbot codebase clear [--keep-embeddings] [--force] [--json] [dir]")),console.log(""),console.log(e("cli.clear.description","Clear all nodes/edges/file_hashes; keep config.json and meta.")),console.log(e("cli.clear.reset_state",'index_state is reset to "uninitialized" so `status` recommends `index`.')),console.log(""),console.log(e("cli.shared.options_heading","Options:")),console.log(` ${e("cli.clear.opt.keep_embeddings","--keep-embeddings Preserve node_embeddings / embedding_cache")}`),console.log(` ${e("cli.clear.opt.force","--force, -f Skip safety prompts (for scripts)")}`),console.log(` ${e("cli.clear.opt.json","--json Output as JSON")}`),console.log(""),console.log(e("cli.clear.hint","\u{1F4A1} Use `recreate` if you want to drop the entire db file.")),{code:0,handled:!0,command:s};let r=await Pe(i);return i.json?emitJsonOk(r,{keepEmbeddings:i.keepEmbeddings===!0,force:i.force===!0,dir:i.dir??null}):printHuman([Le(r)],{title:e("cli.cmd.clear.description","Clear all nodes/edges (keep config.json)"),boxed:!0}),{code:0,handled:!0,command:s}}case "config":{let i=Me(a);if(i.help)return console.log(e("cli.config.usage","Usage: easbot codebase config <get|set> [key] [value] [--json] [dir]")),console.log(""),console.log(e("cli.config.description","Read or write .easbot/codebase.json fields.")),console.log(""),console.log(e("cli.config.subcommands","Subcommands:")),console.log(` ${e("cli.config.get","get [key] Show all fields (or a specific key)")}`),console.log(` ${e("cli.config.set","set <key> <value> Update a field (must be in allowlist)")}`),console.log(""),console.log(e("cli.config.allowed_keys","Allowed keys: backend, schema_version, extraction_version, index_state")),console.log(""),console.log(e("cli.shared.options_heading","Options:")),console.log(` ${e("cli.config.opt.json","--json Output as JSON (no ANSI)")}`),{code:0,handled:!0,command:s};if(!i.subcommand)return console.error(e("cli.config.no_subcommand","config requires a subcommand: get | set")),{code:1,handled:!0,command:s};if(i.subcommand==="get"){let r=await Be(i);return i.json?emitJsonOk(r,{subcommand:"get",key:i.key??null,dir:i.dir??null}):printHuman([Ge(r)],{title:e("cli.config.get","get [key] Show all fields (or a specific key)")}),{code:0,handled:!0,command:s}}if(i.subcommand==="set"){let r=await We(i);return i.json?emitJsonOk(r,{subcommand:"set",key:i.key??null,dir:i.dir??null}):printHuman([ze(r)],{title:e("cli.config.set","set <key> <value> Update a field (must be in allowlist)")}),{code:0,handled:!0,command:s}}return console.error(e("cli.config.unknown_subcommand",`Unknown config subcommand: ${i.subcommand}`,{subcommand:i.subcommand})),{code:1,handled:!0,command:s}}case "upgrade":{let i=Ve(a);if(i.help)return console.log(e("cli.upgrade.usage","Usage: easbot codebase upgrade [--schema] [--force] [dir]")),console.log(""),console.log(e("cli.upgrade.description","Update indexed_with_extraction_version metadata when stale.")),console.log(e("cli.upgrade.does_not_delete","Does NOT delete data \u2014 use `recreate` to drop the db entirely.")),console.log(""),console.log(e("cli.shared.options_heading","Options:")),console.log(` ${e("cli.upgrade.opt.schema","--schema Also re-run ensureSchema (idempotent CREATE TABLE IF NOT EXISTS)")}`),console.log(` ${e("cli.upgrade.opt.force","--force, -f Update version even when not stale")}`),{code:0,handled:!0,command:s};let r=await He(i);return i.json?emitJsonOk(r,{schema:i.schema===!0,force:i.force===!0,dir:i.dir??null}):printHuman([Ye(r)],{title:e("cli.cmd.upgrade.description","Update extraction_version metadata when stale")}),{code:0,handled:!0,command:s}}case "embed":case "embed-status":{let i=Xe(a);if(i.help)return console.log(e("cli.embed.usage","Usage: easbot codebase embed-status [--all] [--dry-run|-n] [--pending-list|-p] [--json] [dir]")),console.log(""),console.log(e("cli.embed.description","Inspect node embeddings (statistical only) \u2014 does NOT generate embeddings.")),console.log(e("cli.embed.statistical_only","CLI is statistical-only \u2014 actual embedding generation requires")),console.log(e("cli.embed.repl_required","an `easbot` REPL session with an injected EmbeddingModel.")),console.log(""),console.log(e("cli.shared.options_heading","Options:")),console.log(` ${e("cli.embed.opt.all","--all Show all nodes (including those with embeddings)")}`),console.log(` ${e("cli.embed.opt.dry_run","--dry-run, -n Print statistics only (default behavior)")}`),console.log(` ${e("cli.embed.opt.pending","--pending-list, -p List node ids that are pending embedding")}`),console.log(` ${e("cli.embed.opt.json","--json Output as JSON")}`),{code:0,handled:!0,command:s};i.dryRun=!0;let r=await Ze(i);return i.json?emitJsonOk(r,{all:i.all===!0,dryRun:!0,pendingList:i.pendingList===!0,batchSize:i.batchSize??null,dir:i.dir??null}):printHuman([et(r)],{title:e("cli.cmd.embed.description","Inspect node embeddings (statistical only)")}),{code:0,handled:!0,command:s}}case "query":{let i=dt(a);if(i.help)return console.log(e("cli.query.usage","Usage: easbot codebase query <q...> [--language=<lang>] [--ast=<type>] [--max=N] [--no-edges] [--no-vector|--no-embed] [--json] [--dir=<dir>]")),console.log(""),console.log(e("cli.query.description","Hybrid search (FTS + vector + basic) over indexed code nodes.")),console.log(e("cli.query.aliases","Aliases: search")),console.log(""),console.log(e("cli.shared.options_heading","Options:")),console.log(` ${e("cli.query.opt.language","--language=<lang> Filter by language (ts / js / py / go / ...)")}`),console.log(` ${e("cli.query.opt.ast","--ast=<type> Filter by AST type (class_declaration / function_declaration / ...)")}`),console.log(` ${e("cli.query.opt.max","--max=<N> Max results (default 20)")}`),console.log(` ${e("cli.query.opt.no_edges","--no-edges Do not include edges in results (default: include)")}`),console.log(` ${e("cli.query.opt.no_vector","--no-vector / --no-embed Disable vector search (FTS + basic only, default: vector on)")}`),console.log(` ${e("cli.query.opt.json","--json JSON output")}`),console.log(` ${e("cli.query.opt.dir","--dir=<dir> Target workspace (default: cwd)")}`),{code:0,handled:!0,command:s};let r=await pt(i);return i.json?emitJsonOk(r,{query:i.query??"",language:i.language??null,astType:i.astType??null,maxResults:i.maxResults??null,dir:i.dir??null}):printHuman([ut(r)],{title:e("cli.cmd.query.description","Hybrid search (FTS + vector + basic)")}),{code:0,handled:!0,command:s}}case "node":{let i=gt(a);if(i.help)return console.log(e("cli.node.usage","Usage: easbot codebase node <name|id> [--file=<path>] [--kind=<kind>] [--edges] [--max=N] [--json] [--dir=<dir>]")),console.log(""),console.log(e("cli.node.description","Show details for a single node.")),console.log(e("cli.node.accepts_name","Accepts a symbol <name> (LLM workflow friendly, tool/MCP-aligned)")),console.log(e("cli.node.accepts_id","or a raw <node-id> from `query` / database.")),console.log(""),console.log(e("cli.shared.options_heading","Options:")),console.log(` ${e("cli.node.opt.file","--file=<path> Disambiguate when same-named symbols exist")}`),console.log(` ${e("cli.node.opt.kind","--kind=<kind> Filter / disambiguate by AST kind")}`),console.log(` ${e("cli.node.opt.edges","--edges Include incoming / outgoing edge summaries")}`),console.log(` ${e("cli.node.opt.max","--max=<N> Edge limit (default 50)")}`),console.log(` ${e("cli.node.opt.json","--json Output as JSON")}`),console.log(` ${e("cli.node.opt.dir","--dir=<dir> Target workspace (default: cwd)")}`),{code:0,handled:!0,command:s};let r=await ft(i);return i.json?emitJsonOk(r,{name:i.name??"",nodeId:i.nodeId??null,file:i.file??null,kind:i.kind??null,includeEdges:i.includeEdges===!0,edgesLimit:i.edgesLimit??null,found:r.found,dir:i.dir??null}):printHuman([bt(r)],{title:e("cli.cmd.node.description","Show details for a single node")}),{code:r.found?0:1,handled:!0,command:s}}case "context":{let i=yt(a);if(i.help)return console.log(e("cli.context.usage","Usage: easbot codebase context <id> [--depth=N] [--max=N] [--direction=<incoming|outgoing|both>] [--relation=<r1,r2,...>] [--json] [--dir=<dir>]")),console.log(""),console.log(e("cli.context.description","Build a sub-graph context around a node (BFS to N-level neighbors).")),console.log(""),console.log(e("cli.shared.options_heading","Options:")),console.log(` ${e("cli.context.opt.depth","--depth=<N> BFS depth (default 2)")}`),console.log(` ${e("cli.context.opt.max","--max=<N> Max nodes (default 100)")}`),console.log(` ${e("cli.context.opt.direction","--direction=<dir> incoming | outgoing | both (default both)")}`),console.log(` ${e("cli.context.opt.relation","--relation=<r1,r2,...> Filter by relation types (CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS / USES / REFERENCES)")}`),console.log(` ${e("cli.context.opt.json","--json Output as JSON")}`),console.log(` ${e("cli.context.opt.dir","--dir=<dir> Target workspace (default: cwd)")}`),{code:0,handled:!0,command:s};let r=await xt(i);return i.json?emitJsonOk(r,{nodeId:i.nodeId??"",depth:i.depth??null,direction:i.direction??"both",dir:i.dir??null}):printHuman([St(r)],{title:e("cli.cmd.context.description","Build sub-graph context around a node")}),{code:0,handled:!0,command:s}}case "impact":{let i=Et(a);if(i.help)return console.log(e("cli.impact.usage","Usage: easbot codebase impact <id> [-d=N | --depth=N] [--relation=<r1,r2,...>] [--json] [--dir=<dir>]")),console.log(""),console.log(e("cli.impact.description","Blast radius: BFS incoming CALLS / REFERENCES / USES / IMPORTS / TYPE_REFERENCES, bucketed by depth.")),console.log(""),console.log(e("cli.shared.options_heading","Options:")),console.log(` ${e("cli.impact.opt.depth","--depth=<N> BFS depth (default 3)")}`),console.log(` ${e("cli.impact.opt.relation","--relation=<r1,r2,...> Filter by relation types")}`),console.log(` ${e("cli.impact.opt.json","--json Output as JSON")}`),console.log(` ${e("cli.impact.opt.dir","--dir=<dir> Target workspace (default: cwd)")}`),{code:0,handled:!0,command:s};let r=await Ct(i);return i.json?emitJsonOk(r,{nodeId:i.nodeId??"",depth:i.depth??null,dir:i.dir??null}):printHuman([kt(r)],{title:e("cli.cmd.impact.description","Blast radius (BFS incoming edges)")}),{code:0,handled:!0,command:s}}case "callers":{let i=Bt(a);if(i.help)return console.log(e("cli.callers.usage","Usage: easbot codebase callers <symbol> [--node-id=<id>] [--file=<path>] [--kind=<kind>] [--max=N] [--json] [--dir=<dir>]")),console.log(""),console.log(e("cli.callers.description","Flat list of who calls <symbol> (incoming CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS).")),console.log(e("cli.callers.accepts","Accepts <symbol> name (LLM-friendly) OR --node-id for raw node id.")),console.log(""),console.log(e("cli.shared.options_heading","Options:")),console.log(` ${e("cli.callers.opt.node_id","--node-id=<id> Raw node id from `query` / database")}`),console.log(` ${e("cli.callers.opt.file","--file=<path> File path or basename to disambiguate when same-named symbols exist")}`),console.log(` ${e("cli.callers.opt.kind","--kind=<kind> Filter by node kind (class_declaration / function_declaration / ...)")}`),console.log(` ${e("cli.callers.opt.max","--max=<N> Max callers (default 20)")}`),console.log(` ${e("cli.callers.opt.json","--json Output as JSON")}`),console.log(` ${e("cli.callers.opt.dir","--dir=<dir> Target workspace (default: cwd)")}`),{code:0,handled:!0,command:s};let r=await Wt(i);return i.json?emitJsonOk(r,{symbol:i.symbol??"",nodeId:i.nodeId??null,file:i.file??null,kind:i.kind??null,maxResults:i.maxResults??null,dir:i.dir??null}):printHuman([Gt(r)],{title:e("cli.cmd.callers.description","Flat list of who calls <symbol> (incoming edges)")}),{code:0,handled:!0,command:s}}case "callees":{let i=zt(a);if(i.help)return console.log(e("cli.callees.usage","Usage: easbot codebase callees <symbol> [--node-id=<id>] [--file=<path>] [--kind=<kind>] [--max=N] [--json] [--dir=<dir>]")),console.log(""),console.log(e("cli.callees.description","Flat list of what <symbol> calls (outgoing edges).")),console.log(e("cli.callees.accepts","Accepts <symbol> name (LLM-friendly) OR --node-id for raw node id.")),console.log(""),console.log(e("cli.shared.options_heading","Options:")),console.log(` ${e("cli.callees.opt.node_id","--node-id=<id> Raw node id from `query` / database")}`),console.log(` ${e("cli.callees.opt.file","--file=<path> File path or basename to disambiguate")}`),console.log(` ${e("cli.callees.opt.kind","--kind=<kind> Filter by node kind")}`),console.log(` ${e("cli.callees.opt.max","--max=<N> Max callees (default 20)")}`),console.log(` ${e("cli.callees.opt.json","--json Output as JSON")}`),console.log(` ${e("cli.callees.opt.dir","--dir=<dir> Target workspace (default: cwd)")}`),{code:0,handled:!0,command:s};let r=await Jt(i);return i.json?emitJsonOk(r,{symbol:i.symbol??"",nodeId:i.nodeId??null,file:i.file??null,kind:i.kind??null,maxResults:i.maxResults??null,dir:i.dir??null}):printHuman([Kt(r)],{title:e("cli.cmd.callees.description","Flat list of what <symbol> calls (outgoing edges)")}),{code:0,handled:!0,command:s}}case "explore":{let i=Vt(a);if(i.help)return console.log(e("cli.explore.usage","Usage: easbot codebase explore <query> [--file=<path>] [--kind=<kind>] [--max-files=N] [--max-symbols=N] [--depth=N] [--no-content] [--intent=<ctx>] [--json] [--dir=<dir>]")),console.log(""),console.log(e("cli.explore.description","PRIMARY tool \u2014 single call to get source code + caller/callee trail.")),console.log(e("cli.explore.query_help","<query> can be a symbol name or natural language.")),console.log(""),console.log(e("cli.shared.options_heading","Options:")),console.log(` ${e("cli.explore.opt.file","--file=<path> File path or basename to disambiguate")}`),console.log(` ${e("cli.explore.opt.kind","--kind=<kind> Filter by node kind")}`),console.log(` ${e("cli.explore.opt.max_files","--max-files=<N> Max entry-point files (default 5)")}`),console.log(` ${e("cli.explore.opt.max_symbols","--max-symbols=<N> Max symbols per file (default 3)")}`),console.log(` ${e("cli.explore.opt.depth","--depth=<N> Neighbor depth for caller/callee trail (default 1)")}`),console.log(` ${e("cli.explore.opt.no_content","--no-content Do not include source code (locations only, default: include)")}`),console.log(` ${e("cli.explore.opt.intent","--intent=<ctx> LLM context string for ranking")}`),console.log(` ${e("cli.explore.opt.json","--json Output as JSON")}`),console.log(` ${e("cli.explore.opt.dir","--dir=<dir> Target workspace (default: cwd)")}`),{code:0,handled:!0,command:s};let r=await Ht(i);return i.json?emitJsonOk(r,{query:i.query??"",file:i.file??null,kind:i.kind??null,maxFiles:i.maxFiles??null,maxSymbols:i.maxSymbols??null,depth:i.depth??null,includeContent:i.includeContent!==!1,intent:i.intent??null,dir:i.dir??null}):printHuman([await Yt(r)],{title:e("cli.cmd.explore.description","PRIMARY tool \u2014 source code + caller/callee trail in one call")}),{code:0,handled:!0,command:s}}case "dead-code":{let i=_t(a);if(i.help)return console.log(e("cli.dead_code.usage","Usage: easbot codebase dead-code [--type=<t1,t2,...>] [--no-exclude-entry] [--limit=N] [--json] [--dir=<dir>]")),console.log(""),console.log(e("cli.dead_code.description","Find nodes with no incoming edges (heuristic dead code).")),console.log(""),console.log(e("cli.shared.options_heading","Options:")),console.log(` ${e("cli.dead_code.opt.type","--type=<t1,t2,...> Only consider these AST types")}`),console.log(` ${e("cli.dead_code.opt.no_exclude_entry","--no-exclude-entry Include entry-point files (default: exclude)")}`),console.log(` ${e("cli.dead_code.opt.limit","--limit=<N> Max results (default 100)")}`),console.log(` ${e("cli.dead_code.opt.json","--json Output as JSON")}`),console.log(` ${e("cli.dead_code.opt.dir","--dir=<dir> Target workspace (default: cwd)")}`),{code:0,handled:!0,command:s};let r=await Nt(i);return i.json?emitJsonOk(r,{astTypes:i.astTypes??null,limit:i.limit??null,excludeEntry:i.excludeEntry!==!1,dir:i.dir??null}):printHuman([Dt(r)],{title:e("cli.cmd.dead_code.description","Find unused symbols")}),{code:0,handled:!0,command:s}}case "circular":{let i=jt(a);if(i.help)return console.log(e("cli.circular.usage","Usage: easbot codebase circular [--relation=<r>] [--scope=<file|module>] [--json] [--dir=<dir>]")),console.log(""),console.log(e("cli.circular.description","Detect circular dependencies via Tarjan SCC.")),console.log(""),console.log(e("cli.shared.options_heading","Options:")),console.log(` ${e("cli.circular.opt.relation","--relation=<r> Relation type to follow (default IMPORTS)")}`),console.log(` ${e("cli.circular.opt.scope","--scope=<scope> file | module (default file)")}`),console.log(` ${e("cli.circular.opt.json","--json Output as JSON")}`),console.log(` ${e("cli.circular.opt.dir","--dir=<dir> Target workspace (default: cwd)")}`),{code:0,handled:!0,command:s};let r=await vt(i);return i.json?emitJsonOk(r,{relation:i.relation??null,scope:i.scope??null,dir:i.dir??null}):printHuman([Ot(r)],{title:e("cli.cmd.circular.description","Detect circular dependencies (Tarjan SCC)")}),{code:0,handled:!0,command:s}}case "path":{let i=$t(a);if(i.help)return console.log(e("cli.path.usage","Usage: easbot codebase path <from> <to> [-d=N | --depth=N] [--relation=<r1,r2,...>] [--json] [--dir=<dir>]")),console.log(""),console.log(e("cli.path.description","Find shortest path between two nodes (BFS along CALLS / IMPORTS / TYPE_REFERENCES / USES / REFERENCES).")),console.log(""),console.log(e("cli.shared.options_heading","Options:")),console.log(` ${e("cli.path.opt.depth","--depth=<N> BFS depth limit (default 6)")}`),console.log(` ${e("cli.path.opt.relation","--relation=<r1,r2,...> Filter by relation types")}`),console.log(` ${e("cli.path.opt.json","--json Output as JSON")}`),console.log(` ${e("cli.path.opt.dir","--dir=<dir> Target workspace (default: cwd)")}`),{code:0,handled:!0,command:s};let r=await Pt(i);return i.json?emitJsonOk(r,{fromId:i.fromId??"",toId:i.toId??"",depth:i.depth??null,dir:i.dir??null}):printHuman([Lt(r)],{title:e("cli.cmd.path.description","Find shortest path between two nodes")}),{code:r.found?0:1,handled:!0,command:s}}case "mcp":{let i=qt(a);return i.help?(console.log(e("cli.mcp.usage","Usage: easbot codebase mcp [dir]")),console.log(""),console.log(e("cli.mcp.description","Start a stdio MCP server exposing 9 codebase tools:")),console.log(` ${e("cli.mcp.tools.1"," query / node / context / impact")}`),console.log(` ${e("cli.mcp.tools.2"," callers / callees / explore")}`),console.log(` ${e("cli.mcp.tools.3"," status / doctor")}`),console.log(""),console.log(e("cli.mcp.transport","Connect from MCP clients via stdio JSON-RPC.")),{code:0,handled:!0,command:s}):(await Ut(i),{code:0,handled:!0,command:s})}case "watch":{let i=ot(a);if(i.help)return console.log(e("cli.watch.usage","Usage: easbot codebase watch [--debounce=N] [--interval=N] [dir]")),console.log(""),console.log(e("cli.watch.description","Watch the workspace directory for file changes and log events.")),console.log(e("cli.watch.pid_file","Writes a pid file at .easbot/.watcher.pid for subsequent `stop`.")),console.log(""),console.log(e("cli.shared.options_heading","Options:")),console.log(` ${e("cli.watch.opt.debounce","--debounce=N Per-path debounce in ms (default 200)")}`),console.log(` ${e("cli.watch.opt.interval","--interval=N Polling interval in ms (default 500)")}`),console.log(""),console.log(e("cli.watch.note","NOTE: This command blocks. Press Ctrl+C to exit.")),{code:0,handled:!0,command:s};let r=await nt(i);return console.log(it(r.events)),await new Promise(c=>{let b=()=>{te.info("watcher received signal, stopping"),c();};process.once("SIGINT",b),process.once("SIGTERM",b);}),await r.watcher.dispose(),{code:0,handled:!0,command:s}}case "stop":{let i=rt(a);if(i.help)return console.log(e("cli.stop.usage","Usage: easbot codebase stop [dir]")),console.log(""),console.log(e("cli.stop.description","Stop a running watcher identified by .easbot/.watcher.pid.")),console.log(""),console.log(e("cli.shared.options_heading","Options:")),console.log(` ${e("cli.stop.opt.force","--force, -f Ignore errors and clear the pid file anyway")}`),{code:0,handled:!0,command:s};let r=await at(i);return i.json?emitJsonOk(r,{force:i.force===!0,dir:i.dir??null}):printHuman([ct(r)],{title:e("cli.cmd.stop.description","Stop a running file watcher")}),{code:r.stopped?0:1,handled:!0,command:s}}default:return console.error(e("cli.unknown_command",`Unknown command: ${s}`,{command:s})),console.error(e("cli.help_hint","Run `easbot codebase --help` for available commands.")),{code:1,handled:!0,command:s}}}catch(i){let r=i instanceof Error?i.message:String(i);return console.error(e("cli.command_failed",`codebase ${s} failed: ${r}`,{command:s,message:r})),te.error("codebase CLI error",{command:s,error:r,stack:i instanceof Error?i.stack:void 0}),{code:1,handled:true,command:s}}}function Vn(o){let t={},n=[];for(let e of o)e==="--json"?t.json=true:e.startsWith("--dir=")?t.dir=e.slice(6):e.startsWith("-")||n.push(e);return t.dir===void 0&&n.length>0&&(t.dir=n[0]),t}function Hn(o){let t={},n=[];for(let e of o)e==="--help"||e==="-h"?t.help=true:e.startsWith("--dir=")?t.dir=e.slice(6):e==="--json"?t.json=true:e.startsWith("-")||n.push(e);return t.dir===void 0&&n.length>0&&(t.dir=n[0]),t}function Yn(o){return {packageName:"codebase",rootDir:o.rootDir,configPath:o.configPath,configExists:o.configExists,dbPath:o.dbPath,dbExists:o.dbExists,dbSize:o.dbSize,indexState:o.indexState,schemaVersion:o.schemaVersion,extractionVersion:o.extractionVersion,lastSyncAt:o.lastSyncAt,vectorEnabled:o.vectorEnabled,embeddingDims:o.embeddingDims,llm:o.llm,backend:o.backend,counts:o.counts,healthy:o.healthy,recommendation:o.recommendation,extras:o.isStale===true?{stale:"yes \u2014 reindex recommended"}:void 0}}function Qn(o){return {packageName:"codebase",healthy:o.healthy,durationMs:o.durationMs,checks:o.checks.map(t=>({code:t.code,severity:t.severity,name:t.name,message:t.message,durationMs:t.durationMs,details:t.details})),backendAvailable:o.backendAvailable,dbStats:o.dbStats}}export{Gn as a,Va as b,zn as c,Ha as d};