@easbot/codebase 0.3.0 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -0
- package/dist/chunks/chunk-7XCIIOM6.cjs +1 -0
- package/dist/chunks/chunk-ABKFCPSL.cjs +234 -0
- package/dist/chunks/chunk-B35QBUQP.cjs +34 -0
- package/dist/chunks/chunk-BL4XMOO2.cjs +43 -0
- package/dist/chunks/chunk-EVDJNYI2.cjs +1 -0
- package/dist/chunks/chunk-G3IYU6TZ.mjs +1 -0
- package/dist/chunks/chunk-LBEWQNER.mjs +234 -0
- package/dist/chunks/chunk-O3Z5ORQ3.mjs +43 -0
- package/dist/chunks/chunk-PSPE6FME.mjs +34 -0
- package/dist/chunks/chunk-RLZHDTHY.cjs +154 -0
- package/dist/chunks/chunk-SV4WN2DV.mjs +2 -0
- package/dist/chunks/chunk-TS4OAYIJ.cjs +1 -0
- package/dist/chunks/chunk-UEILXBZB.mjs +1 -0
- package/dist/chunks/chunk-UTKA3WG3.mjs +1 -0
- package/dist/chunks/chunk-YOFBT3V6.cjs +2 -0
- package/dist/chunks/chunk-Z4Y3VCYS.mjs +154 -0
- package/dist/chunks/code-base-ONPUU5A3.cjs +1 -0
- package/dist/chunks/code-base-XJXVJ35Z.mjs +1 -0
- package/dist/chunks/database-manager-DRLNOQ6C.cjs +1 -0
- package/dist/chunks/database-manager-WOYUSWKD.mjs +1 -0
- package/dist/chunks/file-watcher-5WEDJY6M.mjs +1 -0
- package/dist/chunks/file-watcher-LZZUEGMY.cjs +1 -0
- package/dist/chunks/stdio-server-3DPRM3WQ.cjs +47 -0
- package/dist/chunks/stdio-server-3HFZJ5G2.mjs +47 -0
- package/dist/chunks/sync-D5GNVNM2.mjs +1 -0
- package/dist/chunks/sync-IYOM3Y62.cjs +1 -0
- package/dist/cli.cjs +3 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.mjs +3 -0
- package/dist/index.cjs +1 -108
- package/dist/index.d.cts +494 -21
- package/dist/index.d.ts +494 -21
- package/dist/index.mjs +1 -108
- package/package.json +13 -6
|
@@ -0,0 +1,43 @@
|
|
|
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)&©FileSync(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(`
|
|
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
|
|
26
|
+
|
|
27
|
+
Usage: easbot codebase <command> [options]
|
|
28
|
+
|
|
29
|
+
Commands:
|
|
30
|
+
init [dir] Initialize .easbot/codebase.json in the target directory
|
|
31
|
+
status Show index state / db / config
|
|
32
|
+
doctor Run health checks (backend availability, etc.)
|
|
33
|
+
index [dir] Build the full index
|
|
34
|
+
sync Run incremental sync
|
|
35
|
+
recreate Discard the entire db and re-init
|
|
36
|
+
clear Clear all nodes/edges (keep config.json)
|
|
37
|
+
config Get/set .easbot/codebase.json fields
|
|
38
|
+
upgrade Update extraction_version metadata when stale
|
|
39
|
+
embed Generate node embeddings
|
|
40
|
+
|
|
41
|
+
Run \x1B[1measbot codebase <command> --help\x1B[0m for details.
|
|
42
|
+
`;function 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};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import {n,k as k$1}from'./chunk-LBEWQNER.mjs';import {c}from'./chunk-UTKA3WG3.mjs';import {a}from'./chunk-G3IYU6TZ.mjs';import {Log,Filesystem,TruncateContent}from'@easbot/utils';import {DEFAULT_SEARCH_CONFIG,DEFAULT_PARSER_CONFIG,DEFAULT_INDEXER_CONFIG,DEFAULT_EMBEDDING_CONFIG}from'@easbot/types';var R=class extends Error{constructor(n,l,a$1){super(n);a(this,"code",l);a(this,"details",a$1);this.name="ServiceError";}},P=class extends R{constructor(t,n=[]){super(`Node not found: ${t}`,"NOT_FOUND",{name:t,candidates:n});}},F=class extends R{constructor(t,n){super(`Ambiguous name "${t}" \u2014 ${n.length} candidates`,"AMBIGUOUS",{name:t,candidates:n});}};Log.create({service:"codebase-service"});var N=Filesystem.toUnixPath;async function D(e,t,n){if(n.nodeId){let o=e.getNode(n.nodeId);if(!o)throw new P(`nodeId=${n.nodeId}`);return {node:o,candidates:[]}}if(!n.name)throw new R("Either name or nodeId is required","NOT_FOUND",n);let a=e.queryNodes({limit:5e3});if(n.file){let o=N(n.file),r=a.filter(c=>N(c.file_path).endsWith(o)||N(c.file_path).includes(o));r.length>0&&(a=r);}if(n.kind){let o=n.kind.toLowerCase(),r=a.filter(c=>c.ast_type.includes(o)||c.name.toLowerCase().includes(o));r.length>0&&(a=r);}let i=a.find(o=>o.name===n.name||o.id.split(":").pop()===n.name);if(i)return {node:i,candidates:[]};let d=k$1(n.name,a,{limit:10,minScore:.5});if(d.length===0)throw new P(n.name);if(d.length===1){let o=e.getNode(d[0].nodeId);if(!o)throw new P(n.name);return {node:o,candidates:d.map(r=>({node:o,score:r.score}))}}let s=[];for(let o of d){let r=e.getNode(o.nodeId);r&&s.push({node:r,score:o.score});}throw s.length===0?new P(n.name):new F(n.name,s)}async function C(e){let t=c(e.rootDir),n$1=new n({workspaceDir:e.workspaceDir,database:{path:t,walMode:true},embedding:DEFAULT_EMBEDDING_CONFIG,indexer:DEFAULT_INDEXER_CONFIG,parser:DEFAULT_PARSER_CONFIG,search:DEFAULT_SEARCH_CONFIG,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});return await n$1.initialize(),n$1}function ue(e,t,n,l){let a=l==="in"?e.source:e.target,i=n.getNodeById(a);return i?{id:i.id,name:i.name,astType:i.ast_type,filePath:N(i.file_path),startLine:i.start_line??0,relation:e.relation}:null}async function J(e,t){let n=Date.now(),d=await(await C(e)).getQuery().search(t.query??"",{maxResults:t.maxResults??10,language:t.language,filePath:t.file,astType:t.astType,includeEdges:true,enableFts:t.enableFts!==false,enableEmbedding:t.enableEmbedding!==false});if(t.kind){let o=t.kind.toLowerCase();d=d.filter(r=>r.ast_type.includes(o)||r.name.toLowerCase().includes(o));}if(t.file){let o=N(t.file);d=d.filter(r=>N(r.file_path).endsWith(o)||N(r.file_path).includes(o));}let s=d.map(o=>({node:o,edges:o.edges??[],source:"basic",score:0,snippet:(o.text??"").slice(0,200).replace(/\s+/g," ").trim()}));return {total:s.length,hits:s,durationMs:Date.now()-n,truncated:false}}async function pe(e,t){let n=await C(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await D(l,e,t),d=[];if(t.includeEdges){let s=t.edgesLimit??50;d=a.queryEdges({sourceOrTarget:[i.id],limit:s});}return {node:i,edges:d}}var me=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"];async function ge(e,t){let n=await C(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await D(l,e,t);if(!i)return {root:null,nodes:[],edges:[],truncated:false,totalNodes:0,totalEdges:0};let d=t.depth??2,s=t.maxNodes??100,o=t.direction??"both",r=new Map,c=[{nodeId:i.id,depth:0}];r.set(i.id,0);let p=[],u=false;for(;c.length>0;){let g=c.shift();if(g.depth>=d)continue;if(r.size>=s){u=true;break}let f=l.queryNeighbors(g.nodeId,{direction:o,relationTypes:t.relationTypes??me,limit:s-r.size+1});for(let h of f.edges){p.push(h);let I=h.source===g.nodeId?h.target:h.source;if(!r.has(I)&&(r.set(I,g.depth+1),c.push({nodeId:I,depth:g.depth+1}),r.size>=s)){u=true;break}}if(u)break}let m=Array.from(r.keys()),y=m.length>0?a.queryNodes({ids:m}):[],E=new Map(y.map(g=>[g.id,g])),b=[];for(let[g,f]of r.entries()){let h=E.get(g);h&&b.push({node:h,depth:f});}return {root:i,nodes:b,edges:p,truncated:u,totalNodes:b.length,totalEdges:p.length}}var fe=["CALLS","IMPORTS","TYPE_REFERENCES"];async function he(e,t){let n=await C(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await D(l,e,t);if(!i)return {root:null,totalImpacted:0,buckets:[]};let d=t.depth??2,s=t.maxResults??50,o=t.relationTypes??fe,r=new Set([i.id]),c=[],p=[i.id];for(let u=1;u<=d&&!(p.length===0||r.size-1>=s);u++){let m=p.map(()=>"?").join(","),y=o.map(()=>"?").join(","),E=a.queryAll(`SELECT source, target, relation FROM edges WHERE target IN (${m}) AND relation IN (${y})`,[...p,...o]),b=[],g=new Set;for(let f of E)if(!r.has(f.source)&&!g.has(f.source)&&(g.add(f.source),r.add(f.source),b.push(f.source),r.size-1>=s))break;if(b.length>0){let f=b.slice(0,10),h=a.queryNodes({ids:f}),I=new Map(h.map(L=>[L.id,L])),oe=f.map(L=>{let U=I.get(L);return {id:L,name:U?.name??"(unknown)",filePath:U?N(U.file_path):"(unknown)",relation:"CALLS"}});c.push({depth:u,count:b.length,sample:oe});}p=b;}return {root:i,totalImpacted:r.size-1,buckets:c}}var ye=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","METHOD_OVERRIDES"];async function be(e,t){return k(e,t,"incoming")}async function Ee(e,t){return k(e,t,"outgoing")}async function k(e,t,n,l){let a=await C(e),i=a.getQuery(),d=a.getDatabase(),{node:s}=await D(i,e,t);if(!s)return {root:null,callers:[],truncated:false};let o=t.maxResults??20,r=t.relationTypes??ye,c=i.queryNeighbors(s.id,{direction:n,relationTypes:r,limit:o+1}),p=[];for(let m of c.edges){let y=ue(m,s.id,d,n==="incoming"?"in":"out");y&&p.push(y);}let u=p.length>o;return {root:s,callers:u?p.slice(0,o):p,truncated:u}}async function xe(e,t){if(!t.query)throw new R("explore requires a non-empty query","NOT_FOUND",{query:t.query});let l=await C(e);l.getQuery();l.getDatabase();let s=(await J(e,{query:t.query,file:t.file,kind:t.kind,intent:t.intent,maxResults:t.maxFiles??5,enableFts:true,enableEmbedding:true})).hits,o=new Map;for(let p of s){let u=N(p.node.file_path),m=o.get(u);m?m.push(p):o.set(u,[p]);}let r=t.maxSymbols??3,c=[];for(let[p,u]of o){let m=u.slice(0,r),y=[];for(let E of m){let b=await k(e,{name:E.node.name,file:p,kind:t.kind,maxResults:5},"incoming"),g=await k(e,{name:E.node.name,file:p,kind:t.kind,maxResults:5},"outgoing");y.push({node:E.node,callers:b.callers,callees:g.callers});}c.push({file:p,symbols:y});}return {query:t.query,entryPoints:c,totalHits:s.length}}async function Ne(e,t){return await(await C(e)).getStatus()}async function Re(e,t){return await(await C(e)).healthCheck()}var Ce=Filesystem.toUnixPath;function Se(e){let t=e.text??"";if(!t)return false;let n=t.slice(0,80);return /\bexport\s/.test(n)||/\bpublic\s/.test(n)?true:(false)}function Te(e){let t=e.text??"";if(!t)return [];let n=t.slice(0,80),l=[];return /\basync\s/.test(n)&&l.push("async"),/\bstatic\s/.test(n)&&l.push("static"),/\babstract\s/.test(n)&&l.push("abstract"),/\breadonly\s/.test(n)&&l.push("readonly"),/\bconst\s/.test(n)&&l.push("const"),/\blet\s/.test(n)&&l.push("let"),l}function x(e){return {id:e.id,name:e.name,astType:e.ast_type,language:e.language,filePath:Ce(e.file_path),startLine:e.start_line??0,endLine:e.end_line??0,isExported:Se(e),modifiers:Te(e)}}function $(e,t){return {id:e.id,source:e.source,target:e.target,relation:e.relation,direction:t}}function j(e,t,n){return e.map((l,a)=>({node:x(l),source:t[a]??"basic",score:n[a]??0,snippet:(l.text??"").slice(0,200).replace(/\s+/g," ").trim(),edges:(l.edges??[]).slice(0,10).map(i=>$(i))}))}function Q(){return {id:"",name:"",astType:"",language:"",filePath:"",startLine:0,endLine:0,isExported:false,modifiers:[]}}var Ie=Log.create({service:"codebase-format-truncate"}),z="**`",Le="**",ee=24e3,te=25e3;async function _(e,t={}){let n=t.softLimit??ee,l=t.hardCeiling??te,a=t.toolName??"codebase",i=t.writeToDisk!==false;if(e.length<=n)return {content:e,truncated:false};let d=e.slice(0,l),s=d.lastIndexOf(`
|
|
2
|
+
${z}`),o=d.lastIndexOf(`
|
|
3
|
+
`),r;s>l*.5?r=s:o>0?r=o:r=-1;let c=r>0?d.slice(0,r):d,u=c+"\n\n... (output truncated to budget; the source above is complete and verbatim \u2014 treat it as already Read. For any area not covered, make ANOTHER `<tool>` targeting those names \u2014 do NOT Read these files.)";if(!i)return {content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-c.length}/${e.length} characters truncated ...`};try{let m=await TruncateContent.truncate(e,{maxChars:c.length,direction:"head",label:`${a}-output`});return m.truncated?{content:u,truncated:!0,outputPath:m.outputPath,hint:TruncateContent.formatHint(m),info:`... ${m.removedLength}/${m.originalLength} characters truncated ...`}:{content:u,truncated:!0,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-c.length}/${e.length} characters truncated ...`}}catch(m){return Ie.warn("TruncateContent.truncate failed, returning without disk hint",{error:m instanceof Error?m.message:String(m)}),{content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-c.length}/${e.length} characters truncated ...`}}}function v(e,t={}){let n=t.softLimit??ee,l=t.hardCeiling??te;if(e.length<=n)return {content:e,truncated:false};let a=e.slice(0,l),i=a.lastIndexOf(`
|
|
4
|
+
${z}`),d=a.lastIndexOf(`
|
|
5
|
+
`),s;i>l*.5?s=i:d>0?s=d:s=-1;let o=s>0?a.slice(0,s):a;return {content:o+`
|
|
6
|
+
|
|
7
|
+
... (output truncated; tail dropped at section boundary)`,truncated:true,outputPath:"",hint:"",info:`... ${e.length-o.length}/${e.length} characters truncated ...`}}function Fe(e,t=Date.now()){let n=Math.max(0,Math.floor((t-e)/1e3));return n>60?">60s ago":`${n}s ago`}function H(e,t){if(!e||e.length===0)return null;let n=e.filter(a=>t.has(a.path));return n.length===0?null:`\u26A0\uFE0F Index may be stale for: ${n.map(a=>`${a.path} (edited ${Fe(a.lastEventAt)})`).join(", ")}
|
|
8
|
+
|
|
9
|
+
`}function w(e,t,n={}){return (ne[e]??ne.default).replace(/<(\w+)>/g,(a,i)=>i==="tool"?t:n[i]??`<${i}>`)}var ne={search:`---
|
|
10
|
+
|
|
11
|
+
> **Complete source for N files is included above \u2014 do NOT re-read them.**
|
|
12
|
+
> If your question also needs files/symbols listed under "Not shown above" (or any area this call didn't cover), make ANOTHER \`<tool>\` targeting those names \u2014 it returns the same source with line numbers and is cheaper and more complete than reading.`,impact:"---\n\n> **Risk: <riskLevel>**. Before editing `<root>`, review d=1 first \u2014 those WILL BREAK.\n> Use `<tool>` to read full source of any direct caller.",context:"---\n\n> **Use `impact` for blast-radius analysis. Use `explore` to read source.**",default:`---
|
|
13
|
+
|
|
14
|
+
> **Output truncated to budget; the content above is the source of truth.**
|
|
15
|
+
> For more detail, call \`<tool>\` with refined parameters.`};async function M(e,t){let{pendingFiles:n,toolName:l,sync:a=false}=t;if(e.length===0)return O(l,"No matches found.","Try broader search terms, or use `explore` to read source.");let i=Oe(e),d=new Set(i.keys()),s=[];s.push(H(n,d)??"");let o="[[codebase-search-summary]]";s.push(o+`
|
|
16
|
+
`);let r=e.length;s.push(`**Files with matches:** ${i.size}
|
|
17
|
+
`);for(let[m,y]of i){let E=y.map(h=>h.node.name),b=E.slice(0,5).join(", "),g=E.length>5?`, +${E.length-5} more`:"";s.push(`**\`${m}\`** \u2014 ${b}${g}
|
|
18
|
+
`);let f=y[0]?.node.language??"";s.push("```"+f);for(let h of y)s.push(`L${h.node.startLine} ${h.snippet}`);s.push("```\n");}s.push(w("search",l,{}));let c=s.join(`
|
|
19
|
+
`),p=`Found ${r} symbol${r===1?"":"s"} across ${i.size} file${i.size===1?"":"s"}.`,u=c.replace(o,p);return A(u,t,a)}async function q(e,t,n){let{pendingFiles:l,toolName:a,sync:i=false}=n;if(t.length===0||t.every(r=>r.count===0))return O(a,`No incoming edges for \`${e.name}\`.`,"This symbol has no callers \u2014 safe to refactor.");let d=t.reduce((r,c)=>r+c.count,0),s=we(d),o=[];o.push(H(l,new Set([e.filePath]))??""),o.push(`**Impact for \`${e.name}\`** (root: ${e.filePath}:${e.startLine}, total impacted: ${d})
|
|
20
|
+
`);for(let r of t){o.push(`- **d=${r.depth}** (${r.count} nodes) \u2014 ${r.riskLabel}`);for(let c of r.samples.slice(0,5))o.push(` - \`${c.name}\` ${c.file}:${c.line} [${c.relation}]`);r.samples.length>5&&o.push(` - ... and ${r.samples.length-5} more`);}return o.push(w("impact",a,{root:e.name,riskLevel:s})),A(o.join(`
|
|
21
|
+
`),n,i)}function we(e){return e>=100?"CRITICAL":e>=50?"HIGH":e>=10?"MEDIUM":"LOW"}function K(e){return e===1?"WILL BREAK (direct callers)":e===2?"LIKELY AFFECTED (indirect)":"MAY NEED TESTING (transitive)"}async function W(e,t){let{root:n,incoming:l,outgoing:a,neighbors:i}=e,{pendingFiles:d,toolName:s,sync:o=false}=t;if(l.length===0&&a.length===0&&i.length===0)return O(s,`No relations found for \`${n.name}\`.`,"This is a leaf node.");let r=[];r.push(H(d,new Set([n.filePath]))??""),r.push(`**Context for \`${n.name}\`** (${n.astType}, ${n.language}, ${n.filePath}:${n.startLine})
|
|
22
|
+
`),r.push(`**Incoming** (${l.length}):`);for(let c of l.slice(0,10))r.push(`- ${c.source} \u2192 [${c.relation}] \u2192 \`${n.name}\``);l.length>10&&r.push(`- ... and ${l.length-10} more`),r.push(""),r.push(`**Outgoing** (${a.length}):`);for(let c of a.slice(0,10))r.push(`- \`${n.name}\` \u2192 [${c.relation}] \u2192 ${c.target}`);if(a.length>10&&r.push(`- ... and ${a.length-10} more`),r.push(""),i.length>0){r.push(`**Neighbors** (${i.length}):`);for(let c of i.slice(0,20))r.push(`- [d=${c.depth}] \`${c.node.name}\` (${c.node.astType}) ${c.node.filePath}:${c.node.startLine}`);i.length>20&&r.push(`- ... and ${i.length-20} more`),r.push("");}return r.push(w("context",s,{})),A(r.join(`
|
|
23
|
+
`),t,o)}async function B(e,t,n){let{pendingFiles:l,toolName:a,sync:i=false}=n;if(!e.id)return O(a,"Node not found.","Check the node ID or use `search` to find it.");let d=t.filter(r=>r.direction==="in"),s=t.filter(r=>r.direction==="out"),o=[];o.push(H(l,new Set([e.filePath]))??""),o.push(`**Node: \`${e.name}\`**
|
|
24
|
+
`),o.push(`- ID: \`${e.id}\``),o.push(`- Kind: ${e.astType}`),o.push(`- Language: ${e.language}`),o.push(`- Location: ${e.filePath}:${e.startLine}-${e.endLine}`),o.push(`- Exported: ${e.isExported}`),e.modifiers.length>0&&o.push(`- Modifiers: ${e.modifiers.join(", ")}`),o.push(""),o.push(`**Edges** (incoming: ${d.length} / outgoing: ${s.length}):`);for(let r of d.slice(0,5))o.push(`- \u2190 [${r.relation}] ${r.source}`);for(let r of s.slice(0,5))o.push(`- \u2192 [${r.relation}] ${r.target}`);return t.length>10&&o.push(`- ... and ${t.length-10} more`),o.push(w("default",a,{})),A(o.join(`
|
|
25
|
+
`),n,i)}async function re(e,t){let{entryPoints:n,totalHits:l,query:a}=e,{toolName:i,sync:d=false}=t;if(n.length===0)return O(i,`No matches for \`${a}\`.`,"Try broader search terms, or use `callers` / `callees` to traverse from a known symbol.");let s=[];s.push(`## Code Context
|
|
26
|
+
`),s.push(`**Query:** ${a} `),s.push(`**Total hits:** ${l} `),s.push(`**Entry points:** ${n.length}
|
|
27
|
+
`);for(let o of n){s.push(`**\`${o.file}\`** \u2014 ${o.symbols.length} symbol${o.symbols.length===1?"":"s"}
|
|
28
|
+
`);for(let r of o.symbols){let c=(r.source??"").trim()||"(source not included)",p=r.node.language;if(s.push("```"+p),s.push(`L${r.node.startLine}-L${r.node.endLine} ${r.node.name} (${r.node.astType}${r.node.modifiers.length>0?`, ${r.node.modifiers.join(" ")}`:""})`),s.push(""),s.push(c),s.push("```\n"),r.callers.length>0){s.push(`**Callers of \`${r.node.name}\` (${r.callers.length}):**`);for(let u of r.callers.slice(0,5))s.push(`- [${u.relation}] \`${u.name}\` ${u.filePath}:${u.startLine}`);r.callers.length>5&&s.push(`- ... and ${r.callers.length-5} more`),s.push("");}if(r.callees.length>0){s.push(`**Callees of \`${r.node.name}\` (${r.callees.length}):**`);for(let u of r.callees.slice(0,5))s.push(`- [${u.relation}] \`${u.name}\` ${u.filePath}:${u.startLine}`);r.callees.length>5&&s.push(`- ... and ${r.callees.length-5} more`),s.push("");}}}return s.push(`---
|
|
29
|
+
`),s.push(w("context",i,{})),A(s.join(`
|
|
30
|
+
`),t,d)}function Oe(e){let t=new Map;for(let n of e){let l=n.node.filePath,a=t.get(l);a?a.push(n):t.set(l,[n]);}return t}function O(e,t,n){return `**${e}**
|
|
31
|
+
|
|
32
|
+
${t}
|
|
33
|
+
|
|
34
|
+
> **Tip:** ${n}`}async function A(e,t,n){let l={softLimit:t.softLimit,hardCeiling:t.hardCeiling,toolName:t.toolName,writeToDisk:n?false:t.writeToDisk};return (n?v(e,l):await _(e,l)).content}var ke=Log.create({service:"codebase-format-render"});async function De(e,t){if(e.length===0)return M([],t);let n=j(e,e.map(()=>"basic"),e.map(()=>0));return M(n,t)}async function _e(e,t,n){if(t.length===0)return q(x(e),[],n);let l=[{depth:1,count:t.length,riskLabel:K(1),samples:t.slice(0,10).map(a=>({name:a.source.name,file:x(a.source).filePath,line:a.source.start_line??0,relation:a.relation}))}];return q(x(e),l,n)}async function ve(e,t,n,l,a){let i=x(e),d=t.map(r=>$(r,"in")),s=n.map(r=>$(r,"out")),o=l.map(r=>({node:x(r),depth:1}));return W({root:i,incoming:d,outgoing:s,neighbors:o},a)}async function He(e,t,n){if(!e)return B(Q(),[],n);let l=x(e),a=t.map(i=>{let d=i.target===e.id?"in":"out";return $(i,d)});return B(l,a,n)}async function Me(e,t){let n={query:e.query,totalHits:e.totalHits,entryPoints:e.entryPoints.map(l=>({file:l.file,symbols:l.symbols.map(a=>({node:x(a.node),source:a.node.text??"",callers:a.callers.map(i=>({name:i.name,filePath:i.filePath,startLine:i.startLine,relation:i.relation})),callees:a.callees.map(i=>({name:i.name,filePath:i.filePath,startLine:i.startLine,relation:i.relation}))}))}))};return re(n,t)}ke.debug("format/render.ts loaded");export{_e as A,ve as B,He as C,Me as D,R as a,P as b,F as c,J as d,pe as e,ge as f,he as g,be as h,Ee as i,xe as j,Ne as k,Re as l,x as m,$ as n,j as o,Q as p,z as q,Le as r,_ as s,v as t,M as u,q as v,K as w,W as x,B as y,De as z};
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
'use strict';var chunkTS4OAYIJ_cjs=require('./chunk-TS4OAYIJ.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database');var F=class o extends Error{constructor(t,s,r){super(t);chunkTS4OAYIJ_cjs.a(this,"name","ParserError");chunkTS4OAYIJ_cjs.a(this,"filePath");chunkTS4OAYIJ_cjs.a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `ParserError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},g=class o extends Error{constructor(t,s,r){super(t);chunkTS4OAYIJ_cjs.a(this,"name","DatabaseError");chunkTS4OAYIJ_cjs.a(this,"operation");chunkTS4OAYIJ_cjs.a(this,"cause");this.operation=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `DatabaseError: ${this.message} during ${this.operation}${t}`}toJSON(){return {name:this.name,message:this.message,operation:this.operation,cause:this.cause?.message}}},M=class o extends Error{constructor(t,s,r){super(t);chunkTS4OAYIJ_cjs.a(this,"name","FileSystemError");chunkTS4OAYIJ_cjs.a(this,"filePath");chunkTS4OAYIJ_cjs.a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `FileSystemError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},u=class o extends Error{constructor(t,s){super(t);chunkTS4OAYIJ_cjs.a(this,"name","SchemaError");chunkTS4OAYIJ_cjs.a(this,"missing");this.missing=s,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.missing?` (missing: ${this.missing.join(", ")})`:"";return `SchemaError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,missing:this.missing}}},A=class o extends Error{constructor(t,s){super(t);chunkTS4OAYIJ_cjs.a(this,"name","ConfigError");chunkTS4OAYIJ_cjs.a(this,"field");this.field=s,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.field?` (field: ${this.field})`:"";return `ConfigError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,field:this.field}}},v=class o extends Error{constructor(t,s,r){super(t);chunkTS4OAYIJ_cjs.a(this,"name","IndexError");chunkTS4OAYIJ_cjs.a(this,"filePath");chunkTS4OAYIJ_cjs.a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=[this.message];return this.filePath&&t.push(`at ${this.filePath}`),this.cause&&t.push(`(caused by: ${this.cause.message})`),`IndexError: ${t.join(" ")}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},x=class o extends Error{constructor(t,s,r){super(t);chunkTS4OAYIJ_cjs.a(this,"name","QueryError");chunkTS4OAYIJ_cjs.a(this,"params");chunkTS4OAYIJ_cjs.a(this,"cause");this.params=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.params?` (params: ${JSON.stringify(this.params)})`:"",s=this.cause?` (caused by: ${this.cause.message})`:"";return `QueryError: ${this.message}${t}${s}`}toJSON(){return {name:this.name,message:this.message,params:this.params,cause:this.cause?.message}}},w=class o extends Error{constructor(t,s){super(`Unsupported language: ${t}`);chunkTS4OAYIJ_cjs.a(this,"name","UnsupportedLanguageError");chunkTS4OAYIJ_cjs.a(this,"extension");chunkTS4OAYIJ_cjs.a(this,"filePath");this.extension=t,this.filePath=s,Object.setPrototypeOf(this,o.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var P=utils.Log.create({service:"codebase-schema-migrations"}),p=1,W=[{id:1,description:"v1 baseline: nodes / edges / file_hashes / nodes_fts / meta / embedding_cache / node_embeddings + unresolved_refs / name_segment_vocab / project_metadata / parse_errors + \u6027\u80FD index (nodes.file_path / edges.source/target)",up:[`CREATE TABLE IF NOT EXISTS nodes (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
name TEXT NOT NULL,
|
|
4
|
+
ast_type TEXT NOT NULL,
|
|
5
|
+
language TEXT NOT NULL,
|
|
6
|
+
file_path TEXT NOT NULL,
|
|
7
|
+
start_line INTEGER,
|
|
8
|
+
start_col INTEGER,
|
|
9
|
+
end_line INTEGER,
|
|
10
|
+
end_col INTEGER,
|
|
11
|
+
text TEXT,
|
|
12
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
13
|
+
)`,`CREATE TABLE IF NOT EXISTS edges (
|
|
14
|
+
id TEXT PRIMARY KEY,
|
|
15
|
+
source TEXT NOT NULL,
|
|
16
|
+
target TEXT NOT NULL,
|
|
17
|
+
relation TEXT NOT NULL,
|
|
18
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
19
|
+
FOREIGN KEY (source) REFERENCES nodes(id) ON DELETE CASCADE,
|
|
20
|
+
FOREIGN KEY (target) REFERENCES nodes(id) ON DELETE CASCADE
|
|
21
|
+
)`,`CREATE TABLE IF NOT EXISTS file_hashes (
|
|
22
|
+
file_path TEXT PRIMARY KEY,
|
|
23
|
+
content_hash TEXT NOT NULL,
|
|
24
|
+
last_modified DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
25
|
+
)`,`CREATE VIRTUAL TABLE IF NOT EXISTS nodes_fts USING fts5(
|
|
26
|
+
id, name, ast_type, language, file_path, text,
|
|
27
|
+
tokenize='unicode61'
|
|
28
|
+
)`,`CREATE TABLE IF NOT EXISTS meta (
|
|
29
|
+
key TEXT PRIMARY KEY,
|
|
30
|
+
value TEXT
|
|
31
|
+
)`,`CREATE TABLE IF NOT EXISTS embedding_cache (
|
|
32
|
+
content_hash TEXT PRIMARY KEY,
|
|
33
|
+
embedding BLOB NOT NULL
|
|
34
|
+
)`,`CREATE TABLE IF NOT EXISTS node_embeddings (
|
|
35
|
+
node_id TEXT PRIMARY KEY,
|
|
36
|
+
embedding_text TEXT NOT NULL,
|
|
37
|
+
embedding BLOB NOT NULL,
|
|
38
|
+
FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
|
|
39
|
+
)`,`CREATE TABLE IF NOT EXISTS unresolved_refs (
|
|
40
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
41
|
+
from_node_id TEXT,
|
|
42
|
+
reference_name TEXT NOT NULL,
|
|
43
|
+
reference_kind TEXT NOT NULL,
|
|
44
|
+
line INTEGER,
|
|
45
|
+
col INTEGER,
|
|
46
|
+
file_path TEXT NOT NULL,
|
|
47
|
+
language TEXT NOT NULL,
|
|
48
|
+
candidates TEXT,
|
|
49
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
50
|
+
FOREIGN KEY (from_node_id) REFERENCES nodes(id) ON DELETE SET NULL
|
|
51
|
+
)`,"CREATE INDEX IF NOT EXISTS idx_unresolved_refs_file_path ON unresolved_refs(file_path)","CREATE INDEX IF NOT EXISTS idx_unresolved_refs_kind ON unresolved_refs(reference_kind)",`CREATE TABLE IF NOT EXISTS name_segment_vocab (
|
|
52
|
+
segment TEXT NOT NULL,
|
|
53
|
+
name TEXT NOT NULL,
|
|
54
|
+
PRIMARY KEY (segment, name)
|
|
55
|
+
) WITHOUT ROWID`,"CREATE INDEX IF NOT EXISTS idx_name_segment ON name_segment_vocab(segment)",`CREATE TABLE IF NOT EXISTS project_metadata (
|
|
56
|
+
key TEXT PRIMARY KEY,
|
|
57
|
+
value TEXT,
|
|
58
|
+
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
59
|
+
)`,`CREATE TABLE IF NOT EXISTS parse_errors (
|
|
60
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
61
|
+
file_path TEXT NOT NULL,
|
|
62
|
+
language TEXT NOT NULL,
|
|
63
|
+
stage TEXT NOT NULL,
|
|
64
|
+
message TEXT NOT NULL,
|
|
65
|
+
line INTEGER,
|
|
66
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
67
|
+
)`,"CREATE INDEX IF NOT EXISTS idx_parse_errors_file_path ON parse_errors(file_path)","CREATE INDEX IF NOT EXISTS idx_nodes_file_path ON nodes(file_path)","CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)"]}];function D(o,e=p,t={}){o.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
68
|
+
id INTEGER PRIMARY KEY,
|
|
69
|
+
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
70
|
+
)`);let s=o.prepare("SELECT id FROM schema_migrations").all(),r=new Set(s.map(a=>a.id)),n={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(a=>a.id)),targetVersion:e};for(let a of W){if(a.id>e)break;if(r.has(a.id)){n.pending.push(a.id);continue}if(t.dryRun){n.applied.push(a.id);continue}try{o.execBatch([...a.up]),o.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(a.id),r.add(a.id),n.applied.push(a.id),P.info("migration applied",{id:a.id,description:a.description});}catch(i){let c=i instanceof Error?i.message:String(i),T=a.up[0]??"";n.errors.push({migrationId:a.id,sql:T,error:c}),P.warn("migration step failed (may be idempotent)",{id:a.id,error:c,sqlCount:a.up.length});}}return n}function X(o){try{let e=o.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(t=>t.id))}catch{return 0}}var l=utils.Filesystem.toUnixPath,E=utils.Log.create({service:"codebase-database"}),m=2,H=class{constructor(e){chunkTS4OAYIJ_cjs.a(this,"db");chunkTS4OAYIJ_cjs.a(this,"dbPath");chunkTS4OAYIJ_cjs.a(this,"closed",false);chunkTS4OAYIJ_cjs.a(this,"ftsAvailable",false);this.dbPath=e===":memory:"?e:utils.Filesystem.normalize(e),this.db=database.createSyncSqliteConnection({path:this.dbPath,backend:"better-sqlite3",walMode:true,foreignKeys:true,busyTimeoutMs:5e3}),this.db.initialize();try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("foreign_keys = ON");}catch(t){E.warn("Failed to apply codebase PRAGMAs (synchronous / cache_size / foreign_keys)",{error:String(t)});}try{this.ensureSchema();let t=X(this.db);t>0&&this.setMeta("schema_version",String(t)),this.ftsAvailable=this.checkFtsAvailability(),this.detectAndMarkStaleOnInit();}catch(t){try{this.db.close();}catch{}throw this.closed=true,t}}ensureSchema(){try{D(this.db,p);let e=[["version","1.0.0"],["createdAt",new Date().toISOString()],["index_state","uninitialized"],["indexed_with_version","unknown"]],t=this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[s,r]of e)t.run(s,r);}catch(e){throw E.error("ensureSchema failed",{message:e instanceof Error?e.message:String(e),cause:e instanceof Error?e.cause:void 0,stack:e instanceof Error?e.stack:void 0}),new u("Failed to create database schema",e instanceof Error?[e.message]:[String(e)])}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:l(e.file_path)};this.db.prepare(`
|
|
71
|
+
INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
|
|
72
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
73
|
+
`).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(n=>({...n,file_path:l(n.file_path)})),s=this.db.prepare(`
|
|
74
|
+
INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
|
|
75
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
76
|
+
`);this.db.transaction(n=>{for(let a of n)s.run(a.id,a.name,a.ast_type,a.language,a.file_path,a.start_line,a.start_col,a.end_line,a.end_col,a.text,a.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(n);})(t);}updateFtsNodesInternal(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),r=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");for(let n of e)try{let a=s.get(n.id);a&&t.run(a.rowid),r.run(n.id,n.name,n.ast_type,n.language,n.file_path,n.text);}catch(a){E.warn("FTS update failed for node",{nodeId:n.id,error:String(a)});}}updateFtsNode(e){try{let t=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?").get(e.id);t&&this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(t.rowid),this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.ast_type,e.language,e.file_path,e.text);}catch(t){E.warn("FTS update failed for node",{nodeId:e.id,error:String(t)});}}updateFtsNodes(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),r=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");this.db.transaction(a=>{for(let i of a)try{let c=s.get(i.id);c&&t.run(c.rowid),r.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.text);}catch(c){E.warn("FTS update failed for node",{nodeId:i.id,error:String(c)});}})(e);}insertEdge(e){this.db.prepare(`
|
|
77
|
+
INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
|
|
78
|
+
VALUES (?, ?, ?, ?, ?)
|
|
79
|
+
`).run(e.id,e.source,e.target,e.relation,e.created_at);}insertEdges(e){if(e.length===0)return;let t=this.db.prepare(`
|
|
80
|
+
INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
|
|
81
|
+
VALUES (?, ?, ?, ?, ?)
|
|
82
|
+
`);this.db.transaction(r=>{for(let n of r)t.run(n.id,n.source,n.target,n.relation,n.created_at);})(e);}queryNodes(e){let t=[],s=[];e.filePath&&(t.push("file_path LIKE ?"),s.push(`%${l(e.filePath)}%`)),e.astType&&(t.push("ast_type = ?"),s.push(e.astType)),e.name&&(t.push("name = ?"),s.push(e.name)),e.language&&(t.push("language = ?"),s.push(e.language));let r="SELECT * FROM nodes";t.length>0&&(r+=` WHERE ${t.join(" AND ")}`),r+=" ORDER BY file_path, start_line",e.limit&&(r+=" LIMIT ?",s.push(e.limit)),e.offset&&(r+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(r).all(...s)}catch(n){throw new g("Failed to query nodes","queryNodes",n instanceof Error?n:new Error(String(n)))}}queryEdges(e){let t=[],s=[];if(e.sourceOrTarget&&e.sourceOrTarget.length>0){let n=e.sourceOrTarget.map(()=>"?").join(",");t.push(`(source IN (${n}) OR target IN (${n}))`),s.push(...e.sourceOrTarget,...e.sourceOrTarget);}else e.source&&(t.push("source = ?"),s.push(e.source)),e.target&&(t.push("target = ?"),s.push(e.target));e.relation&&(t.push("relation = ?"),s.push(e.relation));let r="SELECT * FROM edges";t.length>0&&(r+=` WHERE ${t.join(" AND ")}`),r+=" ORDER BY created_at DESC",e.limit&&(r+=" LIMIT ?",s.push(e.limit)),e.offset&&(r+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(r).all(...s)}catch(n){throw new g("Failed to query edges","queryEdges",n instanceof Error?n:new Error(String(n)))}}queryAll(e,t){try{let s=this.db.prepare(e);return t?s.all(...t):s.all()}catch(s){throw new g("Failed to execute query","queryAll",s instanceof Error?s:new Error(String(s)))}}searchNodesFts(e,t=20){if(E.debug("searchNodesFts start",{query:e,limit:t,ftsAvailable:this.ftsAvailable}),!this.ftsAvailable)return E.debug("searchNodesFts skip - FTS not available"),[];try{let s=e.split(/\s+/).map(i=>`${i}*`).join(" ");E.debug("searchNodesFts query",{ftsQuery:s});let a=this.db.prepare(`
|
|
83
|
+
SELECT
|
|
84
|
+
nodes_fts.id,
|
|
85
|
+
nodes_fts.name,
|
|
86
|
+
nodes_fts.ast_type,
|
|
87
|
+
nodes_fts.language,
|
|
88
|
+
nodes_fts.file_path,
|
|
89
|
+
nodes_fts.text,
|
|
90
|
+
nodes.start_line,
|
|
91
|
+
nodes.start_col,
|
|
92
|
+
nodes.end_line,
|
|
93
|
+
nodes.end_col,
|
|
94
|
+
bm25(nodes_fts) as score
|
|
95
|
+
FROM nodes_fts
|
|
96
|
+
JOIN nodes ON nodes.id = nodes_fts.id
|
|
97
|
+
WHERE nodes_fts.text MATCH ?
|
|
98
|
+
ORDER BY score DESC
|
|
99
|
+
LIMIT ?
|
|
100
|
+
`).all(s,t);return E.debug("searchNodesFts done",{resultCount:a.length}),a}catch(s){return E.warn("searchNodesFts failed",{error:String(s)}),[]}}deleteNodesByFile(e){let t=l(e);if(this.ftsAvailable)try{let r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let n of r)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(n.rowid);}catch(r){E.warn("FTS delete failed for file",{filePath:t,error:String(r)});}return this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t).changes}deleteEdgesByFile(e){let t=l(e);return this.db.prepare(`
|
|
101
|
+
DELETE FROM edges
|
|
102
|
+
WHERE source IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
103
|
+
OR target IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
104
|
+
`).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(l(e))?.content_hash??null}setFileHash(e,t){this.db.prepare(`
|
|
105
|
+
INSERT OR REPLACE INTO file_hashes (file_path, content_hash, last_modified)
|
|
106
|
+
VALUES (?, ?, ?)
|
|
107
|
+
`).run(l(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(l(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}checkIntegrity(){let e=h=>this.db.prepare(h).get().c,t=h=>e(h),s={nodes:t("SELECT COUNT(*) as c FROM nodes"),edges:t("SELECT COUNT(*) as c FROM edges"),file_hashes:t("SELECT COUNT(*) as c FROM file_hashes"),fts:t("SELECT COUNT(*) as c FROM nodes_fts"),node_embeddings:t("SELECT COUNT(*) as c FROM node_embeddings"),embedding_cache:t("SELECT COUNT(*) as c FROM embedding_cache"),parse_errors:t("SELECT COUNT(*) as c FROM parse_errors"),unresolved_refs:t("SELECT COUNT(*) as c FROM unresolved_refs"),name_segment_vocab:t("SELECT COUNT(*) as c FROM name_segment_vocab"),project_metadata:t("SELECT COUNT(*) as c FROM project_metadata"),meta:t("SELECT COUNT(*) as c FROM meta")},r=[],n=t(`
|
|
108
|
+
SELECT COUNT(*) as c FROM node_embeddings e
|
|
109
|
+
LEFT JOIN nodes n ON n.id = e.node_id WHERE n.id IS NULL
|
|
110
|
+
`);n>0&&r.push({severity:"error",message:`orphan node_embeddings: ${n}`});let a=t(`
|
|
111
|
+
SELECT COUNT(*) as c FROM edges e WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.source)
|
|
112
|
+
`);a>0&&r.push({severity:"error",message:`orphan edges (source): ${a}`});let i=t(`
|
|
113
|
+
SELECT COUNT(*) as c FROM edges e WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.target)
|
|
114
|
+
`);i>0&&r.push({severity:"error",message:`orphan edges (target): ${i}`});let c=t("SELECT COUNT(*) as c FROM edges WHERE source = target");c>0&&r.push({severity:"error",message:`self-loop edges: ${c} \u2014 re-run \`easbot codebase sync\` to filter (fixed in Wave 4 R3-2)`});t("SELECT COUNT(DISTINCT file_path) as c FROM nodes");let f=t(`
|
|
115
|
+
SELECT COUNT(*) as c FROM file_hashes fh
|
|
116
|
+
WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.file_path = fh.file_path)
|
|
117
|
+
`);f>0&&r.push({severity:"warn",message:`orphan file_hashes (no nodes): ${f} \u2014 run \`easbot codebase sync\` to cleanup`});let _=t(`
|
|
118
|
+
SELECT COUNT(DISTINCT n.file_path) as c FROM nodes n
|
|
119
|
+
WHERE NOT EXISTS (SELECT 1 FROM file_hashes fh WHERE fh.file_path = n.file_path)
|
|
120
|
+
`);_>0&&r.push({severity:"warn",message:`node files without hash: ${_}`});let R=t("SELECT COUNT(*) as c FROM nodes WHERE name IS NULL OR name = ''");R>0&&r.push({severity:"error",message:`nodes with null/empty name: ${R}`});let S=t("SELECT COUNT(*) as c FROM nodes WHERE ast_type IS NULL OR ast_type = ''");S>0&&r.push({severity:"error",message:`nodes with null/empty ast_type: ${S}`});let b=t("SELECT COUNT(*) as c FROM nodes WHERE language IS NULL OR language = ''");b>0&&r.push({severity:"error",message:`nodes with null/empty language: ${b}`});let N=t("SELECT COUNT(*) as c FROM nodes WHERE file_path IS NULL OR file_path = ''");N>0&&r.push({severity:"error",message:`nodes with null/empty file_path: ${N}`});let O=this.db.prepare("SELECT id, COUNT(*) as c FROM nodes GROUP BY id HAVING c > 1").all().length;O>0&&r.push({severity:"error",message:`duplicate node ids: ${O}`});let I=t("SELECT COUNT(*) as c FROM nodes WHERE file_path LIKE '%\\\\%'");I>0&&r.push({severity:"warn",message:`nodes with backslash in file_path: ${I}`});let L=t(`
|
|
121
|
+
SELECT COUNT(*) as c FROM nodes
|
|
122
|
+
WHERE start_line IS NOT NULL AND end_line IS NOT NULL AND start_line > end_line
|
|
123
|
+
`);L>0&&r.push({severity:"error",message:`invalid line ranges: ${L}`});let y=this.db.prepare("SELECT id, COUNT(*) as c FROM edges GROUP BY id HAVING c > 1").all().length;y>0&&r.push({severity:"error",message:`duplicate edge ids: ${y}`});let C=t("SELECT COUNT(*) as c FROM nodes_fts_content");return C!==s.nodes&&r.push({severity:"error",message:`FTS content desync: ${C} vs ${s.nodes} (run \`easbot codebase recreate\` to rebuild)`}),s.parse_errors>100&&r.push({severity:"warn",message:`parse_errors > 100 (${s.parse_errors}) \u2014\u2014 many files failed to parse`}),{issues:r,stats:s}}getStatus(){let e=this.db.prepare("SELECT COUNT(*) as c FROM nodes").get(),t=this.db.prepare("SELECT COUNT(*) as c FROM edges").get(),s=this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get(),r=this.db.prepare("SELECT key, value FROM meta").all(),n={};for(let a of r)n[a.key]=a.value;return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:s?.c??0,dbPath:this.dbPath,meta:n,indexState:this.getIndexState(),extractionVersion:parseInt(this.getMeta("indexed_with_extraction_version")??"0",10),isStale:this.isIndexStale()}}setLastSync(){this.db.prepare(`
|
|
124
|
+
INSERT OR REPLACE INTO meta (key, value)
|
|
125
|
+
VALUES ('lastSync', ?)
|
|
126
|
+
`).run(new Date().toISOString());}getIndexState(){return this.getMeta("index_state")??"uninitialized"}setIndexState(e){this.setMeta("index_state",e),this.setMeta("last_index_state_change",new Date().toISOString());}markIndexed(e){this.setMeta("indexed_with_version",e),this.setMeta("indexed_with_extraction_version",String(m)),this.setMeta("index_state","complete"),this.setMeta("last_index_state_change",new Date().toISOString());}isIndexStale(){let e=this.getMeta("indexed_with_extraction_version");if(!e)return false;let t=parseInt(e,10);return Number.isNaN(t)||t<m}detectAndMarkStaleOnInit(){if(this.isIndexStale()){let e=this.getMeta("indexed_with_extraction_version");E.warn("codebase db is stale",{recorded:e??"(none)",current:String(m),hint:"run `easbot codebase recreate` or `easbot codebase index --force` to rebuild"});let t=this.getIndexState();(t==="complete"||t==="partial")&&this.setIndexState("stale");}}getNodeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM nodes").get()?.c??0}getEdgeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM edges").get()?.c??0}getFileCount(){return this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get()?.c??0}getNodeById(e){return this.db.prepare("SELECT * FROM nodes WHERE id = ?").get(e)??null}getEdgeById(e){return this.db.prepare("SELECT * FROM edges WHERE id = ?").get(e)??null}clearAll(e={}){this.db.exec("DELETE FROM nodes"),this.db.exec("DELETE FROM edges"),this.db.exec("DELETE FROM file_hashes"),this.db.exec("DELETE FROM meta"),e.keepEmbeddings||(this.db.exec("DELETE FROM node_embeddings"),this.db.exec("DELETE FROM embedding_cache")),this.ftsAvailable&&this.db.exec("DELETE FROM nodes_fts");try{this.db.exec("DELETE FROM sqlite_sequence WHERE name IN ('nodes', 'edges', 'file_hashes', 'meta')");}catch{}}getCachedEmbedding(e){let s=this.db.prepare(`
|
|
127
|
+
SELECT embedding FROM embedding_cache WHERE content_hash = ?
|
|
128
|
+
`).get(e);return s?new Float32Array(s.embedding.buffer,s.embedding.byteOffset,s.embedding.length/4):null}getVectorDims(){let e=this.db.prepare("SELECT value FROM meta WHERE key = ?").get("vectorDims");return e?parseInt(e.value,10):void 0}ensureVectorDims(e){this.db.prepare("SELECT value FROM meta WHERE key = ?").get("vectorDims")||this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)").run("vectorDims",String(e));}cacheEmbedding(e,t){if(this.db.prepare("SELECT embedding FROM embedding_cache WHERE content_hash = ?").get(e))return;this.ensureVectorDims(t.length),this.db.prepare(`
|
|
129
|
+
INSERT OR REPLACE INTO embedding_cache (content_hash, embedding)
|
|
130
|
+
VALUES (?, ?)
|
|
131
|
+
`).run(e,t);}deleteEmbeddingsByFile(e){let t=l(e);return this.db.prepare(`
|
|
132
|
+
DELETE FROM node_embeddings WHERE node_id IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
133
|
+
`).run(t).changes}getAllNodeEmbeddings(){return this.db.prepare("SELECT node_id, embedding FROM node_embeddings").all()}storeNodeEmbeddings(e){if(e.length===0)return;this.ensureVectorDims(e[0].embedding.length);let t=this.db.prepare(`
|
|
134
|
+
INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
|
|
135
|
+
VALUES (?, ?, ?)
|
|
136
|
+
`);this.db.transaction(r=>{for(let n of r)try{t.run(n.nodeId,n.embeddingText,n.embedding);}catch(a){E.warn("Failed to store embedding for node",{nodeId:n.nodeId,error:String(a)});}})(e);}insertParseError(e){return this.db.prepare(`
|
|
137
|
+
INSERT INTO parse_errors (file_path, language, stage, message, line)
|
|
138
|
+
VALUES (?, ?, ?, ?, ?)
|
|
139
|
+
`).run(e.filePath.replace(/\\/g,"/"),e.language,e.stage,e.message,e.line??null).changes}insertUnresolvedRef(e){return this.db.prepare(`
|
|
140
|
+
INSERT INTO unresolved_refs
|
|
141
|
+
(from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
|
|
142
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
143
|
+
`).run(e.fromNodeId??null,e.referenceName,e.referenceKind,e.line??null,e.col??null,e.filePath.replace(/\\/g,"/"),e.language,e.candidates?JSON.stringify(e.candidates):null).changes}insertUnresolvedRefsBatch(e){if(e.length===0)return 0;let s=`
|
|
144
|
+
INSERT INTO unresolved_refs
|
|
145
|
+
(from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
|
|
146
|
+
VALUES ${e.map(()=>"(?, ?, ?, ?, ?, ?, ?, ?)").join(", ")}
|
|
147
|
+
`,r=[];for(let i of e)r.push(i.fromNodeId??null,i.referenceName,i.referenceKind,i.line??null,i.col??null,i.filePath.replace(/\\/g,"/"),i.language,i.candidates?JSON.stringify(i.candidates):null);return this.db.prepare(s).run(...r).changes}insertNameSegment(e,t){return this.db.prepare(`
|
|
148
|
+
INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES (?, ?)
|
|
149
|
+
`).run(e,t).changes}insertNameSegmentsBatch(e){if(e.length===0)return 0;let s=`
|
|
150
|
+
INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES ${e.map(()=>"(?, ?)").join(", ")}
|
|
151
|
+
`,r=[];for(let i of e)r.push(i.segment,i.name);return this.db.prepare(s).run(...r).changes}setProjectMetadata(e,t){return this.db.prepare(`
|
|
152
|
+
INSERT OR REPLACE INTO project_metadata (key, value, updated_at)
|
|
153
|
+
VALUES (?, ?, CURRENT_TIMESTAMP)
|
|
154
|
+
`).run(e,t).changes}getNodeIdsByFile(e){let t=e.replace(/\\/g,"/");return this.db.prepare("SELECT id FROM nodes WHERE file_path = ?").all(t).map(r=>r.id)}deleteFtsByFile(e){let t=e.replace(/\\/g,"/"),s=this.getNodeIdsByFile(t);if(s.length===0)return 0;let r=this.db.prepare("DELETE FROM nodes_fts WHERE id = ?");return this.db.transaction(a=>{for(let i of a)r.run(i);})(s),s.length}initialize(){if(this.closed)throw new g("Cannot initialize closed database","initialize")}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){E.warn("Database close error",{error:String(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}deleteMeta(e){if(!this.db)throw new Error("Database not initialized");this.db.prepare("DELETE FROM meta WHERE key = ?").run(e);}};function te(o){return o.isClosed()}function se(o){return o.getDbPath()}function re(o,e){return o.transaction(e)}exports.a=F;exports.b=g;exports.c=M;exports.d=u;exports.e=A;exports.f=v;exports.g=x;exports.h=w;exports.i=p;exports.j=W;exports.k=D;exports.l=X;exports.m=m;exports.n=H;exports.o=te;exports.p=se;exports.q=re;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {c}from'./chunk-UTKA3WG3.mjs';import {join,isAbsolute}from'path';import {homedir}from'os';import {xdgState,xdgData,xdgCache,xdgConfig}from'xdg-basedir';var u=null,p=null;function N(e){u=e;}function R(){u=null;}function a(){if(u)return u;let e=homedir();return {Path:{home:e,data:process.env.EASBOT_DATA_PATH?.trim()||join(xdgData??join(e,".local","share"),"easbot"),config:process.env.EASBOT_CONFIG_PATH?.trim()||join(xdgConfig??join(e,".config"),"easbot"),state:process.env.EASBOT_STATE_PATH?.trim()||join(xdgState??join(xdgData??join(e,".local","share"),"easbot"),"state"),cache:process.env.EASBOT_CACHE_PATH?.trim()||join(xdgCache??join(e,".cache"),"easbot"),log:process.env.EASBOT_LOG_PATH?.trim()||join(xdgState??join(xdgData??join(e,".local","share"),"easbot"),"log"),bin:process.env.EASBOT_BIN_PATH?.trim()||join(e,".local","bin")}}}function U(e){p=e;}function q(){p=null;}function v(){if(p)return p;let e=process.cwd();return {directory:e,worktree:e}}function g(){return a().Path.home||homedir()}function j(){let e=a().Path.data;return e||(xdgData??join(g(),".local","share"))}function X(){let e=a().Path.config;return e||(xdgConfig??join(g(),".config"))}function L(){let e=a().Path.state;return e||(xdgState??join(j(),"state"))}function z(){let e=a().Path.cache;return e||(xdgCache??join(g(),".cache"))}function P(){return v().directory||process.cwd()}function ee(e){let t={},s=[];for(let n of e)n==="--json"?t.json=true:n==="--quiet"||n==="-q"?t.quiet=true:n==="--help"||n==="-h"?t.help=true:n==="--no-embed"?t.noEmbed=true:n==="--embed"?t.noEmbed=false:n.startsWith("-")||s.push(n);return t.dir=s[0],t}async function te(e){let t=e.dir&&isAbsolute(e.dir)?e.dir:join(P(),e.dir??"."),s=c(t),{CodeBase:n}=await import('./code-base-XJXVJ35Z.mjs'),{DEFAULT_EMBEDDING_CONFIG:_,DEFAULT_INDEXER_CONFIG:C,DEFAULT_PARSER_CONFIG:I}=await import('@easbot/types'),c$1=new n({workspaceDir:t,database:{path:s,walMode:true},embedding:e.noEmbed===false?_:void 0,indexer:C,parser:I,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}}),h,l={_lastPct:-1,_lastProgressAt:0};try{await c$1.initialize();let o=await c$1.sync(e.quiet?void 0:i=>{let E=Math.max(i.total,1),f=Math.min(100,Math.floor(i.processed/E*100)),b=Date.now(),T=f!==l._lastPct,O=b-l._lastProgressAt>3e4;if(T||O){let $=String(f).padStart(3," ");console.error(` \u{1F4A1} [${$}%] ${i.stage}: ${i.processed}/${i.total} files`),l._lastPct=f,l._lastProgressAt=b;}}),D=c$1.getDatabase().getIndexState();h={rootDir:t,success:o.success,filesAdded:o.filesAdded,filesUpdated:o.filesUpdated,filesDeleted:o.filesDeleted,filesSkipped:o.filesSkipped,nodesCreated:o.nodesCreated,edgesCreated:o.edgesCreated,errorCount:o.errors.length,errors:o.errors,durationMs:o.duration,indexState:D};}finally{await c$1.close();}return h}function re(e){let t=[];if(t.push("Codebase sync"),t.push(` rootDir: ${e.rootDir}`),t.push(` success: ${e.success?"\u2713":"\u2717"}`),t.push(` indexState: ${e.indexState}`),t.push(` files added: ${e.filesAdded}`),t.push(` files updated: ${e.filesUpdated}`),t.push(` files deleted: ${e.filesDeleted}`),t.push(` files skipped: ${e.filesSkipped}`),t.push(` nodes created: ${e.nodesCreated}`),t.push(` edges created: ${e.edgesCreated}`),t.push(` duration: ${e.durationMs}ms`),e.errorCount>0){t.push(` errors (${e.errorCount}):`);for(let s of e.errors.slice(0,10))t.push(` - ${s.filePath}: ${s.error}`);e.errors.length>10&&t.push(` ... and ${e.errors.length-10} more`);}return t.join(`
|
|
2
|
+
`)}export{N as a,R as b,a as c,U as d,q as e,v as f,g,j as h,X as i,L as j,z as k,P as l,ee as m,te as n,re as o};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var n=Object.defineProperty;var c=(t,e,r)=>e in t?n(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r;var m=(t,e,r)=>c(t,typeof e!="symbol"?e+"":e,r);var o=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,u=o();exports.a=m;exports.b=u;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-G3IYU6TZ.mjs';import {existsSync,readFileSync,promises}from'fs';import {isAbsolute,normalize,join,dirname}from'path';import {createRequire}from'module';import {fileURLToPath}from'url';import {Log,Ignore}from'@easbot/utils';var s=Log.create({service:"codebase-file-watcher"}),O=["node_modules/**",".git/**","dist/**","build/**","__pycache__/**","*.min.js","*.min.ts",".easbot/**",".codebase/**"],d=null,l=null;function S(){let n=process.platform==="linux"?`-${globalThis.EASBOT_LIBC||"glibc"}`:"";return `@parcel/watcher-${process.platform}-${process.arch}${n}`}async function $(n){if(d)return d;if(l){let e=new Error(l);throw n==="warn"&&s.warn("@parcel/watcher previously failed",{error:l}),e}let r=dirname(fileURLToPath(import.meta.url)),t=S();try{let c=(await import('@parcel/watcher/wrapper.js')).createWrapper;if(typeof c!="function")throw new Error("@parcel/watcher/wrapper.js: createWrapper not exported");let p=createRequire(r+"/")(t),o=c(p);return d=o,s.info("@parcel/watcher loaded",{binding:t,backend:"available"}),o}catch(e){let c=e instanceof Error?e.message:String(e),i=`binding "${t}" not found or failed to load. Run: pnpm install ${t}`;throw l=`${c}. ${i}`,s.error("failed to load @parcel/watcher",{error:e,binding:t}),n==="warn"&&s.warn("continuing without watcher (warn mode)"),e instanceof Error?new Error(l):new Error(l)}}function w(){return process.platform==="darwin"?"fs-events":process.platform==="linux"?"inotify":process.platform==="win32"?"windows":"brute-force"}var g=class{constructor(r){a(this,"workspaceDir");a(this,"backendOpt");a(this,"ignorePatterns");a(this,"onLoadFailure");a(this,"ignoreInstance");a(this,"listeners",new Set);a(this,"unsubscribe",null);a(this,"disposed",false);a(this,"running",false);this.workspaceDir=isAbsolute(r.workspaceDir)?r.workspaceDir:normalize(r.workspaceDir),this.backendOpt=r.backend??"auto",this.ignorePatterns=r.ignorePatterns??[...O],this.onLoadFailure=r.onLoadFailure??"throw",this.ignoreInstance=Ignore.create().add(this.ignorePatterns);}getIgnoreInstance(){return this.ignoreInstance}getIgnorePatterns(){return this.ignorePatterns}getActiveBackend(){return this.backendOpt==="auto"?w():this.backendOpt}on(r){return this.listeners.add(r),()=>this.listeners.delete(r)}async start(){if(this.running)return;this.running=true;let r=this.backendOpt==="auto"?w():this.backendOpt;s.info("FileWatcher start",{workspaceDir:this.workspaceDir,backend:r});let t;try{t=await $(this.onLoadFailure);}catch(e){if(this.running=false,this.onLoadFailure==="warn")return;throw e}await this.subscribeWithParcel(t,r);}async stop(){if(this.unsubscribe){try{await this.unsubscribe();}catch(r){s.warn("parcel unsubscribe error",{error:r});}this.unsubscribe=null;}this.running=false;}async dispose(){await this.stop(),this.disposed=true,this.listeners.clear();}isRunning(){return this.running}isDisposed(){return this.disposed}async subscribeWithParcel(r,t){if(this.disposed)throw new Error("FileWatcher disposed before subscribe");let e=(i,p)=>{if(this.disposed)return;let o=this.workspaceDir.replace(/\\/g,"/").replace(/\/$/,""),f=p.replace(/\\/g,"/"),u=p;if(f.startsWith(o+"/")&&(u=f.slice(o.length+1)),this.ignoreInstance.ignores(u,i==="create"&&u.endsWith("/")))return;let m=i==="create"?"add":i==="delete"?"unlink":"change";for(let P of this.listeners)try{P(m,u);}catch(v){s.warn("listener threw",{error:v});}},c=await r.subscribe(this.workspaceDir,(i,p)=>{if(i){s.error("parcel subscribe callback error",{error:i});return}for(let o of p)e(o.type,o.path);},{ignore:[...this.ignorePatterns],backend:t});if(this.disposed){await c.unsubscribe().catch(()=>{});return}this.unsubscribe=async()=>{await c.unsubscribe().catch(i=>{s.warn("parcel unsubscribe error",{error:i});});};}};function h(n){return join(n,".watcher.pid")}function C(n){let r=h(n);if(!existsSync(r))return null;try{let t=readFileSync(r,"utf-8").trim(),e=parseInt(t,10);return Number.isFinite(e)?e:null}catch{return null}}async function U(n,r){let t=h(n);await promises.writeFile(t,String(r),"utf-8");}async function z(n){let r=h(n);try{await promises.unlink(r);}catch{}}export{g as a,h as b,C as c,U as d,z as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {join}from'path';import {existsSync,mkdirSync}from'fs';function t(r){return join(r,".easbot")}function d(r){return join(t(r),"codebase.json")}function b(r){return join(t(r),"db","codebase.db")}function f(r){existsSync(r)||mkdirSync(r,{recursive:true});}export{t as a,d as b,b as c,f as d};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunk7XCIIOM6_cjs=require('./chunk-7XCIIOM6.cjs'),path=require('path'),os=require('os'),xdgBasedir=require('xdg-basedir');var u=null,p=null;function F(e){u=e;}function N(){u=null;}function a(){if(u)return u;let e=os.homedir();return {Path:{home:e,data:process.env.EASBOT_DATA_PATH?.trim()||path.join(xdgBasedir.xdgData??path.join(e,".local","share"),"easbot"),config:process.env.EASBOT_CONFIG_PATH?.trim()||path.join(xdgBasedir.xdgConfig??path.join(e,".config"),"easbot"),state:process.env.EASBOT_STATE_PATH?.trim()||path.join(xdgBasedir.xdgState??path.join(xdgBasedir.xdgData??path.join(e,".local","share"),"easbot"),"state"),cache:process.env.EASBOT_CACHE_PATH?.trim()||path.join(xdgBasedir.xdgCache??path.join(e,".cache"),"easbot"),log:process.env.EASBOT_LOG_PATH?.trim()||path.join(xdgBasedir.xdgState??path.join(xdgBasedir.xdgData??path.join(e,".local","share"),"easbot"),"log"),bin:process.env.EASBOT_BIN_PATH?.trim()||path.join(e,".local","bin")}}}function R(e){p=e;}function U(){p=null;}function G(){if(p)return p;let e=process.cwd();return {directory:e,worktree:e}}function g(){return a().Path.home||os.homedir()}function v(){let e=a().Path.data;return e||(xdgBasedir.xdgData??path.join(g(),".local","share"))}function q(){let e=a().Path.config;return e||(xdgBasedir.xdgConfig??path.join(g(),".config"))}function X(){let e=a().Path.state;return e||(xdgBasedir.xdgState??path.join(v(),"state"))}function L(){let e=a().Path.cache;return e||(xdgBasedir.xdgCache??path.join(g(),".cache"))}function P(){return G().directory||process.cwd()}function Z(e){let t={},s=[];for(let n of e)n==="--json"?t.json=true:n==="--quiet"||n==="-q"?t.quiet=true:n==="--help"||n==="-h"?t.help=true:n==="--no-embed"?t.noEmbed=true:n==="--embed"?t.noEmbed=false:n.startsWith("-")||s.push(n);return t.dir=s[0],t}async function ee(e){let t=e.dir&&path.isAbsolute(e.dir)?e.dir:path.join(P(),e.dir??"."),s=chunk7XCIIOM6_cjs.c(t),{CodeBase:n}=await import('./code-base-ONPUU5A3.cjs'),{DEFAULT_EMBEDDING_CONFIG:_,DEFAULT_INDEXER_CONFIG:C,DEFAULT_PARSER_CONFIG:I}=await import('@easbot/types'),c=new n({workspaceDir:t,database:{path:s,walMode:true},embedding:e.noEmbed===false?_:void 0,indexer:C,parser:I,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}}),h,l={_lastPct:-1,_lastProgressAt:0};try{await c.initialize();let o=await c.sync(e.quiet?void 0:i=>{let E=Math.max(i.total,1),f=Math.min(100,Math.floor(i.processed/E*100)),b=Date.now(),T=f!==l._lastPct,O=b-l._lastProgressAt>3e4;if(T||O){let $=String(f).padStart(3," ");console.error(` \u{1F4A1} [${$}%] ${i.stage}: ${i.processed}/${i.total} files`),l._lastPct=f,l._lastProgressAt=b;}}),D=c.getDatabase().getIndexState();h={rootDir:t,success:o.success,filesAdded:o.filesAdded,filesUpdated:o.filesUpdated,filesDeleted:o.filesDeleted,filesSkipped:o.filesSkipped,nodesCreated:o.nodesCreated,edgesCreated:o.edgesCreated,errorCount:o.errors.length,errors:o.errors,durationMs:o.duration,indexState:D};}finally{await c.close();}return h}function te(e){let t=[];if(t.push("Codebase sync"),t.push(` rootDir: ${e.rootDir}`),t.push(` success: ${e.success?"\u2713":"\u2717"}`),t.push(` indexState: ${e.indexState}`),t.push(` files added: ${e.filesAdded}`),t.push(` files updated: ${e.filesUpdated}`),t.push(` files deleted: ${e.filesDeleted}`),t.push(` files skipped: ${e.filesSkipped}`),t.push(` nodes created: ${e.nodesCreated}`),t.push(` edges created: ${e.edgesCreated}`),t.push(` duration: ${e.durationMs}ms`),e.errorCount>0){t.push(` errors (${e.errorCount}):`);for(let s of e.errors.slice(0,10))t.push(` - ${s.filePath}: ${s.error}`);e.errors.length>10&&t.push(` ... and ${e.errors.length-10} more`);}return t.join(`
|
|
2
|
+
`)}exports.a=F;exports.b=N;exports.c=a;exports.d=R;exports.e=U;exports.f=G;exports.g=g;exports.h=v;exports.i=q;exports.j=X;exports.k=L;exports.l=P;exports.m=Z;exports.n=ee;exports.o=te;
|