@easbot/codebase 0.3.32 → 0.3.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/dist/chunks/{cache-LSQZJEDR.cjs → cache-CSRIBDNY.cjs} +1 -1
  4. package/dist/chunks/{cache-D7NVUXB2.mjs → cache-EZ3VLUUC.mjs} +1 -1
  5. package/dist/chunks/{chunk-TBDAGLC4.cjs → chunk-3DAM6EZN.cjs} +6 -6
  6. package/dist/chunks/{chunk-OJK5EFPD.cjs → chunk-6NYX22KV.cjs} +19 -19
  7. package/dist/chunks/{chunk-OZYQQS63.cjs → chunk-AARBEAIB.cjs} +2 -2
  8. package/dist/chunks/{chunk-JEHVBEBS.cjs → chunk-D5NDNAKA.cjs} +1 -1
  9. package/dist/chunks/{chunk-TMQVJU4I.mjs → chunk-ECMVXJH2.mjs} +1 -1
  10. package/dist/chunks/{chunk-33DIOGLJ.mjs → chunk-EU2I2AMK.mjs} +1 -1
  11. package/dist/chunks/{chunk-PRPBK7D6.mjs → chunk-FZNMPXUO.mjs} +2 -2
  12. package/dist/chunks/{chunk-37KKG3UK.mjs → chunk-OUJNWRIY.mjs} +12 -12
  13. package/dist/chunks/{chunk-KR6BQNY6.mjs → chunk-QZMJ5EUF.mjs} +3 -3
  14. package/dist/chunks/{chunk-CLUGDJA5.cjs → chunk-VXLUR7M5.cjs} +2 -2
  15. package/dist/chunks/cli-handler-7HKSS3UW.mjs +1 -0
  16. package/dist/chunks/cli-handler-OU2TC2SB.cjs +1 -0
  17. package/dist/chunks/{code-base-M4EMTQTG.mjs → code-base-OBQSRCQ3.mjs} +1 -1
  18. package/dist/chunks/{code-base-5BXR4FUU.cjs → code-base-WZ3L5IE5.cjs} +1 -1
  19. package/dist/chunks/database-manager-T43UZZ45.cjs +1 -0
  20. package/dist/chunks/database-manager-ZC46AHSS.mjs +1 -0
  21. package/dist/chunks/file-watcher-GUS2OVZU.cjs +1 -0
  22. package/dist/chunks/file-watcher-RAO72GUL.mjs +1 -0
  23. package/dist/chunks/{interfaces-43SSCG3E.mjs → interfaces-UUDPRWI6.mjs} +1 -1
  24. package/dist/chunks/{interfaces-LUHDPZOT.cjs → interfaces-YGSG2MI4.cjs} +1 -1
  25. package/dist/chunks/{llm-WS3XKT46.mjs → llm-NWYEBR5K.mjs} +1 -1
  26. package/dist/chunks/{llm-S6D5ICOO.cjs → llm-UYBJKQ3S.cjs} +1 -1
  27. package/dist/chunks/{stdio-server-KA3JQB7C.cjs → stdio-server-37QG6AO2.cjs} +2 -2
  28. package/dist/chunks/{stdio-server-QP63TXGI.mjs → stdio-server-QAEXVFSI.mjs} +1 -1
  29. package/dist/cli.cjs +1 -1
  30. package/dist/cli.mjs +1 -1
  31. package/dist/index.cjs +1 -1
  32. package/dist/index.mjs +1 -1
  33. package/package.json +10 -10
  34. package/dist/chunks/cli-handler-IQ6ZNLEJ.mjs +0 -1
  35. package/dist/chunks/cli-handler-WTEPKO4E.cjs +0 -1
  36. package/dist/chunks/database-manager-KM7BOISA.mjs +0 -1
  37. package/dist/chunks/database-manager-LTHK7MM6.cjs +0 -1
  38. package/dist/chunks/file-watcher-2MUX5MO5.cjs +0 -1
  39. package/dist/chunks/file-watcher-ABFT22GS.mjs +0 -1
  40. /package/dist/chunks/{chunk-T6KJWYTV.mjs → chunk-47LKNS74.mjs} +0 -0
  41. /package/dist/chunks/{chunk-KFESJR3T.cjs → chunk-R32346OA.cjs} +0 -0
@@ -1,4 +1,4 @@
1
- import {f,e}from'./chunk-33DIOGLJ.mjs';import {b}from'./chunk-KTSR5VPT.mjs';import {a as a$2}from'./chunk-ESA2CL57.mjs';import {a as a$1,b as b$1,c,d}from'./chunk-T6KJWYTV.mjs';import te from'path';import {existsSync,mkdirSync,readFileSync}from'fs';import {fileURLToPath}from'url';import {DEFAULT_SYNC_CONFIG,DEFAULT_INDEXER_CONFIG,DEFAULT_PARSER_CONFIG,DEFAULT_SEARCH_CONFIG,DEFAULT_EMBEDDING_CONFIG}from'@easbot/types';import {Filesystem,Log,errorMeta,Shell,NameErrors,Glob,Ignore}from'@easbot/utils';import {Worker}from'worker_threads';import {createRequire}from'module';import et from'fs/promises';import {createHash}from'crypto';import {resolveSqlTextLimit,SQL_TEXT_LIMIT_DEFAULT}from'@easbot/database';var ze={".ts":"ts",".tsx":"tsx",".js":"js",".jsx":"js",".mjs":"js",".cjs":"js",".py":"py",".rs":"rs",".go":"go",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"csharp",".java":"java",".scala":"scala",".rb":"ruby",".php":"php",".zig":"zig"};var K=Filesystem.toUnixPath,lt=`
1
+ import {f,e}from'./chunk-EU2I2AMK.mjs';import {b}from'./chunk-KTSR5VPT.mjs';import {a as a$2}from'./chunk-ESA2CL57.mjs';import {a as a$1,b as b$1,c,d}from'./chunk-47LKNS74.mjs';import te from'path';import {existsSync,mkdirSync,readFileSync}from'fs';import {fileURLToPath}from'url';import {DEFAULT_SYNC_CONFIG,DEFAULT_INDEXER_CONFIG,DEFAULT_PARSER_CONFIG,DEFAULT_SEARCH_CONFIG,DEFAULT_EMBEDDING_CONFIG}from'@easbot/types';import {Filesystem,Log,errorMeta,Shell,NameErrors,Glob,Ignore}from'@easbot/utils';import {Worker}from'worker_threads';import {createRequire}from'module';import et from'fs/promises';import {createHash}from'crypto';import {resolveSqlTextLimit,SQL_TEXT_LIMIT_DEFAULT}from'@easbot/database';var ze={".ts":"ts",".tsx":"tsx",".js":"js",".jsx":"js",".mjs":"js",".cjs":"js",".py":"py",".rs":"rs",".go":"go",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"csharp",".java":"java",".scala":"scala",".rb":"ruby",".php":"php",".zig":"zig"};var K=Filesystem.toUnixPath,lt=`
2
2
  INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
3
3
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
4
4
  `,pt=`
@@ -163,7 +163,7 @@ if (parentPort !== null) {
163
163
  }
164
164
  queueDepth++;
165
165
  try {
166
- // ADR 0080 (FK + wildcard target fix): CALLS / IMPORTS edge targets are wildcards
166
+ // (FK + wildcard target fix): CALLS / IMPORTS edge targets are wildcards
167
167
  // ('ts:*:*:calleeName', resolved in resolution stage) \u2014 by design NOT in nodes table.
168
168
  // edges FK (source/target) \u2192 nodes(id) makes every CALLS / IMPORTS INSERT FK-fail,
169
169
  // rolling back the whole transaction \u2192 caller sees success:true but db is empty.
@@ -200,4 +200,4 @@ if (parentPort !== null) {
200
200
  `}function Ie(y,e){return new Worker(wt(e.betterSqlite3Path),{eval:true})}var _e=Log.create({service:"codebase.better-sqlite3-resolver"}),Ge=createRequire(import.meta.url);async function je(y={}){try{let s=Ge.resolve("better-sqlite3");if(s)return _e.debug("better-sqlite3 resolved from monorepo",{resolved:s}),{absolutePath:Filesystem.normalize(s),source:"monorepo"}}catch(s){_e.errorDegradable("better-sqlite3 not in current resolve paths",{error:errorMeta(s)});}let e=process.env.EASBOT_CACHE_PATH,r=y.installPath??e??`${process.cwd()}/.easbot/.cache`,t=Filesystem.normalize(r),i=y.version??"latest";_e.info("better-sqlite3 not found locally, installing to cache",{installPath:t,version:i,envCache:e});let n;try{n=await Shell.install("better-sqlite3",i,t);}catch(s){throw new b.BetterSqlite3ResolveError({message:`Failed to install better-sqlite3@${i} into ${t}: ${errorMeta(s).message}. You can also install it manually: \`npm i -g better-sqlite3\` or \`pnpm add better-sqlite3\` in your project.`,installPath:t},{cause:s})}try{let s=Ge.resolve("better-sqlite3",{paths:[n]}),o=Filesystem.normalize(s),c=t===Filesystem.normalize(e??"")?"env-cache-install":"cwd-cache-install";return _e.info("better-sqlite3 installed and resolved",{resolved:o,installPath:t}),{absolutePath:o,source:c}}catch(s){throw new b.BetterSqlite3ResolveError({message:`Installed better-sqlite3 to ${n} but cannot resolve entry from there: ${errorMeta(s).message}`,installPath:t},{cause:s})}}var de=Log.create({service:"database.async-write"}),Fe,ce,be=class{constructor(e){a$1(this,"worker");a$1(this,"mock");a$1(this,"dbPath");a$1(this,"batchSize");a$1(this,"batchIntervalMs");a$1(this,"queueMax");a$1(this,"bufferedStatements",[]);a$1(this,"pendingRequests",new Map);a$1(this,"nextRequestId",1);a$1(this,"flushTimer",null);a$1(this,"ready");a$1(this,"disposed",false);a$1(this,"lastBatchError",null);if(this.dbPath=e.dbPath,this.mock=e.mock??false,this.batchSize=e.batchSize??100,this.batchIntervalMs=e.batchIntervalMs??50,this.queueMax=e.queueMax??1e3,this.mock)this.worker=$e(),this.ready=this.waitForReady();else {let r=e.betterSqlite3Path;r?(this.worker=Ie(this.dbPath,{betterSqlite3Path:r}),this.ready=this.waitForReady()):(this.worker=null,this.ready=this.initRealAsync());}this.worker&&this.installAckHandler();}async initRealAsync(){let e=await It();this.worker=Ie(this.dbPath,{betterSqlite3Path:e}),this.installAckHandler(),await this.waitForReady();}installAckHandler(){this.requireWorker().on("message",r=>{let t=r;if(t.type==="debug_error"){de.error("AsyncWriteBackend statement failed (debug)",{error:errorMeta(t.error)});return}if(typeof t.requestId!="number"||t.requestId<1)return;let i=this.pendingRequests.get(t.requestId);if(i){if(this.pendingRequests.delete(t.requestId),clearTimeout(i.timer),t.type==="write_batch_ack")i.resolve();else if(t.type==="error"){let n=new Error(t.error??"worker write error");this.lastBatchError={error:n,timestamp:Date.now()},i.reject(n);}}});}requireWorker(){if(!this.worker)throw new NameErrors.OperationFailedError({message:"AsyncWriteBackend worker not initialized yet (call installAckHandler / waitForReady only after spawn)",operation:"async-write-backend-worker-not-initialized"});return this.worker}waitForReady(){let e=this.requireWorker();return new Promise((r,t)=>{let i=setTimeout(()=>t(new Error("worker init timeout")),1e4),n=s=>{if(s.type==="ready"){clearTimeout(i),e.off("message",n);let o=setTimeout(()=>t(new Error("worker open timeout")),1e4),c=l=>{l.type==="open_ack"&&l.requestId===0?(clearTimeout(o),e.off("message",c),r()):l.type==="error"&&l.requestId===0&&(clearTimeout(o),e.off("message",c),t(new Error(l.error??"worker open error")));};e.on("message",c),e.postMessage({type:"open",requestId:0,dbPath:this.dbPath});}else s.type==="error"&&s.requestId===-1&&(clearTimeout(i),e.off("message",n),t(new Error(s.error??"unknown init error")));};e.on("message",n);})}async waitReady(){await this.ready;}enqueue(e){if(this.disposed)throw new NameErrors.OperationFailedError({message:"AsyncWriteBackend has been disposed",operation:"async-write-backend-disposed"});if(!this.worker)throw new NameErrors.OperationFailedError({message:"AsyncWriteBackend worker not ready yet (await backend.ready before enqueue)",operation:"async-write-backend-worker-not-ready"});let r=Math.ceil(this.bufferedStatements.length/Math.max(this.batchSize,1));if(this.pendingRequests.size+r>=this.queueMax)throw new NameErrors.TooLargeError({message:`AsyncWriteBackend queue overflow (pending=${this.pendingRequests.size}, buffered=${this.bufferedStatements.length}, max=${this.queueMax})`,size:this.pendingRequests.size+r,maxSize:this.queueMax});this.bufferedStatements.push(...e),this.bufferedStatements.length>=this.batchSize?this.flushBuffer():this.flushTimer||(this.flushTimer=setTimeout(()=>this.flushBuffer(),this.batchIntervalMs));}flushBuffer(){if(!this.worker||(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.bufferedStatements.length===0))return;let e=this.bufferedStatements;this.bufferedStatements=[];let r=this.nextRequestId++,t={resolve:()=>{},reject:i=>{de.error("AsyncWriteBackend write failed",{error:errorMeta(i),requestId:r});},timer:setTimeout(()=>{this.pendingRequests.delete(r),t.reject(new Error(`AsyncWriteBackend write timeout (${r})`));},3e4)};this.pendingRequests.set(r,t),this.worker.postMessage({type:"write_batch",statements:e,requestId:r});}async flush(e=Number.parseInt(process.env.EASBOT_FLUSH_TIMEOUT??"3600000",10)||36e5){let r=this.lastBatchError;if(this.lastBatchError=null,this.flushBuffer(),this.pendingRequests.size===0){if(r)throw new NameErrors.OperationFailedError({message:`AsyncWriteBackend flush failed (deferred from previous batch): ${r.error.message}`,operation:"async-write-backend-flush-deferred"});return}let t=this.pendingRequests.size,i=Date.now();await new Promise((s,o)=>{let c=setTimeout(()=>o(new Error(`flush timeout after ${e}ms, pending=${this.pendingRequests.size}`)),e),l=setInterval(()=>{let p=this.pendingRequests.size,u=Math.floor((Date.now()-i)/1e3);p>0&&u>0&&u%5===0&&de.debug("flush in progress",{pending:p,initial:t,elapsedSec:u});},1e3),d=setInterval(()=>{this.pendingRequests.size===0&&(clearTimeout(c),clearInterval(d),clearInterval(l),s());},5);});let n=this.lastBatchError;if(n!==null)throw this.lastBatchError=null,new NameErrors.OperationFailedError({message:`AsyncWriteBackend flush failed: ${n.error.message}`,operation:"async-write-backend-flush-failed"})}async dispose(){this.disposed=true,this.flushBuffer();try{await this.flush(3e4);}catch(e){de.warn("dispose flush failed, forcing terminate",{pending:this.pendingRequests.size,error:errorMeta(e)});}this.worker&&(this.worker.postMessage({type:"shutdown",requestId:0}),await this.worker.terminate());}pendingCount(){return this.pendingRequests.size}getLastBatchError(){return this.lastBatchError}clearLastBatchError(){this.lastBatchError=null;}};async function It(){return Fe||(ce||(ce=je().then(y=>(Fe=y.absolutePath,ce=void 0,de.info("better-sqlite3 resolved for AsyncWriteBackend",{path:y.absolutePath,source:y.source}),y.absolutePath)).catch(y=>{throw ce=void 0,y})),ce)}var Qe=Log.create({service:"codebase.parser"}),Rt={js:{package:"tree-sitter-javascript",wasmFile:"tree-sitter-javascript.wasm"},ts:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-typescript.wasm"},tsx:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-tsx.wasm"},py:{package:"tree-sitter-python",wasmFile:"tree-sitter-python.wasm"},rs:{package:"tree-sitter-rust",wasmFile:"tree-sitter-rust.wasm"},go:{package:"tree-sitter-go",wasmFile:"tree-sitter-go.wasm"},c:{package:"tree-sitter-c",wasmFile:"tree-sitter-c.wasm"},cpp:{package:"tree-sitter-cpp",wasmFile:"tree-sitter-cpp.wasm"},csharp:{package:"tree-sitter-c-sharp",wasmFile:"tree-sitter-c_sharp.wasm"},java:{package:"tree-sitter-java",wasmFile:"tree-sitter-java.wasm"},ruby:{package:"tree-sitter-ruby",wasmFile:"tree-sitter-ruby.wasm"},php:{package:"tree-sitter-php",wasmFile:"tree-sitter-php.wasm"},scala:{package:"tree-sitter-scala",wasmFile:"tree-sitter-scala.wasm"},zig:{package:"@tree-sitter-grammars/tree-sitter-zig",wasmFile:"tree-sitter-zig.wasm"}};function At(){return typeof import.meta<"u"&&import.meta.url?te.dirname(fileURLToPath(import.meta.url)):typeof d<"u"?d:process.cwd()}function Mt(y,e){let r=At(),t=r;for(let i=0;i<10;i++){let n=te.join(t,"node_modules",y,e);if(Filesystem.stat(n)!==void 0)return n;let s=te.dirname(t);if(s===t)break;t=s;}return te.join(r,"node_modules",y,e)}var re=class{constructor(){a$1(this,"parsers",new Map);a$1(this,"initialized",false);a$1(this,"initPromise",null);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize(),await this.initPromise,this.initPromise=null;}}async doInitialize(){let e=await import('web-tree-sitter'),r=e.default?.default||e.default?.Parser||e.default||e.Parser,t=r?.Language||e.Language||e.default?.Language;if(typeof r?.init=="function"&&await r.init(),typeof r!="function")throw new NameErrors.OperationFailedError({message:`web-tree-sitter did not export a Parser constructor. Got: ${typeof r}`,operation:"web-tree-sitter-parser-missing"});if(typeof t!="function")throw new NameErrors.OperationFailedError({message:`web-tree-sitter did not export a Language class. Got: ${typeof t}`,operation:"web-tree-sitter-language-missing"});let i=["ts","tsx","js","py","rs","go","c","cpp","csharp","java","ruby","php","scala","zig"],n=await Promise.allSettled(i.map(async s=>{try{let o=Rt[s];if(!o)return Qe.warn("No WASM config for language",{lang:s}),null;let c=Mt(o.package,o.wasmFile),l=await t.load(c),d=new r;return d.setLanguage(l),{lang:s,parser:d,language:l}}catch(o){return Qe.warn("Failed to load parser",{lang:s,error:errorMeta(o)}),null}}));for(let s of n)if(s.status==="fulfilled"&&s.value){let{lang:o,parser:c,language:l}=s.value;this.parsers.set(o,{parser:c,language:l});}this.initialized=true;}getParser(e){return this.parsers.get(e)?.parser??null}getLanguage(e){return this.parsers.get(e)?.language??null}detectLanguage(e){let r=te.extname(e).toLowerCase();return ze[r]??null}parse(e,r){if(!this.initialized)throw new b.ParserError({message:"Parser not initialized",filePath:""});let t=this.parsers.get(r);if(!t)throw new b.ParserError({message:`No parser available for language: ${r}`,filePath:""});try{return t.parser.parse(e)}catch(i){throw new b.ParserError({message:"Failed to parse code",filePath:""},{cause:i})}}parseFile(e,r){let t=this.detectLanguage(e);if(!t)throw new b.UnsupportedLanguageError({extension:te.extname(e),filePath:e});return this.parse(r,t)}isLanguageSupported(e){return this.parsers.has(e)}getSupportedLanguages(){return Array.from(this.parsers.keys())}isInitialized(){return this.initialized}getStatus(){let e={},r=["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"];for(let t of r)e[t]=this.parsers.has(t);return e}dispose(){this.parsers.clear(),this.initialized=false;}},Y=null;async function Lt(){return Y||(Y=new re,await Y.initialize()),Y}function qt(){Y&&(Y.dispose(),Y=null);}var W={class_declaration:"class_declaration",class_item:"class_declaration",class_definition:"class_declaration",abstract_class_declaration:"class_declaration",class_specifier:"class_declaration",record_declaration:"class_declaration",interface_declaration:"interface_declaration",protocol_declaration:"interface_declaration",function_declaration:"function_definition",function_definition:"function_definition",function_item:"function_definition",function_expression:"function_definition",arrow_function:"function_definition",method_definition:"method_definition",method_declaration:"method_definition",method:"method_definition",method_invocation:"method_definition",public_field_definition:"property_declaration",field_definition:"property_declaration",property_signature:"property_declaration",field_declaration:"field_declaration",property_declaration:"property_declaration",val_definition:"property_declaration",var_definition:"property_declaration",variable_declaration:"variable_declaration",lexical_declaration:"variable_declaration",variable_declarator:"variable_declaration",assignment:"variable_declaration",module:"module_declaration",internal_module:"module_declaration",ambient_declaration:"module_declaration",namespace_declaration:"module_declaration",namespace_definition:"module_declaration",mod_item:"module_declaration",import_declaration:"import_declaration",import_statement:"import_declaration",import_from_statement:"import_declaration",use_declaration:"import_declaration",use_list:"import_declaration",using_directive:"import_declaration",require:"import_declaration",require_relative:"import_declaration",preproc_include:"import_declaration",include_directive:"import_declaration",struct_declaration:"struct_declaration",struct_definition:"struct_declaration",struct_item:"struct_declaration",struct_specifier:"struct_declaration",trait_item:"trait_declaration",trait_definition:"trait_declaration",impl_item:"impl_item",enum_declaration:"enum_declaration",enum_item:"enum_declaration",enum_specifier:"enum_declaration",type_alias_declaration:"type_alias_declaration",type_declaration:"type_declaration",class:"class_declaration",decorator:"decorator",annotation:"annotation",marker_annotation:"annotation",attribute:"attribute",attribute_item:"attribute",modifiers:"modifiers",decorated_expression:"decorator",attribute_decorator:"decorator",export_statement:"export_statement",const_item:"constant_declaration",constant_declaration:"constant_declaration",function:"function_definition"},ke={language:"ts",rawTypes:{classTypes:["class_declaration","abstract_class_declaration"],interfaceTypes:["interface_declaration"],moduleTypes:["module","internal_module","ambient_declaration"],methodTypes:["method_definition","function_declaration"],propertyTypes:["public_field_definition","property_signature"],functionTypes:["function_declaration"],typeAliasTypes:["type_alias_declaration"],enumTypes:["enum_declaration"],importTypes:["import_statement"],callExpressionTypes:["call_expression","new_expression"],memberAccessTypes:["member_expression"],contextualKeywordTypes:["this","super"],identifierTypes:["identifier","type_identifier","property_identifier"],annotationTypes:["decorator"],variableTypes:["lexical_declaration","variable_declaration"],exportTypes:["export_statement"],ambientDeclarationTypes:["ambient_declaration"]},normalizeMap:W,inheritance:{extendsClauseTypes:["extends_clause","extends_type_clause"],implementsClauseTypes:["implements_clause"],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:["class_declaration","abstract_class_declaration","function_declaration","method_definition","export_statement"]},parameters:{wrapperType:"formal_parameters",paramTypes:["required_parameter","optional_parameter"],typeInWrapper:["type_identifier","generic_type","predefined_type","array_type"],declaratorStyle:"wrapper"}},Dt={...ke,language:"tsx"},Ot={language:"js",rawTypes:{classTypes:["class_declaration"],interfaceTypes:[],moduleTypes:[],methodTypes:["method_definition"],propertyTypes:["public_field_definition","field_definition"],functionTypes:["function_declaration","function_expression","arrow_function"],typeAliasTypes:[],enumTypes:[],importTypes:["import_statement"],callExpressionTypes:["call_expression","new_expression"],memberAccessTypes:["member_expression"],contextualKeywordTypes:["this","super"],identifierTypes:["identifier","property_identifier"],annotationTypes:["decorator"],variableTypes:["lexical_declaration","variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:W,inheritance:{extendsClauseTypes:["extends_clause","superclass"],implementsClauseTypes:[],fallbackToFirstIdentifier:true,stripTemplateArgs:false},annotation:{annotatableTypes:["class_declaration","function_declaration","method_definition"]},parameters:{wrapperType:"formal_parameters",paramTypes:["required_parameter","optional_parameter"],typeInWrapper:["type_identifier","generic_type","predefined_type","array_type"],declaratorStyle:"wrapper"}},Wt={language:"py",rawTypes:{classTypes:["class_definition"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:[],functionTypes:["function_definition"],typeAliasTypes:[],enumTypes:[],importTypes:["import_statement","import_from_statement"],callExpressionTypes:["call"],memberAccessTypes:["attribute"],contextualKeywordTypes:[],identifierTypes:["identifier"],annotationTypes:["decorator"],variableTypes:["assignment","expression_statement"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:W,inheritance:{extendsClauseTypes:["argument_list","superclass"],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:["function_definition","class_definition","decorated_definition"]},parameters:{wrapperType:"formal_parameters",paramTypes:["identifier","typed_parameter","default_parameter","list_splat_pattern","dictionary_splat_pattern"],typeInWrapper:["type","identifier"],declaratorStyle:"wrapper"}},zt={language:"java",rawTypes:{classTypes:["class_declaration","abstract_class_declaration"],interfaceTypes:["interface_declaration"],moduleTypes:[],methodTypes:["method_declaration"],propertyTypes:["field_declaration"],functionTypes:[],typeAliasTypes:[],enumTypes:["enum_declaration"],importTypes:["import_declaration"],callExpressionTypes:["method_invocation","object_creation_expression"],memberAccessTypes:[],contextualKeywordTypes:["this","super"],identifierTypes:["identifier","type_identifier"],annotationTypes:["annotation","marker_annotation","modifiers"],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:W,inheritance:{extendsClauseTypes:["superclass","extends_clause"],implementsClauseTypes:["super_interfaces","implements_clause","interface_list"],fallbackToFirstIdentifier:false,stripTemplateArgs:true},annotation:{annotatableTypes:["class_declaration","method_declaration","field_declaration","interface_declaration"]},parameters:{wrapperType:"formal_parameters",paramTypes:["formal_parameter"],typeInWrapper:["type_identifier","generic_type","array_type","integral_type","floating_point_type","boolean_type"],declaratorStyle:"wrapper"}},Bt={language:"csharp",rawTypes:{classTypes:["class_declaration","record_declaration"],interfaceTypes:["interface_declaration"],moduleTypes:[],methodTypes:["method_declaration"],propertyTypes:["field_declaration","property_declaration"],functionTypes:[],typeAliasTypes:[],enumTypes:["enum_declaration"],importTypes:["using_directive"],callExpressionTypes:["invocation_expression","new_expression","object_creation_expression"],memberAccessTypes:["member_access_expression"],contextualKeywordTypes:["this","base"],identifierTypes:["identifier","type_identifier"],annotationTypes:["attribute"],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:W,inheritance:{extendsClauseTypes:["base_list","super"],implementsClauseTypes:["base_list"],fallbackToFirstIdentifier:true,stripTemplateArgs:true},annotation:{annotatableTypes:["class_declaration","method_declaration","field_declaration"]},parameters:{wrapperType:"formal_parameters",paramTypes:["parameter"],typeInWrapper:["predefined_type","identifier","generic_name","array_type","nullable_type"],declaratorStyle:"wrapper"}},Ht={language:"c",rawTypes:{classTypes:["struct_specifier"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:["field_declaration"],functionTypes:["function_definition"],typeAliasTypes:["type_declaration"],enumTypes:["enum_specifier"],importTypes:["preproc_include"],callExpressionTypes:["call_expression"],memberAccessTypes:["field_expression"],contextualKeywordTypes:["this"],identifierTypes:["identifier","type_identifier","field_identifier"],annotationTypes:[],variableTypes:["declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:W,inheritance:{extendsClauseTypes:[],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:[]},parameters:{wrapperType:"parameter_list",paramTypes:["parameter_declaration","parameter"],typeInWrapper:["type_identifier","primitive_type","pointer_type","array_type","sized_type_specifier","struct_specifier","union_specifier","enum_specifier"],declaratorStyle:"declarator"}},$t={language:"cpp",rawTypes:{classTypes:["class_specifier","struct_specifier"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:["field_declaration"],functionTypes:["function_definition"],typeAliasTypes:["type_declaration"],enumTypes:["enum_specifier"],importTypes:["preproc_include"],callExpressionTypes:["call_expression","new_expression"],memberAccessTypes:["field_expression"],contextualKeywordTypes:["this"],identifierTypes:["identifier","type_identifier","field_identifier","pointer_type","reference_type","qualified_identifier"],annotationTypes:["attribute"],variableTypes:["declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:W,inheritance:{extendsClauseTypes:["base_class_clause","superclass"],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:true},annotation:{annotatableTypes:["class_specifier","function_definition"]},parameters:{wrapperType:"parameter_list",paramTypes:["parameter_declaration","parameter"],typeInWrapper:["type_identifier","primitive_type","pointer_type","array_type","sized_type_specifier","struct_specifier","class_specifier","enum_specifier","scoped_identifier","template_type","auto"],declaratorStyle:"declarator"}},Gt={language:"rs",rawTypes:{classTypes:["struct_item","enum_item","impl_item"],interfaceTypes:["trait_item"],moduleTypes:["mod_item"],methodTypes:["function_item"],propertyTypes:["field_declaration"],functionTypes:["function_item"],typeAliasTypes:["type_declaration"],enumTypes:["enum_item"],importTypes:["use_declaration"],callExpressionTypes:["call_expression"],memberAccessTypes:["field_expression","scoped_identifier"],contextualKeywordTypes:["Self"],identifierTypes:["identifier","type_identifier"],annotationTypes:["attribute_item"],variableTypes:["const_item"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:W,inheritance:{extendsClauseTypes:[],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:true},annotation:{annotatableTypes:["function_item","struct_item","trait_item"]},parameters:{wrapperType:"parameters",paramTypes:["parameter"],typeInWrapper:["type_identifier","reference_type","slice_type","array_type","generic_type","scoped_identifier","pointer_type","unit_type","never_type"],declaratorStyle:"wrapper"}},jt={language:"go",rawTypes:{classTypes:["type_declaration"],interfaceTypes:[],moduleTypes:[],methodTypes:["method_declaration"],propertyTypes:[],functionTypes:["function_declaration"],typeAliasTypes:["type_declaration"],enumTypes:[],importTypes:["import_declaration"],callExpressionTypes:["call_expression"],memberAccessTypes:["selector_expression"],contextualKeywordTypes:[],identifierTypes:["identifier","type_identifier","field_identifier"],annotationTypes:[],variableTypes:[],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:W,inheritance:{extendsClauseTypes:[],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:[]},parameters:{wrapperType:"parameter_list",paramTypes:["parameter_declaration","variadic_parameter"],typeInWrapper:["type_identifier","pointer_type","slice_type","map_type","channel_type","array_type","function_type","qualified_type","generic_type"],declaratorStyle:"wrapper"}},Ut={language:"ruby",rawTypes:{classTypes:["class"],interfaceTypes:[],moduleTypes:["module"],methodTypes:["method","method_definition","singleton_method"],propertyTypes:[],functionTypes:["method","method_definition"],typeAliasTypes:[],enumTypes:[],importTypes:[],callExpressionTypes:["call"],memberAccessTypes:["constant"],contextualKeywordTypes:["self"],identifierTypes:["identifier","constant"],annotationTypes:[],variableTypes:["assignment"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:W,inheritance:{extendsClauseTypes:["superclass"],implementsClauseTypes:[],fallbackToFirstIdentifier:true,stripTemplateArgs:false},annotation:{annotatableTypes:[]},parameters:{wrapperType:"method_parameters",paramTypes:["identifier","required_parameter","optional_parameter","splat_parameter","hash_splat_parameter","block_parameter","keyword_rest_parameter"],typeInWrapper:[],declaratorStyle:"wrapper"}},Qt={language:"php",rawTypes:{classTypes:["class_declaration"],interfaceTypes:["interface_declaration"],moduleTypes:["namespace_definition"],methodTypes:["method_declaration"],propertyTypes:["property_declaration"],functionTypes:["function_definition"],typeAliasTypes:[],enumTypes:[],importTypes:["namespace_use_declaration"],callExpressionTypes:["function_call_expression","member_call_expression","scoped_call_expression","object_creation_expression"],memberAccessTypes:["member_call_expression"],contextualKeywordTypes:[],identifierTypes:["name","variable_name"],annotationTypes:["attribute"],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:W,inheritance:{extendsClauseTypes:["base_clause"],implementsClauseTypes:["class_interface_clause"],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:["class_declaration","method_declaration","function_definition"]},parameters:{wrapperType:"formal_parameters",paramTypes:["simple_parameter","variadic_parameter","property_promotion_parameter"],typeInWrapper:["named_type","primitive_type","optional_type"],declaratorStyle:"wrapper"}},Kt={language:"scala",rawTypes:{classTypes:["class_definition"],interfaceTypes:["trait_definition"],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:["val_definition","var_definition"],functionTypes:["function_definition"],typeAliasTypes:[],enumTypes:[],importTypes:["import_declaration"],callExpressionTypes:["call_expression","call","instance_expression"],memberAccessTypes:["field_expression","select","stable_identifier","field_access"],contextualKeywordTypes:["this"],identifierTypes:["identifier","type_identifier"],annotationTypes:["annotation"],variableTypes:["val_definition","var_definition"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:W,inheritance:{extendsClauseTypes:["extends_clause"],implementsClauseTypes:["with_clause"],fallbackToFirstIdentifier:false,stripTemplateArgs:true},annotation:{annotatableTypes:["function_definition","class_definition","trait_definition"]},parameters:{wrapperType:"parameters",paramTypes:["parameter"],typeInWrapper:["type_identifier","generic_type","scoped_type_identifier","function_type","tuple_type","refined_type"],declaratorStyle:"wrapper"}},Vt={language:"zig",rawTypes:{classTypes:["struct_declaration","enum_declaration"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_declaration"],propertyTypes:[],functionTypes:["function_declaration"],typeAliasTypes:[],enumTypes:["enum_declaration"],importTypes:[],callExpressionTypes:["call_expression","builtin_call_expression"],memberAccessTypes:["field_access","field_expression"],contextualKeywordTypes:[],identifierTypes:["identifier","type_identifier"],annotationTypes:[],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:W,inheritance:{extendsClauseTypes:[],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:[]},parameters:{wrapperType:"parameters",paramTypes:["parameter"],typeInWrapper:["identifier","optional_type","array_type","pointer_type","slice_type"],declaratorStyle:"wrapper"}},Ke=new Map([["ts",ke],["tsx",Dt],["js",Ot],["py",Wt],["java",zt],["csharp",Bt],["c",Ht],["cpp",$t],["rs",Gt],["go",jt],["php",Qt],["scala",Kt],["zig",Vt],["ruby",Ut]]);function A(y){return Ke.get(y)??ke}Array.from(Ke.keys());function Ve(y){let e=A(y),r=new Set;for(let t of [e.rawTypes.classTypes,e.rawTypes.interfaceTypes,e.rawTypes.moduleTypes,e.rawTypes.methodTypes,e.rawTypes.propertyTypes,e.rawTypes.functionTypes,e.rawTypes.typeAliasTypes,e.rawTypes.enumTypes,e.rawTypes.importTypes,e.rawTypes.annotationTypes,e.rawTypes.variableTypes,e.rawTypes.exportTypes,e.rawTypes.ambientDeclarationTypes])for(let i of t)r.add(i);return r}function Ye(y){let e=A(y),r=new Set;for(let t of e.rawTypes.methodTypes)r.add(t);for(let t of e.rawTypes.propertyTypes)r.add(t);return r}function Je(y){let e=A(y);return new Set(e.rawTypes.identifierTypes)}function F(y,e){return A(y).normalizeMap[e]??e}var ie=class{extractNodes(e,r,t,i){let n=[],s=r.split(`
201
201
  `),o=Ve(t),c=Ye(t),l=Je(t);return this.walkTree(e.rootNode,n,t,i,s,o,c,l),n}walkTree(e,r,t,i,n,s,o,c,l,d){if(s.has(e.type)){let p=this.extractNode(e,t,i,n,l,d,o,c);p&&(r.push(p),p.name&&(l=this.generateNodeId(p)),o.has(e.type)||(d=p.name??d));}for(let p=0;p<e.childCount;p++){let u=e.children[p];u&&this.walkTree(u,r,t,i,n,s,o,c,l,d);}}extractNode(e,r,t,i,n,s,o,c){let l=this.getNodeName(e,r,c);if(!l)return null;let d=e.startPosition,p=e.endPosition,u=this.getNodeText(e,i),g=o.has(e.type),f=g&&s?`${s}.${l}@${d.row+1}`:l,h=g?this.extractParameterTypes(e,r):[];return {name:f,ast_type:F(r,e.type),language:r,file_path:t,start_line:d.row+1,start_col:d.column,end_line:p.row+1,end_col:p.column,text:u,parent_id:n,metadata:g?{originalName:l,parameterTypes:h}:void 0}}extractParameterTypes(e,r){let i=A(r).parameters;if(!i)return [];let n=new Set(i.typeInWrapper),s=[],o=c=>{for(let l of c.children)if(l.type===i.wrapperType)return l;return null};if(i.declaratorStyle==="declarator"){for(let c of e.children)if(c.type==="function_declarator"||c.type==="pointer_declarator"){let l=o(c);if(l){for(let d of l.children)if(i.paramTypes.includes(d.type)){let p=this.findTypeInNode(d,n);p&&s.push(p);}return s}}}else {let c=o(e);if(c){for(let l of c.children)if(i.paramTypes.includes(l.type)){let d=this.findTypeInNode(l,n);d&&s.push(d);}}}return s}findTypeInNode(e,r){for(let t of e.children)if(r.has(t.type))return t.text;return null}getNodeName(e,r,t){switch(e.type){case "class_declaration":case "class_definition":case "abstract_class_declaration":case "class":case "interface_declaration":case "protocol_declaration":case "trait_item":case "trait_definition":case "struct_item":case "struct_declaration":case "struct_definition":case "struct_specifier":case "enum_item":case "enum_declaration":case "enum_specifier":case "type_alias_declaration":case "record_declaration":return this.findNameInChildren(e,["name","identifier","type_identifier","type_name"],t);case "function_declaration":case "function_definition":case "function_item":case "function_expression":case "arrow_function":case "function":case "method_definition":case "method_declaration":case "method":case "method_invocation":case "singleton_method":return this.findNameInChildren(e,["name","property_identifier","function_name"],t)??this.findNameInGrandchildren(e,["function_declarator","declarator","name"],["identifier","property_identifier","field_identifier","name"],t);case "public_field_definition":case "field_definition":case "field_declaration":case "property_signature":case "property_declaration":case "val_definition":case "var_definition":return this.findNameInGrandchildren(e,["variable_declarator","declarator","property_element"],["identifier","name"],t)??this.findNameInChildren(e,["name","property_identifier","field_identifier"],t);case "module":case "internal_module":case "ambient_declaration":case "namespace_declaration":case "namespace_definition":case "mod_item":case "type_declaration":if(e.type==="namespace_definition"){for(let n of e.children)if(n.type==="namespace_name")return n.text}return this.findNameInChildren(e,["name","identifier"],t)??this.findNameInGrandchildren(e,["type_spec","type_alias","namespace_name"],["type_identifier","identifier","name"],t);case "variable_declaration":case "lexical_declaration":case "variable_declarator":return this.findNameInChildren(e,["name","identifier","variable_name"],t)??this.findNameInGrandchildren(e,["variable_declarator"],["name","identifier"],t);case "import_declaration":case "import_statement":case "import_from_statement":case "use_declaration":case "use_list":case "namespace_use_declaration":case "namespace_use_clause":case "using_directive":case "require":case "require_relative":case "preproc_include":return this.extractImportName(e);case "const_item":case "constant_declaration":return this.findNameInChildren(e,["name","identifier"],t);case "attribute_item":case "attribute":case "annotation":case "marker_annotation":case "decorator":return this.findNameInChildren(e,["name","identifier"],t)??this.findNameInGrandchildren(e,["attribute","decorator"],["identifier","name","token_tree"],t);default:return this.findNameInChildren(e,["name","identifier"],t)}}findNameInChildren(e,r,t){for(let i of r){let n=e.childForFieldName?.(i);if(n?.text)return n.text}for(let i of e.children)if(t.has(i.type))return i.text;return null}findNameInGrandchildren(e,r,t,i){for(let n of e.children)if(r.includes(n.type)){let s=this.findNameInChildren(n,t,i);if(s)return s}return null}extractImportName(e){for(let r of e.children)if(r.type==="string"||r.type==="string_literal"||r.type==="module_name"||r.type==="identifier"||r.type==="dotted_name"){let t=r.text;return (t.startsWith('"')||t.startsWith("'"))&&(t=t.slice(1,-1)),t}return e.text.slice(0,100)}getNodeText(e,r){let t=e.startPosition.row,i=e.endPosition.row;return t===i?r[t]?.trim()??"":r.slice(t,i+1).join(`
202
202
  `)}generateNodeId(e){let r=Filesystem.toUnixPath(e.file_path);return `${e.language}:${r}:${e.ast_type}:${e.name}`}};function Jt(){return new ie}var a={class_declaration:"class_declaration",class_definition:"class_definition",class_specifier:"class_specifier",interface_declaration:"interface_declaration",struct_item:"struct_item",struct_declaration:"struct_declaration",struct_specifier:"struct_specifier",type_declaration:"type_declaration",type_alias_declaration:"type_alias_declaration",enum_declaration:"enum_declaration",record_declaration:"record_declaration",function_declaration:"function_declaration",function_definition:"function_definition",function_item:"function_item",method_declaration:"method_declaration",method_definition:"method_definition",variable_declaration:"variable_declaration",lexical_declaration:"lexical_declaration",variable_declarator:"variable_declarator",assignment:"assignment",parameter:"parameter",parameter_declaration:"parameter_declaration",formal_parameter:"formal_parameter",formal_parameters:"formal_parameters",parameter_list:"parameter_list",parameters:"parameters",simple_parameter:"simple_parameter",typed_param:"typed_param",argument:"argument",field_declaration:"field_declaration",property_declaration:"property_declaration",public_field_definition:"public_field_definition",field_definition:"field_definition",property_signature:"property_signature",type_identifier:"type_identifier",type_annotation:"type_annotation",generic_type:"generic_type",named_type:"named_type",primitive_type:"primitive_type",return_type:"return_type",pointer_type:"pointer_type",reference_type:"reference_type",array_type:"array_type",sized_type_specifier:"sized_type_specifier",void_type:"void_type",predefined_type:"predefined_type",this:"this",function_declarator:"function_declarator",pointer_declarator:"pointer_declarator",declarator:"declarator",identifier:"identifier",property_identifier:"property_identifier",field_identifier:"field_identifier",name:"name",type_spec:"type_spec",super:"super",self:"self",required_parameter:"required_parameter",optional_parameter:"optional_parameter",aliased_import:"aliased_import",relative_import:"relative_import",import_prefix:"import_prefix",import_statement:"import_statement",import_from_statement:"import_from_statement",namespace_use_declaration:"namespace_use_declaration",scoped_identifier:"scoped_identifier",qualified_name:"qualified_name",dotted_name:"dotted_name",dotted_identifier:"dotted_identifier",module_name:"module_name",namespace_name:"namespace_name",system_lib_string:"system_lib_string",string_literal:"string_literal",string:"string",string_content:"string_content",interpreted_string_literal:"interpreted_string_literal",interpreted_string_literal_content:"interpreted_string_literal_content",annotation:"annotation",attribute:"attribute",member_call_expression:"member_call_expression",scoped_call_expression:"scoped_call_expression",relative_scope:"relative_scope",scoped_type_identifier:"scoped_type_identifier",constant:"constant",slice_type:"slice_type",map_type:"map_type",channel_type:"channel_type",parenthesized_type:"parenthesized_type",variable_name:"variable_name",decorated_definition:"decorated_definition",export_statement:"export_statement",namespace_use_clause:"namespace_use_clause"},Re={extends:"extends",implements:"implements"},Xe="new",le={void_any_null:new Set(["void","any","null"]),string_number_boolean:new Set(["string","number","boolean"])};function xe(y,e){e(y);for(let r of y.children)xe(r,e);}function D(y){for(let e of y.children)if(e.type===a.identifier||e.type===a.type_identifier||e.type===a.property_identifier||e.type===a.field_identifier||e.type===a.name)return e.text;return null}function Te(y){for(let e=y.children.length-1;e>=0;e--){let r=y.children[e];if(r&&(r.type===a.identifier||r.type===a.property_identifier||r.type===a.name))return r.text}return null}function we(y,e){for(let r of y.children)if(e.includes(r.type))return r;return null}function G(y,e){for(let r of y.children){if(e.includes(r.type))return r;let t=G(r,e);if(t)return t}return null}function j(y,e){for(let r of y.children)if(e.includes(r.type)){let t=D(r);if(t)return t;for(let i of r.children){let n=D(i);if(n)return n}}for(let r of y.children){let t=j(r,e);if(t)return t}return null}function pe(y){let e=y.indexOf("<");if(e<0)return y;let r=0,t=null;for(let i=e;i<y.length;i++){let n=y[i];if(t){n===t&&(t=null);continue}if(n==='"'||n==="'"||n==="`"){t=n;continue}if(n==="<")r++;else if(n===">"&&(r--,r===0))return y.slice(0,e).trim()}return y}function Ze(y){let e=A(y),r=new Set;for(let t of e.rawTypes.classTypes)r.add(F(y,t));for(let t of e.rawTypes.interfaceTypes)r.add(F(y,t));for(let t of e.rawTypes.moduleTypes)r.add(F(y,t));return r}function Xt(y){let e=A(y),r=new Set;for(let t of e.rawTypes.methodTypes)r.add(F(y,t));return r}function Zt(y){let e=A(y),r=new Set;for(let t of e.rawTypes.propertyTypes)r.add(F(y,t));return r}var ne=class{extractEdges(e,r,t,i){let n=[],s=new Map;for(let c of r){let l=s.get(c.name);l||(l=[],s.set(c.name,l)),l.push(c);}let o=new Map;for(let[c,l]of s){let d=l[0];d&&o.set(c,d);}return this.extractContainsEdges(r,n),this.extractCallEdges(e.rootNode,r,n,t,i,o),this.extractInheritanceEdges(e.rootNode,r,n,t,i,o),this.extractImportEdges(e.rootNode,r,n,t,i),this.extractTypeReferences(e.rootNode,r,n,t,i,o),this.extractAnnotationEdges(e.rootNode,r,n,t,i),this.extractHasMethodEdges(r,n,t),this.extractHasPropertyEdges(r,n,t),this.extractOverrideEdges(r,n,t,i),n}extractContainsEdges(e,r){for(let t of e)t.parent_id&&r.push({source:t.parent_id,target:this.generateNodeId(t),relation:"CONTAINS"});}extractCallEdges(e,r,t,i,n,s){let o=A(i),c=new Set(o.rawTypes.callExpressionTypes),l=new Set,d=Filesystem.toUnixPath(n),p=`${i}:${d}:module:file`;this.walkTree(e,u=>{if(c.has(u.type)){let g=this.findEnclosingFunction(u,r,s,i,n,p),f=this.extractCalleeName(u,i);if(g&&f){let h=`${i}:*:*:${f}`,m=`${g.id}|${h}|CALLS`;if(l.has(m))return;l.add(m),t.push({source:g.id,target:h,relation:"CALLS",line:(u.startPosition?.row??-1)+1,col:(u.startPosition?.column??-1)+1,filePath:n});}}});}extractInheritanceEdges(e,r,t,i,n,s){let o=A(i),c=new Set(o.rawTypes.classTypes),l=new Set(o.rawTypes.interfaceTypes),d=this.buildImportAliasMap(e,i);this.walkTree(e,p=>{if(c.has(p.type)){let u=D(p);if(!u)return;let g=Filesystem.toUnixPath(n),f=`${i}:${g}:${F(i,p.type)}:${u}`,h=we(p,[...o.inheritance.extendsClauseTypes]);h||(h=G(p,[...o.inheritance.extendsClauseTypes]));let m=[];h?(m=this.extractClauseNames(h,i),o.inheritance.stripTemplateArgs&&(m=m.map(b=>pe(b)))):o.inheritance.fallbackToFirstIdentifier&&(m=this.collectNamedIdentifiers(p).filter(b=>b!==u).slice(0,1));for(let b of m){if(!b||b===u)continue;let w=F(i,o.rawTypes.classTypes[0]??"class_declaration"),_=d.get(b)??b,T=Filesystem.toUnixPath(n),x=`${i}:${T}:${w}:${_}`;t.push({source:f,target:x,relation:"EXTENDS",line:(h?.startPosition?.row??p.startPosition?.row??-1)+1,col:(h?.startPosition?.column??p.startPosition?.column??-1)+1,filePath:n});}for(let b of o.inheritance.implementsClauseTypes){let w=we(p,[b]);if(w||(w=G(p,[b])),w){let _=this.extractClauseNames(w,i);o.inheritance.stripTemplateArgs&&(_=_.map(T=>pe(T)));for(let T of _){if(!T)continue;let x=o.rawTypes.interfaceTypes[0]??o.rawTypes.classTypes[0]??a.interface_declaration,E=d.get(T)??T,I=Filesystem.toUnixPath(n),M=`${i}:${I}:${x}:${E}`;t.push({source:f,target:M,relation:"IMPLEMENTS",line:(w?.startPosition?.row??p.startPosition?.row??-1)+1,col:(w?.startPosition?.column??p.startPosition?.column??-1)+1,filePath:n});}}}return}if(l.has(p.type)){let u=D(p);if(!u)return;let g=Filesystem.toUnixPath(n),f=`${i}:${g}:${F(i,p.type)}:${u}`;for(let h of o.inheritance.extendsClauseTypes){let m=G(p,[h]);if(m){let b=this.extractClauseNames(m,i);o.inheritance.stripTemplateArgs&&(b=b.map(w=>pe(w)));for(let w of b){if(w===u)continue;let _=F(i,o.rawTypes.interfaceTypes[0]??"interface_declaration"),T=d.get(w)??w,x=`${i}:${g}:${_}:${T}`;t.push({source:f,target:x,relation:"EXTENDS",line:(m?.startPosition?.row??p.startPosition?.row??-1)+1,col:(m?.startPosition?.column??p.startPosition?.column??-1)+1,filePath:n});}break}}}});}collectTypeAnnotations(e){let r=[],t=new Set([a.type_annotation,"type",a.reference_type,a.pointer_type,a.generic_type,a.array_type,a.named_type,a.primitive_type]),i=n=>{if(t.has(n.type)){r.push(n);return}for(let s of n.children)i(s);};return i(e),r}collectNamedIdentifiers(e){let r=[],t=new Set,i=n=>{if(n.type===a.identifier||n.type===a.type_identifier||n.type===a.attribute){let s=n.text;t.has(s)||(t.add(s),r.push(s));return}for(let s of n.namedChildren)s&&i(s);};return i(e),r}extractClauseNames(e,r){let t=[],i=new Set,n=l=>{!l||i.has(l)||(i.add(l),t.push(l));},s=new Set([a.scoped_identifier,a.scoped_type_identifier,a.qualified_name,a.dotted_name,a.dotted_identifier]),o=new Set([a.identifier,a.type_identifier,a.name,a.attribute]),c=l=>{if(s.has(l.type)){n(l.text);return}if(o.has(l.type)){if(l.type===a.name&&(l.text===Re.extends||l.text===Re.implements))return;n(l.text);return}if(l.type===a.generic_type){let d=l.childForFieldName?.("name")?.text??l.namedChildren[0]?.text;d&&n(d);return}for(let d of l.namedChildren)d&&c(d);};return c(e),t}extractImportEdges(e,r,t,i,n){let s=A(i),o=new Set(s.rawTypes.importTypes),c=new Set;this.walkTree(e,l=>{if(o.has(l.type)){let d,p=this.extractImportWholePath(l);p?d=[p]:d=this.extractImportPaths(l);for(let u of d){if(!u||c.has(u))continue;c.add(u);let g=Filesystem.toUnixPath(n),f=`${i}:${g}:module:file`;t.push({source:f,target:u,relation:"IMPORTS",line:(l.startPosition?.row??-1)+1,col:(l.startPosition?.column??-1)+1,filePath:n});}}});}walkTree(e,r){xe(e,r);}findEnclosingFunction(e,r,t,i,n,s){let o=e,c=A(i),l=new Set([...c.rawTypes.methodTypes,...c.rawTypes.functionTypes]),d=new Set([a.lexical_declaration,a.variable_declaration,a.variable_declarator,a.export_statement]),p=new Set([a.public_field_definition,a.property_declaration,a.field_declaration]),u=new Map;for(let g of r){let f=u.get(g.ast_type);f?f.push(g):u.set(g.ast_type,[g]);}for(;o;){if(l.has(o.type)){let g=null,f=new Set([c.parameters?.wrapperType??a.parameter_list,a.parameter_list]);if(o.type===a.method_declaration||o.type===a.method_definition){let h=-1;for(let m=0;m<o.childCount;m++){let b=o.children[m];if(b&&f.has(b.type)){h=m;break}}if(h>0)for(let m=h-1;m>=0;m--){let b=o.children[m];if(b&&(b.type===a.identifier||b.type===a.type_identifier||b.type===a.property_identifier)){g=b.text;break}}}if(g||(g=D(o)??j(o,[a.function_declarator,a.declarator])),g){let h=F(i,o.type),b=u.get(h)?.find(w=>{let _=w.name.split("@")[0]??w.name;return _===g||_.endsWith(`.${g}`)});if(b){let w=Filesystem.toUnixPath(b.file_path);return {id:`${b.language}:${w}:${b.ast_type}:${b.name}`,name:b.name}}return null}}if(d.has(o.type)){let g=D(o);if(g){let f=F(i,a.variable_declaration),m=u.get(f)?.find(b=>(b.name.split("@")[0]??b.name)===g);if(m){let b=Filesystem.toUnixPath(m.file_path);return {id:`${m.language}:${b}:${m.ast_type}:${m.name}`,name:m.name}}}}if(p.has(o.type)){let g=D(o);if(g){let f=F(i,a.property_declaration),m=(u.get(f)??u.get(F(i,a.public_field_definition)))?.find(b=>{let w=b.name.split("@")[0]??b.name;return w===g||w.endsWith(`.${g}`)});if(m){let b=Filesystem.toUnixPath(m.file_path);return {id:`${m.language}:${b}:${m.ast_type}:${m.name}`,name:m.name}}}}o=o.parent;}return s?{id:s,name:"file"}:null}extractCalleeName(e,r){let t=e.firstChild;if(!t)return null;if(t.type===a.constant){for(let s of e.namedChildren)if(s!==t&&(s.type===a.identifier||s.type===a.property_identifier))return `${t.text}.${s.text}`}let i=A(r),n=new Set(i.rawTypes.memberAccessTypes);if(t.type===a.variable_name&&e.type===a.member_call_expression){let s=t.text,o=e.childForFieldName?.("name");if(o)return `${s}.${o.text}`;let c=e.children.find(l=>l.type===a.name);if(c)return `${s}.${c.text}`}if(e.type===a.member_call_expression){let s=e.childForFieldName?.("name");if(s){let c=e.childForFieldName?.("object")?.text??"";return /[()]/.test(c)?s.text:`${c}.${s.text}`}}if(n.has(t.type)){let s=t.childForFieldName?.("property")?.text,o=t.childForFieldName?.("field")?.text,c=t.childForFieldName?.("name")?.text,l;for(let p=t.children.length-1;p>=0;p--){let u=t.children[p];if(u&&(u.type===a.identifier||u.type===a.property_identifier||u.type===a.name||u.type===a.field_identifier||u.type===a.constant)){l=u.text;break}}let d=s??o??c??l;if(d){let p=t.childForFieldName?.("object")??t.children[0],u=p?.text,g=new Set(i.rawTypes.contextualKeywordTypes),f=!u||u===d||(p?g.has(p.type):false)||/[()]/.test(u);return u&&!f?`${u}.${d}`:d}}if(t.type===a.relative_scope&&e.type===a.scoped_call_expression){for(let s of e.children)if(s.type===a.name)return s.text}if(t.type===a.identifier||t.type===a.property_identifier||t.type===a.name)return t.text;if(t.type===a.this){for(let s of e.children)if(s.type===a.identifier||s.type===a.property_identifier)return s.text}if(t.type===a.identifier&&t.text.includes("."))return t.text;if(t.type===a.super){for(let s of e.children)if(s.type===a.identifier||s.type===a.property_identifier)return s.text}if(t.type===a.self){for(let s of e.children)if(s.type===a.identifier||s.type===a.property_identifier)return s.text}if(t.type===Xe){for(let s of e.children)if(s.type===a.identifier||s.type===a.type_identifier||s.type===a.name||s.type===a.scoped_identifier)return s.text}return null}extractImportPaths(e){let r=this.extractPythonImportPaths(e);if(r.length>0)return r;let t=new Set([a.string,a.string_literal,a.string_content,a.interpreted_string_literal,a.interpreted_string_literal_content,a.system_lib_string]),i=new Set([a.dotted_name,a.dotted_identifier,a.scoped_identifier,a.qualified_name,a.module_name,a.namespace_name,a.name,a.identifier]),n=[],s=c=>{if(t.has(c.type)){let l=c.text;(l.startsWith('"')||l.startsWith("'")||l.startsWith("<"))&&(l=l.slice(1,-1)),n.push(l);return}for(let l of c.children)s(l);};if(s(e),n.length>0)return n;let o=c=>{if(i.has(c.type)){let l=c.text;(l.startsWith('"')||l.startsWith("'")||l.startsWith("<"))&&(l=l.slice(1,-1)),n.push(l);return}for(let l of c.children)o(l);};return o(e),n}extractPythonImportPaths(e){let r=e.type;if(r!==a.import_statement&&r!==a.import_from_statement)return [];let t=[];if(r===a.import_statement){for(let i of e.children)if(i.type===a.dotted_name)t.push(i.text);else if(i.type===a.aliased_import){let n=i.childForFieldName?.("name");if(n)t.push(n.text);else for(let s of i.children)if(s.type===a.dotted_name||s.type===a.identifier){t.push(s.text);break}}}else for(let i of e.children){if(i.type===a.dotted_name){t.push(i.text);break}if(i.type===a.relative_import){let n=i.childForFieldName?.(a.import_prefix),s=i.childForFieldName?.(a.module_name),o="";n&&(o+=n.text),s&&(o+=s.text),o?t.push(o):t.push(i.text);break}}return t}extractImportWholePath(e){let r=new Set([a.qualified_name,a.scoped_identifier,a.dotted_name,a.dotted_identifier,a.module_name,a.namespace_name,a.namespace_use_clause,a.name,a.identifier,a.string,a.string_literal,a.interpreted_string_literal,a.system_lib_string]);return (i=>{if(r.has(i.type)){let n=i.text;return (n.startsWith('"')||n.startsWith("'")||n.startsWith("<"))&&(n=n.slice(1,-1)),i.type===a.namespace_use_clause&&n.includes(" as ")&&(n=n.split(" as ")[0]??n),n}if(i.type===a.namespace_use_declaration||i.type===a.namespace_use_clause){for(let n of i.children)if(r.has(n.type)){let s=n.text;return (s.startsWith('"')||s.startsWith("'")||s.startsWith("<"))&&(s=s.slice(1,-1)),n.type===a.namespace_use_clause&&s.includes(" as ")&&(s=s.split(" as ")[0]??s),s}}return null})(e)}generateNodeId(e){let r=Filesystem.toUnixPath(e.file_path);return `${e.language}:${r}:${e.ast_type}:${e.name}`}extractTypeReferences(e,r,t,i,n,s){let o=new Set([a.function_declaration,a.function_definition,a.function_item,a.method_declaration,a.method_definition,a.variable_declaration,a.lexical_declaration,a.property_declaration,a.field_declaration,a.typed_param,a.identifier]),c=new Set([a.field_declaration,a.parameter_declaration,a.parameter]),l=new Set([a.formal_parameters,a.parameter,a.parameter_declaration,a.formal_parameter,a.simple_parameter,a.typed_param,a.argument,a.required_parameter,a.optional_parameter,a.parameter,a.parameters]);this.walkTree(e,d=>{if(o.has(d.type)&&d.type!==a.lexical_declaration&&d.type!==a.variable_declaration){let g=d.childForFieldName?.("name")?.text??Te(d)??D(d)??j(d,[a.function_declarator,a.pointer_declarator,a.declarator]);if(!g)return;let f=null,h=[a.return_type,a.type_annotation,"type",a.pointer_type,a.array_type,a.void_type];for(let T of h){for(let x of d.children)if(x.type===T){f=x;break}if(f)break}let m=new Set([a.type_identifier,a.generic_type,a.array_type,a.identifier,a.struct_specifier,a.class_specifier,a.named_type,a.primitive_type]),b=new Set([a.function_declarator,a.pointer_declarator,a.declarator]);if(!f){for(let T of d.children)if(m.has(T.type)){if(T.type===a.void_type)continue;let x=Te(d);if(x&&T.text===x||b.has(T.type))continue;f=T;break}}let w=new Set([a.type_identifier,a.pointer_type,a.array_type]);if(!f){let T=false;for(let x of d.children){if(x.type==="->"||x.text==="->"){T=true;continue}if(T&&w.has(x.type)){f=x;break}}}if(f){let T=this.extractTypeName(f);if(T&&!le.void_any_null.has(T)){let x=this.resolveTypeNodeId(T,i,n);x&&t.push({source:this.generateNodeIdFromName(g,d.type,i,n),target:x,relation:"TYPE_REFERENCES",line:(f.startPosition?.row??-1)+1,col:(f.startPosition?.column??-1)+1,filePath:n});}}let _=G(d,["type_parameter","generic_type"]);if(_){let T=this.extractTypeName(_);if(T){let x=this.resolveTypeNodeId(T,i,n);x&&t.push({source:this.generateNodeIdFromName(g,d.type,i,n),target:x,relation:"TYPE_REFERENCES",line:(_.startPosition?.row??-1)+1,col:(_.startPosition?.column??-1)+1,filePath:n});}}}if(c.has(d.type)){let g=this.findEnclosingClass(d,r);if(g){for(let f of d.children)if(f.type===a.type_identifier){let h=f.text,m=this.resolveTypeNodeId(h,i,n);m&&t.push({source:g.id,target:m,relation:"TYPE_REFERENCES",line:(f.startPosition?.row??-1)+1,col:(f.startPosition?.column??-1)+1,filePath:n});}}}let p=new Set([a.type_annotation,a.annotation,"type",a.reference_type,a.pointer_type,a.type_identifier,a.struct_specifier,a.class_specifier,a.array_type,a.sized_type_specifier,a.named_type,a.primitive_type,a.slice_type,a.array_type,a.map_type,a.channel_type]);if(l.has(d.type)){for(let g of d.children)if(p.has(g.type)){let f=this.extractTypeName(g);if(f&&!le.string_number_boolean.has(f)){let h=this.resolveTypeNodeId(f,i,n);if(h){let m=this.findEnclosingFunction(d,r,s,i,n);m&&t.push({source:m.id,target:h,relation:"TYPE_REFERENCES",line:(g.startPosition?.row??-1)+1,col:(g.startPosition?.column??-1)+1,filePath:n});}}}if((i==="zig"||i==="csharp")&&d.type===a.parameter&&d.children.length>=2){let g=i==="zig"?2:0,f=d.children[g];if(f&&f.type===a.identifier){let h=f.text;if(h&&!le.string_number_boolean.has(h)){let m=this.resolveTypeNodeId(h,i,n);if(m){let b=this.findEnclosingFunction(d,r,s,i,n);b&&t.push({source:b.id,target:m,relation:"TYPE_REFERENCES",line:(f.startPosition?.row??-1)+1,col:(f.startPosition?.column??-1)+1,filePath:n});}}}}}if(new Set([a.variable_declaration,a.lexical_declaration,a.public_field_definition,a.field_definition,a.field_declaration,a.property_declaration,a.property_signature,a.assignment]).has(d.type)){let g=this.collectTypeAnnotations(d);for(let f of g){let h=this.extractTypeName(f);if(h&&!le.string_number_boolean.has(h)&&h!=="any"){let m=this.resolveTypeNodeId(h,i,n);if(m){let b=D(d)??j(d,["variable_declarator"])??D(d);b&&t.push({source:this.generateNodeIdFromName(b,"variable_declaration",i,n),target:m,relation:"TYPE_REFERENCES",line:(f.startPosition?.row??-1)+1,col:(f.startPosition?.column??-1)+1,filePath:n});}}}}});}extractHasMethodEdges(e,r,t){let i=Ze(t),n=Xt(t);this.emitContainerToMemberEdges(e,r,i,n,"HAS_METHOD");}extractHasPropertyEdges(e,r,t){let i=Ze(t),n=Zt(t);this.emitContainerToMemberEdges(e,r,i,n,"HAS_PROPERTY");}emitContainerToMemberEdges(e,r,t,i,n){let s=new Map;for(let o of e){let c=s.get(o.file_path);c||(c=[],s.set(o.file_path,c)),c.push(o);}for(let o of s.values()){o.sort((l,d)=>l.start_line-d.start_line);let c=[];for(let l of o){for(;c.length>0&&(c[c.length-1]?.end_line??1/0)<l.start_line;)c.pop();if(t.has(l.ast_type))c.push(l);else if(i.has(l.ast_type)){let d=c[c.length-1];if(d){let p=this.generateNodeId(d),u=this.generateNodeId(l);r.push({source:p,target:u,relation:n});}}}}}extractOverrideEdges(e,r,t,i){let n=A(t),s=new Set;for(let d of n.rawTypes.classTypes)s.add(F(t,d));for(let d of n.rawTypes.interfaceTypes)s.add(F(t,d));let o=e.filter(d=>s.has(d.ast_type));if(o.length===0)return;let c=new Map;for(let d of e){let p=c.get(d.file_path);p||(p=[],c.set(d.file_path,p)),p.push(d);}let l=new Map;for(let d of r)if(d.relation==="EXTENDS"){let p;for(let g of c.values())if(p=g.find(f=>this.generateNodeId(f)===d.target),p)break;if(!p)continue;let u=l.get(d.source);u||(u=[],l.set(d.source,u)),u.push(p);}for(let d of o){let p=l.get(this.generateNodeId(d))??[];if(p.length===0)continue;let u=this.collectMemberIdsByName(d,c,"HAS_METHOD",t);if(u.size===0)continue;let g=new Set,f=[],h=[...p];for(;h.length>0;){let m=h.shift();if(g.has(this.generateNodeId(m)))continue;g.add(this.generateNodeId(m)),f.push(m);let b=l.get(this.generateNodeId(m))??[];h.push(...b);}for(let[m,b]of u){let w=b[0];if(!w)continue;let _=null;for(let T of f){let E=this.collectMemberIdsByName(T,c,"HAS_METHOD",t).get(m);if(!(!E||E.length===0)){_=E[0]??null;break}}if(_&&_!==w){let T=this.generateNodeId(d);if(r.some(I=>I.relation==="METHOD_OVERRIDES"&&I.source===T&&I.target===_))continue;r.push({source:T,target:_,relation:"METHOD_OVERRIDES"});}}}}collectMemberIdsByName(e,r,t,i){let n=new Map,s=r.get(e.file_path);if(!s)return n;let o=new Set([a.method_definition,a.method_declaration,a.function_definition]);for(let c of s)if(o.has(c.ast_type)&&c.start_line>=e.start_line&&c.end_line<=e.end_line){let l=c.metadata?.originalName??c.name,d=c.metadata?.parameterTypes??[],p=d.length>0?`${l}|${d.join(",")}`:l,u=n.get(p);u||(u=[],n.set(p,u));let g=this.generateNodeId(c);u.push(g);}return n}buildImportAliasMap(e,r){let t=new Map;return this.walkTree(e,i=>{if(i.type===a.namespace_use_clause){let n=i.children,s=n.findIndex(o=>o.type==="as");if(s>=0){let o=n.slice(0,s).find(l=>l.type===a.qualified_name),c=n[s+1];o&&c&&c.type===a.name&&c.text&&t.set(c.text,o.text);}}}),t}findEnclosingClass(e,r){let t=e.parent,i=new Set([a.class_declaration,a.class_definition,a.struct_specifier,a.struct_declaration,a.struct_item,a.type_declaration,a.record_declaration,a.class_specifier,a.enum_declaration]);for(;t;){if(i.has(t.type)){let n=D(t)??j(t,[a.type_spec,a.name]);if(n){let s=r.find(d=>d.name===n);if(s)return {id:this.generateNodeId(s),name:n};let o=r[0],c=o?.language??"ts",l=o?.file_path??"";return {id:`${c}:${l}:${t.type}:${n}`,name:n}}}t=t.parent;}return null}extractAnnotationEdges(e,r,t,i,n){let s=A(i),o=new Set(s.rawTypes.annotationTypes),c=new Set(s.annotation.annotatableTypes);this.walkTree(e,l=>{if(o.has(l.type)){let d=this.extractTypeName(l)||D(l);if(!d)return;let p=l.parent;for(;p;){if(c.has(p.type)){let u=D(p),g=p.type;if(!u&&(p.type===a.decorated_definition||p.type===a.export_statement)){let f=j(p,[a.function_definition,a.class_definition,a.method_definition,a.function_declaration,a.method_declaration]),h=G(p,[a.function_definition,a.class_definition,a.method_definition,a.function_declaration,a.method_declaration]);f&&(u=f,g=h?.type??"function_definition");}if(u){let f=this.generateNodeIdFromName(u,g,i,n),h=Filesystem.toUnixPath(n),m=`${i}:${h}:annotation:${d}`;t.push({source:m,target:f,relation:"ANNOTATES",line:(l.startPosition?.row??-1)+1,col:(l.startPosition?.column??-1)+1,filePath:n});}break}p=p.parent;}}});}extractTypeName(e){if(e.type===a.type_identifier||e.type===a.identifier||e.type===a.predefined_type||e.type===a.name)return e.text;let r=new Set([a.type_identifier,a.identifier,a.name]);for(let i of e.children)if(r.has(i.type))return i.text;for(let i of e.children)if(i.type===a.predefined_type)return i.text;let t=new Set([a.pointer_type,a.reference_type,a.array_type,a.generic_type,a.slice_type,a.map_type,a.channel_type,a.parenthesized_type]);for(let i of e.children)if(t.has(i.type)){let n=this.extractTypeName(i);if(n)return n}return null}resolveTypeNodeId(e,r,t){let i=[a.class_declaration,a.interface_declaration,a.type_alias_declaration,a.type_declaration,a.enum_declaration,a.struct_declaration];for(let n of i)return `${r}:${Filesystem.toUnixPath(t)}:${n}:${e}`;return null}generateNodeIdFromName(e,r,t,i){return `${t}:${Filesystem.toUnixPath(i)}:${F(t,r)}:${e}`}};function er(){return new ne}var $=Log.create({service:"codebase.indexer"}),ae=class{constructor(e,r,t,i){a$1(this,"db");a$1(this,"parserManager");a$1(this,"nodeExtractor");a$1(this,"edgeExtractor");a$1(this,"config");a$1(this,"writeProxy",null);this.db=e,this.parserManager=r,this.nodeExtractor=new ie,this.edgeExtractor=new ne,this.config=t,this.writeProxy=i??null;}async flushPendingWrites(){this.writeProxy&&await this.writeProxy.flush();}get dbWriter(){return this.writeProxy?this.writeProxy:this.db}generateNodeEmbeddingText(e){return [e.name,e.ast_type,e.language,e.text].join(" | ")}async embedText(e){if(!this.config.embedding)return null;try{let r=this.computeHash(e),t=this.db.getCachedEmbedding?.(r);if(t)return new Float32Array(t.buffer,t.byteOffset,t.length/4);let n=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(n){let s=new Float32Array(n);return this.dbWriter.cacheEmbedding?.(r,s),s}return null}catch{return null}}async indexFile(e,r){var l=[];try{let t=Date.now();let i=b$1(l,$.time("indexFile",{level:"DEBUG",filePath:e}));let n=[];let s=0;let o=0;let c=null;try{let g=this.parserManager.detectLanguage(e);if(!g)throw new b.IndexError({message:"Unsupported file type",filePath:e});r?.({currentFile:e,processed:0,total:1,stage:"parsing"});let f=await this.readFile(e),h=this.computeHash(f);if(this.config.incremental&&this.db.getFileHash(e)===h)return {success:!0,filesProcessed:1,nodesCreated:0,edgesCreated:0,errors:[],duration:Date.now()-t};this.dbWriter.deleteEdgesByFile(e),this.db.deleteFtsByFile(e),this.dbWriter.deleteNodesByFile(e),this.writeProxy&&await this.writeProxy.flush(),r?.({currentFile:e,processed:0,total:1,stage:"extracting"}),c=this.parserManager.parse(f,g);let m=this.nodeExtractor.extractNodes(c,f,g,e);s=m.length;let b$1=this.edgeExtractor.extractEdges(c,m,g,e);r?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(m);let w=this.getValidEdgeCount(b$1,m);this.storeEdges(b$1,m),o=w,this.config.embedding&&m.length>0&&(r?.({currentFile:e,processed:0,total:1,stage:"embedding"}),await this.embedNodes(m)),this.dbWriter.setFileHash(e,h),this.writeProxy&&this.writeProxy.flush();}catch(g){n.push({filePath:e,error:errorMeta(g).message});}finally{if(c)try{c.delete();}catch(g){$.warn("tree.delete failed",{filePath:e,error:errorMeta(g)});}}return {success:n.length===0,filesProcessed:1,nodesCreated:s,edgesCreated:o,errors:n,duration:Date.now()-t}}catch(d){var p=d,u=true;}finally{c(l,p,u);}}async indexDirectory(e,r){var d=[];try{let t=Date.now();let i=b$1(d,$.time("indexDirectory",{level:"DEBUG",dir:e}));let n=e??this.config.workspaceDir;let s=[];let o=0;let c=0;let l=0;try{let f=await this.scanFiles(n);for(let _ of f.readErrors)s.push(_);let h=f.results,m=h.length,b=0,w=_=>{r&&r({currentFile:_.currentFile,processed:b,total:h.length,stage:_.stage});};for(let _=0;_<h.length;_+=this.config.batchSize){let T=h.slice(_,_+this.config.batchSize),x=await Promise.all(T.map(E=>this.indexFile(E.filePath,w)));for(let E of x)o++,b++,c+=E.nodesCreated,l+=E.edgesCreated,!E.success&&E.errors.length>0&&s.push(...E.errors);}if(r&&h.length>0){let _=h[h.length-1]?.filePath??"";r({currentFile:_,processed:h.length,total:h.length,stage:"storing"});}}catch(f){s.push({filePath:n,error:errorMeta(f).message});}this.dbWriter.setLastSync();this.writeProxy&&await this.writeProxy.flush();return {success:s.length===0,filesProcessed:o,nodesCreated:c,edgesCreated:l,errors:s,duration:Date.now()-t}}catch(p){var u=p,g=true;}finally{c(d,u,g);}}async sync(e){var f=[];try{let r=Date.now();let t=b$1(f,$.time("sync",{level:"DEBUG"}));let i=[];let n=0;let s=0;let o=0;let c=0;let l=0;let d=0;try{let w=await this.scanFiles(this.config.workspaceDir),_=w.results;for(let N of w.readErrors)i.push(N);let T=new Set(_.map(N=>N.filePath)),x=this.db.getAllFileHashes(),E=new Set(x.map(N=>N.file_path));for(let N of x)T.has(N.file_path)||(this.dbWriter.deleteFtsByFile?.(N.file_path),this.dbWriter.deleteNodesByFile(N.file_path),this.dbWriter.deleteEdgesByFile(N.file_path),this.dbWriter.deleteFileHash(N.file_path),o++);let I=_.length,M=0,J=N=>{e&&e({currentFile:N.currentFile,processed:M,total:I,stage:N.stage});},v=Math.max(1,this.config.batchSize),Q=new Map;for(let N of x)Q.set(N.file_path,N.content_hash);for(let N=0;N<_.length;N+=v){let Z=_.slice(N,N+v),H=await Promise.all(Z.map(L=>{let O=Q.get(L.filePath);return O?O!==L.contentHash?this.indexFile(L.filePath,J).then(oe=>({file:L,kind:"updated",r:oe})):Promise.resolve({file:L,kind:"skipped",r:null}):this.indexFile(L.filePath,J).then(oe=>({file:L,kind:"added",r:oe}))}));for(let{kind:L,r:O}of H)L==="skipped"?c++:O&&(O.success?O.nodesCreated===0?c++:(L==="added"?n++:s++,l+=O.nodesCreated,d+=O.edgesCreated):i.push(...O.errors));M+=Z.length;}if(e&&I>0){let N=_[_.length-1]?.filePath??"";e({currentFile:N,processed:I,total:I,stage:"storing"});}this.writeProxy&&await this.writeProxy.flush();let X=new Set(this.db.queryAll("SELECT DISTINCT file_path FROM nodes").map(N=>N.file_path)),fe=this.db.getAllFileHashes().filter(N=>!X.has(N.file_path)).map(N=>N.file_path);for(let N of fe)this.dbWriter.deleteFileHash(N);}catch(w){i.push({filePath:this.config.workspaceDir,error:errorMeta(w).message});}this.dbWriter.setLastSync();this.writeProxy&&await this.writeProxy.flush();let p=new Date().toISOString();let u=Date.now()-r;let g={timestamp:p,success:i.length===0,filesAdded:n,filesUpdated:s,filesDeleted:o,filesSkipped:c,nodesCreated:l,edgesCreated:d,errorCount:i.length,errors:i,duration:u};this.db.setMeta("lastSyncResult",JSON.stringify(g));return {success:i.length===0,filesAdded:n,filesUpdated:s,filesDeleted:o,filesSkipped:c,nodesCreated:l,edgesCreated:d,errors:i,duration:u}}catch(h){var m=h,b=true;}finally{c(f,m,b);}}async scanFiles(e){let r=[],t=[],n=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(m=>`**/*${m}`),s=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts","**/.easbot/**","**/.codebase/**"],o=this.config.ignorePatterns.map(m=>m.includes("/")||m.includes("*")?m:`**/${m}/**`),c=[...s,...o],l=await this.loadGitignore(e),d=new Set;for(let m of n){let b=await Glob.scan(m,{cwd:e,absolute:true,include:"file",dot:false,symlink:false,ignore:c});for(let w of b)d.has(w)||d.add(w);}let p=Array.from(d),u=Filesystem.toUnixPath(e),g=l?p.filter(m=>!l.ignores(this.toRelativePosix(m,u),false)):p,f=Math.max(1,Number.parseInt(process.env.EASBOT_SCAN_BATCH_SIZE??"50",10)||50),h=[];for(let m of g){let b=Filesystem.normalize(m);this.parserManager.detectLanguage(b)&&h.push(b);}for(let m=0;m<h.length;m+=f){let b=h.slice(m,m+f),w=await Promise.all(b.map(async _=>{try{let T=await this.readFile(_),x=this.computeHash(T),E=this.parserManager.detectLanguage(_);return E?{filePath:_,language:E,contentHash:x,content:T}:null}catch(T){let x=errorMeta(T);return t.push({filePath:_,error:x.message}),$.warn("scanFiles read failed",{filePath:_,error:x}),null}}));for(let _ of w)_&&r.push(_);}return {results:r,readErrors:t}}async loadGitignore(e){try{let r=`${Filesystem.toUnixPath(e)}/.gitignore`,t=await et.readFile(r,"utf-8"),i=Ignore.create();return i.add(t),$.debug("Loaded .gitignore",{path:r,lines:t.split(`
203
- `).length}),i}catch(r){return r.code!=="ENOENT"&&$.warn("Failed to read .gitignore, falling back to defaultIgnore only",{error:errorMeta(r)}),null}}toRelativePosix(e,r){let t=Filesystem.toUnixPath(e),i=Filesystem.toUnixPath(r),n=t;return i&&n.startsWith(i)&&(n=n.slice(i.length)),(i.endsWith("/")&&n.startsWith("/")||n.startsWith("/"))&&(n=n.slice(1)),n}async readFile(e){try{return await et.readFile(e,"utf-8")}catch(r){throw new b.FileSystemError({message:"Failed to read file",filePath:e},{cause:r})}}computeHash(e){return createHash("sha256").update(e).digest("hex")}storeNodes(e){let r=e.map(t=>({id:this.nodeExtractor.generateNodeId(t),name:t.name,ast_type:t.ast_type,language:t.language,file_path:t.file_path,start_line:t.start_line,start_col:t.start_col,end_line:t.end_line,end_col:t.end_col,text:t.text,created_at:new Date().toISOString()}));this.dbWriter.insertNodes(r),e.length>0&&this.storeNameSegments(e);}storeNameSegments(e){let r=[];for(let t of e){let i=this.splitIdentifier(t.name);for(let n of i)n.length>0&&r.push({segment:n,name:t.name});}if(r.length!==0)try{this.db.insertNameSegmentsBatch(r);}catch(t){$.warn("insertNameSegmentsBatch failed, falling back to per-row insert",{batchSize:r.length,error:errorMeta(t)});for(let{segment:i,name:n}of r)try{this.db.insertNameSegment(i,n);}catch(s){$.warn("insertNameSegment failed",{nodeName:n,segment:i,error:errorMeta(s)});}}}splitIdentifier(e){if(!e||e.length===0)return [];let r=[],n=e.replace(/[-_]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2");for(let s of n.split(/\s+/)){let o=s.toLowerCase();o.length>0&&r.push(o);}return r}storeEdges(e,r){let t=new Set(r.map(o=>this.nodeExtractor.generateNodeId(o))),i=new Set(["CALLS","IMPORTS"]),n=new Set(["IMPORTS"]),s=e.filter(o=>o.source===o.target?false:n.has(o.relation)||t.has(o.source)?i.has(o.relation)?true:t.has(o.target):false).map((o,c)=>({id:`${o.source}:${o.relation}:${o.target}:${c}`,source:o.source,target:o.target,relation:o.relation,created_at:new Date().toISOString()}));s.length>0&&this.dbWriter.insertEdges(s),this.storeUnresolvedRefs(e,r,t);}storeUnresolvedRefs(e,r,t){let i=new Map,n=(d,p)=>{let u=i.get(d);u||(u=[],i.set(d,u)),u.includes(p)||u.push(p);};for(let d of r){let p=this.nodeExtractor.generateNodeId(d);n(d.name,p);let u=d.metadata?.originalName;typeof u=="string"&&u.length>0&&n(u,p);let g=d.name.lastIndexOf("@");if(g>0){let f=d.name.slice(0,g),h=f.lastIndexOf(".");h>0&&n(f.slice(h+1),p);}}let s=r[0]?.file_path??"",o=r[0]?.language??"unknown",c=new Set(["CALLS","IMPORTS"]),l=[];for(let d of e){if(c.has(d.relation))continue;let p=t.has(d.source),u=t.has(d.target);if(p&&u)continue;let g=p?d.target:d.source,f=p?d.source:t.has(d.target)?d.target:void 0,h=g.includes(":")?g.split(":").pop()??g:g,m=i.get(h)??[];l.push({fromNodeId:f,referenceName:g,referenceKind:d.relation,line:d.line,col:d.col,filePath:d.filePath??s,language:o,candidates:m.length>0?m:void 0});}l.length!==0&&this.dbWriter.insertUnresolvedRefsBatch(l);}getValidEdgeCount(e,r){let t=new Set(r.map(s=>this.nodeExtractor.generateNodeId(s))),i=new Set(["CALLS","IMPORTS"]),n=new Set(["IMPORTS"]);return e.filter(s=>n.has(s.relation)||t.has(s.source)?i.has(s.relation)?true:t.has(s.target):false).length}async embedNodes(e){if(!this.config.embedding)return;let r=this.config.embedding.maxEmbeddingsPerCall||10,t=this.chunkArray(e,r),i=[],n=4,s=t.map((c,l)=>({index:l,batch:c})),o=[];for(let c=0;c<s.length;c+=n){let l=s.slice(c,c+n),d=await Promise.all(l.map(async({index:p,batch:u})=>{let g=[],f=u.map(h=>this.generateNodeEmbeddingText(h));try{let h=await this.config.embedding.doEmbed({values:f});for(let m=0;m<u.length;m++){let b=u[m];if(!b)continue;let w=h.embeddings[m];if(w){let _=new Float32Array(w),T=this.computeHash(this.generateNodeEmbeddingText(b));this.dbWriter.cacheEmbedding?.(T,_),g.push({nodeId:this.nodeExtractor.generateNodeId(b),embeddingText:f[m]||"",embedding:_});}}}catch{for(let m of u){if(!m)continue;let b=this.generateNodeEmbeddingText(m),w=await this.embedText(b);w&&g.push({nodeId:this.nodeExtractor.generateNodeId(m),embeddingText:b,embedding:w});}}return {index:p,embeddings:g}}));o.push(...d);}o.sort((c,l)=>c.index-l.index);for(let c of o)i.push(...c.embeddings);i.length>0&&this.dbWriter.storeNodeEmbeddings?.(i);}chunkArray(e,r){let t=[];for(let i=0;i<e.length;i+=r)t.push(e.slice(i,i+r));return t}};function ar(y,e,r){return new ae(y,e,r)}function Ae(y){if(!y)return [];let e=y.split(/[^a-zA-Z0-9]+/),r=[];for(let t of e){if(!t)continue;let i=t.match(/[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|\d+/g);i&&r.push(...i);}return r.map(t=>t.toLowerCase()).filter(t=>t.length>0)}function tt(y,e){if(y.length===0||e.length===0)return 0;let r=0;for(let t of y)e.includes(t)&&r++;return r/y.length}function rt(y,e,r={}){let t=r.limit??20,i=r.minScore??.2;if(!y)return [];let n=Ae(y),s=[];for(let o of e){let c=o.id.split(":").pop()??"";if(c===y||o.name===y){s.push({nodeId:o.id,score:1,matchedPart:"full"});continue}let l=Ae(c),d=Ae(o.name),p=tt(n,l),u=tt(n,d),g=Math.max(p,u);g>=i&&s.push({nodeId:o.id,score:g,matchedPart:g>=.99?"full":"segment"});}return s.sort((o,c)=>c.score-o.score),s.slice(0,t)}var Me=Filesystem.toUnixPath,C=Log.create({service:"codebase.query"}),dr=new Set(["AND","OR","NOT","NEAR"]);function lr(y){return y?y.split(/\s+/).flatMap(r=>r.split(/[^\p{L}\p{N}_]+/u)).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>!dr.has(r.toUpperCase())).join(" "):""}var se=class{constructor(e,r,t={maxResults:20,minScore:.1,hybrid:{enabled:true,vectorWeight:.7,textWeight:.3}}){a$1(this,"db");a$1(this,"embedding");a$1(this,"config");this.db=e,this.embedding=r,this.config=t;}async search(e,r={}){let{maxResults:t=this.config.maxResults,minScore:i=this.config.minScore,language:n,filePath:s,astType:o,enableFts:c=true,includeEdges:l=true,edgesLimit:d=100,vectorWeight:p=this.config.hybrid.vectorWeight,textWeight:u=this.config.hybrid.textWeight,enableEmbedding:g=true}=r,f=resolveSqlTextLimit(r.snippetMaxChars??SQL_TEXT_LIMIT_DEFAULT);C.debug("search() called",{query:e,astType:o,language:n,enableEmbedding:g,enableFts:c,minScore:i});let h=[],m=new Map;if(g&&this.embedding){let _=await this.vectorSearchNodes(e,t*2,i,void 0,f);C.debug("vectorSearchNodes results",{count:_.length,astTypeFilter:o});for(let T of _){if(n&&T.language!==n||o&&T.astType!==o)continue;let x={...T,source:"vector",vectorScore:T.score,hybridScore:T.score*p};h.push(x),m.set(x.id,x);}C.debug("after vector filter",{resultsCount:h.length});}if(c&&this.db.isFtsAvailable()){let _=lr(e);_||C.debug("FTS query sanitized to empty \u2014 skipping FTS",{originalQuery:e});let T=_?this.db.searchNodesFts(_,t*2):[];C.debug("FTS results before filter",{count:T.length});for(let x of T){if(n&&x.language!==n||s&&!x.file_path.includes(Me(s))||o&&x.ast_type!==o)continue;let E=this.normalizeScore(x.score),I=m.get(x.id);if(I)I.ftsScore=E,I.hybridScore=I.vectorScore*p+E*u;else {let M={id:x.id,name:x.name,astType:x.ast_type,language:x.language,filePath:x.file_path,text:x.text,snippet:x.text.slice(0,f),startLine:x.start_line,startCol:x.start_col,endLine:x.end_line,endCol:x.end_col,score:E,source:"fts",ftsScore:E,hybridScore:E*u};h.push(M),m.set(M.id,M);}}C.debug("after FTS filter",{resultsCount:h.length});}if(!c||!this.db.isFtsAvailable()||h.length===0){try{let _=this.db.queryNodes({limit:t*2,astType:o,language:n,filePath:s}),T=new Set(h.map(v=>v.id)),x=e.toLowerCase(),E=x.split(/\s+/).filter(v=>v.length>0),I=v=>v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),M=E.map(v=>({term:v,regex:new RegExp(I(v),"gi")})),J=[];for(let v of _){if(s&&!v.file_path.includes(Me(s)))continue;let Q=v.name.toLowerCase(),X=v.text.toLowerCase(),fe=0;if(M.some(({term:H})=>Q.includes(H))){let H=0;for(let{regex:L}of M){let O=Q.match(L);H+=O?O.length:0;}fe=.8*Math.min(H/M.length,1);}let N=0;if(M.some(({term:H})=>X.includes(H))){let H=0;for(let{regex:oe}of M){let Oe=X.match(oe);H+=Oe?Oe.length:0;}N=.5*Math.min(H/M.length,1);let L=X.indexOf(x),O=L===-1?0:Math.max(0,1-L/X.length)*.2;N+=O;}let Z=Math.max(fe,N);Z>0&&J.push({id:v.id,name:v.name,astType:v.ast_type,language:v.language,filePath:v.file_path,text:v.text,snippet:v.text.slice(0,f),startLine:v.start_line,startCol:v.start_col,endLine:v.end_line,endCol:v.end_col,score:Z,source:"basic",hybridScore:Z});}J.sort((v,Q)=>Q.score-v.score),h.push(...J.slice(0,t));}catch{}if(h.length===0)try{let _=this.db.queryNodes({limit:1e3}),T=rt(e,_,{limit:t,minScore:.5});C.debug("name-segment matches",{count:T.length,query:e});for(let x of T){let E=this.db.getNodeById(x.nodeId);if(!E||n&&E.language!==n||o&&E.ast_type!==o||s&&!E.file_path.includes(Me(s)))continue;let I={id:E.id,name:E.name,astType:E.ast_type,language:E.language,filePath:E.file_path,text:E.text??"",snippet:(E.text??"").slice(0,f),startLine:E.start_line??0,startCol:E.start_col??0,endLine:E.end_line??0,endCol:E.end_col??0,score:x.score,source:"structural",hybridScore:x.score};h.push(I),m.set(I.id,I);}}catch(_){C.errorDegradable("name-segment channel error",{error:errorMeta(_)});}}let b=h.filter(_=>_.hybridScore>=i).sort((_,T)=>T.hybridScore-_.hybridScore).slice(0,t);b.length===0&&c&&this.db.isFtsAvailable()&&(!g||!this.embedding)&&(b=h.sort((_,T)=>T.hybridScore-_.hybridScore).slice(0,t),C.warn("q.search: FTS-only minScore threshold too strict, falling back to minScore=0",{originalMinScore:i,ftsRawCount:h.filter(_=>_.source==="fts").length,preservedHits:b.length}));let w=b.map(_=>({id:_.id,name:_.name,ast_type:_.astType,language:_.language,file_path:_.filePath,start_line:_.startLine,start_col:_.startCol,end_line:_.endLine,end_col:_.endCol,text:_.text,created_at:new Date().toISOString()}));if(l&&w.length>0){let _=w.map(E=>E.id),T=this.db.queryEdges({sourceOrTarget:_}),x=new Map;for(let E of T)E.source!==E.target&&(x.has(E.source)||x.set(E.source,[]),x.get(E.source).push(E));return w.map(E=>{let I=x.get(E.id)||[];return {...E,edges:I.slice(0,d)}})}return w.map(_=>({..._,edges:[]}))}async vectorSearchNodes(e,r,t,i,n=resolveSqlTextLimit(SQL_TEXT_LIMIT_DEFAULT)){if(C.debug("vectorSearchNodes start",{query:e,limit:r,minScore:t,hasEmbedding:!!this.embedding,candidateCount:i?.length}),!this.embedding)return C.debug("vectorSearchNodes skip - no embedding model"),[];let s=await this.embedText(e);if(!s)return C.debug("vectorSearchNodes skip - no embedding result"),[];let o=new Float32Array(s),c,l=5e3;if(i&&i.length>0){let f=i.map(()=>"?").join(",");c=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${f})`,i);}else c=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[l]);C.debug("vectorSearchNodes vectors loaded",{count:c.length});let d=[];for(let f of c){let h=new Float32Array(f.embedding.buffer,f.embedding.byteOffset,f.embedding.length/4),m=this.cosineSimilarity(o,h);m<t||(d.push({nodeId:f.node_id,score:m}),d.length>r&&(d.sort((b,w)=>w.score-b.score),d.splice(r)));}if(d.length===0)return C.debug("vectorSearchNodes done - no results above minScore"),[];d.sort((f,h)=>h.score-f.score);let p=d.map(f=>f.nodeId);C.debug("vectorSearchNodes query nodes",{nodeIdsCount:p.length});let u=this.db.queryNodes({ids:p}),g=new Map(d.map(f=>[f.nodeId,f.score]));return C.debug("vectorSearchNodes done",{nodesFound:u.length}),u.map(f=>({id:f.id,name:f.name,astType:f.ast_type,language:f.language,filePath:f.file_path,text:f.text??"",snippet:(f.text??"").slice(0,n),startLine:f.start_line??0,startCol:f.start_col??0,endLine:f.end_line??0,endCol:f.end_col??0,score:g.get(f.id)||0,source:"vector"}))}async getEdgesForNode(e,r=100){let t=this.db.queryEdges({sourceOrTarget:[e.id],limit:r});return {...e,edges:t}}async embedText(e){if(!this.embedding)return null;try{let t=(await this.embedding.doEmbed({values:[e]})).embeddings[0];return t?new Float32Array(t):null}catch{return null}}cosineSimilarity(e,r){let t=0,i=0,n=0;for(let s=0;s<e.length;s++){let o=e[s],c=r[s];t+=o*c,i+=o*o,n+=c*c;}return i===0||n===0?0:t/(Math.sqrt(i)*Math.sqrt(n))}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){C.debug("queryNodes() called",{language:e.language,astType:e.astType,filePath:e.filePath?.slice(0,80),name:e.name,limit:e.limit});try{return this.db.queryNodes(e)}catch(r){throw new b.QueryError({message:"Failed to query nodes",params:{filter:e}},{cause:r})}}queryEdges(e){C.debug("queryEdges() called",{source:e.source?.split(":").slice(-2).join(":"),target:e.target?.split(":").slice(-2).join(":"),sourceOrTarget:Array.isArray(e.sourceOrTarget)?e.sourceOrTarget.map(r=>r.split(":").slice(-2).join(":")):void 0,relation:e.relation,limit:e.limit});try{return this.db.queryEdges(e)}catch(r){throw new b.QueryError({message:"Failed to query edges",params:{filter:e}},{cause:r})}}queryEdgesWithNodes(e){let r=this.db.queryEdges(e),t=[];for(let i of r){let n=this.db.getNodeById(i.source),s=this.db.getNodeById(i.target);n&&s&&t.push({edge:i,sourceNode:n,targetNode:s});}return t}queryNeighbors(e,r={}){let{relationTypes:t,direction:i="both",limit:n=100}=r;C.debug("queryNeighbors() called",{nodeId:e.split(":").slice(-2).join(":"),relationTypes:t,direction:i,limit:n});let s=[],o=[],c=new Set,l=new Set,d=t&&t.length>0?t:[void 0],p=u=>{for(let g of d){let f=g===void 0?{}:{relation:g},h=u==="outgoing"?this.db.queryEdges({source:e,...f,limit:n}):this.db.queryEdges({target:e,...f,limit:n});for(let m of h){if(l.has(m.id))continue;l.add(m.id),s.push(m);let b=u==="outgoing"?m.target:m.source,w=this.db.getNodeById(b);w&&!c.has(w.id)&&(o.push(w),c.add(w.id));}}};return (i==="outgoing"||i==="both")&&p("outgoing"),(i==="incoming"||i==="both")&&p("incoming"),{nodes:o.slice(0,n),edges:s.slice(0,n)}}queryCallGraph(e,r=2){let t=new Map,i=new Set,n=(s,o)=>{if(o>r||i.has(s))return;i.add(s);let c=[],l=[],d=this.db.queryEdges({target:s,relation:"CALLS"});for(let u of d)c.push(u.source),n(u.source,o+1);let p=this.db.queryEdges({source:s,relation:"CALLS"});for(let u of p)l.push(u.target),n(u.target,o+1);t.set(s,{callers:c,callees:l});};return n(e,0),t}queryInheritance(e){C.debug("queryInheritance() called",{nodeId:e.split(":").slice(-2).join(":")});let r=[],t=[],i=new Set,n=new Set,s=c=>{if(i.has(c))return;i.add(c);let l=this.db.queryEdges({source:c,relation:"EXTENDS"}),d=this.db.queryEdges({source:c,relation:"IMPLEMENTS"});for(let p of [...l,...d]){let u=this.db.getNodeById(p.target);u&&(r.push(u),s(p.target));}},o=c=>{if(n.has(c))return;n.add(c);let l=this.db.queryEdges({target:c,relation:"EXTENDS"}),d=this.db.queryEdges({target:c,relation:"IMPLEMENTS"});for(let p of [...l,...d]){let u=this.db.getNodeById(p.source);u&&(t.push(u),o(p.source));}};return s(e),o(e),{ancestors:r,descendants:t}}queryMembers(e,r){let t=r?Array.isArray(r)?r:[r]:["HAS_METHOD","HAS_PROPERTY"],i=[],n=new Set;for(let s of t){let o=this.db.queryEdges({source:e,relation:s});for(let c of o){if(n.has(c.target))continue;n.add(c.target);let l=this.db.getNodeById(c.target);l&&i.push(l);}}return i}queryOverrides(e){let r=this.db.queryEdges({source:e,relation:"METHOD_OVERRIDES"}),t=[],i=new Set;for(let n of r){if(i.has(n.target))continue;i.add(n.target);let s=this.db.getNodeById(n.target);s&&t.push(s);}return t}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}getDatabase(){return this.db}};function pr(y){return new se(y)}function ot(y){return Filesystem.join(y,".easbot")}function Vi(y){return Filesystem.join(ot(y),"codebase.json")}function Le(y){return Filesystem.join(ot(y),"db","codebase.db")}function Yi(y){let e=Filesystem.dirname(Le(y));existsSync(e)||mkdirSync(e,{recursive:true});}function ct(y){existsSync(y)||mkdirSync(y,{recursive:true});}var P=Log.create({service:"codebase.core"}),xr={database:{path:Filesystem.resolve(".easbot/db/codebase.db"),walMode:true},parser:{languages:["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"],lazyLoad:true},indexer:{batchSize:50,ignorePatterns:["node_modules/**","dist/**","build/**",".git/**","__pycache__/**","*.min.js","*.min.ts"],incremental:true},sync:DEFAULT_SYNC_CONFIG},De=class{constructor(e={}){a$1(this,"config");a$1(this,"db");a$1(this,"writeBackend",null);a$1(this,"writeProxy",null);a$1(this,"parserManager");a$1(this,"indexer");a$1(this,"queryInterface");a$1(this,"initialized",false);a$1(this,"dirty",false);a$1(this,"syncTimer");a$1(this,"syncingInProgress",false);a$1(this,"codebasePackageVersion");a$1(this,"fileWatcher",null);this.config={...xr,...e};let r=e.workspaceDir??process.cwd(),t=e.database?.path||Le(r);this.config={workspaceDir:r,database:{path:t,walMode:e.database?.walMode??true},embedding:{...DEFAULT_EMBEDDING_CONFIG,...e.embedding},search:{...DEFAULT_SEARCH_CONFIG,...e.search},parser:{...DEFAULT_PARSER_CONFIG,...e.parser},indexer:{...DEFAULT_INDEXER_CONFIG,...e.indexer},logDir:e.logDir,embeddingLlm:e.embeddingLlm,evaluationLlm:e.evaluationLlm},a$2.init({models:{evaluation:e.evaluationLlm,embedding:e.embeddingLlm}}),this.validateConfig();let i=this.resolveDbPath();ct(Filesystem.dirname(i)),this.db=new f(i),this.parserManager=new re,this.queryInterface=new se(this.db,this.config.embeddingLlm,this.config.search),this.codebasePackageVersion=Tr();}get dbWriter(){return this.writeProxy??this.db}async initialize(){if(this.initialized)return;this.db.initialize(),await this.parserManager.initialize();let e=null,r=null;try{e=new be({dbPath:this.db.getDbPath()}),await e.ready,r=new ye(this.db,e,{ftsAvailable:this.db.isFtsAvailable()}),this.indexer=new ae(this.db,this.parserManager,{workspaceDir:this.config.workspaceDir,batchSize:this.config.indexer?.batchSize??50,ignorePatterns:this.config.indexer?.ignorePatterns??[],incremental:this.config.indexer?.incremental??!0,embedding:this.config.embeddingLlm},r),this.writeBackend=e,this.writeProxy=r,e=null,r=null;}catch(t){if(P.error("Codebase.initialize failed; rolling back resources",{error:errorMeta(t)}),r)try{await r.dispose();}catch(i){P.warn("writeProxy.dispose failed during rollback",{error:errorMeta(i)});}if(e)try{await e.dispose();}catch(i){P.warn("writeBackend.dispose failed during rollback",{error:errorMeta(i)});}throw t}try{let t=this.config.workspaceDir??"";this.db.setProjectMetadata("worktree",t),this.db.setProjectMetadata("project",t),this.db.setProjectMetadata("version",this.codebasePackageVersion),this.db.setProjectMetadata("language","ts");}catch(t){P.warn("setProjectMetadata failed",{error:errorMeta(t)});}this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(t=>P.warn("codebase sync on boot failed",{error:errorMeta(t)})),this.initialized=true,P.info("Codebase initialized",{workspaceDir:this.config.workspaceDir,dbPath:this.config.database.path,embeddingEnabled:!!this.config.embeddingLlm,syncOnBoot:!!this.config.sync?.onBoot,syncIntervalMs:this.config.sync?.intervalMs??0,batchSize:this.config.indexer?.batchSize,incremental:this.config.indexer?.incremental,languages:this.config.parser?.languages?.length??0});}startSyncTimer(e){this.syncTimer&&clearInterval(this.syncTimer),e>0&&(this.syncTimer=setInterval(()=>{if(this.syncingInProgress){P.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(r=>{P.error("Interval sync failed",{error:errorMeta(r)});}));},e));}stopSyncTimer(){this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=void 0);}ensureSynced(){this.dirty&&!this.syncingInProgress&&this.config.sync?.onSearch&&(this.dirty=false,this.sync().catch(e=>{P.error("Background sync failed",{error:errorMeta(e)});}));}markDirty(){this.dirty=true;}validateConfig(){if(!this.config.workspaceDir)throw new b.ConfigError({message:"workspaceDir is required",field:"workspaceDir"});if(!this.config.database?.path)throw new b.ConfigError({message:"database.path is required",field:"database.path"})}resolveDbPath(){let e=this.config.database.path;return Filesystem.isAbsolute(e)?e:Filesystem.join(this.config.workspaceDir,e)}async indexFile(e,r){return await this.ensureInitialized(),this.indexer.indexFile(e,r)}async indexDirectory(e,r){return await this.ensureInitialized(),this.indexer.indexDirectory(e,r)}async sync(e$1){if(await this.ensureInitialized(),this.syncingInProgress)return P.debug("sync skipped \u2014 another sync is already in progress"),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,nodesCreated:0,edgesCreated:0,errors:[],duration:0,skipped:true};this.syncingInProgress=true,this.dbWriter.setIndexState("indexing");try{let r=await this.indexer.sync(e$1),t=new Date().toISOString();return r.errors.length===0?this.dbWriter.markIndexed(this.codebasePackageVersion,e,t):r.nodesCreated>0||r.filesAdded>0||r.filesUpdated>0?(this.dbWriter.markIndexed(this.codebasePackageVersion,e,t),this.dbWriter.setIndexState("partial")):this.dbWriter.setIndexState("failed"),P.debug("Codebase sync completed",{success:r.success,filesAdded:r.filesAdded,filesUpdated:r.filesUpdated,filesDeleted:r.filesDeleted,filesSkipped:r.filesSkipped,nodesCreated:r.nodesCreated,edgesCreated:r.edgesCreated,errors:r.errors.length,duration:r.duration}),this.writeProxy&&await this.writeProxy.flush(),r}catch(r){throw this.dbWriter.setIndexState("failed"),this.writeProxy&&await this.writeProxy.flush(),r}finally{this.syncingInProgress=false;}}async watch(e){if(await this.ensureInitialized(),this.fileWatcher)return P.warn("watch already running, returning existing instance"),{stop:()=>this.fileWatcher.stop()};let{FileWatcher:r}=await import('./file-watcher-ABFT22GS.mjs'),t=this.config.workspaceDir,i=e?.debounceMs??200,n=e?.initialSync??true,s=new r({workspaceDir:t,ignorePatterns:e?.ignorePatterns??this.config.indexer?.ignorePatterns});this.fileWatcher=s;try{await s.start();}catch(p){throw this.fileWatcher=null,p}let o=null,c=new Set,l=()=>{o=null;let p=c.size;c.clear(),p!==0&&(P.debug("file-watcher triggered sync",{changedFiles:p}),this.sync().catch(u=>{P.error("auto-sync after file change failed",{error:errorMeta(u)});}));},d=()=>{o&&clearTimeout(o),o=setTimeout(l,i);};return s.on((p,u)=>{P.debug("file change",{event:p,relPath:u}),c.add(u),d();}),n&&this.sync().catch(p=>{P.warn("initial sync in watch failed",{error:errorMeta(p)});}),P.info("file watcher started",{workspaceDir:t,debounceMs:i}),{stop:async()=>{o&&(clearTimeout(o),o=null),await s.stop(),this.fileWatcher=null,P.info("file watcher stopped");}}}async search(e,r){return await this.ensureInitialized(),this.ensureSynced(),this.queryInterface.search(e,r)}async queryNodes(e){return await this.ensureInitialized(),this.queryInterface.queryNodes(e)}async queryEdges(e){return await this.ensureInitialized(),this.queryInterface.queryEdges(e)}async queryNeighbors(e,r){return await this.ensureInitialized(),this.queryInterface.queryNeighbors(e,r)}async queryCallGraph(e,r){return await this.ensureInitialized(),this.queryInterface.queryCallGraph(e,r)}async queryInheritance(e){return await this.ensureInitialized(),this.queryInterface.queryInheritance(e)}async queryMembers(e,r){return await this.ensureInitialized(),this.queryInterface.queryMembers(e,r)}async queryOverrides(e){return await this.ensureInitialized(),this.queryInterface.queryOverrides(e)}async getNode(e){return await this.ensureInitialized(),this.queryInterface.getNode(e)}async getEdge(e){return await this.ensureInitialized(),this.queryInterface.getEdge(e)}async getStatus(){let e=this.db.getStatus();return {dbPath:e.dbPath,nodeCount:e.nodeCount,edgeCount:e.edgeCount,indexedFiles:e.indexedFiles,workspaceDir:this.config.workspaceDir,meta:e.meta,healthy:this.initialized,indexState:e.indexState,extractionVersion:e.extractionVersion,isStale:e.isStale,indexedWithVersion:e.meta.indexed_with_version,lastSync:e.meta.lastSync}}async healthCheck(){let e=[];this.db.isClosed()&&e.push("Database is closed"),this.parserManager.isInitialized()||e.push("Parser not initialized"),this.db.isFtsAvailable()||e.push("FTS not available");let r=this.db.getNodeCount();return r===0&&e.push("No nodes indexed"),{healthy:e.length===0,issues:e,nodeCount:r,edgeCount:this.db.getEdgeCount(),fileCount:this.db.getFileCount(),ftsAvailable:this.db.isFtsAvailable(),parserStatus:this.parserManager.getStatus()}}async clear(e={}){this.db.clearAll({keepEmbeddings:e.keepEmbeddings});}async close(){if(this.initialized){if(this.stopSyncTimer(),this.fileWatcher){try{await this.fileWatcher.stop();}catch(e){P.warn("fileWatcher stop during close failed",{error:errorMeta(e)});}this.fileWatcher=null;}if(this.writeProxy)try{await this.writeProxy.flush();}catch(e){P.warn("writeProxy flush during close failed",{error:errorMeta(e)});}if(this.writeBackend){try{await this.writeBackend.dispose();}catch(e){P.warn("writeBackend dispose during close failed",{error:errorMeta(e)});}this.writeBackend=null;}this.writeProxy=null,this.db.close(),this.parserManager.dispose(),this.initialized=false,P.info("Codebase closed");}}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}getWorkspaceDir(){return this.config.workspaceDir??process.cwd()}};async function yn(y){let e=new De(y);return await e.initialize(),e}function Tr(){try{let e=te.dirname(fileURLToPath(import.meta.url));for(let r=0;r<8;r++){let t=te.join(e,"package.json");try{let n=JSON.parse(readFileSync(t,"utf-8"));if(n&&n.name==="@easbot/codebase"&&typeof n.version=="string")return n.version}catch{}let i=te.dirname(e);if(i===e)break;e=i;}}catch{}return "0.0.0"}export{ot as a,Vi as b,Le as c,Yi as d,je as e,ze as f,re as g,Lt as h,qt as i,ie as j,Jt as k,ne as l,er as m,ae as n,ar as o,se as p,pr as q,De as r,yn as s};
203
+ `).length}),i}catch(r){return r.code!=="ENOENT"&&$.warn("Failed to read .gitignore, falling back to defaultIgnore only",{error:errorMeta(r)}),null}}toRelativePosix(e,r){let t=Filesystem.toUnixPath(e),i=Filesystem.toUnixPath(r),n=t;return i&&n.startsWith(i)&&(n=n.slice(i.length)),(i.endsWith("/")&&n.startsWith("/")||n.startsWith("/"))&&(n=n.slice(1)),n}async readFile(e){try{return await et.readFile(e,"utf-8")}catch(r){throw new b.FileSystemError({message:"Failed to read file",filePath:e},{cause:r})}}computeHash(e){return createHash("sha256").update(e).digest("hex")}storeNodes(e){let r=e.map(t=>({id:this.nodeExtractor.generateNodeId(t),name:t.name,ast_type:t.ast_type,language:t.language,file_path:t.file_path,start_line:t.start_line,start_col:t.start_col,end_line:t.end_line,end_col:t.end_col,text:t.text,created_at:new Date().toISOString()}));this.dbWriter.insertNodes(r),e.length>0&&this.storeNameSegments(e);}storeNameSegments(e){let r=[];for(let t of e){let i=this.splitIdentifier(t.name);for(let n of i)n.length>0&&r.push({segment:n,name:t.name});}if(r.length!==0)try{this.db.insertNameSegmentsBatch(r);}catch(t){$.warn("insertNameSegmentsBatch failed, falling back to per-row insert",{batchSize:r.length,error:errorMeta(t)});for(let{segment:i,name:n}of r)try{this.db.insertNameSegment(i,n);}catch(s){$.warn("insertNameSegment failed",{nodeName:n,segment:i,error:errorMeta(s)});}}}splitIdentifier(e){if(!e||e.length===0)return [];let r=[],n=e.replace(/[-_]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2");for(let s of n.split(/\s+/)){let o=s.toLowerCase();o.length>0&&r.push(o);}return r}storeEdges(e,r){let t=new Set(r.map(o=>this.nodeExtractor.generateNodeId(o))),i=new Set(["CALLS","IMPORTS"]),n=new Set(["IMPORTS"]),s=e.filter(o=>o.source===o.target?false:n.has(o.relation)||t.has(o.source)?i.has(o.relation)?true:t.has(o.target):false).map((o,c)=>({id:`${o.source}:${o.relation}:${o.target}:${c}`,source:o.source,target:o.target,relation:o.relation,created_at:new Date().toISOString()}));s.length>0&&this.dbWriter.insertEdges(s),this.storeUnresolvedRefs(e,r,t);}storeUnresolvedRefs(e,r,t){let i=new Map,n=(d,p)=>{let u=i.get(d);u||(u=[],i.set(d,u)),u.includes(p)||u.push(p);};for(let d of r){let p=this.nodeExtractor.generateNodeId(d);n(d.name,p);let u=d.metadata?.originalName;typeof u=="string"&&u.length>0&&n(u,p);let g=d.name.lastIndexOf("@");if(g>0){let f=d.name.slice(0,g),h=f.lastIndexOf(".");h>0&&n(f.slice(h+1),p);}}let s=r[0]?.file_path??"",o=r[0]?.language??"unknown",c=new Set(["CALLS","IMPORTS"]),l=[];for(let d of e){if(c.has(d.relation))continue;let p=t.has(d.source),u=t.has(d.target);if(p&&u)continue;let g=p?d.target:d.source,f=p?d.source:t.has(d.target)?d.target:void 0,h=g.includes(":")?g.split(":").pop()??g:g,m=i.get(h)??[];l.push({fromNodeId:f,referenceName:g,referenceKind:d.relation,line:d.line,col:d.col,filePath:d.filePath??s,language:o,candidates:m.length>0?m:void 0});}l.length!==0&&this.dbWriter.insertUnresolvedRefsBatch(l);}getValidEdgeCount(e,r){let t=new Set(r.map(s=>this.nodeExtractor.generateNodeId(s))),i=new Set(["CALLS","IMPORTS"]),n=new Set(["IMPORTS"]);return e.filter(s=>n.has(s.relation)||t.has(s.source)?i.has(s.relation)?true:t.has(s.target):false).length}async embedNodes(e){if(!this.config.embedding)return;let r=this.config.embedding.maxEmbeddingsPerCall||10,t=this.chunkArray(e,r),i=[],n=4,s=t.map((c,l)=>({index:l,batch:c})),o=[];for(let c=0;c<s.length;c+=n){let l=s.slice(c,c+n),d=await Promise.all(l.map(async({index:p,batch:u})=>{let g=[],f=u.map(h=>this.generateNodeEmbeddingText(h));try{let h=await this.config.embedding.doEmbed({values:f});for(let m=0;m<u.length;m++){let b=u[m];if(!b)continue;let w=h.embeddings[m];if(w){let _=new Float32Array(w),T=this.computeHash(this.generateNodeEmbeddingText(b));this.dbWriter.cacheEmbedding?.(T,_),g.push({nodeId:this.nodeExtractor.generateNodeId(b),embeddingText:f[m]||"",embedding:_});}}}catch{for(let m of u){if(!m)continue;let b=this.generateNodeEmbeddingText(m),w=await this.embedText(b);w&&g.push({nodeId:this.nodeExtractor.generateNodeId(m),embeddingText:b,embedding:w});}}return {index:p,embeddings:g}}));o.push(...d);}o.sort((c,l)=>c.index-l.index);for(let c of o)i.push(...c.embeddings);i.length>0&&this.dbWriter.storeNodeEmbeddings?.(i);}chunkArray(e,r){let t=[];for(let i=0;i<e.length;i+=r)t.push(e.slice(i,i+r));return t}};function ar(y,e,r){return new ae(y,e,r)}function Ae(y){if(!y)return [];let e=y.split(/[^a-zA-Z0-9]+/),r=[];for(let t of e){if(!t)continue;let i=t.match(/[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|\d+/g);i&&r.push(...i);}return r.map(t=>t.toLowerCase()).filter(t=>t.length>0)}function tt(y,e){if(y.length===0||e.length===0)return 0;let r=0;for(let t of y)e.includes(t)&&r++;return r/y.length}function rt(y,e,r={}){let t=r.limit??20,i=r.minScore??.2;if(!y)return [];let n=Ae(y),s=[];for(let o of e){let c=o.id.split(":").pop()??"";if(c===y||o.name===y){s.push({nodeId:o.id,score:1,matchedPart:"full"});continue}let l=Ae(c),d=Ae(o.name),p=tt(n,l),u=tt(n,d),g=Math.max(p,u);g>=i&&s.push({nodeId:o.id,score:g,matchedPart:g>=.99?"full":"segment"});}return s.sort((o,c)=>c.score-o.score),s.slice(0,t)}var Me=Filesystem.toUnixPath,C=Log.create({service:"codebase.query"}),dr=new Set(["AND","OR","NOT","NEAR"]);function lr(y){return y?y.split(/\s+/).flatMap(r=>r.split(/[^\p{L}\p{N}_]+/u)).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>!dr.has(r.toUpperCase())).join(" "):""}var se=class{constructor(e,r,t={maxResults:20,minScore:.1,hybrid:{enabled:true,vectorWeight:.7,textWeight:.3}}){a$1(this,"db");a$1(this,"embedding");a$1(this,"config");this.db=e,this.embedding=r,this.config=t;}async search(e,r={}){let{maxResults:t=this.config.maxResults,minScore:i=this.config.minScore,language:n,filePath:s,astType:o,enableFts:c=true,includeEdges:l=true,edgesLimit:d=100,vectorWeight:p=this.config.hybrid.vectorWeight,textWeight:u=this.config.hybrid.textWeight,enableEmbedding:g=true}=r,f=resolveSqlTextLimit(r.snippetMaxChars??SQL_TEXT_LIMIT_DEFAULT);C.debug("search() called",{query:e,astType:o,language:n,enableEmbedding:g,enableFts:c,minScore:i});let h=[],m=new Map;if(g&&this.embedding){let _=await this.vectorSearchNodes(e,t*2,i,void 0,f);C.debug("vectorSearchNodes results",{count:_.length,astTypeFilter:o});for(let T of _){if(n&&T.language!==n||o&&T.astType!==o)continue;let x={...T,source:"vector",vectorScore:T.score,hybridScore:T.score*p};h.push(x),m.set(x.id,x);}C.debug("after vector filter",{resultsCount:h.length});}if(c&&this.db.isFtsAvailable()){let _=lr(e);_||C.debug("FTS query sanitized to empty \u2014 skipping FTS",{originalQuery:e});let T=_?this.db.searchNodesFts(_,t*2):[];C.debug("FTS results before filter",{count:T.length});for(let x of T){if(n&&x.language!==n||s&&!x.file_path.includes(Me(s))||o&&x.ast_type!==o)continue;let E=this.normalizeScore(x.score),I=m.get(x.id);if(I)I.ftsScore=E,I.hybridScore=I.vectorScore*p+E*u;else {let M={id:x.id,name:x.name,astType:x.ast_type,language:x.language,filePath:x.file_path,text:x.text,snippet:x.text.slice(0,f),startLine:x.start_line,startCol:x.start_col,endLine:x.end_line,endCol:x.end_col,score:E,source:"fts",ftsScore:E,hybridScore:E*u};h.push(M),m.set(M.id,M);}}C.debug("after FTS filter",{resultsCount:h.length});}if(!c||!this.db.isFtsAvailable()||h.length===0){try{let _=this.db.queryNodes({limit:t*2,astType:o,language:n,filePath:s}),T=new Set(h.map(v=>v.id)),x=e.toLowerCase(),E=x.split(/\s+/).filter(v=>v.length>0),I=v=>v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),M=E.map(v=>({term:v,regex:new RegExp(I(v),"gi")})),J=[];for(let v of _){if(s&&!v.file_path.includes(Me(s)))continue;let Q=v.name.toLowerCase(),X=v.text.toLowerCase(),fe=0;if(M.some(({term:H})=>Q.includes(H))){let H=0;for(let{regex:L}of M){let O=Q.match(L);H+=O?O.length:0;}fe=.8*Math.min(H/M.length,1);}let N=0;if(M.some(({term:H})=>X.includes(H))){let H=0;for(let{regex:oe}of M){let Oe=X.match(oe);H+=Oe?Oe.length:0;}N=.5*Math.min(H/M.length,1);let L=X.indexOf(x),O=L===-1?0:Math.max(0,1-L/X.length)*.2;N+=O;}let Z=Math.max(fe,N);Z>0&&J.push({id:v.id,name:v.name,astType:v.ast_type,language:v.language,filePath:v.file_path,text:v.text,snippet:v.text.slice(0,f),startLine:v.start_line,startCol:v.start_col,endLine:v.end_line,endCol:v.end_col,score:Z,source:"basic",hybridScore:Z});}J.sort((v,Q)=>Q.score-v.score),h.push(...J.slice(0,t));}catch{}if(h.length===0)try{let _=this.db.queryNodes({limit:1e3}),T=rt(e,_,{limit:t,minScore:.5});C.debug("name-segment matches",{count:T.length,query:e});for(let x of T){let E=this.db.getNodeById(x.nodeId);if(!E||n&&E.language!==n||o&&E.ast_type!==o||s&&!E.file_path.includes(Me(s)))continue;let I={id:E.id,name:E.name,astType:E.ast_type,language:E.language,filePath:E.file_path,text:E.text??"",snippet:(E.text??"").slice(0,f),startLine:E.start_line??0,startCol:E.start_col??0,endLine:E.end_line??0,endCol:E.end_col??0,score:x.score,source:"structural",hybridScore:x.score};h.push(I),m.set(I.id,I);}}catch(_){C.errorDegradable("name-segment channel error",{error:errorMeta(_)});}}let b=h.filter(_=>_.hybridScore>=i).sort((_,T)=>T.hybridScore-_.hybridScore).slice(0,t);b.length===0&&c&&this.db.isFtsAvailable()&&(!g||!this.embedding)&&(b=h.sort((_,T)=>T.hybridScore-_.hybridScore).slice(0,t),C.warn("q.search: FTS-only minScore threshold too strict, falling back to minScore=0",{originalMinScore:i,ftsRawCount:h.filter(_=>_.source==="fts").length,preservedHits:b.length}));let w=b.map(_=>({id:_.id,name:_.name,ast_type:_.astType,language:_.language,file_path:_.filePath,start_line:_.startLine,start_col:_.startCol,end_line:_.endLine,end_col:_.endCol,text:_.text,created_at:new Date().toISOString()}));if(l&&w.length>0){let _=w.map(E=>E.id),T=this.db.queryEdges({sourceOrTarget:_}),x=new Map;for(let E of T)E.source!==E.target&&(x.has(E.source)||x.set(E.source,[]),x.get(E.source).push(E));return w.map(E=>{let I=x.get(E.id)||[];return {...E,edges:I.slice(0,d)}})}return w.map(_=>({..._,edges:[]}))}async vectorSearchNodes(e,r,t,i,n=resolveSqlTextLimit(SQL_TEXT_LIMIT_DEFAULT)){if(C.debug("vectorSearchNodes start",{query:e,limit:r,minScore:t,hasEmbedding:!!this.embedding,candidateCount:i?.length}),!this.embedding)return C.debug("vectorSearchNodes skip - no embedding model"),[];let s=await this.embedText(e);if(!s)return C.debug("vectorSearchNodes skip - no embedding result"),[];let o=new Float32Array(s),c,l=5e3;if(i&&i.length>0){let f=i.map(()=>"?").join(",");c=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${f})`,i);}else c=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[l]);C.debug("vectorSearchNodes vectors loaded",{count:c.length});let d=[];for(let f of c){let h=new Float32Array(f.embedding.buffer,f.embedding.byteOffset,f.embedding.length/4),m=this.cosineSimilarity(o,h);m<t||(d.push({nodeId:f.node_id,score:m}),d.length>r&&(d.sort((b,w)=>w.score-b.score),d.splice(r)));}if(d.length===0)return C.debug("vectorSearchNodes done - no results above minScore"),[];d.sort((f,h)=>h.score-f.score);let p=d.map(f=>f.nodeId);C.debug("vectorSearchNodes query nodes",{nodeIdsCount:p.length});let u=this.db.queryNodes({ids:p}),g=new Map(d.map(f=>[f.nodeId,f.score]));return C.debug("vectorSearchNodes done",{nodesFound:u.length}),u.map(f=>({id:f.id,name:f.name,astType:f.ast_type,language:f.language,filePath:f.file_path,text:f.text??"",snippet:(f.text??"").slice(0,n),startLine:f.start_line??0,startCol:f.start_col??0,endLine:f.end_line??0,endCol:f.end_col??0,score:g.get(f.id)||0,source:"vector"}))}async getEdgesForNode(e,r=100){let t=this.db.queryEdges({sourceOrTarget:[e.id],limit:r});return {...e,edges:t}}async embedText(e){if(!this.embedding)return null;try{let t=(await this.embedding.doEmbed({values:[e]})).embeddings[0];return t?new Float32Array(t):null}catch{return null}}cosineSimilarity(e,r){let t=0,i=0,n=0;for(let s=0;s<e.length;s++){let o=e[s],c=r[s];t+=o*c,i+=o*o,n+=c*c;}return i===0||n===0?0:t/(Math.sqrt(i)*Math.sqrt(n))}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){C.debug("queryNodes() called",{language:e.language,astType:e.astType,filePath:e.filePath?.slice(0,80),name:e.name,limit:e.limit});try{return this.db.queryNodes(e)}catch(r){throw new b.QueryError({message:"Failed to query nodes",params:{filter:e}},{cause:r})}}queryEdges(e){C.debug("queryEdges() called",{source:e.source?.split(":").slice(-2).join(":"),target:e.target?.split(":").slice(-2).join(":"),sourceOrTarget:Array.isArray(e.sourceOrTarget)?e.sourceOrTarget.map(r=>r.split(":").slice(-2).join(":")):void 0,relation:e.relation,limit:e.limit});try{return this.db.queryEdges(e)}catch(r){throw new b.QueryError({message:"Failed to query edges",params:{filter:e}},{cause:r})}}queryEdgesWithNodes(e){let r=this.db.queryEdges(e),t=[];for(let i of r){let n=this.db.getNodeById(i.source),s=this.db.getNodeById(i.target);n&&s&&t.push({edge:i,sourceNode:n,targetNode:s});}return t}queryNeighbors(e,r={}){let{relationTypes:t,direction:i="both",limit:n=100}=r;C.debug("queryNeighbors() called",{nodeId:e.split(":").slice(-2).join(":"),relationTypes:t,direction:i,limit:n});let s=[],o=[],c=new Set,l=new Set,d=t&&t.length>0?t:[void 0],p=u=>{for(let g of d){let f=g===void 0?{}:{relation:g},h=u==="outgoing"?this.db.queryEdges({source:e,...f,limit:n}):this.db.queryEdges({target:e,...f,limit:n});for(let m of h){if(l.has(m.id))continue;l.add(m.id),s.push(m);let b=u==="outgoing"?m.target:m.source,w=this.db.getNodeById(b);w&&!c.has(w.id)&&(o.push(w),c.add(w.id));}}};return (i==="outgoing"||i==="both")&&p("outgoing"),(i==="incoming"||i==="both")&&p("incoming"),{nodes:o.slice(0,n),edges:s.slice(0,n)}}queryCallGraph(e,r=2){let t=new Map,i=new Set,n=(s,o)=>{if(o>r||i.has(s))return;i.add(s);let c=[],l=[],d=this.db.queryEdges({target:s,relation:"CALLS"});for(let u of d)c.push(u.source),n(u.source,o+1);let p=this.db.queryEdges({source:s,relation:"CALLS"});for(let u of p)l.push(u.target),n(u.target,o+1);t.set(s,{callers:c,callees:l});};return n(e,0),t}queryInheritance(e){C.debug("queryInheritance() called",{nodeId:e.split(":").slice(-2).join(":")});let r=[],t=[],i=new Set,n=new Set,s=c=>{if(i.has(c))return;i.add(c);let l=this.db.queryEdges({source:c,relation:"EXTENDS"}),d=this.db.queryEdges({source:c,relation:"IMPLEMENTS"});for(let p of [...l,...d]){let u=this.db.getNodeById(p.target);u&&(r.push(u),s(p.target));}},o=c=>{if(n.has(c))return;n.add(c);let l=this.db.queryEdges({target:c,relation:"EXTENDS"}),d=this.db.queryEdges({target:c,relation:"IMPLEMENTS"});for(let p of [...l,...d]){let u=this.db.getNodeById(p.source);u&&(t.push(u),o(p.source));}};return s(e),o(e),{ancestors:r,descendants:t}}queryMembers(e,r){let t=r?Array.isArray(r)?r:[r]:["HAS_METHOD","HAS_PROPERTY"],i=[],n=new Set;for(let s of t){let o=this.db.queryEdges({source:e,relation:s});for(let c of o){if(n.has(c.target))continue;n.add(c.target);let l=this.db.getNodeById(c.target);l&&i.push(l);}}return i}queryOverrides(e){let r=this.db.queryEdges({source:e,relation:"METHOD_OVERRIDES"}),t=[],i=new Set;for(let n of r){if(i.has(n.target))continue;i.add(n.target);let s=this.db.getNodeById(n.target);s&&t.push(s);}return t}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}getDatabase(){return this.db}};function pr(y){return new se(y)}function ot(y){return Filesystem.join(y,".easbot")}function Vi(y){return Filesystem.join(ot(y),"codebase.json")}function Le(y){return Filesystem.join(ot(y),"db","codebase.db")}function Yi(y){let e=Filesystem.dirname(Le(y));existsSync(e)||mkdirSync(e,{recursive:true});}function ct(y){existsSync(y)||mkdirSync(y,{recursive:true});}var P=Log.create({service:"codebase.core"}),xr={database:{path:Filesystem.resolve(".easbot/db/codebase.db"),walMode:true},parser:{languages:["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"],lazyLoad:true},indexer:{batchSize:50,ignorePatterns:["node_modules/**","dist/**","build/**",".git/**","__pycache__/**","*.min.js","*.min.ts"],incremental:true},sync:DEFAULT_SYNC_CONFIG},De=class{constructor(e={}){a$1(this,"config");a$1(this,"db");a$1(this,"writeBackend",null);a$1(this,"writeProxy",null);a$1(this,"parserManager");a$1(this,"indexer");a$1(this,"queryInterface");a$1(this,"initialized",false);a$1(this,"dirty",false);a$1(this,"syncTimer");a$1(this,"syncingInProgress",false);a$1(this,"codebasePackageVersion");a$1(this,"fileWatcher",null);this.config={...xr,...e};let r=e.workspaceDir??process.cwd(),t=e.database?.path||Le(r);this.config={workspaceDir:r,database:{path:t,walMode:e.database?.walMode??true},embedding:{...DEFAULT_EMBEDDING_CONFIG,...e.embedding},search:{...DEFAULT_SEARCH_CONFIG,...e.search},parser:{...DEFAULT_PARSER_CONFIG,...e.parser},indexer:{...DEFAULT_INDEXER_CONFIG,...e.indexer},logDir:e.logDir,embeddingLlm:e.embeddingLlm,evaluationLlm:e.evaluationLlm},a$2.init({models:{evaluation:e.evaluationLlm,embedding:e.embeddingLlm}}),this.validateConfig();let i=this.resolveDbPath();ct(Filesystem.dirname(i)),this.db=new f(i),this.parserManager=new re,this.queryInterface=new se(this.db,this.config.embeddingLlm,this.config.search),this.codebasePackageVersion=Tr();}get dbWriter(){return this.writeProxy??this.db}async initialize(){if(this.initialized)return;this.db.initialize(),await this.parserManager.initialize();let e=null,r=null;try{e=new be({dbPath:this.db.getDbPath()}),await e.ready,r=new ye(this.db,e,{ftsAvailable:this.db.isFtsAvailable()}),this.indexer=new ae(this.db,this.parserManager,{workspaceDir:this.config.workspaceDir,batchSize:this.config.indexer?.batchSize??50,ignorePatterns:this.config.indexer?.ignorePatterns??[],incremental:this.config.indexer?.incremental??!0,embedding:this.config.embeddingLlm},r),this.writeBackend=e,this.writeProxy=r,e=null,r=null;}catch(t){if(P.error("Codebase.initialize failed; rolling back resources",{error:errorMeta(t)}),r)try{await r.dispose();}catch(i){P.warn("writeProxy.dispose failed during rollback",{error:errorMeta(i)});}if(e)try{await e.dispose();}catch(i){P.warn("writeBackend.dispose failed during rollback",{error:errorMeta(i)});}throw t}try{let t=this.config.workspaceDir??"";this.db.setProjectMetadata("worktree",t),this.db.setProjectMetadata("project",t),this.db.setProjectMetadata("version",this.codebasePackageVersion),this.db.setProjectMetadata("language","ts");}catch(t){P.warn("setProjectMetadata failed",{error:errorMeta(t)});}this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(t=>P.warn("codebase sync on boot failed",{error:errorMeta(t)})),this.initialized=true,P.info("Codebase initialized",{workspaceDir:this.config.workspaceDir,dbPath:this.config.database.path,embeddingEnabled:!!this.config.embeddingLlm,syncOnBoot:!!this.config.sync?.onBoot,syncIntervalMs:this.config.sync?.intervalMs??0,batchSize:this.config.indexer?.batchSize,incremental:this.config.indexer?.incremental,languages:this.config.parser?.languages?.length??0});}startSyncTimer(e){this.syncTimer&&clearInterval(this.syncTimer),e>0&&(this.syncTimer=setInterval(()=>{if(this.syncingInProgress){P.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(r=>{P.error("Interval sync failed",{error:errorMeta(r)});}));},e));}stopSyncTimer(){this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=void 0);}ensureSynced(){this.dirty&&!this.syncingInProgress&&this.config.sync?.onSearch&&(this.dirty=false,this.sync().catch(e=>{P.error("Background sync failed",{error:errorMeta(e)});}));}markDirty(){this.dirty=true;}validateConfig(){if(!this.config.workspaceDir)throw new b.ConfigError({message:"workspaceDir is required",field:"workspaceDir"});if(!this.config.database?.path)throw new b.ConfigError({message:"database.path is required",field:"database.path"})}resolveDbPath(){let e=this.config.database.path;return Filesystem.isAbsolute(e)?e:Filesystem.join(this.config.workspaceDir,e)}async indexFile(e,r){return await this.ensureInitialized(),this.indexer.indexFile(e,r)}async indexDirectory(e,r){return await this.ensureInitialized(),this.indexer.indexDirectory(e,r)}async sync(e$1){if(await this.ensureInitialized(),this.syncingInProgress)return P.debug("sync skipped \u2014 another sync is already in progress"),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,nodesCreated:0,edgesCreated:0,errors:[],duration:0,skipped:true};this.syncingInProgress=true,this.dbWriter.setIndexState("indexing");try{let r=await this.indexer.sync(e$1),t=new Date().toISOString();return r.errors.length===0?this.dbWriter.markIndexed(this.codebasePackageVersion,e,t):r.nodesCreated>0||r.filesAdded>0||r.filesUpdated>0?(this.dbWriter.markIndexed(this.codebasePackageVersion,e,t),this.dbWriter.setIndexState("partial")):this.dbWriter.setIndexState("failed"),P.debug("Codebase sync completed",{success:r.success,filesAdded:r.filesAdded,filesUpdated:r.filesUpdated,filesDeleted:r.filesDeleted,filesSkipped:r.filesSkipped,nodesCreated:r.nodesCreated,edgesCreated:r.edgesCreated,errors:r.errors.length,duration:r.duration}),this.writeProxy&&await this.writeProxy.flush(),r}catch(r){throw this.dbWriter.setIndexState("failed"),this.writeProxy&&await this.writeProxy.flush(),r}finally{this.syncingInProgress=false;}}async watch(e){if(await this.ensureInitialized(),this.fileWatcher)return P.warn("watch already running, returning existing instance"),{stop:()=>this.fileWatcher.stop()};let{FileWatcher:r}=await import('./file-watcher-RAO72GUL.mjs'),t=this.config.workspaceDir,i=e?.debounceMs??200,n=e?.initialSync??true,s=new r({workspaceDir:t,ignorePatterns:e?.ignorePatterns??this.config.indexer?.ignorePatterns});this.fileWatcher=s;try{await s.start();}catch(p){throw this.fileWatcher=null,p}let o=null,c=new Set,l=()=>{o=null;let p=c.size;c.clear(),p!==0&&(P.debug("file-watcher triggered sync",{changedFiles:p}),this.sync().catch(u=>{P.error("auto-sync after file change failed",{error:errorMeta(u)});}));},d=()=>{o&&clearTimeout(o),o=setTimeout(l,i);};return s.on((p,u)=>{P.debug("file change",{event:p,relPath:u}),c.add(u),d();}),n&&this.sync().catch(p=>{P.warn("initial sync in watch failed",{error:errorMeta(p)});}),P.info("file watcher started",{workspaceDir:t,debounceMs:i}),{stop:async()=>{o&&(clearTimeout(o),o=null),await s.stop(),this.fileWatcher=null,P.info("file watcher stopped");}}}async search(e,r){return await this.ensureInitialized(),this.ensureSynced(),this.queryInterface.search(e,r)}async queryNodes(e){return await this.ensureInitialized(),this.queryInterface.queryNodes(e)}async queryEdges(e){return await this.ensureInitialized(),this.queryInterface.queryEdges(e)}async queryNeighbors(e,r){return await this.ensureInitialized(),this.queryInterface.queryNeighbors(e,r)}async queryCallGraph(e,r){return await this.ensureInitialized(),this.queryInterface.queryCallGraph(e,r)}async queryInheritance(e){return await this.ensureInitialized(),this.queryInterface.queryInheritance(e)}async queryMembers(e,r){return await this.ensureInitialized(),this.queryInterface.queryMembers(e,r)}async queryOverrides(e){return await this.ensureInitialized(),this.queryInterface.queryOverrides(e)}async getNode(e){return await this.ensureInitialized(),this.queryInterface.getNode(e)}async getEdge(e){return await this.ensureInitialized(),this.queryInterface.getEdge(e)}async getStatus(){let e=this.db.getStatus();return {dbPath:e.dbPath,nodeCount:e.nodeCount,edgeCount:e.edgeCount,indexedFiles:e.indexedFiles,workspaceDir:this.config.workspaceDir,meta:e.meta,healthy:this.initialized,indexState:e.indexState,extractionVersion:e.extractionVersion,isStale:e.isStale,indexedWithVersion:e.meta.indexed_with_version,lastSync:e.meta.lastSync}}async healthCheck(){let e=[];this.db.isClosed()&&e.push("Database is closed"),this.parserManager.isInitialized()||e.push("Parser not initialized"),this.db.isFtsAvailable()||e.push("FTS not available");let r=this.db.getNodeCount();return r===0&&e.push("No nodes indexed"),{healthy:e.length===0,issues:e,nodeCount:r,edgeCount:this.db.getEdgeCount(),fileCount:this.db.getFileCount(),ftsAvailable:this.db.isFtsAvailable(),parserStatus:this.parserManager.getStatus()}}async clear(e={}){this.db.clearAll({keepEmbeddings:e.keepEmbeddings});}async close(){if(this.initialized){if(this.stopSyncTimer(),this.fileWatcher){try{await this.fileWatcher.stop();}catch(e){P.warn("fileWatcher stop during close failed",{error:errorMeta(e)});}this.fileWatcher=null;}if(this.writeProxy)try{await this.writeProxy.flush();}catch(e){P.warn("writeProxy flush during close failed",{error:errorMeta(e)});}if(this.writeBackend){try{await this.writeBackend.dispose();}catch(e){P.warn("writeBackend dispose during close failed",{error:errorMeta(e)});}this.writeBackend=null;}this.writeProxy=null,this.db.close(),this.parserManager.dispose(),this.initialized=false,P.info("Codebase closed");}}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}getWorkspaceDir(){return this.config.workspaceDir??process.cwd()}};async function yn(y){let e=new De(y);return await e.initialize(),e}function Tr(){try{let e=te.dirname(fileURLToPath(import.meta.url));for(let r=0;r<8;r++){let t=te.join(e,"package.json");try{let n=JSON.parse(readFileSync(t,"utf-8"));if(n&&n.name==="@easbot/codebase"&&typeof n.version=="string")return n.version}catch{}let i=te.dirname(e);if(i===e)break;e=i;}}catch{}return "0.0.0"}export{ot as a,Vi as b,Le as c,Yi as d,je as e,ze as f,re as g,Lt as h,qt as i,ie as j,Jt as k,ne as l,er as m,ae as n,ar as o,se as p,pr as q,De as r,yn as s};
@@ -1,4 +1,4 @@
1
- 'use strict';var chunkTBDAGLC4_cjs=require('./chunk-TBDAGLC4.cjs'),chunkW5SMGCKO_cjs=require('./chunk-W5SMGCKO.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database'),types=require('@easbot/types'),fs=require('fs');var ee=utils.Log.create({service:"codebase.services.codebase"}),N=utils.Filesystem.toUnixPath;function Pe(e,t){let n={exact:1,qualified:.85,substring:.5}[e];return t?Math.min(1,n+.2):n}function Re(e,t){if(!t)return false;if(e===t)return true;let n=e.split(/[/\\]/).pop()??"",s=t.split(/[/\\]/).pop()??"";return !!(n&&s&&n===s||t.includes("/")&&e.endsWith("/"+t))}async function $(e,t,n){if(n.nodeId){let o=e.getNode(n.nodeId);if(!o)throw new utils.ServiceError({code:"NOT_FOUND",message:`Node not found: nodeId=${n.nodeId}`,details:{name:n.nodeId}});return {node:o,candidates:[]}}if(!n.name)throw new utils.ServiceError({code:"NOT_FOUND",message:"Either name or nodeId is required",details:{...n}});let l=e.getDatabase().findNodesByName({name:n.name,file:n.file,kind:n.kind,limit:50});if(l.length===0)throw new utils.ServiceError({code:"NOT_FOUND",message:`Node not found: ${n.name}`,details:{name:n.name,candidates:[]}});let a=!!n.file,c=n.file?N(n.file):null,i=l.map(o=>{let u=c?Re(N(o.node.file_path),c):false;return {node:o.node,score:Pe(o.matchKind,u),matchKind:o.matchKind,inFile:u}});if(i.sort((o,u)=>u.score-o.score),i.length===1)return {node:i[0].node,candidates:i.map(o=>({node:o.node,score:o.score}))};let d=i[0].score,r=i.filter(o=>o.score===d);if(r.length===1)return {node:r[0].node,candidates:i.slice(0,10).map(o=>({node:o.node,score:o.score}))};if(a&&r.length>1){let o=r.filter(u=>u.inFile);if(o.length===1)return {node:o[0].node,candidates:i.slice(0,10).map(u=>({node:u.node,score:u.score}))}}throw new utils.ServiceError({code:"AMBIGUOUS",message:`Ambiguous name "${n.name}" \u2014 ${i.length} candidates`,details:{name:n.name,candidates:i.slice(0,10).map(o=>({node:o.node,score:o.score}))}})}async function P(e){let t=chunkTBDAGLC4_cjs.c(e.rootDir),n=new chunkTBDAGLC4_cjs.r({workspaceDir:e.workspaceDir,database:{path:t,walMode:true},embedding:types.DEFAULT_EMBEDDING_CONFIG,indexer:types.DEFAULT_INDEXER_CONFIG,parser:types.DEFAULT_PARSER_CONFIG,search:types.DEFAULT_SEARCH_CONFIG,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});return await n.initialize(),n}function U(e,t,n,s){let l=n.map(()=>"?").join(","),a=t.name.split("@")[0]??t.name,c=a.includes(".")?a.split(".").pop()??a:a,i=new Set([`${t.language}:*:*:${a}`]);c!==a&&i.add(`${t.language}:*:*:${c}`);let d=[];c!==a&&d.push(`${t.language}:*:*:%${c}`);let r=Array.from(i),o=r.map(()=>"?").join(","),g=d.length>0?"OR LOWER(target) LIKE LOWER(?)":"";r.length>1&&ee.warn("queryIncomingEdgesWithWildcard: multi-variant wildcards (bare+namespaced)",{rootName:t.name,wildcards:r,hint:"\u540C\u540D\u540C namespace \u4E0D\u540C file \u7684\u65B9\u6CD5\u53EF\u80FD\u90FD\u88AB\u547D\u4E2D\uFF0CLLM \u63A8\u7406\u8BF7\u7528 file \u8FC7\u6EE4\u8F85\u4F50"});let m=`
1
+ 'use strict';var chunk3DAM6EZN_cjs=require('./chunk-3DAM6EZN.cjs'),chunkW5SMGCKO_cjs=require('./chunk-W5SMGCKO.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database'),types=require('@easbot/types'),fs=require('fs');var ee=utils.Log.create({service:"codebase.services.codebase"}),N=utils.Filesystem.toUnixPath;function Pe(e,t){let n={exact:1,qualified:.85,substring:.5}[e];return t?Math.min(1,n+.2):n}function Re(e,t){if(!t)return false;if(e===t)return true;let n=e.split(/[/\\]/).pop()??"",s=t.split(/[/\\]/).pop()??"";return !!(n&&s&&n===s||t.includes("/")&&e.endsWith("/"+t))}async function $(e,t,n){if(n.nodeId){let o=e.getNode(n.nodeId);if(!o)throw new utils.ServiceError({code:"NOT_FOUND",message:`Node not found: nodeId=${n.nodeId}`,details:{name:n.nodeId}});return {node:o,candidates:[]}}if(!n.name)throw new utils.ServiceError({code:"NOT_FOUND",message:"Either name or nodeId is required",details:{...n}});let l=e.getDatabase().findNodesByName({name:n.name,file:n.file,kind:n.kind,limit:50});if(l.length===0)throw new utils.ServiceError({code:"NOT_FOUND",message:`Node not found: ${n.name}`,details:{name:n.name,candidates:[]}});let a=!!n.file,c=n.file?N(n.file):null,i=l.map(o=>{let u=c?Re(N(o.node.file_path),c):false;return {node:o.node,score:Pe(o.matchKind,u),matchKind:o.matchKind,inFile:u}});if(i.sort((o,u)=>u.score-o.score),i.length===1)return {node:i[0].node,candidates:i.map(o=>({node:o.node,score:o.score}))};let d=i[0].score,r=i.filter(o=>o.score===d);if(r.length===1)return {node:r[0].node,candidates:i.slice(0,10).map(o=>({node:o.node,score:o.score}))};if(a&&r.length>1){let o=r.filter(u=>u.inFile);if(o.length===1)return {node:o[0].node,candidates:i.slice(0,10).map(u=>({node:u.node,score:u.score}))}}throw new utils.ServiceError({code:"AMBIGUOUS",message:`Ambiguous name "${n.name}" \u2014 ${i.length} candidates`,details:{name:n.name,candidates:i.slice(0,10).map(o=>({node:o.node,score:o.score}))}})}async function P(e){let t=chunk3DAM6EZN_cjs.c(e.rootDir),n=new chunk3DAM6EZN_cjs.r({workspaceDir:e.workspaceDir,database:{path:t,walMode:true},embedding:types.DEFAULT_EMBEDDING_CONFIG,indexer:types.DEFAULT_INDEXER_CONFIG,parser:types.DEFAULT_PARSER_CONFIG,search:types.DEFAULT_SEARCH_CONFIG,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});return await n.initialize(),n}function U(e,t,n,s){let l=n.map(()=>"?").join(","),a=t.name.split("@")[0]??t.name,c=a.includes(".")?a.split(".").pop()??a:a,i=new Set([`${t.language}:*:*:${a}`]);c!==a&&i.add(`${t.language}:*:*:${c}`);let d=[];c!==a&&d.push(`${t.language}:*:*:%${c}`);let r=Array.from(i),o=r.map(()=>"?").join(","),g=d.length>0?"OR LOWER(target) LIKE LOWER(?)":"";r.length>1&&ee.warn("queryIncomingEdgesWithWildcard: multi-variant wildcards (bare+namespaced)",{rootName:t.name,wildcards:r,hint:"\u540C\u540D\u540C namespace \u4E0D\u540C file \u7684\u65B9\u6CD5\u53EF\u80FD\u90FD\u88AB\u547D\u4E2D\uFF0CLLM \u63A8\u7406\u8BF7\u7528 file \u8FC7\u6EE4\u8F85\u4F50"});let m=`
2
2
  SELECT id, source, target, relation, created_at FROM edges
3
3
  WHERE relation IN (${l})
4
4
  AND source != target
@@ -22,7 +22,7 @@
22
22
  AND source != target
23
23
  AND source = ?
24
24
  LIMIT ?
25
- `;return e.queryAll(a,[...n,t.id,s])}function ne(e,t,n,s){let l=s==="in"?e.source:e.target;t.id;let c=n.getNodeById(l);if(!c&&l.includes(":*:")){let i=l.split(":").pop()??l,d=i.split("@")[0]??i;if(d&&d!==l){let r=n.findNodesByName({name:d}),o=t.file_path??"",u=o.split(/[/\\]/).pop()??"",g=o.split(/[/\\]/).filter(Boolean),m=r.find(p=>p.node.file_path?p.node.file_path===o:false)??r.find(p=>!p.node.file_path||!u?false:p.node.file_path.split(/[/\\]/).pop()===u)??r.find(p=>{if(!p.node.file_path)return false;let f=p.node.file_path.split(/[/\\]/).filter(Boolean);return g.length<2||f.length<2?false:g[0]===f[0]&&g[1]===f[1]})??null;m&&(c=m.node);}}if(!c){let i=l.split(":").pop()??l;return {id:l,name:i,astType:"unresolved",filePath:"(unresolved)",startLine:0,relation:e.relation}}return {id:c.id,name:c.name,astType:c.ast_type,filePath:N(c.file_path),startLine:c.start_line??0,relation:e.relation}}async function re(e,t){let n=Date.now(),l=(await P(e)).getQuery(),a=database.resolveSqlTextLimit(t.snippetMaxChars??database.SQL_TEXT_LIMIT_DEFAULT),i=await l.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,snippetMaxChars:a});if(t.kind){let o=t.kind.toLowerCase();i=i.filter(u=>u.ast_type.includes(o)||u.name.toLowerCase().includes(o));}if(t.file){let o=N(t.file);i=i.filter(u=>N(u.file_path).endsWith(o)||N(u.file_path).includes(o));}let d=t.maxEdgesPerNode??10,r=i.map(o=>({nodeId:o.id,name:o.name,kind:o.ast_type??"unknown",filePath:N(o.file_path),startLine:o.start_line,endLine:o.end_line,edges:(o.edges??[]).slice(0,d),source:"basic",score:0,snippet:(o.text??"").slice(0,a).replace(/\s+/g," ").trim()}));return {total:r.length,hits:r,durationMs:Date.now()-n,truncated:false}}async function Ie(e,t){let n=await P(e),s=n.getQuery(),l=n.getDatabase(),{node:a}=await $(s,e,t),c=[];if(t.includeEdges){let i=t.maxEdgesPerNode??10,d=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"],r=U(l,a,d,i+1),o=te(l,a,d,i+1),u=new Set,g=[];for(let m of [...r,...o])m.id&&!u.has(m.id)&&(u.add(m.id),g.push(m));c=g.slice(0,i);}return {node:a,edges:c}}var Le=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"];async function Te(e,t){let n=await P(e),s=n.getQuery(),l=n.getDatabase(),{node:a}=await $(s,e,t);if(!a)return {root:null,nodes:[],edges:[],truncated:false,totalNodes:0,totalEdges:0};let c=t.depth??2,i=t.maxNodes??100,d=t.direction??"both";t.maxEdgesPerNode??10;let o=new Map,u=[{nodeId:a.id,depth:0}];o.set(a.id,0);let g=[],m=false;for(;u.length>0;){let y=u.shift();if(y.depth>=c)continue;if(o.size>=i){m=true;break}let I=s.queryNeighbors(y.nodeId,{direction:d,relationTypes:t.relationTypes??Le,limit:i-o.size+1});for(let b of I.edges){g.push(b);let L=b.source===y.nodeId?b.target:b.source;if(!o.has(L)&&(o.set(L,y.depth+1),u.push({nodeId:L,depth:y.depth+1}),o.size>=i)){m=true;break}}if(m)break}let p=new Set,f=[];for(let y of g)!y.id||p.has(y.id)||(p.add(y.id),f.push(y));let E=Array.from(o.keys()),h=E.length>0?l.queryNodes({ids:E}):[],C=new Map(h.map(y=>[y.id,y])),x=[];for(let[y,I]of o.entries()){let b=C.get(y);b&&x.push({node:b,depth:I});}return {root:a,nodes:x,edges:f,truncated:m,totalNodes:x.length,totalEdges:g.length}}var $e=["CALLS","IMPORTS","TYPE_REFERENCES"];async function _e(e,t){let n=await P(e),s=n.getQuery(),l=n.getDatabase(),{node:a}=await $(s,e,t);if(!a)return {root:null,totalImpacted:0,buckets:[]};let c=t.depth??2,i=t.maxResults??10,d=t.relationTypes??$e,r=t.maxEdgesPerNode??10,o=new Set([a.id]),u=[],g=[a.id];for(let m=1;m<=c&&!(g.length===0||o.size-1>=i);m++){let p=U(l,a,d,r+1),f=[],E=new Set;for(let h of p)if(!o.has(h.source)&&!E.has(h.source)&&(E.add(h.source),o.add(h.source),f.push(h.source),o.size-1>=i))break;if(f.length>0){let h=f.slice(0,10),C=l.queryNodes({ids:h}),x=new Map(C.map(b=>[b.id,b])),y=new Map;for(let b of p)y.has(b.source)||y.set(b.source,b.relation);let I=h.map(b=>{let L=x.get(b);return {id:b,name:L?.name??"(unknown)",filePath:L?N(L.file_path):"(unknown)",relation:y.get(b)??"CALLS"}});u.push({depth:m,count:f.length,sample:I});}g=f;}return u.length===0&&ee.warn("impact: no incoming edges found",{root:a.name,depth:c,relationTypes:d}),{root:a,totalImpacted:o.size-1,buckets:u}}var oe=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","METHOD_OVERRIDES"];async function we(e,t){return se(e,t)}async function Fe(e,t){return ie(e,t)}async function se(e,t){let n=await P(e),s=n.getQuery(),l=n.getDatabase(),{node:a}=await $(s,e,t);if(!a)return {root:null,callers:[],truncated:false};let c=t.maxResults??10,i=t.maxEdgesPerNode??c,d=t.relationTypes??oe,r=U(l,a,d,i+1),o=[];for(let g of r){let m=ne(g,a,l,"in");m&&o.push(m);}let u=o.length>c;return {root:a,callers:u?o.slice(0,c):o,truncated:u}}async function ie(e,t){let n=await P(e),s=n.getQuery(),l=n.getDatabase(),{node:a}=await $(s,e,t);if(!a)return {root:null,callees:[],truncated:false};let c=t.maxResults??10,i=t.maxEdgesPerNode??c,d=t.relationTypes??oe,r=te(l,a,d,i+1),o=Se(a.ast_type)?Ce(l,a,r,d,i+1):r,u=[];for(let m of o){let p=ne(m,a,l,"out");p&&u.push(p);}let g=u.length>c;return {root:a,callees:g?u.slice(0,c):u,truncated:g}}async function Ae(e,t){if(!t.query)throw new utils.ServiceError({code:"NOT_FOUND",message:"explore requires a non-empty query",details:{query:t.query}});let s=await P(e),l=s.getQuery(),a=s.getDatabase(),c=database.resolveSqlTextLimit(t.snippetMaxChars??database.SQL_TEXT_LIMIT_DEFAULT),d=(await re(e,{query:t.query,file:t.file,kind:t.kind,intent:t.intent,maxResults:t.maxFiles??5,enableFts:true,enableEmbedding:true,snippetMaxChars:c})).hits;if(t.file||t.kind)try{let m=await $(l,e,{name:t.query,file:t.file,kind:t.kind});if(m?.node){let p={nodeId:m.node.id,name:m.node.name,kind:m.node.ast_type,filePath:N(m.node.file_path),startLine:m.node.start_line,endLine:m.node.end_line,edges:[],source:"basic",score:0,snippet:(m.node.text??"").slice(0,c).replace(/\s+/g," ").trim()},f=d.filter(E=>E.nodeId!==p.nodeId);d=[p,...f];}}catch{}let r=new Map;for(let m of d){let p=N(m.filePath),f=r.get(p);f?f.push(m):r.set(p,[m]);}let o=t.maxSymbols??3,u=t.maxEdgesPerNode??10,g=[];for(let[m,p]of r){let f=p.slice(0,o),E=[];for(let h of f){let C=await se(e,{name:h.name,file:m,kind:t.kind,maxResults:u,maxEdgesPerNode:u}),x=await ie(e,{name:h.name,file:m,kind:t.kind,maxResults:u,maxEdgesPerNode:u});E.push({node:(()=>{let y={id:h.nodeId,name:h.name,ast_type:h.kind,language:"ts",file_path:h.filePath,start_line:h.startLine??0,end_line:h.endLine??0};try{let I=a.getNodeById(h.nodeId);return {...y,text:I?.text??""}}catch{return {...y,text:""}}})(),callers:C.callers,callees:x.callees});}g.push({file:m,symbols:E});}return {query:t.query,entryPoints:g,totalHits:d.length}}async function De(e,t){let s=await(await P(e)).getStatus();s.package="codebase",s.workspaceDir=e.workspaceDir;let l=chunkTBDAGLC4_cjs.b(e.workspaceDir),a=fs.existsSync(l),c=fs.existsSync(s.dbPath),i;if(c)try{i=fs.statSync(s.dbPath).size;}catch{}s.configPath=l,s.configExists=a,s.dbExists=c,s.dbSize=i,s.vectorEnabled=s.meta?.vector_enabled==="true"||s.meta?.vector_enabled==="1";let d=s.meta?.embeddingDims;d&&Number.isFinite(Number.parseInt(d,10))&&(s.embeddingDims=Number.parseInt(d,10));let r={initialized:false,capabilities:{embedding:false,evaluation:false}};try{let{Llm:o}=await import('./llm-S6D5ICOO.cjs');if(o.isInitialized()){r.initialized=!0;let u=o.capabilities();r.capabilities={embedding:u.embedding===!0,evaluation:u.evaluation===!0},r.embeddingModel=r.capabilities.embedding?"configured":void 0,r.evaluationModel=r.capabilities.evaluation?"configured":void 0;}}catch{}s.llm=r;try{let{DatabaseManager:o}=await import('./database-manager-LTHK7MM6.cjs'),u=new o(s.dbPath);try{let{stats:g}=u.checkIntegrity();s.dbStats=g,s.ftsAvailable=u.isFtsAvailable();}finally{u.close();}}catch{}return s}async function Oe(e,t){return await(await P(e)).healthCheck()}var Me=utils.Log.create({service:"codebase.services.init"}),ae=false;async function He(){ae||(ae=true,Me.info("codebase service init"),await utils.ServiceErrorBus.init(),await chunkW5SMGCKO_cjs.e());}var Ue=200,le=utils.Filesystem.toUnixPath;function ze(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 Ke(e){let t=e.text??"";if(!t)return [];let n=t.slice(0,80),s=[];return /\basync\s/.test(n)&&s.push("async"),/\bstatic\s/.test(n)&&s.push("static"),/\babstract\s/.test(n)&&s.push("abstract"),/\breadonly\s/.test(n)&&s.push("readonly"),/\bconst\s/.test(n)&&s.push("const"),/\blet\s/.test(n)&&s.push("let"),s}function R(e){return {id:e.id,name:e.name,astType:e.ast_type,language:e.language,filePath:le(e.file_path),startLine:e.start_line??0,endLine:e.end_line??0,isExported:ze(e),modifiers:Ke(e)}}function _(e,t){return {id:e.id,source:e.source,target:e.target,relation:e.relation,direction:t}}function z(e){return e.map(t=>({node:{id:t.nodeId,name:t.name,astType:t.kind,language:"typescript",filePath:le(t.filePath),startLine:t.startLine??0,endLine:t.endLine??0,isExported:false,modifiers:[]},source:t.source,score:t.score,snippet:(t.snippet??"").slice(0,database.resolveSqlTextLimit(Ue)),edges:(t.edges??[]).slice(0,10).map(n=>_({...n}))}))}function K(){return {id:"",name:"",astType:"",language:"",filePath:"",startLine:0,endLine:0,isExported:false,modifiers:[]}}var Ge=utils.Log.create({service:"codebase.format.truncate"}),j="**`",Qe="**",ce=24e3,ue=25e3;async function D(e,t={}){let n=t.softLimit??ce,s=t.hardCeiling??ue,l=t.toolName??"codebase",a=t.writeToDisk!==false;if(e.length<=n)return {content:e,truncated:false};let c=e.slice(0,s),i=c.lastIndexOf(`
25
+ `;return e.queryAll(a,[...n,t.id,s])}function ne(e,t,n,s){let l=s==="in"?e.source:e.target;t.id;let c=n.getNodeById(l);if(!c&&l.includes(":*:")){let i=l.split(":").pop()??l,d=i.split("@")[0]??i;if(d&&d!==l){let r=n.findNodesByName({name:d}),o=t.file_path??"",u=o.split(/[/\\]/).pop()??"",g=o.split(/[/\\]/).filter(Boolean),m=r.find(p=>p.node.file_path?p.node.file_path===o:false)??r.find(p=>!p.node.file_path||!u?false:p.node.file_path.split(/[/\\]/).pop()===u)??r.find(p=>{if(!p.node.file_path)return false;let f=p.node.file_path.split(/[/\\]/).filter(Boolean);return g.length<2||f.length<2?false:g[0]===f[0]&&g[1]===f[1]})??null;m&&(c=m.node);}}if(!c){let i=l.split(":").pop()??l;return {id:l,name:i,astType:"unresolved",filePath:"(unresolved)",startLine:0,relation:e.relation}}return {id:c.id,name:c.name,astType:c.ast_type,filePath:N(c.file_path),startLine:c.start_line??0,relation:e.relation}}async function re(e,t){let n=Date.now(),l=(await P(e)).getQuery(),a=database.resolveSqlTextLimit(t.snippetMaxChars??database.SQL_TEXT_LIMIT_DEFAULT),i=await l.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,snippetMaxChars:a});if(t.kind){let o=t.kind.toLowerCase();i=i.filter(u=>u.ast_type.includes(o)||u.name.toLowerCase().includes(o));}if(t.file){let o=N(t.file);i=i.filter(u=>N(u.file_path).endsWith(o)||N(u.file_path).includes(o));}let d=t.maxEdgesPerNode??10,r=i.map(o=>({nodeId:o.id,name:o.name,kind:o.ast_type??"unknown",filePath:N(o.file_path),startLine:o.start_line,endLine:o.end_line,edges:(o.edges??[]).slice(0,d),source:"basic",score:0,snippet:(o.text??"").slice(0,a).replace(/\s+/g," ").trim()}));return {total:r.length,hits:r,durationMs:Date.now()-n,truncated:false}}async function Ie(e,t){let n=await P(e),s=n.getQuery(),l=n.getDatabase(),{node:a}=await $(s,e,t),c=[];if(t.includeEdges){let i=t.maxEdgesPerNode??10,d=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"],r=U(l,a,d,i+1),o=te(l,a,d,i+1),u=new Set,g=[];for(let m of [...r,...o])m.id&&!u.has(m.id)&&(u.add(m.id),g.push(m));c=g.slice(0,i);}return {node:a,edges:c}}var Le=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"];async function Te(e,t){let n=await P(e),s=n.getQuery(),l=n.getDatabase(),{node:a}=await $(s,e,t);if(!a)return {root:null,nodes:[],edges:[],truncated:false,totalNodes:0,totalEdges:0};let c=t.depth??2,i=t.maxNodes??100,d=t.direction??"both";t.maxEdgesPerNode??10;let o=new Map,u=[{nodeId:a.id,depth:0}];o.set(a.id,0);let g=[],m=false;for(;u.length>0;){let y=u.shift();if(y.depth>=c)continue;if(o.size>=i){m=true;break}let I=s.queryNeighbors(y.nodeId,{direction:d,relationTypes:t.relationTypes??Le,limit:i-o.size+1});for(let b of I.edges){g.push(b);let L=b.source===y.nodeId?b.target:b.source;if(!o.has(L)&&(o.set(L,y.depth+1),u.push({nodeId:L,depth:y.depth+1}),o.size>=i)){m=true;break}}if(m)break}let p=new Set,f=[];for(let y of g)!y.id||p.has(y.id)||(p.add(y.id),f.push(y));let E=Array.from(o.keys()),h=E.length>0?l.queryNodes({ids:E}):[],C=new Map(h.map(y=>[y.id,y])),x=[];for(let[y,I]of o.entries()){let b=C.get(y);b&&x.push({node:b,depth:I});}return {root:a,nodes:x,edges:f,truncated:m,totalNodes:x.length,totalEdges:g.length}}var $e=["CALLS","IMPORTS","TYPE_REFERENCES"];async function _e(e,t){let n=await P(e),s=n.getQuery(),l=n.getDatabase(),{node:a}=await $(s,e,t);if(!a)return {root:null,totalImpacted:0,buckets:[]};let c=t.depth??2,i=t.maxResults??10,d=t.relationTypes??$e,r=t.maxEdgesPerNode??10,o=new Set([a.id]),u=[],g=[a.id];for(let m=1;m<=c&&!(g.length===0||o.size-1>=i);m++){let p=U(l,a,d,r+1),f=[],E=new Set;for(let h of p)if(!o.has(h.source)&&!E.has(h.source)&&(E.add(h.source),o.add(h.source),f.push(h.source),o.size-1>=i))break;if(f.length>0){let h=f.slice(0,10),C=l.queryNodes({ids:h}),x=new Map(C.map(b=>[b.id,b])),y=new Map;for(let b of p)y.has(b.source)||y.set(b.source,b.relation);let I=h.map(b=>{let L=x.get(b);return {id:b,name:L?.name??"(unknown)",filePath:L?N(L.file_path):"(unknown)",relation:y.get(b)??"CALLS"}});u.push({depth:m,count:f.length,sample:I});}g=f;}return u.length===0&&ee.warn("impact: no incoming edges found",{root:a.name,depth:c,relationTypes:d}),{root:a,totalImpacted:o.size-1,buckets:u}}var oe=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","METHOD_OVERRIDES"];async function we(e,t){return se(e,t)}async function Fe(e,t){return ie(e,t)}async function se(e,t){let n=await P(e),s=n.getQuery(),l=n.getDatabase(),{node:a}=await $(s,e,t);if(!a)return {root:null,callers:[],truncated:false};let c=t.maxResults??10,i=t.maxEdgesPerNode??c,d=t.relationTypes??oe,r=U(l,a,d,i+1),o=[];for(let g of r){let m=ne(g,a,l,"in");m&&o.push(m);}let u=o.length>c;return {root:a,callers:u?o.slice(0,c):o,truncated:u}}async function ie(e,t){let n=await P(e),s=n.getQuery(),l=n.getDatabase(),{node:a}=await $(s,e,t);if(!a)return {root:null,callees:[],truncated:false};let c=t.maxResults??10,i=t.maxEdgesPerNode??c,d=t.relationTypes??oe,r=te(l,a,d,i+1),o=Se(a.ast_type)?Ce(l,a,r,d,i+1):r,u=[];for(let m of o){let p=ne(m,a,l,"out");p&&u.push(p);}let g=u.length>c;return {root:a,callees:g?u.slice(0,c):u,truncated:g}}async function Ae(e,t){if(!t.query)throw new utils.ServiceError({code:"NOT_FOUND",message:"explore requires a non-empty query",details:{query:t.query}});let s=await P(e),l=s.getQuery(),a=s.getDatabase(),c=database.resolveSqlTextLimit(t.snippetMaxChars??database.SQL_TEXT_LIMIT_DEFAULT),d=(await re(e,{query:t.query,file:t.file,kind:t.kind,intent:t.intent,maxResults:t.maxFiles??5,enableFts:true,enableEmbedding:true,snippetMaxChars:c})).hits;if(t.file||t.kind)try{let m=await $(l,e,{name:t.query,file:t.file,kind:t.kind});if(m?.node){let p={nodeId:m.node.id,name:m.node.name,kind:m.node.ast_type,filePath:N(m.node.file_path),startLine:m.node.start_line,endLine:m.node.end_line,edges:[],source:"basic",score:0,snippet:(m.node.text??"").slice(0,c).replace(/\s+/g," ").trim()},f=d.filter(E=>E.nodeId!==p.nodeId);d=[p,...f];}}catch{}let r=new Map;for(let m of d){let p=N(m.filePath),f=r.get(p);f?f.push(m):r.set(p,[m]);}let o=t.maxSymbols??3,u=t.maxEdgesPerNode??10,g=[];for(let[m,p]of r){let f=p.slice(0,o),E=[];for(let h of f){let C=await se(e,{name:h.name,file:m,kind:t.kind,maxResults:u,maxEdgesPerNode:u}),x=await ie(e,{name:h.name,file:m,kind:t.kind,maxResults:u,maxEdgesPerNode:u});E.push({node:(()=>{let y={id:h.nodeId,name:h.name,ast_type:h.kind,language:"ts",file_path:h.filePath,start_line:h.startLine??0,end_line:h.endLine??0};try{let I=a.getNodeById(h.nodeId);return {...y,text:I?.text??""}}catch{return {...y,text:""}}})(),callers:C.callers,callees:x.callees});}g.push({file:m,symbols:E});}return {query:t.query,entryPoints:g,totalHits:d.length}}async function De(e,t){let s=await(await P(e)).getStatus();s.package="codebase",s.workspaceDir=e.workspaceDir;let l=chunk3DAM6EZN_cjs.b(e.workspaceDir),a=fs.existsSync(l),c=fs.existsSync(s.dbPath),i;if(c)try{i=fs.statSync(s.dbPath).size;}catch{}s.configPath=l,s.configExists=a,s.dbExists=c,s.dbSize=i,s.vectorEnabled=s.meta?.vector_enabled==="true"||s.meta?.vector_enabled==="1";let d=s.meta?.embeddingDims;d&&Number.isFinite(Number.parseInt(d,10))&&(s.embeddingDims=Number.parseInt(d,10));let r={initialized:false,capabilities:{embedding:false,evaluation:false}};try{let{Llm:o}=await import('./llm-UYBJKQ3S.cjs');if(o.isInitialized()){r.initialized=!0;let u=o.capabilities();r.capabilities={embedding:u.embedding===!0,evaluation:u.evaluation===!0},r.embeddingModel=r.capabilities.embedding?"configured":void 0,r.evaluationModel=r.capabilities.evaluation?"configured":void 0;}}catch{}s.llm=r;try{let{DatabaseManager:o}=await import('./database-manager-T43UZZ45.cjs'),u=new o(s.dbPath);try{let{stats:g}=u.checkIntegrity();s.dbStats=g,s.ftsAvailable=u.isFtsAvailable();}finally{u.close();}}catch{}return s}async function Oe(e,t){return await(await P(e)).healthCheck()}var Me=utils.Log.create({service:"codebase.services.init"}),ae=false;async function He(){ae||(ae=true,Me.info("codebase service init"),await utils.ServiceErrorBus.init(),await chunkW5SMGCKO_cjs.e());}var Ue=200,le=utils.Filesystem.toUnixPath;function ze(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 Ke(e){let t=e.text??"";if(!t)return [];let n=t.slice(0,80),s=[];return /\basync\s/.test(n)&&s.push("async"),/\bstatic\s/.test(n)&&s.push("static"),/\babstract\s/.test(n)&&s.push("abstract"),/\breadonly\s/.test(n)&&s.push("readonly"),/\bconst\s/.test(n)&&s.push("const"),/\blet\s/.test(n)&&s.push("let"),s}function R(e){return {id:e.id,name:e.name,astType:e.ast_type,language:e.language,filePath:le(e.file_path),startLine:e.start_line??0,endLine:e.end_line??0,isExported:ze(e),modifiers:Ke(e)}}function _(e,t){return {id:e.id,source:e.source,target:e.target,relation:e.relation,direction:t}}function z(e){return e.map(t=>({node:{id:t.nodeId,name:t.name,astType:t.kind,language:"typescript",filePath:le(t.filePath),startLine:t.startLine??0,endLine:t.endLine??0,isExported:false,modifiers:[]},source:t.source,score:t.score,snippet:(t.snippet??"").slice(0,database.resolveSqlTextLimit(Ue)),edges:(t.edges??[]).slice(0,10).map(n=>_({...n}))}))}function K(){return {id:"",name:"",astType:"",language:"",filePath:"",startLine:0,endLine:0,isExported:false,modifiers:[]}}var Ge=utils.Log.create({service:"codebase.format.truncate"}),j="**`",Qe="**",ce=24e3,ue=25e3;async function D(e,t={}){let n=t.softLimit??ce,s=t.hardCeiling??ue,l=t.toolName??"codebase",a=t.writeToDisk!==false;if(e.length<=n)return {content:e,truncated:false};let c=e.slice(0,s),i=c.lastIndexOf(`
26
26
  ${j}`),d=c.lastIndexOf(`
27
27
  `),r;i>s*.5?r=i:d>0?r=d:r=-1;let o=r>0?c.slice(0,r):c,g=o+"\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(!a)return {content:g,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-o.length}/${e.length} characters truncated ...`};try{let m=await utils.TruncateContent.truncate(e,{maxChars:o.length,direction:"head",label:`${l}-output`});return m.truncated?{content:g,truncated:!0,outputPath:m.outputPath,hint:utils.TruncateContent.formatHint(m),info:`... ${m.removedLength}/${m.originalLength} characters truncated ...`}:{content:g,truncated:!0,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-o.length}/${e.length} characters truncated ...`}}catch(m){return Ge.warn("TruncateContent.truncate failed, returning without disk hint",{error:utils.errorMeta(m)}),{content:g,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-o.length}/${e.length} characters truncated ...`}}}function O(e,t={}){let n=t.softLimit??ce,s=t.hardCeiling??ue;if(e.length<=n)return {content:e,truncated:false};let l=e.slice(0,s),a=l.lastIndexOf(`
28
28
  ${j}`),c=l.lastIndexOf(`
@@ -0,0 +1 @@
1
+ export{c as COMMANDS_HELP,d as handleCodebaseCli,e as mapCodebaseDoctor,a as renderBanner,b as renderHelp}from'./chunk-OUJNWRIY.mjs';import'./chunk-FZNMPXUO.mjs';import'./chunk-ETCTXAXR.mjs';import'./chunk-H4VZF3ZQ.mjs';import'./chunk-ECMVXJH2.mjs';import'./chunk-QZMJ5EUF.mjs';import'./chunk-EU2I2AMK.mjs';import'./chunk-KTSR5VPT.mjs';import'./chunk-ESA2CL57.mjs';import'./chunk-43WAI4Z7.mjs';import'./chunk-47LKNS74.mjs';
@@ -0,0 +1 @@
1
+ 'use strict';var chunk6NYX22KV_cjs=require('./chunk-6NYX22KV.cjs');require('./chunk-VXLUR7M5.cjs'),require('./chunk-Y7JDLK56.cjs'),require('./chunk-J7Z3MIR7.cjs'),require('./chunk-D5NDNAKA.cjs'),require('./chunk-3DAM6EZN.cjs'),require('./chunk-AARBEAIB.cjs'),require('./chunk-W5SMGCKO.cjs'),require('./chunk-EH2QTB6S.cjs'),require('./chunk-VZCOLSBF.cjs'),require('./chunk-R32346OA.cjs');Object.defineProperty(exports,"COMMANDS_HELP",{enumerable:true,get:function(){return chunk6NYX22KV_cjs.c}});Object.defineProperty(exports,"handleCodebaseCli",{enumerable:true,get:function(){return chunk6NYX22KV_cjs.d}});Object.defineProperty(exports,"mapCodebaseDoctor",{enumerable:true,get:function(){return chunk6NYX22KV_cjs.e}});Object.defineProperty(exports,"renderBanner",{enumerable:true,get:function(){return chunk6NYX22KV_cjs.a}});Object.defineProperty(exports,"renderHelp",{enumerable:true,get:function(){return chunk6NYX22KV_cjs.b}});
@@ -1 +1 @@
1
- export{r as CodeBase,l as EdgeExtractor,f as FILE_EXTENSION_MAP,n as Indexer,j as NodeExtractor,g as ParserManager,p as QueryInterface,s as createCodebase,m as createEdgeExtractor,o as createIndexer,k as createNodeExtractor,q as createQueryInterface,h as getParserManager,i as resetParserManager}from'./chunk-KR6BQNY6.mjs';export{f as DatabaseManager}from'./chunk-33DIOGLJ.mjs';export{c as CODEBASE_BUSINESS_CODES,d as CODEBASE_BUSINESS_HINTS,b as CodebaseError,a as ServiceError,e as registerBusinessErrors}from'./chunk-KTSR5VPT.mjs';import'./chunk-ESA2CL57.mjs';export{a as DEFAULT_EMBEDDING_CONFIG,b as DEFAULT_INDEXER_CONFIG,c as DEFAULT_PARSER_CONFIG,d as DEFAULT_TOKENIZER_CONFIG}from'./chunk-43WAI4Z7.mjs';import'./chunk-T6KJWYTV.mjs';
1
+ export{r as CodeBase,l as EdgeExtractor,f as FILE_EXTENSION_MAP,n as Indexer,j as NodeExtractor,g as ParserManager,p as QueryInterface,s as createCodebase,m as createEdgeExtractor,o as createIndexer,k as createNodeExtractor,q as createQueryInterface,h as getParserManager,i as resetParserManager}from'./chunk-QZMJ5EUF.mjs';export{f as DatabaseManager}from'./chunk-EU2I2AMK.mjs';export{c as CODEBASE_BUSINESS_CODES,d as CODEBASE_BUSINESS_HINTS,b as CodebaseError,a as ServiceError,e as registerBusinessErrors}from'./chunk-KTSR5VPT.mjs';import'./chunk-ESA2CL57.mjs';export{a as DEFAULT_EMBEDDING_CONFIG,b as DEFAULT_INDEXER_CONFIG,c as DEFAULT_PARSER_CONFIG,d as DEFAULT_TOKENIZER_CONFIG}from'./chunk-43WAI4Z7.mjs';import'./chunk-47LKNS74.mjs';
@@ -1 +1 @@
1
- 'use strict';var chunkTBDAGLC4_cjs=require('./chunk-TBDAGLC4.cjs'),chunkOZYQQS63_cjs=require('./chunk-OZYQQS63.cjs'),chunkW5SMGCKO_cjs=require('./chunk-W5SMGCKO.cjs');require('./chunk-EH2QTB6S.cjs');var chunkVZCOLSBF_cjs=require('./chunk-VZCOLSBF.cjs');require('./chunk-KFESJR3T.cjs');Object.defineProperty(exports,"CodeBase",{enumerable:true,get:function(){return chunkTBDAGLC4_cjs.r}});Object.defineProperty(exports,"EdgeExtractor",{enumerable:true,get:function(){return chunkTBDAGLC4_cjs.l}});Object.defineProperty(exports,"FILE_EXTENSION_MAP",{enumerable:true,get:function(){return chunkTBDAGLC4_cjs.f}});Object.defineProperty(exports,"Indexer",{enumerable:true,get:function(){return chunkTBDAGLC4_cjs.n}});Object.defineProperty(exports,"NodeExtractor",{enumerable:true,get:function(){return chunkTBDAGLC4_cjs.j}});Object.defineProperty(exports,"ParserManager",{enumerable:true,get:function(){return chunkTBDAGLC4_cjs.g}});Object.defineProperty(exports,"QueryInterface",{enumerable:true,get:function(){return chunkTBDAGLC4_cjs.p}});Object.defineProperty(exports,"createCodebase",{enumerable:true,get:function(){return chunkTBDAGLC4_cjs.s}});Object.defineProperty(exports,"createEdgeExtractor",{enumerable:true,get:function(){return chunkTBDAGLC4_cjs.m}});Object.defineProperty(exports,"createIndexer",{enumerable:true,get:function(){return chunkTBDAGLC4_cjs.o}});Object.defineProperty(exports,"createNodeExtractor",{enumerable:true,get:function(){return chunkTBDAGLC4_cjs.k}});Object.defineProperty(exports,"createQueryInterface",{enumerable:true,get:function(){return chunkTBDAGLC4_cjs.q}});Object.defineProperty(exports,"getParserManager",{enumerable:true,get:function(){return chunkTBDAGLC4_cjs.h}});Object.defineProperty(exports,"resetParserManager",{enumerable:true,get:function(){return chunkTBDAGLC4_cjs.i}});Object.defineProperty(exports,"DatabaseManager",{enumerable:true,get:function(){return chunkOZYQQS63_cjs.f}});Object.defineProperty(exports,"CODEBASE_BUSINESS_CODES",{enumerable:true,get:function(){return chunkW5SMGCKO_cjs.c}});Object.defineProperty(exports,"CODEBASE_BUSINESS_HINTS",{enumerable:true,get:function(){return chunkW5SMGCKO_cjs.d}});Object.defineProperty(exports,"CodebaseError",{enumerable:true,get:function(){return chunkW5SMGCKO_cjs.b}});Object.defineProperty(exports,"ServiceError",{enumerable:true,get:function(){return chunkW5SMGCKO_cjs.a}});Object.defineProperty(exports,"registerBusinessErrors",{enumerable:true,get:function(){return chunkW5SMGCKO_cjs.e}});Object.defineProperty(exports,"DEFAULT_EMBEDDING_CONFIG",{enumerable:true,get:function(){return chunkVZCOLSBF_cjs.a}});Object.defineProperty(exports,"DEFAULT_INDEXER_CONFIG",{enumerable:true,get:function(){return chunkVZCOLSBF_cjs.b}});Object.defineProperty(exports,"DEFAULT_PARSER_CONFIG",{enumerable:true,get:function(){return chunkVZCOLSBF_cjs.c}});Object.defineProperty(exports,"DEFAULT_TOKENIZER_CONFIG",{enumerable:true,get:function(){return chunkVZCOLSBF_cjs.d}});
1
+ 'use strict';var chunk3DAM6EZN_cjs=require('./chunk-3DAM6EZN.cjs'),chunkAARBEAIB_cjs=require('./chunk-AARBEAIB.cjs'),chunkW5SMGCKO_cjs=require('./chunk-W5SMGCKO.cjs');require('./chunk-EH2QTB6S.cjs');var chunkVZCOLSBF_cjs=require('./chunk-VZCOLSBF.cjs');require('./chunk-R32346OA.cjs');Object.defineProperty(exports,"CodeBase",{enumerable:true,get:function(){return chunk3DAM6EZN_cjs.r}});Object.defineProperty(exports,"EdgeExtractor",{enumerable:true,get:function(){return chunk3DAM6EZN_cjs.l}});Object.defineProperty(exports,"FILE_EXTENSION_MAP",{enumerable:true,get:function(){return chunk3DAM6EZN_cjs.f}});Object.defineProperty(exports,"Indexer",{enumerable:true,get:function(){return chunk3DAM6EZN_cjs.n}});Object.defineProperty(exports,"NodeExtractor",{enumerable:true,get:function(){return chunk3DAM6EZN_cjs.j}});Object.defineProperty(exports,"ParserManager",{enumerable:true,get:function(){return chunk3DAM6EZN_cjs.g}});Object.defineProperty(exports,"QueryInterface",{enumerable:true,get:function(){return chunk3DAM6EZN_cjs.p}});Object.defineProperty(exports,"createCodebase",{enumerable:true,get:function(){return chunk3DAM6EZN_cjs.s}});Object.defineProperty(exports,"createEdgeExtractor",{enumerable:true,get:function(){return chunk3DAM6EZN_cjs.m}});Object.defineProperty(exports,"createIndexer",{enumerable:true,get:function(){return chunk3DAM6EZN_cjs.o}});Object.defineProperty(exports,"createNodeExtractor",{enumerable:true,get:function(){return chunk3DAM6EZN_cjs.k}});Object.defineProperty(exports,"createQueryInterface",{enumerable:true,get:function(){return chunk3DAM6EZN_cjs.q}});Object.defineProperty(exports,"getParserManager",{enumerable:true,get:function(){return chunk3DAM6EZN_cjs.h}});Object.defineProperty(exports,"resetParserManager",{enumerable:true,get:function(){return chunk3DAM6EZN_cjs.i}});Object.defineProperty(exports,"DatabaseManager",{enumerable:true,get:function(){return chunkAARBEAIB_cjs.f}});Object.defineProperty(exports,"CODEBASE_BUSINESS_CODES",{enumerable:true,get:function(){return chunkW5SMGCKO_cjs.c}});Object.defineProperty(exports,"CODEBASE_BUSINESS_HINTS",{enumerable:true,get:function(){return chunkW5SMGCKO_cjs.d}});Object.defineProperty(exports,"CodebaseError",{enumerable:true,get:function(){return chunkW5SMGCKO_cjs.b}});Object.defineProperty(exports,"ServiceError",{enumerable:true,get:function(){return chunkW5SMGCKO_cjs.a}});Object.defineProperty(exports,"registerBusinessErrors",{enumerable:true,get:function(){return chunkW5SMGCKO_cjs.e}});Object.defineProperty(exports,"DEFAULT_EMBEDDING_CONFIG",{enumerable:true,get:function(){return chunkVZCOLSBF_cjs.a}});Object.defineProperty(exports,"DEFAULT_INDEXER_CONFIG",{enumerable:true,get:function(){return chunkVZCOLSBF_cjs.b}});Object.defineProperty(exports,"DEFAULT_PARSER_CONFIG",{enumerable:true,get:function(){return chunkVZCOLSBF_cjs.c}});Object.defineProperty(exports,"DEFAULT_TOKENIZER_CONFIG",{enumerable:true,get:function(){return chunkVZCOLSBF_cjs.d}});
@@ -0,0 +1 @@
1
+ 'use strict';var chunkAARBEAIB_cjs=require('./chunk-AARBEAIB.cjs');require('./chunk-W5SMGCKO.cjs'),require('./chunk-R32346OA.cjs');Object.defineProperty(exports,"DatabaseManager",{enumerable:true,get:function(){return chunkAARBEAIB_cjs.f}});Object.defineProperty(exports,"EXTRACTION_VERSION",{enumerable:true,get:function(){return chunkAARBEAIB_cjs.e}});Object.defineProperty(exports,"getDbPath",{enumerable:true,get:function(){return chunkAARBEAIB_cjs.h}});Object.defineProperty(exports,"isClosed",{enumerable:true,get:function(){return chunkAARBEAIB_cjs.g}});Object.defineProperty(exports,"transaction",{enumerable:true,get:function(){return chunkAARBEAIB_cjs.i}});
@@ -0,0 +1 @@
1
+ export{f as DatabaseManager,e as EXTRACTION_VERSION,h as getDbPath,g as isClosed,i as transaction}from'./chunk-EU2I2AMK.mjs';import'./chunk-KTSR5VPT.mjs';import'./chunk-47LKNS74.mjs';
@@ -0,0 +1 @@
1
+ 'use strict';var chunkD5NDNAKA_cjs=require('./chunk-D5NDNAKA.cjs');require('./chunk-R32346OA.cjs');Object.defineProperty(exports,"FileWatcher",{enumerable:true,get:function(){return chunkD5NDNAKA_cjs.a}});Object.defineProperty(exports,"clearWatcherPid",{enumerable:true,get:function(){return chunkD5NDNAKA_cjs.e}});Object.defineProperty(exports,"getWatcherPidPath",{enumerable:true,get:function(){return chunkD5NDNAKA_cjs.b}});Object.defineProperty(exports,"readWatcherPid",{enumerable:true,get:function(){return chunkD5NDNAKA_cjs.c}});Object.defineProperty(exports,"writeWatcherPid",{enumerable:true,get:function(){return chunkD5NDNAKA_cjs.d}});
@@ -0,0 +1 @@
1
+ export{a as FileWatcher,e as clearWatcherPid,b as getWatcherPidPath,c as readWatcherPid,d as writeWatcherPid}from'./chunk-ECMVXJH2.mjs';import'./chunk-47LKNS74.mjs';
@@ -1 +1 @@
1
- export{c as getGlobal,g as getHomeDir,f as getInstance,l as getProjectDirectory,k as getXdgCache,i as getXdgConfig,h as getXdgData,j as getXdgState,b as resetGlobalAdapter,e as resetInstanceAdapter,a as setGlobalAdapter,d as setInstanceAdapter}from'./chunk-H4VZF3ZQ.mjs';import'./chunk-T6KJWYTV.mjs';
1
+ export{c as getGlobal,g as getHomeDir,f as getInstance,l as getProjectDirectory,k as getXdgCache,i as getXdgConfig,h as getXdgData,j as getXdgState,b as resetGlobalAdapter,e as resetInstanceAdapter,a as setGlobalAdapter,d as setInstanceAdapter}from'./chunk-H4VZF3ZQ.mjs';import'./chunk-47LKNS74.mjs';
@@ -1 +1 @@
1
- 'use strict';var chunkJ7Z3MIR7_cjs=require('./chunk-J7Z3MIR7.cjs');require('./chunk-KFESJR3T.cjs');Object.defineProperty(exports,"getGlobal",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.c}});Object.defineProperty(exports,"getHomeDir",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.g}});Object.defineProperty(exports,"getInstance",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.f}});Object.defineProperty(exports,"getProjectDirectory",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.l}});Object.defineProperty(exports,"getXdgCache",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.k}});Object.defineProperty(exports,"getXdgConfig",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.i}});Object.defineProperty(exports,"getXdgData",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.h}});Object.defineProperty(exports,"getXdgState",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.j}});Object.defineProperty(exports,"resetGlobalAdapter",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.b}});Object.defineProperty(exports,"resetInstanceAdapter",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.e}});Object.defineProperty(exports,"setGlobalAdapter",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.a}});Object.defineProperty(exports,"setInstanceAdapter",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.d}});
1
+ 'use strict';var chunkJ7Z3MIR7_cjs=require('./chunk-J7Z3MIR7.cjs');require('./chunk-R32346OA.cjs');Object.defineProperty(exports,"getGlobal",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.c}});Object.defineProperty(exports,"getHomeDir",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.g}});Object.defineProperty(exports,"getInstance",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.f}});Object.defineProperty(exports,"getProjectDirectory",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.l}});Object.defineProperty(exports,"getXdgCache",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.k}});Object.defineProperty(exports,"getXdgConfig",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.i}});Object.defineProperty(exports,"getXdgData",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.h}});Object.defineProperty(exports,"getXdgState",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.j}});Object.defineProperty(exports,"resetGlobalAdapter",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.b}});Object.defineProperty(exports,"resetInstanceAdapter",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.e}});Object.defineProperty(exports,"setGlobalAdapter",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.a}});Object.defineProperty(exports,"setInstanceAdapter",{enumerable:true,get:function(){return chunkJ7Z3MIR7_cjs.d}});
@@ -1 +1 @@
1
- export{a as Llm,b as llm}from'./chunk-ESA2CL57.mjs';import'./chunk-43WAI4Z7.mjs';import'./chunk-T6KJWYTV.mjs';
1
+ export{a as Llm,b as llm}from'./chunk-ESA2CL57.mjs';import'./chunk-43WAI4Z7.mjs';import'./chunk-47LKNS74.mjs';
@@ -1 +1 @@
1
- 'use strict';var chunkEH2QTB6S_cjs=require('./chunk-EH2QTB6S.cjs');require('./chunk-VZCOLSBF.cjs'),require('./chunk-KFESJR3T.cjs');Object.defineProperty(exports,"Llm",{enumerable:true,get:function(){return chunkEH2QTB6S_cjs.a}});Object.defineProperty(exports,"llm",{enumerable:true,get:function(){return chunkEH2QTB6S_cjs.b}});
1
+ 'use strict';var chunkEH2QTB6S_cjs=require('./chunk-EH2QTB6S.cjs');require('./chunk-VZCOLSBF.cjs'),require('./chunk-R32346OA.cjs');Object.defineProperty(exports,"Llm",{enumerable:true,get:function(){return chunkEH2QTB6S_cjs.a}});Object.defineProperty(exports,"llm",{enumerable:true,get:function(){return chunkEH2QTB6S_cjs.b}});
@@ -1,4 +1,4 @@
1
- 'use strict';var chunkCLUGDJA5_cjs=require('./chunk-CLUGDJA5.cjs');require('./chunk-TBDAGLC4.cjs'),require('./chunk-OZYQQS63.cjs'),require('./chunk-W5SMGCKO.cjs'),require('./chunk-EH2QTB6S.cjs'),require('./chunk-VZCOLSBF.cjs'),require('./chunk-KFESJR3T.cjs');var mcp=require('@easbot/mcp'),utils=require('@easbot/utils');var f=utils.Log.create({service:"codebase.mcp.stdio"}),Q=["query","node","context","impact","callers","callees","explore","status","doctor"];exports.CodebaseStdioServer=void 0;(t=>{let n;function s(){return n||(f.debug("initializing CodebaseStdioServer state factory (lazy)"),n=()=>({toolNames:[...Q],cachedConfigId:"",cachedConfigName:"",cachedConfigVersion:""})),n}async function a(o,r){let p=s()(),g=(process.env.EASBOT_MCP_TRUSTED_LOCAL??"true").toLowerCase()!=="false",l=new mcp.ToolRegistry;me(l,o,g);let y=p.toolNames;f.info("starting codebase MCP stdio server",{id:r.id,name:r.name,toolCount:y.length});let h=await mcp.createAndStartStdioServer(r,l),E=null,$=new Promise(c=>{E=c;}),S=c=>{f.info("received signal, stopping MCP server",{signal:c}),E?.();},T=()=>S("SIGINT"),N=()=>S("SIGTERM");process.on("SIGINT",T),process.on("SIGTERM",N);try{await $;}finally{try{process.off("SIGINT",T),process.off("SIGTERM",N);}catch(c){f.warn("failed to remove signal handlers",{error:utils.errorMeta(c)});}try{await h.stop();}catch(c){f.warn("server.stop failed during cleanup",{error:utils.errorMeta(c)});}try{await o.close();}catch(c){f.warn("codebase.close failed during cleanup",{error:utils.errorMeta(c)});}}return {id:r.id,name:r.name,version:r.version,tools:y}}t.start=a;function d(){return s()().toolNames}t.getToolNames=d;function e(){n=void 0;}t.__resetForTests=e;})(exports.CodebaseStdioServer||(exports.CodebaseStdioServer={}));var X={readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false},z={type:"object",additionalProperties:false,properties:{query:{type:"string",description:'Symbol name or partial name (e.g., "auth", "UserService"). Empty string returns recent nodes.'},kind:{type:"string",description:"Filter by node kind. One of: class, function, method, interface, type, variable, route, component, const.",enum:["class","function","method","interface","type","variable","route","component","const"]},file:{type:"string",description:'Filter by file path (substring match, e.g., "src/auth").'},intent:{type:"string",description:'LLM context for ranking (e.g., "adding OAuth support").'},includeContent:{type:"boolean",description:"Include source code snippets (default false; use `explore` for full code).",default:false},maxResults:{type:"number",description:"Maximum results",default:10,minimum:1,maximum:100},language:{type:"string",description:"Filter by programming language",enum:["ts","tsx","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"]},astType:{type:"string",description:"Filter by AST node type (more specific than kind)."}},required:[]},K={type:"object",additionalProperties:false,properties:{name:{type:"string",description:'Symbol name (e.g., "AuthService"). Recommended \u2014 LLM workflow: query \u2192 use returned name.'},nodeId:{type:"string",description:"Node ID (direct lookup, zero ambiguity)."},file:{type:"string",description:"File path or basename to disambiguate when multiple same-named symbols exist."},kind:{type:"string",description:"Filter by node kind (class, function, method, interface, type, variable, route, component, const)."},includeContent:{type:"boolean",description:"Include source code body (default true).",default:true},includeEdges:{type:"boolean",description:"Include edge listing (incoming + outgoing).",default:true},maxEdgesPerNode:{type:"number",description:"Max edges to return (default 10; range [1, 100]).",default:10,minimum:1,maximum:100}},required:[]},V={type:"object",additionalProperties:false,properties:{name:{type:"string",description:"Symbol name \u2014 LLM workflow friendly."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind in BFS result."},depth:{type:"number",description:"BFS depth (1 = direct only, 2 = default, 3 = max).",default:2,minimum:1,maximum:3},maxNodes:{type:"number",description:"Max nodes in result.",default:100,minimum:1,maximum:500},direction:{type:"string",description:"Edge direction filter",enum:["incoming","outgoing","both"],default:"both"},maxEdgesPerNode:{type:"number",description:"Max edges per direction per BFS level (default 10; range [1, 100]).",default:10,minimum:1,maximum:100}},required:[]},J={type:"object",additionalProperties:false,properties:{name:{type:"string",description:"Symbol name \u2014 LLM workflow friendly."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind in BFS result."},depth:{type:"number",description:"Max BFS depth (1-3).",default:2,minimum:1,maximum:3},maxResults:{type:"number",description:"Max affected symbols (default 10; range [1, 200]).",default:10,minimum:1,maximum:200},maxEdgesPerNode:{type:"number",description:"Max incoming edges per BFS level (default 10; range [1, 100]).",default:10,minimum:1,maximum:100}},required:[]},Z={type:"object",additionalProperties:false,properties:{name:{type:"string",description:"Symbol name to find callers for."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind."},maxResults:{type:"number",description:"Max callers to return (default 10; range [1, 200]).",default:10,minimum:1,maximum:200},maxEdgesPerNode:{type:"number",description:"Max incoming edges (default 10; range [1, 100]).",default:10,minimum:1,maximum:100}},required:[]},ee={type:"object",additionalProperties:false,properties:{name:{type:"string",description:"Symbol name to find callees for."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind."},maxResults:{type:"number",description:"Max callees to return (default 10; range [1, 200]).",default:10,minimum:1,maximum:200},maxEdgesPerNode:{type:"number",description:"Max outgoing edges (default 10; range [1, 100]).",default:10,minimum:1,maximum:100}},required:[]},te={type:"object",additionalProperties:false,properties:{query:{type:"string",description:'Symbol name or natural language query (e.g., "auth flow", "MemorySystem").'},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind."},maxFiles:{type:"number",description:"Max entry-point files.",default:5,minimum:1,maximum:20},maxSymbols:{type:"number",description:"Max symbols per file.",default:3,minimum:1,maximum:10},maxEdgesPerNode:{type:"number",description:"Max caller/callee edges per symbol (default 10; range [1, 100]).",default:10,minimum:1,maximum:100},depth:{type:"number",description:"Neighbor depth for callers/callees (default 1).",default:1,minimum:1,maximum:2},includeContent:{type:"boolean",description:"Include source code body (default true).",default:true},intent:{type:"string",description:"LLM context for ranking."}},required:["query"]},q={type:"object",additionalProperties:false,properties:{}},ne={query:'Hybrid search over indexed code nodes (FTS + vector + basic + name-segment). Returns symbol locations grouped by file with line-numbered snippets.\n\nWHEN TO USE: Quick lookup of "where is X defined?" \u2014 get symbol locations and snippets in one call. Use `context` to understand a symbol\'s surroundings; use `impact` to see blast radius; use `explore` to get the actual source.\n\nAFTER THIS: Use `node <name>` to fetch full details of one match; use `context` to walk neighbors; use `explore` to get source code.\n\nNOTES: Default FTS-only (fast). Pass `includeContent: true` to include code snippets in results. Use `kind` for friendlier semantic filter (class/function/method/...) instead of `astType`.',node:"Show details for a single symbol: kind, language, location, modifiers, source code, edges.\n\nWHEN TO USE: After `query` / `context` returns a list \u2014 fetch one match's full metadata and edge summary. Pass `name` (preferred) or `nodeId`.\n\nAFTER THIS: Use `context` to walk neighbors; use `impact` for blast radius; use `explore` to get source code + caller/callee trail.\n\nNOTES: `name` is the LLM-friendly input. `file` / `kind` disambiguate when multiple same-named symbols exist. Source code is included by default (set `includeContent: false` for metadata only).",context:"Build a sub-graph around a symbol (BFS to N-level neighbors). Returns incoming/outgoing edges and neighbor nodes grouped by depth.\n\nWHEN TO USE: Understand a symbol's surroundings \u2014 who calls it, what it calls, who extends it. Use after `query` / `node` to get the symbol.\n\nAFTER THIS: Use `impact` for blast-radius (callers only, deeper depth). Use `callers` / `callees` for a flat list. Use `query` to find related symbols.\n\nNOTES: `name` is the LLM-friendly input. Does NOT include source code (use `explore` for code). Set `direction` to narrow to incoming/outgoing only.",impact:"Blast radius of changing a symbol: BFS incoming edges (CALLS / IMPORTS / TYPE_REFERENCES), bucketed by depth. d=1 (WILL BREAK) / d=2 (LIKELY AFFECTED) / d=3 (MAY NEED TESTING).\n\nWHEN TO USE: Before refactoring a symbol \u2014 see what depends on it. Use after `query` to get the symbol.\n\nAFTER THIS: Review d=1 first (those WILL BREAK). Use `node <name>` on high-risk nodes to read their source.\n\nNOTES: `name` is the LLM-friendly input. Returns counts per depth bucket, not full lists. For flat caller list, use `callers`.",callers:'Flat list of who calls <symbol> (incoming CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS / METHOD_OVERRIDES).\n\nWHEN TO USE: Quick "who depends on this?" lookup. Use `impact` for bucketed risk analysis; use `context` for both directions.\n\nAFTER THIS: Use `node <name>` on a high-traffic caller to read its source.\n\nNOTES: `name` is the LLM-friendly input. Returns up to `maxResults` callers (default 10). Use `file` / `kind` to disambiguate.',callees:'Flat list of what <symbol> calls (outgoing CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS).\n\nWHEN TO USE: Quick "what does this function do?" lookup. Use `context` for both directions.\n\nAFTER THIS: Use `node <name>` on a key callee to read its source.\n\nNOTES: `name` is the LLM-friendly input. Returns up to `maxResults` callees (default 10). Use `file` / `kind` to disambiguate.',explore:"**PRIMARY TOOL \u2014 call FIRST** for almost any question OR before an edit: how does X work, architecture, a bug, where/what is X, surveying an area, or symbols you are about to change.\n\nReturns verbatim source of relevant symbols grouped by file in ONE capped call (Read-equivalent \u2014 treat shown source as already Read; do NOT re-open those files), plus caller/callee trail.\n\nWHEN TO USE: Whenever you need to understand an area of the codebase or before refactoring. Query can be a symbol name or natural language.\n\nAFTER THIS: Use `node <name>` for metadata only; use `impact` for blast-radius; use `callers` / `callees` for flat lists.\n\nNOTES: Usually the ONLY call you need \u2014 more accurate context, in far fewer tokens and round-trips than search/Read/Grep loop. The single most cost-effective tool.",status:`Show index state, db path, node/edge counts, indexed files, meta config.
1
+ 'use strict';var chunkVXLUR7M5_cjs=require('./chunk-VXLUR7M5.cjs');require('./chunk-3DAM6EZN.cjs'),require('./chunk-AARBEAIB.cjs'),require('./chunk-W5SMGCKO.cjs'),require('./chunk-EH2QTB6S.cjs'),require('./chunk-VZCOLSBF.cjs'),require('./chunk-R32346OA.cjs');var mcp=require('@easbot/mcp'),utils=require('@easbot/utils');var f=utils.Log.create({service:"codebase.mcp.stdio"}),Q=["query","node","context","impact","callers","callees","explore","status","doctor"];exports.CodebaseStdioServer=void 0;(t=>{let n;function s(){return n||(f.debug("initializing CodebaseStdioServer state factory (lazy)"),n=()=>({toolNames:[...Q],cachedConfigId:"",cachedConfigName:"",cachedConfigVersion:""})),n}async function a(o,r){let p=s()(),g=(process.env.EASBOT_MCP_TRUSTED_LOCAL??"true").toLowerCase()!=="false",l=new mcp.ToolRegistry;me(l,o,g);let y=p.toolNames;f.info("starting codebase MCP stdio server",{id:r.id,name:r.name,toolCount:y.length});let h=await mcp.createAndStartStdioServer(r,l),E=null,$=new Promise(c=>{E=c;}),S=c=>{f.info("received signal, stopping MCP server",{signal:c}),E?.();},T=()=>S("SIGINT"),N=()=>S("SIGTERM");process.on("SIGINT",T),process.on("SIGTERM",N);try{await $;}finally{try{process.off("SIGINT",T),process.off("SIGTERM",N);}catch(c){f.warn("failed to remove signal handlers",{error:utils.errorMeta(c)});}try{await h.stop();}catch(c){f.warn("server.stop failed during cleanup",{error:utils.errorMeta(c)});}try{await o.close();}catch(c){f.warn("codebase.close failed during cleanup",{error:utils.errorMeta(c)});}}return {id:r.id,name:r.name,version:r.version,tools:y}}t.start=a;function d(){return s()().toolNames}t.getToolNames=d;function e(){n=void 0;}t.__resetForTests=e;})(exports.CodebaseStdioServer||(exports.CodebaseStdioServer={}));var X={readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false},z={type:"object",additionalProperties:false,properties:{query:{type:"string",description:'Symbol name or partial name (e.g., "auth", "UserService"). Empty string returns recent nodes.'},kind:{type:"string",description:"Filter by node kind. One of: class, function, method, interface, type, variable, route, component, const.",enum:["class","function","method","interface","type","variable","route","component","const"]},file:{type:"string",description:'Filter by file path (substring match, e.g., "src/auth").'},intent:{type:"string",description:'LLM context for ranking (e.g., "adding OAuth support").'},includeContent:{type:"boolean",description:"Include source code snippets (default false; use `explore` for full code).",default:false},maxResults:{type:"number",description:"Maximum results",default:10,minimum:1,maximum:100},language:{type:"string",description:"Filter by programming language",enum:["ts","tsx","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"]},astType:{type:"string",description:"Filter by AST node type (more specific than kind)."}},required:[]},K={type:"object",additionalProperties:false,properties:{name:{type:"string",description:'Symbol name (e.g., "AuthService"). Recommended \u2014 LLM workflow: query \u2192 use returned name.'},nodeId:{type:"string",description:"Node ID (direct lookup, zero ambiguity)."},file:{type:"string",description:"File path or basename to disambiguate when multiple same-named symbols exist."},kind:{type:"string",description:"Filter by node kind (class, function, method, interface, type, variable, route, component, const)."},includeContent:{type:"boolean",description:"Include source code body (default true).",default:true},includeEdges:{type:"boolean",description:"Include edge listing (incoming + outgoing).",default:true},maxEdgesPerNode:{type:"number",description:"Max edges to return (default 10; range [1, 100]).",default:10,minimum:1,maximum:100}},required:[]},V={type:"object",additionalProperties:false,properties:{name:{type:"string",description:"Symbol name \u2014 LLM workflow friendly."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind in BFS result."},depth:{type:"number",description:"BFS depth (1 = direct only, 2 = default, 3 = max).",default:2,minimum:1,maximum:3},maxNodes:{type:"number",description:"Max nodes in result.",default:100,minimum:1,maximum:500},direction:{type:"string",description:"Edge direction filter",enum:["incoming","outgoing","both"],default:"both"},maxEdgesPerNode:{type:"number",description:"Max edges per direction per BFS level (default 10; range [1, 100]).",default:10,minimum:1,maximum:100}},required:[]},J={type:"object",additionalProperties:false,properties:{name:{type:"string",description:"Symbol name \u2014 LLM workflow friendly."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind in BFS result."},depth:{type:"number",description:"Max BFS depth (1-3).",default:2,minimum:1,maximum:3},maxResults:{type:"number",description:"Max affected symbols (default 10; range [1, 200]).",default:10,minimum:1,maximum:200},maxEdgesPerNode:{type:"number",description:"Max incoming edges per BFS level (default 10; range [1, 100]).",default:10,minimum:1,maximum:100}},required:[]},Z={type:"object",additionalProperties:false,properties:{name:{type:"string",description:"Symbol name to find callers for."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind."},maxResults:{type:"number",description:"Max callers to return (default 10; range [1, 200]).",default:10,minimum:1,maximum:200},maxEdgesPerNode:{type:"number",description:"Max incoming edges (default 10; range [1, 100]).",default:10,minimum:1,maximum:100}},required:[]},ee={type:"object",additionalProperties:false,properties:{name:{type:"string",description:"Symbol name to find callees for."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind."},maxResults:{type:"number",description:"Max callees to return (default 10; range [1, 200]).",default:10,minimum:1,maximum:200},maxEdgesPerNode:{type:"number",description:"Max outgoing edges (default 10; range [1, 100]).",default:10,minimum:1,maximum:100}},required:[]},te={type:"object",additionalProperties:false,properties:{query:{type:"string",description:'Symbol name or natural language query (e.g., "auth flow", "MemorySystem").'},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind."},maxFiles:{type:"number",description:"Max entry-point files.",default:5,minimum:1,maximum:20},maxSymbols:{type:"number",description:"Max symbols per file.",default:3,minimum:1,maximum:10},maxEdgesPerNode:{type:"number",description:"Max caller/callee edges per symbol (default 10; range [1, 100]).",default:10,minimum:1,maximum:100},depth:{type:"number",description:"Neighbor depth for callers/callees (default 1).",default:1,minimum:1,maximum:2},includeContent:{type:"boolean",description:"Include source code body (default true).",default:true},intent:{type:"string",description:"LLM context for ranking."}},required:["query"]},q={type:"object",additionalProperties:false,properties:{}},ne={query:'Hybrid search over indexed code nodes (FTS + vector + basic + name-segment). Returns symbol locations grouped by file with line-numbered snippets.\n\nWHEN TO USE: Quick lookup of "where is X defined?" \u2014 get symbol locations and snippets in one call. Use `context` to understand a symbol\'s surroundings; use `impact` to see blast radius; use `explore` to get the actual source.\n\nAFTER THIS: Use `node <name>` to fetch full details of one match; use `context` to walk neighbors; use `explore` to get source code.\n\nNOTES: Default FTS-only (fast). Pass `includeContent: true` to include code snippets in results. Use `kind` for friendlier semantic filter (class/function/method/...) instead of `astType`.',node:"Show details for a single symbol: kind, language, location, modifiers, source code, edges.\n\nWHEN TO USE: After `query` / `context` returns a list \u2014 fetch one match's full metadata and edge summary. Pass `name` (preferred) or `nodeId`.\n\nAFTER THIS: Use `context` to walk neighbors; use `impact` for blast radius; use `explore` to get source code + caller/callee trail.\n\nNOTES: `name` is the LLM-friendly input. `file` / `kind` disambiguate when multiple same-named symbols exist. Source code is included by default (set `includeContent: false` for metadata only).",context:"Build a sub-graph around a symbol (BFS to N-level neighbors). Returns incoming/outgoing edges and neighbor nodes grouped by depth.\n\nWHEN TO USE: Understand a symbol's surroundings \u2014 who calls it, what it calls, who extends it. Use after `query` / `node` to get the symbol.\n\nAFTER THIS: Use `impact` for blast-radius (callers only, deeper depth). Use `callers` / `callees` for a flat list. Use `query` to find related symbols.\n\nNOTES: `name` is the LLM-friendly input. Does NOT include source code (use `explore` for code). Set `direction` to narrow to incoming/outgoing only.",impact:"Blast radius of changing a symbol: BFS incoming edges (CALLS / IMPORTS / TYPE_REFERENCES), bucketed by depth. d=1 (WILL BREAK) / d=2 (LIKELY AFFECTED) / d=3 (MAY NEED TESTING).\n\nWHEN TO USE: Before refactoring a symbol \u2014 see what depends on it. Use after `query` to get the symbol.\n\nAFTER THIS: Review d=1 first (those WILL BREAK). Use `node <name>` on high-risk nodes to read their source.\n\nNOTES: `name` is the LLM-friendly input. Returns counts per depth bucket, not full lists. For flat caller list, use `callers`.",callers:'Flat list of who calls <symbol> (incoming CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS / METHOD_OVERRIDES).\n\nWHEN TO USE: Quick "who depends on this?" lookup. Use `impact` for bucketed risk analysis; use `context` for both directions.\n\nAFTER THIS: Use `node <name>` on a high-traffic caller to read its source.\n\nNOTES: `name` is the LLM-friendly input. Returns up to `maxResults` callers (default 10). Use `file` / `kind` to disambiguate.',callees:'Flat list of what <symbol> calls (outgoing CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS).\n\nWHEN TO USE: Quick "what does this function do?" lookup. Use `context` for both directions.\n\nAFTER THIS: Use `node <name>` on a key callee to read its source.\n\nNOTES: `name` is the LLM-friendly input. Returns up to `maxResults` callees (default 10). Use `file` / `kind` to disambiguate.',explore:"**PRIMARY TOOL \u2014 call FIRST** for almost any question OR before an edit: how does X work, architecture, a bug, where/what is X, surveying an area, or symbols you are about to change.\n\nReturns verbatim source of relevant symbols grouped by file in ONE capped call (Read-equivalent \u2014 treat shown source as already Read; do NOT re-open those files), plus caller/callee trail.\n\nWHEN TO USE: Whenever you need to understand an area of the codebase or before refactoring. Query can be a symbol name or natural language.\n\nAFTER THIS: Use `node <name>` for metadata only; use `impact` for blast-radius; use `callers` / `callees` for flat lists.\n\nNOTES: Usually the ONLY call you need \u2014 more accurate context, in far fewer tokens and round-trips than search/Read/Grep loop. The single most cost-effective tool.",status:`Show index state, db path, node/edge counts, indexed files, meta config.
2
2
 
3
3
  WHEN TO USE: Diagnostic only \u2014 check whether the index is up-to-date or stale. Skip unless debugging.
4
4
 
@@ -15,7 +15,7 @@ NOTES: Read-only. Returns healthy/unhealthy + a list of issues.`};function i(n,s
15
15
 
16
16
  ${t}
17
17
 
18
- ... and ${e.length-5} more candidates.`}return mcp.formatFailClosed(n,a)}function oe(n,s){return async(a,d)=>{let e=a;try{let t=u(n),o=await chunkCLUGDJA5_cjs.a(t,{query:e.query,kind:e.kind,file:e.file,intent:e.intent,includeContent:e.includeContent??!1,maxResults:e.maxResults??10,language:e.language,astType:e.astType,maxEdgesPerNode:e.maxEdgesPerNode??10}),r=await chunkCLUGDJA5_cjs.y(o.hits,{pendingFiles:[],toolName:"query",writeToDisk:!1});return i(r)}catch(t){return i(m(t,"query",s),true)}}}function se(n,s){return async(a,d)=>{let e=a;try{let t=u(n),o=await chunkCLUGDJA5_cjs.b(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,includeEdges:e.includeEdges??!0,includeContent:e.includeContent??!0,maxEdgesPerNode:e.maxEdgesPerNode??10}),r=await chunkCLUGDJA5_cjs.E(o.node,o.edges,{pendingFiles:[],toolName:"node",writeToDisk:!1});return i(r)}catch(t){return i(m(t,"node",s),true)}}}function re(n,s){return async(a,d)=>{let e=a;try{let t=u(n),o=await chunkCLUGDJA5_cjs.c(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,depth:e.depth??2,maxNodes:e.maxNodes??100,direction:e.direction??"both",maxEdgesPerNode:e.maxEdgesPerNode??10});if(!o.root)return i("**context** \u2014 node not found.");let r=[],p=[];for(let l of o.edges)l.target===o.root.id?r.push(l):p.push(l);let g=await chunkCLUGDJA5_cjs.A(o.root,r,p,o.nodes.map(l=>l.node),{pendingFiles:[],toolName:"context",writeToDisk:!1});return i(g)}catch(t){return i(m(t,"context",s),true)}}}function ae(n,s){return async(a,d)=>{let e=a;try{let t=u(n),o=await chunkCLUGDJA5_cjs.d(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,depth:e.depth??2,maxResults:e.maxResults??10,maxEdgesPerNode:e.maxEdgesPerNode??10});if(!o.root)return i("**impact** \u2014 node not found.");let r=[],p=n.getDatabase();for(let l of o.buckets)for(let y of l.sample){let h=p.getNodeById(y.id);h&&r.push({source:h,relation:y.relation});}let g=await chunkCLUGDJA5_cjs.z(o.root,r,{pendingFiles:[],toolName:"impact",writeToDisk:!1});return i(g)}catch(t){return i(m(t,"impact",s),true)}}}function ie(n,s){return async(a,d)=>{let e=a;try{let t=u(n),o=await chunkCLUGDJA5_cjs.e(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,maxResults:e.maxResults??10,maxEdgesPerNode:e.maxEdgesPerNode??10}),r=await chunkCLUGDJA5_cjs.B(o,{toolName:"codebase_callers"});return i(r)}catch(t){return i(m(t,"callers",s),true)}}}function de(n,s){return async(a,d)=>{let e=a;try{let t=u(n),o=await chunkCLUGDJA5_cjs.f(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,maxResults:e.maxResults??10,maxEdgesPerNode:e.maxEdgesPerNode??10}),r=await chunkCLUGDJA5_cjs.C(o,{toolName:"codebase_callees"});return i(r)}catch(t){return i(m(t,"callees",s),true)}}}function le(n,s){return async(a,d)=>{let e=a;try{let t=u(n),o=await chunkCLUGDJA5_cjs.g(t,{query:e.query,file:e.file,kind:e.kind,maxFiles:e.maxFiles??5,maxSymbols:e.maxSymbols??3,maxEdgesPerNode:e.maxEdgesPerNode??10,depth:e.depth??1,includeContent:e.includeContent??!0,intent:e.intent}),r=await chunkCLUGDJA5_cjs.F(o,{pendingFiles:[],toolName:"explore",writeToDisk:!1});return i(r)}catch(t){return i(m(t,"explore",s),true)}}}function ce(n,s){return async(a,d)=>{try{let e=u(n),t=await chunkCLUGDJA5_cjs.h(e,{}),o=await chunkCLUGDJA5_cjs.D(t,{toolName:"codebase_status"});return i(o)}catch(e){return i(m(e,"status",s),true)}}}function ue(n,s){return async(a,d)=>{try{let e=u(n),t=await chunkCLUGDJA5_cjs.i(e,{}),o=await chunkCLUGDJA5_cjs.h(e,{}),r=`**Codebase Health Check**
18
+ ... and ${e.length-5} more candidates.`}return mcp.formatFailClosed(n,a)}function oe(n,s){return async(a,d)=>{let e=a;try{let t=u(n),o=await chunkVXLUR7M5_cjs.a(t,{query:e.query,kind:e.kind,file:e.file,intent:e.intent,includeContent:e.includeContent??!1,maxResults:e.maxResults??10,language:e.language,astType:e.astType,maxEdgesPerNode:e.maxEdgesPerNode??10}),r=await chunkVXLUR7M5_cjs.y(o.hits,{pendingFiles:[],toolName:"query",writeToDisk:!1});return i(r)}catch(t){return i(m(t,"query",s),true)}}}function se(n,s){return async(a,d)=>{let e=a;try{let t=u(n),o=await chunkVXLUR7M5_cjs.b(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,includeEdges:e.includeEdges??!0,includeContent:e.includeContent??!0,maxEdgesPerNode:e.maxEdgesPerNode??10}),r=await chunkVXLUR7M5_cjs.E(o.node,o.edges,{pendingFiles:[],toolName:"node",writeToDisk:!1});return i(r)}catch(t){return i(m(t,"node",s),true)}}}function re(n,s){return async(a,d)=>{let e=a;try{let t=u(n),o=await chunkVXLUR7M5_cjs.c(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,depth:e.depth??2,maxNodes:e.maxNodes??100,direction:e.direction??"both",maxEdgesPerNode:e.maxEdgesPerNode??10});if(!o.root)return i("**context** \u2014 node not found.");let r=[],p=[];for(let l of o.edges)l.target===o.root.id?r.push(l):p.push(l);let g=await chunkVXLUR7M5_cjs.A(o.root,r,p,o.nodes.map(l=>l.node),{pendingFiles:[],toolName:"context",writeToDisk:!1});return i(g)}catch(t){return i(m(t,"context",s),true)}}}function ae(n,s){return async(a,d)=>{let e=a;try{let t=u(n),o=await chunkVXLUR7M5_cjs.d(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,depth:e.depth??2,maxResults:e.maxResults??10,maxEdgesPerNode:e.maxEdgesPerNode??10});if(!o.root)return i("**impact** \u2014 node not found.");let r=[],p=n.getDatabase();for(let l of o.buckets)for(let y of l.sample){let h=p.getNodeById(y.id);h&&r.push({source:h,relation:y.relation});}let g=await chunkVXLUR7M5_cjs.z(o.root,r,{pendingFiles:[],toolName:"impact",writeToDisk:!1});return i(g)}catch(t){return i(m(t,"impact",s),true)}}}function ie(n,s){return async(a,d)=>{let e=a;try{let t=u(n),o=await chunkVXLUR7M5_cjs.e(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,maxResults:e.maxResults??10,maxEdgesPerNode:e.maxEdgesPerNode??10}),r=await chunkVXLUR7M5_cjs.B(o,{toolName:"codebase_callers"});return i(r)}catch(t){return i(m(t,"callers",s),true)}}}function de(n,s){return async(a,d)=>{let e=a;try{let t=u(n),o=await chunkVXLUR7M5_cjs.f(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,maxResults:e.maxResults??10,maxEdgesPerNode:e.maxEdgesPerNode??10}),r=await chunkVXLUR7M5_cjs.C(o,{toolName:"codebase_callees"});return i(r)}catch(t){return i(m(t,"callees",s),true)}}}function le(n,s){return async(a,d)=>{let e=a;try{let t=u(n),o=await chunkVXLUR7M5_cjs.g(t,{query:e.query,file:e.file,kind:e.kind,maxFiles:e.maxFiles??5,maxSymbols:e.maxSymbols??3,maxEdgesPerNode:e.maxEdgesPerNode??10,depth:e.depth??1,includeContent:e.includeContent??!0,intent:e.intent}),r=await chunkVXLUR7M5_cjs.F(o,{pendingFiles:[],toolName:"explore",writeToDisk:!1});return i(r)}catch(t){return i(m(t,"explore",s),true)}}}function ce(n,s){return async(a,d)=>{try{let e=u(n),t=await chunkVXLUR7M5_cjs.h(e,{}),o=await chunkVXLUR7M5_cjs.D(t,{toolName:"codebase_status"});return i(o)}catch(e){return i(m(e,"status",s),true)}}}function ue(n,s){return async(a,d)=>{try{let e=u(n),t=await chunkVXLUR7M5_cjs.i(e,{}),o=await chunkVXLUR7M5_cjs.h(e,{}),r=`**Codebase Health Check**
19
19
 
20
20
  - Healthy: ${t.healthy?"\u2713 yes":"\u2717 no"}
21
21
  - Nodes: ${o.nodeCount}