@easbot/codebase 0.3.3 → 0.3.5

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.
@@ -1,43 +1,58 @@
1
- import {c,e,a as a$1,d}from'./chunk-UEILXBZB.mjs';import {m,n,o,l}from'./chunk-SV4WN2DV.mjs';import {j,D as D$1,i,h,e as e$1}from'./chunk-PSPE6FME.mjs';import {j as j$1,m as m$1,k,i as i$1,l as l$1}from'./chunk-Z4Y3VCYS.mjs';import {a,c as c$1,b}from'./chunk-UTKA3WG3.mjs';import {existsSync,readFileSync,copyFileSync,mkdirSync,rmSync,statSync,writeFileSync}from'fs';import {isAbsolute,join,dirname}from'path';import {createRequire}from'module';import {Log}from'@easbot/utils';import {fileURLToPath}from'url';import {ServerTransportType}from'@easbot/mcp';function ne(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&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??"."),n=a(e),o=b(e);if(existsSync(o)&&!t.force)return {configPath:o,created:false,skipped:true};existsSync(n)||mkdirSync(n,{recursive:true});let s={version:1,schema_version:i$1,extraction_version:m$1,backend:"better-sqlite3",created_at:new Date().toISOString()};if(writeFileSync(o,JSON.stringify(s,null,2),"utf-8"),t.skipAutoSync===false)try{let{runSync:r}=await import('./sync-D5GNVNM2.mjs'),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 F(t){let e=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??"."),n=e,o=b(e),s=c$1(e),r={rootDir:e,codebaseDir:n,configExists:existsSync(o),dbExists: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=statSync(s).size;}catch{}try{let{DatabaseManager:i}=await import('./database-manager-WOYUSWKD.mjs'),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 re(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 ie(t){let e=await F({dir:t.dir}),n=[],o;if(e.dbExists)try{let{DatabaseManager:i}=await import('./database-manager-WOYUSWKD.mjs'),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=createRequire(import.meta.url),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 ae(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 le(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 de(t){let e=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??".");a(e);b(e);await D({dir:e});let {CodeBase:s}=await import('./code-base-XJXVJ35Z.mjs'),{DEFAULT_EMBEDDING_CONFIG:r,DEFAULT_INDEXER_CONFIG:i,DEFAULT_PARSER_CONFIG:c}=await import('@easbot/types'),l$1=t.batch??i.batchSize??50,y=new s({workspaceDir:e,database:{path:c$1(e),walMode:true},embedding:t.noEmbed===false?r:void 0,indexer:{...i,batchSize:l$1},parser:c,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}}),h=-1,w=0,a$1=!t.quiet,N;try{await y.initialize();let x=await y.indexDirectory(e,a$1?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$1};}finally{await y.close();}return N}function ce(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 ge(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 pe(t){let e=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??".");a(e);let o=c$1(e),s=b(e),r=false,i=false;for(let c of [o,`${o}-wal`,`${o}-shm`])if(existsSync(c))try{rmSync(c,{force:!0}),c===o&&(r=!0);}catch{}if(!t.keepConfig&&existsSync(s))try{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 me(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 he(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 be(t){let e=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??".");a(e);let o=c$1(e),s=b(e);if(!existsSync(o))return await D({dir:e}),{rootDir:e,cleared:false,nodesRemoved:0,edgesRemoved:0,filesRemoved:0,embeddingsPreserved:false,configPreserved:existsSync(s),nextIndexState:"uninitialized"};let{CodeBase:r}=await import('./code-base-XJXVJ35Z.mjs'),{DEFAULT_EMBEDDING_CONFIG:i,DEFAULT_INDEXER_CONFIG:c,DEFAULT_PARSER_CONFIG:l$1}=await import('@easbot/types'),y=new r({workspaceDir:e,database:{path:o,walMode:true},embedding:t.keepEmbeddings?i:void 0,indexer:c,parser:l$1,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:existsSync(s),nextIndexState:"uninitialized"};}finally{await y.close();}return g}function ye(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 xe=new Set(["backend","schema_version","extraction_version","index_state"]);function eo(t){return new Set(["schema_version","extraction_version"]).has(t)?"number":"string"}function we(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]??"";isAbsolute(o)||o==="."||o===".."||o.startsWith("./")||o.startsWith("../")?e.dir=o:e.key=o;}n.length>=3&&(e.dir=n[2]);}return e}function Ee(t){let e=readFileSync(t,"utf-8");return JSON.parse(e)}function to(t,e){writeFileSync(t,JSON.stringify(e,null,2),"utf-8");}function Ce(t){return t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??".")}async function De(t){let e=Ce(t),n=b(e),o=existsSync(n),s={rootDir:e,configPath:o?n:void 0,exists:o,values:null};if(!o)return s;let r;try{r=Ee(n);}catch{return s}return t.key?(s.key=t.key,s.value=r[t.key]):s.values=r,s}var oo=new Set(["backend","schema_version","extraction_version","index_state"]);async function Re(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(!xe.has(t.key))throw new Error(`Unsupported config key: "${t.key}". Allowed: ${Array.from(xe).join(", ")}`);let e=Ce(t),n=a(e),o=b(e);if(!existsSync(n))throw new Error(`codebase not initialized at ${e} \u2014 run \`easbot codebase init\` first`);let s=t.value;if(eo(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=existsSync(o)?Ee(o):{},c=i[t.key];return i[t.key]=s,existsSync(n)||mkdirSync(n,{recursive:true}),to(o,i),{rootDir:e,configPath:o,key:t.key,oldValue:c,newValue:s,requiresRestart:oo.has(t.key)}}function Ie(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 Ne(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 ke(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 Pe(t){let e=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??"."),n=a(e),o=c$1(e);if(existsSync(n)||await D({dir:e}),!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-WOYUSWKD.mjs'),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:m$1,applied:!1,schemaMigrated:!1,previousSchemaVersion:w,currentSchemaVersion:w,dryRun:!!t.dryRun,schemaSteps:j$1.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=join(n,`codebase.db.bak.${d}`),copyFileSync(o,N);for(let m of ["-wal","-shm"]){let u=o+m;existsSync(u)&&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=k(i,i$1,{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=l$1(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(m$1)),(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=${m$1}). 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 Te(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 io=200;function ao(t,e=io){return t?t.length<=e?t:t.slice(0,e)+"\u2026":""}async function je(t){let e=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??"."),n=a(e),o=c$1(e);if(!existsSync(n))throw new Error(`codebase not initialized at ${e} \u2014 run \`easbot codebase init\` first`);if(!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-XJXVJ35Z.mjs'),{DEFAULT_EMBEDDING_CONFIG:c,DEFAULT_INDEXER_CONFIG:l$1,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$1,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:ao(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 Fe(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 Ae=Log.create({service:"codebase-watch"});function Me(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 Le(t){let e=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??"."),n=a(e);existsSync(n)||await D({dir:e});let o=new a$1({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()}),Ae.info("watch event",{event:r,relPath:i});}),await o.start();try{await d(n,process.pid);}catch(r){Ae.warn("failed to write watcher pid",{error:String(r)});}return {watcher:o,events:s,startTime:Date.now()}}function We(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 qe(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 Ge(t){let e$1=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??"."),n=a(e$1);existsSync(n)||await D({dir:e$1});let o=join(n,".watcher.pid"),s=c(n);if(s===null)return {rootDir:e$1,pidFile:o,pid:null,stopped:false,error:"No watcher running (no .easbot/.watcher.pid found)"};try{return process.kill(s,"SIGTERM"),await e(n),{rootDir:e$1,pidFile:o,pid:s,stopped:!0}}catch(r){await e(n);let i=r instanceof Error?r.message:String(r);return {rootDir:e$1,pidFile:o,pid:s,stopped:false,error:i}}}function Be(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 Ve(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 Je(t){let e=isAbsolute(t.dir??"")&&t.dir?t.dir:join(l(),t.dir??"."),n=a(e),o=c$1(e);if(existsSync(n)||await D({dir:e}),!existsSync(o))throw new Error(`db not found at ${o} \u2014 run \`easbot codebase index\` first`);let{CodeBase:s}=await import('./code-base-XJXVJ35Z.mjs'),{DEFAULT_EMBEDDING_CONFIG:r,DEFAULT_INDEXER_CONFIG:i,DEFAULT_PARSER_CONFIG:c,DEFAULT_SEARCH_CONFIG:l$1}=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$1,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 Qe(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 Xe(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 Ye(t){if(!t.name&&!t.nodeId)throw new Error("node command requires a <name> or <node-id> argument");let e=isAbsolute(t.dir??"")&&t.dir?t.dir:join(l(),t.dir??"."),n=a(e),o=c$1(e);if(existsSync(n)||await D({dir:e}),!existsSync(o))throw new Error(`db not found at ${o} \u2014 run \`easbot codebase index\` first`);let r=await e$1({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 Ke(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 et(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 tt(t){let e=isAbsolute(t.dir??"")&&t.dir?t.dir:join(l(),t.dir??"."),n=a(e),o=c$1(e);if(existsSync(n)||await D({dir:e}),!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-XJXVJ35Z.mjs'),{DEFAULT_EMBEDDING_CONFIG:l$1,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$1,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 T=N.queryNeighbors(R.nodeId,{direction:i,relationTypes:t.relationTypes,limit:r-p.size+1});for(let P of T.edges){d.push({source:P.source,target:P.target,relation:P.relation});let M=P.source===R.nodeId?P.target:P.source;if(!p.has(M)&&(p.set(M,R.depth+1),E.push({nodeId:M,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])),O=[];for(let[R,T]of p.entries()){let P=C.get(R);P&&O.push({id:P.id,name:P.name,astType:P.ast_type,language:P.language,filePath:P.file_path,depth:T});}return {rootDir:e,rootNodeId:t.nodeId,depth:s,totalNodes:O.length,totalEdges:d.length,nodes:O,edges:d,truncated:m}}finally{await w.close();}}function ot(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 st(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 rt(t){let e=isAbsolute(t.dir??"")&&t.dir?t.dir:join(l(),t.dir??"."),n=a(e),o=c$1(e);if(existsSync(n)||await D({dir:e}),!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-XJXVJ35Z.mjs'),{DEFAULT_EMBEDDING_CONFIG:c,DEFAULT_INDEXER_CONFIG:l$1,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$1,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 O of C)!N.has(O.source)&&!m.has(O.source)&&(m.add(O.source),N.add(O.source),d.push(O.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])),O=u.map(R=>{let T=C.get(R);return {id:R,name:T?.name??"(unknown)",filePath:T?.file_path??"(unknown)"}});x.push({depth:E,count:d.length,sample:O});}p=d;}return {rootDir:e,rootNodeId:t.nodeId,totalImpacted:N.size-1,depth:s,buckets:x}}finally{await h.close();}}function it(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 Ro="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",Io=[new RegExp(`(?:^|/)(?:main|index|app|server)\\.(?:${Ro})$`)];function lt(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 dt(t){let e=isAbsolute(t.dir??"")&&t.dir?t.dir:join(l(),t.dir??"."),n=a(e),o=c$1(e);if(existsSync(n)||await D({dir:e}),!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-XJXVJ35Z.mjs'),{DEFAULT_EMBEDDING_CONFIG:l$1,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$1,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&&Io.some(O=>O.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 ct(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 ft(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 vo(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 gt(t){let e=isAbsolute(t.dir??"")&&t.dir?t.dir:join(l(),t.dir??"."),n=a(e),o=c$1(e);if(existsSync(n)||await D({dir:e}),!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-XJXVJ35Z.mjs'),{DEFAULT_EMBEDDING_CONFIG:i,DEFAULT_INDEXER_CONFIG:c,DEFAULT_PARSER_CONFIG:l$1,DEFAULT_SEARCH_CONFIG:y}=await import('@easbot/types'),g=new r({workspaceDir:e,database:{path:o,walMode:true},embedding:i,indexer:c,parser:l$1,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),O=x.get(b.target);if(!C||!O||C===O)continue;let R=E.get(C);R||(R=new Set,E.set(C,R)),R.add(O);}let d=new Map;for(let[b,C]of E.entries())d.set(b,Array.from(C));let u=vo(d).map(b=>{let C=[];for(let O=0;O<b.length;O++){let R=b[O],T=E.get(R);if(T)for(let P of T)b.includes(P)&&C.push({source:R,target:P});}return {cycle:b,edges:C}});return {rootDir:e,relation:s,totalCycles:u.length,cycles:u.slice(0,50)}}finally{await g.close();}}function pt(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 ht(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 bt(t){let e=isAbsolute(t.dir??"")&&t.dir?t.dir:join(l(),t.dir??"."),n=a(e),o=c$1(e);if(existsSync(n)||await D({dir:e}),!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-XJXVJ35Z.mjs'),{DEFAULT_EMBEDDING_CONFIG:c,DEFAULT_INDEXER_CONFIG:l$1,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$1,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 O=w.queryNeighbors(C,{direction:"both",relationTypes:r,limit:1e3});for(let R of O.edges){let T=R.source===C?R.target:R.source;if(!a.has(T)){if(a.add(T),N.set(T,{via:C,relation:R.relation}),T===t.toId){p=!0;break e}b.push(T);}}}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 yt(t){let e=[];if(!t.found)return e.push("Codebase path: NOT FOUND within depth limit"),e.join(`
1
+ import {c,e,a as a$1,d}from'./chunk-UEILXBZB.mjs';import {m,n,o,l}from'./chunk-CJSKATXN.mjs';import {j,D,i,h,e as e$1}from'./chunk-TGMIUXU3.mjs';import {a as a$2}from'./chunk-VBIXWHTD.mjs';import {j as j$1,m as m$1,k,i as i$1,l as l$1}from'./chunk-Z4Y3VCYS.mjs';import {a,c as c$1,b}from'./chunk-UTKA3WG3.mjs';import {existsSync,readFileSync,copyFileSync,mkdirSync,rmSync,statSync,writeFileSync}from'fs';import {isAbsolute,join,dirname}from'path';import {createRequire}from'module';import {Log}from'@easbot/utils';import {fileURLToPath}from'url';import {ServerTransportType}from'@easbot/mcp';function se(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 R(t){let e=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??".");try{let r=await a$2(),{Log:i}=await import('@easbot/utils'),c=i.create({service:"codebase.init"});r.source==="monorepo"?c.debug("better-sqlite3 resolved (monorepo)",{path:r.absolutePath}):c.info("better-sqlite3 auto-installed to cache",{source:r.source,path:r.absolutePath});}catch(r){let{Log:i}=await import('@easbot/utils');i.create({service:"codebase.init"}).warn("better-sqlite3 resolve / install failed; index/sync/mcp may still fail later",{error:r instanceof Error?r.message:String(r),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=a(e),o=b(e);if(existsSync(o)&&!t.force)return {configPath:o,created:false,skipped:true};existsSync(n)||mkdirSync(n,{recursive:true});let s={version:1,schema_version:i$1,extraction_version:m$1,backend:"better-sqlite3",created_at:new Date().toISOString()};if(writeFileSync(o,JSON.stringify(s,null,2),"utf-8"),t.skipAutoSync===false)try{let{runSync:r}=await import('./sync-JNCNYSWI.mjs'),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 F(t){let e=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??"."),n=e,o=b(e),s=c$1(e),r={rootDir:e,codebaseDir:n,configExists:existsSync(o),dbExists: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=statSync(s).size;}catch{}try{let{DatabaseManager:i}=await import('./database-manager-WOYUSWKD.mjs'),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 ie(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 ae(t){let e=await F({dir:t.dir}),n=[],o;if(e.dbExists)try{let{DatabaseManager:i}=await import('./database-manager-WOYUSWKD.mjs'),c=new i(e.dbPath);try{let{issues:l,stats:y}=c.checkIntegrity();for(let f of l)n.push({severity:f.severity,message:f.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=createRequire(import.meta.url),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 le(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 de(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 ce(t){let e=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??".");a(e);b(e);await R({dir:e});let {CodeBase:s}=await import('./code-base-N3PTDWLC.mjs'),{DEFAULT_EMBEDDING_CONFIG:r,DEFAULT_INDEXER_CONFIG:i,DEFAULT_PARSER_CONFIG:c}=await import('@easbot/types'),l$1=t.batch??i.batchSize??50,y=new s({workspaceDir:e,database:{path:c$1(e),walMode:true},embedding:t.noEmbed===false?r:void 0,indexer:{...i,batchSize:l$1},parser:c,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}}),h=-1,S=0,a$1=!t.quiet,N;try{await y.initialize();let x=await y.indexDirectory(e,a$1?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-S>3e4){let b=String(d).padStart(3," ");console.error(` \u{1F4A1} [${b}%] ${p.stage}: ${p.processed}/${p.total} files`),h=d,S=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$1};}finally{await y.close();}return N}function ue(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 pe(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 me(t){let e=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??".");a(e);let o=c$1(e),s=b(e),r=false,i=false;for(let c of [o,`${o}-wal`,`${o}-shm`])if(existsSync(c))try{rmSync(c,{force:!0}),c===o&&(r=!0);}catch{}if(!t.keepConfig&&existsSync(s))try{rmSync(s,{force:!0}),i=!0;}catch{}return await R({dir:e,force:true}),{rootDir:e,removedDb:r,removedConfig:i,recreated:true,configPath:s}}function he(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 be(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 ye(t){let e=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??".");a(e);let o=c$1(e),s=b(e);if(!existsSync(o))return await R({dir:e}),{rootDir:e,cleared:false,nodesRemoved:0,edgesRemoved:0,filesRemoved:0,embeddingsPreserved:false,configPreserved:existsSync(s),nextIndexState:"uninitialized"};let{CodeBase:r}=await import('./code-base-N3PTDWLC.mjs'),{DEFAULT_EMBEDDING_CONFIG:i,DEFAULT_INDEXER_CONFIG:c,DEFAULT_PARSER_CONFIG:l$1}=await import('@easbot/types'),y=new r({workspaceDir:e,database:{path:o,walMode:true},embedding:t.keepEmbeddings?i:void 0,indexer:c,parser:l$1,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}}),f;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"),f={rootDir:e,cleared:!0,nodesRemoved:h.nodes,edgesRemoved:h.edges,filesRemoved:h.files,embeddingsPreserved:!!t.keepEmbeddings,configPreserved:existsSync(s),nextIndexState:"uninitialized"};}finally{await y.close();}return f}function xe(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 we=new Set(["backend","schema_version","extraction_version","index_state"]);function to(t){return new Set(["schema_version","extraction_version"]).has(t)?"number":"string"}function Ee(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]??"";isAbsolute(o)||o==="."||o===".."||o.startsWith("./")||o.startsWith("../")?e.dir=o:e.key=o;}n.length>=3&&(e.dir=n[2]);}return e}function Ce(t){let e=readFileSync(t,"utf-8");return JSON.parse(e)}function oo(t,e){writeFileSync(t,JSON.stringify(e,null,2),"utf-8");}function Re(t){return t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??".")}async function De(t){let e=Re(t),n=b(e),o=existsSync(n),s={rootDir:e,configPath:o?n:void 0,exists:o,values:null};if(!o)return s;let r;try{r=Ce(n);}catch{return s}return t.key?(s.key=t.key,s.value=r[t.key]):s.values=r,s}var no=new Set(["backend","schema_version","extraction_version","index_state"]);async function Oe(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(!we.has(t.key))throw new Error(`Unsupported config key: "${t.key}". Allowed: ${Array.from(we).join(", ")}`);let e=Re(t),n=a(e),o=b(e);if(!existsSync(n))throw new Error(`codebase not initialized at ${e} \u2014 run \`easbot codebase init\` first`);let s=t.value;if(to(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=existsSync(o)?Ce(o):{},c=i[t.key];return i[t.key]=s,existsSync(n)||mkdirSync(n,{recursive:true}),oo(o,i),{rootDir:e,configPath:o,key:t.key,oldValue:c,newValue:s,requiresRestart:no.has(t.key)}}function Ne(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 Pe(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 Te(t){let e=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??"."),n=a(e),o=c$1(e);if(existsSync(n)||await R({dir:e}),!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-WOYUSWKD.mjs'),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,f=r.getIndexState(),h=r.getMeta("schema_version"),S=h?parseInt(h,10):0,a={rootDir:e,dbPath:o,wasStale:c,previousVersion:y??null,currentVersion:m$1,applied:!1,schemaMigrated:!1,previousSchemaVersion:S,currentSchemaVersion:S,dryRun:!!t.dryRun,schemaSteps:j$1.map(d=>({id:d.id,description:d.description,status:"pending"})),migrationErrors:[],indexState:f},N;if(t.backup!==!1&&!t.dryRun)try{let d=new Date().toISOString().replace(/[:.]/g,"-");N=join(n,`codebase.db.bak.${d}`),copyFileSync(o,N);for(let m of ["-wal","-shm"]){let u=o+m;existsSync(u)&&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=k(i,i$1,{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=l$1(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(m$1)),(f==="stale"||f==="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=${m$1}). 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 $e(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 je(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 ao=200;function lo(t,e=ao){return t?t.length<=e?t:t.slice(0,e)+"\u2026":""}async function Fe(t){let e=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??"."),n=a(e),o=c$1(e);if(!existsSync(n))throw new Error(`codebase not initialized at ${e} \u2014 run \`easbot codebase init\` first`);if(!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-N3PTDWLC.mjs'),{DEFAULT_EMBEDDING_CONFIG:c,DEFAULT_INDEXER_CONFIG:l$1,DEFAULT_PARSER_CONFIG:y}=await import('@easbot/types'),f={...c,modelId:r??"(dry-run)"},h=new i({workspaceDir:e,database:{path:o,walMode:true},embedding:f,indexer:l$1,parser:y,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});try{await h.initialize();let S=h.getDatabase(),a=S.getNodeCount(),N=S.queryAll("SELECT node_id FROM node_embeddings"),x=new Set(N.map(m=>m.node_id)),p;if(t.all)p=S.queryAll("SELECT id, name, ast_type, language, file_path, text FROM nodes");else if(x.size===0)p=S.queryAll("SELECT id, name, ast_type, language, file_path, text FROM nodes");else {let m=Array.from(x),u=m.map(()=>"?").join(",");p=S.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:lo(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 Ae(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 Me=Log.create({service:"codebase-watch"});function Le(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 Ue(t){let e=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??"."),n=a(e);existsSync(n)||await R({dir:e});let o=new a$1({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()}),Me.info("watch event",{event:r,relPath:i});}),await o.start();try{await d(n,process.pid);}catch(r){Me.warn("failed to write watcher pid",{error:String(r)});}return {watcher:o,events:s,startTime:Date.now()}}function We(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 Be(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 Ge(t){let e$1=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??"."),n=a(e$1);existsSync(n)||await R({dir:e$1});let o=join(n,".watcher.pid"),s=c(n);if(s===null)return {rootDir:e$1,pidFile:o,pid:null,stopped:false,error:"No watcher running (no .easbot/.watcher.pid found)"};try{return process.kill(s,"SIGTERM"),await e(n),{rootDir:e$1,pidFile:o,pid:s,stopped:!0}}catch(r){await e(n);let i=r instanceof Error?r.message:String(r);return {rootDir:e$1,pidFile:o,pid:s,stopped:false,error:i}}}function ze(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 Je(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 He(t){let e=isAbsolute(t.dir??"")&&t.dir?t.dir:join(l(),t.dir??"."),n=a(e),o=c$1(e);if(existsSync(n)||await R({dir:e}),!existsSync(o))throw new Error(`db not found at ${o} \u2014 run \`easbot codebase index\` first`);let{CodeBase:s}=await import('./code-base-N3PTDWLC.mjs'),{DEFAULT_EMBEDDING_CONFIG:r,DEFAULT_INDEXER_CONFIG:i,DEFAULT_PARSER_CONFIG:c,DEFAULT_SEARCH_CONFIG:l$1}=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$1,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}}),f=Date.now();try{await y.initialize();let S=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:S.length,results:S.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()-f}}finally{await y.close();}}function Qe(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 Ye(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.nodeId=n[0]),e}async function Ke(t){if(!t.name&&!t.nodeId)throw new Error("node command requires a <name> or <node-id> argument");let e=isAbsolute(t.dir??"")&&t.dir?t.dir:join(l(),t.dir??"."),n=a(e),o=c$1(e);if(existsSync(n)||await R({dir:e}),!existsSync(o))throw new Error(`db not found at ${o} \u2014 run \`easbot codebase index\` first`);let r=await e$1({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 Ze(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 tt(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 ot(t){let e=isAbsolute(t.dir??"")&&t.dir?t.dir:join(l(),t.dir??"."),n=a(e),o=c$1(e);if(existsSync(n)||await R({dir:e}),!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-N3PTDWLC.mjs'),{DEFAULT_EMBEDDING_CONFIG:l$1,DEFAULT_INDEXER_CONFIG:y,DEFAULT_PARSER_CONFIG:f,DEFAULT_SEARCH_CONFIG:h}=await import('@easbot/types'),S=new c({workspaceDir:e,database:{path:o,walMode:true},embedding:l$1,indexer:y,parser:f,search:h,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});try{await S.initialize();let a=S.getDatabase(),N=S.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 D=E.shift();if(D.depth>=s)continue;if(p.size>=r){m=!0;break}let T=N.queryNeighbors(D.nodeId,{direction:i,relationTypes:t.relationTypes,limit:r-p.size+1});for(let P of T.edges){d.push({source:P.source,target:P.target,relation:P.relation});let M=P.source===D.nodeId?P.target:P.source;if(!p.has(M)&&(p.set(M,D.depth+1),E.push({nodeId:M,depth:D.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(D=>[D.id,D])),I=[];for(let[D,T]of p.entries()){let P=C.get(D);P&&I.push({id:P.id,name:P.name,astType:P.ast_type,language:P.language,filePath:P.file_path,depth:T});}return {rootDir:e,rootNodeId:t.nodeId,depth:s,totalNodes:I.length,totalEdges:d.length,nodes:I,edges:d,truncated:m}}finally{await S.close();}}function nt(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 rt(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 it(t){let e=isAbsolute(t.dir??"")&&t.dir?t.dir:join(l(),t.dir??"."),n=a(e),o=c$1(e);if(existsSync(n)||await R({dir:e}),!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-N3PTDWLC.mjs'),{DEFAULT_EMBEDDING_CONFIG:c,DEFAULT_INDEXER_CONFIG:l$1,DEFAULT_PARSER_CONFIG:y,DEFAULT_SEARCH_CONFIG:f}=await import('@easbot/types'),h=new i({workspaceDir:e,database:{path:o,walMode:true},embedding:c,indexer:l$1,parser:y,search:f,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});try{await h.initialize();let S=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 I of C)!N.has(I.source)&&!m.has(I.source)&&(m.add(I.source),N.add(I.source),d.push(I.source));}if(d.length>0){let u=d.slice(0,10),b=u.length>0?a.queryNodes({ids:u}):[],C=new Map(b.map(D=>[D.id,D])),I=u.map(D=>{let T=C.get(D);return {id:D,name:T?.name??"(unknown)",filePath:T?.file_path??"(unknown)"}});x.push({depth:E,count:d.length,sample:I});}p=d;}return {rootDir:e,rootNodeId:t.nodeId,totalImpacted:N.size-1,depth:s,buckets:x}}finally{await h.close();}}function at(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 Oo="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",No=[new RegExp(`(?:^|/)(?:main|index|app|server)\\.(?:${Oo})$`)];function dt(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 ct(t){let e=isAbsolute(t.dir??"")&&t.dir?t.dir:join(l(),t.dir??"."),n=a(e),o=c$1(e);if(existsSync(n)||await R({dir:e}),!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-N3PTDWLC.mjs'),{DEFAULT_EMBEDDING_CONFIG:l$1,DEFAULT_INDEXER_CONFIG:y,DEFAULT_PARSER_CONFIG:f,DEFAULT_SEARCH_CONFIG:h}=await import('@easbot/types'),S=new c({workspaceDir:e,database:{path:o,walMode:true},embedding:l$1,indexer:y,parser:f,search:h,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});try{await S.initialize();let a=S.getDatabase(),N=S.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&&No.some(I=>I.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 S.close();}}function ut(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 ft(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 ko(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 f of y)n.has(f)?s.has(f)&&o.set(l,Math.min(o.get(l),n.get(f))):(c(f),o.set(l,Math.min(o.get(l),o.get(f))));if(o.get(l)===n.get(l)){let f=[],h;do h=r.pop(),s.delete(h),f.push(h);while(h!==l);f.length>1&&i.push(f);}}for(let l of t.keys())n.has(l)||c(l);return i}async function pt(t){let e=isAbsolute(t.dir??"")&&t.dir?t.dir:join(l(),t.dir??"."),n=a(e),o=c$1(e);if(existsSync(n)||await R({dir:e}),!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-N3PTDWLC.mjs'),{DEFAULT_EMBEDDING_CONFIG:i,DEFAULT_INDEXER_CONFIG:c,DEFAULT_PARSER_CONFIG:l$1,DEFAULT_SEARCH_CONFIG:y}=await import('@easbot/types'),f=new r({workspaceDir:e,database:{path:o,walMode:true},embedding:i,indexer:c,parser:l$1,search:y,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});try{await f.initialize();let h=f.getDatabase(),S=h.queryNodes({limit:1e5}),a=new Map;for(let b of S){let C=a.get(b.file_path)??[];C.push(b.id),a.set(b.file_path,C);}let N=S.map(b=>b.id),x=new Map;for(let b of S)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),I=x.get(b.target);if(!C||!I||C===I)continue;let D=E.get(C);D||(D=new Set,E.set(C,D)),D.add(I);}let d=new Map;for(let[b,C]of E.entries())d.set(b,Array.from(C));let u=ko(d).map(b=>{let C=[];for(let I=0;I<b.length;I++){let D=b[I],T=E.get(D);if(T)for(let P of T)b.includes(P)&&C.push({source:D,target:P});}return {cycle:b,edges:C}});return {rootDir:e,relation:s,totalCycles:u.length,cycles:u.slice(0,50)}}finally{await f.close();}}function mt(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 bt(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 yt(t){let e=isAbsolute(t.dir??"")&&t.dir?t.dir:join(l(),t.dir??"."),n=a(e),o=c$1(e);if(existsSync(n)||await R({dir:e}),!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-N3PTDWLC.mjs'),{DEFAULT_EMBEDDING_CONFIG:c,DEFAULT_INDEXER_CONFIG:l$1,DEFAULT_PARSER_CONFIG:y,DEFAULT_SEARCH_CONFIG:f}=await import('@easbot/types'),h=new i({workspaceDir:e,database:{path:o,walMode:true},embedding:c,indexer:l$1,parser:y,search:f,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});try{await h.initialize();let S=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 I=S.queryNeighbors(C,{direction:"both",relationTypes:r,limit:1e3});for(let D of I.edges){let T=D.source===C?D.target:D.source;if(!a.has(T)){if(a.add(T),N.set(T,{via:C,relation:D.relation}),T===t.toId){p=!0;break e}b.push(T);}}}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 xt(t){let e=[];if(!t.found)return e.push("Codebase path: NOT FOUND within depth limit"),e.join(`
19
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 Et(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 Ct(t){let e=isAbsolute(t.dir??"")&&t.dir?t.dir:join(l(),t.dir??"."),n=a(e),o=c$1(e);if(existsSync(n)||await D({dir:e}),!existsSync(o))throw new Error(`db not found at ${o} \u2014 run \`easbot codebase index\` first`);let{CodeBase:s}=await import('./code-base-XJXVJ35Z.mjs'),{DEFAULT_EMBEDDING_CONFIG:r,DEFAULT_INDEXER_CONFIG:i,DEFAULT_PARSER_CONFIG:c,DEFAULT_SEARCH_CONFIG:l$1}=await import('@easbot/types'),{CodebaseStdioServer:y}=await import('./stdio-server-3HFZJ5G2.mjs'),g="0.0.0";try{let x=dirname(fileURLToPath(import.meta.url));for(let p=0;p<8;p++){try{let d=JSON.parse(readFileSync(join(x,"package.json"),"utf-8"));if(d?.name==="@easbot/codebase"&&typeof d.version=="string"){g=d.version;break}}catch{}let E=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$1,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:ServerTransportType.STDIO},a$1=await y.start(h,w);return {rootDir:e,tools:a$1.tools}}var Lo=Log.create({service:"codebase-cmd-callers"});function Dt(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 Rt(t){if(!t.symbol&&!t.nodeId)throw new Error("callers command requires a <symbol> or --nodeId argument");let e=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??"."),n=Date.now(),s=await h({workspaceDir:e,rootDir:e},{name:t.symbol,nodeId:t.nodeId,file:t.file,kind:t.kind,maxResults:t.maxResults});return Lo.debug("callers command done",{symbol:t.symbol,count:s.callers.length,rootDir:e}),{rootDir:e,serviceResult:s,durationMs:Date.now()-n}}function It(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 Go=Log.create({service:"codebase-cmd-callees"});function Nt(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 Ot(t){if(!t.symbol&&!t.nodeId)throw new Error("callees command requires a <symbol> or --nodeId argument");let e=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??"."),n=Date.now(),s=await i({workspaceDir:e,rootDir:e},{name:t.symbol,nodeId:t.nodeId,file:t.file,kind:t.kind,maxResults:t.maxResults});return Go.debug("callees command done",{symbol:t.symbol,count:s.callers.length,rootDir:e}),{rootDir:e,serviceResult:s,durationMs:Date.now()-n}}function vt(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 Jo=Log.create({service:"codebase-cmd-explore"});function kt(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 Pt(t){if(!t.query)throw new Error("explore command requires a <query> argument");let e=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??"."),n=Date.now(),s=await 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 Jo.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 Tt(t){let e={pendingFiles:[],toolName:"codebase_explore",writeToDisk:false};return await D$1(t.serviceResult,e)}var $t=Log.create({service:"codebase-cli"}),jt=`
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
20
+ `)}function Ct(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 Rt(t){let e=isAbsolute(t.dir??"")&&t.dir?t.dir:join(l(),t.dir??"."),n=a(e),o=c$1(e);if(existsSync(n)||await R({dir:e}),!existsSync(o))throw new Error(`db not found at ${o} \u2014 run \`easbot codebase index\` first`);let{CodeBase:s}=await import('./code-base-N3PTDWLC.mjs'),{DEFAULT_EMBEDDING_CONFIG:r,DEFAULT_INDEXER_CONFIG:i,DEFAULT_PARSER_CONFIG:c,DEFAULT_SEARCH_CONFIG:l$1}=await import('@easbot/types'),{CodebaseStdioServer:y}=await import('./stdio-server-DIGUR2PS.mjs'),f="0.0.0";try{let x=dirname(fileURLToPath(import.meta.url));for(let p=0;p<8;p++){try{let d=JSON.parse(readFileSync(join(x,"package.json"),"utf-8"));if(d?.name==="@easbot/codebase"&&typeof d.version=="string"){f=d.version;break}}catch{}let E=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$1,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});await h.initialize();let S={id:"easbot-codebase-mcp",name:"EASBot Codebase MCP",version:f,transportType:ServerTransportType.STDIO},a$1=await y.start(h,S);return {rootDir:e,tools:a$1.tools}}var Uo=Log.create({service:"codebase-cmd-callers"});function Dt(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 Ot(t){if(!t.symbol&&!t.nodeId)throw new Error("callers command requires a <symbol> or --nodeId argument");let e=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??"."),n=Date.now(),s=await h({workspaceDir:e,rootDir:e},{name:t.symbol,nodeId:t.nodeId,file:t.file,kind:t.kind,maxResults:t.maxResults});return Uo.debug("callers command done",{symbol:t.symbol,count:s.callers.length,rootDir:e}),{rootDir:e,serviceResult:s,durationMs:Date.now()-n}}function Nt(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 Go=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 vt(t){if(!t.symbol&&!t.nodeId)throw new Error("callees command requires a <symbol> or --nodeId argument");let e=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??"."),n=Date.now(),s=await i({workspaceDir:e,rootDir:e},{name:t.symbol,nodeId:t.nodeId,file:t.file,kind:t.kind,maxResults:t.maxResults});return Go.debug("callees command done",{symbol:t.symbol,count:s.callers.length,rootDir:e}),{rootDir:e,serviceResult:s,durationMs:Date.now()-n}}function kt(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 Ho=Log.create({service:"codebase-cmd-explore"});function Pt(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 Tt(t){if(!t.query)throw new Error("explore command requires a <query> argument");let e=t.dir&&isAbsolute(t.dir)?t.dir:join(l(),t.dir??"."),n=Date.now(),s=await 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 Ho.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 $t(t){let e={pendingFiles:[],toolName:"codebase_explore",writeToDisk:false};return await D(t.serviceResult,e)}var _t=Log.create({service:"codebase-cli"}),Ft=`
23
+ \x1B[1m@easbot/codebase\x1B[0m \u2014 Code Knowledge Graph for EASBot
26
24
 
27
25
  Usage: easbot codebase <command> [options]
28
26
 
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
27
+ Commands (lifecycle):
28
+ init [dir] Initialize .easbot/codebase.json in the target directory
29
+ index [dir] Build the full index
30
+ sync Run incremental sync
31
+ recreate Discard the entire db and re-init
32
+ clear Clear all nodes/edges (keep config.json)
33
+ status Show index state / db / config
34
+ doctor Run health checks (backend availability, etc.)
35
+ config Get/set .easbot/codebase.json fields
36
+ upgrade Update extraction_version metadata when stale
37
+ embed Generate node embeddings
38
+ watch Watch workspace for file changes (auto-sync)
39
+ stop Stop a running file watcher
40
+
41
+ Commands (graph query):
42
+ query <q...> Hybrid search (FTS + vector + basic)
43
+ node <name|id> Show details for a single node
44
+ context <id> Build sub-graph context around a node
45
+ impact <id> Blast radius (BFS incoming edges)
46
+ callers <sym> Flat list of who calls <symbol>
47
+ callees <sym> Flat list of what <symbol> calls
48
+ explore <q> PRIMARY tool \u2014 source code + caller/callee trail in one call
49
+ dead-code Find unused symbols
50
+ circular Detect circular dependencies
51
+ path <from> <to> Find shortest path between two nodes
52
+
53
+ External:
54
+ mcp [dir] Start stdio MCP server (exposes 9 codebase tools)
40
55
 
41
56
  Run \x1B[1measbot codebase <command> --help\x1B[0m for details.
42
- `;function Ho(){console.log(jt);}function Ai(){console.log(jt),console.log(""),console.log("Available commands:");for(let t of Xo)console.log(` ${t.name.padEnd(14)} ${t.description}`);console.log(""),console.log("Run `easbot codebase <command> --help` for command-specific options.");}var Xo=[{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 Yo(){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 Mi(t,e){if(Yo(),t.length===0)return Ho(),{code:0,handled:false};let n$1=t[0],o$1=t.slice(1);try{switch(n$1){case "init":{let s=ne(o$1);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$1};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$1}):(console.log(`\u2713 codebase initialized at ${r.configPath}`),{code:0,handled:!0,command:n$1})}case "status":{let s=Ko(o$1),r=await F(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(re(r)),{code:0,handled:!0,command:n$1}}case "doctor":{let s=Zo(o$1),r=await ie(s);return console.log(ae(r)),{code:r.healthy?0:1,handled:!0,command:n$1}}case "index":{let s=le(o$1);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$1};let r=await de(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(ce(r)),{code:r.success?0:1,handled:!0,command:n$1}}case "sync":{let s=m(o$1);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$1};let r=await n(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(o(r)),{code:r.success?0:1,handled:!0,command:n$1}}case "recreate":{let s=ge(o$1);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$1};let r=await pe(s);return console.log(me(r)),{code:0,handled:!0,command:n$1}}case "clear":{let s=he(o$1);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$1};let r=await be(s);return console.log(ye(r)),{code:0,handled:!0,command:n$1}}case "config":{let s=we(o$1);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$1};if(!s.subcommand)return console.error("config requires a subcommand: get | set"),{code:1,handled:!0,command:n$1};if(s.subcommand==="get"){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$1}}if(s.subcommand==="set"){let r=await Re(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(Ne(r)),{code:0,handled:!0,command:n$1}}return console.error(`Unknown config subcommand: ${s.subcommand}`),{code:1,handled:!0,command:n$1}}case "upgrade":{let s=ke(o$1);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$1};let r=await Pe(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(Te(r)),{code:0,handled:!0,command:n$1}}case "embed":{let s=_e(o$1);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$1};let r=await je(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(Fe(r)),{code:0,handled:!0,command:n$1}}case "query":{let s=Ve(o$1);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$1};let r=await Je(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(Qe(r)),{code:0,handled:!0,command:n$1}}case "node":{let s=Xe(o$1);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$1};let r=await Ye(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(Ke(r)),{code:r.found?0:1,handled:!0,command:n$1}}case "context":{let s=et(o$1);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$1};let r=await tt(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(ot(r)),{code:0,handled:!0,command:n$1}}case "impact":{let s=st(o$1);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$1};let r=await rt(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(it(r)),{code:0,handled:!0,command:n$1}}case "callers":{let s=Dt(o$1);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$1};let r=await Rt(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(It(r)),{code:0,handled:!0,command:n$1}}case "callees":{let s=Nt(o$1);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$1};let r=await Ot(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(vt(r)),{code:0,handled:!0,command:n$1}}case "explore":{let s=kt(o$1);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$1};let r=await Pt(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(await Tt(r)),{code:0,handled:!0,command:n$1}}case "dead-code":{let s=lt(o$1);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$1};let r=await dt(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(ct(r)),{code:0,handled:!0,command:n$1}}case "circular":{let s=ft(o$1);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$1};let r=await gt(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(pt(r)),{code:0,handled:!0,command:n$1}}case "path":{let s=ht(o$1);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$1};let r=await bt(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(yt(r)),{code:r.found?0:1,handled:!0,command:n$1}}case "mcp":{let s=Et(o$1);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$1}):(await Ct(s),{code:0,handled:!0,command:n$1})}case "watch":{let s=Me(o$1);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$1};let r=await Le(s);return console.log(We(r.events)),await new Promise(i=>{let c=()=>{$t.info("watcher received signal, stopping"),i();};process.once("SIGINT",c),process.once("SIGTERM",c);}),r.watcher.dispose(),{code:0,handled:!0,command:n$1}}case "stop":{let s=qe(o$1);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$1};let r=await Ge(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(Be(r)),{code:r.stopped?0:1,handled:!0,command:n$1}}default:return console.error(`Unknown command: ${n$1}`),console.error("Run \x1B[1measbot codebase --help\x1B[0m for available commands."),{code:1,handled:!0,command:n$1}}}catch(s){let r=s instanceof Error?s.message:String(s);return console.error(`codebase ${n$1} failed: ${r}`),$t.error("codebase CLI error",{command:n$1,error:r,stack:s instanceof Error?s.stack:void 0}),{code:1,handled:true,command:n$1}}}function Ko(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 Zo(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}export{Ho as a,Ai as b,Mi as c};
57
+ `;function Xo(){console.log(Ft);}function Mi(){console.log(Ft);}var jt=false;function Yo(){if(jt)return;jt=true;let t=false,e=n=>{t||(t=true,console.error(`
58
+ [codebase] received ${n}, cleaning up...`),setTimeout(()=>process.exit(130),200));};process.on("SIGINT",e),process.on("SIGTERM",e);}async function Li(t,e){if(Yo(),t.length===0)return Xo(),{code:0,handled:false};let n$1=t[0],o$1=t.slice(1);try{switch(n$1){case "init":{let s=se(o$1);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$1};let r=await R({...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$1}):(console.log(`\u2713 codebase initialized at ${r.configPath}`),{code:0,handled:!0,command:n$1})}case "status":{let s=Ko(o$1),r=await F(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(ie(r)),{code:0,handled:!0,command:n$1}}case "doctor":{let s=Zo(o$1),r=await ae(s);return console.log(le(r)),{code:r.healthy?0:1,handled:!0,command:n$1}}case "index":{let s=de(o$1);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$1};let r=await ce(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(ue(r)),{code:r.success?0:1,handled:!0,command:n$1}}case "sync":{let s=m(o$1);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$1};let r=await n(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(o(r)),{code:r.success?0:1,handled:!0,command:n$1}}case "recreate":{let s=pe(o$1);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$1};let r=await me(s);return console.log(he(r)),{code:0,handled:!0,command:n$1}}case "clear":{let s=be(o$1);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$1};let r=await ye(s);return console.log(xe(r)),{code:0,handled:!0,command:n$1}}case "config":{let s=Ee(o$1);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$1};if(!s.subcommand)return console.error("config requires a subcommand: get | set"),{code:1,handled:!0,command:n$1};if(s.subcommand==="get"){let r=await De(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(Ne(r)),{code:0,handled:!0,command:n$1}}if(s.subcommand==="set"){let r=await Oe(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(Ie(r)),{code:0,handled:!0,command:n$1}}return console.error(`Unknown config subcommand: ${s.subcommand}`),{code:1,handled:!0,command:n$1}}case "upgrade":{let s=Pe(o$1);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$1};let r=await Te(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log($e(r)),{code:0,handled:!0,command:n$1}}case "embed":{let s=je(o$1);if(s.help)return console.log("Usage: easbot codebase embed [--all] [--dry-run|-n] [--pending-list|-p] [--batch=N] [--json] [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(" --dry-run, -n Print statistics only (default behavior in CLI)"),console.log(" --pending-list, -p List node ids that are pending embedding"),console.log(" --batch=N Embedding batch size (default 10)"),console.log(" --json Output as JSON"),console.log(""),console.log("Environment:"),console.log(" EASBOT_EMBEDDING_MODEL e.g. openai/text-embedding-3-small"),{code:0,handled:!0,command:n$1};let r=await Fe(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(Ae(r)),{code:0,handled:!0,command:n$1}}case "query":{let s=Je(o$1);if(s.help)return console.log("Usage: easbot codebase query <q...> [--language=<lang>] [--ast=<type>] [--max=N] [--no-edges] [--no-vector|--no-embed] [--json] [--dir=<worktree>]"),console.log(""),console.log("Hybrid search (FTS + vector + basic) over indexed code nodes."),console.log("Aliases: search"),console.log(""),console.log("Options:"),console.log(" --language=<lang> Filter by language (ts / js / py / go / ...)"),console.log(" --ast=<type> Filter by AST type (class_declaration / function_declaration / ...)"),console.log(" --max=<N> Max results (default 20)"),console.log(" --no-edges Do not include edges in results (default: include)"),console.log(" --no-vector / --no-embed Disable vector search (FTS + basic only, default: vector on)"),console.log(" --json JSON output"),console.log(" --dir=<worktree> Target worktree (default: cwd)"),{code:0,handled:!0,command:n$1};let r=await He(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(Qe(r)),{code:0,handled:!0,command:n$1}}case "node":{let s=Ye(o$1);if(s.help)return console.log("Usage: easbot codebase node <name|id> [--file=<path>] [--kind=<kind>] [--edges] [--max=N] [--json] [--dir=<worktree>]"),console.log(""),console.log("Show details for a single node."),console.log("Accepts a symbol <name> (LLM workflow friendly, tool/MCP-aligned)"),console.log("or a raw <node-id> from `query` / database."),console.log(""),console.log("Options:"),console.log(" --file=<path> Disambiguate when same-named symbols exist"),console.log(" --kind=<kind> Filter / disambiguate by AST kind"),console.log(" --edges Include incoming / outgoing edge summaries"),console.log(" --max=<N> Edge limit (default 50)"),console.log(" --json Output as JSON"),console.log(" --dir=<worktree> Target worktree (default: cwd)"),{code:0,handled:!0,command:n$1};let r=await Ke(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(Ze(r)),{code:r.found?0:1,handled:!0,command:n$1}}case "context":{let s=tt(o$1);if(s.help)return console.log("Usage: easbot codebase context <id> [--depth=N] [--max=N] [--direction=<incoming|outgoing|both>] [--relation=<r1,r2,...>] [--json] [--dir=<worktree>]"),console.log(""),console.log("Build a sub-graph context around a node (BFS to N-level neighbors)."),console.log(""),console.log("Options:"),console.log(" --depth=<N> BFS depth (default 2)"),console.log(" --max=<N> Max nodes (default 100)"),console.log(" --direction=<dir> incoming | outgoing | both (default both)"),console.log(" --relation=<r1,r2,...> Filter by relation types (CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS / USES / REFERENCES)"),console.log(" --json Output as JSON"),console.log(" --dir=<worktree> Target worktree (default: cwd)"),{code:0,handled:!0,command:n$1};let r=await ot(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(nt(r)),{code:0,handled:!0,command:n$1}}case "impact":{let s=rt(o$1);if(s.help)return console.log("Usage: easbot codebase impact <id> [-d=N | --depth=N] [--relation=<r1,r2,...>] [--json] [--dir=<worktree>]"),console.log(""),console.log("Blast radius: BFS incoming CALLS / REFERENCES / USES / IMPORTS / TYPE_REFERENCES, bucketed by depth."),console.log(""),console.log("Options:"),console.log(" --depth=<N> BFS depth (default 3)"),console.log(" --relation=<r1,r2,...> Filter by relation types"),console.log(" --json Output as JSON"),console.log(" --dir=<worktree> Target worktree (default: cwd)"),{code:0,handled:!0,command:n$1};let r=await it(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(at(r)),{code:0,handled:!0,command:n$1}}case "callers":{let s=Dt(o$1);if(s.help)return console.log("Usage: easbot codebase callers <symbol> [--node-id=<id>] [--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("Accepts <symbol> name (LLM-friendly) OR --node-id for raw node id."),console.log(""),console.log("Options:"),console.log(" --node-id=<id> Raw node id from `query` / database"),console.log(" --file=<path> File path or basename to disambiguate when same-named symbols exist"),console.log(" --kind=<kind> Filter by node kind (class_declaration / function_declaration / ...)"),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$1};let r=await Ot(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(Nt(r)),{code:0,handled:!0,command:n$1}}case "callees":{let s=It(o$1);if(s.help)return console.log("Usage: easbot codebase callees <symbol> [--node-id=<id>] [--file=<path>] [--kind=<kind>] [--max=N] [--json] [--dir=<worktree>]"),console.log(""),console.log("Flat list of what <symbol> calls (outgoing edges)."),console.log("Accepts <symbol> name (LLM-friendly) OR --node-id for raw node id."),console.log(""),console.log("Options:"),console.log(" --node-id=<id> Raw node id from `query` / database"),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$1};let r=await vt(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(kt(r)),{code:0,handled:!0,command:n$1}}case "explore":{let s=Pt(o$1);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, default: include)"),console.log(" --intent=<ctx> LLM context string for ranking"),console.log(" --json Output as JSON"),console.log(" --dir=<worktree> Target worktree (default: cwd)"),{code:0,handled:!0,command:n$1};let r=await Tt(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(await $t(r)),{code:0,handled:!0,command:n$1}}case "dead-code":{let s=dt(o$1);if(s.help)return console.log("Usage: easbot codebase dead-code [--type=<t1,t2,...>] [--no-exclude-entry] [--limit=N] [--json] [--dir=<worktree>]"),console.log(""),console.log("Find nodes with no incoming edges (heuristic dead code)."),console.log(""),console.log("Options:"),console.log(" --type=<t1,t2,...> Only consider these AST types"),console.log(" --no-exclude-entry Include entry-point files (default: exclude)"),console.log(" --limit=<N> Max results (default 100)"),console.log(" --json Output as JSON"),console.log(" --dir=<worktree> Target worktree (default: cwd)"),{code:0,handled:!0,command:n$1};let r=await ct(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(ut(r)),{code:0,handled:!0,command:n$1}}case "circular":{let s=ft(o$1);if(s.help)return console.log("Usage: easbot codebase circular [--relation=<r>] [--scope=<file|module>] [--json] [--dir=<worktree>]"),console.log(""),console.log("Detect circular dependencies via Tarjan SCC."),console.log(""),console.log("Options:"),console.log(" --relation=<r> Relation type to follow (default IMPORTS)"),console.log(" --scope=<scope> file | module (default file)"),console.log(" --json Output as JSON"),console.log(" --dir=<worktree> Target worktree (default: cwd)"),{code:0,handled:!0,command:n$1};let r=await pt(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(mt(r)),{code:0,handled:!0,command:n$1}}case "path":{let s=bt(o$1);if(s.help)return console.log("Usage: easbot codebase path <from> <to> [-d=N | --depth=N] [--relation=<r1,r2,...>] [--json] [--dir=<worktree>]"),console.log(""),console.log("Find shortest path between two nodes (BFS along CALLS / IMPORTS / TYPE_REFERENCES / USES / REFERENCES)."),console.log(""),console.log("Options:"),console.log(" --depth=<N> BFS depth limit (default 6)"),console.log(" --relation=<r1,r2,...> Filter by relation types"),console.log(" --json Output as JSON"),console.log(" --dir=<worktree> Target worktree (default: cwd)"),{code:0,handled:!0,command:n$1};let r=await yt(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(xt(r)),{code:r.found?0:1,handled:!0,command:n$1}}case "mcp":{let s=Ct(o$1);return s.help?(console.log("Usage: easbot codebase mcp [dir]"),console.log(""),console.log("Start a stdio MCP server exposing 9 codebase tools:"),console.log(" query / node / context / impact"),console.log(" callers / callees / explore"),console.log(" status / doctor"),console.log(""),console.log("Connect from MCP clients via stdio JSON-RPC."),{code:0,handled:!0,command:n$1}):(await Rt(s),{code:0,handled:!0,command:n$1})}case "watch":{let s=Le(o$1);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$1};let r=await Ue(s);return console.log(We(r.events)),await new Promise(i=>{let c=()=>{_t.info("watcher received signal, stopping"),i();};process.once("SIGINT",c),process.once("SIGTERM",c);}),r.watcher.dispose(),{code:0,handled:!0,command:n$1}}case "stop":{let s=Be(o$1);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$1};let r=await Ge(s);return s.json?console.log(JSON.stringify(r,null,2)):console.log(ze(r)),{code:r.stopped?0:1,handled:!0,command:n$1}}default:return console.error(`Unknown command: ${n$1}`),console.error("Run \x1B[1measbot codebase --help\x1B[0m for available commands."),{code:1,handled:!0,command:n$1}}}catch(s){let r=s instanceof Error?s.message:String(s);return console.error(`codebase ${n$1} failed: ${r}`),_t.error("codebase CLI error",{command:n$1,error:r,stack:s instanceof Error?s.stack:void 0}),{code:1,handled:true,command:n$1}}}function Ko(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 Zo(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}export{Xo as a,Mi as b,Li as c};