@easbot/codebase 0.3.0 → 0.3.3

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 (36) hide show
  1. package/README.md +30 -0
  2. package/dist/chunks/chunk-7XCIIOM6.cjs +1 -0
  3. package/dist/chunks/chunk-ABKFCPSL.cjs +234 -0
  4. package/dist/chunks/chunk-B35QBUQP.cjs +34 -0
  5. package/dist/chunks/chunk-BL4XMOO2.cjs +43 -0
  6. package/dist/chunks/chunk-EVDJNYI2.cjs +1 -0
  7. package/dist/chunks/chunk-G3IYU6TZ.mjs +1 -0
  8. package/dist/chunks/chunk-LBEWQNER.mjs +234 -0
  9. package/dist/chunks/chunk-O3Z5ORQ3.mjs +43 -0
  10. package/dist/chunks/chunk-PSPE6FME.mjs +34 -0
  11. package/dist/chunks/chunk-RLZHDTHY.cjs +154 -0
  12. package/dist/chunks/chunk-SV4WN2DV.mjs +2 -0
  13. package/dist/chunks/chunk-TS4OAYIJ.cjs +1 -0
  14. package/dist/chunks/chunk-UEILXBZB.mjs +1 -0
  15. package/dist/chunks/chunk-UTKA3WG3.mjs +1 -0
  16. package/dist/chunks/chunk-YOFBT3V6.cjs +2 -0
  17. package/dist/chunks/chunk-Z4Y3VCYS.mjs +154 -0
  18. package/dist/chunks/code-base-ONPUU5A3.cjs +1 -0
  19. package/dist/chunks/code-base-XJXVJ35Z.mjs +1 -0
  20. package/dist/chunks/database-manager-DRLNOQ6C.cjs +1 -0
  21. package/dist/chunks/database-manager-WOYUSWKD.mjs +1 -0
  22. package/dist/chunks/file-watcher-5WEDJY6M.mjs +1 -0
  23. package/dist/chunks/file-watcher-LZZUEGMY.cjs +1 -0
  24. package/dist/chunks/stdio-server-3DPRM3WQ.cjs +47 -0
  25. package/dist/chunks/stdio-server-3HFZJ5G2.mjs +47 -0
  26. package/dist/chunks/sync-D5GNVNM2.mjs +1 -0
  27. package/dist/chunks/sync-IYOM3Y62.cjs +1 -0
  28. package/dist/cli.cjs +3 -0
  29. package/dist/cli.d.cts +1 -0
  30. package/dist/cli.d.ts +1 -0
  31. package/dist/cli.mjs +3 -0
  32. package/dist/index.cjs +1 -108
  33. package/dist/index.d.cts +494 -21
  34. package/dist/index.d.ts +494 -21
  35. package/dist/index.mjs +1 -108
  36. package/package.json +13 -6
@@ -0,0 +1,43 @@
1
+ 'use strict';var chunkEVDJNYI2_cjs=require('./chunk-EVDJNYI2.cjs'),chunkYOFBT3V6_cjs=require('./chunk-YOFBT3V6.cjs'),chunkB35QBUQP_cjs=require('./chunk-B35QBUQP.cjs'),chunkRLZHDTHY_cjs=require('./chunk-RLZHDTHY.cjs'),chunk7XCIIOM6_cjs=require('./chunk-7XCIIOM6.cjs'),chunkTS4OAYIJ_cjs=require('./chunk-TS4OAYIJ.cjs'),fs=require('fs'),path=require('path'),module$1=require('module'),utils=require('@easbot/utils'),url=require('url'),mcp=require('@easbot/mcp');function oe(t){let e={},n=[];for(let o of t)o==="--force"||o==="-f"?e.force=true:o==="--help"||o==="-h"?e.help=true:o.startsWith("-")||n.push(o);return e.dir=n[0],e}async function D(t){let e=t.dir&&path.isAbsolute(t.dir)?t.dir:path.join(chunkYOFBT3V6_cjs.l(),t.dir??"."),n=chunk7XCIIOM6_cjs.a(e),o=chunk7XCIIOM6_cjs.b(e);if(fs.existsSync(o)&&!t.force)return {configPath:o,created:false,skipped:true};fs.existsSync(n)||fs.mkdirSync(n,{recursive:true});let s={version:1,schema_version:chunkRLZHDTHY_cjs.i,extraction_version:chunkRLZHDTHY_cjs.m,backend:"better-sqlite3",created_at:new Date().toISOString()};if(fs.writeFileSync(o,JSON.stringify(s,null,2),"utf-8"),t.skipAutoSync===false)try{let{runSync:r}=await import('./sync-IYOM3Y62.cjs'),i=await r({dir:e,quiet:!0});return {configPath:o,created:!0,skipped:!1,initialSync:{filesAdded:i.filesAdded,filesUpdated:i.filesUpdated,filesDeleted:i.filesDeleted,nodesCreated:i.nodesCreated,edgesCreated:i.edgesCreated,durationMs:i.durationMs}}}catch(r){let{Log:i}=await import('@easbot/utils');i.create({service:"codebase.init"}).warn("initial sync failed (run `easbot codebase sync` to retry)",{error:String(r)});}return {configPath:o,created:true,skipped:false}}async function j(t){let e=t.dir&&path.isAbsolute(t.dir)?t.dir:path.join(chunkYOFBT3V6_cjs.l(),t.dir??"."),n=e,o=chunk7XCIIOM6_cjs.b(e),s=chunk7XCIIOM6_cjs.c(e),r={rootDir:e,codebaseDir:n,configExists:fs.existsSync(o),dbExists:fs.existsSync(s)};if(r.configExists){r.configPath=o;try{let i=JSON.parse(await import('fs').then(c=>c.promises.readFile(o,"utf-8")));r.indexState=i.index_state,r.schemaVersion=i.schema_version,r.extractionVersion=i.extraction_version,r.backend=i.backend;}catch{}}if(r.dbExists){r.dbPath=s;try{r.dbSize=fs.statSync(s).size;}catch{}try{let{DatabaseManager:i}=await import('./database-manager-DRLNOQ6C.cjs'),c=new i(s);try{let l=c.getStatus();r.indexState=l.indexState??r.indexState,r.extractionVersion=l.extractionVersion??r.extractionVersion,r.isStale=l.isStale,r.nodeCount=l.nodeCount,r.edgeCount=l.edgeCount;}finally{c.close();}}catch{}}return r.configExists?r.dbExists?r.indexState==="failed"?r.recommendation="Last sync failed \u2014 run `easbot codebase index` to retry.":r.isStale?r.recommendation="Index is stale (extraction version mismatch) \u2014 run `easbot codebase recreate` to rebuild.":r.indexState==="uninitialized"?r.recommendation="Config exists but index never built \u2014 run `easbot codebase index` to populate.":r.indexState==="partial"&&(r.recommendation="Last sync partially succeeded \u2014 re-run `easbot codebase index` to fill missing files."):r.recommendation="Run `easbot codebase index` to build the index.":r.recommendation="Run `easbot codebase init` to initialize the configuration.",r}function se(t){let e=[];return e.push("Codebase status"),e.push(` rootDir: ${t.rootDir}`),e.push(` codebaseDir: ${t.rootDir}`),e.push(` config: ${t.configExists?`\u2713 ${t.configPath}`:"\u2717 (run `easbot codebase init`)"}`),t.configExists&&(e.push(` indexState: ${t.indexState??"(unknown)"}${t.isStale?" [STALE \u2014 reindex recommended]":""}`),e.push(` schemaVersion: ${t.schemaVersion??"(unknown)"}`),e.push(` extractionVersion: ${t.extractionVersion??"(unknown)"}`),e.push(` backend: ${t.backend??"(unknown)"}`)),e.push(` db: ${t.dbExists?`\u2713 ${t.dbPath} (${t.dbSize??0} bytes)`:"\u2717"}`),typeof t.nodeCount=="number"&&(e.push(` nodes: ${t.nodeCount}`),e.push(` edges: ${t.edgeCount??0}`)),t.recommendation&&(e.push(""),e.push(` \u{1F4A1} ${t.recommendation}`)),e.join(`
2
+ `)}async function re(t){let e=await j({dir:t.dir}),n=[],o;if(e.dbExists)try{let{DatabaseManager:i}=await import('./database-manager-DRLNOQ6C.cjs'),c=new i(e.dbPath);try{let{issues:l,stats:y}=c.checkIntegrity();for(let g of l)n.push({severity:g.severity,message:g.message});o=y,o.parse_errors===0&&n.push({severity:"info",message:"parse_errors: 0 (no parse errors recorded)"}),o.unresolved_refs===0&&n.push({severity:"info",message:"unresolved_refs: 0 (resolution pipeline not active)"}),o.name_segment_vocab===0&&n.push({severity:"info",message:"name_segment_vocab: 0 (identifier-segments not active)"}),o.project_metadata===0&&n.push({severity:"info",message:"project_metadata: 0 (CodeBase.initialize not run)"});}finally{c.close();}}catch(i){n.push({severity:"warn",message:`db integrity check failed: ${i instanceof Error?i.message:String(i)}`});}let s=module$1.createRequire(chunkTS4OAYIJ_cjs.b),r={"better-sqlite3":false,"node:sqlite":false,"@tursodatabase/database":false};try{s.resolve("better-sqlite3"),r["better-sqlite3"]=!0;}catch{}r["node:sqlite"]=typeof process.versions.sqlite=="string";try{s.resolve("@tursodatabase/database"),r["@tursodatabase/database"]=!0;}catch{}return e.configExists||n.push({severity:"warn",message:"config not found \u2014 run `easbot codebase init` first"}),e.dbExists||n.push({severity:"info",message:"db not initialized \u2014 run `easbot codebase index` to build"}),!r["better-sqlite3"]&&!r["node:sqlite"]&&n.push({severity:"error",message:"no SQLite backend available (install better-sqlite3 or use Node 22.5+)"}),e.configExists&&e.backend&&!r[e.backend]&&n.push({severity:"error",message:`configured backend "${e.backend}" not available in this environment`}),{healthy:!n.some(i=>i.severity==="error"),issues:n,status:e,backendAvailable:r,dbStats:o??void 0}}function ie(t){let e=[];e.push("Codebase doctor"),e.push(` healthy: ${t.healthy?"\u2713":"\u2717"}`),e.push(" backend availability:");for(let[r,i]of Object.entries(t.backendAvailable))e.push(` - ${r}: ${i?"\u2713":"\u2717"}`);let n=t.issues.filter(r=>r.severity==="error"),o=t.issues.filter(r=>r.severity==="warn"),s=t.issues.filter(r=>r.severity==="info");if(t.issues.length===0)e.push(" issues: none");else {e.push(` issues: ${t.issues.length} total (${n.length} error, ${o.length} warn, ${s.length} info)`);for(let r of n)e.push(` [error] ${r.message}`);for(let r of o)e.push(` [warn] ${r.message}`);for(let r of s.slice(0,5))e.push(` [info] ${r.message}`);s.length>5&&e.push(` [info] ... (${s.length-5} more)`);}return e.join(`
3
+ `)}function ae(t){let e={},n=[];for(let o of t)if(o==="--no-embed")e.noEmbed=true;else if(o==="--embed")e.noEmbed=false;else if(o==="--json")e.json=true;else if(o==="--verbose"||o==="-v")e.verbose=true;else if(o==="--quiet"||o==="-q")e.quiet=true;else if(o==="--help"||o==="-h")e.help=true;else if(o.startsWith("--batch=")){let s=o.slice(8),r=Number.parseInt(s,10);Number.isFinite(r)&&r>0&&(e.batch=r);}else o.startsWith("-")||n.push(o);return e.dir=n[0],e}async function le(t){let e=t.dir&&path.isAbsolute(t.dir)?t.dir:path.join(chunkYOFBT3V6_cjs.l(),t.dir??".");chunk7XCIIOM6_cjs.a(e);chunk7XCIIOM6_cjs.b(e);await D({dir:e});let {CodeBase:s}=await import('./code-base-ONPUU5A3.cjs'),{DEFAULT_EMBEDDING_CONFIG:r,DEFAULT_INDEXER_CONFIG:i,DEFAULT_PARSER_CONFIG:c}=await import('@easbot/types'),l=t.batch??i.batchSize??50,y=new s({workspaceDir:e,database:{path:chunk7XCIIOM6_cjs.c(e),walMode:true},embedding:t.noEmbed===false?r:void 0,indexer:{...i,batchSize:l},parser:c,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}}),h=-1,w=0,a=!t.quiet,N;try{await y.initialize();let x=await y.indexDirectory(e,a?p=>{let E=Math.max(p.total,1),d=Math.min(100,Math.floor(p.processed/E*100)),m=Date.now();if(d!==h||m-w>3e4){let b=String(d).padStart(3," ");console.error(` \u{1F4A1} [${b}%] ${p.stage}: ${p.processed}/${p.total} files`),h=d,w=m;}}:void 0);N={rootDir:e,success:x.success,filesProcessed:x.filesProcessed,nodesCreated:x.nodesCreated,edgesCreated:x.edgesCreated,errorCount:x.errors.length,errors:x.errors,durationMs:x.duration,embedded:!t.noEmbed,batchSize:l};}finally{await y.close();}return N}function de(t){let e=[];if(e.push("Codebase index"),e.push(` rootDir: ${t.rootDir}`),e.push(` success: ${t.success?"\u2713":"\u2717"}`),e.push(` files processed: ${t.filesProcessed}`),e.push(` nodes created: ${t.nodesCreated}`),e.push(` edges created: ${t.edgesCreated}`),e.push(` embedded: ${t.embedded?"yes":"no (--no-embed)"}`),e.push(` batch size: ${t.batchSize}`),e.push(` duration: ${t.durationMs}ms`),t.errorCount>0){e.push(` errors (${t.errorCount}):`);for(let n of t.errors.slice(0,10))e.push(` - ${n.filePath}: ${n.error}`);t.errors.length>10&&e.push(` ... and ${t.errors.length-10} more`);}return e.join(`
4
+ `)}function fe(t){let e={},n=[];for(let o of t)o==="--keep-config"?e.keepConfig=true:o==="--force"||o==="-f"?e.force=true:o==="--help"||o==="-h"?e.help=true:o.startsWith("-")||n.push(o);return e.dir=n[0],e}async function ge(t){let e=t.dir&&path.isAbsolute(t.dir)?t.dir:path.join(chunkYOFBT3V6_cjs.l(),t.dir??".");chunk7XCIIOM6_cjs.a(e);let o=chunk7XCIIOM6_cjs.c(e),s=chunk7XCIIOM6_cjs.b(e),r=false,i=false;for(let c of [o,`${o}-wal`,`${o}-shm`])if(fs.existsSync(c))try{fs.rmSync(c,{force:!0}),c===o&&(r=!0);}catch{}if(!t.keepConfig&&fs.existsSync(s))try{fs.rmSync(s,{force:!0}),i=!0;}catch{}return await D({dir:e,force:true}),{rootDir:e,removedDb:r,removedConfig:i,recreated:true,configPath:s}}function pe(t){let e=[];return e.push("Codebase recreate"),e.push(` rootDir: ${t.rootDir}`),e.push(` removed db: ${t.removedDb?"\u2713":"\u2717 (not found)"}`),e.push(` removed config:${t.removedConfig?"\u2713":"(preserved via --keep-config or absent)"}`),e.push(` \u2713 reinitialized at ${t.configPath}`),e.push(""),e.push("\u{1F4A1} Next: run `easbot codebase index` to rebuild the index."),e.join(`
5
+ `)}function me(t){let e={},n=[];for(let o of t)o==="--keep-embeddings"?e.keepEmbeddings=true:o==="--force"||o==="-f"?e.force=true:o==="--help"||o==="-h"?e.help=true:o.startsWith("-")||n.push(o);return e.dir=n[0],e}async function he(t){let e=t.dir&&path.isAbsolute(t.dir)?t.dir:path.join(chunkYOFBT3V6_cjs.l(),t.dir??".");chunk7XCIIOM6_cjs.a(e);let o=chunk7XCIIOM6_cjs.c(e),s=chunk7XCIIOM6_cjs.b(e);if(!fs.existsSync(o))return await D({dir:e}),{rootDir:e,cleared:false,nodesRemoved:0,edgesRemoved:0,filesRemoved:0,embeddingsPreserved:false,configPreserved:fs.existsSync(s),nextIndexState:"uninitialized"};let{CodeBase:r}=await import('./code-base-ONPUU5A3.cjs'),{DEFAULT_EMBEDDING_CONFIG:i,DEFAULT_INDEXER_CONFIG:c,DEFAULT_PARSER_CONFIG:l}=await import('@easbot/types'),y=new r({workspaceDir:e,database:{path:o,walMode:true},embedding:t.keepEmbeddings?i:void 0,indexer:c,parser:l,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}}),g;try{await y.initialize();let h={nodes:y.getDatabase().getNodeCount(),edges:y.getDatabase().getEdgeCount(),files:y.getDatabase().getFileCount()};await y.clear({keepEmbeddings:!!t.keepEmbeddings}),y.getDatabase().setIndexState("uninitialized"),g={rootDir:e,cleared:!0,nodesRemoved:h.nodes,edgesRemoved:h.edges,filesRemoved:h.files,embeddingsPreserved:!!t.keepEmbeddings,configPreserved:fs.existsSync(s),nextIndexState:"uninitialized"};}finally{await y.close();}return g}function be(t){let e=[];return e.push("Codebase clear"),e.push(` rootDir: ${t.rootDir}`),t.cleared?(e.push(" \u2713 cleared data"),e.push(` nodes removed: ${t.nodesRemoved}`),e.push(` edges removed: ${t.edgesRemoved}`),e.push(` file hashes removed: ${t.filesRemoved}`),e.push(` embeddings preserved: ${t.embeddingsPreserved?"yes (--keep-embeddings)":"no"}`),e.push(` config preserved: ${t.configPreserved?"\u2713":"\u2717"}`)):(e.push(" \u2717 db not found at .easbot/db/codebase.db \u2014 nothing to clear"),e.push(` config preserved: ${t.configPreserved?"\u2713":"\u2717"}`)),e.push(""),e.push("\u{1F4A1} Next: run `easbot codebase index` to rebuild."),e.join(`
6
+ `)}var ye=new Set(["backend","schema_version","extraction_version","index_state"]);function Zt(t){return new Set(["schema_version","extraction_version"]).has(t)?"number":"string"}function Se(t){let e={},n=[];for(let o of t)o==="--json"?e.json=true:o==="--help"||o==="-h"?e.help=true:o.startsWith("-")||n.push(o);if(n.length>0)if(e.subcommand=n[0],e.subcommand==="set")n.length>1&&(e.key=n[1]),n.length>2&&(e.value=n[2]),n.length>3&&(e.dir=n[3]);else {if(n.length>=2){let o=n[1]??"";path.isAbsolute(o)||o==="."||o===".."||o.startsWith("./")||o.startsWith("../")?e.dir=o:e.key=o;}n.length>=3&&(e.dir=n[2]);}return e}function we(t){let e=fs.readFileSync(t,"utf-8");return JSON.parse(e)}function eo(t,e){fs.writeFileSync(t,JSON.stringify(e,null,2),"utf-8");}function Ee(t){return t.dir&&path.isAbsolute(t.dir)?t.dir:path.join(chunkYOFBT3V6_cjs.l(),t.dir??".")}async function Ce(t){let e=Ee(t),n=chunk7XCIIOM6_cjs.b(e),o=fs.existsSync(n),s={rootDir:e,configPath:o?n:void 0,exists:o,values:null};if(!o)return s;let r;try{r=we(n);}catch{return s}return t.key?(s.key=t.key,s.value=r[t.key]):s.values=r,s}var to=new Set(["backend","schema_version","extraction_version","index_state"]);async function De(t){if(!t.key)throw new Error("config set requires <key>");if(t.value===void 0)throw new Error("config set requires <value> after <key>");if(!ye.has(t.key))throw new Error(`Unsupported config key: "${t.key}". Allowed: ${Array.from(ye).join(", ")}`);let e=Ee(t),n=chunk7XCIIOM6_cjs.a(e),o=chunk7XCIIOM6_cjs.b(e);if(!fs.existsSync(n))throw new Error(`codebase not initialized at ${e} \u2014 run \`easbot codebase init\` first`);let s=t.value;if(Zt(t.key)==="number"){let l=Number(t.value);if(!Number.isFinite(l))throw new Error(`config key "${t.key}" expects a number, got "${t.value}"`);s=l;}let i=fs.existsSync(o)?we(o):{},c=i[t.key];return i[t.key]=s,fs.existsSync(n)||fs.mkdirSync(n,{recursive:true}),eo(o,i),{rootDir:e,configPath:o,key:t.key,oldValue:c,newValue:s,requiresRestart:to.has(t.key)}}function Re(t){if(!t.exists)return `\u2717 config not found at ${t.configPath??"/.easbot/codebase.json"} \u2014 run \`easbot codebase init\` first`;let e=[];if(e.push(`Codebase config: ${t.configPath}`),t.key!==void 0)e.push(` ${t.key}: ${JSON.stringify(t.value)}`);else if(t.values)for(let[n,o]of Object.entries(t.values))e.push(` ${n}: ${JSON.stringify(o)}`);return e.join(`
7
+ `)}function Ie(t){let e=[];return e.push(`\u2713 ${t.key}: ${JSON.stringify(t.oldValue)} \u2192 ${JSON.stringify(t.newValue)} (${t.configPath})`),t.requiresRestart&&(e.push(""),e.push(" \u26A0\uFE0F this setting affects db connection / sync behavior \u2014 restart CodeBase or run `recreate` for the change to take effect.")),e.join(`
8
+ `)}function ve(t){let e={},n=[];for(let o of t)o==="--schema"?e.schema=true:o==="--force"||o==="-f"?e.force=true:o==="--backup"||o==="-b"?e.backup=true:o==="--dry-run"||o==="-n"?e.dryRun=true:o==="--json"?e.json=true:o==="--help"||o==="-h"?e.help=true:o.startsWith("-")||n.push(o);return e.dir=n[0],e}async function ke(t){let e=t.dir&&path.isAbsolute(t.dir)?t.dir:path.join(chunkYOFBT3V6_cjs.l(),t.dir??"."),n=chunk7XCIIOM6_cjs.a(e),o=chunk7XCIIOM6_cjs.c(e);if(fs.existsSync(n)||await D({dir:e}),!fs.existsSync(o))throw new Error(`db not found at ${o} \u2014 run \`easbot codebase index\` first to create it`);let{DatabaseManager:s}=await import('./database-manager-DRLNOQ6C.cjs'),r=new s(o);try{let i=r.db,c=r.isIndexStale(),l=r.getMeta("indexed_with_extraction_version"),y=l?parseInt(l,10):null,g=r.getIndexState(),h=r.getMeta("schema_version"),w=h?parseInt(h,10):0,a={rootDir:e,dbPath:o,wasStale:c,previousVersion:y??null,currentVersion:chunkRLZHDTHY_cjs.m,applied:!1,schemaMigrated:!1,previousSchemaVersion:w,currentSchemaVersion:w,dryRun:!!t.dryRun,schemaSteps:chunkRLZHDTHY_cjs.j.map(d=>({id:d.id,description:d.description,status:"pending"})),migrationErrors:[],indexState:g},N;if(t.backup!==!1&&!t.dryRun)try{let d=new Date().toISOString().replace(/[:.]/g,"-");N=path.join(n,`codebase.db.bak.${d}`),fs.copyFileSync(o,N);for(let m of ["-wal","-shm"]){let u=o+m;fs.existsSync(u)&&fs.copyFileSync(u,N+m);}a.backupPath=N;}catch(d){let m=d instanceof Error?d.message:String(d);a.recommendation=`Backup failed: ${m}. Continuing without backup.`;}let p=t.schema!==!1;try{let d=chunkRLZHDTHY_cjs.k(i,chunkRLZHDTHY_cjs.i,{dryRun:t.dryRun});a.currentSchemaVersion=t.dryRun?d.targetVersion:Math.max(d.currentVersion,d.targetVersion),a.migrationErrors=d.errors.map(u=>({migrationId:u.migrationId,error:u.error}));let m=new Set(d.applied);for(let u of a.schemaSteps)m.has(u.id)&&(u.status=t.dryRun?"pending":"applied");for(let u of a.migrationErrors){let b=a.schemaSteps.find(C=>C.id===u.migrationId);b&&(b.status="failed");}if(a.schemaMigrated=d.applied.length>0&&!t.dryRun,!t.dryRun){let u=chunkRLZHDTHY_cjs.l(i);a.currentSchemaVersion=u,u>0&&r.setMeta("schema_version",String(u));}}catch(d){let m=d instanceof Error?d.message:String(d);a.migrationErrors.push({migrationId:0,error:m});}let E=c||t.force;return E&&!t.dryRun&&(r.setMeta("indexed_with_extraction_version",String(chunkRLZHDTHY_cjs.m)),(g==="stale"||g==="failed")&&(r.setIndexState("complete"),a.indexState="complete"),a.applied=!0),t.dryRun?a.migrationErrors.length>0?a.recommendation="dry-run finished. Run without --dry-run to apply.":a.schemaMigrated?a.recommendation="dry-run: schema migration would apply. Run without --dry-run to apply.":a.recommendation="dry-run: nothing to apply.":!E&&!a.schemaMigrated&&a.migrationErrors.length===0?a.recommendation=`Already current (schema_version=${a.currentSchemaVersion}, extraction_version=${chunkRLZHDTHY_cjs.m}). No upgrade needed.`:a.migrationErrors.length>0?a.recommendation=`Schema migration completed with ${a.migrationErrors.length} error(s). `+(a.backupPath?`Restore from backup: ${a.backupPath}`:"Re-run `recreate` to drop & rebuild."):a.schemaMigrated&&!E?a.recommendation=`Schema migrated (v${a.previousSchemaVersion} \u2192 v${a.currentSchemaVersion}). To apply extraction changes, run \`recreate\` to rebuild data or \`index --force\`.`:a.schemaMigrated&&E?a.recommendation="Schema + extraction metadata both updated. To rebuild data with new extractor, run `recreate` or `index --force`.":a.recommendation="Extraction metadata updated. No schema changes needed.",a}finally{r.close();}}function Pe(t){let e=[];if(e.push(`Codebase upgrade${t.dryRun?" (dry-run)":""}`),e.push(` db: ${t.dbPath}`),t.backupPath&&e.push(` backup: ${t.backupPath}`),e.push(` previous version: ${t.previousVersion??"(none)"}`),e.push(` current version: ${t.currentVersion}`),e.push(` previous schema_version: ${t.previousSchemaVersion}`),e.push(` current schema_version: ${t.currentSchemaVersion}`),e.push(` was stale: ${t.wasStale?"yes":"no"}`),e.push(` applied: ${t.applied?"\u2713":"(noop \u2014 already current)"}`),(t.schemaSteps??[]).length>0){e.push(""),e.push(" schema steps:");for(let n of t.schemaSteps){let o=n.status==="applied"?"\u2713":n.status==="pending"?"\xB7":n.status==="failed"?"\u2717":"-";e.push(` [${o}] v${n.id}: ${n.description}`);}}if((t.migrationErrors??[]).length>0){e.push(""),e.push(` migration errors: ${t.migrationErrors.length}`);for(let n of t.migrationErrors)e.push(` - v${n.migrationId}: ${n.error}`);}return e.push(` index_state: ${t.indexState}`),t.recommendation&&(e.push(""),e.push(` \u{1F4A1} ${t.recommendation}`)),e.join(`
9
+ `)}function $e(t){let e={},n=[];for(let o of t)if(o==="--all")e.all=true;else if(o==="--dry-run"||o==="-n")e.dryRun=true;else if(o==="--pending-list"||o==="-p")e.pendingList=true;else if(o.startsWith("--batch=")){let s=parseInt(o.slice(8),10);Number.isFinite(s)&&s>0&&(e.batchSize=s);}else o==="--json"?e.json=true:o==="--help"||o==="-h"?e.help=true:o.startsWith("-")||n.push(o);return e.dir=n[0],e}var ro=200;function io(t,e=ro){return t?t.length<=e?t:t.slice(0,e)+"\u2026":""}async function _e(t){let e=t.dir&&path.isAbsolute(t.dir)?t.dir:path.join(chunkYOFBT3V6_cjs.l(),t.dir??"."),n=chunk7XCIIOM6_cjs.a(e),o=chunk7XCIIOM6_cjs.c(e);if(!fs.existsSync(n))throw new Error(`codebase not initialized at ${e} \u2014 run \`easbot codebase init\` first`);if(!fs.existsSync(o))throw new Error(`db not found at ${o} \u2014 run \`easbot codebase index\` first to build`);let s=Date.now(),r=process.env.EASBOT_EMBEDDING_MODEL;if(!t.dryRun&&!r)throw new Error('embed requires an embedding model. Set EASBOT_EMBEDDING_MODEL env var (e.g. "openai/text-embedding-3-small") or pass --dry-run to skip embedding generation and just inspect pending nodes. Call `embed` from within an `easbot` REPL session for actual generation.');let{CodeBase:i}=await import('./code-base-ONPUU5A3.cjs'),{DEFAULT_EMBEDDING_CONFIG:c,DEFAULT_INDEXER_CONFIG:l,DEFAULT_PARSER_CONFIG:y}=await import('@easbot/types'),g={...c,modelId:r??"(dry-run)"},h=new i({workspaceDir:e,database:{path:o,walMode:true},embedding:g,indexer:l,parser:y,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});try{await h.initialize();let w=h.getDatabase(),a=w.getNodeCount(),N=w.queryAll("SELECT node_id FROM node_embeddings"),x=new Set(N.map(m=>m.node_id)),p;if(t.all)p=w.queryAll("SELECT id, name, ast_type, language, file_path, text FROM nodes");else if(x.size===0)p=w.queryAll("SELECT id, name, ast_type, language, file_path, text FROM nodes");else {let m=Array.from(x),u=m.map(()=>"?").join(",");p=w.queryAll(`SELECT id, name, ast_type, language, file_path, text FROM nodes WHERE id NOT IN (${u})`,m);}let E=p.map(m=>({id:m.id,name:m.name,ast_type:m.ast_type,file_path:m.file_path,language:m.language,text_preview:io(m.text)})),d={rootDir:e,dbPath:o,totalNodes:a,alreadyEmbedded:x.size,newlyEmbedded:0,failed:0,all:!!t.all,dryRun:!!t.dryRun,pendingList:t.pendingList?E:[],duration:Date.now()-s,embeddingModelConfigured:!!r};return t.dryRun?d.recommendation=E.length>0?`dry-run: ${E.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.":E.length===0?d.recommendation="All nodes already have embeddings. Use --all to force regenerate.":d.recommendation=`${E.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).`,d}finally{await h.close();}}function je(t){let e=[],n=t.dryRun?" (dry-run)":"";if(e.push(`Codebase embed${n}`),e.push(` db: ${t.dbPath}`),e.push(` mode: ${t.all?"all (force regenerate)":"incremental (only missing)"}`),e.push(` embedding model: ${t.embeddingModelConfigured?"configured":"(none)"}`),e.push(` total nodes: ${t.totalNodes}`),e.push(` already embedded: ${t.alreadyEmbedded}`),e.push(` newly embedded: ${t.newlyEmbedded}`),t.failed>0&&e.push(` failed: ${t.failed}`),e.push(` pending: ${t.pendingList.length}`),e.push(` duration: ${t.duration}ms`),t.dryRun&&t.pendingList.length>0){e.push(""),e.push(" \u{1F4A1} first 5 pending nodes:");for(let o of t.pendingList.slice(0,5))e.push(` - ${o.id} (${o.ast_type})`);}return t.recommendation&&(e.push(""),e.push(` \u{1F4A1} ${t.recommendation}`)),e.join(`
10
+ `)}var Fe=utils.Log.create({service:"codebase-watch"});function Ae(t){let e={},n=[];for(let o of t)if(o.startsWith("--debounce=")){let s=parseInt(o.slice(11),10);Number.isFinite(s)&&s>0&&(e.debounce=s);}else if(o.startsWith("--interval=")){let s=parseInt(o.slice(11),10);Number.isFinite(s)&&s>0&&(e.interval=s);}else if(o.startsWith("--backend=")){let s=o.slice(10);(s==="fs-events"||s==="inotify"||s==="windows"||s==="brute-force"||s==="watchman"||s==="auto")&&(e.backend=s);}else o.startsWith("--ignore=")?(e.ignore||(e.ignore=[]),e.ignore.push(o.slice(9))):o==="--on-load-failure=throw"?e.onLoadFailure="throw":o==="--on-load-failure=warn"?e.onLoadFailure="warn":o==="--json"?e.json=true:o==="--help"||o==="-h"?e.help=true:o.startsWith("-")||n.push(o);return e.dir=n[0],e}async function Me(t){let e=t.dir&&path.isAbsolute(t.dir)?t.dir:path.join(chunkYOFBT3V6_cjs.l(),t.dir??"."),n=chunk7XCIIOM6_cjs.a(e);fs.existsSync(n)||await D({dir:e});let o=new chunkEVDJNYI2_cjs.a({workspaceDir:e,backend:t.backend??"auto",ignorePatterns:t.ignore,onLoadFailure:t.onLoadFailure??"warn"}),s=[];o.on((r,i)=>{s.push({event:r,relPath:i,at:Date.now()}),Fe.info("watch event",{event:r,relPath:i});}),await o.start();try{await chunkEVDJNYI2_cjs.d(n,process.pid);}catch(r){Fe.warn("failed to write watcher pid",{error:String(r)});}return {watcher:o,events:s,startTime:Date.now()}}function Le(t){return ["Codebase watcher started"," backend: native @parcel/watcher (real-time FS events)"," debounce: 200ms (event coalescing)",` pid: ${process.pid}`,` initial events: ${t.length}`].join(`
11
+ `)}function Ue(t){let e={},n=[];for(let o of t)o==="--force"||o==="-f"?e.force=true:o==="--json"?e.json=true:o==="--help"||o==="-h"?e.help=true:o.startsWith("-")||n.push(o);return e.dir=n[0],e}async function qe(t){let e=t.dir&&path.isAbsolute(t.dir)?t.dir:path.join(chunkYOFBT3V6_cjs.l(),t.dir??"."),n=chunk7XCIIOM6_cjs.a(e);fs.existsSync(n)||await D({dir:e});let o=path.join(n,".watcher.pid"),s=chunkEVDJNYI2_cjs.c(n);if(s===null)return {rootDir:e,pidFile:o,pid:null,stopped:false,error:"No watcher running (no .easbot/.watcher.pid found)"};try{return process.kill(s,"SIGTERM"),await chunkEVDJNYI2_cjs.e(n),{rootDir:e,pidFile:o,pid:s,stopped:!0}}catch(r){await chunkEVDJNYI2_cjs.e(n);let i=r instanceof Error?r.message:String(r);return {rootDir:e,pidFile:o,pid:s,stopped:false,error:i}}}function Ge(t){let e=[];return e.push("Codebase stop"),e.push(` pid file: ${t.pidFile}`),e.push(` pid: ${t.pid??"(none)"}`),e.push(` stopped: ${t.stopped?"\u2713":"\u2717"}`),t.error?(e.push(` error: ${t.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 [dir]` to start a new watcher session.")),e.join(`
12
+ `)}function ze(t){let e={includeEdges:true,enableEmbedding:true},n=[];for(let o of t)if(o==="--help"||o==="-h")e.help=true;else if(o==="--json")e.json=true;else if(o==="--no-edges")e.includeEdges=false;else if(o==="--no-vector"||o==="--no-embed")e.enableEmbedding=false;else if(o.startsWith("-l=")||o.startsWith("--language="))e.language=o.includes("=")?o.split("=")[1]:void 0;else if(!(o==="-l"||o==="--language"))if(o.startsWith("--ast="))e.astType=o.slice(6);else if(o.startsWith("-n=")||o.startsWith("--max=")){let s=parseInt(o.split("=")[1]??"",10);Number.isFinite(s)&&s>0&&(e.maxResults=s);}else o.startsWith("--dir=")?e.dir=o.slice(6):o.startsWith("-")||n.push(o);return n.length>0&&(e.query=n.join(" ")),e}async function Ve(t){let e=path.isAbsolute(t.dir??"")&&t.dir?t.dir:path.join(chunkYOFBT3V6_cjs.l(),t.dir??"."),n=chunk7XCIIOM6_cjs.a(e),o=chunk7XCIIOM6_cjs.c(e);if(fs.existsSync(n)||await D({dir:e}),!fs.existsSync(o))throw new Error(`db not found at ${o} \u2014 run \`easbot codebase index\` first`);let{CodeBase:s}=await import('./code-base-ONPUU5A3.cjs'),{DEFAULT_EMBEDDING_CONFIG:r,DEFAULT_INDEXER_CONFIG:i,DEFAULT_PARSER_CONFIG:c,DEFAULT_SEARCH_CONFIG:l}=await import('@easbot/types'),y=new s({workspaceDir:e,database:{path:o,walMode:true},embedding:t.enableEmbedding?r:void 0,indexer:i,parser:c,search:l,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}}),g=Date.now();try{await y.initialize();let w=await y.getQuery().search(t.query??"",{maxResults:t.maxResults??20,language:t.language,astType:t.astType,includeEdges:t.includeEdges,enableEmbedding:t.enableEmbedding});return {rootDir:e,query:t.query??"",totalResults:w.length,results:w.map(a=>({id:a.id,name:a.name,astType:a.ast_type,language:a.language,filePath:a.file_path,startLine:a.start_line??0,endLine:a.end_line??0,snippet:(a.text??"").slice(0,200),edgeCount:(a.edges??[]).length})),durationMs:Date.now()-g}}finally{await y.close();}}function Je(t){let e=[];e.push(`Codebase query: ${JSON.stringify(t.query)}`),e.push(` results: ${t.totalResults} (in ${t.durationMs}ms)`);for(let n of t.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 He(t){let e={includeEdges:false},n=[];for(let o of t)if(o==="--help"||o==="-h")e.help=true;else if(o==="--json")e.json=true;else if(o==="--edges")e.includeEdges=true;else if(o.startsWith("--file="))e.file=o.slice(7);else if(o.startsWith("--kind="))e.kind=o.slice(7);else if(o.startsWith("--max=")){let s=parseInt(o.slice(6),10);Number.isFinite(s)&&s>0&&(e.edgesLimit=s);}else o.startsWith("--dir=")?e.dir=o.slice(6):o.startsWith("-")||n.push(o);return n.length>0&&(e.name=n[0]),e}async function Xe(t){if(!t.name&&!t.nodeId)throw new Error("node command requires a <name> or <node-id> argument");let e=path.isAbsolute(t.dir??"")&&t.dir?t.dir:path.join(chunkYOFBT3V6_cjs.l(),t.dir??"."),n=chunk7XCIIOM6_cjs.a(e),o=chunk7XCIIOM6_cjs.c(e);if(fs.existsSync(n)||await D({dir:e}),!fs.existsSync(o))throw new Error(`db not found at ${o} \u2014 run \`easbot codebase index\` first`);let r=await chunkB35QBUQP_cjs.e({workspaceDir:e,rootDir:e},{name:t.name,nodeId:t.nodeId,file:t.file,kind:t.kind,includeEdges:t.includeEdges??false,includeContent:true,edgesLimit:t.edgesLimit??50});if(!r.node)return {rootDir:e,found:false,incomingEdges:[],outgoingEdges:[]};let i=[],c=[];for(let l of r.edges)l.target===r.node.id?i.push({id:l.id,relation:l.relation,source:l.source,target:l.target,direction:"in"}):c.push({id:l.id,relation:l.relation,source:l.source,target:l.target,direction:"out"});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:i,outgoingEdges:c}}function Ye(t){if(!t.found||!t.node)return `\u2717 node not found (rootDir: ${t.rootDir})`;let e=[];if(e.push(`Codebase node: ${t.node.id}`),e.push(` name: ${t.node.name}`),e.push(` type: ${t.node.astType}`),e.push(` language: ${t.node.language}`),e.push(` location: ${t.node.filePath}:${t.node.startLine}-${t.node.endLine}`),e.push(` edges: ${t.incomingEdges.length} incoming / ${t.outgoingEdges.length} outgoing`),t.incomingEdges.length>0&&typeof t.incomingEdges[0]=="object"&&"relation"in t.incomingEdges[0]){e.push(""),e.push(" incoming edges:");for(let n of t.incomingEdges.slice(0,20))e.push(` [${n.relation}] ${n.source} \u2192 ${n.target}`);e.push(" outgoing edges:");for(let n of t.outgoingEdges.slice(0,20))e.push(` [${n.relation}] ${n.source} \u2192 ${n.target}`);}return e.join(`
14
+ `)}function Ze(t){let e={direction:"both"},n=[];for(let o of t)if(o==="--help"||o==="-h")e.help=true;else if(o==="--json")e.json=true;else if(o.startsWith("--depth=")){let s=parseInt(o.slice(8),10);Number.isFinite(s)&&s>0&&(e.depth=s);}else if(o.startsWith("--max=")){let s=parseInt(o.slice(6),10);Number.isFinite(s)&&s>0&&(e.maxNodes=s);}else if(o.startsWith("--direction=")){let s=o.slice(12);(s==="incoming"||s==="outgoing"||s==="both")&&(e.direction=s);}else if(o.startsWith("--relation=")){let s=o.slice(11).split(",").map(r=>r.trim()).filter(Boolean);e.relationTypes=s;}else o.startsWith("--dir=")?e.dir=o.slice(6):o.startsWith("-")||n.push(o);return n.length>0&&(e.nodeId=n[0]),e}async function et(t){let e=path.isAbsolute(t.dir??"")&&t.dir?t.dir:path.join(chunkYOFBT3V6_cjs.l(),t.dir??"."),n=chunk7XCIIOM6_cjs.a(e),o=chunk7XCIIOM6_cjs.c(e);if(fs.existsSync(n)||await D({dir:e}),!fs.existsSync(o))throw new Error(`db not found at ${o} \u2014 run \`easbot codebase index\` first`);if(!t.nodeId)throw new Error("context command requires a <node-id> argument");let s=t.depth??2,r=t.maxNodes??100,i=t.direction??"both",{CodeBase:c}=await import('./code-base-ONPUU5A3.cjs'),{DEFAULT_EMBEDDING_CONFIG:l,DEFAULT_INDEXER_CONFIG:y,DEFAULT_PARSER_CONFIG:g,DEFAULT_SEARCH_CONFIG:h}=await import('@easbot/types'),w=new c({workspaceDir:e,database:{path:o,walMode:true},embedding:l,indexer:y,parser:g,search:h,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});try{await w.initialize();let a=w.getDatabase(),N=w.getQuery();if(!a.getNodeById(t.nodeId))return {rootDir:e,rootNodeId:t.nodeId,depth:s,totalNodes:0,totalEdges:0,nodes:[],edges:[],truncated:!1};let p=new Map,E=[{nodeId:t.nodeId,depth:0}];p.set(t.nodeId,0);let d=[],m=!1;for(;E.length>0;){let R=E.shift();if(R.depth>=s)continue;if(p.size>=r){m=!0;break}let P=N.queryNeighbors(R.nodeId,{direction:i,relationTypes:t.relationTypes,limit:r-p.size+1});for(let k of P.edges){d.push({source:k.source,target:k.target,relation:k.relation});let A=k.source===R.nodeId?k.target:k.source;if(!p.has(A)&&(p.set(A,R.depth+1),E.push({nodeId:A,depth:R.depth+1}),p.size>=r)){m=!0;break}}if(m)break}let u=Array.from(p.keys()),b=u.length>0?a.queryNodes({ids:u}):[],C=new Map(b.map(R=>[R.id,R])),v=[];for(let[R,P]of p.entries()){let k=C.get(R);k&&v.push({id:k.id,name:k.name,astType:k.ast_type,language:k.language,filePath:k.file_path,depth:P});}return {rootDir:e,rootNodeId:t.nodeId,depth:s,totalNodes:v.length,totalEdges:d.length,nodes:v,edges:d,truncated:m}}finally{await w.close();}}function tt(t){let e=[];e.push(`Codebase context: ${t.rootNodeId} (depth=${t.depth})`),e.push(` nodes: ${t.totalNodes}${t.truncated?" [TRUNCATED]":""}`),e.push(` edges: ${t.totalEdges}`);for(let n of t.nodes.slice(0,50))e.push(` [d=${n.depth}] ${n.name} (${n.astType}) \u2014 ${n.language} ${n.filePath}`);return t.nodes.length>50&&e.push(` ... and ${t.nodes.length-50} more`),e.join(`
15
+ `)}function nt(t){let e={},n=[];for(let o of t)if(o==="--help"||o==="-h")e.help=true;else if(o==="--json")e.json=true;else if(o.startsWith("-d=")||o.startsWith("--depth=")){let s=parseInt(o.split("=")[1]??"",10);Number.isFinite(s)&&s>0&&(e.depth=s);}else if(o.startsWith("--relation=")){let s=o.slice(11).split(",").map(r=>r.trim()).filter(Boolean);e.relationTypes=s;}else o.startsWith("--dir=")?e.dir=o.slice(6):o.startsWith("-")||n.push(o);return n.length>0&&(e.nodeId=n[0]),e}async function st(t){let e=path.isAbsolute(t.dir??"")&&t.dir?t.dir:path.join(chunkYOFBT3V6_cjs.l(),t.dir??"."),n=chunk7XCIIOM6_cjs.a(e),o=chunk7XCIIOM6_cjs.c(e);if(fs.existsSync(n)||await D({dir:e}),!fs.existsSync(o))throw new Error(`db not found at ${o} \u2014 run \`easbot codebase index\` first`);if(!t.nodeId)throw new Error("impact command requires a <node-id> argument");let s=t.depth??3,r=t.relationTypes??["CALLS","REFERENCES","USES"],{CodeBase:i}=await import('./code-base-ONPUU5A3.cjs'),{DEFAULT_EMBEDDING_CONFIG:c,DEFAULT_INDEXER_CONFIG:l,DEFAULT_PARSER_CONFIG:y,DEFAULT_SEARCH_CONFIG:g}=await import('@easbot/types'),h=new i({workspaceDir:e,database:{path:o,walMode:true},embedding:c,indexer:l,parser:y,search:g,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});try{await h.initialize();let w=h.getQuery(),a=h.getDatabase(),N=new Set([t.nodeId]),x=[],p=[t.nodeId];for(let E=1;E<=s&&p.length!==0;E++){let d=[],m=new Set;if(p.length>0){let u=p.map(()=>"?").join(","),b=r.map(()=>"?").join(","),C=a.queryAll(`SELECT source, target, relation FROM edges WHERE target IN (${u}) AND relation IN (${b})`,[...p,...r]);for(let v of C)!N.has(v.source)&&!m.has(v.source)&&(m.add(v.source),N.add(v.source),d.push(v.source));}if(d.length>0){let u=d.slice(0,10),b=u.length>0?a.queryNodes({ids:u}):[],C=new Map(b.map(R=>[R.id,R])),v=u.map(R=>{let P=C.get(R);return {id:R,name:P?.name??"(unknown)",filePath:P?.file_path??"(unknown)"}});x.push({depth:E,count:d.length,sample:v});}p=d;}return {rootDir:e,rootNodeId:t.nodeId,totalImpacted:N.size-1,depth:s,buckets:x}}finally{await h.close();}}function rt(t){let e=[];e.push(`Codebase impact: ${t.rootNodeId} (depth=${t.depth})`),e.push(` total impacted: ${t.totalImpacted}`);for(let n of t.buckets){e.push(` d=${n.depth}: ${n.count} nodes`);for(let o of n.sample.slice(0,5))e.push(` - ${o.name} (${o.filePath})`);}return e.join(`
16
+ `)}var Do="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",Ro=[new RegExp(`(?:^|/)(?:main|index|app|server)\\.(?:${Do})$`)];function at(t){let e={excludeEntry:true};for(let n of t)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(o=>o.trim()).filter(Boolean);else if(n.startsWith("--limit=")){let o=parseInt(n.slice(8),10);Number.isFinite(o)&&o>0&&(e.limit=o);}return e}async function lt(t){let e=path.isAbsolute(t.dir??"")&&t.dir?t.dir:path.join(chunkYOFBT3V6_cjs.l(),t.dir??"."),n=chunk7XCIIOM6_cjs.a(e),o=chunk7XCIIOM6_cjs.c(e);if(fs.existsSync(n)||await D({dir:e}),!fs.existsSync(o))throw new Error(`db not found at ${o} \u2014 run \`easbot codebase index\` first`);let s=t.astTypes??["function","method","class"],r=t.limit??100,i=t.excludeEntry!==false,{CodeBase:c}=await import('./code-base-ONPUU5A3.cjs'),{DEFAULT_EMBEDDING_CONFIG:l,DEFAULT_INDEXER_CONFIG:y,DEFAULT_PARSER_CONFIG:g,DEFAULT_SEARCH_CONFIG:h}=await import('@easbot/types'),w=new c({workspaceDir:e,database:{path:o,walMode:true},embedding:l,indexer:y,parser:g,search:h,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});try{await w.initialize();let a=w.getDatabase(),N=w.getQuery(),x=[],p=0,E=["CALLS","IMPORTS","TYPE_REFERENCES"],d=a.queryAll("SELECT DISTINCT target FROM edges WHERE relation IN ('CALLS','IMPORTS','TYPE_REFERENCES')"),m=new Set(d.map(u=>u.target));for(let u of s){let b=a.queryNodes({astType:u,limit:1e5});for(let C of b){if(i&&Ro.some(v=>v.test(C.file_path))){p++;continue}if(!m.has(C.id)&&(x.push({id:C.id,name:C.name,astType:C.ast_type,filePath:C.file_path,startLine:C.start_line??0}),x.length>=r))break}if(x.length>=r)break}return {rootDir:e,totalCandidates:x.length,excludedEntry:p,candidates:x.slice(0,r)}}finally{await w.close();}}function dt(t){let e=[];e.push("Codebase dead-code"),e.push(` total candidates: ${t.totalCandidates}`),t.excludedEntry>0&&e.push(` excluded (entry files): ${t.excludedEntry}`);for(let n of t.candidates.slice(0,50))e.push(` - ${n.name} (${n.astType}) \u2014 ${n.filePath}:${n.startLine}`);return t.candidates.length>50&&e.push(` ... and ${t.candidates.length-50} more`),e.join(`
17
+ `)}function ut(t){let e={relation:"IMPORTS",scope:"file"};for(let n of t)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 o=n.slice(8);(o==="file"||o==="module")&&(e.scope=o);}return e}function Oo(t){let e=0,n=new Map,o=new Map,s=new Set,r=[],i=[];function c(l){n.set(l,e),o.set(l,e),e++,r.push(l),s.add(l);let y=t.get(l)??[];for(let g of y)n.has(g)?s.has(g)&&o.set(l,Math.min(o.get(l),n.get(g))):(c(g),o.set(l,Math.min(o.get(l),o.get(g))));if(o.get(l)===n.get(l)){let g=[],h;do h=r.pop(),s.delete(h),g.push(h);while(h!==l);g.length>1&&i.push(g);}}for(let l of t.keys())n.has(l)||c(l);return i}async function ft(t){let e=path.isAbsolute(t.dir??"")&&t.dir?t.dir:path.join(chunkYOFBT3V6_cjs.l(),t.dir??"."),n=chunk7XCIIOM6_cjs.a(e),o=chunk7XCIIOM6_cjs.c(e);if(fs.existsSync(n)||await D({dir:e}),!fs.existsSync(o))throw new Error(`db not found at ${o} \u2014 run \`easbot codebase index\` first`);let s=t.relation??"IMPORTS",{CodeBase:r}=await import('./code-base-ONPUU5A3.cjs'),{DEFAULT_EMBEDDING_CONFIG:i,DEFAULT_INDEXER_CONFIG:c,DEFAULT_PARSER_CONFIG:l,DEFAULT_SEARCH_CONFIG:y}=await import('@easbot/types'),g=new r({workspaceDir:e,database:{path:o,walMode:true},embedding:i,indexer:c,parser:l,search:y,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});try{await g.initialize();let h=g.getDatabase(),w=h.queryNodes({limit:1e5}),a=new Map;for(let b of w){let C=a.get(b.file_path)??[];C.push(b.id),a.set(b.file_path,C);}let N=w.map(b=>b.id),x=new Map;for(let b of w)x.set(b.id,b.file_path);let p;if(N.length===0)p=[];else {let b=N.map(()=>"?").join(",");p=h.queryAll(`SELECT * FROM edges WHERE relation = ? AND source IN (${b})`,[s,...N]);}let E=new Map;for(let b of p){let C=x.get(b.source),v=x.get(b.target);if(!C||!v||C===v)continue;let R=E.get(C);R||(R=new Set,E.set(C,R)),R.add(v);}let d=new Map;for(let[b,C]of E.entries())d.set(b,Array.from(C));let u=Oo(d).map(b=>{let C=[];for(let v=0;v<b.length;v++){let R=b[v],P=E.get(R);if(P)for(let k of P)b.includes(k)&&C.push({source:R,target:k});}return {cycle:b,edges:C}});return {rootDir:e,relation:s,totalCycles:u.length,cycles:u.slice(0,50)}}finally{await g.close();}}function gt(t){let e=[];e.push(`Codebase circular (relation=${t.relation})`),e.push(` total cycles: ${t.totalCycles}`);for(let n=0;n<t.cycles.length;n++){let o=t.cycles[n];e.push(` cycle #${n+1} (${o.cycle.length} files):`),e.push(` ${o.cycle.join(" \u2192 ")} \u2192 ${o.cycle[0]}`);}return e.join(`
18
+ `)}function mt(t){let e={},n=[];for(let o of t)if(o==="--help"||o==="-h")e.help=true;else if(o==="--json")e.json=true;else if(o.startsWith("-d=")||o.startsWith("--depth=")){let s=parseInt(o.split("=")[1]??"",10);Number.isFinite(s)&&s>0&&(e.depth=s);}else if(o.startsWith("--relation=")){let s=o.slice(11).split(",").map(r=>r.trim()).filter(Boolean);e.relationTypes=s;}else o.startsWith("-")||n.push(o);return n.length>0&&(e.fromId=n[0]),n.length>1&&(e.toId=n[1]),e}async function ht(t){let e=path.isAbsolute(t.dir??"")&&t.dir?t.dir:path.join(chunkYOFBT3V6_cjs.l(),t.dir??"."),n=chunk7XCIIOM6_cjs.a(e),o=chunk7XCIIOM6_cjs.c(e);if(fs.existsSync(n)||await D({dir:e}),!fs.existsSync(o))throw new Error(`db not found at ${o} \u2014 run \`easbot codebase index\` first`);if(!t.fromId||!t.toId)throw new Error("path command requires <from> and <to> node IDs");let s=t.depth??6,r=t.relationTypes??["CALLS","IMPORTS"],{CodeBase:i}=await import('./code-base-ONPUU5A3.cjs'),{DEFAULT_EMBEDDING_CONFIG:c,DEFAULT_INDEXER_CONFIG:l,DEFAULT_PARSER_CONFIG:y,DEFAULT_SEARCH_CONFIG:g}=await import('@easbot/types'),h=new i({workspaceDir:e,database:{path:o,walMode:true},embedding:c,indexer:l,parser:y,search:g,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});try{await h.initialize();let w=h.getQuery();if(t.fromId===t.toId)return {rootDir:e,found:!0,depth:0,steps:[],pathNodes:[t.fromId]};let a=new Set([t.fromId]),N=new Map,x=[t.fromId],p=!1;e:for(let u=0;u<=s;u++){let b=[];for(let C of x){let v=w.queryNeighbors(C,{direction:"both",relationTypes:r,limit:1e3});for(let R of v.edges){let P=R.source===C?R.target:R.source;if(!a.has(P)){if(a.add(P),N.set(P,{via:C,relation:R.relation}),P===t.toId){p=!0;break e}b.push(P);}}}x.length=0,x.push(...b);}if(!p)return {rootDir:e,found:!1,depth:0,steps:[],pathNodes:[]};let E=[t.toId],d=[],m=t.toId;for(;m!==t.fromId;){let u=N.get(m);if(!u)break;d.unshift({from:u.via,to:m,relation:u.relation}),E.unshift(u.via),m=u.via;}return {rootDir:e,found:!0,depth:d.length,steps:d,pathNodes:E}}finally{await h.close();}}function bt(t){let e=[];if(!t.found)return e.push("Codebase path: NOT FOUND within depth limit"),e.join(`
19
+ `);e.push(`Codebase path: depth=${t.depth}`);for(let n=0;n<t.steps.length;n++){let o=t.steps[n];e.push(` ${n+1}. [${o.relation}] ${o.from} \u2192 ${o.to}`);}return e.join(`
20
+ `)}function wt(t){let e={},n=[];for(let o of t)o==="--help"||o==="-h"?e.help=true:o.startsWith("-")||n.push(o);return e.dir=n[0],e}async function Et(t){let e=path.isAbsolute(t.dir??"")&&t.dir?t.dir:path.join(chunkYOFBT3V6_cjs.l(),t.dir??"."),n=chunk7XCIIOM6_cjs.a(e),o=chunk7XCIIOM6_cjs.c(e);if(fs.existsSync(n)||await D({dir:e}),!fs.existsSync(o))throw new Error(`db not found at ${o} \u2014 run \`easbot codebase index\` first`);let{CodeBase:s}=await import('./code-base-ONPUU5A3.cjs'),{DEFAULT_EMBEDDING_CONFIG:r,DEFAULT_INDEXER_CONFIG:i,DEFAULT_PARSER_CONFIG:c,DEFAULT_SEARCH_CONFIG:l}=await import('@easbot/types'),{CodebaseStdioServer:y}=await import('./stdio-server-3DPRM3WQ.cjs'),g="0.0.0";try{let x=path.dirname(url.fileURLToPath(chunkTS4OAYIJ_cjs.b));for(let p=0;p<8;p++){try{let d=JSON.parse(fs.readFileSync(path.join(x,"package.json"),"utf-8"));if(d?.name==="@easbot/codebase"&&typeof d.version=="string"){g=d.version;break}}catch{}let E=path.dirname(x);if(E===x)break;x=E;}}catch{}let h=new s({workspaceDir:e,database:{path:o,walMode:true},embedding:r,indexer:i,parser:c,search:l,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});await h.initialize();let w={id:"easbot-codebase-mcp",name:"EASBot Codebase MCP",version:g,transportType:mcp.ServerTransportType.STDIO},a=await y.start(h,w);return {rootDir:e,tools:a.tools}}var Mo=utils.Log.create({service:"codebase-cmd-callers"});function Ct(t){let e={maxResults:20},n=[];for(let o of t)if(o==="--help"||o==="-h")e.help=true;else if(o==="--json")e.json=true;else if(o.startsWith("--file="))e.file=o.slice(7);else if(o.startsWith("--kind="))e.kind=o.slice(7);else if(o.startsWith("--max=")){let s=parseInt(o.slice(6),10);Number.isFinite(s)&&s>0&&(e.maxResults=s);}else o.startsWith("--dir=")?e.dir=o.slice(6):o.startsWith("-")||n.push(o);return n.length>0&&(e.symbol=n[0]),e}async function Dt(t){if(!t.symbol&&!t.nodeId)throw new Error("callers command requires a <symbol> or --nodeId argument");let e=t.dir&&path.isAbsolute(t.dir)?t.dir:path.join(chunkYOFBT3V6_cjs.l(),t.dir??"."),n=Date.now(),s=await chunkB35QBUQP_cjs.h({workspaceDir:e,rootDir:e},{name:t.symbol,nodeId:t.nodeId,file:t.file,kind:t.kind,maxResults:t.maxResults});return Mo.debug("callers command done",{symbol:t.symbol,count:s.callers.length,rootDir:e}),{rootDir:e,serviceResult:s,durationMs:Date.now()-n}}function Rt(t){let{serviceResult:e,rootDir:n}=t,o=[],s=e.root?.name??"?",r=e.truncated?"+":"";if(o.push(`Callers of \`${s}\` (${e.callers.length}${r}) [${n}]`),e.callers.length===0)o.push(" (no incoming edges)");else for(let i of e.callers)o.push(` - [${i.relation}] \`${i.name}\` ${i.filePath}:${i.startLine}`);return e.callers.length>0&&(o.push(""),o.push("\u{1F4A1} Use `easbot codebase node <name>` to read full source of any caller.")),o.join(`
21
+ `)}var qo=utils.Log.create({service:"codebase-cmd-callees"});function It(t){let e={maxResults:20},n=[];for(let o of t)if(o==="--help"||o==="-h")e.help=true;else if(o==="--json")e.json=true;else if(o.startsWith("--file="))e.file=o.slice(7);else if(o.startsWith("--kind="))e.kind=o.slice(7);else if(o.startsWith("--max=")){let s=parseInt(o.slice(6),10);Number.isFinite(s)&&s>0&&(e.maxResults=s);}else o.startsWith("--dir=")?e.dir=o.slice(6):o.startsWith("-")||n.push(o);return n.length>0&&(e.symbol=n[0]),e}async function Nt(t){if(!t.symbol&&!t.nodeId)throw new Error("callees command requires a <symbol> or --nodeId argument");let e=t.dir&&path.isAbsolute(t.dir)?t.dir:path.join(chunkYOFBT3V6_cjs.l(),t.dir??"."),n=Date.now(),s=await chunkB35QBUQP_cjs.i({workspaceDir:e,rootDir:e},{name:t.symbol,nodeId:t.nodeId,file:t.file,kind:t.kind,maxResults:t.maxResults});return qo.debug("callees command done",{symbol:t.symbol,count:s.callers.length,rootDir:e}),{rootDir:e,serviceResult:s,durationMs:Date.now()-n}}function Ot(t){let{serviceResult:e,rootDir:n}=t,o=[],s=e.root?.name??"?",r=e.truncated?"+":"";if(o.push(`Callees of \`${s}\` (${e.callers.length}${r}) [${n}]`),e.callers.length===0)o.push(" (no outgoing edges)");else for(let i of e.callers)o.push(` - [${i.relation}] \`${i.name}\` ${i.filePath}:${i.startLine}`);return e.callers.length>0&&(o.push(""),o.push("\u{1F4A1} Use `easbot codebase node <name>` to read full source of any callee.")),o.join(`
22
+ `)}var Vo=utils.Log.create({service:"codebase-cmd-explore"});function vt(t){let e={maxFiles:5,maxSymbols:3,depth:1,includeContent:true},n=[];for(let o of t)if(o==="--help"||o==="-h")e.help=true;else if(o==="--json")e.json=true;else if(o==="--no-content")e.includeContent=false;else if(o.startsWith("--file="))e.file=o.slice(7);else if(o.startsWith("--kind="))e.kind=o.slice(7);else if(o.startsWith("--max-files=")){let s=parseInt(o.slice(12),10);Number.isFinite(s)&&s>0&&(e.maxFiles=s);}else if(o.startsWith("--max-symbols=")){let s=parseInt(o.slice(14),10);Number.isFinite(s)&&s>0&&(e.maxSymbols=s);}else if(o.startsWith("--depth=")){let s=parseInt(o.slice(8),10);Number.isFinite(s)&&s>0&&(e.depth=s);}else o.startsWith("--intent=")?e.intent=o.slice(9):o.startsWith("--dir=")?e.dir=o.slice(6):o.startsWith("-")||n.push(o);return n.length>0&&(e.query=n.join(" ")),e}async function kt(t){if(!t.query)throw new Error("explore command requires a <query> argument");let e=t.dir&&path.isAbsolute(t.dir)?t.dir:path.join(chunkYOFBT3V6_cjs.l(),t.dir??"."),n=Date.now(),s=await chunkB35QBUQP_cjs.j({workspaceDir:e,rootDir:e},{query:t.query,file:t.file,kind:t.kind,maxFiles:t.maxFiles,maxSymbols:t.maxSymbols,depth:t.depth,includeContent:t.includeContent,intent:t.intent});return Vo.debug("explore command done",{query:t.query,totalHits:s.totalHits,entryPoints:s.entryPoints.length,rootDir:e}),{rootDir:e,serviceResult:s,durationMs:Date.now()-n}}async function Pt(t){let e={pendingFiles:[],toolName:"codebase_explore",writeToDisk:false};return await chunkB35QBUQP_cjs.D(t.serviceResult,e)}var Tt=utils.Log.create({service:"codebase-cli"}),_t=`
23
+ \x1B[36m\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E\x1B[0m
24
+ \x1B[36m\u2502\x1B[0m \x1B[1m@easbot/codebase\x1B[0m \u2014 Code Knowledge Graph for EASBot \x1B[36m\u2502\x1B[0m
25
+ \x1B[36m\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F\x1B[0m
26
+
27
+ Usage: easbot codebase <command> [options]
28
+
29
+ Commands:
30
+ init [dir] Initialize .easbot/codebase.json in the target directory
31
+ status Show index state / db / config
32
+ doctor Run health checks (backend availability, etc.)
33
+ index [dir] Build the full index
34
+ sync Run incremental sync
35
+ recreate Discard the entire db and re-init
36
+ clear Clear all nodes/edges (keep config.json)
37
+ config Get/set .easbot/codebase.json fields
38
+ upgrade Update extraction_version metadata when stale
39
+ embed Generate node embeddings
40
+
41
+ Run \x1B[1measbot codebase <command> --help\x1B[0m for details.
42
+ `;function Qo(){console.log(_t);}function Fi(){console.log(_t),console.log(""),console.log("Available commands:");for(let t of Ho)console.log(` ${t.name.padEnd(14)} ${t.description}`);console.log(""),console.log("Run `easbot codebase <command> --help` for command-specific options.");}var Ho=[{name:"init",description:"Initialize .easbot/codebase.json in the target directory"},{name:"status",description:"Show index state / db / config"},{name:"doctor",description:"Run health checks (backend, FTS, parser)"},{name:"index [dir]",description:"Build the full index"},{name:"sync",description:"Run incremental sync"},{name:"recreate",description:"Discard the entire db and re-init"},{name:"clear",description:"Clear all nodes/edges (keep config.json)"},{name:"config",description:"Get/set .easbot/codebase.json fields"},{name:"upgrade",description:"Update extraction_version metadata when stale"},{name:"embed",description:"Dry-run / inspect node embeddings"},{name:"query ...",description:"Hybrid search (FTS + vector + basic)"},{name:"node <id>",description:"Show details for a single node"},{name:"context <id>",description:"Build sub-graph context around a node"},{name:"impact <id>",description:"Blast radius (BFS incoming edges)"},{name:"callers <symbol>",description:"Flat list of who calls <symbol> (incoming edges)"},{name:"callees <symbol>",description:"Flat list of what <symbol> calls (outgoing edges)"},{name:"explore <query>",description:"PRIMARY tool \u2014 source code + caller/callee trail in one call"},{name:"dead-code",description:"Find unused symbols"},{name:"circular",description:"Detect circular dependencies"},{name:"path <from> <to>",description:"Find shortest path between two nodes"},{name:"watch",description:"Watch workspace for file changes (auto-sync)"},{name:"stop",description:"Stop a running file watcher"},{name:"mcp",description:"Start stdio MCP server (6 tools)"}],$t=false;function Xo(){if($t)return;$t=true;let t=false,e=n=>{t||(t=true,console.error(`
43
+ [codebase] received ${n}, cleaning up...`),setTimeout(()=>process.exit(130),200));};process.on("SIGINT",e),process.on("SIGTERM",e);}async function Ai(t,e){if(Xo(),t.length===0)return Qo(),{code:0,handled:false};let n=t[0],o=t.slice(1);try{switch(n){case "init":{let s=oe(o);if(s.help)return console.log("Usage: easbot codebase init [dir] [--force]"),console.log(""),console.log("Initialize .easbot/codebase.json in the target directory."),console.log("Creates .easbot/codebase.json with default backend = better-sqlite3."),console.log(""),console.log("Options:"),console.log(" --force, -f Overwrite existing config.json"),{code:0,handled:!0,command:n};let r=await D({...s,skipAutoSync:!1});return r.skipped?(console.log(`codebase config already exists at ${r.configPath} (use --force to overwrite)`),{code:0,handled:!0,command:n}):(console.log(`\u2713 codebase initialized at ${r.configPath}`),{code:0,handled:!0,command:n})}case "status":{let s=Yo(o),r=await j(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(se(r)),{code:0,handled:!0,command:n}}case "doctor":{let s=Ko(o),r=await re(s);return console.log(ie(r)),{code:r.healthy?0:1,handled:!0,command:n}}case "index":{let s=ae(o);if(s.help)return console.log("Usage: easbot codebase index [dir] [--embed] [--no-embed] [--batch=N] [--json]"),console.log(""),console.log("Build the full index for the target directory."),console.log("Auto-initializes .easbot/codebase.json if it does not exist."),console.log(""),console.log("Options:"),console.log(" --embed Generate node embeddings (default: skip)"),console.log(" --no-embed Same as default (skip embedding)"),console.log(" --batch=N Batch size for indexing (default 50)"),console.log(" --json Output as JSON (no ANSI)"),{code:0,handled:!0,command:n};let r=await le(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(de(r)),{code:r.success?0:1,handled:!0,command:n}}case "sync":{let s=chunkYOFBT3V6_cjs.m(o);if(s.help)return console.log("Usage: easbot codebase sync [--embed] [--no-embed] [--quiet] [--json] [dir]"),console.log(""),console.log("Run incremental sync (only adds/updates/deletes changed files)."),console.log("Auto-updates meta['indexed_with_version'] on success."),console.log(""),console.log("Options:"),console.log(" --embed Enable node embeddings (default off, FTS-only)"),console.log(" --no-embed Explicitly disable embeddings (default)"),console.log(" --quiet, -q Only print summary"),console.log(" --json Output as JSON (no ANSI)"),{code:0,handled:!0,command:n};let r=await chunkYOFBT3V6_cjs.n(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(chunkYOFBT3V6_cjs.o(r)),{code:r.success?0:1,handled:!0,command:n}}case "recreate":{let s=fe(o);if(s.help)return console.log("Usage: easbot codebase recreate [--keep-config] [--force] [dir]"),console.log(""),console.log("Discard the entire db (codebase.db + -wal + -shm) and re-init."),console.log("Equivalent to codegraph `recreate()` for safe index recovery."),console.log(""),console.log("Options:"),console.log(" --keep-config Keep .easbot/codebase.json (only drop db)"),console.log(" --force, -f Skip safety prompts (for scripts)"),console.log(""),console.log("\u26A0\uFE0F This deletes the entire index. Run `index` after."),{code:0,handled:!0,command:n};let r=await ge(s);return console.log(pe(r)),{code:0,handled:!0,command:n}}case "clear":{let s=me(o);if(s.help)return console.log("Usage: easbot codebase clear [--keep-embeddings] [--force] [dir]"),console.log(""),console.log("Clear all nodes/edges/file_hashes; keep config.json and meta."),console.log('index_state is reset to "uninitialized" so `status` recommends `index`.'),console.log(""),console.log("Options:"),console.log(" --keep-embeddings Preserve node_embeddings / embedding_cache"),console.log(" --force, -f Skip safety prompts (for scripts)"),console.log(""),console.log("\u{1F4A1} Use `recreate` if you want to drop the entire db file."),{code:0,handled:!0,command:n};let r=await he(s);return console.log(be(r)),{code:0,handled:!0,command:n}}case "config":{let s=Se(o);if(s.help)return console.log("Usage: easbot codebase config <get|set> [key] [value] [--json] [dir]"),console.log(""),console.log("Read or write .easbot/codebase.json fields."),console.log(""),console.log("Subcommands:"),console.log(" get [key] Show all fields (or a specific key)"),console.log(" set <key> <value> Update a field (must be in allowlist)"),console.log(""),console.log("Allowed keys: backend, schema_version, extraction_version, index_state"),console.log(""),console.log("Options:"),console.log(" --json Output as JSON (no ANSI)"),{code:0,handled:!0,command:n};if(!s.subcommand)return console.error("config requires a subcommand: get | set"),{code:1,handled:!0,command:n};if(s.subcommand==="get"){let r=await Ce(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(Re(r)),{code:0,handled:!0,command:n}}if(s.subcommand==="set"){let r=await De(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(Ie(r)),{code:0,handled:!0,command:n}}return console.error(`Unknown config subcommand: ${s.subcommand}`),{code:1,handled:!0,command:n}}case "upgrade":{let s=ve(o);if(s.help)return console.log("Usage: easbot codebase upgrade [--schema] [--force] [dir]"),console.log(""),console.log("Update indexed_with_extraction_version metadata when stale."),console.log("Does NOT delete data \u2014 use `recreate` to drop the db entirely."),console.log(""),console.log("Options:"),console.log(" --schema Also re-run ensureSchema (idempotent CREATE TABLE IF NOT EXISTS)"),console.log(" --force, -f Update version even when not stale"),{code:0,handled:!0,command:n};let r=await ke(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(Pe(r)),{code:0,handled:!0,command:n}}case "embed":{let s=$e(o);if(s.help)return console.log("Usage: easbot codebase embed [--all] [--batch=N] [dir]"),console.log(""),console.log("Generate node embeddings for nodes missing from node_embeddings."),console.log("CLI is statistical-only \u2014 actual embedding generation requires"),console.log("an `easbot` REPL session with an injected EmbeddingModel."),console.log(""),console.log("Options:"),console.log(" --all Force regenerate for all nodes"),console.log(" --batch=N Embedding batch size (default 10)"),console.log(""),console.log("Environment:"),console.log(" EASBOT_EMBEDDING_MODEL e.g. openai/text-embedding-3-small"),{code:0,handled:!0,command:n};let r=await _e(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(je(r)),{code:0,handled:!0,command:n}}case "query":{let s=ze(o);if(s.help)return console.log("Usage: easbot codebase query [q...] [-l <lang>] [--ast=<type>] [-n <max>] [--json]"),console.log(""),console.log("Hybrid search (FTS + vector + basic) over indexed code nodes."),console.log("Aliases: search"),console.log(""),console.log("Options:"),console.log(" -l, --language=<lang> Filter by language"),console.log(" --ast=<type> Filter by AST type"),console.log(" -n, --max=<n> Max results (default 20)"),console.log(" --no-vector Disable vector search (FTS + basic only)"),console.log(" --no-edges Do not include edges in results"),console.log(" --json JSON output"),{code:0,handled:!0,command:n};let r=await Ve(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(Je(r)),{code:0,handled:!0,command:n}}case "node":{let s=He(o);if(s.help)return console.log("Usage: easbot codebase node <id> [--edges] [--max=N] [--json]"),console.log(""),console.log("Show details for a single node, including optional edge listing."),{code:0,handled:!0,command:n};let r=await Xe(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(Ye(r)),{code:r.found?0:1,handled:!0,command:n}}case "context":{let s=Ze(o);if(s.help)return console.log("Usage: easbot codebase context <id> [--depth=N] [--max=N] [--direction=<in|out|both>] [--relation=<r1,r2>] [--json]"),console.log(""),console.log("Build a sub-graph context around a node (BFS to N-level neighbors)."),{code:0,handled:!0,command:n};let r=await et(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(tt(r)),{code:0,handled:!0,command:n}}case "impact":{let s=nt(o);if(s.help)return console.log("Usage: easbot codebase impact <id> [-d N | --depth=N] [--relation=<r1,r2>] [--json]"),console.log(""),console.log("Blast radius: BFS incoming CALLS / REFERENCES / USES, bucketed by depth."),{code:0,handled:!0,command:n};let r=await st(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(rt(r)),{code:0,handled:!0,command:n}}case "callers":{let s=Ct(o);if(s.help)return console.log("Usage: easbot codebase callers <symbol> [--file=<path>] [--kind=<kind>] [--max=N] [--json] [--dir=<worktree>]"),console.log(""),console.log("Flat list of who calls <symbol> (incoming CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS)."),console.log(""),console.log("Options:"),console.log(" --file=<path> File path or basename to disambiguate when same-named symbols exist"),console.log(" --kind=<kind> Filter by node kind"),console.log(" --max=<N> Max callers (default 20)"),console.log(" --json Output as JSON"),console.log(" --dir=<worktree> Target worktree (default: cwd)"),{code:0,handled:!0,command:n};let r=await Dt(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(Rt(r)),{code:0,handled:!0,command:n}}case "callees":{let s=It(o);if(s.help)return console.log("Usage: easbot codebase callees <symbol> [--file=<path>] [--kind=<kind>] [--max=N] [--json] [--dir=<worktree>]"),console.log(""),console.log("Flat list of what <symbol> calls (outgoing edges)."),console.log(""),console.log("Options:"),console.log(" --file=<path> File path or basename to disambiguate"),console.log(" --kind=<kind> Filter by node kind"),console.log(" --max=<N> Max callees (default 20)"),console.log(" --json Output as JSON"),console.log(" --dir=<worktree> Target worktree (default: cwd)"),{code:0,handled:!0,command:n};let r=await Nt(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(Ot(r)),{code:0,handled:!0,command:n}}case "explore":{let s=vt(o);if(s.help)return console.log("Usage: easbot codebase explore <query> [--file=<path>] [--kind=<kind>] [--max-files=N] [--max-symbols=N] [--depth=N] [--no-content] [--intent=<ctx>] [--json] [--dir=<worktree>]"),console.log(""),console.log("PRIMARY tool \u2014 single call to get source code + caller/callee trail."),console.log("Query can be a symbol name or natural language."),console.log(""),console.log("Options:"),console.log(" --file=<path> File path or basename to disambiguate"),console.log(" --kind=<kind> Filter by node kind"),console.log(" --max-files=<N> Max entry-point files (default 5)"),console.log(" --max-symbols=<N> Max symbols per file (default 3)"),console.log(" --depth=<N> Neighbor depth for caller/callee trail (default 1)"),console.log(" --no-content Do not include source code (locations only)"),console.log(" --intent=<ctx> LLM context for ranking"),console.log(" --json Output as JSON"),console.log(" --dir=<worktree> Target worktree (default: cwd)"),{code:0,handled:!0,command:n};let r=await kt(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(await Pt(r)),{code:0,handled:!0,command:n}}case "dead-code":{let s=at(o);if(s.help)return console.log("Usage: easbot codebase dead-code [--type=<t1,t2>] [--no-exclude-entry] [--limit=N] [--json]"),console.log(""),console.log("Find nodes with no incoming edges (heuristic dead code)."),{code:0,handled:!0,command:n};let r=await lt(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(dt(r)),{code:0,handled:!0,command:n}}case "circular":{let s=ut(o);if(s.help)return console.log("Usage: easbot codebase circular [--relation=<r>] [--scope=<file|module>] [--json]"),console.log(""),console.log("Detect circular dependencies via Tarjan SCC."),{code:0,handled:!0,command:n};let r=await ft(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(gt(r)),{code:0,handled:!0,command:n}}case "path":{let s=mt(o);if(s.help)return console.log("Usage: easbot codebase path <from> <to> [-d N | --depth=N] [--relation=<r1,r2>] [--json]"),console.log(""),console.log("Find shortest path between two nodes (BFS along CALLS / IMPORTS / TYPE_REFERENCES)."),{code:0,handled:!0,command:n};let r=await ht(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(bt(r)),{code:r.found?0:1,handled:!0,command:n}}case "mcp":{let s=wt(o);return s.help?(console.log("Usage: easbot codebase mcp [dir]"),console.log(""),console.log("Start a stdio MCP server exposing 6 codebase tools:"),console.log(" codebase_query / codebase_node / codebase_context"),console.log(" codebase_impact / codebase_status / codebase_doctor"),console.log(""),console.log("Connect from MCP clients via stdio JSON-RPC."),{code:0,handled:!0,command:n}):(await Et(s),{code:0,handled:!0,command:n})}case "watch":{let s=Ae(o);if(s.help)return console.log("Usage: easbot codebase watch [--debounce=N] [--interval=N] [dir]"),console.log(""),console.log("Watch the workspace directory for file changes and log events."),console.log("Writes a pid file at .easbot/.watcher.pid for subsequent `stop`."),console.log(""),console.log("Options:"),console.log(" --debounce=N Per-path debounce in ms (default 200)"),console.log(" --interval=N Polling interval in ms (default 500)"),console.log(""),console.log("NOTE: This command blocks. Press Ctrl+C to exit."),{code:0,handled:!0,command:n};let r=await Me(s);return console.log(Le(r.events)),await new Promise(i=>{let c=()=>{Tt.info("watcher received signal, stopping"),i();};process.once("SIGINT",c),process.once("SIGTERM",c);}),r.watcher.dispose(),{code:0,handled:!0,command:n}}case "stop":{let s=Ue(o);if(s.help)return console.log("Usage: easbot codebase stop [dir]"),console.log(""),console.log("Stop a running watcher identified by .easbot/.watcher.pid."),console.log(""),console.log("Options:"),console.log(" --force, -f Ignore errors and clear the pid file anyway"),{code:0,handled:!0,command:n};let r=await qe(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(Ge(r)),{code:r.stopped?0:1,handled:!0,command:n}}default:return console.error(`Unknown command: ${n}`),console.error("Run \x1B[1measbot codebase --help\x1B[0m for available commands."),{code:1,handled:!0,command:n}}}catch(s){let r=s instanceof Error?s.message:String(s);return console.error(`codebase ${n} failed: ${r}`),Tt.error("codebase CLI error",{command:n,error:r,stack:s instanceof Error?s.stack:void 0}),{code:1,handled:true,command:n}}}function Yo(t){let e={},n=[];for(let o of t)o==="--json"?e.json=true:o.startsWith("--dir=")?e.dir=o.slice(6):o.startsWith("-")||n.push(o);return e.dir===void 0&&n.length>0&&(e.dir=n[0]),e}function Ko(t){let e={},n=[];for(let o of t)o.startsWith("--dir=")?e.dir=o.slice(6):o.startsWith("-")||n.push(o);return e.dir===void 0&&n.length>0&&(e.dir=n[0]),e}exports.a=Qo;exports.b=Fi;exports.c=Ai;
@@ -0,0 +1 @@
1
+ 'use strict';var chunkTS4OAYIJ_cjs=require('./chunk-TS4OAYIJ.cjs'),fs=require('fs'),path=require('path'),module$1=require('module'),url=require('url'),utils=require('@easbot/utils');var s=utils.Log.create({service:"codebase-file-watcher"}),S=["node_modules/**",".git/**","dist/**","build/**","__pycache__/**","*.min.js","*.min.ts",".easbot/**",".codebase/**"],d=null,l=null;function $(){let n=process.platform==="linux"?`-${globalThis.EASBOT_LIBC||"glibc"}`:"";return `@parcel/watcher-${process.platform}-${process.arch}${n}`}async function _(n){if(d)return d;if(l){let e=new Error(l);throw n==="warn"&&s.warn("@parcel/watcher previously failed",{error:l}),e}let r=path.dirname(url.fileURLToPath(chunkTS4OAYIJ_cjs.b)),t=$();try{let c=(await import('@parcel/watcher/wrapper.js')).createWrapper;if(typeof c!="function")throw new Error("@parcel/watcher/wrapper.js: createWrapper not exported");let p=module$1.createRequire(r+"/")(t),o=c(p);return d=o,s.info("@parcel/watcher loaded",{binding:t,backend:"available"}),o}catch(e){let c=e instanceof Error?e.message:String(e),i=`binding "${t}" not found or failed to load. Run: pnpm install ${t}`;throw l=`${c}. ${i}`,s.error("failed to load @parcel/watcher",{error:e,binding:t}),n==="warn"&&s.warn("continuing without watcher (warn mode)"),e instanceof Error?new Error(l):new Error(l)}}function g(){return process.platform==="darwin"?"fs-events":process.platform==="linux"?"inotify":process.platform==="win32"?"windows":"brute-force"}var b=class{constructor(r){chunkTS4OAYIJ_cjs.a(this,"workspaceDir");chunkTS4OAYIJ_cjs.a(this,"backendOpt");chunkTS4OAYIJ_cjs.a(this,"ignorePatterns");chunkTS4OAYIJ_cjs.a(this,"onLoadFailure");chunkTS4OAYIJ_cjs.a(this,"ignoreInstance");chunkTS4OAYIJ_cjs.a(this,"listeners",new Set);chunkTS4OAYIJ_cjs.a(this,"unsubscribe",null);chunkTS4OAYIJ_cjs.a(this,"disposed",false);chunkTS4OAYIJ_cjs.a(this,"running",false);this.workspaceDir=path.isAbsolute(r.workspaceDir)?r.workspaceDir:path.normalize(r.workspaceDir),this.backendOpt=r.backend??"auto",this.ignorePatterns=r.ignorePatterns??[...S],this.onLoadFailure=r.onLoadFailure??"throw",this.ignoreInstance=utils.Ignore.create().add(this.ignorePatterns);}getIgnoreInstance(){return this.ignoreInstance}getIgnorePatterns(){return this.ignorePatterns}getActiveBackend(){return this.backendOpt==="auto"?g():this.backendOpt}on(r){return this.listeners.add(r),()=>this.listeners.delete(r)}async start(){if(this.running)return;this.running=true;let r=this.backendOpt==="auto"?g():this.backendOpt;s.info("FileWatcher start",{workspaceDir:this.workspaceDir,backend:r});let t;try{t=await _(this.onLoadFailure);}catch(e){if(this.running=false,this.onLoadFailure==="warn")return;throw e}await this.subscribeWithParcel(t,r);}async stop(){if(this.unsubscribe){try{await this.unsubscribe();}catch(r){s.warn("parcel unsubscribe error",{error:r});}this.unsubscribe=null;}this.running=false;}async dispose(){await this.stop(),this.disposed=true,this.listeners.clear();}isRunning(){return this.running}isDisposed(){return this.disposed}async subscribeWithParcel(r,t){if(this.disposed)throw new Error("FileWatcher disposed before subscribe");let e=(i,p)=>{if(this.disposed)return;let o=this.workspaceDir.replace(/\\/g,"/").replace(/\/$/,""),f=p.replace(/\\/g,"/"),u=p;if(f.startsWith(o+"/")&&(u=f.slice(o.length+1)),this.ignoreInstance.ignores(u,i==="create"&&u.endsWith("/")))return;let P=i==="create"?"add":i==="delete"?"unlink":"change";for(let v of this.listeners)try{v(P,u);}catch(k){s.warn("listener threw",{error:k});}},c=await r.subscribe(this.workspaceDir,(i,p)=>{if(i){s.error("parcel subscribe callback error",{error:i});return}for(let o of p)e(o.type,o.path);},{ignore:[...this.ignorePatterns],backend:t});if(this.disposed){await c.unsubscribe().catch(()=>{});return}this.unsubscribe=async()=>{await c.unsubscribe().catch(i=>{s.warn("parcel unsubscribe error",{error:i});});};}};function h(n){return path.join(n,".watcher.pid")}function j(n){let r=h(n);if(!fs.existsSync(r))return null;try{let t=fs.readFileSync(r,"utf-8").trim(),e=parseInt(t,10);return Number.isFinite(e)?e:null}catch{return null}}async function C(n,r){let t=h(n);await fs.promises.writeFile(t,String(r),"utf-8");}async function z(n){let r=h(n);try{await fs.promises.unlink(r);}catch{}}exports.a=b;exports.b=h;exports.c=j;exports.d=C;exports.e=z;
@@ -0,0 +1 @@
1
+ import i from'path';import {fileURLToPath}from'url';var m=Object.defineProperty;var r=(e,t,o)=>t in e?m(e,t,{enumerable:true,configurable:true,writable:true,value:o}):e[t]=o;var c=(e,t,o)=>r(e,typeof t!="symbol"?t+"":t,o);var a=()=>fileURLToPath(import.meta.url),p=()=>i.dirname(a()),_=p();export{c as a,_ as b};