@easbot/codebase 0.3.28 → 0.3.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.en.md +55 -1
  2. package/README.md +55 -1
  3. package/dist/chunks/cache-D7NVUXB2.mjs +1 -0
  4. package/dist/chunks/cache-LSQZJEDR.cjs +1 -0
  5. package/dist/chunks/chunk-33DIOGLJ.mjs +158 -0
  6. package/dist/chunks/chunk-37KKG3UK.mjs +48 -0
  7. package/dist/chunks/chunk-43WAI4Z7.mjs +1 -0
  8. package/dist/chunks/chunk-CLUGDJA5.cjs +62 -0
  9. package/dist/chunks/chunk-EH2QTB6S.cjs +37 -0
  10. package/dist/chunks/chunk-ESA2CL57.mjs +37 -0
  11. package/dist/chunks/chunk-ETCTXAXR.mjs +1 -0
  12. package/dist/chunks/chunk-H4VZF3ZQ.mjs +1 -0
  13. package/dist/chunks/chunk-J7Z3MIR7.cjs +1 -0
  14. package/dist/chunks/chunk-JEHVBEBS.cjs +1 -0
  15. package/dist/chunks/chunk-KFESJR3T.cjs +1 -0
  16. package/dist/chunks/chunk-KR6BQNY6.mjs +203 -0
  17. package/dist/chunks/chunk-KTSR5VPT.mjs +1 -0
  18. package/dist/chunks/chunk-OJK5EFPD.cjs +48 -0
  19. package/dist/chunks/chunk-OZYQQS63.cjs +158 -0
  20. package/dist/chunks/chunk-PRPBK7D6.mjs +62 -0
  21. package/dist/chunks/chunk-T6KJWYTV.mjs +1 -0
  22. package/dist/chunks/chunk-TBDAGLC4.cjs +203 -0
  23. package/dist/chunks/chunk-TMQVJU4I.mjs +1 -0
  24. package/dist/chunks/chunk-VZCOLSBF.cjs +1 -0
  25. package/dist/chunks/chunk-W5SMGCKO.cjs +1 -0
  26. package/dist/chunks/chunk-Y7JDLK56.cjs +1 -0
  27. package/dist/chunks/cli-handler-IQ6ZNLEJ.mjs +1 -0
  28. package/dist/chunks/cli-handler-WTEPKO4E.cjs +1 -0
  29. package/dist/chunks/code-base-5BXR4FUU.cjs +1 -0
  30. package/dist/chunks/code-base-M4EMTQTG.mjs +1 -0
  31. package/dist/chunks/database-manager-KM7BOISA.mjs +1 -0
  32. package/dist/chunks/database-manager-LTHK7MM6.cjs +1 -0
  33. package/dist/chunks/file-watcher-2MUX5MO5.cjs +1 -0
  34. package/dist/chunks/file-watcher-ABFT22GS.mjs +1 -0
  35. package/dist/chunks/{interfaces-DPFLQBQ6.mjs → interfaces-43SSCG3E.mjs} +1 -1
  36. package/dist/chunks/interfaces-LUHDPZOT.cjs +1 -0
  37. package/dist/chunks/llm-S6D5ICOO.cjs +1 -0
  38. package/dist/chunks/llm-WS3XKT46.mjs +1 -0
  39. package/dist/chunks/stdio-server-KA3JQB7C.cjs +30 -0
  40. package/dist/chunks/stdio-server-QP63TXGI.mjs +30 -0
  41. package/dist/cli.cjs +1 -1
  42. package/dist/cli.mjs +1 -1
  43. package/dist/index.cjs +1 -1
  44. package/dist/index.d.cts +1215 -89
  45. package/dist/index.d.ts +1215 -89
  46. package/dist/index.mjs +1 -1
  47. package/package.json +9 -10
  48. package/dist/chunks/chunk-2YMB6W5S.mjs +0 -1
  49. package/dist/chunks/chunk-34CU2EU4.mjs +0 -1
  50. package/dist/chunks/chunk-4HJ7RFP7.cjs +0 -1
  51. package/dist/chunks/chunk-4TCNRCEK.mjs +0 -48
  52. package/dist/chunks/chunk-7CL37IYG.mjs +0 -158
  53. package/dist/chunks/chunk-7N7UVPKB.cjs +0 -48
  54. package/dist/chunks/chunk-GWCRGM4D.mjs +0 -51
  55. package/dist/chunks/chunk-ICEJ23S3.mjs +0 -203
  56. package/dist/chunks/chunk-JCJFUUU2.cjs +0 -203
  57. package/dist/chunks/chunk-JVX6PHPN.cjs +0 -1
  58. package/dist/chunks/chunk-M2YU5LAI.cjs +0 -1
  59. package/dist/chunks/chunk-TGCR6O3S.cjs +0 -62
  60. package/dist/chunks/chunk-UHNJOT5S.cjs +0 -158
  61. package/dist/chunks/chunk-VPWALTY7.cjs +0 -51
  62. package/dist/chunks/chunk-WRM2FP4O.mjs +0 -62
  63. package/dist/chunks/chunk-ZPEE2LSX.mjs +0 -1
  64. package/dist/chunks/cli-handler-DXLDGJFQ.mjs +0 -1
  65. package/dist/chunks/cli-handler-KKNIISIE.cjs +0 -1
  66. package/dist/chunks/code-base-BFLIOZXA.cjs +0 -1
  67. package/dist/chunks/code-base-DMVLROV6.mjs +0 -1
  68. package/dist/chunks/database-manager-GT3LOQUV.cjs +0 -1
  69. package/dist/chunks/database-manager-N5WLNG3F.mjs +0 -1
  70. package/dist/chunks/file-watcher-QS442D52.cjs +0 -1
  71. package/dist/chunks/file-watcher-X56TEWNY.mjs +0 -1
  72. package/dist/chunks/interfaces-YX56SVRQ.cjs +0 -1
  73. package/dist/chunks/llm-ADBGTSCV.mjs +0 -1
  74. package/dist/chunks/llm-BDMNIGOH.cjs +0 -1
  75. package/dist/chunks/stdio-server-4X7YFQA2.mjs +0 -30
  76. package/dist/chunks/stdio-server-5UQVBBZP.cjs +0 -30
@@ -0,0 +1,48 @@
1
+ 'use strict';var chunkCLUGDJA5_cjs=require('./chunk-CLUGDJA5.cjs'),chunkY7JDLK56_cjs=require('./chunk-Y7JDLK56.cjs'),chunkJEHVBEBS_cjs=require('./chunk-JEHVBEBS.cjs'),chunkTBDAGLC4_cjs=require('./chunk-TBDAGLC4.cjs'),chunkOZYQQS63_cjs=require('./chunk-OZYQQS63.cjs'),chunkW5SMGCKO_cjs=require('./chunk-W5SMGCKO.cjs'),chunkEH2QTB6S_cjs=require('./chunk-EH2QTB6S.cjs'),chunkKFESJR3T_cjs=require('./chunk-KFESJR3T.cjs'),fs=require('fs'),utils=require('@easbot/utils'),llm=require('@easbot/llm'),module$1=require('module'),types=require('@easbot/types'),terminal=require('@easbot/terminal'),path=require('path'),database=require('@easbot/database'),url=require('url'),mcp=require('@easbot/mcp');var ee=utils.Log.create({service:"codebase.init"});function Re(o){let e={},n=[];for(let t of o)t==="--force"||t==="-f"?e.force=true:t==="--help"||t==="-h"?e.help=true:t==="--json"?e.json=true:t.startsWith("-")||n.push(t);return e}async function v(o={}){let e=await chunkY7JDLK56_cjs.b.getRootDir();try{let m=await chunkTBDAGLC4_cjs.e();m.source==="monorepo"?ee.debug("better-sqlite3 resolved (monorepo)",{path:m.absolutePath}):ee.debug("better-sqlite3 auto-installed to cache",{source:m.source,path:m.absolutePath});}catch(m){ee.warn("better-sqlite3 resolve / install failed; index/sync/mcp may still fail later",{error:utils.errorMeta(m),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=chunkTBDAGLC4_cjs.a(e),t=await chunkY7JDLK56_cjs.b.getConfigPath(),i=chunkTBDAGLC4_cjs.c(e);if(await chunkY7JDLK56_cjs.b.exists()&&!o.force)return {configPath:t,dbPath:i,created:false,skipped:true,backend:"better-sqlite3",schemaVersion:chunkOZYQQS63_cjs.a,migrationsApplied:0,tablesCreated:0,durationMs:0};if(fs.existsSync(n)||fs.mkdirSync(n,{recursive:true}),await chunkY7JDLK56_cjs.b.writeCodebaseJson({version:1,schema_version:chunkOZYQQS63_cjs.a,extraction_version:chunkOZYQQS63_cjs.e,backend:"better-sqlite3",created_at:new Date().toISOString()}),o.force)for(let m of [i,`${i}-wal`,`${i}-shm`])try{fs.rmSync(m,{force:!0});}catch{}chunkTBDAGLC4_cjs.d(e);let r=false,l=0,s=0,a=Date.now(),d=new chunkOZYQQS63_cjs.f(i);try{let m=d.getMeta("index_state"),h=d.getMeta("createdAt"),p=d.getMeta("version"),w=d.getMeta("indexed_with_version");r=m!==null&&h!==null&&p!==null&&w!==null;try{l=d.countSqliteObjects();}catch{}let u=d.getMeta("schema_version");s=u?Number.parseInt(u,10)||chunkOZYQQS63_cjs.a:chunkOZYQQS63_cjs.a;}finally{d.close();}let c=Date.now()-a;return {configPath:t,dbPath:i,created:true,skipped:false,metaInitialized:r,backend:"better-sqlite3",schemaVersion:chunkOZYQQS63_cjs.a,migrationsApplied:s,tablesCreated:l,durationMs:c}}async function K(o){let e=await chunkY7JDLK56_cjs.b.getRootDir(),t=await chunkY7JDLK56_cjs.b.getConfigPath(),i=chunkTBDAGLC4_cjs.c(e),r=await chunkY7JDLK56_cjs.b.exists(),l=fs.existsSync(i),s;if(l)try{s=fs.statSync(i).size;}catch{}let a={initialized:false,capabilities:{embedding:false,evaluation:false}},d={},c,m,h,p=0,w=0,u,E,x,f=false,N,g=false,y;if(r)try{let D=await chunkY7JDLK56_cjs.b.getCodebaseJson();D&&(c=D.index_state,E=D.schema_version,m=D.extraction_version,u=D.backend);}catch{}if(l&&i)try{let{DatabaseManager:D}=await import('./database-manager-LTHK7MM6.cjs'),P=new D(i);try{let $=P.getStatus();c=$.indexState??c,m=$.extractionVersion??m,h=$.isStale,p=$.nodeCount,w=$.edgeCount;for(let[X,ro]of Object.entries($.meta))d[X]=ro;N=$.meta.lastSyncAt,E=parseInt($.meta.schema_version??"",10)||E,u=$.meta.backend??u,f=$.meta.vector_enabled==="true"||$.meta.vector_enabled==="1",x=parseInt($.meta.embeddingDims??"",10)||void 0;try{let{stats:X}=P.checkIntegrity();y={...X};}catch{}g=P.isFtsAvailable();}finally{P.close();}}catch{}let S=chunkEH2QTB6S_cjs.a.isInitialized();if(S){a.initialized=true;let D=chunkEH2QTB6S_cjs.a.capabilities();a.capabilities={embedding:D.embedding===true,evaluation:D.evaluation===true},a.embeddingModel=a.capabilities.embedding?"configured":void 0,a.evaluationModel=a.capabilities.evaluation?"configured":void 0;}if(S&&a.capabilities.embedding&&i)try{let D=await chunkEH2QTB6S_cjs.a.probeEmbeddingDims({timeoutMs:5e3});if(typeof D=="number"){x=D;try{let{DatabaseManager:P}=await import('./database-manager-LTHK7MM6.cjs'),$=new P(i);try{llm.syncMeta($,[["embeddingDims",String(D)]]);}finally{$.close();}}catch{}}}catch{}let O=l&&r&&!h&&c!=="failed"&&c!=="stale",C;return r?l?c==="failed"?C="Last sync failed \u2014 run `easbot codebase index` to retry.":h?C="Index is stale (extraction version mismatch) \u2014 run `easbot codebase recreate` to rebuild.":c==="uninitialized"?C="Config exists but index never built \u2014 run `easbot codebase index` to populate.":c==="partial"&&(C="Last sync partially succeeded \u2014 re-run `easbot codebase index` to fill missing files."):C="Run `easbot codebase index` to build the index.":C="Run `easbot codebase init` to initialize the configuration.",{package:"codebase",rootDir:e,dbPath:i,dbSize:s,configPath:t,configExists:r,schemaVersion:E,extractionVersion:m,lastSyncAt:N,indexState:c,vectorEnabled:f,embeddingDims:x,llm:a,backend:u,meta:d,recommendation:C,healthy:O,dbStats:y,dbExists:l,nodeCount:p,edgeCount:w,ftsAvailable:g}}var F=()=>Date.now();async function ke(o){let e=F(),n=await K(),t=[],i,r=F(),l;if(n.dbExists?n.configExists?l=I("database","ok",`db readable at ${n.dbPath}`,Date.now()-r):l=I("database","warn","config not found \u2014 run `easbot codebase init` first",Date.now()-r):l=I("database","info","db not initialized \u2014 run `easbot codebase index` to build",Date.now()-r),t.push(l),n.dbExists){let u=F();t.push(I("fts","ok","fts sync checked in integrity pass",Date.now()-u));}if(n.dbExists){let u=F();t.push(I("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()-u));}if(n.dbExists){let u=F();t.push(I("schema",n.isStale===true?"warn":"ok",n.isStale===true?`extraction_version mismatch (current=${n.extractionVersion??0})`:`schema_version=${n.schemaVersion??"unknown"}`,Date.now()-u));}t.push(I("lock","ok","no lock contention observed",0)),t.push(I("disk_space","ok","no disk space check (v0.5.1 placeholder)",0));let s=F(),a={"better-sqlite3":false,"node:sqlite":false,"@tursodatabase/database":false},d=module$1.createRequire(chunkKFESJR3T_cjs.d);try{d.resolve("better-sqlite3"),a["better-sqlite3"]=!0;}catch{}a["node:sqlite"]=typeof process.versions.sqlite=="string";try{d.resolve("@tursodatabase/database"),a["@tursodatabase/database"]=!0;}catch{}let c="ok",m=`backend available: ${n.backend??"unknown"}`;!a["better-sqlite3"]&&!a["node:sqlite"]?(c="error",m="no SQLite backend available (install better-sqlite3 or use Node 22.5+)"):n.configExists&&n.backend&&!a[n.backend]&&(c="error",m=`configured backend "${n.backend}" not available in this environment`),t.push(I("backend",c,m,Date.now()-s));let h=F(),p;if(!n.llm.initialized||!n.llm.capabilities.embedding)p=I(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","llm not initialized; probe skipped",Date.now()-h);else if(!n.dbExists)p=I(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","db not initialized; probe skipped",Date.now()-h);else try{let u=await chunkEH2QTB6S_cjs.a.probeEmbeddingDims({timeoutMs:5e3});typeof u!="number"?p=I(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info","probe failed (network / model error)",Date.now()-h):n.embeddingDims===void 0?p=I(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe=${u}, meta missing \u2014 next status will sync`,Date.now()-h):u!==n.embeddingDims?p=I(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"warn",`probe=${u} but meta.embeddingDims=${n.embeddingDims} (drift detected)`,Date.now()-h,{probed:u,recorded:n.embeddingDims}):p=I(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"ok",`probe=${u} matches meta`,Date.now()-h,{probed:u});}catch(u){p=I(types.EMBEDDING_DIMS_CONSISTENCY_CHECK,"info",`probe threw: ${utils.errorMeta(u).message}`,Date.now()-h);}if(t.push(p),n.dbExists){let u=F();try{let{DatabaseManager:E}=await import('./database-manager-LTHK7MM6.cjs'),x=new E(n.dbPath);try{let{issues:f,stats:N}=x.checkIntegrity();i=N;for(let g of f)t.push(I("integrity_stats",g.severity,g.message,0,{source:"database.checkIntegrity"}));i.parse_errors===0&&t.push(I("parse_errors_zero","info","parse_errors: 0 (no parse errors recorded)",0)),i.unresolved_refs===0&&t.push(I("unresolved_refs_zero","info","unresolved_refs: 0 (resolution pipeline not active)",0)),i.name_segment_vocab===0&&t.push(I("name_segment_vocab_zero","info","name_segment_vocab: 0 (identifier-segments not active)",0)),i.project_metadata===0&&t.push(I("project_metadata_zero","info","project_metadata: 0 (CodeBase.initialize not run)",0));}finally{x.close();}}catch(E){t.push(I("integrity_stats","warn",`db integrity check failed: ${utils.errorMeta(E).message}`,Date.now()-u));}}let w=F();if(!n.llm.initialized)t.push(I("llm","info","Llm namespace not initialized (calls `easbot codebase init` first)",Date.now()-w));else {let u=[];n.llm.capabilities.embedding||u.push("embedding"),n.llm.capabilities.evaluation||u.push("evaluation"),t.push(I("llm",u.length===0?"ok":"info",u.length===0?"embedding + evaluation configured":`missing capabilities: ${u.join(", ")}`,Date.now()-w,{capabilities:n.llm.capabilities}));}return {healthy:!t.some(u=>u.severity==="error"),checks:t,issues:t.map(u=>({severity:u.severity,message:u.message,name:u.name,code:u.code})),durationMs:Date.now()-e,status:n,backendAvailable:a,dbStats:i??void 0}}function I(o,e,n,t,i){return {code:o.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),severity:e,name:o,message:n,details:i,durationMs:t}}var wo=utils.Log.create({service:"codebase.cmd.index"});function De(o){let e={};for(let n of o)if(n==="--no-embed")e.noEmbed=true;else if(n==="--embed")e.noEmbed=false;else if(n==="--json")e.json=true;else if(n==="--verbose"||n==="-v")e.verbose=true;else if(n==="--quiet"||n==="-q")e.quiet=true;else if(n==="--help"||n==="-h")e.help=true;else if(n.startsWith("--batch=")){let t=n.slice(8),i=Number.parseInt(t,10);Number.isFinite(i)&&i>0&&(e.batch=i);}return e}async function V(o){var E=[];try{let e=await chunkY7JDLK56_cjs.b.getRootDir();let n=chunkTBDAGLC4_cjs.a(e);let t=chunkTBDAGLC4_cjs.b(e);await v();let{CodeBase:i}=await import('./code-base-5BXR4FUU.cjs');let{DEFAULT_EMBEDDING_CONFIG:r,DEFAULT_INDEXER_CONFIG:l,DEFAULT_PARSER_CONFIG:s}=await import('@easbot/types');let a=o.batch??l.batchSize??50;let d=new i({workspaceDir:e,database:{path:chunkTBDAGLC4_cjs.c(e),walMode:!0},embedding:o.noEmbed===!1?r:void 0,indexer:{...l,batchSize:a},parser:s,sync:{onBoot:!1,onSearch:!1,onSessionStart:!1,intervalMs:0}});let c=Date.now();let m=chunkKFESJR3T_cjs.b(E,wo.time("codebaseIndex",{level:"DEBUG"}));let h=-1;let p=0;let w=!o.quiet;let u;try{await d.initialize(),terminal.registerActiveProgressLine(process.stderr);let g=await d.indexDirectory(e,w?y=>{let S=Math.max(y.total,1),O=Math.min(100,Math.floor(y.processed/S*100)),C=Date.now();if(O!==h||C-p>3e4){let P=String(O).padStart(3," ");terminal.clearActiveProgressLine(),process.stderr.write(` \u{1F4A1} [${P}%] ${y.stage}: ${y.processed}/${y.total} files`),h=O,p=C;}}:void 0);u={rootDir:e,success:g.success,filesProcessed:g.filesProcessed,nodesCreated:g.nodesCreated,edgesCreated:g.edgesCreated,errorCount:g.errors.length,errors:g.errors,durationMs:g.duration,embedded:!o.noEmbed,batchSize:a};}finally{terminal.clearActiveProgressLine(),terminal.unregisterActiveProgressLine(process.stderr),await d.close();}return u}catch(x){var f=x,N=true;}finally{chunkKFESJR3T_cjs.c(E,f,N);}}function ve(o){let e=[];if(e.push("Codebase index"),e.push(` rootDir: ${o.rootDir}`),e.push(` success: ${o.success?"\u2713":"\u2717"}`),e.push(` files processed: ${o.filesProcessed}`),e.push(` nodes created: ${o.nodesCreated}`),e.push(` edges created: ${o.edgesCreated}`),e.push(` embedded: ${o.embedded?"yes":"no (--no-embed)"}`),e.push(` batch size: ${o.batchSize}`),e.push(` duration: ${o.durationMs}ms`),o.errorCount>0){e.push(` errors (${o.errorCount}):`);for(let n of o.errors.slice(0,10))e.push(` - ${n.filePath}: ${n.error}`);o.errors.length>10&&e.push(` ... and ${o.errors.length-10} more`);}return e.join(`
2
+ `)}function Oe(o){let e={};for(let n of o)n==="--json"?e.json=true:n==="--quiet"||n==="-q"?e.quiet=true:n==="--help"||n==="-h"?e.help=true:n==="--no-embed"?e.noEmbed=true:n==="--embed"&&(e.noEmbed=false);return e}async function je(o){let e=await chunkY7JDLK56_cjs.b.getRootDir(),n=chunkTBDAGLC4_cjs.c(e),{CodeBase:t}=await import('./code-base-5BXR4FUU.cjs'),{DEFAULT_EMBEDDING_CONFIG:i,DEFAULT_INDEXER_CONFIG:r,DEFAULT_PARSER_CONFIG:l}=await import('@easbot/types'),s=new t({workspaceDir:e,database:{path:n,walMode:true},embedding:o.noEmbed===false?i:void 0,indexer:r,parser:l,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}}),a,d={_lastPct:-1,_lastProgressAt:0};try{await s.initialize(),terminal.registerActiveProgressLine(process.stderr);let c=await s.sync(o.quiet?void 0:h=>{let p=Math.max(h.total,1),w=Math.min(100,Math.floor(h.processed/p*100)),u=Date.now(),E=w!==d._lastPct,x=u-d._lastProgressAt>3e4;if(E||x){let f=String(w).padStart(3," ");terminal.clearActiveProgressLine(),process.stderr.write(` \u{1F4A1} [${f}%] ${h.stage}: ${h.processed}/${h.total} files`),d._lastPct=w,d._lastProgressAt=u;}}),m=s.getDatabase().getIndexState();a={rootDir:e,success:c.success,filesAdded:c.filesAdded,filesUpdated:c.filesUpdated,filesDeleted:c.filesDeleted,filesSkipped:c.filesSkipped,nodesCreated:c.nodesCreated,edgesCreated:c.edgesCreated,errorCount:c.errors.length,errors:c.errors,durationMs:c.duration,indexState:m};}finally{terminal.clearActiveProgressLine(),terminal.unregisterActiveProgressLine(process.stderr),await s.close();}return a}function Te(o){let e=[];if(e.push("Codebase sync"),e.push(` rootDir: ${o.rootDir}`),e.push(` success: ${o.success?"\u2713":"\u2717"}`),e.push(` indexState: ${o.indexState}`),e.push(""),e.push(" Files"),e.push(` \u2139 added: ${o.filesAdded}`),e.push(` \u2139 updated: ${o.filesUpdated}`),e.push(` \u2139 deleted: ${o.filesDeleted}`),e.push(` \u2139 skipped: ${o.filesSkipped} (no-change: hash matches; parser-rejected: 0 nodes)`),e.push(""),e.push(" Graph"),e.push(` \u2139 nodes created: ${o.nodesCreated}`),e.push(` \u2139 edges created: ${o.edgesCreated}`),e.push(` duration: ${o.durationMs}ms`),o.errorCount>0){e.push(` errors (${o.errorCount}):`);for(let n of o.errors.slice(0,10))e.push(` - ${n.filePath}: ${n.error}`);o.errors.length>10&&e.push(` ... and ${o.errors.length-10} more`);}return e.join(`
3
+ `)}function Fe(o){let e={};for(let n of o)n==="--keep-config"?e.keepConfig=true:n==="--no-reindex"?e.noReindex=true:n==="--no-embed"?e.noEmbed=true:n==="--force"||n==="-f"?e.force=true:n==="--json"?e.json=true:(n==="--help"||n==="-h")&&(e.help=true);return e}async function Le(o){let e=await chunkY7JDLK56_cjs.b.getRootDir();chunkTBDAGLC4_cjs.a(e);let t=chunkTBDAGLC4_cjs.c(e),i=chunkTBDAGLC4_cjs.b(e),r=false,l=false;for(let d of [t,`${t}-wal`,`${t}-shm`])if(fs.existsSync(d))try{fs.rmSync(d,{force:!0}),d===t&&(r=!0);}catch{}if(!o.keepConfig&&fs.existsSync(i))try{fs.rmSync(i,{force:!0}),l=!0;}catch{}await v({force:true});let s=false,a;if(!o.noReindex){let d=await V({noEmbed:o.noEmbed,quiet:true});s=true,a={filesProcessed:d.filesProcessed,nodesCreated:d.nodesCreated,edgesCreated:d.edgesCreated,durationMs:d.durationMs,embedded:d.embedded};}return {rootDir:e,removedDb:r,removedConfig:l,recreated:true,reindexed:s,configPath:i,indexSummary:a}}function Me(o){let e=[];return e.push("Codebase recreate"),e.push(` rootDir: ${o.rootDir}`),e.push(` removed db: ${o.removedDb?"\u2713":"\u2717 (not found)"}`),e.push(` removed config:${o.removedConfig?"\u2713":"(preserved via --keep-config or absent)"}`),e.push(` \u2713 reinitialized at ${o.configPath}`),o.reindexed&&o.indexSummary?e.push(` \u2713 reindexed in ${o.indexSummary.durationMs}ms (files: ${o.indexSummary.filesProcessed}, nodes: ${o.indexSummary.nodesCreated}, edges: ${o.indexSummary.edgesCreated}, embed: ${o.indexSummary.embedded?"on":"off"})`):e.push(" \u2139 reindex skipped (--no-reindex). Next: run `easbot codebase index` to rebuild the index."),e.join(`
4
+ `)}function Ae(o){let e={};for(let n of o)n==="--keep-embeddings"?e.keepEmbeddings=true:n==="--force"||n==="-f"?e.force=true:n==="--json"?e.json=true:(n==="--help"||n==="-h")&&(e.help=true);return e}async function qe(o){let e=await chunkY7JDLK56_cjs.b.getRootDir();chunkTBDAGLC4_cjs.a(e);let t=chunkTBDAGLC4_cjs.c(e),i=chunkTBDAGLC4_cjs.b(e);if(!fs.existsSync(t))return await v(),{rootDir:e,cleared:false,nodesRemoved:0,edgesRemoved:0,filesRemoved:0,embeddingsPreserved:false,configPreserved:fs.existsSync(i),nextIndexState:"uninitialized"};let{CodeBase:r}=await import('./code-base-5BXR4FUU.cjs'),{DEFAULT_EMBEDDING_CONFIG:l,DEFAULT_INDEXER_CONFIG:s,DEFAULT_PARSER_CONFIG:a}=await import('@easbot/types'),d=new r({workspaceDir:e,database:{path:t,walMode:true},embedding:o.keepEmbeddings?l:void 0,indexer:s,parser:a,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}}),c;try{await d.initialize();let m={nodes:d.getDatabase().getNodeCount(),edges:d.getDatabase().getEdgeCount(),files:d.getDatabase().getFileCount()};await d.clear({keepEmbeddings:!!o.keepEmbeddings}),d.getDatabase().setIndexState("uninitialized"),c={rootDir:e,cleared:!0,nodesRemoved:m.nodes,edgesRemoved:m.edges,filesRemoved:m.files,embeddingsPreserved:!!o.keepEmbeddings,configPreserved:fs.existsSync(i),nextIndexState:"uninitialized"};}finally{await d.close();}return c}function Ue(o){let e=[];return e.push("Codebase clear"),e.push(` rootDir: ${o.rootDir}`),o.cleared?(e.push(" \u2713 cleared data"),e.push(` nodes removed: ${o.nodesRemoved}`),e.push(` edges removed: ${o.edgesRemoved}`),e.push(` file hashes removed: ${o.filesRemoved}`),e.push(` embeddings preserved: ${o.embeddingsPreserved?"yes (--keep-embeddings)":"no"}`),e.push(` config preserved: ${o.configPreserved?"\u2713":"\u2717"}`)):(e.push(" \u2717 db not found at .easbot/db/codebase.db \u2014 nothing to clear"),e.push(` config preserved: ${o.configPreserved?"\u2713":"\u2717"}`)),e.push(""),e.push("\u{1F4A1} Next: run `easbot codebase index` to rebuild."),e.join(`
5
+ `)}var Be=new Set(["backend","schema_version","extraction_version"]);function Ro(o){return new Set(["schema_version","extraction_version"]).has(o)?"number":"string"}function Ge(o){let e={},n=[];for(let t of o)t==="--json"?e.json=true:t==="--help"||t==="-h"?e.help=true:t.startsWith("-")||n.push(t);return n.length>0&&(e.subcommand=n[0],e.subcommand==="set"?(n.length>1&&(e.key=n[1]),n.length>2&&(e.value=n[2])):n.length>1&&(e.key=n[1])),e}var _o=new Set(["backend","schema_version","extraction_version"]);async function ze(o){let e=await chunkY7JDLK56_cjs.b.getConfigPath(),n=await chunkY7JDLK56_cjs.b.exists(),t={rootDir:await chunkY7JDLK56_cjs.b.getRootDir(),configPath:n?e:void 0,exists:n,values:null};if(!n)return t;let i=await chunkY7JDLK56_cjs.b.getCodebaseJson();return i?(o.key?(t.key=o.key,t.value=i[o.key]):t.values={...i},t):{...t,exists:false}}async function We(o){if(!o.key)throw new chunkW5SMGCKO_cjs.b.ConfigError({message:"config set requires <key>"});if(o.value===void 0)throw new chunkW5SMGCKO_cjs.b.ConfigError({message:"config set requires <value> after <key>",field:o.key});if(!Be.has(o.key))throw new chunkW5SMGCKO_cjs.b.ConfigError({message:`Unsupported config key: "${o.key}". Allowed: ${Array.from(Be).join(", ")}`,field:o.key});let e=await chunkY7JDLK56_cjs.b.getConfigPath();if(!await chunkY7JDLK56_cjs.b.exists())throw new chunkW5SMGCKO_cjs.b.ConfigError({message:`codebase not initialized at ${await chunkY7JDLK56_cjs.b.getRootDir()} \u2014 run \`easbot codebase init\` first`});let n=o.value;if(Ro(o.key)==="number"){let l=Number(o.value);if(!Number.isFinite(l))throw new chunkW5SMGCKO_cjs.b.ConfigError({message:`config key "${o.key}" expects a number, got "${o.value}"`,field:o.key});n=l;}let i=await chunkY7JDLK56_cjs.b.getCodebaseJson()??{},r=i[o.key];return i[o.key]=n,await chunkY7JDLK56_cjs.b.writeCodebaseJson(i),{rootDir:await chunkY7JDLK56_cjs.b.getRootDir(),configPath:e,key:o.key,oldValue:r,newValue:n,requiresRestart:_o.has(o.key)}}function Je(o){if(!o.exists)return `\u2717 config not found at ${o.configPath??"/.easbot/codebase.json"} \u2014 run \`easbot codebase init\` first`;let e=[];if(e.push(`Codebase config: ${o.configPath}`),o.key!==void 0)e.push(` ${o.key}: ${JSON.stringify(o.value)}`);else if(o.values)for(let[n,t]of Object.entries(o.values))e.push(` ${n}: ${JSON.stringify(t)}`);return e.join(`
6
+ `)}function Ke(o){let e=[];return e.push(`\u2713 ${o.key}: ${JSON.stringify(o.oldValue)} \u2192 ${JSON.stringify(o.newValue)} (${o.configPath})`),o.requiresRestart&&(e.push(""),e.push(" \u26A0\uFE0F this setting affects db connection / sync behavior \u2014 restart CodeBase or run `easbot codebase recreate` for the change to take effect.")),e.join(`
7
+ `)}function Ye(o){let e={};for(let n of o)n==="--schema"?e.schema=true:n==="--force"||n==="-f"?e.force=true:n==="--backup"||n==="-b"?e.backup=true:n==="--dry-run"||n==="-n"?e.dryRun=true:n==="--json"?e.json=true:(n==="--help"||n==="-h")&&(e.help=true);return e}async function Qe(o){let e=await chunkY7JDLK56_cjs.b.getRootDir(),n=chunkTBDAGLC4_cjs.a(e),t=chunkTBDAGLC4_cjs.c(e);if(!fs.existsSync(n)||!fs.existsSync(t))throw new utils.NameErrors.OperationFailedError({message:`codebase not initialized at ${e} \u2014 run \`easbot codebase init\` first`,operation:"codebase-not-initialized",target:e});let{DatabaseManager:i}=await import('./database-manager-LTHK7MM6.cjs'),r=new i(t);try{let l=r.db,s=r.isIndexStale(),a=r.getMeta("indexed_with_extraction_version"),d=a?parseInt(a,10):null,c=r.getIndexState(),m=r.getMeta("schema_version"),h=m?parseInt(m,10):0,p={rootDir:e,dbPath:t,wasStale:s,previousVersion:d??null,currentVersion:chunkOZYQQS63_cjs.e,applied:!1,schemaMigrated:!1,previousSchemaVersion:h,currentSchemaVersion:h,dryRun:!!o.dryRun,schemaSteps:chunkOZYQQS63_cjs.b.map(f=>({id:f.id,description:f.description,status:"pending"})),migrationErrors:[],indexState:c},w;if(o.backup!==!1&&!o.dryRun)try{let f=new Date().toISOString().replace(/[:.]/g,"-");w=path.join(n,`codebase.db.bak.${f}`),fs.copyFileSync(t,w);for(let N of ["-wal","-shm"]){let g=t+N;fs.existsSync(g)&&fs.copyFileSync(g,w+N);}p.backupPath=w;}catch(f){let N=utils.errorMeta(f).message;p.recommendation=`Backup failed: ${N}. Continuing without backup.`;}let E=o.schema!==!1;try{let f=chunkOZYQQS63_cjs.c(l,chunkOZYQQS63_cjs.a,{dryRun:o.dryRun});p.currentSchemaVersion=o.dryRun?f.targetVersion:Math.max(f.currentVersion,f.targetVersion),p.migrationErrors=f.errors.map(g=>({migrationId:g.migrationId,error:g.error}));let N=new Set(f.applied);for(let g of p.schemaSteps)N.has(g.id)&&(g.status=o.dryRun?"pending":"applied");for(let g of p.migrationErrors){let y=p.schemaSteps.find(S=>S.id===g.migrationId);y&&(y.status="failed");}if(p.schemaMigrated=f.applied.length>0&&!o.dryRun,!o.dryRun){let g=chunkOZYQQS63_cjs.d(l);p.currentSchemaVersion=g,g>0&&r.setMeta("schema_version",String(g));}}catch(f){let N=utils.errorMeta(f).message;p.migrationErrors.push({migrationId:0,error:N});}let x=s||o.force;return x&&!o.dryRun&&(r.setMeta("indexed_with_extraction_version",String(chunkOZYQQS63_cjs.e)),(c==="stale"||c==="failed")&&(r.setIndexState("complete"),p.indexState="complete"),p.applied=!0),o.dryRun?p.migrationErrors.length>0?p.recommendation="dry-run finished. Run without --dry-run to apply.":p.schemaMigrated?p.recommendation="dry-run: schema migration would apply. Run without --dry-run to apply.":p.recommendation="dry-run: nothing to apply.":!x&&!p.schemaMigrated&&p.migrationErrors.length===0?p.recommendation=`Already current (schema_version=${p.currentSchemaVersion}, extraction_version=${chunkOZYQQS63_cjs.e}). No upgrade needed.`:p.migrationErrors.length>0?p.recommendation=`Schema migration completed with ${p.migrationErrors.length} error(s). `+(p.backupPath?`Restore from backup: ${p.backupPath}`:"Re-run `recreate` to drop & rebuild."):p.schemaMigrated&&!x?p.recommendation=`Schema migrated (v${p.previousSchemaVersion} \u2192 v${p.currentSchemaVersion}). To apply extraction changes, run \`recreate\` to rebuild data or \`index --force\`.`:p.schemaMigrated&&x?p.recommendation="Schema + extraction metadata both updated. To rebuild data with new extractor, run `recreate` or `index --force`.":p.recommendation="Extraction metadata updated. No schema changes needed.",p}finally{r.close();}}function Xe(o){let e=[];if(e.push(`Codebase upgrade${o.dryRun?" (dry-run)":""}`),e.push(` db: ${o.dbPath}`),o.backupPath&&e.push(` backup: ${o.backupPath}`),e.push(` previous version: ${o.previousVersion??"(none)"}`),e.push(` current version: ${o.currentVersion}`),e.push(` previous schema_version: ${o.previousSchemaVersion}`),e.push(` current schema_version: ${o.currentSchemaVersion}`),e.push(` was stale: ${o.wasStale?"yes":"no"}`),e.push(` applied: ${o.applied?"\u2713":"(noop \u2014 already current)"}`),(o.schemaSteps??[]).length>0){e.push(""),e.push(" schema steps:");for(let n of o.schemaSteps){let t=n.status==="applied"?"\u2713":n.status==="pending"?"\xB7":n.status==="failed"?"\u2717":"-";e.push(` [${t}] v${n.id}: ${n.description}`);}}if((o.migrationErrors??[]).length>0){e.push(""),e.push(` migration errors: ${o.migrationErrors.length}`);for(let n of o.migrationErrors)e.push(` - v${n.migrationId}: ${n.error}`);}return e.push(` index_state: ${o.indexState}`),o.recommendation&&(e.push(""),e.push(` \u{1F4A1} ${o.recommendation}`)),e.join(`
8
+ `)}var vo=utils.Log.create({service:"codebase.cmd.embed"});function et(o){let e={};for(let n of o)if(n==="--all")e.all=true;else if(n==="--dry-run"||n==="-n")e.dryRun=true;else if(n==="--pending-list"||n==="-p")e.pendingList=true;else if(n.startsWith("--batch=")){let t=parseInt(n.slice(8),10);Number.isFinite(t)&&t>0&&(e.batchSize=t);}else n==="--json"?e.json=true:(n==="--help"||n==="-h")&&(e.help=true);return e}var Io=200;function Oo(o,e=Io){return o?o.length<=e?o:o.slice(0,e)+"\u2026":""}async function tt(o){var p=[];try{let e=await chunkY7JDLK56_cjs.b.getRootDir();let n=chunkTBDAGLC4_cjs.a(e);let t=chunkTBDAGLC4_cjs.c(e);if(!fs.existsSync(n))throw new utils.NameErrors.OperationFailedError({message:`codebase not initialized at ${e} \u2014 run \`easbot codebase init\` first`,operation:"codebase-not-initialized",target:e});if(!fs.existsSync(t))throw new utils.NameErrors.OperationFailedError({message:`db not found at ${t} \u2014 run \`easbot codebase index\` first to build`,operation:"db-not-found",target:t});let i=Date.now();let r=chunkKFESJR3T_cjs.b(p,vo.time("codebaseEmbed",{level:"DEBUG",dbPath:t}));let l=process.env.EASBOT_EMBEDDING_MODEL;if(!o.dryRun&&!l)throw new utils.NameErrors.MissingFieldError({field:"EASBOT_EMBEDDING_MODEL",message:'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:s}=await import('./code-base-5BXR4FUU.cjs');let{DEFAULT_EMBEDDING_CONFIG:a,DEFAULT_INDEXER_CONFIG:d,DEFAULT_PARSER_CONFIG:c}=await import('@easbot/types');let m={...a,modelId:l??"(dry-run)"};let h=new s({workspaceDir:e,database:{path:t,walMode:!0},embedding:m,indexer:d,parser:c,sync:{onBoot:!1,onSearch:!1,onSessionStart:!1,intervalMs:0}});try{await h.initialize();let x=h.getDatabase(),f=x.getNodeCount(),N=x.queryAll("SELECT node_id FROM node_embeddings"),g=new Set(N.map(C=>C.node_id)),y;if(o.all)y=x.queryAll("SELECT id, name, ast_type, language, file_path, text FROM nodes");else if(g.size===0)y=x.queryAll("SELECT id, name, ast_type, language, file_path, text FROM nodes");else {let C=Array.from(g),D=C.map(()=>"?").join(",");y=x.queryAll(`SELECT id, name, ast_type, language, file_path, text FROM nodes WHERE id NOT IN (${D})`,C);}let S=y.map(C=>({id:C.id,name:C.name,ast_type:C.ast_type,file_path:C.file_path,language:C.language,text_preview:Oo(C.text)})),O={rootDir:e,dbPath:t,totalNodes:f,alreadyEmbedded:g.size,newlyEmbedded:0,failed:0,all:!!o.all,dryRun:!!o.dryRun,pendingList:o.pendingList?S:[],duration:Date.now()-i,embeddingModelConfigured:!!l};return o.dryRun?O.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?O.recommendation="All nodes already have embeddings. Use --all to force regenerate.":O.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).`,O}finally{await h.close();}}catch(w){var u=w,E=true;}finally{chunkKFESJR3T_cjs.c(p,u,E);}}function ot(o){let e=[],n=o.dryRun?" (dry-run)":"";if(e.push(`Codebase embed${n}`),e.push(` db: ${o.dbPath}`),e.push(` mode: ${o.all?"all (force regenerate)":"incremental (only missing)"}`),e.push(` embedding model: ${o.embeddingModelConfigured?"configured":"(none)"}`),e.push(` total nodes: ${o.totalNodes}`),e.push(` already embedded: ${o.alreadyEmbedded}`),e.push(` newly embedded: ${o.newlyEmbedded}`),o.failed>0&&e.push(` failed: ${o.failed}`),e.push(` pending: ${o.pendingList.length}`),e.push(` duration: ${o.duration}ms`),o.dryRun&&o.pendingList.length>0){e.push(""),e.push(" \u{1F4A1} first 5 pending nodes:");for(let t of o.pendingList.slice(0,5))e.push(` - ${t.id} (${t.ast_type})`);}return o.recommendation&&(e.push(""),e.push(` \u{1F4A1} ${o.recommendation}`)),e.join(`
9
+ `)}var nt=utils.Log.create({service:"codebase.command.watch"});function st(o){let e={};for(let n of o)if(n.startsWith("--debounce=")){let t=parseInt(n.slice(11),10);Number.isFinite(t)&&t>0&&(e.debounce=t);}else if(n.startsWith("--interval=")){let t=parseInt(n.slice(11),10);Number.isFinite(t)&&t>0&&(e.interval=t);}else if(n.startsWith("--backend=")){let t=n.slice(10);(t==="fs-events"||t==="inotify"||t==="windows"||t==="brute-force"||t==="watchman"||t==="auto")&&(e.backend=t);}else n.startsWith("--ignore=")?(e.ignore||(e.ignore=[]),e.ignore.push(n.slice(9))):n==="--on-load-failure=throw"?e.onLoadFailure="throw":n==="--on-load-failure=warn"?e.onLoadFailure="warn":n==="--json"?e.json=true:(n==="--help"||n==="-h")&&(e.help=true);return e}async function it(o){let e=await chunkY7JDLK56_cjs.b.getRootDir(),n=chunkTBDAGLC4_cjs.a(e);fs.existsSync(n)||await v();let t=new chunkJEHVBEBS_cjs.a({workspaceDir:e,backend:o.backend??"auto",ignorePatterns:o.ignore,onLoadFailure:o.onLoadFailure??"warn"}),i=[];t.on((r,l)=>{let s={event:r,relPath:l,at:Date.now()};i.push(s),nt.debug("watch event",{event:r,relPath:l});let a=`[${new Date(s.at).toISOString()}]`,d=r==="add"?"\x1B[32m+ ADD \x1B[0m":r==="change"?"\x1B[33m~ CHANGE\x1B[0m":"\x1B[31m- UNLINK\x1B[0m";process.stdout.write(`${a} ${d} ${l}
10
+ `);}),await t.start();try{await chunkJEHVBEBS_cjs.d(n,process.pid);}catch(r){nt.warn("failed to write watcher pid",{error:utils.errorMeta(r)});}return {watcher:t,events:i,startTime:Date.now()}}function at(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(`
11
+ `)}function rt(o){let e={};for(let n of o)n==="--force"||n==="-f"?e.force=true:n==="--json"?e.json=true:(n==="--help"||n==="-h")&&(e.help=true);return e}async function ct(o){let e=await chunkY7JDLK56_cjs.b.getRootDir(),n=chunkTBDAGLC4_cjs.a(e);fs.existsSync(n)||await v();let t=path.join(n,".watcher.pid"),i=chunkJEHVBEBS_cjs.c(n);if(i===null)return {rootDir:e,pidFile:t,pid:null,stopped:false,error:"No watcher running (no .easbot/.watcher.pid found)"};try{return process.kill(i,"SIGTERM"),await chunkJEHVBEBS_cjs.e(n),{rootDir:e,pidFile:t,pid:i,stopped:!0}}catch(r){await chunkJEHVBEBS_cjs.e(n);let l=utils.errorMeta(r).message;return {rootDir:e,pidFile:t,pid:i,stopped:false,error:l}}}function lt(o){let e=[];return e.push("Codebase stop"),e.push(` pid file: ${o.pidFile}`),e.push(` pid: ${o.pid??"(none)"}`),e.push(` stopped: ${o.stopped?"\u2713":"\u2717"}`),o.error?(e.push(` error: ${o.error}`),e.push(""),e.push(" \u{1F4A1} If a stale watcher was running, its process may have already exited.")):(e.push(""),e.push(" \u{1F4A1} Use `easbot codebase watch` to start a new watcher session.")),e.join(`
12
+ `)}var Uo=utils.Log.create({service:"codebase.cmd.query"}),Bo=200;function pt(o){let e={includeEdges:true,enableEmbedding:true},n=[];for(let t of o)if(t==="--help"||t==="-h")e.help=true;else if(t==="--json")e.json=true;else if(t==="--no-edges")e.includeEdges=false;else if(t==="--no-vector"||t==="--no-embed")e.enableEmbedding=false;else if(t.startsWith("-l=")||t.startsWith("--language="))e.language=t.includes("=")?t.split("=")[1]:void 0;else if(!(t==="-l"||t==="--language"))if(t.startsWith("--ast="))e.astType=t.slice(6);else if(t.startsWith("-n=")||t.startsWith("--max=")){let i=parseInt(t.split("=")[1]??"",10);Number.isFinite(i)&&i>0&&(e.maxResults=i);}else t.startsWith("-")||n.push(t);return n.length>0&&(e.query=n.join(" ")),e}async function ut(o){var h=[];try{let e=await chunkY7JDLK56_cjs.b.getRootDir();let n=chunkTBDAGLC4_cjs.a(e);let t=chunkTBDAGLC4_cjs.c(e);fs.existsSync(n)||await v();if(!fs.existsSync(t))throw new utils.NameErrors.OperationFailedError({message:`db not found at ${t} \u2014 run \`easbot codebase index\` first`,operation:"db-not-found",target:t});let{CodeBase:i}=await import('./code-base-5BXR4FUU.cjs');let{DEFAULT_EMBEDDING_CONFIG:r,DEFAULT_INDEXER_CONFIG:l,DEFAULT_PARSER_CONFIG:s,DEFAULT_SEARCH_CONFIG:a}=await import('@easbot/types');let d=new i({workspaceDir:e,database:{path:t,walMode:!0},embedding:o.enableEmbedding?r:void 0,indexer:l,parser:s,search:a,sync:{onBoot:!1,onSearch:!1,onSessionStart:!1,intervalMs:0}});let c=Date.now();let m=chunkKFESJR3T_cjs.b(h,Uo.time("codebaseQuery",{level:"DEBUG",query:o.query}));try{await d.initialize();let x=await d.getQuery().search(o.query??"",{maxResults:o.maxResults??10,language:o.language,astType:o.astType,includeEdges:o.includeEdges,enableEmbedding:o.enableEmbedding});return {rootDir:e,query:o.query??"",totalResults:x.length,results:x.map(f=>({id:f.id,name:f.name,astType:f.ast_type,language:f.language,filePath:f.file_path,startLine:f.start_line??0,endLine:f.end_line??0,snippet:(f.text??"").slice(0,database.resolveSqlTextLimit(Bo)),edgeCount:(f.edges??[]).length})),durationMs:Date.now()-c}}finally{await d.close();}}catch(p){var w=p,u=true;}finally{chunkKFESJR3T_cjs.c(h,w,u);}}function mt(o){let e=[];e.push(`Codebase query: ${JSON.stringify(o.query)}`),e.push(` results: ${o.totalResults} (in ${o.durationMs}ms)`);for(let n of o.results)e.push(` ${n.name} (${n.astType}) \u2014 ${n.language} ${n.filePath}:${n.startLine}-${n.endLine} [${n.edgeCount} edges]`),e.push(` ${n.snippet.replace(/\s+/g," ").slice(0,100)}`);return e.join(`
13
+ `)}function bt(o){let e={includeEdges:false},n=[];for(let t of o)if(t==="--help"||t==="-h")e.help=true;else if(t==="--json")e.json=true;else if(t==="--edges")e.includeEdges=true;else if(t.startsWith("--file="))e.file=t.slice(7);else if(t.startsWith("--kind="))e.kind=t.slice(7);else if(t.startsWith("--max=")){let i=parseInt(t.slice(6),10);Number.isFinite(i)&&i>0&&(e.edgesLimit=i);}else t.startsWith("-")||n.push(t);return n.length>0&&(e.name=n[0],e.nodeId=n[0]),e}async function ht(o){if(!o.name&&!o.nodeId)throw new utils.NameErrors.MissingFieldError({field:"name-or-nodeId",message:"node command requires a <name> or <node-id> argument"});let e=await chunkY7JDLK56_cjs.b.getRootDir(),n=chunkTBDAGLC4_cjs.a(e),t=chunkTBDAGLC4_cjs.c(e);if(fs.existsSync(n)||await v(),!fs.existsSync(t))throw new utils.NameErrors.OperationFailedError({message:`db not found at ${t} \u2014 run \`easbot codebase index\` first`,operation:"db-not-found",target:t});let i={workspaceDir:e,rootDir:e},r;try{r=await chunkCLUGDJA5_cjs.b(i,{name:o.name,nodeId:o.nodeId,file:o.file,kind:o.kind,includeEdges:o.includeEdges??!1,includeContent:!0,maxEdgesPerNode:o.edgesLimit??10});}catch(c){if(c instanceof utils.ServiceError&&c.data?.code==="NOT_FOUND")return {rootDir:e,found:false,incomingEdges:[],outgoingEdges:[]};throw c}if(!r.node)return {rootDir:e,found:false,incomingEdges:[],outgoingEdges:[]};let l=[],s=[],a=r.node.name.split("@")[0]??r.node.name,d=a.includes(".")?a.split(".").pop()??a:a;for(let c of r.edges){let m;if(c.target===r.node.id)m="in";else if(c.source===r.node.id)m="out";else if(c.target.includes(":*:")){let p=(c.target.split(":").pop()??"").split("@")[0]??"";m=a.includes(".")&&p===a||p===d?"in":"out";}else m="out";let h={id:c.id,relation:c.relation,source:c.source,target:c.target,direction:m};(m==="in"?l:s).push(h);}return {rootDir:e,found:true,node:{id:r.node.id,name:r.node.name,astType:r.node.ast_type,language:r.node.language,filePath:r.node.file_path,startLine:r.node.start_line??0,endLine:r.node.end_line??0,text:r.node.text??""},incomingEdges:l,outgoingEdges:s}}function yt(o){if(!o.found||!o.node)return `\u2717 node not found (rootDir: ${o.rootDir})`;let e=[];if(e.push(`Codebase node: ${o.node.id}`),e.push(` name: ${o.node.name}`),e.push(` type: ${o.node.astType}`),e.push(` language: ${o.node.language}`),e.push(` location: ${o.node.filePath}:${o.node.startLine}-${o.node.endLine}`),e.push(` edges: ${o.incomingEdges.length} incoming / ${o.outgoingEdges.length} outgoing`),o.incomingEdges.length>0&&typeof o.incomingEdges[0]=="object"&&"relation"in o.incomingEdges[0]){e.push(""),e.push(" incoming edges:");for(let n of o.incomingEdges.slice(0,20))e.push(` [${n.relation}] ${n.source} \u2192 ${n.target}`);e.push(" outgoing edges:");for(let n of o.outgoingEdges.slice(0,20))e.push(` [${n.relation}] ${n.source} \u2192 ${n.target}`);}return e.join(`
14
+ `)}async function H(o={}){let{CodeBase:e}=await import('./code-base-5BXR4FUU.cjs'),{DEFAULT_EMBEDDING_CONFIG:n,DEFAULT_INDEXER_CONFIG:t,DEFAULT_PARSER_CONFIG:i,DEFAULT_SEARCH_CONFIG:r,DEFAULT_SYNC_CONFIG:l}=await import('@easbot/types'),s=await chunkY7JDLK56_cjs.b.getRootDir(),a=chunkTBDAGLC4_cjs.c(s),d=chunkTBDAGLC4_cjs.a(s);if(!fs.existsSync(d))if(o.autoInit)await v();else throw new utils.NameErrors.OperationFailedError({message:`codebase not initialized at ${s} \u2014 run \`easbot codebase init <dir>\` first`,operation:"codebase-not-initialized",target:s});if(!fs.existsSync(a))throw new utils.NameErrors.OperationFailedError({message:`db not found at ${a} \u2014 run \`easbot codebase index\` first`,operation:"db-not-found",target:a});let c=new e({workspaceDir:s,database:{path:a,walMode:true},embedding:n,indexer:t,parser:i,search:r,sync:{...l,onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0},...o.configOverrides});await c.initialize();let m=false;return {codebase:c,rootDir:s,close:async()=>{if(!m){m=true;try{await c.close();}catch{}}}}}function wt(o){let e={direction:"both"},n=[];for(let t of o)if(t==="--help"||t==="-h")e.help=true;else if(t==="--json")e.json=true;else if(t.startsWith("--depth=")){let i=parseInt(t.slice(8),10);Number.isFinite(i)&&i>0&&(e.depth=i);}else if(t.startsWith("--max=")){let i=parseInt(t.slice(6),10);Number.isFinite(i)&&i>0&&(e.maxNodes=i);}else if(t.startsWith("--direction=")){let i=t.slice(12);(i==="incoming"||i==="outgoing"||i==="both")&&(e.direction=i);}else if(t.startsWith("--relation=")){let i=t.slice(11).split(",").map(r=>r.trim()).filter(Boolean);e.relationTypes=i;}else t.startsWith("-")||n.push(t);return n.length>0&&(e.nodeId=n[0]),e}async function Ct(o){if(!o.nodeId)throw new utils.NameErrors.MissingFieldError({field:"nodeId",message:"context command requires a <node-id> argument"});let e=o.depth??2,n=o.maxNodes??100,t=o.direction??"both",{codebase:i,rootDir:r,close:l}=await H();try{let s=i.getDatabase(),a=i.getQuery();if(!s.getNodeById(o.nodeId))return {rootDir:r,rootNodeId:o.nodeId,depth:e,totalNodes:0,totalEdges:0,nodes:[],edges:[],truncated:!1};let c=new Map,m=[{nodeId:o.nodeId,depth:0}];c.set(o.nodeId,0);let h=[],p=!1;for(;m.length>0;){let f=m.shift();if(f.depth>=e)continue;if(c.size>=n){p=!0;break}let N=a.queryNeighbors(f.nodeId,{direction:t,relationTypes:o.relationTypes,limit:n-c.size+1});for(let g of N.edges){h.push({source:g.source,target:g.target,relation:g.relation});let y=g.source===f.nodeId?g.target:g.source;if(!c.has(y)&&(c.set(y,f.depth+1),m.push({nodeId:y,depth:f.depth+1}),c.size>=n)){p=!0;break}}if(p)break}let w=Array.from(c.keys()),u=w.length>0?s.queryNodes({ids:w}):[],E=new Map(u.map(f=>[f.id,f])),x=[];for(let[f,N]of c.entries()){let g=E.get(f);g&&x.push({id:g.id,name:g.name,astType:g.ast_type,language:g.language,filePath:g.file_path,depth:N});}return {rootDir:r,rootNodeId:o.nodeId,depth:e,totalNodes:x.length,totalEdges:h.length,nodes:x,edges:h,truncated:p}}finally{await l();}}function Et(o){let e=[];e.push(`Codebase context: ${o.rootNodeId} (depth=${o.depth})`),e.push(` nodes: ${o.totalNodes}${o.truncated?" [TRUNCATED]":""}`),e.push(` edges: ${o.totalEdges}`);for(let n of o.nodes.slice(0,50))e.push(` [d=${n.depth}] ${n.name} (${n.astType}) \u2014 ${n.language} ${n.filePath}`);return o.nodes.length>50&&e.push(` ... and ${o.nodes.length-50} more`),e.join(`
15
+ `)}function Rt(o){let e={},n=[];for(let t of o)if(t==="--help"||t==="-h")e.help=true;else if(t==="--json")e.json=true;else if(t.startsWith("-d=")||t.startsWith("--depth=")){let i=parseInt(t.split("=")[1]??"",10);Number.isFinite(i)&&i>0&&(e.depth=i);}else if(t.startsWith("--relation=")){let i=t.slice(11).split(",").map(r=>r.trim()).filter(Boolean);e.relationTypes=i;}else t.startsWith("--file=")?e.file=t.slice(7):t.startsWith("--kind=")?e.kind=t.slice(7):t.startsWith("-")||n.push(t);return n.length>0&&(e.nodeId=n[0]),e}async function _t(o){if(!o.nodeId)throw new utils.NameErrors.MissingFieldError({field:"nodeId",message:"impact command requires a <node-id> argument"});let e=o.depth??3,n=o.relationTypes??["CALLS","REFERENCES","USES"],{rootDir:t,close:i}=await H(),r={workspaceDir:t,rootDir:t};try{let l=await chunkCLUGDJA5_cjs.d(r,{name:o.nodeId,nodeId:o.nodeId,file:o.file,kind:o.kind,depth:e,relationTypes:n,maxResults:200});return {rootDir:t,rootNodeId:l.root?.id??o.nodeId,totalImpacted:l.totalImpacted,depth:e,buckets:l.buckets.map(s=>({depth:s.depth,count:s.count,sample:s.sample.map(a=>({id:a.id,name:a.name,filePath:a.filePath}))}))}}finally{await i();}}function kt(o){let e=[];e.push(`Codebase impact: ${o.rootNodeId} (depth=${o.depth})`),e.push(` total impacted: ${o.totalImpacted}`);for(let n of o.buckets){e.push(` d=${n.depth}: ${n.count} nodes`);for(let t of n.sample.slice(0,5))e.push(` - ${t.name} (${t.filePath})`);}return e.join(`
16
+ `)}var Ko="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",Vo=[new RegExp(`(?:^|/)(?:main|index|app|server)\\.(?:${Ko})$`)];function Dt(o){let e={excludeEntry:true};for(let n of o)if(n==="--help"||n==="-h")e.help=true;else if(n==="--json")e.json=true;else if(n==="--no-exclude-entry")e.excludeEntry=false;else if(n.startsWith("--type="))e.astTypes=n.slice(7).split(",").map(t=>t.trim()).filter(Boolean);else if(n.startsWith("--limit=")){let t=parseInt(n.slice(8),10);Number.isFinite(t)&&t>0&&(e.limit=t);}return e}async function vt(o){let e=await chunkY7JDLK56_cjs.b.getRootDir(),n=chunkTBDAGLC4_cjs.a(e),t=chunkTBDAGLC4_cjs.c(e);if(fs.existsSync(n)||await v(),!fs.existsSync(t))throw new utils.NameErrors.OperationFailedError({message:`db not found at ${t} \u2014 run \`easbot codebase index\` first`,operation:"db-not-found",target:t});let i=o.astTypes??["function","method","class"],r=o.limit??100,l=o.excludeEntry!==false,{CodeBase:s}=await import('./code-base-5BXR4FUU.cjs'),{DEFAULT_EMBEDDING_CONFIG:a,DEFAULT_INDEXER_CONFIG:d,DEFAULT_PARSER_CONFIG:c,DEFAULT_SEARCH_CONFIG:m}=await import('@easbot/types'),h=new s({workspaceDir:e,database:{path:t,walMode:true},embedding:a,indexer:d,parser:c,search:m,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});try{await h.initialize();let p=h.getDatabase(),w=h.getQuery(),u=[],E=0,x=["CALLS","IMPORTS","TYPE_REFERENCES"],f=p.queryAll("SELECT DISTINCT target FROM edges WHERE relation IN ('CALLS','IMPORTS','TYPE_REFERENCES')"),N=new Set(f.map(g=>g.target));for(let g of i){let y=p.queryNodes({astType:g,limit:1e5});for(let S of y){if(l&&Vo.some(O=>O.test(S.file_path))){E++;continue}if(!N.has(S.id)&&(u.push({id:S.id,name:S.name,astType:S.ast_type,filePath:S.file_path,startLine:S.start_line??0}),u.length>=r))break}if(u.length>=r)break}return {rootDir:e,totalCandidates:u.length,excludedEntry:E,candidates:u.slice(0,r)}}finally{await h.close();}}function It(o){let e=[];e.push("Codebase dead-code"),e.push(` total candidates: ${o.totalCandidates}`),o.excludedEntry>0&&e.push(` excluded (entry files): ${o.excludedEntry}`);for(let n of o.candidates.slice(0,50))e.push(` - ${n.name} (${n.astType}) \u2014 ${n.filePath}:${n.startLine}`);return o.candidates.length>50&&e.push(` ... and ${o.candidates.length-50} more`),e.join(`
17
+ `)}function jt(o){let e={relation:"IMPORTS",scope:"file"};for(let n of o)if(n==="--help"||n==="-h")e.help=true;else if(n==="--json")e.json=true;else if(n.startsWith("--relation="))e.relation=n.slice(11);else if(n.startsWith("--scope=")){let t=n.slice(8);(t==="file"||t==="module")&&(e.scope=t);}return e}function Yo(o){let e=0,n=new Map,t=new Map,i=new Set,r=[],l=[];function s(a){n.set(a,e),t.set(a,e),e++,r.push(a),i.add(a);let d=o.get(a)??[];for(let c of d)n.has(c)?i.has(c)&&t.set(a,Math.min(t.get(a),n.get(c))):(s(c),t.set(a,Math.min(t.get(a),t.get(c))));if(t.get(a)===n.get(a)){let c=[],m;do m=r.pop(),i.delete(m),c.push(m);while(m!==a);c.length>1&&l.push(c);}}for(let a of o.keys())n.has(a)||s(a);return l}async function Tt(o){let e=await chunkY7JDLK56_cjs.b.getRootDir(),n=chunkTBDAGLC4_cjs.a(e),t=chunkTBDAGLC4_cjs.c(e);if(fs.existsSync(n)||await v(),!fs.existsSync(t))throw new utils.NameErrors.OperationFailedError({message:`db not found at ${t} \u2014 run \`easbot codebase index\` first`,operation:"db-not-found",target:t});let i=o.relation??"IMPORTS",{CodeBase:r}=await import('./code-base-5BXR4FUU.cjs'),{DEFAULT_EMBEDDING_CONFIG:l,DEFAULT_INDEXER_CONFIG:s,DEFAULT_PARSER_CONFIG:a,DEFAULT_SEARCH_CONFIG:d}=await import('@easbot/types'),c=new r({workspaceDir:e,database:{path:t,walMode:true},embedding:l,indexer:s,parser:a,search:d,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});try{await c.initialize();let m=c.getDatabase(),h=m.queryNodes({limit:1e5}),p=new Map;for(let y of h){let S=p.get(y.file_path)??[];S.push(y.id),p.set(y.file_path,S);}let w=h.map(y=>y.id),u=new Map;for(let y of h)u.set(y.id,y.file_path);let E;if(w.length===0)E=[];else {let y=w.map(()=>"?").join(",");E=m.queryAll(`SELECT * FROM edges WHERE relation = ? AND source IN (${y})`,[i,...w]);}let x=new Map;for(let y of E){let S=u.get(y.source),O=u.get(y.target);if(!S||!O||S===O)continue;let C=x.get(S);C||(C=new Set,x.set(S,C)),C.add(O);}let f=new Map;for(let[y,S]of x.entries())f.set(y,Array.from(S));let g=Yo(f).map(y=>{let S=[];for(let O=0;O<y.length;O++){let C=y[O],D=x.get(C);if(D)for(let P of D)y.includes(P)&&S.push({source:C,target:P});}return {cycle:y,edges:S}});return {rootDir:e,relation:i,totalCycles:g.length,cycles:g.slice(0,50)}}finally{await c.close();}}function $t(o){let e=[];e.push(`Codebase circular (relation=${o.relation})`),e.push(` total cycles: ${o.totalCycles}`);for(let n=0;n<o.cycles.length;n++){let t=o.cycles[n];e.push(` cycle #${n+1} (${t.cycle.length} files):`),e.push(` ${t.cycle.join(" \u2192 ")} \u2192 ${t.cycle[0]}`);}return e.join(`
18
+ `)}function Lt(o){let e={},n=[];for(let t of o)if(t==="--help"||t==="-h")e.help=true;else if(t==="--json")e.json=true;else if(t.startsWith("-d=")||t.startsWith("--depth=")){let i=parseInt(t.split("=")[1]??"",10);Number.isFinite(i)&&i>0&&(e.depth=i);}else if(t.startsWith("--relation=")){let i=t.slice(11).split(",").map(r=>r.trim()).filter(Boolean);e.relationTypes=i;}else t.startsWith("-")||n.push(t);return n.length>0&&(e.fromId=n[0]),n.length>1&&(e.toId=n[1]),e}async function Mt(o){let e=await chunkY7JDLK56_cjs.b.getRootDir(),n=chunkTBDAGLC4_cjs.a(e),t=chunkTBDAGLC4_cjs.c(e);if(fs.existsSync(n)||await v(),!fs.existsSync(t))throw new utils.NameErrors.OperationFailedError({message:`db not found at ${t} \u2014 run \`easbot codebase index\` first`,operation:"db-not-found",target:t});if(!o.fromId||!o.toId)throw new utils.NameErrors.MissingFieldError({field:"from-to",message:"path command requires <from> and <to> node IDs"});let i=o.depth??6,r=o.relationTypes??["CALLS","IMPORTS"],{CodeBase:l}=await import('./code-base-5BXR4FUU.cjs'),{DEFAULT_EMBEDDING_CONFIG:s,DEFAULT_INDEXER_CONFIG:a,DEFAULT_PARSER_CONFIG:d,DEFAULT_SEARCH_CONFIG:c}=await import('@easbot/types'),m=new l({workspaceDir:e,database:{path:t,walMode:true},embedding:s,indexer:a,parser:d,search:c,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});try{await m.initialize();let h=m.getQuery();if(o.fromId===o.toId)return {rootDir:e,found:!0,depth:0,steps:[],pathNodes:[o.fromId]};let p=new Set([o.fromId]),w=new Map,u=[o.fromId],E=!1;e:for(let g=0;g<=i;g++){let y=[];for(let S of u){let O=h.queryNeighbors(S,{direction:"both",relationTypes:r,limit:1e3});for(let C of O.edges){let D=C.source===S?C.target:C.source;if(!p.has(D)){if(p.add(D),w.set(D,{via:S,relation:C.relation}),D===o.toId){E=!0;break e}y.push(D);}}}u.length=0,u.push(...y);}if(!E)return {rootDir:e,found:!1,depth:0,steps:[],pathNodes:[]};let x=[o.toId],f=[],N=o.toId;for(;N!==o.fromId;){let g=w.get(N);if(!g)break;f.unshift({from:g.via,to:N,relation:g.relation}),x.unshift(g.via),N=g.via;}return {rootDir:e,found:!0,depth:f.length,steps:f,pathNodes:x}}finally{await m.close();}}function At(o){let e=[];if(!o.found)return e.push("Codebase path: NOT FOUND within depth limit"),e.join(`
19
+ `);e.push(`Codebase path: depth=${o.depth}`);for(let n=0;n<o.steps.length;n++){let t=o.steps[n];e.push(` ${n+1}. [${t.relation}] ${t.from} \u2192 ${t.to}`);}return e.join(`
20
+ `)}function Bt(o){let e={};for(let n of o)(n==="--help"||n==="-h")&&(e.help=true);return e}async function Gt(o){let e=await chunkY7JDLK56_cjs.b.getRootDir(),n=chunkTBDAGLC4_cjs.a(e),t=chunkTBDAGLC4_cjs.c(e);if(fs.existsSync(n)||await v(),!fs.existsSync(t))throw new utils.NameErrors.OperationFailedError({message:`db not found at ${t} \u2014 run \`easbot codebase index\` first`,operation:"db-not-found",target:t});let{CodeBase:i}=await import('./code-base-5BXR4FUU.cjs'),{DEFAULT_EMBEDDING_CONFIG:r,DEFAULT_INDEXER_CONFIG:l,DEFAULT_PARSER_CONFIG:s,DEFAULT_SEARCH_CONFIG:a}=await import('@easbot/types'),{CodebaseStdioServer:d}=await import('./stdio-server-KA3JQB7C.cjs'),c="0.0.0";try{let u=path.dirname(url.fileURLToPath(chunkKFESJR3T_cjs.d));for(let E=0;E<8;E++){try{let f=JSON.parse(fs.readFileSync(path.join(u,"package.json"),"utf-8"));if(f?.name==="@easbot/codebase"&&typeof f.version=="string"){c=f.version;break}}catch{}let x=path.dirname(u);if(x===u)break;u=x;}}catch{}let m=new i({workspaceDir:e,database:{path:t,walMode:true},embedding:r,indexer:l,parser:s,search:a,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});await m.initialize();let h={id:"easbot-codebase-mcp",name:"EASBot Codebase MCP",version:c,transportType:mcp.ServerTransportType.STDIO},p=await d.start(m,h);return {rootDir:e,tools:p.tools}}var sn=utils.Log.create({service:"codebase.command.callers"});function zt(o){let e={maxResults:10},n=[];for(let t of o)if(t==="--help"||t==="-h")e.help=true;else if(t==="--json")e.json=true;else if(t.startsWith("--file="))e.file=t.slice(7);else if(t.startsWith("--kind="))e.kind=t.slice(7);else if(t.startsWith("--max=")){let i=parseInt(t.slice(6),10);Number.isFinite(i)&&i>0&&(e.maxResults=i);}else t.startsWith("-")||n.push(t);return n.length>0&&(e.symbol=n[0]),e}async function Wt(o){if(!o.symbol&&!o.nodeId)throw new utils.NameErrors.MissingFieldError({field:"symbol-or-nodeId",message:"callers command requires a <symbol> or --nodeId argument"});let e=await chunkY7JDLK56_cjs.b.getRootDir(),n=Date.now(),i=await chunkCLUGDJA5_cjs.e({workspaceDir:e,rootDir:e},{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:i.callers.length,rootDir:e}),{rootDir:e,serviceResult:i,durationMs:Date.now()-n}}function Jt(o){let{serviceResult:e,rootDir:n}=o,t=[],i=e.root?.name??"?",r=e.truncated?"+":"";if(t.push(`Callers of \`${i}\` (${e.callers.length}${r}) [${n}]`),e.callers.length===0)t.push(" (no incoming edges)");else for(let l of e.callers)t.push(` - [${l.relation}] \`${l.name}\` ${l.filePath}:${l.startLine}`);return e.callers.length>0&&(t.push(""),t.push("\u{1F4A1} Use `easbot codebase node <name>` to read full source of any caller.")),t.join(`
21
+ `)}var cn=utils.Log.create({service:"codebase.command.callees"});function Kt(o){let e={maxResults:10},n=[];for(let t of o)if(t==="--help"||t==="-h")e.help=true;else if(t==="--json")e.json=true;else if(t.startsWith("--file="))e.file=t.slice(7);else if(t.startsWith("--kind="))e.kind=t.slice(7);else if(t.startsWith("--max=")){let i=parseInt(t.slice(6),10);Number.isFinite(i)&&i>0&&(e.maxResults=i);}else t.startsWith("-")||n.push(t);return n.length>0&&(e.symbol=n[0]),e}async function Vt(o){if(!o.symbol&&!o.nodeId)throw new utils.NameErrors.MissingFieldError({field:"symbol-or-nodeId",message:"callees command requires a <symbol> or --nodeId argument"});let e=await chunkY7JDLK56_cjs.b.getRootDir(),n=Date.now(),i=await chunkCLUGDJA5_cjs.f({workspaceDir:e,rootDir:e},{name:o.symbol,nodeId:o.nodeId,file:o.file,kind:o.kind,maxResults:o.maxResults});return cn.debug("callees command done",{symbol:o.symbol,count:i.callees.length,rootDir:e}),{rootDir:e,serviceResult:i,durationMs:Date.now()-n}}function Ht(o){let{serviceResult:e,rootDir:n}=o,t=[],i=e.root?.name??"?",r=e.truncated?"+":"";if(t.push(`Callees of \`${i}\` (${e.callees.length}${r}) [${n}]`),e.callees.length===0)t.push(" (no outgoing edges)");else for(let l of e.callees)t.push(` - [${l.relation}] \`${l.name}\` ${l.filePath}:${l.startLine}`);return e.callees.length>0&&(t.push(""),t.push("\u{1F4A1} Use `easbot codebase node <name>` to read full source of any callee.")),t.join(`
22
+ `)}var pn=utils.Log.create({service:"codebase.command.explore"});function Yt(o){let e={maxFiles:5,maxSymbols:3,depth:1,includeContent:true},n=[];for(let t of o)if(t==="--help"||t==="-h")e.help=true;else if(t==="--json")e.json=true;else if(t==="--no-content")e.includeContent=false;else if(t.startsWith("--file="))e.file=t.slice(7);else if(t.startsWith("--kind="))e.kind=t.slice(7);else if(t.startsWith("--max-files=")){let i=parseInt(t.slice(12),10);Number.isFinite(i)&&i>0&&(e.maxFiles=i);}else if(t.startsWith("--max-symbols=")){let i=parseInt(t.slice(14),10);Number.isFinite(i)&&i>0&&(e.maxSymbols=i);}else if(t.startsWith("--depth=")){let i=parseInt(t.slice(8),10);Number.isFinite(i)&&i>0&&(e.depth=i);}else t.startsWith("--intent=")?e.intent=t.slice(9):t.startsWith("-")||n.push(t);return n.length>0&&(e.query=n.join(" ")),e}async function Qt(o){if(!o.query)throw new utils.NameErrors.MissingFieldError({field:"query",message:"explore command requires a <query> argument"});let e=await chunkY7JDLK56_cjs.b.getRootDir(),n=Date.now(),i=await chunkCLUGDJA5_cjs.g({workspaceDir:e,rootDir:e},{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 pn.debug("explore command done",{query:o.query,totalHits:i.totalHits,entryPoints:i.entryPoints.length,rootDir:e}),{rootDir:e,serviceResult:i,durationMs:Date.now()-n}}async function Xt(o){let e={pendingFiles:[],toolName:"codebase_explore",writeToDisk:false};return await chunkCLUGDJA5_cjs.F(o.serviceResult,e)}var Zt={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 mn=Zt.languages,gn=mn.filter(o=>o.supported).map(o=>o.value),A={defaultLocale:"zh-CN",locales:gn},J={},Y=(o,e)=>{let n=J[o]||{translation:{}};return J[o]={translation:{...n.translation,...e.translation}},J[o]},Q=(o=A.defaultLocale)=>(J[o]||Y(o,{translation:{}}),{locale:o,resources:J[o]||{translation:{}}});var fn={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\u6570\u636E\u5E93 + \u91CD\u65B0\u521D\u59CB\u5316 + \u91CD\u5EFA\u7D22\u5F15\uFF08\u4E00\u6761\u9F99\uFF09","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 + \u91CD\u65B0\u521D\u59CB\u5316 + \u91CD\u5EFA\u7D22\u5F15\uFF08\u4E00\u6761\u9F99\uFF09","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] [--no-reindex] [--no-embed] [--force] [--json] [dir]","cli.recreate.description":"\u4E22\u5F03\u6574\u4E2A\u6570\u636E\u5E93\uFF08codebase.db + -wal + -shm\uFF09\uFF0C\u91CD\u65B0\u521D\u59CB\u5316\uFF0C\u5E76\u81EA\u52A8\u91CD\u5EFA\u7D22\u5F15\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.no_reindex":"--no-reindex \u8DF3\u8FC7\u81EA\u52A8\u91CD\u5EFA\u7D22\u5F15\u6B65\u9AA4\uFF08\u4E4B\u540E\u9700\u624B\u52A8\u8DD1 `easbot codebase index`\uFF09","cli.recreate.opt.no_embed":"--no-embed \u8F6C\u53D1\u7ED9 runIndex\uFF1A\u8DF3\u8FC7 embedding \u751F\u6210\uFF08\u66F4\u5FEB\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\u9ED8\u8BA4\u60C5\u51B5\u4E0B `recreate` \u4F1A\u5728\u540C\u4E00\u6B21\u8C03\u7528\u4E2D\u91CD\u5EFA\u7D22\u5F15\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]","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.node.usage":"\u7528\u6CD5: easbot codebase node <name|id> [--file=<path>] [--kind=<kind>] [--edges] [--max=N] [--json]","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.context.usage":"\u7528\u6CD5: easbot codebase context <id> [--depth=N] [--max=N] [--direction=<incoming|outgoing|both>] [--relation=<r1,r2,...>] [--json]","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.impact.usage":"\u7528\u6CD5: easbot codebase impact <id> [-d=N | --depth=N] [--relation=<r1,r2,...>] [--json]","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.callers.usage":"\u7528\u6CD5: easbot codebase callers <symbol> [--node-id=<id>] [--file=<path>] [--kind=<kind>] [--max=N] [--json]","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.callees.usage":"\u7528\u6CD5: easbot codebase callees <symbol> [--node-id=<id>] [--file=<path>] [--kind=<kind>] [--max=N] [--json]","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.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]","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.dead_code.usage":"\u7528\u6CD5: easbot codebase dead-code [--type=<t1,t2,...>] [--no-exclude-entry] [--limit=N] [--json]","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.circular.usage":"\u7528\u6CD5: easbot codebase circular [--relation=<r>] [--scope=<file|module>] [--json]","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.path.usage":"\u7528\u6CD5: easbot codebase path <from> <to> [-d=N | --depth=N] [--relation=<r1,r2,...>] [--json]","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.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}}"}},eo=fn;var bn={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 Drop db, re-init, rebuild index in one step","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] [--no-reindex] [--no-embed] [--force] [--json] [dir]","cli.recreate.description":"Discard the entire db (codebase.db + -wal + -shm), re-init, and rebuild the index in one step.","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.no_reindex":"--no-reindex Skip the auto rebuild-index step (manual `easbot codebase index` required after)","cli.recreate.opt.no_embed":"--no-embed Forward to runIndex: skip embedding generation (faster)","cli.recreate.opt.force":"--force, -f Skip safety prompts (for scripts)","cli.recreate.opt.json":"--json Output as JSON","cli.recreate.warn":"\u26A0\uFE0F This deletes the entire index. By default `recreate` also rebuilds the index in the same call.","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]","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.node.usage":"Usage: easbot codebase node <name|id> [--file=<path>] [--kind=<kind>] [--edges] [--max=N] [--json]","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.context.usage":"Usage: easbot codebase context <id> [--depth=N] [--max=N] [--direction=<incoming|outgoing|both>] [--relation=<r1,r2,...>] [--json]","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.impact.usage":"Usage: easbot codebase impact <id> [-d=N | --depth=N] [--relation=<r1,r2,...>] [--json]","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.callers.usage":"Usage: easbot codebase callers <symbol> [--node-id=<id>] [--file=<path>] [--kind=<kind>] [--max=N] [--json]","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.callees.usage":"Usage: easbot codebase callees <symbol> [--node-id=<id>] [--file=<path>] [--kind=<kind>] [--max=N] [--json]","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.explore.usage":"Usage: easbot codebase explore <query> [--file=<path>] [--kind=<kind>] [--max-files=N] [--max-symbols=N] [--depth=N] [--no-content] [--intent=<ctx>] [--json]","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.dead_code.usage":"Usage: easbot codebase dead-code [--type=<t1,t2,...>] [--no-exclude-entry] [--limit=N] [--json]","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.circular.usage":"Usage: easbot codebase circular [--relation=<r>] [--scope=<file|module>] [--json]","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.path.usage":"Usage: easbot codebase path <from> <to> [-d=N | --depth=N] [--relation=<r1,r2,...>] [--json]","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.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}}"}},to=bn;var hn=()=>{Q("zh-CN"),Q("en-US"),Y("zh-CN",eo),Y("en-US",to);};hn();var se=new Map;var ie=new Map;var yn=o=>{if(ie.has(o))return ie.get(o);let e=/{{\s*(\w+)\s*}}/g,n=[],t;for(;(t=e.exec(o))!==null;){let l=t[1];l&&!n.includes(l)&&n.push(l);}let i=new RegExp("{{\\s*("+n.join("|")+")\\s*}}","g"),r={keys:n,regex:i};return ie.set(o,r),r},oo=(o,e)=>{if(!o||typeof o!="string")return "";if(!e||Object.keys(e).length===0)return o;let{regex:n,keys:t}=yn(o);return t.length===0||!t.some(r=>r in e)?o:o.replace(n,(r,l)=>{let s=e[l];return s==null?"":String(s)})},xn=o=>{if(o&&A.locales.includes(o))return o;let e=process.env.EASBOT_LANG?.trim()||process.env.LANG?.trim();if(e){let n=e.replace(/_/g,"-");if(A.locales.includes(n))return n;let t=n.split("-")[0];if(t==="zh")return "zh-CN";if(t==="en")return "en-US"}return A.defaultLocale},no=o=>{if(!se.has(o)){let{resources:e}=Q(o);se.set(o,e);}return se.get(o)},Sn=(o,e={})=>{let n=xn(e.locale),i=no(n)?.translation[o];if(i&&typeof i=="string"){let r=oo(i,e.vars);return r!=null?String(r):String(o)}if(n!==A.defaultLocale){let l=no(A.defaultLocale)?.translation[o];if(l&&typeof l=="string"){let s=oo(l,e.vars);return s!=null?String(s):String(o)}}return String(e.fallback??o)},ae=Sn;var re=utils.Log.create({service:"codebase.cli"});async function Nn(){try{let{Llm:o}=await import('./llm-S6D5ICOO.cjs'),{CodebaseCache:e}=await import('./cache-LSQZJEDR.cjs'),n=await e.getCodebaseJson();o.init({models:{embedding:n?.embedding_model??void 0,evaluation:n?.evaluation_model??void 0},evaluationThreshold:n?.evaluation_threshold});}catch(o){let{errorMeta:e}=await import('@easbot/utils');re.warn("Llm init failed; Llm-related features will be disabled",{error:e(o)});}}function ce(o){return utils.resolveLocaleLang(o?.locale)}function ao(o){let e=(t,i,r)=>ae(t,{locale:o,vars:r,fallback:i}),n=(t,i,r)=>{let l=vn.filter(s=>s.group===t).map(s=>` ${In(s.name)}${e(s.i18nKey,s.description)}`).join(`
23
+ `);return `${e(i,r)}
24
+ ${l}`};return `
25
+ \x1B[1m${e("cli.banner.title","easbot-codebase \u2014 Code Knowledge Graph for EASBot")}\x1B[0m
26
+
27
+ ${e("cli.banner.usage","Usage: easbot-codebase <command> [options]")}
28
+
29
+ ${n("lifecycle","cli.banner.section.lifecycle","Commands (lifecycle):")}
30
+
31
+ ${n("graph","cli.banner.section.graph","Commands (graph query):")}
32
+
33
+ ${n("external","cli.banner.section.external","External:")}
34
+
35
+ Run \x1B[1measbot codebase <command> --help\x1B[0m for details.
36
+
37
+ \x1B[1m${e("cli.banner.local.title","Local CLI:")}\x1B[0m
38
+ ${e("cli.banner.local.body","This package is also published as `easbot-codebase` for standalone use.")}
39
+ ${e("cli.banner.local.agent","Agent CLI users: `easbot codebase <command> ...`")}
40
+ ${e("cli.banner.local.standalone","Standalone users: `easbot-codebase <command> ...`")}
41
+
42
+ \x1B[2m$\x1B[0m easbot-codebase init ${e("cli.cmd.init.description","Initialize .easbot/codebase.json in the target directory")}
43
+ \x1B[2m$\x1B[0m easbot-codebase index ${e("cli.cmd.index.description","Build the full index (creates db if missing)")}
44
+ \x1B[2m$\x1B[0m easbot-codebase status ${e("cli.cmd.status.description","Show index state / db / config")}
45
+ \x1B[2m$\x1B[0m easbot-codebase query <q...> ${e("cli.cmd.query.description","Hybrid search (FTS + vector + basic)")}
46
+ \x1B[2m$\x1B[0m easbot-codebase --help ${e("cli.shared.show_help","Show this help")}
47
+ `}function Dn(o){let e=ce(o);console.log(ao(e));}function vr(o){let e=ce(o);console.log(ao(e));}var vn=[{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",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:"Drop db, re-init, and rebuild the index in one step",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",description:"Start stdio MCP server (exposes 9 codebase tools)",group:"external"}];function In(o){return o.length>=18?o:o+" ".repeat(18-o.length)}var io=false;function On(){if(io)return;io=true;let o=false,e=n=>{o||(o=true,console.error(`
48
+ [codebase] received ${n}, cleaning up...`),setTimeout(()=>process.exit(130),5e3));};process.on("SIGINT",e),process.on("SIGTERM",e);}async function Ir(o,e){On();let n=ce(e),t=(s,a,d)=>ae(s,{locale:n,vars:d,fallback:a});if(await Nn(),o.length===0)return Dn(e),{code:0,handled:false};let i=o[0],r=o.slice(1),l=r.includes("--json");try{switch(i){case "init":{let s=Re(r);if(s.help)return console.log(t("cli.init.usage","Usage: easbot codebase init [dir] [--force] [--json]")),console.log(""),console.log(t("cli.init.description","Initialize .easbot/codebase.json in the target directory.")),console.log(t("cli.init.creates","Creates .easbot/codebase.json with default backend = better-sqlite3.")),console.log(""),console.log(t("cli.shared.options_heading","Options:")),console.log(` ${t("cli.init.opt.force","--force, -f Overwrite existing config.json")}`),console.log(` ${t("cli.init.opt.json","--json Output as JSON (no ANSI)")}`),{code:0,handled:!0,command:i};let a=await v({...s,skipAutoSync:!1});if(s.json){let{business:c,meta:m}=a.skipped?{business:{configPath:a.configPath,backend:a.backend,schemaVersion:a.schemaVersion,created:a.created,skipped:a.skipped},meta:{action:"exists"}}:{business:{configPath:a.configPath,backend:a.backend,schemaVersion:a.schemaVersion,created:a.created,skipped:a.skipped,initialSync:a.initialSync},meta:{action:"created"}};return terminal.emitJsonOk(c,m),{code:0,handled:!0,command:i}}let d={dbPath:a.dbPath};return typeof a.migrationsApplied=="number"&&(d.migrationsApplied=a.migrationsApplied),typeof a.tablesCreated=="number"&&(d.tablesCreated=a.tablesCreated),typeof a.durationMs=="number"&&(d.durationMs=`${a.durationMs}ms`),terminal.printHuman([terminal.formatKnowledgeInit({packageName:"codebase",configPath:a.configPath,backend:a.backend,schemaVersion:a.schemaVersion,skipped:a.skipped===!0,extras:d})],{title:"init codebase workspace",boxed:!0,skipOutro:a.skipped===!0}),{code:0,handled:!0,command:i}}case "status":{let s=jn(r),a=await K(s);return s.json?terminal.emitJsonOk(a,{healthy:a.healthy}):terminal.printHuman([terminal.formatKnowledgeStatus($n(a))],{title:t("cli.cmd.status.description","Show index state / db / config"),boxed:!0}),{code:0,handled:!0,command:i}}case "doctor":{let s=Tn(r);if(s.help)return console.log(t("cli.doctor.usage","Usage: easbot codebase doctor [--json]")),console.log(""),console.log(t("cli.doctor.description","Run health checks (backend, FTS, parser, db integrity).")),console.log(""),console.log(t("cli.shared.options_heading","Options:")),console.log(` ${t("cli.doctor.opt.json","--json Output as JSON (no ANSI)")}`),{code:0,handled:!0,command:i};let a=await ke(s);return s.json?terminal.emitJsonOk(a,{healthy:a.healthy,checkCount:a.checks.length,issueCount:a.issues.length,errorCount:a.checks.filter(d=>d.severity==="error").length,warnCount:a.checks.filter(d=>d.severity==="warn").length}):terminal.printHuman([terminal.formatKnowledgeDoctor(Pn(a))],{title:t("cli.cmd.doctor.description","Run health checks (backend, FTS, parser)"),boxed:!0}),{code:a.healthy?0:1,handled:!0,command:i}}case "index":{let s=De(r);if(s.help)return console.log(t("cli.index.usage","Usage: easbot codebase index [--embed] [--no-embed] [--batch=N] [--json]")),console.log(""),console.log(t("cli.index.description","Build the full index for the target directory.")),console.log(t("cli.index.auto_init","Auto-initializes .easbot/codebase.json if it does not exist.")),console.log(""),console.log(t("cli.shared.options_heading","Options:")),console.log(` ${t("cli.index.opt.embed","--embed Generate node embeddings (default: skip)")}`),console.log(` ${t("cli.index.opt.no_embed","--no-embed Same as default (skip embedding)")}`),console.log(` ${t("cli.index.opt.batch","--batch=N Batch size for indexing (default 50)")}`),console.log(` ${t("cli.index.opt.json","--json Output as JSON (no ANSI)")}`),{code:0,handled:!0,command:i};let a=await V(s);return s.json?terminal.emitJsonOk(a,{success:a.success,noEmbed:s.noEmbed!==!1,batch:s.batch??null,verbose:s.verbose===!0,quiet:s.quiet===!0}):terminal.printHuman([ve(a)],{title:t("cli.cmd.index.description","Build the full index (creates db if missing)")}),{code:a.success?0:1,handled:!0,command:i}}case "sync":{let s=Oe(r);if(s.help)return console.log(t("cli.sync.usage","Usage: easbot codebase sync [--embed] [--no-embed] [--quiet] [--json]")),console.log(""),console.log(t("cli.sync.description","Run incremental sync (only adds/updates/deletes changed files).")),console.log(t("cli.sync.auto_version","Auto-updates meta['indexed_with_version'] on success.")),console.log(""),console.log(t("cli.shared.options_heading","Options:")),console.log(` ${t("cli.sync.opt.embed","--embed Enable node embeddings (default off, FTS-only)")}`),console.log(` ${t("cli.sync.opt.no_embed","--no-embed Explicitly disable embeddings (default)")}`),console.log(` ${t("cli.sync.opt.quiet","--quiet, -q Only print summary")}`),console.log(` ${t("cli.sync.opt.json","--json Output as JSON (no ANSI)")}`),{code:0,handled:!0,command:i};let a=await je(s);return s.json?terminal.emitJsonOk(a,{success:a.success,quiet:s.quiet===!0}):terminal.printHuman([Te(a)],{title:t("cli.cmd.sync.description","Run incremental sync (only changed files)")}),{code:a.success?0:1,handled:!0,command:i}}case "recreate":{let s=Fe(r);if(s.help)return console.log(t("cli.recreate.usage","Usage: easbot codebase recreate [--keep-config] [--no-reindex] [--no-embed] [--force] [--json]")),console.log(""),console.log(t("cli.recreate.description","Discard the entire db (codebase.db + -wal + -shm), re-init, and rebuild the index in one step.")),console.log(t("cli.recreate.equivalent","Equivalent to codegraph `recreate()` for safe index recovery.")),console.log(""),console.log(t("cli.shared.options_heading","Options:")),console.log(` ${t("cli.recreate.opt.keep_config","--keep-config Keep .easbot/codebase.json (only drop db)")}`),console.log(` ${t("cli.recreate.opt.no_reindex","--no-reindex Skip the auto rebuild-index step (manual `easbot codebase index` required after)")}`),console.log(` ${t("cli.recreate.opt.no_embed","--no-embed Forward to runIndex: skip embedding generation (faster)")}`),console.log(` ${t("cli.recreate.opt.force","--force, -f Skip safety prompts (for scripts)")}`),console.log(` ${t("cli.recreate.opt.json","--json Output as JSON")}`),console.log(""),console.log(t("cli.recreate.warn","\u26A0\uFE0F This deletes the entire index. By default `recreate` also rebuilds the index in the same call.")),{code:0,handled:!0,command:i};let a=await Le(s);return s.json?terminal.emitJsonOk(a,{keepConfig:s.keepConfig===!0,force:s.force===!0}):terminal.printHuman([Me(a)],{title:t("cli.cmd.recreate.description","Discard the entire db and re-init"),boxed:!0}),{code:0,handled:!0,command:i}}case "clear":{let s=Ae(r);if(s.help)return console.log(t("cli.clear.usage","Usage: easbot codebase clear [--keep-embeddings] [--force] [--json]")),console.log(""),console.log(t("cli.clear.description","Clear all nodes/edges/file_hashes; keep config.json and meta.")),console.log(t("cli.clear.reset_state",'index_state is reset to "uninitialized" so `status` recommends `index`.')),console.log(""),console.log(t("cli.shared.options_heading","Options:")),console.log(` ${t("cli.clear.opt.keep_embeddings","--keep-embeddings Preserve node_embeddings / embedding_cache")}`),console.log(` ${t("cli.clear.opt.force","--force, -f Skip safety prompts (for scripts)")}`),console.log(` ${t("cli.clear.opt.json","--json Output as JSON")}`),console.log(""),console.log(t("cli.clear.hint","\u{1F4A1} Use `recreate` if you want to drop the entire db file.")),{code:0,handled:!0,command:i};let a=await qe(s);return s.json?terminal.emitJsonOk(a,{keepEmbeddings:s.keepEmbeddings===!0,force:s.force===!0}):terminal.printHuman([Ue(a)],{title:t("cli.cmd.clear.description","Clear all nodes/edges (keep config.json)"),boxed:!0}),{code:0,handled:!0,command:i}}case "config":{let s=Ge(r);if(s.help)return console.log(t("cli.config.usage","Usage: easbot codebase config <get|set> [key] [value] [--json]")),console.log(""),console.log(t("cli.config.description","Read or write .easbot/codebase.json fields.")),console.log(""),console.log(t("cli.config.subcommands","Subcommands:")),console.log(` ${t("cli.config.get","get [key] Show all fields (or a specific key)")}`),console.log(` ${t("cli.config.set","set <key> <value> Update a field (must be in allowlist)")}`),console.log(""),console.log(t("cli.config.allowed_keys","Allowed keys: backend, schema_version, extraction_version, index_state")),console.log(""),console.log(t("cli.shared.options_heading","Options:")),console.log(` ${t("cli.config.opt.json","--json Output as JSON (no ANSI)")}`),{code:0,handled:!0,command:i};if(!s.subcommand)return console.error(t("cli.config.no_subcommand","config requires a subcommand: get | set")),{code:1,handled:!0,command:i};if(s.subcommand==="get"){let a=await ze(s);return s.json?terminal.emitJsonOk(a,{subcommand:"get",key:s.key??null}):terminal.printHuman([Je(a)],{title:t("cli.config.get","get [key] Show all fields (or a specific key)")}),{code:0,handled:!0,command:i}}if(s.subcommand==="set"){let a=await We(s);return s.json?terminal.emitJsonOk(a,{subcommand:"set",key:s.key??null}):terminal.printHuman([Ke(a)],{title:t("cli.config.set","set <key> <value> Update a field (must be in allowlist)")}),{code:0,handled:!0,command:i}}return console.error(t("cli.config.unknown_subcommand",`Unknown config subcommand: ${s.subcommand}`,{subcommand:s.subcommand})),{code:1,handled:!0,command:i}}case "upgrade":{let s=Ye(r);if(s.help)return console.log(t("cli.upgrade.usage","Usage: easbot codebase upgrade [--schema] [--force]")),console.log(""),console.log(t("cli.upgrade.description","Update indexed_with_extraction_version metadata when stale.")),console.log(t("cli.upgrade.does_not_delete","Does NOT delete data \u2014 use `recreate` to drop the db entirely.")),console.log(""),console.log(t("cli.shared.options_heading","Options:")),console.log(` ${t("cli.upgrade.opt.schema","--schema Also re-run ensureSchema (idempotent CREATE TABLE IF NOT EXISTS)")}`),console.log(` ${t("cli.upgrade.opt.force","--force, -f Update version even when not stale")}`),{code:0,handled:!0,command:i};let a=await Qe(s);return s.json?terminal.emitJsonOk(a,{schema:s.schema===!0,force:s.force===!0}):terminal.printHuman([Xe(a)],{title:t("cli.cmd.upgrade.description","Update extraction_version metadata when stale")}),{code:0,handled:!0,command:i}}case "embed":case "embed-status":{let s=et(r);if(s.help)return console.log(t("cli.embed.usage","Usage: easbot codebase embed-status [--all] [--dry-run|-n] [--pending-list|-p] [--json]")),console.log(""),console.log(t("cli.embed.description","Inspect node embeddings (statistical only) \u2014 does NOT generate embeddings.")),console.log(t("cli.embed.statistical_only","CLI is statistical-only \u2014 actual embedding generation requires")),console.log(t("cli.embed.repl_required","an `easbot` REPL session with an injected EmbeddingModel.")),console.log(""),console.log(t("cli.shared.options_heading","Options:")),console.log(` ${t("cli.embed.opt.all","--all Show all nodes (including those with embeddings)")}`),console.log(` ${t("cli.embed.opt.dry_run","--dry-run, -n Print statistics only (default behavior)")}`),console.log(` ${t("cli.embed.opt.pending","--pending-list, -p List node ids that are pending embedding")}`),console.log(` ${t("cli.embed.opt.json","--json Output as JSON")}`),{code:0,handled:!0,command:i};s.dryRun=!0;let a=await tt(s);return s.json?terminal.emitJsonOk(a,{all:s.all===!0,dryRun:!0,pendingList:s.pendingList===!0,batchSize:s.batchSize??null}):terminal.printHuman([ot(a)],{title:t("cli.cmd.embed.description","Inspect node embeddings (statistical only)")}),{code:0,handled:!0,command:i}}case "query":{let s=pt(r);if(s.help)return console.log(t("cli.query.usage","Usage: easbot codebase query <q...> [--language=<lang>] [--ast=<type>] [--max=N] [--no-edges] [--no-vector|--no-embed] [--json]")),console.log(""),console.log(t("cli.query.description","Hybrid search (FTS + vector + basic) over indexed code nodes.")),console.log(t("cli.query.aliases","Aliases: search")),console.log(""),console.log(t("cli.shared.options_heading","Options:")),console.log(` ${t("cli.query.opt.language","--language=<lang> Filter by language (ts / js / py / go / ...)")}`),console.log(` ${t("cli.query.opt.ast","--ast=<type> Filter by AST type (class_declaration / function_declaration / ...)")}`),console.log(` ${t("cli.query.opt.max","--max=<N> Max results (default 20)")}`),console.log(` ${t("cli.query.opt.no_edges","--no-edges Do not include edges in results (default: include)")}`),console.log(` ${t("cli.query.opt.no_vector","--no-vector / --no-embed Disable vector search (FTS + basic only, default: vector on)")}`),console.log(` ${t("cli.query.opt.json","--json JSON output")}`),{code:0,handled:!0,command:i};let a=await ut(s);return s.json?terminal.emitJsonOk(a,{query:s.query??"",language:s.language??null,astType:s.astType??null,maxResults:s.maxResults??null}):terminal.printHuman([mt(a)],{title:t("cli.cmd.query.description","Hybrid search (FTS + vector + basic)")}),{code:0,handled:!0,command:i}}case "node":{let s=bt(r);if(s.help)return console.log(t("cli.node.usage","Usage: easbot codebase node <name|id> [--file=<path>] [--kind=<kind>] [--edges] [--max=N] [--json]")),console.log(""),console.log(t("cli.node.description","Show details for a single node.")),console.log(t("cli.node.accepts_name","Accepts a symbol <name> (LLM workflow friendly, tool/MCP-aligned)")),console.log(t("cli.node.accepts_id","or a raw <node-id> from `query` / database.")),console.log(""),console.log(t("cli.shared.options_heading","Options:")),console.log(` ${t("cli.node.opt.file","--file=<path> Disambiguate when same-named symbols exist")}`),console.log(` ${t("cli.node.opt.kind","--kind=<kind> Filter / disambiguate by AST kind")}`),console.log(` ${t("cli.node.opt.edges","--edges Include incoming / outgoing edge summaries")}`),console.log(` ${t("cli.node.opt.max","--max=<N> Edge limit (default 50)")}`),console.log(` ${t("cli.node.opt.json","--json Output as JSON")}`),{code:0,handled:!0,command:i};let a=await ht(s);return s.json?terminal.emitJsonOk(a,{name:s.name??"",nodeId:s.nodeId??null,file:s.file??null,kind:s.kind??null,includeEdges:s.includeEdges===!0,edgesLimit:s.edgesLimit??null,found:a.found}):terminal.printHuman([yt(a)],{title:t("cli.cmd.node.description","Show details for a single node")}),{code:a.found?0:1,handled:!0,command:i}}case "context":{let s=wt(r);if(s.help)return console.log(t("cli.context.usage","Usage: easbot codebase context <id> [--depth=N] [--max=N] [--direction=<incoming|outgoing|both>] [--relation=<r1,r2,...>] [--json]")),console.log(""),console.log(t("cli.context.description","Build a sub-graph context around a node (BFS to N-level neighbors).")),console.log(""),console.log(t("cli.shared.options_heading","Options:")),console.log(` ${t("cli.context.opt.depth","--depth=<N> BFS depth (default 2)")}`),console.log(` ${t("cli.context.opt.max","--max=<N> Max nodes (default 100)")}`),console.log(` ${t("cli.context.opt.direction","--direction=<dir> incoming | outgoing | both (default both)")}`),console.log(` ${t("cli.context.opt.relation","--relation=<r1,r2,...> Filter by relation types (CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS / USES / REFERENCES)")}`),console.log(` ${t("cli.context.opt.json","--json Output as JSON")}`),{code:0,handled:!0,command:i};let a=await Ct(s);return s.json?terminal.emitJsonOk(a,{nodeId:s.nodeId??"",depth:s.depth??null,direction:s.direction??"both"}):terminal.printHuman([Et(a)],{title:t("cli.cmd.context.description","Build sub-graph context around a node")}),{code:0,handled:!0,command:i}}case "impact":{let s=Rt(r);if(s.help)return console.log(t("cli.impact.usage","Usage: easbot codebase impact <id> [-d=N | --depth=N] [--relation=<r1,r2,...>] [--json]")),console.log(""),console.log(t("cli.impact.description","Blast radius: BFS incoming CALLS / REFERENCES / USES / IMPORTS / TYPE_REFERENCES, bucketed by depth.")),console.log(""),console.log(t("cli.shared.options_heading","Options:")),console.log(` ${t("cli.impact.opt.depth","--depth=<N> BFS depth (default 3)")}`),console.log(` ${t("cli.impact.opt.relation","--relation=<r1,r2,...> Filter by relation types")}`),console.log(` ${t("cli.impact.opt.json","--json Output as JSON")}`),{code:0,handled:!0,command:i};let a=await _t(s);return s.json?terminal.emitJsonOk(a,{nodeId:s.nodeId??"",depth:s.depth??null}):terminal.printHuman([kt(a)],{title:t("cli.cmd.impact.description","Blast radius (BFS incoming edges)")}),{code:0,handled:!0,command:i}}case "callers":{let s=zt(r);if(s.help)return console.log(t("cli.callers.usage","Usage: easbot codebase callers <symbol> [--node-id=<id>] [--file=<path>] [--kind=<kind>] [--max=N] [--json]")),console.log(""),console.log(t("cli.callers.description","Flat list of who calls <symbol> (incoming CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS).")),console.log(t("cli.callers.accepts","Accepts <symbol> name (LLM-friendly) OR --node-id for raw node id.")),console.log(""),console.log(t("cli.shared.options_heading","Options:")),console.log(` ${t("cli.callers.opt.node_id","--node-id=<id> Raw node id from `query` / database")}`),console.log(` ${t("cli.callers.opt.file","--file=<path> File path or basename to disambiguate when same-named symbols exist")}`),console.log(` ${t("cli.callers.opt.kind","--kind=<kind> Filter by node kind (class_declaration / function_declaration / ...)")}`),console.log(` ${t("cli.callers.opt.max","--max=<N> Max callers (default 20)")}`),console.log(` ${t("cli.callers.opt.json","--json Output as JSON")}`),{code:0,handled:!0,command:i};let a=await Wt(s);return s.json?terminal.emitJsonOk(a,{symbol:s.symbol??"",nodeId:s.nodeId??null,file:s.file??null,kind:s.kind??null,maxResults:s.maxResults??null}):terminal.printHuman([Jt(a)],{title:t("cli.cmd.callers.description","Flat list of who calls <symbol> (incoming edges)")}),{code:0,handled:!0,command:i}}case "callees":{let s=Kt(r);if(s.help)return console.log(t("cli.callees.usage","Usage: easbot codebase callees <symbol> [--node-id=<id>] [--file=<path>] [--kind=<kind>] [--max=N] [--json]")),console.log(""),console.log(t("cli.callees.description","Flat list of what <symbol> calls (outgoing edges).")),console.log(t("cli.callees.accepts","Accepts <symbol> name (LLM-friendly) OR --node-id for raw node id.")),console.log(""),console.log(t("cli.shared.options_heading","Options:")),console.log(` ${t("cli.callees.opt.node_id","--node-id=<id> Raw node id from `query` / database")}`),console.log(` ${t("cli.callees.opt.file","--file=<path> File path or basename to disambiguate")}`),console.log(` ${t("cli.callees.opt.kind","--kind=<kind> Filter by node kind")}`),console.log(` ${t("cli.callees.opt.max","--max=<N> Max callees (default 20)")}`),console.log(` ${t("cli.callees.opt.json","--json Output as JSON")}`),{code:0,handled:!0,command:i};let a=await Vt(s);return s.json?terminal.emitJsonOk(a,{symbol:s.symbol??"",nodeId:s.nodeId??null,file:s.file??null,kind:s.kind??null,maxResults:s.maxResults??null}):terminal.printHuman([Ht(a)],{title:t("cli.cmd.callees.description","Flat list of what <symbol> calls (outgoing edges)")}),{code:0,handled:!0,command:i}}case "explore":{let s=Yt(r);if(s.help)return console.log(t("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]")),console.log(""),console.log(t("cli.explore.description","PRIMARY tool \u2014 single call to get source code + caller/callee trail.")),console.log(t("cli.explore.query_help","<query> can be a symbol name or natural language.")),console.log(""),console.log(t("cli.shared.options_heading","Options:")),console.log(` ${t("cli.explore.opt.file","--file=<path> File path or basename to disambiguate")}`),console.log(` ${t("cli.explore.opt.kind","--kind=<kind> Filter by node kind")}`),console.log(` ${t("cli.explore.opt.max_files","--max-files=<N> Max entry-point files (default 5)")}`),console.log(` ${t("cli.explore.opt.max_symbols","--max-symbols=<N> Max symbols per file (default 3)")}`),console.log(` ${t("cli.explore.opt.depth","--depth=<N> Neighbor depth for caller/callee trail (default 1)")}`),console.log(` ${t("cli.explore.opt.no_content","--no-content Do not include source code (locations only, default: include)")}`),console.log(` ${t("cli.explore.opt.intent","--intent=<ctx> LLM context string for ranking")}`),console.log(` ${t("cli.explore.opt.json","--json Output as JSON")}`),{code:0,handled:!0,command:i};let a=await Qt(s);return s.json?terminal.emitJsonOk(a,{query:s.query??"",file:s.file??null,kind:s.kind??null,maxFiles:s.maxFiles??null,maxSymbols:s.maxSymbols??null,depth:s.depth??null,includeContent:s.includeContent!==!1,intent:s.intent??null}):terminal.printHuman([await Xt(a)],{title:t("cli.cmd.explore.description","PRIMARY tool \u2014 source code + caller/callee trail in one call")}),{code:0,handled:!0,command:i}}case "dead-code":{let s=Dt(r);if(s.help)return console.log(t("cli.dead_code.usage","Usage: easbot codebase dead-code [--type=<t1,t2,...>] [--no-exclude-entry] [--limit=N] [--json]")),console.log(""),console.log(t("cli.dead_code.description","Find nodes with no incoming edges (heuristic dead code).")),console.log(""),console.log(t("cli.shared.options_heading","Options:")),console.log(` ${t("cli.dead_code.opt.type","--type=<t1,t2,...> Only consider these AST types")}`),console.log(` ${t("cli.dead_code.opt.no_exclude_entry","--no-exclude-entry Include entry-point files (default: exclude)")}`),console.log(` ${t("cli.dead_code.opt.limit","--limit=<N> Max results (default 100)")}`),console.log(` ${t("cli.dead_code.opt.json","--json Output as JSON")}`),{code:0,handled:!0,command:i};let a=await vt(s);return s.json?terminal.emitJsonOk(a,{astTypes:s.astTypes??null,limit:s.limit??null,excludeEntry:s.excludeEntry!==!1}):terminal.printHuman([It(a)],{title:t("cli.cmd.dead_code.description","Find unused symbols")}),{code:0,handled:!0,command:i}}case "circular":{let s=jt(r);if(s.help)return console.log(t("cli.circular.usage","Usage: easbot codebase circular [--relation=<r>] [--scope=<file|module>] [--json]")),console.log(""),console.log(t("cli.circular.description","Detect circular dependencies via Tarjan SCC.")),console.log(""),console.log(t("cli.shared.options_heading","Options:")),console.log(` ${t("cli.circular.opt.relation","--relation=<r> Relation type to follow (default IMPORTS)")}`),console.log(` ${t("cli.circular.opt.scope","--scope=<scope> file | module (default file)")}`),console.log(` ${t("cli.circular.opt.json","--json Output as JSON")}`),{code:0,handled:!0,command:i};let a=await Tt(s);return s.json?terminal.emitJsonOk(a,{relation:s.relation??null,scope:s.scope??null}):terminal.printHuman([$t(a)],{title:t("cli.cmd.circular.description","Detect circular dependencies (Tarjan SCC)")}),{code:0,handled:!0,command:i}}case "path":{let s=Lt(r);if(s.help)return console.log(t("cli.path.usage","Usage: easbot codebase path <from> <to> [-d=N | --depth=N] [--relation=<r1,r2,...>] [--json]")),console.log(""),console.log(t("cli.path.description","Find shortest path between two nodes (BFS along CALLS / IMPORTS / TYPE_REFERENCES / USES / REFERENCES).")),console.log(""),console.log(t("cli.shared.options_heading","Options:")),console.log(` ${t("cli.path.opt.depth","--depth=<N> BFS depth limit (default 6)")}`),console.log(` ${t("cli.path.opt.relation","--relation=<r1,r2,...> Filter by relation types")}`),console.log(` ${t("cli.path.opt.json","--json Output as JSON")}`),{code:0,handled:!0,command:i};let a=await Mt(s);return s.json?terminal.emitJsonOk(a,{fromId:s.fromId??"",toId:s.toId??"",depth:s.depth??null}):terminal.printHuman([At(a)],{title:t("cli.cmd.path.description","Find shortest path between two nodes")}),{code:a.found?0:1,handled:!0,command:i}}case "mcp":{let s=Bt(r);return s.help?(console.log(t("cli.mcp.usage","Usage: easbot codebase mcp")),console.log(""),console.log(t("cli.mcp.description","Start a stdio MCP server exposing 9 codebase tools:")),console.log(` ${t("cli.mcp.tools.1"," query / node / context / impact")}`),console.log(` ${t("cli.mcp.tools.2"," callers / callees / explore")}`),console.log(` ${t("cli.mcp.tools.3"," status / doctor")}`),console.log(""),console.log(t("cli.mcp.transport","Connect from MCP clients via stdio JSON-RPC.")),{code:0,handled:!0,command:i}):(await Gt(s),{code:0,handled:!0,command:i})}case "watch":{let s=st(r);if(s.help)return console.log(t("cli.watch.usage","Usage: easbot codebase watch [--debounce=N] [--interval=N]")),console.log(""),console.log(t("cli.watch.description","Watch the workspace directory for file changes and log events.")),console.log(t("cli.watch.pid_file","Writes a pid file at .easbot/.watcher.pid for subsequent `stop`.")),console.log(""),console.log(t("cli.shared.options_heading","Options:")),console.log(` ${t("cli.watch.opt.debounce","--debounce=N Per-path debounce in ms (default 200)")}`),console.log(` ${t("cli.watch.opt.interval","--interval=N Polling interval in ms (default 500)")}`),console.log(""),console.log(t("cli.watch.note","NOTE: This command blocks. Press Ctrl+C to exit.")),{code:0,handled:!0,command:i};let a=await it(s);return console.log(at(a.events)),await new Promise(d=>{let c=()=>{re.info("watcher received signal, stopping"),d();};process.once("SIGINT",c),process.once("SIGTERM",c);}),await a.watcher.dispose(),{code:0,handled:!0,command:i}}case "stop":{let s=rt(r);if(s.help)return console.log(t("cli.stop.usage","Usage: easbot codebase stop")),console.log(""),console.log(t("cli.stop.description","Stop a running watcher identified by .easbot/.watcher.pid.")),console.log(""),console.log(t("cli.shared.options_heading","Options:")),console.log(` ${t("cli.stop.opt.force","--force, -f Ignore errors and clear the pid file anyway")}`),{code:0,handled:!0,command:i};let a=await ct(s);return s.json?terminal.emitJsonOk(a,{force:s.force===!0}):terminal.printHuman([lt(a)],{title:t("cli.cmd.stop.description","Stop a running file watcher")}),{code:a.stopped?0:1,handled:!0,command:i}}default:return l?terminal.emitJsonError(i,t("cli.unknown_command",`Unknown command: ${i}`,{command:i})):(console.error(t("cli.unknown_command",`Unknown command: ${i}`,{command:i})),console.error(t("cli.help_hint","Run `easbot codebase --help` for available commands."))),{code:1,handled:!0,command:i}}}catch(s){let a=utils.errorMeta(s),d=a.message;return l?terminal.emitJsonError(i,d):console.error(t("cli.command_failed",`codebase ${i} failed: ${d}`,{command:i,message:d})),re.error("codebase CLI error",{command:i,error:a}),{code:1,handled:true,command:i}}}function jn(o){let e={};for(let n of o)n==="--json"&&(e.json=true);return e}function Tn(o){let e={};for(let n of o)n==="--help"||n==="-h"?e.help=true:n==="--json"&&(e.json=true);return e}function $n(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,healthy:o.healthy,recommendation:o.recommendation,dbStats:o.dbStats,extras:(()=>{let e={};if(o.isStale===true&&(e.stale="yes \u2014 reindex recommended"),typeof o.ftsAvailable=="boolean"&&(e.fts_available=o.ftsAvailable?"yes":"no"),o.meta&&typeof o.meta=="object")for(let[n,t]of Object.entries(o.meta))e[`meta/${n}`]=t===void 0?"\u2205":t;return Object.keys(e).length>0?e:void 0})()}}function Pn(o){return {packageName:"codebase",healthy:o.healthy,durationMs:o.durationMs,checks:o.checks.map(e=>({code:e.code,severity:e.severity,name:e.name,message:e.message,durationMs:e.durationMs,details:e.details})),backendAvailable:o.backendAvailable,dbStats:o.dbStats}}exports.a=Dn;exports.b=vr;exports.c=vn;exports.d=Ir;exports.e=Pn;
@@ -0,0 +1,158 @@
1
+ 'use strict';var chunkW5SMGCKO_cjs=require('./chunk-W5SMGCKO.cjs'),chunkKFESJR3T_cjs=require('./chunk-KFESJR3T.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database');var A=utils.Log.create({service:"codebase.database.migrations"}),N=1,X=[{id:1,description:"v1 baseline: nodes / edges / file_hashes / nodes_fts / meta / embedding_cache / node_embeddings + unresolved_refs / name_segment_vocab / project_metadata / parse_errors + \u6027\u80FD index (nodes.file_path / edges.source/target)",up:[`CREATE TABLE IF NOT EXISTS nodes (
2
+ id TEXT PRIMARY KEY,
3
+ name TEXT NOT NULL,
4
+ ast_type TEXT NOT NULL,
5
+ language TEXT NOT NULL,
6
+ file_path TEXT NOT NULL,
7
+ start_line INTEGER,
8
+ start_col INTEGER,
9
+ end_line INTEGER,
10
+ end_col INTEGER,
11
+ text TEXT,
12
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
13
+ )`,`CREATE TABLE IF NOT EXISTS edges (
14
+ id TEXT PRIMARY KEY,
15
+ source TEXT NOT NULL,
16
+ target TEXT NOT NULL,
17
+ relation TEXT NOT NULL,
18
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
19
+ FOREIGN KEY (source) REFERENCES nodes(id) ON DELETE CASCADE,
20
+ FOREIGN KEY (target) REFERENCES nodes(id) ON DELETE CASCADE
21
+ )`,`CREATE TABLE IF NOT EXISTS file_hashes (
22
+ file_path TEXT PRIMARY KEY,
23
+ content_hash TEXT NOT NULL,
24
+ last_modified DATETIME DEFAULT CURRENT_TIMESTAMP
25
+ )`,`CREATE VIRTUAL TABLE IF NOT EXISTS nodes_fts USING fts5(
26
+ id, name, ast_type, language, file_path, text,
27
+ tokenize='unicode61'
28
+ )`,`CREATE TABLE IF NOT EXISTS meta (
29
+ key TEXT PRIMARY KEY,
30
+ value TEXT
31
+ )`,`CREATE TABLE IF NOT EXISTS embedding_cache (
32
+ content_hash TEXT PRIMARY KEY,
33
+ embedding BLOB NOT NULL
34
+ )`,`CREATE TABLE IF NOT EXISTS node_embeddings (
35
+ node_id TEXT PRIMARY KEY,
36
+ embedding_text TEXT NOT NULL,
37
+ embedding BLOB NOT NULL,
38
+ FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
39
+ )`,`CREATE TABLE IF NOT EXISTS unresolved_refs (
40
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
41
+ from_node_id TEXT,
42
+ reference_name TEXT NOT NULL,
43
+ reference_kind TEXT NOT NULL,
44
+ line INTEGER,
45
+ col INTEGER,
46
+ file_path TEXT NOT NULL,
47
+ language TEXT NOT NULL,
48
+ candidates TEXT,
49
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
50
+ FOREIGN KEY (from_node_id) REFERENCES nodes(id) ON DELETE SET NULL
51
+ )`,"CREATE INDEX IF NOT EXISTS idx_unresolved_refs_file_path ON unresolved_refs(file_path)","CREATE INDEX IF NOT EXISTS idx_unresolved_refs_kind ON unresolved_refs(reference_kind)",`CREATE TABLE IF NOT EXISTS name_segment_vocab (
52
+ segment TEXT NOT NULL,
53
+ name TEXT NOT NULL,
54
+ PRIMARY KEY (segment, name)
55
+ ) WITHOUT ROWID`,"CREATE INDEX IF NOT EXISTS idx_name_segment ON name_segment_vocab(segment)",`CREATE TABLE IF NOT EXISTS project_metadata (
56
+ key TEXT PRIMARY KEY,
57
+ value TEXT,
58
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
59
+ )`,`CREATE TABLE IF NOT EXISTS parse_errors (
60
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
61
+ file_path TEXT NOT NULL,
62
+ language TEXT NOT NULL,
63
+ stage TEXT NOT NULL,
64
+ message TEXT NOT NULL,
65
+ line INTEGER,
66
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
67
+ )`,"CREATE INDEX IF NOT EXISTS idx_parse_errors_file_path ON parse_errors(file_path)","CREATE INDEX IF NOT EXISTS idx_nodes_file_path ON nodes(file_path)","CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)"]}];function v(E,e=N,t={}){E.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
68
+ id INTEGER PRIMARY KEY,
69
+ applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
70
+ )`);let s=E.prepare("SELECT id FROM schema_migrations").all(),n=new Set(s.map(a=>a.id)),r={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(a=>a.id)),targetVersion:e};for(let a of X){if(a.id>e)break;if(n.has(a.id)){r.pending.push(a.id);continue}if(t.dryRun){r.applied.push(a.id);continue}try{E.execBatch([...a.up]),E.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(a.id),n.add(a.id),r.applied.push(a.id),A.debug("migration applied",{id:a.id,description:a.description});}catch(i){let o=utils.errorMeta(i).message,c=a.up[0]??"";r.errors.push({migrationId:a.id,sql:c,error:o}),A.warn("migration step failed (may be idempotent)",{id:a.id,error:utils.errorMeta(i),sqlCount:a.up.length});}}return r}function w(E){try{let e=E.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(t=>t.id))}catch{return 0}}var l=utils.Filesystem.toUnixPath,d=utils.Log.create({service:"codebase.database"}),S=3,U=class{constructor(e){chunkKFESJR3T_cjs.a(this,"db");chunkKFESJR3T_cjs.a(this,"dbPath");chunkKFESJR3T_cjs.a(this,"closed",false);chunkKFESJR3T_cjs.a(this,"ftsAvailable",false);this.dbPath=e===":memory:"?e:utils.Filesystem.normalize(e),this.db=database.createSyncSqliteConnection({path:this.dbPath,backend:"better-sqlite3",walMode:true,foreignKeys:true,busyTimeoutMs:3e4}),this.db.initialize();try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("foreign_keys = ON");}catch(t){d.warn("Failed to apply codebase PRAGMAs (synchronous / cache_size / foreign_keys)",{error:utils.errorMeta(t)});}try{this.ensureSchema();let t=w(this.db);t>0&&this.setMeta("schema_version",String(t)),this.ftsAvailable=this.checkFtsAvailability(),this.detectAndMarkStaleOnInit();}catch(t){try{this.db.close();}catch{}throw this.closed=true,t}}ensureSchema(){try{v(this.db,N);let e=[["version","1.0.0"],["createdAt",new Date().toISOString()],["index_state","uninitialized"],["indexed_with_version","unknown"]],t=this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[s,n]of e)t.run(s,n);}catch(e){d.error("ensureSchema failed",{error:utils.errorMeta(e)});let t=utils.errorMeta(e).message,s=e instanceof Error?e.cause:void 0,n=s!==void 0?String(s):"",r=n&&n!==t?` (cause: ${n})`:"";throw new chunkW5SMGCKO_cjs.b.SchemaError({message:`Failed to create database schema: ${t}${r}`,missing:e instanceof Error?[t,n].filter(Boolean):[t]},{cause:e})}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:l(e.file_path)};this.db.prepare(`
71
+ INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
72
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
73
+ `).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(r=>({...r,file_path:l(r.file_path)})),s=this.db.prepare(`
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
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
76
+ `);this.db.transaction(r=>{for(let a of r)s.run(a.id,a.name,a.ast_type,a.language,a.file_path,a.start_line,a.start_col,a.end_line,a.end_col,a.text,a.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(r);})(t);}updateFtsNodesInternal(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),n=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");for(let r of e)try{let a=s.get(r.id);a&&t.run(a.rowid),n.run(r.id,r.name,r.ast_type,r.language,r.file_path,r.text);}catch(a){d.warn("FTS update failed for node",{nodeId:r.id,error:utils.errorMeta(a)});}}updateFtsNode(e){try{let t=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?").get(e.id);t&&this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(t.rowid),this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.ast_type,e.language,e.file_path,e.text);}catch(t){d.warn("FTS update failed for node",{nodeId:e.id,error:utils.errorMeta(t)});}}updateFtsNodes(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),n=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");this.db.transaction(a=>{for(let i of a)try{let o=s.get(i.id);o&&t.run(o.rowid),n.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.text);}catch(o){d.warn("FTS update failed for node",{nodeId:i.id,error:utils.errorMeta(o)});}})(e);}insertEdge(e){this.db.prepare(`
77
+ INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
78
+ VALUES (?, ?, ?, ?, ?)
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
+ INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
81
+ VALUES (?, ?, ?, ?, ?)
82
+ `);this.db.transaction(n=>{for(let r of n)t.run(r.id,r.source,r.target,r.relation,r.created_at);})(e);}queryNodes(e){let t=[],s=[];e.filePath&&(t.push("file_path LIKE ?"),s.push(`%${l(e.filePath)}%`)),e.astType&&(t.push("ast_type = ?"),s.push(e.astType)),e.name&&(t.push("name = ?"),s.push(e.name)),e.language&&(t.push("language = ?"),s.push(e.language));let n="SELECT * FROM nodes";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY file_path, start_line",e.limit&&(n+=" LIMIT ?",s.push(e.limit)),e.offset&&(n+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(n).all(...s)}catch(r){throw new chunkW5SMGCKO_cjs.b.DatabaseError({message:"Failed to query nodes",operation:"queryNodes"},{cause:r})}}findNodesByName(e){if(!e.name)return [];let t=e.limit??50,s=e.kind?`%${e.kind.toLowerCase()}%`:null,n=new Set,r=[],a=(o,c)=>{n.has(o.id)||(n.add(o.id),r.push({node:o,matchKind:c}));},i=(o,c)=>{e.file&&(e.file.includes("/")?(o.push("file_path = ?"),c.push(e.file)):(o.push("file_path LIKE '%/' || ?"),c.push(e.file))),s&&(o.push("LOWER(ast_type) LIKE ?"),c.push(s));};try{let o=["name = ?"],c=[e.name];i(o,c),c.push(t);let p=this.db.prepare(`SELECT * FROM nodes WHERE ${o.join(" AND ")} LIMIT ?`).all(...c);for(let u of p)a(u,"exact");if(p.length>0&&e.file)return r.slice(0,t);if(r.length<t){let u=this.db.prepare("SELECT * FROM nodes WHERE name LIKE ? LIMIT ?").all(`%${e.name}%`,t);for(let g of u)a(g,"qualified");}if(r.length>0&&e.file)return r.slice(0,t);if(r.length===0&&e.name){let u=["name LIKE ?"],g=[`%${e.name}%`];e.file&&(e.file.includes("/")?(u.push("file_path = ?"),g.push(e.file)):(u.push("file_path LIKE '%/' || ?"),g.push(e.file))),s&&(u.push("LOWER(ast_type) LIKE ?"),g.push(s)),u.push("?"),g.push(t);let f=this.db.prepare(`SELECT * FROM nodes WHERE ${u.join(" AND ")}`).all(...g);for(let _ of f)a(_,"substring");}return r.slice(0,t)}catch(o){throw new chunkW5SMGCKO_cjs.b.DatabaseError({message:"Failed to find nodes by name",operation:"findNodesByName"},{cause:o})}}queryEdges(e){let t=[],s=[];if(e.sourceOrTarget&&e.sourceOrTarget.length>0){let r=e.sourceOrTarget.map(()=>"?").join(",");t.push(`(source IN (${r}) OR target IN (${r}))`),s.push(...e.sourceOrTarget,...e.sourceOrTarget);}else e.source&&(t.push("source = ?"),s.push(e.source)),e.target&&(t.push("target = ?"),s.push(e.target));e.relation&&(t.push("relation = ?"),s.push(e.relation));let n="SELECT * FROM edges";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY created_at DESC",e.limit&&(n+=" LIMIT ?",s.push(e.limit)),e.offset&&(n+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(n).all(...s)}catch(r){throw new chunkW5SMGCKO_cjs.b.DatabaseError({message:"Failed to query edges",operation:"queryEdges"},{cause:r})}}queryAll(e,t){try{let s=this.db.prepare(e);return t?s.all(...t):s.all()}catch(s){throw new chunkW5SMGCKO_cjs.b.DatabaseError({message:"Failed to execute query",operation:"queryAll"},{cause:s})}}searchNodesFts(e,t=20){if(d.debug("searchNodesFts start",{query:e,limit:t,ftsAvailable:this.ftsAvailable}),!this.ftsAvailable)return d.debug("searchNodesFts skip - FTS not available"),[];try{let s=e.split(/\s+/).map(i=>`${i}*`).join(" ");d.debug("searchNodesFts query",{ftsQuery:s});let a=this.db.prepare(`
83
+ SELECT
84
+ nodes_fts.id,
85
+ nodes_fts.name,
86
+ nodes_fts.ast_type,
87
+ nodes_fts.language,
88
+ nodes_fts.file_path,
89
+ nodes_fts.text,
90
+ nodes.start_line,
91
+ nodes.start_col,
92
+ nodes.end_line,
93
+ nodes.end_col,
94
+ bm25(nodes_fts) as score
95
+ FROM nodes_fts
96
+ JOIN nodes ON nodes.id = nodes_fts.id
97
+ WHERE nodes_fts.text MATCH ?
98
+ ORDER BY score DESC
99
+ LIMIT ?
100
+ `).all(s,t);return d.debug("searchNodesFts done",{resultCount:a.length}),a}catch(s){return d.warn("searchNodesFts failed",{error:utils.errorMeta(s)}),[]}}deleteNodesByFile(e){let t=l(e);if(this.ftsAvailable)try{let n=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let r of n)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(r.rowid);}catch(n){d.warn("FTS delete failed for file",{filePath:t,error:utils.errorMeta(n)});}return this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t).changes}deleteEdgesByFile(e){let t=l(e);return this.db.prepare(`
101
+ DELETE FROM edges
102
+ WHERE source IN (SELECT id FROM nodes WHERE file_path = ?)
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(`
105
+ INSERT OR REPLACE INTO file_hashes (file_path, content_hash, last_modified)
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=b=>this.db.prepare(b).get().c,t=b=>e(b),s={nodes:t("SELECT COUNT(*) as c FROM nodes"),edges:t("SELECT COUNT(*) as c FROM edges"),file_hashes:t("SELECT COUNT(*) as c FROM file_hashes"),fts:t("SELECT COUNT(*) as c FROM nodes_fts"),node_embeddings:t("SELECT COUNT(*) as c FROM node_embeddings"),embedding_cache:t("SELECT COUNT(*) as c FROM embedding_cache"),parse_errors:t("SELECT COUNT(*) as c FROM parse_errors"),unresolved_refs:t("SELECT COUNT(*) as c FROM unresolved_refs"),name_segment_vocab:t("SELECT COUNT(*) as c FROM name_segment_vocab"),project_metadata:t("SELECT COUNT(*) as c FROM project_metadata"),schema_migrations:t("SELECT COUNT(*) as c FROM schema_migrations"),meta:t("SELECT COUNT(*) as c FROM meta")},n=[],r=t(`
108
+ SELECT COUNT(*) as c FROM node_embeddings e
109
+ LEFT JOIN nodes n ON n.id = e.node_id WHERE n.id IS NULL
110
+ `);r>0&&n.push({severity:"error",message:`orphan node_embeddings: ${r}`});let a=t(`
111
+ SELECT COUNT(*) as c FROM edges e
112
+ WHERE e.relation != 'IMPORTS'
113
+ AND NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.source)
114
+ `);a>0&&n.push({severity:"error",message:`orphan edges (source): ${a}`});let i=t(`
115
+ SELECT COUNT(*) as c FROM edges e
116
+ WHERE e.relation NOT IN ('CALLS', 'IMPORTS')
117
+ AND NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.target)
118
+ `);i>0&&n.push({severity:"error",message:`orphan edges (target): ${i}`});let o=t("SELECT COUNT(*) as c FROM edges WHERE source = target");o>0&&n.push({severity:"error",message:`self-loop edges: ${o} \u2014 re-run \`easbot codebase sync\` to filter (fixed in Wave 4 R3-2)`});t("SELECT COUNT(DISTINCT file_path) as c FROM nodes");let p=t(`
119
+ SELECT COUNT(*) as c FROM file_hashes fh
120
+ WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.file_path = fh.file_path)
121
+ `);p>0&&n.push({severity:"warn",message:`orphan file_hashes (no nodes): ${p} \u2014 run \`easbot codebase sync\` to cleanup`});let u=t(`
122
+ SELECT COUNT(DISTINCT n.file_path) as c FROM nodes n
123
+ WHERE NOT EXISTS (SELECT 1 FROM file_hashes fh WHERE fh.file_path = n.file_path)
124
+ `);u>0&&n.push({severity:"warn",message:`node files without hash: ${u}`});let g=t("SELECT COUNT(*) as c FROM nodes WHERE name IS NULL OR name = ''");g>0&&n.push({severity:"error",message:`nodes with null/empty name: ${g}`});let f=t("SELECT COUNT(*) as c FROM nodes WHERE ast_type IS NULL OR ast_type = ''");f>0&&n.push({severity:"error",message:`nodes with null/empty ast_type: ${f}`});let _=t("SELECT COUNT(*) as c FROM nodes WHERE language IS NULL OR language = ''");_>0&&n.push({severity:"error",message:`nodes with null/empty language: ${_}`});let O=t("SELECT COUNT(*) as c FROM nodes WHERE file_path IS NULL OR file_path = ''");O>0&&n.push({severity:"error",message:`nodes with null/empty file_path: ${O}`});let I=this.db.prepare("SELECT id, COUNT(*) as c FROM nodes GROUP BY id HAVING c > 1").all().length;I>0&&n.push({severity:"error",message:`duplicate node ids: ${I}`});let L=t("SELECT COUNT(*) as c FROM nodes WHERE file_path LIKE '%\\\\%'");L>0&&n.push({severity:"warn",message:`nodes with backslash in file_path: ${L}`});let C=t(`
125
+ SELECT COUNT(*) as c FROM nodes
126
+ WHERE start_line IS NOT NULL AND end_line IS NOT NULL AND start_line > end_line
127
+ `);C>0&&n.push({severity:"error",message:`invalid line ranges: ${C}`});let F=this.db.prepare("SELECT id, COUNT(*) as c FROM edges GROUP BY id HAVING c > 1").all().length;F>0&&n.push({severity:"error",message:`duplicate edge ids: ${F}`});let M=t("SELECT COUNT(*) as c FROM nodes_fts_content");return M!==s.nodes&&n.push({severity:"error",message:`FTS content desync: ${M} vs ${s.nodes} (run \`easbot codebase recreate\` to rebuild)`}),s.parse_errors>100&&n.push({severity:"warn",message:`parse_errors > 100 (${s.parse_errors}) \u2014\u2014 many files failed to parse`}),{issues:n,stats:s}}getStatus(){let e=this.db.prepare("SELECT COUNT(*) as c FROM nodes").get(),t=this.db.prepare("SELECT COUNT(*) as c FROM edges").get(),s=this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get(),n=this.db.prepare("SELECT key, value FROM meta").all(),r={};for(let a of n)r[a.key]=a.value;return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:s?.c??0,dbPath:this.dbPath,meta:r,indexState:this.getIndexState(),extractionVersion:parseInt(this.getMeta("indexed_with_extraction_version")??"0",10),isStale:this.isIndexStale()}}setLastSync(){this.db.prepare(`
128
+ INSERT OR REPLACE INTO meta (key, value)
129
+ VALUES ('lastSync', ?)
130
+ `).run(new Date().toISOString());}getIndexState(){return this.getMeta("index_state")??"uninitialized"}setIndexState(e){this.setMeta("index_state",e),this.setMeta("last_index_state_change",new Date().toISOString());}markIndexed(e){this.setMeta("indexed_with_version",e),this.setMeta("indexed_with_extraction_version",String(S)),this.setMeta("index_state","complete"),this.setMeta("last_index_state_change",new Date().toISOString());}isIndexStale(){let e=this.getMeta("indexed_with_extraction_version");if(!e)return false;let t=parseInt(e,10);return Number.isNaN(t)||t<S}detectAndMarkStaleOnInit(){if(this.isIndexStale()){let e=this.getMeta("indexed_with_extraction_version");d.warn("codebase db is stale",{recorded:e??"(none)",current:String(S),hint:"run `easbot codebase recreate` or `easbot codebase index --force` to rebuild"});let t=this.getIndexState();(t==="complete"||t==="partial")&&this.setIndexState("stale");}}getNodeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM nodes").get()?.c??0}getEdgeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM edges").get()?.c??0}getFileCount(){return this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get()?.c??0}getNodeById(e){return this.db.prepare("SELECT * FROM nodes WHERE id = ?").get(e)??null}getEdgeById(e){return this.db.prepare("SELECT * FROM edges WHERE id = ?").get(e)??null}clearAll(e={}){this.db.exec("DELETE FROM nodes"),this.db.exec("DELETE FROM edges"),this.db.exec("DELETE FROM file_hashes"),this.db.exec("DELETE FROM meta"),e.keepEmbeddings||(this.db.exec("DELETE FROM node_embeddings"),this.db.exec("DELETE FROM embedding_cache")),this.ftsAvailable&&this.db.exec("DELETE FROM nodes_fts");try{this.db.exec("DELETE FROM sqlite_sequence WHERE name IN ('nodes', 'edges', 'file_hashes', 'meta')");}catch{}}getCachedEmbedding(e){let s=this.db.prepare(`
131
+ SELECT embedding FROM embedding_cache WHERE content_hash = ?
132
+ `).get(e);return s?new Float32Array(s.embedding.buffer,s.embedding.byteOffset,s.embedding.length/4):null}getVectorDims(){let e=this.db.prepare("SELECT value FROM meta WHERE key = ?").get("vectorDims");return e?parseInt(e.value,10):void 0}ensureVectorDims(e){this.db.prepare("SELECT value FROM meta WHERE key = ?").get("vectorDims")||this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)").run("vectorDims",String(e));}cacheEmbedding(e,t){if(this.db.prepare("SELECT embedding FROM embedding_cache WHERE content_hash = ?").get(e))return;this.ensureVectorDims(t.length),this.db.prepare(`
133
+ INSERT OR REPLACE INTO embedding_cache (content_hash, embedding)
134
+ VALUES (?, ?)
135
+ `).run(e,t);}deleteEmbeddingsByFile(e){let t=l(e);return this.db.prepare(`
136
+ DELETE FROM node_embeddings WHERE node_id IN (SELECT id FROM nodes WHERE file_path = ?)
137
+ `).run(t).changes}getAllNodeEmbeddings(){return this.db.prepare("SELECT node_id, embedding FROM node_embeddings").all()}storeNodeEmbeddings(e){if(e.length===0)return;this.ensureVectorDims(e[0].embedding.length);let t=this.db.prepare(`
138
+ INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
139
+ VALUES (?, ?, ?)
140
+ `);this.db.transaction(n=>{for(let r of n)try{t.run(r.nodeId,r.embeddingText,r.embedding);}catch(a){d.warn("Failed to store embedding for node",{nodeId:r.nodeId,error:utils.errorMeta(a)});}})(e);}insertParseError(e){return this.db.prepare(`
141
+ INSERT INTO parse_errors (file_path, language, stage, message, line)
142
+ VALUES (?, ?, ?, ?, ?)
143
+ `).run(l(e.filePath),e.language,e.stage,e.message,e.line??null).changes}insertUnresolvedRef(e){return this.db.prepare(`
144
+ INSERT INTO unresolved_refs
145
+ (from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
146
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
147
+ `).run(e.fromNodeId??null,e.referenceName,e.referenceKind,e.line??null,e.col??null,l(e.filePath),e.language,e.candidates?JSON.stringify(e.candidates):null).changes}insertUnresolvedRefsBatch(e){if(e.length===0)return 0;let s=`
148
+ INSERT INTO unresolved_refs
149
+ (from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
150
+ VALUES ${e.map(()=>"(?, ?, ?, ?, ?, ?, ?, ?)").join(", ")}
151
+ `,n=[];for(let i of e)n.push(i.fromNodeId??null,i.referenceName,i.referenceKind,i.line??null,i.col??null,l(i.filePath),i.language,i.candidates?JSON.stringify(i.candidates):null);return this.db.prepare(s).run(...n).changes}insertNameSegment(e,t){return this.db.prepare(`
152
+ INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES (?, ?)
153
+ `).run(e,t).changes}insertNameSegmentsBatch(e){if(e.length===0)return 0;let s=`
154
+ INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES ${e.map(()=>"(?, ?)").join(", ")}
155
+ `,n=[];for(let i of e)n.push(i.segment,i.name);return this.db.prepare(s).run(...n).changes}setProjectMetadata(e,t){let s=e==="worktree"||e==="project"?l(t):t;return this.db.prepare(`
156
+ INSERT OR REPLACE INTO project_metadata (key, value, updated_at)
157
+ VALUES (?, ?, CURRENT_TIMESTAMP)
158
+ `).run(e,s).changes}getNodeIdsByFile(e){let t=e.replace(/\\/g,"/");return this.db.prepare("SELECT id FROM nodes WHERE file_path = ?").all(t).map(n=>n.id)}deleteFtsByFile(e){let t=e.replace(/\\/g,"/"),s=this.getNodeIdsByFile(t);if(s.length===0)return 0;let n=this.db.prepare("DELETE FROM nodes_fts WHERE id = ?");return this.db.transaction(a=>{for(let i of a)n.run(i);})(s),s.length}initialize(){if(this.closed)throw new chunkW5SMGCKO_cjs.b.DatabaseError({message:"Cannot initialize closed database",operation:"initialize"})}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){d.warn("Database close error",{error:utils.errorMeta(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new utils.NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new utils.NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}countSqliteObjects(){if(!this.db)throw new utils.NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});return this.db.prepare("SELECT COUNT(*) as n FROM sqlite_master WHERE type IN ('table', 'index', 'trigger', 'view')").get()?.n??0}deleteMeta(e){if(!this.db)throw new utils.NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});this.db.prepare("DELETE FROM meta WHERE key = ?").run(e);}};function z(E){return E.isClosed()}function G(E){return E.getDbPath()}function j(E,e){return E.transaction(e)}exports.a=N;exports.b=X;exports.c=v;exports.d=w;exports.e=S;exports.f=U;exports.g=z;exports.h=G;exports.i=j;