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,11 @@
1
+ import {a,c as c$1}from'./chunk-V6JAQNM3.js';import {b as b$2}from'./chunk-V5VLOVE7.js';import {a as a$1}from'./chunk-IFKMF76K.js';import {c,b as b$1}from'./chunk-PZF7YC35.js';import'./chunk-NWQZW3Y6.js';import {G as G$1,e}from'./chunk-2KIPXYOB.js';import'./chunk-OG62YNVF.js';import {R,I}from'./chunk-4BI7EBPQ.js';import {d,b,f}from'./chunk-DXB73IDG.js';import {execSync}from'child_process';import {existsSync}from'fs';import {join}from'path';var se={};d(se,{ContentNormalizer:()=>_});var _,ce=b(()=>{c();G$1();_=class{async normalize(e$1){let t=Buffer.from(await e(e$1)),{encoding:n,hasBom:i}=this.detectEncoding(t),r=t.toString(n);return i&&r.charCodeAt(0)===65279&&(r=r.slice(1)),r=this.normalizeLineEndings(r),r=this.trimTrailingWhitespace(r),r=r.replace(/\n+$/,`
2
+ `),{content:r,originalEncoding:n,hadBom:i}}computeContentHash(e){return b$1(e)}detectEncoding(e){return e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191?{encoding:"utf8",hasBom:true}:e.length>=2&&e[0]===255&&e[1]===254?{encoding:"utf16le",hasBom:true}:e.length>=2&&e[0]===254&&e[1]===255?{encoding:"utf16le",hasBom:true}:{encoding:"utf8",hasBom:false}}normalizeLineEndings(e){return e=e.replace(/\r\n/g,`
3
+ `),e=e.replace(/\r/g,`
4
+ `),e}trimTrailingWhitespace(e){return e.split(`
5
+ `).map(t=>t.replace(/[ \t]+$/,"")).join(`
6
+ `)}};});var le={};d(le,{CodeUnitType:()=>de});var de,he=b(()=>{de=(s=>(s.File="file",s.Module="module",s.Class="class",s.Interface="interface",s.Function="function",s.Method="method",s.Property="property",s.Block="block",s.Statement="statement",s))(de||{});});R();R();function ne(h,e,t){return {id:`conflict-${e.id}-${t.id}-${Date.now()}`,type:"OverlappingChanges",severity:"Medium",baseUnit:h,branchAUnit:e,branchBUnit:t,description:`Both branches modified ${e.fullyQualifiedName}`,conflictingRegions:[],autoResolvable:false}}function ie(h,e,t,n,i){return {id:`conflict-${e.id}-${t.id}-${Date.now()}`,type:"IncompatibleIntents",severity:"High",baseUnit:h,branchAUnit:e,branchBUnit:t,branchAIntent:n,branchBIntent:i,description:`Incompatible intents: ${n.type} vs ${i.type}`,conflictingRegions:[],autoResolvable:false}}function z(h,e,t){return {id:`conflict-${e.id}-${t.id}-${Date.now()}`,type:"APIBreakingChange",severity:"Critical",baseUnit:h,branchAUnit:e,branchBUnit:t,description:`API breaking change in ${e.fullyQualifiedName}`,conflictingRegions:[],autoResolvable:false}}var E=class{config;embeddingCache=new Map;constructor(e){this.config=e;}async analyzeConflict(e){let{baseUnit:t,branchAUnit:n,branchBUnit:i}=e,[r,a,o]=await Promise.all([this.getEmbedding(t),this.getEmbedding(n),this.getEmbedding(i)]),c=this.cosineSimilarity(a,o),s=r&&a?this.cosineDistance(r,a):0,u=r&&o?this.cosineDistance(r,o):0,{strategy:m,confidence:C,explanation:v,mergedCode:w}=this.determineStrategy(e,c,s,u);return {similarity:c,branchADistance:s,branchBDistance:u,suggestedStrategy:m,confidence:C,explanation:v,mergedCode:w}}async getEmbedding(e){if(!e)return null;let t=this.getCacheKey(e);if(this.embeddingCache.has(t))return this.embeddingCache.get(t);if(e.embedding)return this.embeddingCache.set(t,e.embedding),e.embedding;try{let n=this.prepareTextForEmbedding(e),i=await this.config.embeddingGenerator.generateEmbedding(n);return this.embeddingCache.set(t,i),i}catch(n){return I.w("AICONFLICT","embedding_fail",{id:e.id,err:String(n)}),null}}prepareTextForEmbedding(e){let t=[];if(e.fullyQualifiedName&&t.push(`Name: ${e.fullyQualifiedName}`),e.signature&&t.push(`Signature: ${e.signature}`),e.content){let n=e.content.trim().replace(/\s+/g," ");t.push(`Code: ${n}`);}return t.join(`
7
+ `)}determineStrategy(e,t,n,i){let{branchAUnit:r,branchBUnit:a}=e;if(t>=this.config.highSimilarityThreshold){let o=n<=i;return {strategy:o?"TakeBranchA":"TakeBranchB",confidence:.95,explanation:`Both branches made semantically similar changes (similarity: ${t.toFixed(2)}). Choosing ${o?"branchA":"branchB"} as it's closer to base.`,mergedCode:o?r.content:a.content}}if(t>=this.config.mediumSimilarityThreshold){let o=this.attemptIntelligentMerge(e,t);return o?{strategy:"MergeBoth",confidence:.7+t*.2,explanation:`Changes are semantically compatible (similarity: ${t.toFixed(2)}). AI-generated merge proposed.`,mergedCode:o}:{strategy:"ManualReview",confidence:.6,explanation:`Changes are moderately similar (${t.toFixed(2)}) but automatic merge is uncertain. Manual review recommended.`}}return t>=this.config.lowSimilarityThreshold?{strategy:"ManualReview",confidence:.4,explanation:`Changes are semantically different (similarity: ${t.toFixed(2)}). Manual review required.`}:{strategy:"ManualReview",confidence:.2,explanation:`Changes are semantically divergent (similarity: ${t.toFixed(2)}). Careful manual review strongly recommended.`}}attemptIntelligentMerge(e,t){let{baseUnit:n,branchAUnit:i,branchBUnit:r}=e,a=n?.content.length||0,o=i.content.length,c=r.content.length,s=o>a,u=c>a;return s&&u&&t>=.7?o>c?i.content:r.content:Math.max(Math.abs(o-a),Math.abs(c-a))<100&&t>=.8?i.content:null}cosineSimilarity(e,t){if(!e||!t||e.length!==t.length)return 0;let n=0,i=0,r=0;for(let o=0;o<e.length;o++){let c=e[o]??0,s=t[o]??0;n+=c*s,i+=c*c,r+=s*s;}let a=Math.sqrt(i)*Math.sqrt(r);return a===0?0:n/a}cosineDistance(e,t){return 1-this.cosineSimilarity(e,t)}getCacheKey(e){return `${e.id}-${e.contentHash}`}createResolution(e){return {strategy:e.suggestedStrategy,confidence:e.confidence,mergedCode:e.mergedCode||"",explanation:e.explanation}}clearCache(){this.embeddingCache.clear();}getCacheStats(){return {size:this.embeddingCache.size,maxSize:1e3}}};R();function re(h){return {type:"BugFix",confidence:h.length>0?Math.min(.7+h.length*.1,1):.5,evidence:h,description:"Code change appears to fix a bug"}}function ae(h){return {type:"Refactoring",confidence:h.length>0?Math.min(.7+h.length*.1,1):.5,evidence:h,description:"Code change is refactoring without logic changes"}}function O(h){return {type:"FeatureAddition",confidence:h.length>0?Math.min(.7+h.length*.1,1):.5,evidence:h,description:"Code change adds new functionality"}}function oe(h){return {type:"APIChange",confidence:h.length>0?Math.min(.7+h.length*.1,1):.5,evidence:h,description:"Code change modifies API signatures"}}function j(){return {type:"Unknown",confidence:0,evidence:[],description:"Unable to classify change intent"}}var $=class{detectConflict(e,t,n,i,r){if(t.contentHash===n.contentHash)return null;let a=this.detectAPIConflict(e,t,n);if(a)return a;if(i&&r){let c=this.detectIntentConflict(e,t,n,i,r);if(c)return c}let o=ne(e,t,n);return o.severity=this.classifySeverity(e,t,n),o.autoResolvable=this.isAutoResolvable(o,i,r),o}detectAPIConflict(e,t,n){if(!e)return null;let i=e.signature!==t.signature,r=e.signature!==n.signature;if(i&&r)return z(e,t,n);let a=e.fullyQualifiedName!==t.fullyQualifiedName,o=e.fullyQualifiedName!==n.fullyQualifiedName;return a&&o?z(e,t,n):null}detectIntentConflict(e,t,n,i,r){return this.areIntentsCompatible(i.type,r.type)?null:ie(e,t,n,i,r)}areIntentsCompatible(e,t){let i={BugFix:new Set(["BugFix","Refactoring"]),Refactoring:new Set(["BugFix","Refactoring"]),FeatureAddition:new Set(["FeatureAddition"]),APIChange:new Set([]),Unknown:new Set(["Unknown"])}[e];return i?i.has(t):false}classifySeverity(e,t,n){if(!e)return "Medium";let i=this.computeDifference(e.content,t.content),r=this.computeDifference(e.content,n.content);return i>.5&&r>.5?"High":i>.3||r>.3?"Medium":"Low"}computeDifference(e,t){let n=Math.max(e.length,t.length);if(n===0)return 0;let i=Math.abs(e.length-t.length);return Math.min(i/n,1)}isAutoResolvable(e,t,n){return e.severity==="Critical"||e.type==="APIBreakingChange"?false:!!(t&&n&&this.areIntentsCompatible(t.type,n.type)&&e.severity==="Low")}detectConflicts(e){let t=[];for(let n of e){let i=this.detectConflict(n.baseUnit,n.branchAUnit,n.branchBUnit,n.branchAIntent,n.branchBIntent);i&&t.push(i);}return t}};var T=class{classifyIntent(e,t){if(!e)return this.classifyNewUnit(t);let n=this.collectBugFixEvidence(e,t),i=this.collectRefactoringEvidence(e,t),r=this.collectFeatureAdditionEvidence(e,t),a=this.collectAPIChangeEvidence(e,t),o=[{type:"BugFix",evidence:n,count:n.length},{type:"Refactoring",evidence:i,count:i.length},{type:"FeatureAddition",evidence:r,count:r.length},{type:"APIChange",evidence:a,count:a.length}];o.sort((s,u)=>u.count-s.count);let c=o[0];if(!c||c.count===0)return j();switch(c.type){case "BugFix":return re(n);case "Refactoring":return ae(i);case "FeatureAddition":return O(r);case "APIChange":return oe(a);default:return j()}}classifyNewUnit(e){let t=[];return e.type==="class"?t.push({type:"NewClass",description:`Added new class: ${e.name}`,location:`${e.filePath}:${e.startLine}`}):e.type==="function"||e.type==="method"?t.push({type:"NewMethod",description:`Added new method: ${e.name}`,location:`${e.filePath}:${e.startLine}`}):e.type==="property"&&t.push({type:"NewProperty",description:`Added new property: ${e.name}`,location:`${e.filePath}:${e.startLine}`}),O(t)}collectBugFixEvidence(e,t){let n=[],i=e.content.toLowerCase(),r=t.content.toLowerCase();!i.includes("try")&&r.includes("try")&&n.push({type:"AddedTryCatch",description:"Added try-catch block for error handling",location:`${t.filePath}:${t.startLine}`});let a=(i.match(/\bif\s*\(/g)||[]).length,o=(r.match(/\bif\s*\(/g)||[]).length;return o>a&&n.push({type:"AddedValidation",description:`Added validation checks (+${o-a} if statements)`,location:`${t.filePath}:${t.startLine}`}),(r.includes("!= null")||r.includes("!== null")||r.includes("== null")||r.includes("=== null"))&&!i.includes("null")&&n.push({type:"AddedNullCheck",description:"Added null/undefined check",location:`${t.filePath}:${t.startLine}`}),n}collectRefactoringEvidence(e,t){let n=[];return e.name!==t.name&&e.structuralHash===t.structuralHash&&n.push({type:"RenamedVariable",description:`Renamed ${e.name} to ${t.name}`,location:`${t.filePath}:${t.startLine}`}),e.structuralHash===t.structuralHash&&e.contentHash!==t.contentHash&&n.push({type:"CFGPreserved",description:"Code structure preserved (likely refactoring)",location:`${t.filePath}:${t.startLine}`}),n}collectFeatureAdditionEvidence(e,t){let n=[],i=t.childIds.length-e.childIds.length;i>0&&n.push({type:"NewMethod",description:`Added ${i} new methods/properties`,location:`${t.filePath}:${t.startLine}`});let r=(t.content.length-e.content.length)/e.content.length;return r>.3&&n.push({type:"NewMethod",description:`Code size increased by ${Math.round(r*100)}%`,location:`${t.filePath}:${t.startLine}`}),n}collectAPIChangeEvidence(e,t){let n=[];return e.signature&&t.signature&&e.signature!==t.signature&&n.push({type:"SignatureChanged",description:`Signature changed: ${e.signature} \u2192 ${t.signature}`,location:`${t.filePath}:${t.startLine}`}),e.fullyQualifiedName!==t.fullyQualifiedName&&n.push({type:"SignatureChanged",description:`Fully qualified name changed: ${e.fullyQualifiedName} \u2192 ${t.fullyQualifiedName}`,location:`${t.filePath}:${t.startLine}`}),n}};var F=class{embeddingGenerator;cache=new Map;batchSize;constructor(e,t={}){this.embeddingGenerator=e,this.batchSize=t.batchSize??32;}async generateEmbeddings(e,t){let n=t.filter(i=>!i.embedding);if(n.length!==0)for(let i=0;i<n.length;i+=this.batchSize){let r=n.slice(i,i+this.batchSize);await Promise.all(r.map(async a=>{let o=await this.getOrGenerateEmbedding(a);a.embedding=o,e.units.set(a.id,a);}));}}async getOrGenerateEmbedding(e){let t=this.computeCacheKey(e),n=this.cache.get(t);if(n)return n;let i=await this.embeddingGenerator(e.content);return this.cache.set(t,i),i}computeCacheKey(e){return e.contentHash}clearCache(){this.cache.clear();}getCacheStats(){return {size:this.cache.size,memoryUsage:this.estimateMemoryUsage()}}estimateMemoryUsage(){return this.cache.size*1636}};R();var G=class{branchManager;gitIntegration;conductor;constructor(e,t,n){this.branchManager=e,this.gitIntegration=t,this.conductor=n;}async indexThreeBranches(e,t,n={}){let i=Date.now(),r=0;I.i("MULTIVIDX",`[MultiVersionIndexer] Starting 3-way indexing: ${e} + ${t}`);try{let a=this.gitIntegration.getMergeBase(e,t);if(!a)throw new Error(`No merge base found between ${e} and ${t}`);I.i("MULTIVIDX",`[MultiVersionIndexer] Merge base: ${a.slice(0,8)}`);let o=await this.indexBranch(a,"base",n);this.wasCacheHit(o)&&r++;let c=await this.indexBranch(e,e,n);this.wasCacheHit(c)&&r++;let s=await this.indexBranch(t,t,n);this.wasCacheHit(s)&&r++,await this.gitIntegration.restoreOriginalBranch();let u=o.stats.totalUnits+c.stats.totalUnits+s.stats.totalUnits,m=(o.stats.byFile?.size||0)+(c.stats.byFile?.size||0)+(s.stats.byFile?.size||0),C=Date.now()-i;return I.i("MULTIVIDX",`[MultiVersionIndexer] Completed in ${C}ms`),I.i("MULTIVIDX",`[MultiVersionIndexer] Total units: ${u}, Cache hits: ${r}/3`),{base:o,branchA:c,branchB:s,mergeBase:a,stats:{totalUnits:u,totalFiles:m,indexingTimeMs:C,cacheHits:r}}}catch(a){throw await this.gitIntegration.cleanup(),a}}async indexBranch(e,t,n){if(I.i("MULTIVIDX",`[MultiVersionIndexer] Indexing ${t}...`),!n.fullScan&&!n.reset){let s=await this.loadCachedIndex(e);if(s)return I.i("MULTIVIDX",`[MultiVersionIndexer] Loaded ${t} from cache`),s}let i=Date.now();if(await this.gitIntegration.checkoutBranch(e),!this.conductor)throw new Error("ConductorOrchestrator is required for fresh indexing");let r=a(),a$1=await c$1(r,this.conductor,"dev"),o=await this.runIndexing(a$1,e,n);await this.saveCachedIndex(e,o);let c=Date.now()-i;return I.i("MULTIVIDX",`[MultiVersionIndexer] Indexed ${t} in ${c}ms (${o.stats.totalUnits} units)`),o}async runIndexing(e,t,n){let i=this.gitIntegration.repoPath,r=await e.execute?.({task:"index_codebase",params:{directory:i,incremental:n.incremental??true,fullScan:n.fullScan??false,excludePatterns:n.excludePatterns||[],reset:n.reset??false}}),a={branch:t,indexedAt:new Date,units:new Map,contentHashIndex:new Map,structuralHashIndex:new Map,signatureIndex:new Map,filePathIndex:new Map,stats:{totalUnits:0,byType:new Map,byLanguage:new Map,byFile:new Map}};if(r?.entities)for(let o of r.entities){let c=this.entityToCodeUnit(o);this.addUnitToIndex(a,c);}else await this.populateIndexFromStorage(a);return a}entityToCodeUnit(e){let{ContentNormalizer:t}=(ce(),f(se)),n=new t,i=e.content||"",r=n.computeContentHash(i);return {id:e.id,type:this.mapEntityType(e.type),filePath:e.filePath||"",name:e.name||"",fullyQualifiedName:e.fullyQualifiedName||e.name||"",startLine:e.startLine||1,endLine:e.endLine||1,content:i,contentHash:r,structuralHash:e.structuralHash||r,signature:e.signature,language:e.language||"unknown",parentId:e.parentId,childIds:e.childIds||[],metadata:e.metadata||{}}}mapEntityType(e){let{CodeUnitType:t}=(he(),f(le));return {file:t.File,module:t.Module,class:t.Class,interface:t.Interface,function:t.Function,method:t.Method,property:t.Property}[e?.toLowerCase()]||t.Block}addUnitToIndex(e,t){e.units.set(t.id,t),e.contentHashIndex.has(t.contentHash)||e.contentHashIndex.set(t.contentHash,[]),e.contentHashIndex.get(t.contentHash).push(t.id),e.structuralHashIndex.has(t.structuralHash)||e.structuralHashIndex.set(t.structuralHash,[]),e.structuralHashIndex.get(t.structuralHash).push(t.id),t.signature&&(e.signatureIndex.has(t.signature)||e.signatureIndex.set(t.signature,[]),e.signatureIndex.get(t.signature).push(t.id)),e.filePathIndex.has(t.filePath)||e.filePathIndex.set(t.filePath,[]),e.filePathIndex.get(t.filePath).push(t.id),e.stats.totalUnits++,e.stats.byType.set(t.type,(e.stats.byType.get(t.type)||0)+1),e.stats.byLanguage.set(t.language,(e.stats.byLanguage.get(t.language)||0)+1),e.stats.byFile.set(t.filePath,(e.stats.byFile.get(t.filePath)||0)+1);}async populateIndexFromStorage(e){try{let t=this.conductor.getGraphStorage?.();if(!t){I.w("MULTIVIDX","[MultiVersionIndexer] GraphStorage not available for fallback");return}let n=await t.getAllEntities?.();if(!n||n.length===0){I.w("MULTIVIDX","[MultiVersionIndexer] No entities found in GraphStorage");return}for(let i of n){let r=this.entityToCodeUnit(i);this.addUnitToIndex(e,r);}I.i("MULTIVIDX","storage_loaded",{units:e.stats.totalUnits});}catch(t){I.e("MULTIVIDX","storage_populate_fail",{err:String(t)});}}async loadCachedIndex(e){try{if(!this.branchManager.hasBranchDatabase(e))return null;let t=this.branchManager.getBranchMetadata(e);if(!t)return null;let n=this.gitIntegration.getCommitHash(e);if(t.lastCommitHash!==n)return I.i("MULTIVIDX",`[MultiVersionIndexer] Cache outdated for ${e} (${t.lastCommitHash?.slice(0,8)} vs ${n.slice(0,8)})`),null;let i={branch:e,indexedAt:new Date(t.lastIndexedAt),units:new Map,contentHashIndex:new Map,structuralHashIndex:new Map,signatureIndex:new Map,filePathIndex:new Map,stats:{totalUnits:0,byType:new Map,byLanguage:new Map,byFile:new Map}};return i.stats.totalUnits=t.entityCount,i._fromCache=!0,i}catch(t){return I.e("MULTIVIDX","cache_load_fail",{branch:e,err:String(t)}),null}}async saveCachedIndex(e,t){try{let n=this.gitIntegration.repoPath,i=this.gitIntegration.getCommitHash(e),r=this.branchManager.getRepositoryHash(n);this.branchManager.updateBranchMetadata({branch:e,repositoryPath:n,repositoryHash:r,lastCommitHash:i,lastIndexedAt:Date.now(),fileCount:t.stats.byFile?.size||0,entityCount:t.stats.totalUnits,relationshipCount:0,indexVersion:"1.0.0",accessedAt:Date.now()}),I.i("MULTIVIDX","cache_saved",{branch:e,commit:i.slice(0,8)});}catch(n){I.e("MULTIVIDX","cache_save_fail",{branch:e,err:String(n)});}}wasCacheHit(e){return e._fromCache===true}};var D=class{bulkMatch(e,t){let n=new Map;for(let[i,r]of t.units){let a=this.findMatch(r,e);a&&n.set(i,a);}return n}findMatch(e,t){let n=this.tryExactMatch(e,t);if(n)return {baseUnitId:n.id,baseUnit:n,level:"exact_content",confidence:1};let i=this.tryStructuralMatch(e,t);if(i)return {baseUnitId:i.id,baseUnit:i,level:"structural",confidence:.95};if(e.signature){let a=this.trySignatureMatch(e,t);if(a)return {baseUnitId:a.id,baseUnit:a,level:"signature",confidence:.85}}let r=this.tryIdMatch(e,t);if(r)return {baseUnitId:r.id,baseUnit:r,level:"id",confidence:.7}}tryExactMatch(e,t){let n=t.contentHashIndex.get(e.contentHash);if(!n||n.length===0)return;if(n.length===1){let a=n[0];return a?t.units.get(a):void 0}let i=n.find(a=>t.units.get(a)?.filePath===e.filePath);if(i)return t.units.get(i);let r=n[0];return r?t.units.get(r):void 0}tryStructuralMatch(e,t){let n=t.structuralHashIndex.get(e.structuralHash);if(!n||n.length===0)return;let i=n.filter(o=>t.units.get(o)?.type===e.type);if(i.length===0)return;let r=i.find(o=>{let c=t.units.get(o);return c?.filePath===e.filePath&&c?.name===e.name});if(r)return t.units.get(r);let a=i[0];return a?t.units.get(a):void 0}trySignatureMatch(e,t){if(!e.signature)return;let n=t.signatureIndex.get(e.signature);if(!n||n.length===0)return;let i=n.filter(a=>t.units.get(a)?.type===e.type);if(i.length===0)return;let r=i[0];if(r)return t.units.get(r)}tryIdMatch(e,t){let n=t.units.get(e.id);if(n&&n.fullyQualifiedName===e.fullyQualifiedName)return n}computeStatistics(e,t){let n=new Map;for(let a of e.values())n.set(a.level,(n.get(a.level)||0)+1);let i=e.size,r=t>0?i/t:0;return {totalUnits:t,totalMatched:i,coverage:r,exactContentMatches:n.get("exact_content")||0,structuralMatches:n.get("structural")||0,signatureMatches:n.get("signature")||0,idMatches:n.get("id")||0}}};var H=class{findMatch(e,t,n=.7){if(!e.embedding)throw new Error(`Target unit ${e.id} missing embedding. Use LazyEmbeddingCache to generate.`);let i=this.findCandidates(e,t);if(i.length===0)return;let r=i.map(o=>{let c=this.computeVectorSimilarity(e.embedding,o.embedding),s=this.computeStructuralSimilarity(e,o),u=c*.7+s*.3;return {candidate:o,vectorSimilarity:c,structuralSimilarity:s,combinedScore:u}});r.sort((o,c)=>c.combinedScore-o.combinedScore);let a=r[0];if(!(!a||a.combinedScore<n))return {baseUnitId:a.candidate.id,baseUnit:a.candidate,vectorSimilarity:a.vectorSimilarity,structuralSimilarity:a.structuralSimilarity,combinedScore:a.combinedScore,confidence:this.scoreToConfidence(a.combinedScore)}}bulkMatch(e,t,n=.7){let i=new Map;for(let r of e){if(!r.embedding)continue;let a=this.findMatch(r,t,n);a&&i.set(r.id,a);}return i}findCandidates(e,t){let n=[];for(let[,i]of t.units)i.type===e.type&&i.embedding&&n.push(i);return n}computeVectorSimilarity(e,t){return a$1(e,t)}computeStructuralSimilarity(e,t){return e.structuralHash===t.structuralHash?1:0}scoreToConfidence(e){return e>=.9?e:e>=.8?.75+(e-.8)*1.5:.6+(e-.7)*1.5}computeStatistics(e,t){let n=e.size,i=t>0?n/t:0,r=0,a=0,o=0;for(let s of e.values())r+=s.vectorSimilarity,a+=s.structuralSimilarity,o+=s.combinedScore;let c=n||1;return {totalUnits:t,totalMatched:n,coverage:i,avgVectorSimilarity:r/c,avgStructuralSimilarity:a/c,avgCombinedScore:o/c}}};var V=class{branchManager;gitIntegration;conductor;config;multiVersionIndexer;fastPathMatcher;semanticMatcher;intentClassifier;conflictDetector;constructor(e,t,n,i={}){this.branchManager=e,this.gitIntegration=t,this.conductor=n,this.config={fastPathEnabled:true,semanticMatchingEnabled:true,semanticThreshold:.7,classifyIntents:true,detectConflicts:true,autoResolveConflicts:false,...i},this.multiVersionIndexer=new G(this.branchManager,this.gitIntegration,this.conductor),this.fastPathMatcher=new D,this.semanticMatcher=new H,this.intentClassifier=new T,this.conflictDetector=new $;}async performMerge(e,t){I.i("3WAYMERGE",`[ThreeWayMerger] Starting 3-way merge: ${e} + ${t}`);let n=Date.now();I.i("3WAYMERGE","[ThreeWayMerger] Phase 1: Indexing 3 branches...");let i=await this.multiVersionIndexer.indexThreeBranches(e,t),{base:r,branchA:a,branchB:o,mergeBase:c}=i;I.i("3WAYMERGE",`[ThreeWayMerger] Indexed: base=${r.stats.totalUnits}, A=${a.stats.totalUnits}, B=${o.stats.totalUnits}`),I.i("3WAYMERGE","[ThreeWayMerger] Phase 1.5: Detecting file changes from git...");let s=await this.gitIntegration.getChangedFilesBetween(c,e),u=await this.gitIntegration.getChangedFilesBetween(c,t),m=s.filter(g=>g.status==="renamed"),C=u.filter(g=>g.status==="renamed");I.i("3WAYMERGE",`[ThreeWayMerger] Git changes: A=${s.length} (${m.length} renamed), B=${u.length} (${C.length} renamed)`),I.i("3WAYMERGE","[ThreeWayMerger] Phase 2: Fast Path matching...");let{matchedUnits:v,unmatchedA:w,unmatchedB:S}=await this.fastPathMatch(r,a,o);I.i("3WAYMERGE",`[ThreeWayMerger] Fast Path: ${v.length} matched, ${w.length} unmapped in A, ${S.length} unmapped in B`),I.i("3WAYMERGE","[ThreeWayMerger] Phase 2.5: Detecting added/deleted units...");let{addedInA:l,addedInB:f,deletedUnits:b,renamedUnits:p}=this.detectAddedDeletedRenamed(r,a,o,w,S,m,C);I.i("3WAYMERGE",`[ThreeWayMerger] Added: A=${l.length}, B=${f.length}, Deleted=${b.length}, Renamed=${p.length}`);let I$1=new Set([...l.map(g=>g.id),...f.map(g=>g.id)]),B=new Set(p.map(g=>g.unit.id)),M=w.filter(g=>!I$1.has(g.id)&&!B.has(g.id)),P=S.filter(g=>!I$1.has(g.id)&&!B.has(g.id)),L=[];this.config.semanticMatchingEnabled&&(M.length>0||P.length>0)&&(I.i("3WAYMERGE","[ThreeWayMerger] Phase 3: Semantic matching..."),L=await this.semanticMatch(r,M,P),I.i("3WAYMERGE",`[ThreeWayMerger] Semantic: ${L.length} matched`));let U=[...v,...L],k=new Map;this.config.classifyIntents&&(I.i("3WAYMERGE","[ThreeWayMerger] Phase 4: Classifying intents..."),k=this.classifyIntents(U),I.i("3WAYMERGE",`[ThreeWayMerger] Classified intents for ${k.size} unit pairs`));let x=[];if(this.config.detectConflicts){I.i("3WAYMERGE","[ThreeWayMerger] Phase 5: Detecting conflicts..."),x=this.detectConflicts(U,k);let g=this.detectDeleteModifyConflicts(b);x=[...x,...g],I.i("3WAYMERGE",`[ThreeWayMerger] Detected ${x.length} conflicts`);}let W=this.generateMergeActions(U,x,l,f,b,p),A={totalUnitsInBase:r.stats.totalUnits,totalUnitsInA:a.stats.totalUnits,totalUnitsInB:o.stats.totalUnits,matchedCount:U.length,conflictCount:x.length,autoMergedCount:W.filter(g=>g.type==="auto-merge").length,manualReviewCount:W.filter(g=>g.type==="manual-review").length,addedFromACount:l.length,addedFromBCount:f.length,deletedCount:b.length,renamedCount:p.length,mergeTimeMs:Date.now()-n},ge={branchA:e,branchB:t,mergeBase:c,baseIndex:r,branchAIndex:a,branchBIndex:o,matchedUnits:U,addedInA:l,addedInB:f,deletedUnits:b,renamedUnits:p,conflicts:x,mergeActions:W,stats:A};return I.i("3WAYMERGE",`[ThreeWayMerger] Merge completed in ${A.mergeTimeMs}ms: ${A.autoMergedCount} auto-merged, ${A.conflictCount} conflicts, ${A.addedFromACount+A.addedFromBCount} added, ${A.deletedCount} deleted, ${A.renamedCount} renamed`),ge}async fastPathMatch(e,t,n){let i=[],r=[],a=[],o=Array.from(t.units.values()),c=Array.from(n.units.values());for(let u of o){let m=this.fastPathMatcher.findMatch(u,n);if(m){let C=e.units.get(u.id)||null;i.push({baseUnit:C,branchAUnit:u,branchBUnit:m.baseUnit});}else r.push(u);}let s=new Set(i.map(u=>u.branchBUnit.id));for(let u of c)s.has(u.id)||a.push(u);return {matchedUnits:i,unmatchedA:r,unmatchedB:a}}async semanticMatch(e,t,n){if(this.config.embeddingGenerator){let a=new F(this.config.embeddingGenerator);await a.generateEmbeddings(e,t),await a.generateEmbeddings(e,n);}let i=[],r={...e,units:new Map(n.map(a=>[a.id,a]))};for(let a of t){let o=this.semanticMatcher.findMatch(a,r,this.config.semanticThreshold);if(o){let c=e.units.get(a.id)||null;i.push({baseUnit:c,branchAUnit:a,branchBUnit:o.baseUnit});}}return i}classifyIntents(e){let t=new Map;for(let n of e){let i=this.intentClassifier.classifyIntent(n.baseUnit,n.branchAUnit),r=this.intentClassifier.classifyIntent(n.baseUnit,n.branchBUnit);t.set(n.branchAUnit.id,{branchAIntent:i,branchBIntent:r});}return t}detectConflicts(e,t){let n=e.map(i=>{let r=t.get(i.branchAUnit.id);return {...i,branchAIntent:r?.branchAIntent,branchBIntent:r?.branchBIntent}});return this.conflictDetector.detectConflicts(n)}detectAddedDeletedRenamed(e,t,n,i,r,a,o){let c=[],s=[],u=[],m=[],C=new Map(a.map(l=>[l.oldPath,l.path])),v=new Map(o.map(l=>[l.oldPath,l.path])),w=new Set(a.map(l=>l.path)),S=new Set(o.map(l=>l.path));for(let l of i)if(!(e.units.has(l.id)||l.filePath&&this.findUnitByPath(e,l.filePath)))if(l.filePath&&w.has(l.filePath)){for(let[p,I]of C)if(I===l.filePath&&p){m.push({oldPath:p,newPath:I,unit:l,branch:"branchA"});break}}else c.push(l);for(let l of r)if(!(e.units.has(l.id)||l.filePath&&this.findUnitByPath(e,l.filePath)))if(l.filePath&&S.has(l.filePath)){for(let[p,I]of v)if(I===l.filePath&&p){m.push({oldPath:p,newPath:I,unit:l,branch:"branchB"});break}}else s.push(l);for(let[l,f]of e.units){let b=t.units.has(l)||this.findUnitByPath(t,f.filePath),p=n.units.has(l)||this.findUnitByPath(n,f.filePath),I=C.has(f.filePath),B=v.has(f.filePath);if(!b&&!I&&p){let M=n.units.get(l)||this.findUnitByPath(n,f.filePath),P=M&&M.contentHash!==f.contentHash;u.push({baseUnit:f,deletedIn:"branchA",modifiedIn:P?"branchB":void 0});}else if(!p&&!B&&b){let M=t.units.get(l)||this.findUnitByPath(t,f.filePath),P=M&&M.contentHash!==f.contentHash;u.push({baseUnit:f,deletedIn:"branchB",modifiedIn:P?"branchA":void 0});}}return {addedInA:c,addedInB:s,deletedUnits:u,renamedUnits:m}}findUnitByPath(e,t){if(!t)return;let n=e.filePathIndex.get(t);if(n&&n.length>0&&n[0])return e.units.get(n[0])}detectDeleteModifyConflicts(e){let t=[];for(let n of e)n.modifiedIn&&t.push({id:`conflict-delete-modify-${n.baseUnit.id}`,type:"DeleteModify",severity:"High",description:`File deleted in ${n.deletedIn} but modified in ${n.modifiedIn}`,baseUnit:n.baseUnit,branchAUnit:n.baseUnit,branchBUnit:n.baseUnit,conflictingRegions:[],autoResolvable:false});return t}generateMergeActions(e,t,n,i,r,a){let o=[],c=new Set(t.map(s=>s.branchAUnit.id));for(let s of e){if(c.has(s.branchAUnit.id)){let u=t.find(m=>m.branchAUnit.id===s.branchAUnit.id);o.push({type:"manual-review",unitId:s.branchAUnit.id,description:`Conflict detected: ${u?.description}`,conflict:u});continue}if(s.branchAUnit.contentHash===s.branchBUnit.contentHash){o.push({type:"auto-merge",unitId:s.branchAUnit.id,description:"Identical changes in both branches",mergedUnit:s.branchAUnit});continue}o.push({type:"manual-review",unitId:s.branchAUnit.id,description:"Different changes in both branches"});}for(let s of n)o.push({type:"add-from-branchA",unitId:s.id,description:`New file added in branchA: ${s.filePath}`,mergedUnit:s,sourceBranch:"branchA"});for(let s of i)o.push({type:"add-from-branchB",unitId:s.id,description:`New file added in branchB: ${s.filePath}`,mergedUnit:s,sourceBranch:"branchB"});for(let s of r)s.modifiedIn?o.push({type:"conflict-delete-modify",unitId:s.baseUnit.id,description:`Conflict: deleted in ${s.deletedIn}, modified in ${s.modifiedIn}`}):o.push({type:s.deletedIn==="branchA"?"delete-from-branchA":"delete-from-branchB",unitId:s.baseUnit.id,description:`File deleted in ${s.deletedIn}: ${s.baseUnit.filePath}`});for(let s of a)o.push({type:"rename",unitId:s.unit.id,description:`File renamed in ${s.branch}: ${s.oldPath} -> ${s.newPath}`,mergedUnit:s.unit,renameInfo:{oldPath:s.oldPath,newPath:s.newPath,sourceBranch:s.branch}});return o}};R();var N=class{config;originalBranch=null;constructor(e){if(this.config={allowDetachedHead:false,restoreOnError:true,...e},!this.isGitRepository())throw new Error(`Not a git repository: ${this.config.repoPath}`)}get repoPath(){return this.config.repoPath}isGitRepository(){let e=join(this.config.repoPath,".git");return existsSync(e)}getCurrentBranch(){try{let e=execSync("git symbolic-ref --short HEAD",{cwd:this.config.repoPath,encoding:"utf-8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).trim(),t=this.getCommitHash("HEAD");return {name:e,commitHash:t,shortHash:t.slice(0,8),isDetached:!1}}catch{let e=this.getCommitHash("HEAD");return {name:`detached-${e.slice(0,8)}`,commitHash:e,shortHash:e.slice(0,8),isDetached:true}}}getCommitHash(e){try{return execSync(`git rev-parse ${e}`,{cwd:this.config.repoPath,encoding:"utf-8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).trim()}catch(t){throw new Error(`Failed to get commit hash for ${e}`,{cause:t})}}branchExists(e){try{return execSync(`git rev-parse --verify ${e}`,{cwd:this.config.repoPath,stdio:["pipe","pipe","ignore"],windowsHide:!0}),!0}catch{return false}}async checkoutBranch(e){if(this.originalBranch||(this.originalBranch=this.getCurrentBranch().name),!this.branchExists(e))throw new Error(`Branch does not exist: ${e}`);if(this.hasUncommittedChanges())throw new Error("Cannot checkout branch: uncommitted changes detected. Please commit or stash changes first.");try{execSync(`git checkout ${e}`,{cwd:this.config.repoPath,stdio:["pipe","pipe","pipe"],windowsHide:!0}),I.i("GITINTEGR",`[GitIntegration] Checked out branch: ${e}`);}catch(t){throw this.config.restoreOnError&&this.originalBranch&&await this.restoreOriginalBranch(),new Error(`Failed to checkout branch ${e}: ${t}`)}}async restoreOriginalBranch(){if(!this.originalBranch){I.w("GITINTEGR","[GitIntegration] No original branch to restore");return}try{execSync(`git checkout ${this.originalBranch}`,{cwd:this.config.repoPath,stdio:["pipe","pipe","pipe"],windowsHide:!0}),I.i("GITINTEGR",`[GitIntegration] Restored original branch: ${this.originalBranch}`),this.originalBranch=null;}catch(e){throw I.i("GITINTEGR",`[GitIntegration] Failed to restore branch: ${e}`),e}}hasUncommittedChanges(){try{return execSync("git status --porcelain",{cwd:this.config.repoPath,encoding:"utf-8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).trim().length>0}catch{return false}}async getChangedFilesBetween(e,t){try{let n=execSync(`git diff --name-status ${e}...${t}`,{cwd:this.config.repoPath,encoding:"utf-8",stdio:["pipe","pipe","ignore"],windowsHide:!0}),i=[],r=n.trim().split(`
8
+ `);for(let a of r){if(!a)continue;let o=a.split(" "),c=o[0];if(!c)continue;let s;switch(c[0]){case "A":s={path:o[1],status:"added"};break;case "M":s={path:o[1],status:"modified"};break;case "D":s={path:o[1],status:"deleted"};break;case "R":s={path:o[2],status:"renamed",oldPath:o[1]};break;default:s={path:o[1],status:"modified"};}i.push(s);}return i}catch(n){return I.i("GITINTEGR",`[GitIntegration] Failed to get changed files: ${n}`),[]}}async getDiffStats(e,t){try{let n=await this.getChangedFilesBetween(e,t),r=execSync(`git diff --shortstat ${e}...${t}`,{cwd:this.config.repoPath,encoding:"utf-8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).match(/(\d+) files? changed(?:, (\d+) insertions?\(\+\))?(?:, (\d+) deletions?\(-\))?/),a=r?.[1]?Number.parseInt(r[1],10):0,o=r?.[2]?Number.parseInt(r[2],10):0,c=r?.[3]?Number.parseInt(r[3],10):0;return {files:n,filesChanged:a,insertions:o,deletions:c}}catch(n){return I.i("GITINTEGR",`[GitIntegration] Failed to get diff stats: ${n}`),{files:[],filesChanged:0,insertions:0,deletions:0}}}getMergeBase(e,t){try{return execSync(`git merge-base ${e} ${t}`,{cwd:this.config.repoPath,encoding:"utf-8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).trim()}catch(n){return I.i("GITINTEGR",`[GitIntegration] Failed to get merge base: ${n}`),null}}getFileContent(e,t){try{return execSync(`git show ${t}:${e}`,{cwd:this.config.repoPath,encoding:"utf-8",stdio:["pipe","pipe","ignore"],windowsHide:!0})}catch{return null}}async getChangedFiles(e,t){try{return execSync(`git diff --name-only ${e}...${t}`,{cwd:this.config.repoPath,encoding:"utf-8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).trim().split(`
9
+ `).filter(i=>i.length>0)}catch(n){return I.i("GITINTEGR",`[GitIntegration] Failed to get changed files: ${n}`),[]}}getAllBranches(){try{return execSync("git branch --format='%(refname:short)'",{cwd:this.config.repoPath,encoding:"utf-8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).trim().split(`
10
+ `).map(t=>t.trim()).filter(t=>t.length>0)}catch{return []}}async cleanup(){this.originalBranch&&await this.restoreOriginalBranch();}};var ue=class extends b$2{config;gitIntegration=null;threeWayMerger=null;aiResolver=null;branchManager=null;mergeMetrics={mergesPerformed:0,conflictsDetected:0,conflictsAutoResolved:0,totalMergeTimeMs:0,lastMergeAt:0};constructor(e){super("merge",{maxConcurrency:e.maxConcurrency??1,memoryLimit:512,priority:5}),this.config={fastPathEnabled:true,semanticMatchingEnabled:true,semanticThreshold:.7,autoResolveConflicts:false,maxConcurrency:1,...e};}canProcessTask(e){return e.type==="merge"||e.type==="merge:analyze"||e.type==="merge:perform"||e.type==="merge:suggestions"}async processTask(e){I.d("MERGEAGENT","proc_task",{id:e.id,type:e.type});let t=e.payload;switch(e.type){case "merge":case "merge:perform":return await this.performSemanticMerge({branchA:t.branchA,branchB:t.branchB,dryRun:t.dryRun,autoResolve:t.autoResolve,includeAISuggestions:t.includeAISuggestions});case "merge:analyze":return await this.analyzeConflicts(t.branchA,t.branchB);case "merge:suggestions":return await this.getSuggestions(t.conflict);default:throw new Error(`Unknown task type: ${e.type}`)}}async handleMessage(e){I.d("MERGEAGENT","recv_msg",{from:e.from,type:e.type});}async onInitialize(){I.i("MERGEAGENT","init_start"),this.gitIntegration=this.config.gitIntegration??new N({repoPath:this.config.repoPath,allowDetachedHead:true,restoreOnError:true}),this.branchManager=this.config.branchManager??null;let e={fastPathEnabled:this.config.fastPathEnabled,semanticMatchingEnabled:this.config.semanticMatchingEnabled,semanticThreshold:this.config.semanticThreshold,autoResolveConflicts:this.config.autoResolveConflicts};this.branchManager&&this.gitIntegration&&(this.threeWayMerger=new V(this.branchManager,this.gitIntegration,null,e)),this.aiResolver=null,I.i("MERGEAGENT","init_done");}async onShutdown(){I.i("MERGEAGENT","shutdown_start"),this.gitIntegration&&await this.gitIntegration.cleanup(),this.threeWayMerger=null,this.gitIntegration=null,this.aiResolver=null,I.i("MERGEAGENT","shutdown_done");}setDependencies(e,t){this.branchManager=e,t&&(this.gitIntegration=t);}setAIResolver(e){this.aiResolver=new E(e);}async performSemanticMerge(e){let t=Date.now();if(!this.threeWayMerger)return {success:false,error:"MergeAgent not properly initialized - missing ThreeWayMerger",stats:this.createEmptyStats(0)};try{I.i("MERGEAGENT","merge_start",{from:e.branchA,to:e.branchB});let n=await this.threeWayMerger.performMerge(e.branchA,e.branchB);e.includeAISuggestions&&n.conflicts.length>0&&this.aiResolver&&await this.generateAISuggestions(n.conflicts);let i=0;e.autoResolve&&(i=await this.autoResolveConflicts(n));let r=[];e.dryRun||(r=await this.applyMergeActions(n));let a=Date.now()-t;return this.updateMergeMetrics(n,i,a),{success:!0,mergeResult:n,appliedActions:r,stats:{totalUnitsAnalyzed:n.stats.totalUnitsInA+n.stats.totalUnitsInB,matchedUnits:n.stats.matchedCount,conflictsDetected:n.stats.conflictCount,autoResolved:i,manualReviewRequired:n.stats.manualReviewCount-i,mergeTimeMs:a}}}catch(n){let i=n instanceof Error?n.message:String(n);return I.e("MERGEAGENT","merge_fail",{err:i}),{success:false,error:i,stats:this.createEmptyStats(Date.now()-t)}}}async analyzeConflicts(e,t){let n=await this.performSemanticMerge({branchA:e,branchB:t,dryRun:true,autoResolve:false});if(!n.mergeResult)return {conflicts:[],stats:{totalConflicts:0,bySeverity:{},byType:{}}};let i=n.mergeResult.conflicts,r={},a={};for(let o of i)r[o.severity]=(r[o.severity]||0)+1,a[o.type]=(a[o.type]||0)+1;return {conflicts:i,stats:{totalConflicts:i.length,bySeverity:r,byType:a}}}async getSuggestions(e){if(!this.aiResolver)return ["AI resolver not available - configure embedding generator first"];try{let t=await this.aiResolver.analyzeConflict(e),n=this.aiResolver.createResolution(t);return [`Strategy: ${n.strategy}`,`Confidence: ${(n.confidence*100).toFixed(1)}%`,`Explanation: ${n.explanation}`,...n.mergedCode?[`Suggested code:
11
+ ${n.mergedCode}`]:[]]}catch(t){return I.e("MERGEAGENT","ai_suggest_fail",{err:String(t)}),[]}}getMergeMetrics(){return {...this.mergeMetrics}}async generateAISuggestions(e){if(this.aiResolver){I.d("MERGEAGENT","gen_ai_suggest",{cnt:e.length});for(let t of e)try{let n=await this.aiResolver.analyzeConflict(t),i=this.aiResolver.createResolution(n);t.aiSuggestions=[i.explanation],t.aiConfidence=i.confidence;}catch(n){I.w("MERGEAGENT","ai_conflict_fail",{err:String(n)});}}}async autoResolveConflicts(e){let t=0;for(let n of e.mergeActions)if(n.type==="manual-review"&&n.conflict&&this.aiResolver)try{let i=await this.aiResolver.analyzeConflict(n.conflict);i.confidence>=.9&&i.mergedCode&&(n.type="auto-merge",n.description=`Auto-resolved: ${i.explanation}`,t++);}catch{}return t}async applyMergeActions(e){let t=[];for(let n of e.mergeActions)n.type==="auto-merge"&&n.mergedUnit&&t.push(n);return I.i("MERGEAGENT","actions_applied",{cnt:t.length}),t}updateMergeMetrics(e,t,n){this.mergeMetrics.mergesPerformed++,this.mergeMetrics.conflictsDetected+=e.conflicts.length,this.mergeMetrics.conflictsAutoResolved+=t,this.mergeMetrics.totalMergeTimeMs+=n,this.mergeMetrics.lastMergeAt=Date.now();}createEmptyStats(e){return {totalUnitsAnalyzed:0,matchedUnits:0,conflictsDetected:0,autoResolved:0,manualReviewRequired:0,mergeTimeMs:e}}};export{ue as MergeAgent};
@@ -0,0 +1,277 @@
1
+ import { BaseToolHandler } from './chunk-WLKASYMP.js';
2
+ import './chunk-KMXE2SJJ.js';
3
+ import { getGlobalContainer, getOrCreateAgent } from './chunk-KBW6LRQP.js';
4
+ import './chunk-ZD54CMKT.js';
5
+ import './chunk-HEMJHRHZ.js';
6
+ import { toError } from './chunk-5WKPA33T.js';
7
+ import './chunk-GMVGCSNU.js';
8
+ import './chunk-VCCBEJQ5.js';
9
+ import './chunk-NAQKA54E.js';
10
+ import { z } from 'zod';
11
+
12
+ var SemanticMergeSchema = z.object({
13
+ sourceBranch: z.string().describe("Source branch name (where changes come from)"),
14
+ targetBranch: z.string().optional().describe("Target branch name (where to merge). Defaults to current branch."),
15
+ dryRun: z.boolean().optional().default(true).describe("Preview only, don't apply changes"),
16
+ autoResolve: z.boolean().optional().default(false).describe("Auto-resolve compatible conflicts"),
17
+ includeAISuggestions: z.boolean().optional().default(true).describe("Generate AI suggestions for conflicts")
18
+ });
19
+ var SemanticMergeToolHandler = class extends BaseToolHandler {
20
+ parseArgs(args) {
21
+ return SemanticMergeSchema.parse(args);
22
+ }
23
+ async execute(args) {
24
+ try {
25
+ const container = getGlobalContainer();
26
+ const conductor = this.context.getConductor();
27
+ const mergeAgent = await getOrCreateAgent(container, conductor, "merge" /* MERGE */);
28
+ const targetBranch = args.targetBranch || await this.getCurrentBranch();
29
+ const result = await mergeAgent.performSemanticMerge({
30
+ branchA: targetBranch,
31
+ branchB: args.sourceBranch,
32
+ dryRun: args.dryRun,
33
+ autoResolve: args.autoResolve,
34
+ includeAISuggestions: args.includeAISuggestions
35
+ });
36
+ return {
37
+ content: [
38
+ {
39
+ type: "text",
40
+ text: JSON.stringify(
41
+ {
42
+ success: result.success,
43
+ summary: {
44
+ sourceBranch: args.sourceBranch,
45
+ targetBranch,
46
+ dryRun: args.dryRun,
47
+ totalUnitsAnalyzed: result.stats.totalUnitsAnalyzed,
48
+ matchedUnits: result.stats.matchedUnits,
49
+ conflictsDetected: result.stats.conflictsDetected,
50
+ autoResolved: result.stats.autoResolved,
51
+ manualReviewRequired: result.stats.manualReviewRequired,
52
+ mergeTimeMs: result.stats.mergeTimeMs
53
+ },
54
+ conflicts: result.mergeResult?.conflicts.map(
55
+ (c) => ({
56
+ id: c.id,
57
+ type: c.type,
58
+ severity: c.severity,
59
+ description: c.description,
60
+ branchAUnit: {
61
+ name: c.branchAUnit.name,
62
+ filePath: c.branchAUnit.filePath
63
+ },
64
+ branchBUnit: {
65
+ name: c.branchBUnit.name,
66
+ filePath: c.branchBUnit.filePath
67
+ },
68
+ aiSuggestions: c.aiSuggestions
69
+ })
70
+ ),
71
+ actions: result.mergeResult?.mergeActions.slice(0, 20).map((a) => ({
72
+ type: a.type,
73
+ unitId: a.unitId,
74
+ description: a.description
75
+ })),
76
+ error: result.error
77
+ },
78
+ null,
79
+ 2
80
+ )
81
+ }
82
+ ]
83
+ };
84
+ } catch (error) {
85
+ const err = toError(error);
86
+ return {
87
+ content: [{ type: "text", text: JSON.stringify({ error: err.message }) }]
88
+ };
89
+ }
90
+ }
91
+ async getCurrentBranch() {
92
+ const { execSync } = await import('child_process');
93
+ try {
94
+ return execSync("git symbolic-ref --short HEAD", {
95
+ encoding: "utf-8",
96
+ stdio: ["pipe", "pipe", "ignore"],
97
+ windowsHide: true
98
+ }).trim();
99
+ } catch {
100
+ return "HEAD";
101
+ }
102
+ }
103
+ };
104
+ var AnalyzeMergeConflictsSchema = z.object({
105
+ branchA: z.string().describe("First branch name"),
106
+ branchB: z.string().describe("Second branch name")
107
+ });
108
+ var AnalyzeMergeConflictsToolHandler = class extends BaseToolHandler {
109
+ parseArgs(args) {
110
+ return AnalyzeMergeConflictsSchema.parse(args);
111
+ }
112
+ async execute(args) {
113
+ try {
114
+ const container = getGlobalContainer();
115
+ const conductor = this.context.getConductor();
116
+ const mergeAgent = await getOrCreateAgent(container, conductor, "merge" /* MERGE */);
117
+ const result = await mergeAgent.analyzeConflicts(args.branchA, args.branchB);
118
+ return {
119
+ content: [
120
+ {
121
+ type: "text",
122
+ text: JSON.stringify(
123
+ {
124
+ branchA: args.branchA,
125
+ branchB: args.branchB,
126
+ totalConflicts: result.stats.totalConflicts,
127
+ bySeverity: result.stats.bySeverity,
128
+ byType: result.stats.byType,
129
+ conflicts: result.conflicts.map((c) => ({
130
+ id: c.id,
131
+ type: c.type,
132
+ severity: c.severity,
133
+ description: c.description,
134
+ branchAUnit: {
135
+ name: c.branchAUnit.name,
136
+ type: c.branchAUnit.type,
137
+ filePath: c.branchAUnit.filePath,
138
+ startLine: c.branchAUnit.startLine
139
+ },
140
+ branchBUnit: {
141
+ name: c.branchBUnit.name,
142
+ type: c.branchBUnit.type,
143
+ filePath: c.branchBUnit.filePath,
144
+ startLine: c.branchBUnit.startLine
145
+ }
146
+ }))
147
+ },
148
+ null,
149
+ 2
150
+ )
151
+ }
152
+ ]
153
+ };
154
+ } catch (error) {
155
+ const err = toError(error);
156
+ return {
157
+ content: [{ type: "text", text: JSON.stringify({ error: err.message }) }]
158
+ };
159
+ }
160
+ }
161
+ };
162
+ var GetMergeSuggestionsSchema = z.object({
163
+ conflictId: z.string().describe("ID of the conflict to get suggestions for"),
164
+ branchA: z.string().describe("First branch name"),
165
+ branchB: z.string().describe("Second branch name")
166
+ });
167
+ var GetMergeSuggestionsToolHandler = class extends BaseToolHandler {
168
+ parseArgs(args) {
169
+ return GetMergeSuggestionsSchema.parse(args);
170
+ }
171
+ async execute(args) {
172
+ try {
173
+ const container = getGlobalContainer();
174
+ const conductor = this.context.getConductor();
175
+ const mergeAgent = await getOrCreateAgent(container, conductor, "merge" /* MERGE */);
176
+ const analysis = await mergeAgent.analyzeConflicts(args.branchA, args.branchB);
177
+ const conflict = analysis.conflicts.find((c) => c.id === args.conflictId);
178
+ if (!conflict) {
179
+ return {
180
+ content: [
181
+ {
182
+ type: "text",
183
+ text: JSON.stringify({
184
+ error: `Conflict ${args.conflictId} not found`,
185
+ availableConflicts: analysis.conflicts.map((c) => c.id)
186
+ })
187
+ }
188
+ ]
189
+ };
190
+ }
191
+ const suggestions = await mergeAgent.getSuggestions(conflict);
192
+ return {
193
+ content: [
194
+ {
195
+ type: "text",
196
+ text: JSON.stringify(
197
+ {
198
+ conflictId: args.conflictId,
199
+ conflict: {
200
+ type: conflict.type,
201
+ severity: conflict.severity,
202
+ description: conflict.description
203
+ },
204
+ suggestions,
205
+ suggestionsCount: suggestions.length
206
+ },
207
+ null,
208
+ 2
209
+ )
210
+ }
211
+ ]
212
+ };
213
+ } catch (error) {
214
+ const err = toError(error);
215
+ return {
216
+ content: [{ type: "text", text: JSON.stringify({ error: err.message }) }]
217
+ };
218
+ }
219
+ }
220
+ };
221
+ var GetSemanticMergeInfoSchema = z.object({});
222
+ var GetSemanticMergeInfoToolHandler = class extends BaseToolHandler {
223
+ parseArgs(args) {
224
+ return GetSemanticMergeInfoSchema.parse(args);
225
+ }
226
+ async execute(_args) {
227
+ return {
228
+ content: [
229
+ {
230
+ type: "text",
231
+ text: JSON.stringify(
232
+ {
233
+ name: "Semantic Merge",
234
+ version: "1.0.0",
235
+ description: "AI-powered semantic merge for Git branches",
236
+ capabilities: [
237
+ "Fast Path matching (90%+ coverage via hashes)",
238
+ "Semantic matching for moved/refactored code",
239
+ "Intent classification (BugFix, Refactoring, FeatureAddition, APIChange)",
240
+ "Conflict detection and severity classification",
241
+ "AI-assisted conflict resolution suggestions"
242
+ ],
243
+ tools: [
244
+ {
245
+ name: "semantic_merge",
246
+ description: "Perform semantic merge of branches using AI",
247
+ parameters: ["sourceBranch", "targetBranch?", "dryRun?", "autoResolve?", "includeAISuggestions?"]
248
+ },
249
+ {
250
+ name: "analyze_merge_conflicts",
251
+ description: "Analyze merge conflicts between two branches",
252
+ parameters: ["branchA", "branchB"]
253
+ },
254
+ {
255
+ name: "get_merge_suggestions",
256
+ description: "Get AI suggestions for resolving a specific conflict",
257
+ parameters: ["conflictId", "branchA", "branchB"]
258
+ }
259
+ ],
260
+ metrics: {
261
+ fastPathCoverageTarget: ">90%",
262
+ semanticMatchingAccuracyTarget: ">80%",
263
+ autoMergeRateTarget: ">60%"
264
+ }
265
+ },
266
+ null,
267
+ 2
268
+ )
269
+ }
270
+ ]
271
+ };
272
+ }
273
+ };
274
+
275
+ export { AnalyzeMergeConflictsToolHandler, GetMergeSuggestionsToolHandler, GetSemanticMergeInfoToolHandler, SemanticMergeToolHandler };
276
+ //# sourceMappingURL=merge-tool-handlers-BDSVNQVZ.js.map
277
+ //# sourceMappingURL=merge-tool-handlers-BDSVNQVZ.js.map
@@ -0,0 +1 @@
1
+ import {d as d$1}from'./chunk-RPKK6MZA.js';import'./chunk-QBFXI33X.js';import {a,c}from'./chunk-V6JAQNM3.js';import'./chunk-GVQNDMAK.js';import'./chunk-PZF7YC35.js';import {a as a$1}from'./chunk-F3VMUQ7O.js';import'./chunk-NWQZW3Y6.js';import'./chunk-4BI7EBPQ.js';import'./chunk-DXB73IDG.js';import {z}from'zod';var b=z.object({sourceBranch:z.string().describe("Source branch name (where changes come from)"),targetBranch:z.string().optional().describe("Target branch name (where to merge). Defaults to current branch."),dryRun:z.boolean().optional().default(true).describe("Preview only, don't apply changes"),autoResolve:z.boolean().optional().default(false).describe("Auto-resolve compatible conflicts"),includeAISuggestions:z.boolean().optional().default(true).describe("Generate AI suggestions for conflicts")}),h=class extends d$1{parseArgs(e){return b.parse(e)}async execute(e){try{let i=a(),o=this.context.getConductor(),c$1=await c(i,o,"merge"),s=e.targetBranch||await this.getCurrentBranch(),t=await c$1.performSemanticMerge({branchA:s,branchB:e.sourceBranch,dryRun:e.dryRun,autoResolve:e.autoResolve,includeAISuggestions:e.includeAISuggestions});return {content:[{type:"text",text:JSON.stringify({success:t.success,summary:{sourceBranch:e.sourceBranch,targetBranch:s,dryRun:e.dryRun,totalUnitsAnalyzed:t.stats.totalUnitsAnalyzed,matchedUnits:t.stats.matchedUnits,conflictsDetected:t.stats.conflictsDetected,autoResolved:t.stats.autoResolved,manualReviewRequired:t.stats.manualReviewRequired,mergeTimeMs:t.stats.mergeTimeMs},conflicts:t.mergeResult?.conflicts.map(n=>({id:n.id,type:n.type,severity:n.severity,description:n.description,branchAUnit:{name:n.branchAUnit.name,filePath:n.branchAUnit.filePath},branchBUnit:{name:n.branchBUnit.name,filePath:n.branchBUnit.filePath},aiSuggestions:n.aiSuggestions})),actions:t.mergeResult?.mergeActions.slice(0,20).map(n=>({type:n.type,unitId:n.unitId,description:n.description})),error:t.error},null,2)}]}}catch(i){let o=a$1(i);return {content:[{type:"text",text:JSON.stringify({error:o.message})}]}}}async getCurrentBranch(){let{execSync:e}=await import('child_process');try{return e("git symbolic-ref --short HEAD",{encoding:"utf-8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).trim()}catch{return "HEAD"}}},A=z.object({branchA:z.string().describe("First branch name"),branchB:z.string().describe("Second branch name")}),p=class extends d$1{parseArgs(e){return A.parse(e)}async execute(e){try{let i=a(),o=this.context.getConductor(),s=await(await c(i,o,"merge")).analyzeConflicts(e.branchA,e.branchB);return {content:[{type:"text",text:JSON.stringify({branchA:e.branchA,branchB:e.branchB,totalConflicts:s.stats.totalConflicts,bySeverity:s.stats.bySeverity,byType:s.stats.byType,conflicts:s.conflicts.map(t=>({id:t.id,type:t.type,severity:t.severity,description:t.description,branchAUnit:{name:t.branchAUnit.name,type:t.branchAUnit.type,filePath:t.branchAUnit.filePath,startLine:t.branchAUnit.startLine},branchBUnit:{name:t.branchBUnit.name,type:t.branchBUnit.type,filePath:t.branchBUnit.filePath,startLine:t.branchBUnit.startLine}}))},null,2)}]}}catch(i){let o=a$1(i);return {content:[{type:"text",text:JSON.stringify({error:o.message})}]}}}},S=z.object({conflictId:z.string().describe("ID of the conflict to get suggestions for"),branchA:z.string().describe("First branch name"),branchB:z.string().describe("Second branch name")}),d=class extends d$1{parseArgs(e){return S.parse(e)}async execute(e){try{let i=a(),o=this.context.getConductor(),c$1=await c(i,o,"merge"),s=await c$1.analyzeConflicts(e.branchA,e.branchB),t=s.conflicts.find(f=>f.id===e.conflictId);if(!t)return {content:[{type:"text",text:JSON.stringify({error:`Conflict ${e.conflictId} not found`,availableConflicts:s.conflicts.map(f=>f.id)})}]};let n=await c$1.getSuggestions(t);return {content:[{type:"text",text:JSON.stringify({conflictId:e.conflictId,conflict:{type:t.type,severity:t.severity,description:t.description},suggestions:n,suggestionsCount:n.length},null,2)}]}}catch(i){let o=a$1(i);return {content:[{type:"text",text:JSON.stringify({error:o.message})}]}}}},x=z.object({}),y=class extends d$1{parseArgs(e){return x.parse(e)}async execute(e){return {content:[{type:"text",text:JSON.stringify({name:"Semantic Merge",version:"1.0.0",description:"AI-powered semantic merge for Git branches",capabilities:["Fast Path matching (90%+ coverage via hashes)","Semantic matching for moved/refactored code","Intent classification (BugFix, Refactoring, FeatureAddition, APIChange)","Conflict detection and severity classification","AI-assisted conflict resolution suggestions"],tools:[{name:"semantic_merge",description:"Perform semantic merge of branches using AI",parameters:["sourceBranch","targetBranch?","dryRun?","autoResolve?","includeAISuggestions?"]},{name:"analyze_merge_conflicts",description:"Analyze merge conflicts between two branches",parameters:["branchA","branchB"]},{name:"get_merge_suggestions",description:"Get AI suggestions for resolving a specific conflict",parameters:["conflictId","branchA","branchB"]}],metrics:{fastPathCoverageTarget:">90%",semanticMatchingAccuracyTarget:">80%",autoMergeRateTarget:">60%"}},null,2)}]}}};export{p as AnalyzeMergeConflictsToolHandler,d as GetMergeSuggestionsToolHandler,y as GetSemanticMergeInfoToolHandler,h as SemanticMergeToolHandler};
@@ -0,0 +1,277 @@
1
+ import { BaseToolHandler } from './chunk-WLKASYMP.js';
2
+ import './chunk-KMXE2SJJ.js';
3
+ import { getGlobalContainer, getOrCreateAgent } from './chunk-RMZXFGQZ.js';
4
+ import './chunk-ZD54CMKT.js';
5
+ import './chunk-HEMJHRHZ.js';
6
+ import { toError } from './chunk-5WKPA33T.js';
7
+ import './chunk-GMVGCSNU.js';
8
+ import './chunk-VCCBEJQ5.js';
9
+ import './chunk-NAQKA54E.js';
10
+ import { z } from 'zod';
11
+
12
+ var SemanticMergeSchema = z.object({
13
+ sourceBranch: z.string().describe("Source branch name (where changes come from)"),
14
+ targetBranch: z.string().optional().describe("Target branch name (where to merge). Defaults to current branch."),
15
+ dryRun: z.boolean().optional().default(true).describe("Preview only, don't apply changes"),
16
+ autoResolve: z.boolean().optional().default(false).describe("Auto-resolve compatible conflicts"),
17
+ includeAISuggestions: z.boolean().optional().default(true).describe("Generate AI suggestions for conflicts")
18
+ });
19
+ var SemanticMergeToolHandler = class extends BaseToolHandler {
20
+ parseArgs(args) {
21
+ return SemanticMergeSchema.parse(args);
22
+ }
23
+ async execute(args) {
24
+ try {
25
+ const container = getGlobalContainer();
26
+ const conductor = this.context.getConductor();
27
+ const mergeAgent = await getOrCreateAgent(container, conductor, "merge" /* MERGE */);
28
+ const targetBranch = args.targetBranch || await this.getCurrentBranch();
29
+ const result = await mergeAgent.performSemanticMerge({
30
+ branchA: targetBranch,
31
+ branchB: args.sourceBranch,
32
+ dryRun: args.dryRun,
33
+ autoResolve: args.autoResolve,
34
+ includeAISuggestions: args.includeAISuggestions
35
+ });
36
+ return {
37
+ content: [
38
+ {
39
+ type: "text",
40
+ text: JSON.stringify(
41
+ {
42
+ success: result.success,
43
+ summary: {
44
+ sourceBranch: args.sourceBranch,
45
+ targetBranch,
46
+ dryRun: args.dryRun,
47
+ totalUnitsAnalyzed: result.stats.totalUnitsAnalyzed,
48
+ matchedUnits: result.stats.matchedUnits,
49
+ conflictsDetected: result.stats.conflictsDetected,
50
+ autoResolved: result.stats.autoResolved,
51
+ manualReviewRequired: result.stats.manualReviewRequired,
52
+ mergeTimeMs: result.stats.mergeTimeMs
53
+ },
54
+ conflicts: result.mergeResult?.conflicts.map(
55
+ (c) => ({
56
+ id: c.id,
57
+ type: c.type,
58
+ severity: c.severity,
59
+ description: c.description,
60
+ branchAUnit: {
61
+ name: c.branchAUnit.name,
62
+ filePath: c.branchAUnit.filePath
63
+ },
64
+ branchBUnit: {
65
+ name: c.branchBUnit.name,
66
+ filePath: c.branchBUnit.filePath
67
+ },
68
+ aiSuggestions: c.aiSuggestions
69
+ })
70
+ ),
71
+ actions: result.mergeResult?.mergeActions.slice(0, 20).map((a) => ({
72
+ type: a.type,
73
+ unitId: a.unitId,
74
+ description: a.description
75
+ })),
76
+ error: result.error
77
+ },
78
+ null,
79
+ 2
80
+ )
81
+ }
82
+ ]
83
+ };
84
+ } catch (error) {
85
+ const err = toError(error);
86
+ return {
87
+ content: [{ type: "text", text: JSON.stringify({ error: err.message }) }]
88
+ };
89
+ }
90
+ }
91
+ async getCurrentBranch() {
92
+ const { execSync } = await import('child_process');
93
+ try {
94
+ return execSync("git symbolic-ref --short HEAD", {
95
+ encoding: "utf-8",
96
+ stdio: ["pipe", "pipe", "ignore"],
97
+ windowsHide: true
98
+ }).trim();
99
+ } catch {
100
+ return "HEAD";
101
+ }
102
+ }
103
+ };
104
+ var AnalyzeMergeConflictsSchema = z.object({
105
+ branchA: z.string().describe("First branch name"),
106
+ branchB: z.string().describe("Second branch name")
107
+ });
108
+ var AnalyzeMergeConflictsToolHandler = class extends BaseToolHandler {
109
+ parseArgs(args) {
110
+ return AnalyzeMergeConflictsSchema.parse(args);
111
+ }
112
+ async execute(args) {
113
+ try {
114
+ const container = getGlobalContainer();
115
+ const conductor = this.context.getConductor();
116
+ const mergeAgent = await getOrCreateAgent(container, conductor, "merge" /* MERGE */);
117
+ const result = await mergeAgent.analyzeConflicts(args.branchA, args.branchB);
118
+ return {
119
+ content: [
120
+ {
121
+ type: "text",
122
+ text: JSON.stringify(
123
+ {
124
+ branchA: args.branchA,
125
+ branchB: args.branchB,
126
+ totalConflicts: result.stats.totalConflicts,
127
+ bySeverity: result.stats.bySeverity,
128
+ byType: result.stats.byType,
129
+ conflicts: result.conflicts.map((c) => ({
130
+ id: c.id,
131
+ type: c.type,
132
+ severity: c.severity,
133
+ description: c.description,
134
+ branchAUnit: {
135
+ name: c.branchAUnit.name,
136
+ type: c.branchAUnit.type,
137
+ filePath: c.branchAUnit.filePath,
138
+ startLine: c.branchAUnit.startLine
139
+ },
140
+ branchBUnit: {
141
+ name: c.branchBUnit.name,
142
+ type: c.branchBUnit.type,
143
+ filePath: c.branchBUnit.filePath,
144
+ startLine: c.branchBUnit.startLine
145
+ }
146
+ }))
147
+ },
148
+ null,
149
+ 2
150
+ )
151
+ }
152
+ ]
153
+ };
154
+ } catch (error) {
155
+ const err = toError(error);
156
+ return {
157
+ content: [{ type: "text", text: JSON.stringify({ error: err.message }) }]
158
+ };
159
+ }
160
+ }
161
+ };
162
+ var GetMergeSuggestionsSchema = z.object({
163
+ conflictId: z.string().describe("ID of the conflict to get suggestions for"),
164
+ branchA: z.string().describe("First branch name"),
165
+ branchB: z.string().describe("Second branch name")
166
+ });
167
+ var GetMergeSuggestionsToolHandler = class extends BaseToolHandler {
168
+ parseArgs(args) {
169
+ return GetMergeSuggestionsSchema.parse(args);
170
+ }
171
+ async execute(args) {
172
+ try {
173
+ const container = getGlobalContainer();
174
+ const conductor = this.context.getConductor();
175
+ const mergeAgent = await getOrCreateAgent(container, conductor, "merge" /* MERGE */);
176
+ const analysis = await mergeAgent.analyzeConflicts(args.branchA, args.branchB);
177
+ const conflict = analysis.conflicts.find((c) => c.id === args.conflictId);
178
+ if (!conflict) {
179
+ return {
180
+ content: [
181
+ {
182
+ type: "text",
183
+ text: JSON.stringify({
184
+ error: `Conflict ${args.conflictId} not found`,
185
+ availableConflicts: analysis.conflicts.map((c) => c.id)
186
+ })
187
+ }
188
+ ]
189
+ };
190
+ }
191
+ const suggestions = await mergeAgent.getSuggestions(conflict);
192
+ return {
193
+ content: [
194
+ {
195
+ type: "text",
196
+ text: JSON.stringify(
197
+ {
198
+ conflictId: args.conflictId,
199
+ conflict: {
200
+ type: conflict.type,
201
+ severity: conflict.severity,
202
+ description: conflict.description
203
+ },
204
+ suggestions,
205
+ suggestionsCount: suggestions.length
206
+ },
207
+ null,
208
+ 2
209
+ )
210
+ }
211
+ ]
212
+ };
213
+ } catch (error) {
214
+ const err = toError(error);
215
+ return {
216
+ content: [{ type: "text", text: JSON.stringify({ error: err.message }) }]
217
+ };
218
+ }
219
+ }
220
+ };
221
+ var GetSemanticMergeInfoSchema = z.object({});
222
+ var GetSemanticMergeInfoToolHandler = class extends BaseToolHandler {
223
+ parseArgs(args) {
224
+ return GetSemanticMergeInfoSchema.parse(args);
225
+ }
226
+ async execute(_args) {
227
+ return {
228
+ content: [
229
+ {
230
+ type: "text",
231
+ text: JSON.stringify(
232
+ {
233
+ name: "Semantic Merge",
234
+ version: "1.0.0",
235
+ description: "AI-powered semantic merge for Git branches",
236
+ capabilities: [
237
+ "Fast Path matching (90%+ coverage via hashes)",
238
+ "Semantic matching for moved/refactored code",
239
+ "Intent classification (BugFix, Refactoring, FeatureAddition, APIChange)",
240
+ "Conflict detection and severity classification",
241
+ "AI-assisted conflict resolution suggestions"
242
+ ],
243
+ tools: [
244
+ {
245
+ name: "semantic_merge",
246
+ description: "Perform semantic merge of branches using AI",
247
+ parameters: ["sourceBranch", "targetBranch?", "dryRun?", "autoResolve?", "includeAISuggestions?"]
248
+ },
249
+ {
250
+ name: "analyze_merge_conflicts",
251
+ description: "Analyze merge conflicts between two branches",
252
+ parameters: ["branchA", "branchB"]
253
+ },
254
+ {
255
+ name: "get_merge_suggestions",
256
+ description: "Get AI suggestions for resolving a specific conflict",
257
+ parameters: ["conflictId", "branchA", "branchB"]
258
+ }
259
+ ],
260
+ metrics: {
261
+ fastPathCoverageTarget: ">90%",
262
+ semanticMatchingAccuracyTarget: ">80%",
263
+ autoMergeRateTarget: ">60%"
264
+ }
265
+ },
266
+ null,
267
+ 2
268
+ )
269
+ }
270
+ ]
271
+ };
272
+ }
273
+ };
274
+
275
+ export { AnalyzeMergeConflictsToolHandler, GetMergeSuggestionsToolHandler, GetSemanticMergeInfoToolHandler, SemanticMergeToolHandler };
276
+ //# sourceMappingURL=merge-tool-handlers-RUJAKE3D.js.map
277
+ //# sourceMappingURL=merge-tool-handlers-RUJAKE3D.js.map