ultracode 5.3.0 → 5.5.0

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 (57) hide show
  1. package/dist/chunks/analysis-tool-handlers-H2RXLDPX.js +817 -0
  2. package/dist/chunks/analysis-tool-handlers-RJZAR6VT.js +817 -0
  3. package/dist/chunks/analysis-tool-handlers-Z2RF24T7.js +13 -0
  4. package/dist/chunks/autodoc-tool-handlers-CV5JEQUA.js +1112 -0
  5. package/dist/chunks/autodoc-tool-handlers-EHTNCH6I.js +1112 -0
  6. package/dist/chunks/autodoc-tool-handlers-MECXQJ2K.js +138 -0
  7. package/dist/chunks/chaos-CO7TOBOJ.js +18 -0
  8. package/dist/chunks/chaos-VM2PXERO.js +1573 -0
  9. package/dist/chunks/chaos-W3XRVJ7K.js +1564 -0
  10. package/dist/chunks/chunk-6K37BWK5.js +439 -0
  11. package/dist/chunks/chunk-EALTCYHZ.js +10 -0
  12. package/dist/chunks/chunk-FTBE7VMY.js +316 -0
  13. package/dist/chunks/chunk-KBW6LRQP.js +322 -0
  14. package/dist/chunks/chunk-NKUHX4CU.js +5 -0
  15. package/dist/chunks/chunk-NZFF4DQ4.js +3179 -0
  16. package/dist/chunks/chunk-RGP5UVQ7.js +3179 -0
  17. package/dist/chunks/chunk-RMZXFGQZ.js +322 -0
  18. package/dist/chunks/chunk-UG44F23Y.js +316 -0
  19. package/dist/chunks/chunk-V2SCB5H5.js +4403 -0
  20. package/dist/chunks/chunk-V6JAQNM3.js +1 -0
  21. package/dist/chunks/chunk-XFGXM4CR.js +4403 -0
  22. package/dist/chunks/dev-agent-JVIGBMHQ.js +1 -0
  23. package/dist/chunks/dev-agent-TRVP5U6N.js +1624 -0
  24. package/dist/chunks/dev-agent-Y5G5WKQ4.js +1624 -0
  25. package/dist/chunks/graph-storage-factory-AYZ57YSL.js +13 -0
  26. package/dist/chunks/graph-storage-factory-GTAIJEI5.js +1 -0
  27. package/dist/chunks/graph-storage-factory-T2WO5QVG.js +13 -0
  28. package/dist/chunks/incremental-updater-KDIQGAUU.js +14 -0
  29. package/dist/chunks/incremental-updater-OJRSTO3Q.js +1 -0
  30. package/dist/chunks/incremental-updater-SBEBH7KF.js +14 -0
  31. package/dist/chunks/indexer-agent-H3QIEL3Z.js +21 -0
  32. package/dist/chunks/indexer-agent-KHF5JMV7.js +21 -0
  33. package/dist/chunks/indexer-agent-SHJD6Z77.js +1 -0
  34. package/dist/chunks/indexing-pipeline-J6Z4BHKF.js +1 -0
  35. package/dist/chunks/indexing-pipeline-OY3337QN.js +249 -0
  36. package/dist/chunks/indexing-pipeline-WCXIDMAP.js +249 -0
  37. package/dist/chunks/merge-agent-LSUBDJB2.js +2481 -0
  38. package/dist/chunks/merge-agent-MJEW3HWU.js +2481 -0
  39. package/dist/chunks/merge-agent-O45OXF33.js +11 -0
  40. package/dist/chunks/merge-tool-handlers-BDSVNQVZ.js +277 -0
  41. package/dist/chunks/merge-tool-handlers-HP7DRBXJ.js +1 -0
  42. package/dist/chunks/merge-tool-handlers-RUJAKE3D.js +277 -0
  43. package/dist/chunks/pattern-tool-handlers-L62W3CXR.js +1549 -0
  44. package/dist/chunks/pattern-tool-handlers-SAHX2CVW.js +13 -0
  45. package/dist/chunks/query-agent-3TWDFIMT.js +191 -0
  46. package/dist/chunks/query-agent-HXQ3BMMF.js +191 -0
  47. package/dist/chunks/query-agent-USMC2GNG.js +1 -0
  48. package/dist/chunks/semantic-agent-MQCAWIAB.js +6381 -0
  49. package/dist/chunks/semantic-agent-NDGR3NAK.js +6381 -0
  50. package/dist/chunks/semantic-agent-S4ZL6GZC.js +137 -0
  51. package/dist/index.js +17 -17
  52. package/dist/roslyn-addon/.build-hash +1 -1
  53. package/dist/roslyn-addon/ILGPU.Algorithms.dll +0 -0
  54. package/dist/roslyn-addon/ILGPU.dll +0 -0
  55. package/dist/roslyn-addon/UltraCode.CSharp.deps.json +35 -0
  56. package/dist/roslyn-addon/UltraCode.CSharp.dll +0 -0
  57. package/package.json +1 -1
@@ -0,0 +1,5 @@
1
+ import {a as a$2}from'./chunk-7YC4KTAW.js';import {b}from'./chunk-V5VLOVE7.js';import {d,f}from'./chunk-6K37BWK5.js';import {b as b$2,a as a$1}from'./chunk-LESND2CW.js';import {H as H$1,a,q,v}from'./chunk-GVQNDMAK.js';import {c,b as b$4}from'./chunk-PZF7YC35.js';import {b as b$3,c as c$1}from'./chunk-AIZJT6AG.js';import {g,b as b$1}from'./chunk-KXUWGHHN.js';import {G,n,k,p,m,t,u,s}from'./chunk-2KIPXYOB.js';import {R,I,M}from'./chunk-4BI7EBPQ.js';import {nanoid}from'nanoid';import {execSync}from'child_process';import {join,isAbsolute,dirname}from'path';import {EventEmitter}from'events';import {existsSync,watch}from'fs';import {stat}from'fs/promises';import oe from'fast-glob';import ue from'xxhash-wasm';import {LRUCache}from'lru-cache';g();R();H$1();G();var J=class{config;registryPath;registry;currentBranch=null;currentRepoPath=null;constructor(t){this.config=t,this.registryPath=join(t.dataDir,"branch-registry.json"),this.registry=this.loadRegistry();}getProjectsDir(){return join(this.config.dataDir,"projects")}async initialize(){}getCurrentBranch(t){let e=t||this.currentRepoPath||process.cwd();try{let i=join(e,".git");if(!n(i))return I.d("BRANCHMGR","no_git_dir",{path:e}),null;try{let n=execSync("git symbolic-ref --short HEAD",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).trim();return this.currentBranch=n,this.currentRepoPath=e,n}catch{try{let n=execSync("git describe --tags --exact-match",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).trim();return this.currentBranch=`detached-${n}`,this.currentRepoPath=e,this.currentBranch}catch{let n=execSync("git rev-parse --short HEAD",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).trim();return this.currentBranch=`detached-${n}`,this.currentRepoPath=e,this.currentBranch}}}catch(i){return I.d("BRANCHMGR","branch_get_fail",{err:String(i)}),null}}getLastCommitHash(t){let e=t||this.currentRepoPath||process.cwd();try{return execSync("git rev-parse HEAD",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).trim()}catch(i){return I.d("BRANCHMGR","commit_hash_fail",{err:String(i)}),null}}getRepositoryHash(t){return q(t)}sanitizeBranchName(t){return t.replace(/\//g,"-").replace(/\\/g,"-").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/^-+|-+$/g,"")}getBranchDbPath(t,e){return join(this.config.dataDir,"unified-storage.db")}getFaissIndexPath(t,e){let i=e||this.currentRepoPath||process.cwd(),n=this.getRepositoryHash(i),s=this.sanitizeBranchName(t);return join(this.getProjectsDir(),n,`faiss-${s}.bin`)}getBranchMetadata(t,e){let i=e||this.currentRepoPath||process.cwd(),n$1=this.getRepositoryHash(i),s=this.sanitizeBranchName(t),a=join(this.getProjectsDir(),n$1,s,"metadata.json");if(!n(a))return null;try{let l=k(a);return JSON.parse(l)}catch(l){return I.e("BRANCHMGR","metadata_read_fail",{err:String(l)}),null}}updateBranchMetadata(t){let e=this.sanitizeBranchName(t.branch),i=join(this.getProjectsDir(),t.repositoryHash,e,"metadata.json"),n$1=join(this.getProjectsDir(),t.repositoryHash,e);n(n$1)||p(n$1,{recursive:true}),m(i,JSON.stringify(t,null,2),"utf-8"),this.updateRegistry(t.repositoryPath,t.branch,i);}getActiveBranches(t$1){let e=t$1||this.currentRepoPath||process.cwd(),i=this.getRepositoryHash(e),n$1=join(this.getProjectsDir(),i);if(!n(n$1))return [];let s=[],a=t(n$1),l=/^faiss-(.+)\.bin$/;for(let h of a){let o=h.match(l);if(!o||!o[1])continue;let d=o[1],p=join(n$1,h),m=u(p),g=this.getBranchMetadata(d,e);s.push({name:d,dbPath:p,lastAccessed:g?.accessedAt||m.mtimeMs,sizeBytes:m.size,metadata:g});}return s.sort((h,o)=>o.lastAccessed-h.lastAccessed)}async cleanupOldBranches(t$1){let e=t$1||this.config.maxBranchesPerRepo,i=this.getActiveBranches();if(i.length<=e)return 0;let n=i.slice(e),s$1=0;for(let a of n)try{let l=join(this.getProjectsDir(),a.metadata?.repositoryHash||"",a.name),h=t(l);for(let o of h)s(join(l,o));a.metadata&&this.removeFromRegistry(a.metadata.repositoryPath,a.name),s$1++,I.i("BRANCHMGR","branch_cleaned",{branch:a.name});}catch(l){I.e("BRANCHMGR","cleanup_fail",{branch:a.name,err:String(l)});}return s$1}async switchBranch(t,e){let i=e||this.currentRepoPath||process.cwd(),n=this.currentBranch;this.currentBranch=t,this.currentRepoPath=i,I.i("BRANCHMGR","branch_switched",{from:n,to:t});let s=this.getBranchMetadata(t,i);s&&(s.accessedAt=Date.now(),this.updateBranchMetadata(s));}hasBranchDatabase(t,e){let i=this.getFaissIndexPath(t,e);return n(i)}loadRegistry(){if(!n(this.registryPath))return {repositories:{},config:{maxBranchesPerRepo:this.config.maxBranchesPerRepo,maxTotalBranches:this.config.maxTotalBranches,evictionStrategy:this.config.evictionStrategy}};try{let t=k(this.registryPath);return JSON.parse(t)}catch(t){return I.e("BRANCHMGR","registry_load_fail",{err:String(t)}),{repositories:{},config:{maxBranchesPerRepo:this.config.maxBranchesPerRepo,maxTotalBranches:this.config.maxTotalBranches,evictionStrategy:this.config.evictionStrategy}}}}saveRegistry(){let t=join(this.config.dataDir);n(t)||p(t,{recursive:true}),m(this.registryPath,JSON.stringify(this.registry,null,2),"utf-8");}updateRegistry(t,e,i){let n$1=this.getRepositoryHash(t);this.registry.repositories[n$1]||(this.registry.repositories[n$1]={path:t,branches:{}});let s=this.sanitizeBranchName(e),a=n(i)?u(i):{size:0};this.registry.repositories[n$1].branches[s]={dbPath:i,lastAccessed:Date.now(),sizeBytes:a.size},this.saveRegistry();}removeFromRegistry(t,e){let i=this.getRepositoryHash(t),n=this.sanitizeBranchName(e);this.registry.repositories[i]?.branches[n]&&(delete this.registry.repositories[i].branches[n],this.saveRegistry());}};R();var V=typeof globalThis.Bun<"u",L=V&&typeof globalThis.Bun<"u"&&typeof globalThis.Bun.watch=="function",mt=class extends EventEmitter{config;watchers=new Map;watchedFiles=new Set;isRunning=false;pendingChanges=new Map;debounceAbort=null;bunWatcher=null;constructor(t){super(),this.config={rootDir:t.rootDir.replace(/\\/g,"/"),include:t.include??["**/*"],exclude:t.exclude??["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.ultracode/**"],debounceMs:t.debounceMs??100,bulkThreshold:t.bulkThreshold??1e3};}async start(){if(this.isRunning)return;this.isRunning=true;let t=L?"Bun.watch":"fs.watch";I.i("FILEWATCHER","Starting",{runtime:t,rootDir:this.config.rootDir,isBun:V,hasBunWatch:L});try{let e=await this.scanFiles();I.d("FILEWATCHER","Initial scan complete",{files:e.length}),L?await this.startBunWatcher(e):await this.startNodeWatcher(e),this.emit("ready");}catch(e){throw this.isRunning=false,I.e("FILEWATCHER","Failed to start",{error:e.message}),e}}async stop(){if(this.isRunning){this.isRunning=false,this.debounceAbort&&(this.debounceAbort.abort(),this.debounceAbort=null),this.bunWatcher&&(this.bunWatcher.stop(),this.bunWatcher=null);for(let t of this.watchers.values())t.close();this.watchers.clear(),this.watchedFiles.clear(),this.pendingChanges.clear(),I.d("FILEWATCHER","Stopped");}}async scanFiles(){let t=this.config.include.map(i=>i.startsWith("/")||i.includes(":")?i:`${this.config.rootDir}/${i}`);if(V&&globalThis.Bun?.Glob){let i=[];for(let n of t){let s=new globalThis.Bun.Glob(n);for await(let a of s.scan({onlyFiles:true,ignore:this.config.exclude}))i.push(a);}return i}return await oe(t,{ignore:this.config.exclude,onlyFiles:true,absolute:true})}async startBunWatcher(t){let e=new Set;for(let i of t)e.add(dirname(i)),this.watchedFiles.add(i);this.bunWatcher=Bun.watch(this.config.rootDir,{recursive:true,filter:i=>this.matchesPatterns(i)}),this.bunWatcher.on("change",(i,n)=>{if(!n)return;let s=join(this.config.rootDir,n).replace(/\\/g,"/");i==="rename"?stat(s).then(()=>this.queueChange(s,this.watchedFiles.has(s)?"change":"add")).catch(()=>this.queueChange(s,"unlink")):this.queueChange(s,"change");}),I.i("FILEWATCHER","Bun.watch started",{dirs:e.size,files:t.length});}async startNodeWatcher(t){let e=new Set;for(let i of t)e.add(dirname(i)),this.watchedFiles.add(i);for(let i of e)try{let n=watch(i,{persistent:!0},(s,a)=>{if(!a)return;let l=join(i,a).replace(/\\/g,"/");this.matchesPatterns(l)&&(s==="rename"?stat(l).then(()=>this.queueChange(l,this.watchedFiles.has(l)?"change":"add")).catch(()=>this.queueChange(l,"unlink")):this.queueChange(l,"change"));});n.on("error",s=>{I.w("FILEWATCHER","Watcher error",{dir:i,error:s.message});}),this.watchers.set(i,n);}catch(n){I.w("FILEWATCHER","Failed to watch directory",{dir:i,error:n.message});}I.i("FILEWATCHER","fs.watch started",{dirs:this.watchers.size,files:t.length});}matchesPatterns(t){let e=t.replace(/\\/g,"/");for(let i of this.config.exclude)if(this.simpleMatch(e,i))return false;for(let i of this.config.include)if(this.simpleMatch(e,i))return true;return false}simpleMatch(t,e){if(e.startsWith("**/")){let i=e.slice(3);if(i.includes("*")){let n=i.replace("*","");return t.endsWith(n)||t.includes(`/${i.replace("*","")}`)}return t.includes(`/${i}`)||t.endsWith(`/${i}`)}return e.startsWith("*.")?t.endsWith(e.slice(1)):e==="**/*"?true:t===e||t.endsWith(`/${e}`)}queueChange(t,e){this.isRunning&&(e==="add"?this.watchedFiles.add(t):e==="unlink"&&this.watchedFiles.delete(t),this.pendingChanges.set(t,{path:t,type:e,timestamp:Date.now()}),this.scheduleFlush());}scheduleFlush(){this.debounceAbort&&this.debounceAbort.abort();let t=new AbortController;this.debounceAbort=t,(async()=>(await b$3(this.config.debounceMs),t.signal.aborted||this.flush()))();}flush(){if(this.debounceAbort&&(this.debounceAbort.abort(),this.debounceAbort=null),this.pendingChanges.size===0)return;let t=Array.from(this.pendingChanges.values());this.pendingChanges.clear();let e=t.length>=this.config.bulkThreshold;I.d("FILEWATCHER","Emitting changes",{count:t.length,bulkMode:e}),this.emit("change",t,e);}getStatus(){return {running:this.isRunning,runtime:L?"bun":"node",isBunRuntime:V,hasBunWatch:L,watchedFiles:this.watchedFiles.size,watchedDirs:this.watchers.size,pendingChanges:this.pendingChanges.size}}};async function Ft(c){let t=new mt(c);return await t.start(),t}R();function Nt(){return typeof globalThis.Bun<"u"}async function ft(c){typeof globalThis.Bun<"u"&&typeof globalThis.Bun.sleep=="function"?await globalThis.Bun.sleep(c):await new Promise(t=>setTimeout(t,c));}var Z=class{config;repoPath=null;watcher=null;commitPollRunning=false;uncommittedPollRunning=false;stopped=false;currentBranch=null;currentCommit=null;lastUncommittedFiles=new Set;pendingChanges=new Set;debounceAbortController=null;debounceMs;bulkModeThreshold;branchChangeCallbacks=[];commitCallbacks=[];fileChangeCallbacks=[];uncommittedChangeCallbacks=[];debouncedChangeCallbacks=[];constructor(t){this.config={...t,watchUncommitted:t.watchUncommitted??true,uncommittedPollIntervalMs:t.uncommittedPollIntervalMs??1e4,includeUntracked:t.includeUntracked??true},this.debounceMs=t.debounceMs??6e4,this.bulkModeThreshold=t.bulkModeThreshold??1e3;}startWatching(t){if(!this.config.enabled){I.i("GITWATCHER","disabled");return}this.repoPath=t;let e=join(t,".git","HEAD");if(!existsSync(e)){I.i("GITWATCHER","no_git_dir");return}this.currentBranch=this.getCurrentBranch(),this.currentCommit=this.getCurrentCommit(),I.i("GITWATCHER","started",{path:t}),I.i("GITWATCHER","current_branch",{branch:this.currentBranch}),I.i("GITWATCHER","current_commit",{commit:this.currentCommit}),this.stopped=false,this.watcher&&(this.watcher.close(),this.watcher=null),this.watcher=watch(e,i=>{i==="change"&&this.checkBranchChange();}),this.startCommitPollLoop(),this.config.watchUncommitted&&(I.i("GITWATCHER","uncommitted_watch_on",{interval:this.config.uncommittedPollIntervalMs}),this.getUncommittedFiles().then(i=>{this.lastUncommittedFiles=new Set(i.map(n=>n.path)),I.i("GITWATCHER","init_uncommitted",{count:this.lastUncommittedFiles.size});}),this.startUncommittedPollLoop());}commitPollTimer;uncommittedPollTimer;startCommitPollLoop(){this.commitPollRunning||(this.commitPollRunning=true,Nt()?(async()=>{for(;!this.stopped&&(await ft(this.config.pollIntervalMs),!this.stopped);)try{this.checkBranchChange(),this.checkCommitChange();}catch(t){I.w("GITWATCHER","poll_err",{err:String(t)});}this.commitPollRunning=false;})():this.commitPollTimer=setInterval(()=>{if(!this.stopped)try{this.checkBranchChange(),this.checkCommitChange();}catch(t){I.w("GITWATCHER","poll_err",{err:String(t)});}},this.config.pollIntervalMs));}startUncommittedPollLoop(){this.uncommittedPollRunning||(this.uncommittedPollRunning=true,Nt()?(async()=>{for(;!this.stopped&&(await ft(this.config.uncommittedPollIntervalMs),!this.stopped);)try{await this.checkUncommittedChanges();}catch(t){I.w("GITWATCHER","uncommitted_poll_err",{err:String(t)});}this.uncommittedPollRunning=false;})():this.uncommittedPollTimer=setInterval(()=>{this.stopped||this.checkUncommittedChanges().catch(t=>{I.w("GITWATCHER","uncommitted_poll_err",{err:String(t)});});},this.config.uncommittedPollIntervalMs));}getBranch(){return this.currentBranch}isWatching(){return !this.stopped&&(!!this.watcher||this.commitPollRunning||this.uncommittedPollRunning)}stopWatching(){this.stopped=true,this.commitPollTimer&&(clearInterval(this.commitPollTimer),this.commitPollTimer=void 0),this.uncommittedPollTimer&&(clearInterval(this.uncommittedPollTimer),this.uncommittedPollTimer=void 0),this.watcher&&(this.watcher.close(),this.watcher=null),this.debounceAbortController&&(this.debounceAbortController.abort(),this.debounceAbortController=null),this.lastUncommittedFiles.clear(),this.pendingChanges.clear(),I.i("GITWATCHER","stopped");}onBranchChange(t){this.branchChangeCallbacks.push(t);}onCommit(t){this.commitCallbacks.push(t);}onFileChange(t){this.fileChangeCallbacks.push(t);}onUncommittedChange(t){this.uncommittedChangeCallbacks.push(t);}onDebouncedChange(t){this.debouncedChangeCallbacks.push(t);}getPendingChangesCount(){return this.pendingChanges.size}forceFlush(){this.debounceAbortController&&(this.debounceAbortController.abort(),this.debounceAbortController=null),this.flushPendingChanges();}flushPendingChanges(){if(this.pendingChanges.size===0)return;let t=Array.from(this.pendingChanges),e=t.length>=this.bulkModeThreshold,i=t.filter(n=>{let s=n.toLowerCase();return s.includes("swagger")||s.includes("openapi")||s.endsWith(".json")&&(s.includes("api")||s.includes("spec"))});i.length>0&&I.i("GITWATCHER","swagger_files_changed",{swaggerFiles:i.length,files:i,warning:"Generated code may need regeneration"}),I.i("GITWATCHER","flushing",{count:t.length,bulkMode:e,threshold:this.bulkModeThreshold,swaggerChanges:i.length}),this.pendingChanges.clear();for(let n of this.debouncedChangeCallbacks)try{n(t,e);}catch(s){I.w("GITWATCHER","debounce_cb_err",{err:String(s)});}}scheduleDebouncedFlush(){this.debounceAbortController&&this.debounceAbortController.abort();let t=new AbortController;this.debounceAbortController=t,(async()=>(await ft(this.debounceMs),t.signal.aborted||(this.debounceAbortController=null,this.flushPendingChanges())))(),I.i("GITWATCHER","debounce_scheduled",{pending:this.pendingChanges.size,flushInSec:this.debounceMs/1e3});}async getChangedFiles(t){if(!this.repoPath)return [];try{let e=execSync(`git diff --name-status ${t}..HEAD`,{cwd:this.repoPath,encoding:"utf-8",stdio:["pipe","pipe","ignore"],windowsHide:!0}),i=[],n=e.trim().split(`
2
+ `);for(let s of n){if(!s)continue;let[a,...l]=s.split(" ");if(!a)continue;let h=l.join(" "),o;switch(a[0]){case "A":o="added";break;case "M":o="modified";break;case "D":o="deleted";break;case "R":o="renamed";break;default:o="modified";}i.push({path:h,status:o});}return i}catch(e){return I.w("GITWATCHER","get_changed_fail",{err:String(e)}),[]}}async getChangedFilesBetweenBranches(t,e){if(!this.repoPath)return [];try{let i=execSync(`git diff --name-status ${t}...${e}`,{cwd:this.repoPath,encoding:"utf-8",stdio:["pipe","pipe","ignore"],windowsHide:!0}),n=[],s=i.trim().split(`
3
+ `);for(let a of s){if(!a)continue;let[l,...h]=a.split(" ");if(!l)continue;let o=h.join(" "),d;switch(l[0]){case "A":d="added";break;case "M":d="modified";break;case "D":d="deleted";break;case "R":d="renamed";break;default:d="modified";}n.push({path:o,status:d});}return n}catch(i){return I.w("GITWATCHER","get_branch_diff_fail",{err:String(i)}),[]}}getCurrentBranch(){if(!this.repoPath)return null;try{return execSync("git symbolic-ref --short HEAD",{cwd:this.repoPath,encoding:"utf-8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).trim()}catch{try{return `detached-${execSync("git rev-parse --short HEAD",{cwd:this.repoPath,encoding:"utf-8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).trim()}`}catch{return null}}}getCurrentCommit(){if(!this.repoPath)return null;try{return execSync("git rev-parse HEAD",{cwd:this.repoPath,encoding:"utf-8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).trim()}catch{return null}}checkBranchChange(){let t=this.getCurrentBranch();if(t&&t!==this.currentBranch){let e=this.currentBranch||"unknown";I.i("GITWATCHER","branch_changed",{from:e,to:t}),this.currentBranch=t,this.currentCommit=this.getCurrentCommit();for(let i of this.branchChangeCallbacks)try{let n=i(t,e);n&&typeof n.catch=="function"&&n.catch(s=>{I.e("GITWATCHER","branch_cb_async_err",{err:String(s)});});}catch(n){I.w("GITWATCHER","branch_cb_err",{err:String(n)});}}}checkCommitChange(){let t=this.getCurrentCommit();if(t&&t!==this.currentCommit){I.i("GITWATCHER","new_commit",{commit:t.slice(0,8)});let e=this.currentCommit;this.currentCommit=t;for(let i of this.commitCallbacks)try{i(t);}catch(n){I.w("GITWATCHER","commit_cb_err",{err:String(n)});}e&&this.getChangedFiles(e).then(i=>{if(i.length>0)for(let n of this.fileChangeCallbacks)try{n(i.map(s=>s.path));}catch(s){I.w("GITWATCHER","file_cb_err",{err:String(s)});}}),this.lastUncommittedFiles.clear();}}async getUncommittedFiles(){if(!this.repoPath)return [];try{let t=this.config.includeUntracked?"-uall":"-uno",e=execSync(`git status --porcelain ${t}`,{cwd:this.repoPath,encoding:"utf-8",stdio:["pipe","pipe","ignore"],windowsHide:!0}),i=[],n=e.trim().split(`
4
+ `);for(let s of n){if(!s||s.length<3)continue;let a=s[0],l=s[1],h=s.slice(3).split(" -> ").pop()||s.slice(3),o;switch(l!==" "?l:a){case "A":case "?":o="added";break;case "M":o="modified";break;case "D":o="deleted";break;case "R":o="renamed";break;default:o="modified";}i.push({path:h,status:o});}return i}catch(t){return I.w("GITWATCHER","get_uncommitted_fail",{err:String(t)}),[]}}async checkUncommittedChanges(){let t=await this.getUncommittedFiles(),e=new Set(t.map(n=>n.path)),i=[];for(let n of t)this.lastUncommittedFiles.has(n.path)||i.push(n.path);for(let n of this.lastUncommittedFiles)e.has(n)||i.push(n);if(this.lastUncommittedFiles=e,i.length>0){I.i("GITWATCHER","uncommitted_detected",{count:i.length});for(let n of this.uncommittedChangeCallbacks)try{n(i);}catch(s){I.w("GITWATCHER","uncommitted_cb_err",{err:String(s)});}for(let n of this.fileChangeCallbacks)try{n(i);}catch(s){I.w("GITWATCHER","file_cb_err",{err:String(s)});}if(this.debouncedChangeCallbacks.length>0){for(let n of i)this.pendingChanges.add(n);this.scheduleDebouncedFlush();}}}};R();H$1();R();H$1();var ge=1e3,kt=2e3,Bt=12,Wt=()=>new Promise(c=>setImmediate(c)),tt=class{batchSize;adapter;xxhashInstance=null;currentContext={projectHash:"_unset_",branchName:"_unset_"};constructor(t,e=ge){this.adapter=t,this.batchSize=Math.min(e,kt);}setProjectContext(t){I.i("BATCHOPS","context_set",{ctx:`${t.projectHash}/${t.branchName}`}),this.currentContext=t,this.adapter.setProjectContext(t);}setProject(t,e){let i=e??v(t);this.setProjectContext({projectHash:q(t),branchName:i});}async initialize(){this.xxhashInstance=await ue();}destroy(){}entityKey(t){return t.type==="package"||t.type==="import"?`${t.type}|${t.name}`:`${t.filePath}|${t.type}|${t.name}|${t.location?.start?.index??-1}-${t.location?.end?.index??-1}`}stableEntityId(t){if(!this.xxhashInstance)throw new Error("BatchOperationsLibSQL not initialized - call initialize() first");let e=this.entityKey(t);return this.xxhashInstance.h64ToString(e).slice(0,Bt)}relationshipKey(t){return `${t.fromId}|${t.toId}|${t.type}`}stableRelationshipId(t){if(!this.xxhashInstance)throw new Error("BatchOperationsLibSQL not initialized - call initialize() first");let e=this.relationshipKey(t);return this.xxhashInstance.h64ToString(e).slice(0,Bt)}generateReverseRelationships(t){let e={calls:"called_by",imports:"imported_by",references:"referenced_by",extends:"extended_by",implements:"implemented_by",called_by:null,imported_by:null,referenced_by:null,extended_by:null,implemented_by:null,exports:null,contains:null,depends_on:null,member_of:null,documents:null,dispatches_action:null,listens_to_action:null,handles_action:null,selects_state:null,modifies_state:null,produces_api:null,consumes_api:null,generated_from:null},i=[];for(let n of t){let s=e[n.type];s&&i.push({id:"",fromId:n.toId,toId:n.fromId,type:s,metadata:{...n.metadata,isReverse:true,originalType:n.type}});}return i}async insertEntities(t,e){let i=Date.now(),n=[],s=0,{projectHash:a,branchName:l}=this.currentContext;I.i("BATCHOPS","insert_entities",{ctx:`${a}/${l}`,count:t.length});let h=new Set,o=[];for(let p of t){let m=this.entityKey(p);h.has(m)||(h.add(m),o.push(p));}let d=Math.ceil(o.length/this.batchSize);for(let p=0;p<o.length;p+=this.batchSize){let m=o.slice(p,Math.min(p+this.batchSize,o.length)),g=Math.floor(p/this.batchSize);try{let f=m.map(b=>{let C=Date.now();return {...b,id:b.id||this.stableEntityId(b),createdAt:b.createdAt||C,updatedAt:b.updatedAt||C}}),E=await this.adapter.insertEntities(f);s+=E.processed,E.errors.length>0&&n.push(...E.errors),e&&e(s,o.length),g<d-1&&await Wt();}catch(f){I.e("BATCHOPS","batch_error",{err:String(f)});for(let E of m)n.push({item:E,error:f instanceof Error?f.message:String(f)});}}return {processed:s,failed:n.length,errors:n,timeMs:Date.now()-i}}async updateEntities(t,e){let i=t.map(n=>"changes"in n&&n.id?{id:n.id,...n.changes,updatedAt:Date.now()}:n);return this.insertEntities(i,e)}async deleteEntities(t,e){let i=Date.now(),n=[],s=0,a=t.map(l=>typeof l=="string"?l:l.id||this.stableEntityId(l));for(let l=0;l<a.length;l+=this.batchSize){let h=a.slice(l,Math.min(l+this.batchSize,a.length));try{for(let o of h)await this.adapter.deleteEntity(o),s++;e&&e(s,a.length);}catch(o){for(let d of h)n.push({item:d,error:o instanceof Error?o.message:String(o)});}}return {processed:s,failed:n.length,errors:n,timeMs:Date.now()-i}}async insertRelationships(t,e){let i=Date.now(),n=[],s=0,{projectHash:a,branchName:l}=this.currentContext,h=this.generateReverseRelationships(t),o=[...t,...h];I.i("BATCHOPS","insert_relationships",{ctx:`${a}/${l}`,original:t.length,reverse:h.length,total:o.length});let d=new Set,p=[];for(let g of o){let f=this.relationshipKey(g);d.has(f)||(d.add(f),p.push(g));}let m=Math.ceil(p.length/this.batchSize);for(let g=0;g<p.length;g+=this.batchSize){let f=p.slice(g,Math.min(g+this.batchSize,p.length)),E=Math.floor(g/this.batchSize);try{let b=f.map(x=>{let N=Date.now();return {...x,id:this.stableRelationshipId(x),createdAt:x.createdAt||N}}),C=await this.adapter.insertRelationships(b);s+=C.processed,C.errors.length>0&&n.push(...C.errors),e&&e(s,p.length),E<m-1&&await Wt();}catch(b){I.e("BATCHOPS","rel_batch_error",{err:String(b)});for(let C of f)n.push({item:C,error:b instanceof Error?b.message:String(b)});}}return {processed:s,failed:n.length,errors:n,timeMs:Date.now()-i}}optimizeBatchSize(t){t<50?this.batchSize=Math.min(this.batchSize*1.2,kt):t>200&&(this.batchSize=Math.max(this.batchSize*.8,100)),this.batchSize=Math.floor(this.batchSize);}getBatchSize(){return this.batchSize}};R();c();var et={maxBytes:100*1024*1024,maxEntries:2e3,ttlMs:300*1e3};function it(c){if(c==null)return 0;switch(typeof c){case "string":return c.length*2;case "number":return 8;case "boolean":return 4;}if(c instanceof Date)return 8;if(Array.isArray(c)){let t=24;for(let e=0;e<c.length;e++)t+=it(c[e]);return t}if(typeof c=="object"){let t=24,e=c;for(let i of Object.keys(e))t+=i.length*2+it(e[i]);return t}return 24}var H=class{store;counters={hits:0,misses:0,evictions:0,sets:0};constructor(t={}){let e=t.defaultTTL??et.ttlMs;this.store=new LRUCache({max:t.maxEntries??et.maxEntries,maxSize:t.maxSize??et.maxBytes,sizeCalculation:i=>i.size||it(i.value),dispose:(i,n,s)=>{(s==="evict"||s==="delete")&&(this.counters.evictions++,I.d("CACHEMGR","evicted",{key:n,reason:s}));},ttl:e,updateAgeOnGet:true,updateAgeOnHas:false,allowStale:false});}get(t){let e=this.store.get(t);return e?(this.counters.hits++,e.hits++,this.store.set(t,e),e.value):(this.counters.misses++,null)}set(t,e,i){let n={key:t,value:e,timestamp:Date.now(),ttl:i??et.ttlMs,hits:0,size:it(e)};this.store.set(t,n),this.counters.sets++;}delete(t){this.store.delete(t);}clear(){this.store.clear(),I.i("CACHEMGR","cache_cleared");}has(t){return this.store.has(t)}prune(){this.store.purgeStale()&&I.i("CACHEMGR","pruned_stale");}getStats(){let t=this.counters.hits+this.counters.misses;return {size:this.store.size,hits:this.counters.hits,misses:this.counters.misses,hitRate:t>0?this.counters.hits/t:0,entries:this.store.size,evictions:this.counters.evictions,memoryUsage:this.store.calculatedSize||0}}getEntries(){return Array.from(this.store.entries()).map(([t,e])=>({key:t,value:e}))}resetStats(){this.counters={hits:0,misses:0,evictions:0,sets:0};}static createKey(t){let e=Object.keys(t).sort(),i={};for(let n of e)i[n]=t[n];return b$4(JSON.stringify(i)).substring(0,16)}};var yt=null;function Ht(c){return yt||(yt=new H(c)),yt}var me=new Set(["class","interface","module","namespace","enum","struct","object"]);function Gt(c){let t=new Map;for(let e of c){let i=t.get(e.name)||[];i.push(e),t.set(e.name,i);}return t}function $t(c,t,e){for(let i of e){let n=c.get(i.name)||[];n.push(i),c.set(i.name,n);let s=i.name.lastIndexOf(".");if(s>=0){let a=i.name.slice(s),l=t.get(a)||[];l.push(i),t.set(a,l);}}}function O(c,t,e,i,n,s){t.startsWith("this.")&&(t=t.slice(5));let a=c.get(t);if((!a||a.length===0)&&!t.includes(".")){let o=`.${t}`;if(s)a=s.get(o);else {a=[];for(let[d,p]of c)d.endsWith(o)&&a.push(...p);}}if(!a||a.length===0)return;if(i&&a.length>1){let o=a.filter(d=>d.filePath===i);o.length>0&&(a=o);}if(n&&a.length>1){let o=a.filter(d=>me.has(d.type));o.length>0&&(a=o);}if(e==null)return a[0]?.id;let l,h=1/0;for(let o of a){let d=Math.abs((o.location?.start?.line??0)-e);d<h&&(l=o,h=d);}return l?.id}var Xt=12,nt=null;async function zt(){nt||(nt=await ue());}function Lt(){if(!nt)throw new Error("xxHash not initialized - call initXXHash() first");return nt}function U(c){let e=c.type==="package"||c.type==="import"?`${c.type}|${c.name}`:`${c.filePath}|${c.type}|${c.name}|${c.location?.start?.index??-1}-${c.location?.end?.index??-1}`;return Lt().h64ToString(e).slice(0,Xt)}function j(c,t,e){return Lt().h64ToString(`${c}|${t}|${e}`).slice(0,Xt)}function Ut(c){let t="unknown",e="unknown";if(c.startsWith("external:")){let i=c.slice(9);if(/^[A-Za-z]:[\\/]/.test(i)){let n=i.lastIndexOf(":");n>2?(t=i.slice(0,n),e=i.slice(n+1)||"unknown"):t=i;}else {let n=i.indexOf(":");n!==-1?(t=i.slice(0,n),e=i.slice(n+1)||"unknown"):t=i;}}return {source:t,symbol:e}}function ye(c,t,e){let{source:i,symbol:n}=Ut(c),a=i.includes("/")||i.includes("\\")||/\.\w+$/.test(i)||i==="unknown"?n:`${i}.${n}`,l={name:a,type:"import",filePath:`external://${i}`,location:{start:{line:0,column:0,index:0},end:{line:0,column:0,index:0}},metadata:{isExternal:true,source:i,symbol:n,qualifiedName:a},hash:`external:${i}:${n}`},h=U(l);return t.has(c)||(t.set(c,h),e.push({...l,id:h,createdAt:Date.now(),updatedAt:Date.now()})),h}async function bt(c,t,e){let i=new Map,n=[];for(let s of c)typeof s.fromId=="string"&&s.fromId.startsWith("external:")&&(s.fromId=await Ot(s.fromId,i,n)),typeof s.toId=="string"&&s.toId.startsWith("external:")&&(s.toId=await Ot(s.toId,i,n)),s.id=t(s.fromId,s.toId,s.type);return n}async function Ot(c,t,e,i){let n=t.get(c);if(n)return n;Ut(c);return ye(c,t,e)}R();async function Et(c,t){if(!t.currentRepositoryPath||c.length===0)return;I.i("GITWATCHER","uncommitted_changes",{cnt:c.length});let e=c.map(i=>isAbsolute(i)?i:join(t.currentRepositoryPath,i));for(let i of e)a$2.publish("file:changed",{filePath:i,changeType:"modified",source:"git-watcher"},t.agentId);a$2.publish("indexer:files:changed",{files:e,count:e.length,repositoryPath:t.currentRepositoryPath,source:"git-watcher-uncommitted"},t.agentId),I.d("GITWATCHER","published_changes",{cnt:e.length});}async function Ct(c,t,e){!e.currentRepositoryPath||c.length===0||(I.d("GITWATCHER","debounced_embed",{cnt:c.length,bulkMode:t}),a$2.publish("indexer:embeddings:generate",{files:c,count:c.length,bulkMode:t,repositoryPath:e.currentRepositoryPath,source:"git-watcher-debounced"},e.agentId),I.d("GITWATCHER","embed_event_pub",{cnt:c.length,bulkMode:t}));}function Ce(c,t,e){try{return execSync(`git diff --name-only ${c}...${t}`,{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).trim().split(`
5
+ `).filter(s=>s.length>0).map(s=>join(e,s))}catch(i){return I.w("GITWATCHER","get_branch_diff_fail",{err:String(i)}),[]}}async function qt(c,t,e){if(I.i("GITWATCHER","branch_changed",{oldBranch:t,newBranch:c}),!e.branchManager||!e.currentRepositoryPath){I.w("GITWATCHER","branch_mgr_not_init");return}try{await e.branchManager.switchBranch(c,e.currentRepositoryPath);let i=Ce(t,c,e.currentRepositoryPath);I.i("GITWATCHER","branch_files_diff",{cnt:i.length,oldBranch:t,newBranch:c}),a$2.publish("indexer:branch:changed",{oldBranch:t,newBranch:c,repositoryPath:e.currentRepositoryPath,changedFiles:i.length},e.agentId),i.length>0&&(a$2.publish("indexer:files:changed",{files:i,count:i.length,repositoryPath:e.currentRepositoryPath,source:"git-watcher-branch-switch"},e.agentId),I.i("GITWATCHER","branch_reindex_triggered",{files:i.length})),I.i("GITWATCHER","branch_switched",{newBranch:c});}catch(i){I.e("GITWATCHER","branch_change_fail",{err:String(i)});}}async function Qt(c){await b$3(c);}function Kt(c,t){c.abortController&&c.abortController.abort();let e=new AbortController;c.setAbortController(e);let i=e.signal;I.d("INDEXER","embed_scheduled",{ms:c.debouncePeriodMs}),(async()=>{try{let n=Date.now();for(;!i.aborted&&Date.now()-n<c.debouncePeriodMs;)await Qt(1e3);i.aborted||await t();}catch{}})();}async function Yt(c){if(c.pendingGeneration){I.d("INDEXER","embed_pending_skip");return}c.setPendingGeneration(true),I.i("INDEXER","embed_batch_trigger"),a$2.publish("indexer:incremental:complete",{timestamp:Date.now(),reason:"debounced_after_incremental_update"},c.agentId),await Qt(5e3),c.setPendingGeneration(false);}async function Jt(c,t){let e=[],i=new Map;for(let s of t)i.set(`${s.name}:${s.location.start.line}`,s.id);let n=Math.min(c.length,t.length);for(let s=0;s<n;s++){let a=c[s],l=t[s];if(a.type==="import"&&a.importData)for(let h of a.importData.specifiers)e.push({id:nanoid(12),fromId:l.id,toId:`external:${a.importData.source}:${h.imported||h.local}`,type:"imports",metadata:{line:a.location.start.line,column:a.location.start.column,context:`Import from ${a.importData.source}`}});if(a.references)for(let h of a.references){let o=Array.from(i.keys()).find(d=>d.startsWith(`${h}:`));o&&e.push({id:nanoid(12),fromId:l.id,toId:i.get(o),type:"references",metadata:{line:a.location.start.line,column:a.location.start.column}});}if(a.children)for(let h of a.children){let o=`${h.name}:${h.location.start.line}`,d=i.get(o);d&&e.push({id:nanoid(12),fromId:l.id,toId:d,type:"contains",metadata:{line:h.location.start.line,column:h.location.start.column}});}if(a.inheritance){if(a.inheritance.baseClasses)for(let h of a.inheritance.baseClasses){let o=Array.from(i.keys()).find(p=>p.startsWith(`${h}:`)),d=o?i.get(o):`external:${h}`;e.push({id:nanoid(12),fromId:l.id,toId:d,type:"extends",metadata:{line:a.location.start.line,column:a.location.start.column,context:`${a.name} extends ${h}`}});}if(a.inheritance.interfaces)for(let h of a.inheritance.interfaces){let o=Array.from(i.keys()).find(p=>p.startsWith(`${h}:`)),d=o?i.get(o):`external:${h}`;e.push({id:nanoid(12),fromId:l.id,toId:d,type:"implements",metadata:{line:a.location.start.line,column:a.location.start.column,context:`${a.name} implements ${h}`}});}}if(a.relationships)for(let h of a.relationships){let o=h.target.startsWith("this.")?h.target.slice(5):h.target,d=Array.from(i.keys()).find(g=>(g.split(":")[0]??"").startsWith("this.")?false:g.startsWith(`${o}:`)||g.includes(`.${o}:`)),p=d?i.get(d):`external:${h.target}`,m;switch(h.type){case "calls":m="calls";break;case "inherits":m="extends";break;case "implements":m="implements";break;case "imports":m="imports";break;case "contains":m="contains";break;case "member_of":m="member_of";break;case "depends_on":m="depends_on";break;case "produces_api":m="produces_api";break;case "consumes_api":m="consumes_api";break;case "generated_from":m="generated_from";break;default:m="references";break}e.push({id:nanoid(12),fromId:l.id,toId:p,type:m,metadata:{line:a.location.start.line,column:a.location.start.column,context:`${a.name} ${h.type} ${h.target}`,originalType:h.type,...h.metadata}});}}return e}function Vt(){let c=b$1();return {maxConcurrency:c.indexer?.maxConcurrency??8,memoryLimit:c.indexer?.memoryLimit??512,priority:c.indexer?.priority??7,batchSize:c.indexer?.batchSize??1e3,cacheSize:c.indexer?.cacheSize??100*1024*1024,cacheTTL:c.indexer?.cacheTTL??300*1e3}}var Zt=class extends b{graphStorage;batchOps;cacheManager;branchManager=null;gitWatchers=new Map;fileWatcher=null;pendingEmbeddingGeneration=false;embeddingDebounceAbort=null;EMBEDDING_DEBOUNCE_MS=6e4;currentRepositoryPath=null;subscriptionIds=[];ready=false;lastFileWatcherError=null;indexingStats={entitiesIndexed:0,relationshipsCreated:0,filesProcessed:0,totalIndexTime:0,lastIndexTime:0};BATCH_FLUSH_THRESHOLD=270;pendingStorageEntities=[];pendingRelationships=[];pendingParsedEntities=[];pendingFilesCount=0;batchFlushPromise=null;entityNameMap=new Map;entitySuffixMap=new Map;idleFlushAbort=null;IDLE_FLUSH_MS=1e4;constructor(){super("indexer",Vt()),I.i("INDEXER","created",{id:this.id});}async onInitialize(){let t=Date.now();I.t("INDEXER","[IndexerAgent] \u25B6 onInitialize() START"),I.i("INDEXER","init_start"),I.t("INDEXER","[IndexerAgent] \u25B6 initXXHash"),await zt(),I.t("INDEXER",`[IndexerAgent] \u25C0 initXXHash (${Date.now()-t}ms)`);let e=b$1();{I.d("INDEXER","branch_aware_init");let l=e.indexing.dataDir||a();this.branchManager=new J({enabled:true,dataDir:l,maxBranchesPerRepo:e.indexing.maxBranchesPerRepo||10,maxTotalBranches:e.indexing.maxTotalBranches||50,evictionStrategy:e.indexing.evictionStrategy||"LRU"}),await this.branchManager.initialize(),e.git?.enabled&&e.git.watchBranchChanges&&I.i("INDEXER","git_watch_enabled");}I.t("INDEXER","[IndexerAgent] \u25B6 getGraphStorage");let i=Date.now();this.graphStorage=await d(),I.t("INDEXER",`[IndexerAgent] \u25C0 getGraphStorage (${Date.now()-i}ms)`),"initialize"in this.graphStorage&&typeof this.graphStorage.initialize=="function"&&(I.t("INDEXER","[IndexerAgent] \u25B6 graphStorage.initialize"),await this.graphStorage.initialize(),I.t("INDEXER",`[IndexerAgent] \u25C0 graphStorage.initialize (${Date.now()-i}ms)`));let n=Vt();I.t("INDEXER","[IndexerAgent] \u25B6 BatchOperationsLibSQL.initialize");let s=Date.now(),a$1=f();if(!a$1)throw new Error(`[${this.id}] LibSQLAdapter is required but not available - ensure getGraphStorage() was called first`);this.batchOps=new tt(a$1,n.batchSize),await this.batchOps.initialize(),I.t("INDEXER",`[IndexerAgent] \u25C0 BatchOperationsLibSQL.initialize (${Date.now()-s}ms)`),this.cacheManager=Ht({maxSize:n.cacheSize,defaultTTL:n.cacheTTL}),this.subscribeToParseEvents(),this.ready=true,I.i("INDEXER","init_done");}setProjectContext(t,e){I.i("INDEXER","set_project_ctx",{path:t}),this.graphStorage&&typeof this.graphStorage.setProject=="function"?(this.graphStorage.setProject(t,e),I.d("INDEXER","gs_ctx_set",{path:t,branch:e||"main"})):I.w("INDEXER","gs_ctx_not_ready"),this.batchOps&&typeof this.batchOps.setProject=="function"?(this.batchOps.setProject(t,e),I.d("INDEXER","batch_ctx_set",{path:t,branch:e||"main"})):I.w("INDEXER","batch_ctx_not_ready"),this.currentRepositoryPath=t,this.getOrCreateWatcher(t);}subscribeToParseEvents(){I.d("INDEXER","parse_subs_disabled");}canProcessTask(t){return true}async processTask(t){let e=t;switch(e.type){case "index:entities":return await this.indexEntities(e.payload.entities,e.payload.filePath,e.payload.relationships);case "index:incremental":return await this.incrementalUpdate(e.payload.changes);case "query:graph":return await this.queryGraph(e.payload.query);case "query:subgraph":return await this.querySubgraph(e.payload.entityId,e.payload.depth||2);default:throw new Error(`Unknown task type: ${e.type}`)}}async indexEntities(t,e,i){let n=Date.now(),s=b$2(t),a=s.length-t.length,l=s.filter(u=>u.language).length,h=s.filter(u=>u.language).slice(0,2),o=s.filter(u=>!u.language).slice(0,2);if(I.i("INDEXER","lang_check",{total:s.length,withLang:l,langSample:h.map(u=>({n:u.name,l:u.language})),noLangSample:o.map(u=>({n:u.name,t:u.type}))}),I.d("INDEXER","indexing",{entities:t.length,flat:s.length,children:a,file:e}),a>0){let u=s.slice(t.length,t.length+3);I.t("INDEXER","sample_children",{sample:u.map(v=>v.name).join(",")});}let d=[],p=[],m=[],g=nanoid(8);for(let u of s)try{if(!(u&&typeof u=="object"&&"name"in u&&typeof u.name=="string"&&"type"in u&&u.type&&"location"in u&&u.location)){let y=[];u?typeof u!="object"?y.push("not object"):((!("name"in u)||typeof u.name!="string")&&y.push("no name"),(!("type"in u)||!u.type)&&y.push("no type"),(!("location"in u)||!u.location)&&y.push("no location")):y.push("null/undefined");let Q=u&&typeof u=="object"&&"name"in u?u.name:void 0;throw I.t("INDEXER","rejected_entity",{name:Q,reasons:y.join(",")}),new Error("Invalid entity")}let $=u?.type==="import"&&u?.importData?.source,D=!(typeof u.name=="string"&&u.name.trim().length>0)&&$?{...u,name:`import:${u.importData?.source}`}:u,X=D.filePath||e,M=a$1(D,X,g),q={...M,id:U(M),createdAt:Date.now(),updatedAt:Date.now()};d.push(q),p.push(D);}catch(v){m.push({item:u,error:v.message});}let f=await this.batchOps.insertEntities(d,(u,v)=>{I.t("INDEXER","entity_progress",{processed:u,total:v});});if(I.d("INDEXER","entity_insert_done",{processed:f.processed,failed:f.failed,errors:f.errors.length}),f.failed>0&&I.w("INDEXER","entity_errors",{errs:f.errors.slice(0,3).map(u=>u.error)}),p.length){let u=p.map((v,$)=>({...v,id:d[$]?.id||v.id,filePath:e}));a$2.publish("semantic:new_entities",u,this.id),I.d("INDEXER","Published semantic:new_entities EARLY",{count:u.length,file:e});}let E=[];if(i&&i.length>0){let u=Gt(d);I.t("INDEXER","entity_names_sample",{sample:Array.from(u.keys()).slice(0,10)});let v=i.slice(0,3);I.t("INDEXER","raw_rels_sample",{sample:v.map(y=>`${y.from}->${y.to}`)});let $=Date.now();I.t("INDEXER","process_rels",{cnt:i.length});let k=0,D=0,X=0,M=[];for(let y of i){let Q=y.sourceFile||e,te=y.type==="contains",P=O(u,y.from,y.metadata?.line,Q,te),S=O(u,y.to,y.metadata?.line,y.targetFile||Q);y.type==="calls"&&(k++,P&&D++,S&&X++,M.length<3&&M.push({from:y.from,to:y.to,fromId:P||`EXT:${y.from}`,toId:S||`EXT:${y.to}`})),E.length===0&&I.t("INDEXER","first_rel_resolve",{from:y.from,fromId:P,to:y.to,toId:S}),P||(P=`external:${y.sourceFile||e||"unknown"}:${y.from}`),S||(S=`external:${y.targetFile||"unknown"}:${y.to}`),P&&S?E.push({id:j(P,S,y.type),fromId:P,toId:S,type:y.type,metadata:{line:y.metadata?.line,context:y.type},createdAt:Date.now()}):I.t("INDEXER","rel_skipped",{from:y.from,to:y.to,fromId:P,toId:S});}if(k>0){I.i("INDEXER","calls_resolution_stats",{total:k,fromResolved:D,toResolved:X,fromPct:Math.round(D/k*100),toPct:Math.round(X/k*100)}),M.length>0&&I.i("INDEXER","calls_sample",{sample:M});let y=Array.from(u.keys()).slice(0,5);I.i("INDEXER","entity_names_in_map",{sample:y,total:u.size});}let q=Date.now()-$;I.i("INDEXER","RelationshipLoop",{count:i.length,builtCount:E.length,ms:q}),I.d("INDEXER","using_provided_rels",{cnt:E.length,ms:q});}else E=await this.buildRelationshipsInternal(p,d),I.d("INDEXER","built_auto_rels",{cnt:E.length});let b=await bt(E,j);b.length>0&&await this.batchOps.insertEntities(b);let C={processed:0,failed:0,errors:[]},x=0;if(E.length>0){I.t("INDEXER","insert_rels_start",{cnt:E.length});let u=Date.now();C=await this.batchOps.insertRelationships(E),x=Date.now()-u,I.i("INDEXER","InsertRelationships",{count:E.length,processed:C.processed,ms:x});}let N={path:e,hash:g,lastIndexed:Date.now(),entityCount:d.length};await this.graphStorage.updateFileInfo(N),this.cacheManager.clear();let _=Date.now()-n;this.indexingStats.entitiesIndexed+=f.processed,this.indexingStats.relationshipsCreated+=C.processed,this.indexingStats.filesProcessed++,this.indexingStats.totalIndexTime+=_,this.indexingStats.lastIndexTime=_,I.t("INDEXER","pub_index_complete"),a$2.publish("index:complete",{filePath:e,entities:f.processed,relationships:C.processed,timeMs:_},this.id),I.t("INDEXER","index_complete_pubbed"),I.i("INDEXER","indexed_done",{entities:f.processed,rels:C.processed,ms:_});let st=f.failed+C.failed+m.length,w=[...f.errors,...C.errors,...m],{timeMs:at,...A}=f;return {...A,failed:st,errors:w,timeMs:_,entitiesIndexed:f.processed,relationshipsCreated:C.processed}}async buildRelationshipsInternal(t,e){return Jt(t,e)}resetIdleFlushTimer(){if(this.idleFlushAbort&&this.idleFlushAbort.abort(),this.pendingFilesCount===0)return;let t=new AbortController;this.idleFlushAbort=t,(async()=>{if(await b$3(this.IDLE_FLUSH_MS),!t.signal.aborted&&this.pendingFilesCount>0){I.d("INDEXER","idle_flush",{pending:this.pendingFilesCount,entities:this.pendingStorageEntities.length,relationships:this.pendingRelationships.length}),M("INDEXER",{pendingFiles:this.pendingFilesCount});try{await this.flushPendingBatch(),c$1(!0)&&I.d("INDEXER","gc_after_idle_flush");}catch(e){I.w("INDEXER","Idle flush failed",{error:e.message});}}})();}queueForIndexing(t,e,i){if(!t||t.length===0)return;this.resetIdleFlushTimer(),(e.endsWith(".py")||e.endsWith(".cs"))&&I.i("INDEXER","queue_rels_debug",{file:e.split(/[/\\]/).pop(),entities:t.length,relationships:i?.length??0,relSample:i?.slice(0,3).map(l=>`${l.from}->${l.to}:${l.type}`)});let n=b$2(t),s=nanoid(8),a=[];for(let l of n)try{if(!l?.name||!l?.type||!l?.location)continue;let h=l.filePath||e,o=a$1(l,h,s),d={...o,id:U(o),createdAt:Date.now(),updatedAt:Date.now()};a.push(d),e.endsWith(".cs")&&(l.type==="class"||l.type==="interface")&&I.w("INDEXER","csharp_entity_id_debug",{name:d.name,type:d.type,id:d.id,entityFilePath:h?.split(/[/\\]/).slice(-2).join("/"),parsedFilePath:l.filePath?.split(/[/\\]/).slice(-2).join("/"),paramFilePath:e?.split(/[/\\]/).slice(-2).join("/"),pathMatch:h===e,startIndex:o.location?.start?.index,endIndex:o.location?.end?.index});}catch{}if(this.pendingStorageEntities.push(...a),$t(this.entityNameMap,this.entitySuffixMap,a),i&&i.length>0){if(e.endsWith(".swift")){let o=i.filter(d=>d.type==="calls"&&d.metadata?.crossModule);o.length>0&&I.w("XMOD","swift_cross_module",{file:e.split(/[/\\]/).pop(),crossModuleCalls:o.length,pendingEntities:this.pendingStorageEntities.length,byNameSize:this.entityNameMap.size,serverPosterKeys:Array.from(this.entityNameMap.keys()).filter(d=>d.includes("ServerPoster")),calls:o.slice(0,5).map(d=>({from:d.from,to:d.to,inByName:this.entityNameMap.has(d.to)}))});}let l=0,h=0;for(let o of i){let d=o.sourceFile||e,p=o.type==="contains",m=O(this.entityNameMap,o.from,o.metadata?.line,d,p,this.entitySuffixMap),g=O(this.entityNameMap,o.to,o.metadata?.line,o.targetFile||d,void 0,this.entitySuffixMap);if(o.metadata?.crossModule&&I.w("XMOD","resolution",{to:o.to,resolved:!!g,toId:g||"UNRESOLVED"}),m||(m=`external:${d}:${o.from}`),g||(g=`external:${o.targetFile||"unknown"}:${o.to}`),e.endsWith(".cs")&&o.type==="contains"&&l+h<5&&I.w("INDEXER","csharp_rel_id_debug",{file:e.split(/[/\\]/).pop(),from:o.from,to:o.to,fromId:m.slice(0,16),toId:g.slice(0,16),fromIsExternal:m.startsWith("external:"),toIsExternal:g.startsWith("external:"),sourceFile:d?.split(/[/\\]/).slice(-2).join("/")}),e.endsWith(".cs")){let f=!m.startsWith("external:"),E=!g.startsWith("external:");f&&E?l++:h++;}this.pendingRelationships.push({id:j(m,g,o.type),fromId:m,toId:g,type:o.type,metadata:{line:o.metadata?.line,context:o.type},createdAt:Date.now()});}e.endsWith(".cs")&&(l>0||h>0)&&I.i("INDEXER","csharp_rel_resolution",{file:e.split(/[/\\]/).pop(),resolved:l,unresolved:h,pendingEntities:this.pendingStorageEntities.length,byNameSize:this.entityNameMap.size,pendingRels:this.pendingRelationships.length,fileEntityNames:this.pendingStorageEntities.filter(o=>o.filePath===e).slice(0,10).map(o=>`${o.name}(${o.type})`)});}this.pendingParsedEntities.push({entities:n,filePath:e}),this.pendingFilesCount++,this.pendingFilesCount>=this.BATCH_FLUSH_THRESHOLD&&this.flushPendingBatch().catch(l=>{I.w("INDEXER","Auto-flush failed",{error:l.message});});}async flushPendingBatch(){this.batchFlushPromise&&await this.batchFlushPromise;let t=this.pendingStorageEntities,e=this.pendingRelationships,i=this.pendingParsedEntities,n=this.pendingFilesCount;if(this.pendingStorageEntities=[],this.pendingRelationships=[],this.pendingParsedEntities=[],this.pendingFilesCount=0,this.entityNameMap=new Map,this.entitySuffixMap=new Map,t.length===0)return {entities:0,relationships:0,files:0};let s=Date.now();return this.batchFlushPromise=(async()=>{let a=await this.batchOps.insertEntities(t),l=new Map;for(let g of t)l.set(`${g.name}|${g.type}|${g.filePath}`,g.id);for(let{entities:g,filePath:f}of i){let E=g.map(b=>{let C=b.filePath||f,x=l.get(`${b.name}|${b.type}|${C}`);return {...b,id:x||b.id,filePath:C}});a$2.publish("semantic:new_entities",E,this.id);}let h=await bt(e,j);h.length>0&&await this.batchOps.insertEntities(h);let o={processed:0};if(e.length>0){let g=e.filter(b=>!b.fromId.startsWith("external:")&&!b.toId.startsWith("external:")),f=e.length-g.length;I.i("INDEXER","flush_rels",{count:e.length,real:g.length,external:f,sample:g.slice(0,3).map(b=>`${b.fromId}->${b.toId}:${b.type}`)});let E=t.filter(b=>b.language==="csharp"&&b.type==="class");if(E.length>0){let b=new Set(E.map(w=>w.id)),C=new Set(t.map(w=>w.id)),x=0,N=0,_=0;for(let w of e)b.has(w.fromId)&&x++,b.has(w.toId)&&N++,(C.has(w.fromId)||C.has(w.toId))&&_++;let st=E.slice(0,3).map(w=>{let at=e.filter(A=>A.fromId===w.id||A.toId===w.id);return {name:w.name,id:w.id,filePath:w.filePath?.split(/[/\\]/).slice(-2).join("/"),relsCount:at.length,relSample:at.slice(0,3).map(A=>`${A.fromId.slice(0,8)}\u2192${A.toId.slice(0,8)}:${A.type}`)}});I.w("INDEXER","flush_cs_crosscheck",{csClasses:E.length,csClassRelsFrom:x,csClassRelsTo:N,totalRels:e.length,relsRefAnyEntity:_,samples:st});}o=await this.batchOps.insertRelationships(e);}let d=new Map;for(let{filePath:g,entities:f}of i){let E=d.get(g)||0;d.set(g,E+f.length);}let p=[],m=Date.now();for(let[g,f]of d)p.push({path:g,hash:nanoid(8),lastIndexed:m,entityCount:f});if(p.length>0)if("batchUpdateFileInfo"in this.graphStorage&&typeof this.graphStorage.batchUpdateFileInfo=="function")await this.graphStorage.batchUpdateFileInfo(p);else for(let g of p)await this.graphStorage.updateFileInfo(g);this.indexingStats.entitiesIndexed+=a.processed,this.indexingStats.relationshipsCreated+=o.processed,this.indexingStats.filesProcessed+=n,I.i("INDEXER","Batch flush completed",{entities:a.processed,relationships:o.processed,files:n,filesTracked:d.size,ms:Date.now()-s});})(),await this.batchFlushPromise,this.batchFlushPromise=null,{entities:t.length,relationships:e.length,files:n}}getPendingBatchStats(){return {entities:this.pendingStorageEntities.length,relationships:this.pendingRelationships.length,files:this.pendingFilesCount}}async incrementalUpdate(t){I.d("INDEXER","incr_update",{cnt:t.length});let e=[],i=[],n=[];for(let h of t)switch(h.type){case "added":h.entity&&e.push(h.entity);break;case "modified":h.entity&&h.entityId&&i.push({id:h.entityId,changes:h.entity});break;case "deleted":h.entityId&&n.push(h.entityId);break}let s=0,a=0,l=[];if(e.length>0){let h=await this.batchOps.insertEntities(e);s+=h.processed,a+=h.failed,l.push(...h.errors);}if(i.length>0){let h=await this.batchOps.updateEntities(i);s+=h.processed,a+=h.failed,l.push(...h.errors);}if(n.length>0){let h=await this.batchOps.deleteEntities(n);s+=h.processed,a+=h.failed,l.push(...h.errors);}return this.cacheManager.clear(),this.doScheduleEmbeddingGeneration(),{processed:s,failed:a,errors:l,timeMs:0}}getEmbeddingSchedulerContext(){return {agentId:this.id,debouncePeriodMs:this.EMBEDDING_DEBOUNCE_MS,abortController:this.embeddingDebounceAbort,pendingGeneration:this.pendingEmbeddingGeneration,setPendingGeneration:t=>{this.pendingEmbeddingGeneration=t;},setAbortController:t=>{this.embeddingDebounceAbort=t;}}}doScheduleEmbeddingGeneration(){let t=this.getEmbeddingSchedulerContext();Kt(t,async()=>{await Yt(this.getEmbeddingSchedulerContext());});}async queryGraph(t){let e=H.createKey(t),i=this.cacheManager.get(e);if(i)return I.t("INDEXER","cache_hit_query"),i;I.t("INDEXER","exec_query");let n=await this.graphStorage.executeQuery(t);return this.cacheManager.set(e,n),n}async querySubgraph(t,e){let i=H.createKey({entityId:t,depth:e}),n=this.cacheManager.get(i);if(n)return I.t("INDEXER","cache_hit_subgraph"),n;I.t("INDEXER","get_subgraph",{entityId:t,depth:e});let s=await this.graphStorage.getSubgraph(t,e);return this.cacheManager.set(i,s),s}async handleMessage(t){switch(I.d("INDEXER","recv_msg",{type:t.type,from:t.from}),t.type){case "index:request":{let e={id:t.id,type:"index:entities",priority:5,payload:t.payload,createdAt:Date.now()};await this.process(e);break}case "query:request":{let e={id:t.id,type:"query:graph",priority:8,payload:t.payload,createdAt:Date.now()},i=await this.process(e);await this.send({id:nanoid(12),from:this.id,to:t.from,type:"query:response",payload:i,timestamp:Date.now(),correlationId:t.id});break}default:I.w("INDEXER","unknown_msg_type",{type:t.type});}}getGitEventContextForProject(t){return {agentId:this.id,currentRepositoryPath:t,branchManager:this.branchManager}}getGitEventContext(){return this.getGitEventContextForProject(this.currentRepositoryPath)}getOrCreateWatcher(t){let e=b$1();if(!e.git?.enabled||!e.git.watchBranchChanges||!this.branchManager)return null;let i=this.gitWatchers.get(t);if(i)return i;let n=new Z({enabled:true,pollIntervalMs:e.git.pollIntervalMs||5e3,autoReindex:e.git.autoReindex??true,watchUncommitted:e.git.watchUncommitted??true,uncommittedPollIntervalMs:e.git.uncommittedPollIntervalMs||1e4,includeUntracked:e.git.includeUntracked??true,debounceMs:e.git.debounceMs??6e4,bulkModeThreshold:e.git.bulkModeThreshold??1e3}),s=()=>this.getGitEventContextForProject(t);return n.onBranchChange(async(a,l)=>{await qt(a,l,s());}),n.onUncommittedChange(async a=>{await Et(a,s());}),n.onDebouncedChange(async(a,l)=>{await Ct(a,l,s());}),this.gitWatchers.set(t,n),n.startWatching(t),I.i("INDEXER","git_watcher_started",{repository:t,totalWatchers:this.gitWatchers.size}),n}getBranchManager(){return this.branchManager}getGitWatcher(t){let e=t||this.currentRepositoryPath;return e?this.gitWatchers.get(e)??null:null}getFileWatcherStatus(){return this.fileWatcher?{exists:true,status:this.fileWatcher.getStatus(),lastError:null}:{exists:false,lastError:this.lastFileWatcherError}}async setRepositoryPath(t){this.currentRepositoryPath=t,this.getOrCreateWatcher(t),I.d("INDEXER","creating_filewatcher",{path:t});try{this.fileWatcher&&(I.d("INDEXER","stopping_old_filewatcher"),await this.fileWatcher.stop(),this.fileWatcher=null);let e=b$1();this.fileWatcher=await Ft({rootDir:t,include:["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py","**/*.go","**/*.rs","**/*.java","**/*.kt","**/*.cpp","**/*.c","**/*.h","**/*.hpp"],exclude:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.ultracode/**","**/coverage/**","**/__pycache__/**","**/venv/**","**/.venv/**"],debounceMs:100,bulkThreshold:e.git?.bulkModeThreshold??1e3}),this.fileWatcher.on("change",(i,n)=>{this.handleFileWatcherChanges(i,n).catch(s=>{I.e("INDEXER","FileWatcher change handler error",{error:s.message});});}),this.fileWatcher.on("error",i=>{I.e("INDEXER","FileWatcher error",{error:i.message});}),I.i("INDEXER","Started FileWatcher",{repository:t}),this.lastFileWatcherError=null;}catch(e){this.lastFileWatcherError=e.message,I.w("INDEXER","Failed to start FileWatcher, using GitWatcher only",{error:this.lastFileWatcherError});}}async handleFileWatcherChanges(t,e){if(t.length===0)return;let i=t.filter(s=>s.type==="add"||s.type==="change").map(s=>s.path),n=t.filter(s=>s.type==="unlink").map(s=>s.path);I.d("INDEXER","FileWatcher detected changes",{changed:i.length,deleted:n.length,bulkMode:e}),i.length>0&&await Et(i,this.getGitEventContext()),n.length>0&&I.d("INDEXER","Detected deleted files (cleaned on reindex)",{count:n.length,files:n.slice(0,5)}),e?await Ct(i,e,this.getGitEventContext()):this.doScheduleEmbeddingGeneration();}async onShutdown(){if(I.i("INDEXER","Shutting down..."),this.idleFlushAbort&&(this.idleFlushAbort.abort(),this.idleFlushAbort=null),this.pendingFilesCount>0){I.d("INDEXER","shutdown_flush_pending",{pending:this.pendingFilesCount});try{await this.flushPendingBatch();}catch(t){I.w("INDEXER","shutdown_flush_failed",{error:t.message});}}if(this.fileWatcher)try{await this.fileWatcher.stop(),this.fileWatcher=null,I.d("INDEXER","FileWatcher stopped");}catch(t){I.w("INDEXER","Error stopping FileWatcher",{error:t.message});}for(let[t,e]of this.gitWatchers)e.stopWatching(),I.d("INDEXER","git_watcher_stopped",{repository:t});this.gitWatchers.clear();try{for(let t of this.subscriptionIds)a$2.unsubscribe(t);}catch{}if(this.ready)try{await this.graphStorage.analyze();}catch(t){I.w("INDEXER","shutdown_analyze_skip",{err:t.message});}try{this.cacheManager?.clear();}catch{}I.i("INDEXER","shutdown_done",this.indexingStats);}getIndexingStats(){return {...this.indexingStats}}async getStorageMetrics(){return await this.graphStorage.getMetrics()}async performMaintenance(){I.i("INDEXER","maint_start"),await this.graphStorage.vacuum(),await this.graphStorage.analyze(),this.cacheManager.prune();let t=this.indexingStats.totalIndexTime/Math.max(1,this.indexingStats.filesProcessed);this.batchOps.optimizeBatchSize(t),I.i("INDEXER","maint_done");}};export{Zt as a};