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.
- package/dist/chunks/analysis-tool-handlers-H2RXLDPX.js +817 -0
- package/dist/chunks/analysis-tool-handlers-RJZAR6VT.js +817 -0
- package/dist/chunks/analysis-tool-handlers-Z2RF24T7.js +13 -0
- package/dist/chunks/autodoc-tool-handlers-CV5JEQUA.js +1112 -0
- package/dist/chunks/autodoc-tool-handlers-EHTNCH6I.js +1112 -0
- package/dist/chunks/autodoc-tool-handlers-MECXQJ2K.js +138 -0
- package/dist/chunks/chaos-CO7TOBOJ.js +18 -0
- package/dist/chunks/chaos-VM2PXERO.js +1573 -0
- package/dist/chunks/chaos-W3XRVJ7K.js +1564 -0
- package/dist/chunks/chunk-6K37BWK5.js +439 -0
- package/dist/chunks/chunk-EALTCYHZ.js +10 -0
- package/dist/chunks/chunk-FTBE7VMY.js +316 -0
- package/dist/chunks/chunk-KBW6LRQP.js +322 -0
- package/dist/chunks/chunk-NKUHX4CU.js +5 -0
- package/dist/chunks/chunk-NZFF4DQ4.js +3179 -0
- package/dist/chunks/chunk-RGP5UVQ7.js +3179 -0
- package/dist/chunks/chunk-RMZXFGQZ.js +322 -0
- package/dist/chunks/chunk-UG44F23Y.js +316 -0
- package/dist/chunks/chunk-V2SCB5H5.js +4403 -0
- package/dist/chunks/chunk-V6JAQNM3.js +1 -0
- package/dist/chunks/chunk-XFGXM4CR.js +4403 -0
- package/dist/chunks/dev-agent-JVIGBMHQ.js +1 -0
- package/dist/chunks/dev-agent-TRVP5U6N.js +1624 -0
- package/dist/chunks/dev-agent-Y5G5WKQ4.js +1624 -0
- package/dist/chunks/graph-storage-factory-AYZ57YSL.js +13 -0
- package/dist/chunks/graph-storage-factory-GTAIJEI5.js +1 -0
- package/dist/chunks/graph-storage-factory-T2WO5QVG.js +13 -0
- package/dist/chunks/incremental-updater-KDIQGAUU.js +14 -0
- package/dist/chunks/incremental-updater-OJRSTO3Q.js +1 -0
- package/dist/chunks/incremental-updater-SBEBH7KF.js +14 -0
- package/dist/chunks/indexer-agent-H3QIEL3Z.js +21 -0
- package/dist/chunks/indexer-agent-KHF5JMV7.js +21 -0
- package/dist/chunks/indexer-agent-SHJD6Z77.js +1 -0
- package/dist/chunks/indexing-pipeline-J6Z4BHKF.js +1 -0
- package/dist/chunks/indexing-pipeline-OY3337QN.js +249 -0
- package/dist/chunks/indexing-pipeline-WCXIDMAP.js +249 -0
- package/dist/chunks/merge-agent-LSUBDJB2.js +2481 -0
- package/dist/chunks/merge-agent-MJEW3HWU.js +2481 -0
- package/dist/chunks/merge-agent-O45OXF33.js +11 -0
- package/dist/chunks/merge-tool-handlers-BDSVNQVZ.js +277 -0
- package/dist/chunks/merge-tool-handlers-HP7DRBXJ.js +1 -0
- package/dist/chunks/merge-tool-handlers-RUJAKE3D.js +277 -0
- package/dist/chunks/pattern-tool-handlers-L62W3CXR.js +1549 -0
- package/dist/chunks/pattern-tool-handlers-SAHX2CVW.js +13 -0
- package/dist/chunks/query-agent-3TWDFIMT.js +191 -0
- package/dist/chunks/query-agent-HXQ3BMMF.js +191 -0
- package/dist/chunks/query-agent-USMC2GNG.js +1 -0
- package/dist/chunks/semantic-agent-MQCAWIAB.js +6381 -0
- package/dist/chunks/semantic-agent-NDGR3NAK.js +6381 -0
- package/dist/chunks/semantic-agent-S4ZL6GZC.js +137 -0
- package/dist/index.js +17 -17
- package/dist/roslyn-addon/.build-hash +1 -1
- package/dist/roslyn-addon/ILGPU.Algorithms.dll +0 -0
- package/dist/roslyn-addon/ILGPU.dll +0 -0
- package/dist/roslyn-addon/UltraCode.CSharp.deps.json +35 -0
- package/dist/roslyn-addon/UltraCode.CSharp.dll +0 -0
- package/package.json +1 -1
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import {a,b}from'./chunk-E4J4VT3N.js';import {d as d$1}from'./chunk-RPKK6MZA.js';import'./chunk-QBFXI33X.js';import {a as a$2}from'./chunk-IFKMF76K.js';import'./chunk-GVQNDMAK.js';import'./chunk-PZF7YC35.js';import {a as a$1}from'./chunk-F3VMUQ7O.js';import {R,I as I$1}from'./chunk-4BI7EBPQ.js';import {d}from'./chunk-DXB73IDG.js';import {join}from'path';import {createHash}from'crypto';import {readdirSync,readFileSync,existsSync,mkdirSync,writeFileSync}from'fs';import Pt from'yaml';import {z}from'zod';R();var k={};d(k,{checkDeepNesting:()=>pt,checkGodFunction:()=>mt,checkLargeClass:()=>ft,checkNoDocumentation:()=>dt,checkSmallFocusedFunction:()=>ht,checkTooManyParams:()=>ut});function mt(o){if((o.metadata?.modifiers??[]).includes("partial"))return {match:false,confidence:0};let i=o.metadata?.metrics,e=i?.cyclomaticComplexity??0,n=i?.linesOfCode??0,a=[];return e>20&&a.push(`cyclomatic=${e}`),n>200&&a.push(`LOC=${n}`),a.length===0?{match:false,confidence:0}:{match:true,confidence:a.length===2?.95:.8,matchedCriteria:a}}function pt(o){let i=o.metadata?.metrics?.nestingDepth??0;return i<=5?{match:false,confidence:0}:{match:true,confidence:Math.min(.5+(i-5)*.1,1),matchedCriteria:[`nestingDepth=${i}`]}}function ut(o){let t=o.metadata?.parameters??[];if(t.length<=7)return {match:false,confidence:0};let i=o.metadata?.modifiers??[];if(i.includes("constructor")||i.includes("partial"))return {match:false,confidence:0};let e=t.filter(n=>n.type&&/^I[A-Z]/.test(n.type)).length;return t.length>0&&e/t.length>=.7?{match:false,confidence:0}:{match:true,confidence:Math.min(.6+(t.length-7)*.05,1),matchedCriteria:[`paramCount=${t.length}`]}}function dt(o){let t=o.metadata?.modifiers??[];if(!(t.includes("public")||t.includes("export")||t.includes("exported")))return {match:false,confidence:0};if(t.includes("partial"))return {match:false,confidence:0};if(t.includes("internal"))return {match:false,confidence:0};let e=o.filePath;if(/[\\/](Minimal|Internal|Hosting|Kestrel|Middleware|Extensions)\b/i.test(e))return {match:false,confidence:0};let a=o.metadata?.signature?.includes("/**")??false,r=o.metadata?.documentation!=null||o.metadata?.description!=null;return a||r?{match:false,confidence:0}:{match:true,confidence:.7,matchedCriteria:["public-no-docs"]}}function ht(o){let t=o.metadata?.metrics,i=t?.cyclomaticComplexity??0,e=t?.linesOfCode??0;if(e<3)return {match:false,confidence:0};let n=[];return e<=30&&n.push(`LOC=${e}`),i<=5&&n.push(`cyclomatic=${i}`),n.length<2?{match:false,confidence:0}:{match:true,confidence:.85,matchedCriteria:n}}function ft(o){if(o.type!=="class")return {match:false,confidence:0};let i=o.metadata?.metrics?.linesOfCode??0,e=o.metadata?.metrics?.methodCount??0,n=[];return i>500&&n.push(`LOC=${i}`),e>20&&n.push(`methods=${e}`),i<=500?{match:false,confidence:0}:{match:true,confidence:n.length===2?.9:.7,matchedCriteria:n}}R();var $=class{constructor(t,i){this.exemplarsDir=t;this.cacheDir=i??join(process.cwd(),".cache");}exemplars=new Map;exemplarsByPattern=new Map;embeddings=new Map;loaded=false;embedded=false;cacheDir;async load(t){if(this.loaded)return;let i=t??this.exemplarsDir??join(import.meta.dirname,"exemplars"),e;try{e=readdirSync(i).filter(n=>n.endsWith(".yaml")||n.endsWith(".yml"));}catch{I$1.w("EXEMPLAR_STORE","dir_not_found",{dir:i}),this.loaded=true;return}for(let n of e)try{let a=readFileSync(join(i,n),"utf-8"),r=Pt.parse(a);if(!r?.exemplars)continue;for(let s of r.exemplars){let m={id:s.id,patternId:s.patternId,language:s.language,code:s.code.slice(0,400),description:s.description};this.exemplars.set(s.id,m);let c=this.exemplarsByPattern.get(s.patternId)??[];c.push(m),this.exemplarsByPattern.set(s.patternId,c);}I$1.i("EXEMPLAR_STORE","loaded_file",{file:n,count:r.exemplars.length});}catch(a){I$1.e("EXEMPLAR_STORE","load_error",{file:n,error:String(a)});}this.loaded=true,I$1.i("EXEMPLAR_STORE","store_ready",{total:this.exemplars.size});}async ensureEmbeddings(t){if(this.embedded||this.exemplars.size===0)return;let i=this.computeHash(),e=join(this.cacheDir,"pattern-exemplar-embeddings.json");if(this.tryLoadCache(e,i)){this.embedded=true,I$1.i("EXEMPLAR_STORE","cache_hit",{exemplars:this.embeddings.size});return}I$1.i("EXEMPLAR_STORE","generating_embeddings",{count:this.exemplars.size});let n=Date.now();for(let[a,r]of this.exemplars)try{let s=await t.generateCodeEmbedding(r.code,r.language);this.embeddings.set(a,s);}catch(s){I$1.w("EXEMPLAR_STORE","embed_error",{id:a,error:String(s)});}I$1.i("EXEMPLAR_STORE","embeddings_generated",{count:this.embeddings.size,durationMs:Date.now()-n}),this.saveCache(e,i),this.embedded=true;}findSimilarExemplars(t,i,e=1){let n=this.exemplarsByPattern.get(i)??[];if(n.length===0)return [];let a=[];for(let r of n){let s=this.embeddings.get(r.id);if(!s)continue;let m=a$2(t,s);a.push({id:r.id,similarity:m,description:r.description});}return a.sort((r,s)=>s.similarity-r.similarity).slice(0,e)}get(t){return this.exemplars.get(t)}getForPattern(t){return this.exemplarsByPattern.get(t)??[]}get size(){return this.exemplars.size}computeHash(){let t=[...this.exemplars.values()].map(i=>i.code).sort().join("|");return createHash("sha256").update(t).digest("hex").slice(0,16)}tryLoadCache(t,i){try{if(!existsSync(t))return !1;let e=JSON.parse(readFileSync(t,"utf-8"));if(e.hash!==i)return !1;for(let[n,a]of Object.entries(e.embeddings)){if(!this.exemplars.has(n))continue;let r=Buffer.from(a,"base64");this.embeddings.set(n,new Float32Array(r.buffer,r.byteOffset,r.byteLength/4));}return this.embeddings.size>0}catch{return false}}saveCache(t,i){try{existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:!0});let e={hash:i,embeddings:{}};for(let[n,a]of this.embeddings){let r=Buffer.from(a.buffer,a.byteOffset,a.byteLength);e.embeddings[n]=r.toString("base64");}writeFileSync(t,JSON.stringify(e),"utf-8"),I$1.i("EXEMPLAR_STORE","cache_saved",{file:t,count:this.embeddings.size});}catch(e){I$1.w("EXEMPLAR_STORE","cache_save_error",{error:String(e)});}}};R();var Rt=z.object({type:z.string(),direction:z.enum(["incoming","outgoing"]),minCount:z.number().optional(),maxCount:z.number().optional(),crossFileRatio:z.object({min:z.number().optional(),max:z.number().optional()}).optional()}),Mt=z.object({entityTypes:z.array(z.string()).optional(),requiredModifiers:z.array(z.string()).optional(),forbiddenModifiers:z.array(z.string()).optional(),returnTypeMatch:z.string().optional(),returnTypeNotMatch:z.string().optional(),minParams:z.number().optional(),maxParams:z.number().optional(),paramTypeRequired:z.string().optional(),paramTypeAbsent:z.string().optional(),minCyclomatic:z.number().optional(),maxCyclomatic:z.number().optional(),minCognitive:z.number().optional(),minNesting:z.number().optional(),minLOC:z.number().optional(),maxLOC:z.number().optional(),hasLoops:z.boolean().optional(),hasExceptions:z.boolean().optional(),hasAwaits:z.boolean().optional(),minBranches:z.number().optional(),minCallCount:z.number().optional(),callsInclude:z.array(z.string()).optional(),callsExclude:z.array(z.string()).optional(),decoratorMatch:z.array(z.string()).optional(),hasNoInheritance:z.boolean().optional(),filePathNotMatch:z.string().optional(),nameMatch:z.string().optional(),nameNotMatch:z.string().optional(),relationships:z.array(Rt).optional()}),Tt=z.object({id:z.string(),language:z.string().optional(),category:z.enum(["anti-pattern","best-pattern","code-smell","optimization"]),severity:z.enum(["critical","high","medium","low","info"]),name:z.string(),description:z.string(),suggestion:z.string(),bigO:z.object({before:z.string(),after:z.string()}).optional(),benchmark:z.string().optional(),tags:z.array(z.string()).default([]),enabled:z.boolean().default(true),structural:Mt.optional(),customDetector:z.string().optional(),exemplarIds:z.array(z.string()).optional(),minSemanticSimilarity:z.number().default(0),minStructuralConfidence:z.number().default(.6)}),vt=z.object({patterns:z.array(Tt)}),N=class{constructor(t){this.rulesDir=t;}patterns=new Map;allPatterns=new Map;loaded=false;async load(t){if(this.loaded)return;let i=t??this.rulesDir??join(import.meta.dirname,"rules"),e;try{e=readdirSync(i).filter(n=>n.endsWith(".yaml")||n.endsWith(".yml"));}catch{I$1.w("PATTERN_REGISTRY","rules_dir_not_found",{dir:i}),this.loaded=true;return}for(let n of e){let a=n.replace(/\.ya?ml$/,"");try{let r=readFileSync(join(i,n),"utf-8"),s=Pt.parse(r),c=vt.parse(s).patterns.map(p=>({...p,language:p.language??a})),h=this.patterns.get(a)??[];this.patterns.set(a,[...h,...c]);for(let p of c)this.allPatterns.has(p.id)&&I$1.w("PATTERN_REGISTRY","duplicate_pattern_id",{id:p.id}),this.allPatterns.set(p.id,p);I$1.i("PATTERN_REGISTRY","loaded_rules",{file:n,count:c.length});}catch(r){I$1.e("PATTERN_REGISTRY","load_error",{file:n,error:String(r)});}}this.loaded=true,I$1.i("PATTERN_REGISTRY","registry_ready",{languages:this.patterns.size,totalPatterns:this.allPatterns.size});}getPatterns(t){let{language:i,category:e="all",tags:n,enabledOnly:a=true}=t,r=[];return i?r=[...this.patterns.get(i)??[],...this.patterns.get("common")??[]]:r=[...this.allPatterns.values()],a&&(r=r.filter(s=>s.enabled)),e!=="all"&&(r=r.filter(s=>s.category===e)),n&&n.length>0&&(r=r.filter(s=>n.some(m=>s.tags.includes(m)))),r}getPattern(t){return this.allPatterns.get(t)}getLanguages(){return [...this.patterns.keys()]}get size(){return this.allPatterns.size}};R();var D=class{constructor(t,i){this.exemplarStore=t;this.embeddingGen=i;}async validate(t,i){let e=[],n=t.filter(r=>r.pattern.minSemanticSimilarity>0),a=t.filter(r=>r.pattern.minSemanticSimilarity===0);for(let r of a)e.push(this.createMatch(r,1,void 0));if(n.length>0){this.embeddingGen&&await this.exemplarStore.ensureEmbeddings(this.embeddingGen);for(let r of n){let s=await this.getEntityEmbedding(r);if(!s){r.confidence>=r.pattern.minStructuralConfidence&&e.push(this.createMatch(r,-1,void 0));continue}let c=this.exemplarStore.findSimilarExemplars(s,r.pattern.id,1)[0],h=c?.similarity??0;h>=r.pattern.minSemanticSimilarity&&e.push(this.createMatch(r,h,c));}}return I$1.i("SEMANTIC_VALIDATOR","validation_complete",{candidates:t.length,confirmed:e.length,structuralOnly:a.length,semanticValidated:n.length}),e}createMatch(t,i,e){let n=t.pattern.minSemanticSimilarity===0,a=i<0,r=n||a?t.confidence:t.confidence*.4+i*.6;return {patternId:t.pattern.id,pattern:t.pattern,entityId:t.entity.id,entityName:t.entity.name,entityType:t.entity.type,filePath:t.entity.filePath,line:t.entity.location?.start?.line??0,structuralConfidence:t.confidence,semanticSimilarity:n?1:a?0:i,combinedScore:r,matchedCriteria:t.matchedCriteria,closestExemplar:e?{id:e.id,similarity:e.similarity,description:e.description}:void 0}}async getEntityEmbedding(t){let i=t.entity.embeddingBase64;if(i)try{let e=Buffer.from(i,"base64");return new Float32Array(e.buffer,e.byteOffset,e.byteLength/4)}catch{}if(this.embeddingGen)try{let e=t.entity.embeddingText??t.entity.name,n=t.entity.language??t.entity.metadata?.language;return await this.embeddingGen.generateCodeEmbedding(e,n)}catch(e){I$1.w("SEMANTIC_VALIDATOR","embed_error",{entity:t.entity.id,error:String(e)});}return null}};R();var tt=new Map;function B(o){for(let[t,i]of Object.entries(o))tt.set(t,i);}var K=new WeakMap;function Z(o){let t=K.get(o);if(t)return t;let i=o.structural;return t={entityTypeSet:i?.entityTypes?new Set(i.entityTypes):null,returnTypeMatchRe:i?.returnTypeMatch?new RegExp(i.returnTypeMatch,"i"):null,returnTypeNotMatchRe:i?.returnTypeNotMatch?new RegExp(i.returnTypeNotMatch,"i"):null,paramTypeRequiredRe:i?.paramTypeRequired?new RegExp(i.paramTypeRequired,"i"):null,paramTypeAbsentRe:i?.paramTypeAbsent?new RegExp(i.paramTypeAbsent,"i"):null,callsIncludeRe:i?.callsInclude?i.callsInclude.map(e=>new RegExp(e,"i")):null,callsExcludeRe:i?.callsExclude?i.callsExclude.map(e=>new RegExp(e,"i")):null,decoratorMatchRe:i?.decoratorMatch?i.decoratorMatch.map(e=>new RegExp(e,"i")):null,nameMatchRe:i?.nameMatch?new RegExp(i.nameMatch,"i"):null,nameNotMatchRe:i?.nameNotMatch?new RegExp(i.nameNotMatch,"i"):null,filePathNotMatchRe:i?.filePathNotMatch?new RegExp(i.filePathNotMatch,"i"):null,totalCriteriaCount:$t(i??{})},K.set(o,t),t}var Q=new WeakMap;function wt(o){let t=Q.get(o);if(t)return t;let i=o.metadata,e=i?.metrics,n=i?.controlFlow,a=i?.calls??[],r=i?.decorators??[],s=i?.inheritance;return t={modifiers:i?.modifiers??[],returnType:i?.returnType,params:i?.parameters??[],metrics:{cyclomaticComplexity:e?.cyclomaticComplexity??0,cognitiveComplexity:e?.cognitiveComplexity??0,linesOfCode:e?.linesOfCode??0,nestingDepth:e?.nestingDepth??0},cf:{branches:n?.branches?.length??0,loops:n?.loops?.length??0,exceptions:n?.exceptions?.length??0,awaits:n?.awaits?.length??0},callNames:a.map(m=>`${m.target??""}.${m.name??""}`),decoratorNames:r.map(m=>m.name),hasInheritance:(s?.baseClasses?.length??0)>0||(s?.interfaces?.length??0)>0},Q.set(o,t),t}var S={confidence:0,matchedCriteria:[]},O=class{evalCache=new Map;clearEvalCache(){this.evalCache.clear();}async detect(t,i,e){let n=[],a=new Map;for(let c of t){let h=a.get(c.type);h?h.push(c):a.set(c.type,[c]);}let r=[];for(let c of i){let h=Z(c),p;if(h.entityTypeSet){p=[];for(let u of h.entityTypeSet){let g=a.get(u);g&&p.push(...g);}}else p=t;for(let u of p){let g=this.evaluateMetadataCriteria(u,c,h);g.confidence>0&&r.push({entity:u,pattern:c,confidence:g.confidence,matched:g.matchedCriteria});}}let s=r.filter(c=>c.pattern.structural?.relationships&&c.pattern.structural.relationships.length>0),m=r.filter(c=>!c.pattern.structural?.relationships||c.pattern.structural.relationships.length===0);for(let c of m)c.confidence>=c.pattern.minStructuralConfidence&&n.push({entity:c.entity,pattern:c.pattern,confidence:c.confidence,matchedCriteria:c.matched});if(s.length>0&&e){let c=[...new Set(s.map(u=>u.entity.id))],h=[];try{let[u,g]=await Promise.all([e.findRelationships({filters:{fromId:c},limit:1e4}),e.findRelationships({filters:{toId:c},limit:1e4})]);h=[...u,...g];}catch{}let p=new Map;for(let u of h){let g=p.get(u.fromId);if(g?g.push(u):p.set(u.fromId,[u]),u.fromId!==u.toId){let y=p.get(u.toId);y?y.push(u):p.set(u.toId,[u]);}}for(let u of s){let g=p.get(u.entity.id)??[],y=this.evaluateRelationshipCriteria(u.entity,g,u.pattern.structural.relationships);if(y.passed){let C=u.matched.length+y.matchedCriteria.length,R=Z(u.pattern),b=C/Math.max(R.totalCriteriaCount,1);b>=u.pattern.minStructuralConfidence&&n.push({entity:u.entity,pattern:u.pattern,confidence:Math.min(b,1),matchedCriteria:[...u.matched,...y.matchedCriteria]});}}}else if(s.length>0)for(let c of s)c.confidence>=c.pattern.minStructuralConfidence&&n.push({entity:c.entity,pattern:c.pattern,confidence:c.confidence,matchedCriteria:c.matched});return I$1.i("STRUCTURAL_DETECTOR","detection_complete",{entities:t.length,patterns:i.length,candidates:n.length}),n}evaluateMetadataCriteria(t,i,e){let n=`${t.id}::${i.id}`,a=this.evalCache.get(n);if(a)return a;let r=this.evaluateMetadataUncached(t,i,e);return this.evalCache.set(n,r),r}evaluateRequired(t,i,e,n){let a=[];if(i.entityTypeSet&&a.push(`entityType:${t.type}`),e.requiredModifiers){for(let r of e.requiredModifiers)if(!n.modifiers.includes(r))return null;a.push(`modifiers:${e.requiredModifiers.join(",")}`);}if(e.forbiddenModifiers){for(let r of e.forbiddenModifiers)if(n.modifiers.includes(r))return null;a.push("no-forbidden-modifiers");}if(e.hasNoInheritance){if(n.hasInheritance)return null;a.push("no-inheritance");}return i.filePathNotMatchRe&&t.filePath&&i.filePathNotMatchRe.test(t.filePath)||i.nameNotMatchRe&&i.nameNotMatchRe.test(t.name)?null:a}evaluateOptional(t,i,e,n,a){let r=0,s=0;if(i.returnTypeMatchRe&&(r++,typeof n.returnType=="string"&&i.returnTypeMatchRe.test(n.returnType)&&(s++,a.push(`returnType:~/${e.returnTypeMatch}/`))),i.returnTypeNotMatchRe&&(r++,typeof n.returnType=="string"&&!i.returnTypeNotMatchRe.test(n.returnType)&&(s++,a.push(`returnType:!~/${e.returnTypeNotMatch}/`))),e.minParams!=null&&(r++,n.params.length>=e.minParams&&(s++,a.push(`params>=${e.minParams}`))),e.maxParams!=null&&(r++,n.params.length<=e.maxParams&&(s++,a.push(`params<=${e.maxParams}`))),i.paramTypeRequiredRe&&(r++,n.params.some(m=>m.type&&i.paramTypeRequiredRe.test(m.type))&&(s++,a.push(`paramType:${e.paramTypeRequired}`))),i.paramTypeAbsentRe&&(r++,n.params.some(m=>m.type&&i.paramTypeAbsentRe.test(m.type))||(s++,a.push(`paramType:!${e.paramTypeAbsent}`))),e.minCyclomatic!=null&&(r++,n.metrics.cyclomaticComplexity>=e.minCyclomatic&&(s++,a.push(`cyclomatic>=${e.minCyclomatic}`))),e.maxCyclomatic!=null&&(r++,n.metrics.cyclomaticComplexity<=e.maxCyclomatic&&(s++,a.push(`cyclomatic<=${e.maxCyclomatic}`))),e.minCognitive!=null&&(r++,n.metrics.cognitiveComplexity>=e.minCognitive&&(s++,a.push(`cognitive>=${e.minCognitive}`))),e.minNesting!=null&&(r++,n.metrics.nestingDepth>=e.minNesting&&(s++,a.push(`nesting>=${e.minNesting}`))),e.minLOC!=null&&(r++,n.metrics.linesOfCode>=e.minLOC&&(s++,a.push(`LOC>=${e.minLOC}`))),e.maxLOC!=null&&(r++,n.metrics.linesOfCode<=e.maxLOC&&(s++,a.push(`LOC<=${e.maxLOC}`))),e.hasLoops!=null&&(r++,n.cf.loops>0===e.hasLoops&&(s++,a.push(e.hasLoops?"hasLoops":"noLoops"))),e.hasExceptions!=null&&(r++,n.cf.exceptions>0===e.hasExceptions&&(s++,a.push(e.hasExceptions?"hasExceptions":"noExceptions"))),e.hasAwaits!=null&&(r++,n.cf.awaits>0===e.hasAwaits&&(s++,a.push(e.hasAwaits?"hasAwaits":"noAwaits"))),e.minBranches!=null&&(r++,n.cf.branches>=e.minBranches&&(s++,a.push(`branches>=${e.minBranches}`))),e.minCallCount!=null&&(r++,n.callNames.length>=e.minCallCount&&(s++,a.push(`calls>=${e.minCallCount}`))),i.callsIncludeRe)for(let m=0;m<i.callsIncludeRe.length;m++)r++,n.callNames.some(c=>i.callsIncludeRe[m].test(c))&&(s++,a.push(`calls:~/${e.callsInclude[m]}/`));if(i.callsExcludeRe)for(let m=0;m<i.callsExcludeRe.length;m++)r++,n.callNames.some(c=>i.callsExcludeRe[m].test(c))||(s++,a.push(`calls:!~/${e.callsExclude[m]}/`));if(i.decoratorMatchRe)for(let m=0;m<i.decoratorMatchRe.length;m++)r++,n.decoratorNames.some(c=>i.decoratorMatchRe[m].test(c))&&(s++,a.push(`decorator:~/${e.decoratorMatch[m]}/`));return i.nameMatchRe&&(r++,i.nameMatchRe.test(t.name)&&(s++,a.push(`name:~/${e.nameMatch}/`))),i.nameNotMatchRe&&a.push(`name:!~/${e.nameNotMatch}/`),{optionalTotal:r,optionalPassed:s}}evaluateMetadataUncached(t,i,e){let n=i.structural;if(!n&&!i.customDetector)return S;let a=[],r=wt(t);if(n){let s=this.evaluateRequired(t,e,n,r);if(s===null)return S;a.push(...s);let{optionalTotal:m,optionalPassed:c}=this.evaluateOptional(t,e,n,r,a),h=s.length;if(m===0){if(a.length>0&&!i.customDetector)return {confidence:1,matchedCriteria:a}}else {let p=c/m;if((p>0||a.length>h)&&!i.customDetector)return {confidence:p,matchedCriteria:a}}}if(i.customDetector){let s=tt.get(i.customDetector);if(s)try{let m=s(t);if(m.match){let c=m.matchedCriteria??[`custom:${i.customDetector}`],h=[...a,...c],p=a.filter(y=>y.startsWith("entityType:")||y.startsWith("modifiers:")||y==="no-forbidden-modifiers").length;return {confidence:a.length>p?(m.confidence+a.length/Math.max(e.totalCriteriaCount,1))/2:m.confidence,matchedCriteria:h}}return S}catch(m){return I$1.w("STRUCTURAL_DETECTOR","custom_detector_error",{detector:i.customDetector,error:String(m)}),S}return S}return a.length>0&&!n?{confidence:.5,matchedCriteria:a}:{confidence:a.length>0?a.length/Math.max(e.totalCriteriaCount,1):0,matchedCriteria:a}}evaluateRelationshipCriteria(t,i,e){let n=[];for(let a of e){let r=i.filter(m=>{let c=m.type===a.type,h=a.direction==="outgoing"?m.fromId===t.id:m.toId===t.id;return c&&h}),s=r.length;if(a.minCount!=null&&s<a.minCount)return {passed:false,matchedCriteria:n};if(a.maxCount!=null&&s>a.maxCount)return {passed:false,matchedCriteria:n};if(a.crossFileRatio){let m=i.filter(c=>a.direction==="outgoing"?c.fromId===t.id:c.toId===t.id).length;if(m>0){let c=r.length/m;if(a.crossFileRatio.min!=null&&c<a.crossFileRatio.min)return {passed:false,matchedCriteria:n};if(a.crossFileRatio.max!=null&&c>a.crossFileRatio.max)return {passed:false,matchedCriteria:n}}}n.push(`rel:${a.direction}:${a.type}=${s}`);}return {passed:true,matchedCriteria:n}}};function $t(o){let t=0;return o.entityTypes&&t++,o.requiredModifiers&&t++,o.forbiddenModifiers&&t++,o.returnTypeMatch&&t++,o.returnTypeNotMatch&&t++,o.minParams!=null&&t++,o.maxParams!=null&&t++,o.paramTypeRequired&&t++,o.paramTypeAbsent&&t++,o.minCyclomatic!=null&&t++,o.maxCyclomatic!=null&&t++,o.minCognitive!=null&&t++,o.minNesting!=null&&t++,o.minLOC!=null&&t++,o.maxLOC!=null&&t++,o.hasLoops!=null&&t++,o.hasExceptions!=null&&t++,o.hasAwaits!=null&&t++,o.minBranches!=null&&t++,o.minCallCount!=null&&t++,o.callsInclude&&(t+=o.callsInclude.length),o.callsExclude&&(t+=o.callsExclude.length),o.decoratorMatch&&(t+=o.decoratorMatch.length),o.hasNoInheritance&&t++,o.filePathNotMatch&&t++,o.nameMatch&&t++,o.nameNotMatch&&t++,o.relationships&&(t+=o.relationships.length),t}var I={critical:4,high:3,medium:2,low:1,info:0},Nt={typescript:"./detectors/typescript.js",javascript:"./detectors/typescript.js",python:"./detectors/python.js",csharp:"./detectors/csharp.js",java:"./detectors/java.js",kotlin:"./detectors/java.js",go:"./detectors/go.js"},A=class{constructor(t){this.embeddingGen=t;}registry=new N;exemplarStore=new $;structuralDetector=new O;semanticValidator=null;initialized=false;loadedDetectorModules=new Set;async initialize(){if(this.initialized)return;let t=import.meta.dirname;await this.registry.load(join(t,"rules")),await this.exemplarStore.load(join(t,"exemplars")),B(k),this.semanticValidator=new D(this.exemplarStore,this.embeddingGen),this.initialized=true,I$1.i("PATTERN_ENGINE","initialized",{patterns:this.registry.size,exemplars:this.exemplarStore.size});}async ensureDetectorsForLanguage(t){if(!t)return;let i=Nt[t.toLowerCase()];if(!(!i||this.loadedDetectorModules.has(i)))try{let e=await import(i);B(e),this.loadedDetectorModules.add(i),I$1.i("PATTERN_ENGINE","loaded_detectors",{language:t,module:i});}catch{}}async scan(t,i){await this.initialize();let e=Date.now(),{filePath:n,language:a,category:r="all",tags:s,minConfidence:m=.5,severity:c="all",offset:h=0,limit:p=50,entityLimit:u=1e4,suppressPatterns:g}=t,y=u,C;if(n?(/[\\/]$/.test(n)||!/\.\w+$/.test(n.split(/[\\/]/).pop()??""))&&typeof i.searchEntitiesInDirectory=="function"?C=await i.searchEntitiesInDirectory(n):C=await i.findEntities({filters:{filePath:n},limit:y}):C=await i.findEntities({limit:y}),C.length===0)return this.emptyResult();let R=a??this.detectLanguage(C);await this.ensureDetectorsForLanguage(R);let b=this.registry.getPatterns({language:R,category:r,tags:s,enabledOnly:true});if(g?.length){let d=new Set(g);b=b.filter(z=>!d.has(z.id));}if(b.length===0)return this.emptyResult(C.length);let L=await this.structuralDetector.detect(C,b,i),rt=new Map(b.map(d=>[d.id,d])),J=this.semanticValidator?await this.semanticValidator.validate(L,rt):L.map(d=>({patternId:d.pattern.id,pattern:d.pattern,entityId:d.entity.id,entityName:d.entity.name,entityType:d.entity.type,filePath:d.entity.filePath,line:d.entity.location?.start?.line??0,structuralConfidence:d.confidence,semanticSimilarity:1,combinedScore:d.confidence,matchedCriteria:d.matchedCriteria})),P=J.filter(d=>d.combinedScore>=m);c!=="all"&&(P=P.filter(d=>d.pattern.severity===c)),P.sort((d,z)=>z.combinedScore-d.combinedScore);let M=P.filter(d=>d.pattern.category==="anti-pattern"),j=P.filter(d=>d.pattern.category==="best-pattern"),T=P.filter(d=>d.pattern.category==="code-smell"),_=P.filter(d=>d.pattern.category==="optimization"),st=this.computeHealthScore(M,j,T),ot=this.computeTopIssues([...M,...T,..._]),v=d=>d.slice(h,h+p),ct={antiPatterns:v(M),bestPatterns:v(j),codeSmells:v(T),optimizations:v(_),summary:{totalEntitiesScanned:C.length,antiPatternCount:M.length,bestPatternCount:j.length,codeSmellCount:T.length,optimizationCount:_.length,topIssues:ot,healthScore:st}};return I$1.i("PATTERN_ENGINE","scan_complete",{entities:C.length,patterns:b.length,candidates:L.length,confirmed:J.length,filtered:P.length,durationMs:Date.now()-e}),ct}async checkEntity(t,i,e="all"){await this.initialize();let n=await i.getEntity(t);if(!n)return [];let a=n.language??n.metadata?.language;await this.ensureDetectorsForLanguage(a);let r=this.registry.getPatterns({language:a,category:e,enabledOnly:true}),s=await this.structuralDetector.detect([n],r,i),m=new Map(r.map(c=>[c.id,c]));return this.semanticValidator?await this.semanticValidator.validate(s,m):s.map(c=>({patternId:c.pattern.id,pattern:c.pattern,entityId:c.entity.id,entityName:c.entity.name,entityType:c.entity.type,filePath:c.entity.filePath,line:c.entity.location?.start?.line??0,structuralConfidence:c.confidence,semanticSimilarity:1,combinedScore:c.confidence,matchedCriteria:c.matchedCriteria}))}detectLanguage(t){let i=new Map;for(let e of t){let n=e.language??e.metadata?.language;n&&i.set(n,(i.get(n)??0)+1);}if(i.size!==0)return [...i.entries()].sort((e,n)=>n[1]-e[1])[0][0]}computeHealthScore(t,i,e){let n=0;for(let s of t)n+=I[s.pattern.severity]??1;for(let s of e)n+=(I[s.pattern.severity]??1)*.5;let a=i.length,r=Math.round(100*(a+1)/(a+n+1));return Math.max(0,Math.min(100,r))}computeTopIssues(t){let i=new Map;for(let e of t){let n=i.get(e.patternId);n?n.count++:i.set(e.patternId,{count:1,severity:e.pattern.severity});}return [...i.entries()].map(([e,n])=>({patternId:e,...n})).sort((e,n)=>{let a=(I[n.severity]??0)-(I[e.severity]??0);return a!==0?a:n.count-e.count}).slice(0,10)}emptyResult(t=0){return {antiPatterns:[],bestPatterns:[],codeSmells:[],optimizations:[],summary:{totalEntitiesScanned:t,antiPatternCount:0,bestPatternCount:0,codeSmellCount:0,optimizationCount:0,topIssues:[],healthScore:100}}}};var x=class o{static format(t,i="summary"){return i==="json"?JSON.stringify(t,null,2):i==="detailed"?o.formatDetailed(t):o.formatSummary(t)}static formatSummary(t){let{summary:i}=t,e=[];if(e.push("## Pattern Scan Summary"),e.push(`- Entities scanned: ${i.totalEntitiesScanned}`),e.push(`- Health score: ${i.healthScore}/100`),e.push(""),i.antiPatternCount>0){e.push(`### Anti-patterns: ${i.antiPatternCount}`);for(let n of t.antiPatterns.slice(0,10))e.push(` - **${n.pattern.name}** in \`${n.entityName}\` (${n.filePath}:${n.line}) \u2014 score: ${n.combinedScore.toFixed(2)}`);e.push("");}if(i.codeSmellCount>0){e.push(`### Code smells: ${i.codeSmellCount}`);for(let n of t.codeSmells.slice(0,10))e.push(` - **${n.pattern.name}** in \`${n.entityName}\` (${n.filePath}:${n.line}) \u2014 score: ${n.combinedScore.toFixed(2)}`);e.push("");}if(i.optimizationCount>0){e.push(`### Optimizations: ${i.optimizationCount}`);for(let n of t.optimizations.slice(0,10)){let a=n.pattern.bigO?` [${n.pattern.bigO.before} \u2192 ${n.pattern.bigO.after}]`:"",r=n.pattern.benchmark?` (${n.pattern.benchmark})`:"";e.push(` - **${n.pattern.name}**${a}${r} in \`${n.entityName}\` (${n.filePath}:${n.line})`);}e.push("");}if(i.bestPatternCount>0){e.push(`### Best patterns: ${i.bestPatternCount}`);for(let n of t.bestPatterns.slice(0,5))e.push(` - **${n.pattern.name}** in \`${n.entityName}\` (${n.filePath}:${n.line})`);e.push("");}if(i.topIssues.length>0){e.push("### Top Issues");for(let n of i.topIssues.slice(0,5))e.push(` - \`${n.patternId}\` \u2014 ${n.count} occurrence(s), severity: ${n.severity}`);}return e.join(`
|
|
2
|
+
`)}static formatDetailed(t){let i=[...t.antiPatterns,...t.codeSmells,...t.optimizations,...t.bestPatterns],e=[];e.push(`## Pattern Scan \u2014 Detailed (${i.length} matches, health: ${t.summary.healthScore}/100)`),e.push("");for(let n of i){let a=n.pattern.category==="anti-pattern"?"\u{1F534}":n.pattern.category==="code-smell"?"\u{1F7E1}":n.pattern.category==="optimization"?"\u26A1":"\u{1F7E2}";e.push(`### ${a} ${n.pattern.name} [\`${n.patternId}\`]`),e.push(`- **Category**: ${n.pattern.category} | **Severity**: ${n.pattern.severity}`),e.push(`- **Entity**: \`${n.entityName}\` (${n.entityType}) at ${n.filePath}:${n.line}`),e.push(`- **Score**: combined=${n.combinedScore.toFixed(2)}, structural=${n.structuralConfidence.toFixed(2)}, semantic=${n.semanticSimilarity.toFixed(2)}`),e.push(`- **Description**: ${n.pattern.description}`),e.push(`- **Suggestion**: ${n.pattern.suggestion}`),n.pattern.bigO&&e.push(`- **Complexity**: ${n.pattern.bigO.before} \u2192 ${n.pattern.bigO.after}`),n.pattern.benchmark&&e.push(`- **Benchmark**: ${n.pattern.benchmark}`),n.closestExemplar&&e.push(`- **Closest exemplar**: ${n.closestExemplar.id} (similarity: ${n.closestExemplar.similarity.toFixed(2)}) \u2014 ${n.closestExemplar.description}`),n.matchedCriteria.length>0&&e.push(`- **Matched criteria**: ${n.matchedCriteria.join(", ")}`),e.push("");}return e.join(`
|
|
3
|
+
`)}static toJSON(t){return {summary:t.summary,antiPatterns:t.antiPatterns.map(o.matchToJSON),bestPatterns:t.bestPatterns.map(o.matchToJSON),codeSmells:t.codeSmells.map(o.matchToJSON),optimizations:t.optimizations.map(o.matchToJSON)}}static matchToJSON(t){return {patternId:t.patternId,category:t.pattern.category,severity:t.pattern.severity,name:t.pattern.name,description:t.pattern.description,suggestion:t.pattern.suggestion,bigO:t.pattern.bigO,benchmark:t.pattern.benchmark,entityId:t.entityId,entityName:t.entityName,entityType:t.entityType,filePath:t.filePath,line:t.line,combinedScore:Number(t.combinedScore.toFixed(3)),structuralConfidence:Number(t.structuralConfidence.toFixed(3)),semanticSimilarity:Number(t.semanticSimilarity.toFixed(3)),matchedCriteria:t.matchedCriteria,closestExemplar:t.closestExemplar}}};R();var q=null;function at(o){return q||(q=new A(o)),q}var nt=class extends d$1{parseArgs(t){return a.parse(t)}async execute(t){try{let i=await this.ensureGraphStorageForProject(t.projectPath),e;try{let p=await this.context.getSemanticAgent();e=p.embeddingGenerator??p.getEmbeddingGenerator?.();}catch{}let n=at(e),a={projectPath:this.resolveProjectPath(t),filePath:t.filePath,language:t.language,category:t.category,tags:t.tags,minConfidence:t.minConfidence,severity:t.severity==="all"?"all":t.severity,offset:t.offset,limit:t.limit,entityLimit:t.entityLimit,suppressPatterns:t.suppressPatterns},r=await n.scan(a,i),s=[];[...r.antiPatterns,...r.bestPatterns,...r.codeSmells,...r.optimizations].some(p=>p.pattern.tags.some(u=>/security|injection|xss|auth/i.test(u)))&&s.push("taint_analysis() \u2014 deep security analysis of detected vulnerable patterns"),s.push("graph_metrics({metric:'pagerank'}) \u2014 rank affected entities by importance");let h;if(t.format==="json"){let p=x.toJSON(r);p.nextSteps=s,h=JSON.stringify(p,null,2);}else t.format==="detailed"?(h=x.format(r,"detailed"),h+=`
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
Next steps:
|
|
7
|
+
${s.map(p=>`- ${p}`).join(`
|
|
8
|
+
`)}`):(h=x.format(r,"summary"),h+=`
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
Next steps:
|
|
12
|
+
${s.map(p=>`- ${p}`).join(`
|
|
13
|
+
`)}`);return {content:[{type:"text",text:h}]}}catch(i){let e=a$1(i);return I$1.e("DETECT_PATTERNS","scan_error",{error:e.message}),{content:[{type:"text",text:`Error: ${e.message}`}]}}}},it=class extends d$1{parseArgs(t){return b.parse(t)}async execute(t){try{let i=await this.ensureGraphStorageForProject(t.projectPath),e;try{let s=await this.context.getSemanticAgent();e=s.embeddingGenerator??s.getEmbeddingGenerator?.();}catch{}let a=await at(e).checkEntity(t.entityId,i,t.category);if(a.length===0)return {content:[{type:"text",text:`No pattern matches found for entity ${t.entityId}`}]};let r={entityId:t.entityId,matchCount:a.length,matches:a.map(s=>({patternId:s.patternId,category:s.pattern.category,severity:s.pattern.severity,name:s.pattern.name,description:s.pattern.description,suggestion:s.pattern.suggestion,bigO:s.pattern.bigO,benchmark:s.pattern.benchmark,combinedScore:Number(s.combinedScore.toFixed(3)),structuralConfidence:Number(s.structuralConfidence.toFixed(3)),semanticSimilarity:Number(s.semanticSimilarity.toFixed(3)),matchedCriteria:s.matchedCriteria,closestExemplar:s.closestExemplar}))};return {content:[{type:"text",text:JSON.stringify(r,null,2)}]}}catch(i){let e=a$1(i);return I$1.e("CHECK_ENTITY_PATTERNS","check_error",{error:e.message}),{content:[{type:"text",text:`Error: ${e.message}`}]}}}};export{it as CheckEntityPatternsToolHandler,nt as DetectPatternsToolHandler};
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { knowledgeBus } from './chunk-JPI46FLQ.js';
|
|
2
|
+
import { BaseAgent } from './chunk-IGUCJL3R.js';
|
|
3
|
+
import { getGraphStorage } from './chunk-V2SCB5H5.js';
|
|
4
|
+
import './chunk-HNDYLCWI.js';
|
|
5
|
+
import './chunk-CTXFPNDA.js';
|
|
6
|
+
import './chunk-TJSOOFXA.js';
|
|
7
|
+
import './chunk-AIZUHUK6.js';
|
|
8
|
+
import './chunk-L2X4HRXI.js';
|
|
9
|
+
import './chunk-ZD54CMKT.js';
|
|
10
|
+
import './chunk-HEMJHRHZ.js';
|
|
11
|
+
import './chunk-GMVGCSNU.js';
|
|
12
|
+
import { init_yaml_config, getConfig } from './chunk-XV6GNSLC.js';
|
|
13
|
+
import './chunk-F7CKCMXI.js';
|
|
14
|
+
import './chunk-BMHPPH2B.js';
|
|
15
|
+
import { init_logging, log } from './chunk-VCCBEJQ5.js';
|
|
16
|
+
import './chunk-UN27MREV.js';
|
|
17
|
+
import './chunk-NAQKA54E.js';
|
|
18
|
+
import pLimit from 'p-limit';
|
|
19
|
+
|
|
20
|
+
// src/agents/query-agent.ts
|
|
21
|
+
init_yaml_config();
|
|
22
|
+
init_logging();
|
|
23
|
+
var QueryAgent = class extends BaseAgent {
|
|
24
|
+
storage = null;
|
|
25
|
+
ttlCache = /* @__PURE__ */ new Map();
|
|
26
|
+
cacheTtlMs = 3e4;
|
|
27
|
+
concurrencyLimiter;
|
|
28
|
+
stats = { queries: 0, totalMs: 0, hits: 0, misses: 0 };
|
|
29
|
+
taskDispatch = /* @__PURE__ */ new Map([
|
|
30
|
+
["query:entities", (p) => this.findEntities(p)],
|
|
31
|
+
[
|
|
32
|
+
"query:relationships",
|
|
33
|
+
(p) => {
|
|
34
|
+
const { entityId, type } = p;
|
|
35
|
+
return this.findRelationships(entityId, type);
|
|
36
|
+
}
|
|
37
|
+
],
|
|
38
|
+
["query:graph", (p) => this.getGraph(p)],
|
|
39
|
+
["query:dependencies", (p) => this.analyzeDependencies(p.entityId)],
|
|
40
|
+
["query:impact", (p) => this.analyzeImpact(p.entityId)]
|
|
41
|
+
]);
|
|
42
|
+
constructor() {
|
|
43
|
+
const cfg = getConfig();
|
|
44
|
+
const qa = cfg.queryAgent;
|
|
45
|
+
const maxConcurrency = qa?.maxConcurrency ?? 10;
|
|
46
|
+
super("query" /* QUERY */, {
|
|
47
|
+
maxConcurrency,
|
|
48
|
+
memoryLimit: qa?.memoryLimit ?? 112,
|
|
49
|
+
priority: qa?.priority ?? 9
|
|
50
|
+
});
|
|
51
|
+
this.concurrencyLimiter = pLimit(maxConcurrency);
|
|
52
|
+
}
|
|
53
|
+
async handleMessage(_message) {
|
|
54
|
+
}
|
|
55
|
+
async onInitialize() {
|
|
56
|
+
log.i("QUERYAGENT", "init_start", { id: this.id });
|
|
57
|
+
this.storage = await getGraphStorage();
|
|
58
|
+
knowledgeBus.subscribe(this.id, "graph:updated", () => {
|
|
59
|
+
log.d("QUERYAGENT", "graph_updated", { id: this.id });
|
|
60
|
+
this.ttlCache.clear();
|
|
61
|
+
});
|
|
62
|
+
knowledgeBus.subscribe(this.id, "index:complete", () => {
|
|
63
|
+
log.d("QUERYAGENT", "index_complete", { id: this.id });
|
|
64
|
+
this.ttlCache.clear();
|
|
65
|
+
});
|
|
66
|
+
log.i("QUERYAGENT", "init_done", { id: this.id });
|
|
67
|
+
}
|
|
68
|
+
async onShutdown() {
|
|
69
|
+
log.i("QUERYAGENT", "shutdown_start", { id: this.id });
|
|
70
|
+
this.ttlCache.clear();
|
|
71
|
+
log.i("QUERYAGENT", "shutdown_done", { id: this.id });
|
|
72
|
+
}
|
|
73
|
+
canProcessTask(task) {
|
|
74
|
+
return task.type.startsWith("query:");
|
|
75
|
+
}
|
|
76
|
+
async processTask(task) {
|
|
77
|
+
const startTime = Date.now();
|
|
78
|
+
try {
|
|
79
|
+
const handler = this.taskDispatch.get(task.type);
|
|
80
|
+
if (!handler) throw new Error(`Unknown query type: ${task.type}`);
|
|
81
|
+
const result = await this.concurrencyLimiter(() => handler(task.payload));
|
|
82
|
+
this.stats.queries++;
|
|
83
|
+
this.stats.totalMs += Date.now() - startTime;
|
|
84
|
+
return result;
|
|
85
|
+
} catch (error) {
|
|
86
|
+
log.e("QUERYAGENT", "query_fail", { id: this.id, err: String(error) });
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
cacheGet(key) {
|
|
91
|
+
const entry = this.ttlCache.get(key);
|
|
92
|
+
if (!entry) return null;
|
|
93
|
+
if (Date.now() > entry.expiry) {
|
|
94
|
+
this.ttlCache.delete(key);
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
return entry.value;
|
|
98
|
+
}
|
|
99
|
+
cacheSet(key, value) {
|
|
100
|
+
this.ttlCache.set(key, { value, expiry: Date.now() + this.cacheTtlMs });
|
|
101
|
+
}
|
|
102
|
+
async findEntities(filter) {
|
|
103
|
+
if (!this.storage) return [];
|
|
104
|
+
const cacheKey = `entities:${JSON.stringify(filter)}`;
|
|
105
|
+
const cached = this.cacheGet(cacheKey);
|
|
106
|
+
if (cached) {
|
|
107
|
+
this.stats.hits++;
|
|
108
|
+
return cached;
|
|
109
|
+
}
|
|
110
|
+
this.stats.misses++;
|
|
111
|
+
const results = await this.storage.searchEntities({
|
|
112
|
+
namePattern: typeof filter.name === "string" ? filter.name : filter.name?.source,
|
|
113
|
+
types: Array.isArray(filter.type) ? filter.type : filter.type ? [filter.type] : void 0,
|
|
114
|
+
filePath: Array.isArray(filter.filePath) ? filter.filePath[0] : filter.filePath,
|
|
115
|
+
limit: 100
|
|
116
|
+
});
|
|
117
|
+
this.cacheSet(cacheKey, results);
|
|
118
|
+
return results;
|
|
119
|
+
}
|
|
120
|
+
async findRelationships(entityId, type) {
|
|
121
|
+
if (!this.storage) return [];
|
|
122
|
+
const cacheKey = `rels:${entityId}:${type ?? "all"}`;
|
|
123
|
+
const cached = this.cacheGet(cacheKey);
|
|
124
|
+
if (cached) {
|
|
125
|
+
this.stats.hits++;
|
|
126
|
+
return cached;
|
|
127
|
+
}
|
|
128
|
+
this.stats.misses++;
|
|
129
|
+
const results = await this.storage.getRelationshipsForEntity(entityId, type);
|
|
130
|
+
this.cacheSet(cacheKey, results);
|
|
131
|
+
return results;
|
|
132
|
+
}
|
|
133
|
+
async getGraph(query) {
|
|
134
|
+
if (!this.storage) return { entities: [], relationships: [] };
|
|
135
|
+
const result = await this.storage.executeQuery(query);
|
|
136
|
+
return { entities: result.entities, relationships: result.relationships };
|
|
137
|
+
}
|
|
138
|
+
async analyzeDependencies(entityId) {
|
|
139
|
+
if (!this.storage) return { root: entityId, children: [] };
|
|
140
|
+
const rels = await this.storage.getRelationshipsForEntity(entityId);
|
|
141
|
+
return {
|
|
142
|
+
root: entityId,
|
|
143
|
+
children: rels.filter((r) => r.fromId === entityId).map((r) => ({ root: r.toId, children: [] }))
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
async analyzeImpact(entityId) {
|
|
147
|
+
if (!this.storage) return { source: entityId, directImpact: [], transitiveImpact: [], riskLevel: "low" };
|
|
148
|
+
const rels = await this.storage.getRelationshipsForEntity(entityId);
|
|
149
|
+
const directImpact = rels.filter((r) => r.toId === entityId).map((r) => r.fromId);
|
|
150
|
+
const transitiveImpact = [];
|
|
151
|
+
for (const id of directImpact) {
|
|
152
|
+
const tRels = await this.storage.getRelationshipsForEntity(id);
|
|
153
|
+
for (const r of tRels) {
|
|
154
|
+
if (r.toId === id && !directImpact.includes(r.fromId) && r.fromId !== entityId) {
|
|
155
|
+
transitiveImpact.push(r.fromId);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
const total = directImpact.length + transitiveImpact.length;
|
|
160
|
+
const riskLevel = total > 50 ? "critical" : total > 20 ? "high" : total > 5 ? "medium" : "low";
|
|
161
|
+
return { source: entityId, directImpact, transitiveImpact, riskLevel };
|
|
162
|
+
}
|
|
163
|
+
async findPaths(_source, _target, _maxDepth) {
|
|
164
|
+
return [];
|
|
165
|
+
}
|
|
166
|
+
async findCycles(_entityId, _maxDepth) {
|
|
167
|
+
return [];
|
|
168
|
+
}
|
|
169
|
+
async analyzeHotspots(_filter) {
|
|
170
|
+
return [];
|
|
171
|
+
}
|
|
172
|
+
async analyzeRippleEffects(_changeSet) {
|
|
173
|
+
return [];
|
|
174
|
+
}
|
|
175
|
+
getQueryMetrics() {
|
|
176
|
+
const { queries, totalMs, hits, misses } = this.stats;
|
|
177
|
+
const total = hits + misses;
|
|
178
|
+
return {
|
|
179
|
+
totalQueries: queries,
|
|
180
|
+
totalTime: totalMs,
|
|
181
|
+
cacheHits: hits,
|
|
182
|
+
cacheMisses: misses,
|
|
183
|
+
avgQueryTime: queries > 0 ? Math.round(totalMs / queries) : 0,
|
|
184
|
+
cacheHitRate: total > 0 ? Math.round(hits / total * 100) : 0
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
export { QueryAgent };
|
|
190
|
+
//# sourceMappingURL=query-agent-3TWDFIMT.js.map
|
|
191
|
+
//# sourceMappingURL=query-agent-3TWDFIMT.js.map
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { knowledgeBus } from './chunk-JPI46FLQ.js';
|
|
2
|
+
import { BaseAgent } from './chunk-IGUCJL3R.js';
|
|
3
|
+
import { getGraphStorage } from './chunk-XFGXM4CR.js';
|
|
4
|
+
import './chunk-HNDYLCWI.js';
|
|
5
|
+
import './chunk-CTXFPNDA.js';
|
|
6
|
+
import './chunk-TJSOOFXA.js';
|
|
7
|
+
import './chunk-AIZUHUK6.js';
|
|
8
|
+
import './chunk-L2X4HRXI.js';
|
|
9
|
+
import './chunk-ZD54CMKT.js';
|
|
10
|
+
import './chunk-HEMJHRHZ.js';
|
|
11
|
+
import './chunk-GMVGCSNU.js';
|
|
12
|
+
import { init_yaml_config, getConfig } from './chunk-XV6GNSLC.js';
|
|
13
|
+
import './chunk-F7CKCMXI.js';
|
|
14
|
+
import './chunk-BMHPPH2B.js';
|
|
15
|
+
import { init_logging, log } from './chunk-VCCBEJQ5.js';
|
|
16
|
+
import './chunk-UN27MREV.js';
|
|
17
|
+
import './chunk-NAQKA54E.js';
|
|
18
|
+
import pLimit from 'p-limit';
|
|
19
|
+
|
|
20
|
+
// src/agents/query-agent.ts
|
|
21
|
+
init_yaml_config();
|
|
22
|
+
init_logging();
|
|
23
|
+
var QueryAgent = class extends BaseAgent {
|
|
24
|
+
storage = null;
|
|
25
|
+
ttlCache = /* @__PURE__ */ new Map();
|
|
26
|
+
cacheTtlMs = 3e4;
|
|
27
|
+
concurrencyLimiter;
|
|
28
|
+
stats = { queries: 0, totalMs: 0, hits: 0, misses: 0 };
|
|
29
|
+
taskDispatch = /* @__PURE__ */ new Map([
|
|
30
|
+
["query:entities", (p) => this.findEntities(p)],
|
|
31
|
+
[
|
|
32
|
+
"query:relationships",
|
|
33
|
+
(p) => {
|
|
34
|
+
const { entityId, type } = p;
|
|
35
|
+
return this.findRelationships(entityId, type);
|
|
36
|
+
}
|
|
37
|
+
],
|
|
38
|
+
["query:graph", (p) => this.getGraph(p)],
|
|
39
|
+
["query:dependencies", (p) => this.analyzeDependencies(p.entityId)],
|
|
40
|
+
["query:impact", (p) => this.analyzeImpact(p.entityId)]
|
|
41
|
+
]);
|
|
42
|
+
constructor() {
|
|
43
|
+
const cfg = getConfig();
|
|
44
|
+
const qa = cfg.queryAgent;
|
|
45
|
+
const maxConcurrency = qa?.maxConcurrency ?? 10;
|
|
46
|
+
super("query" /* QUERY */, {
|
|
47
|
+
maxConcurrency,
|
|
48
|
+
memoryLimit: qa?.memoryLimit ?? 112,
|
|
49
|
+
priority: qa?.priority ?? 9
|
|
50
|
+
});
|
|
51
|
+
this.concurrencyLimiter = pLimit(maxConcurrency);
|
|
52
|
+
}
|
|
53
|
+
async handleMessage(_message) {
|
|
54
|
+
}
|
|
55
|
+
async onInitialize() {
|
|
56
|
+
log.i("QUERYAGENT", "init_start", { id: this.id });
|
|
57
|
+
this.storage = await getGraphStorage();
|
|
58
|
+
knowledgeBus.subscribe(this.id, "graph:updated", () => {
|
|
59
|
+
log.d("QUERYAGENT", "graph_updated", { id: this.id });
|
|
60
|
+
this.ttlCache.clear();
|
|
61
|
+
});
|
|
62
|
+
knowledgeBus.subscribe(this.id, "index:complete", () => {
|
|
63
|
+
log.d("QUERYAGENT", "index_complete", { id: this.id });
|
|
64
|
+
this.ttlCache.clear();
|
|
65
|
+
});
|
|
66
|
+
log.i("QUERYAGENT", "init_done", { id: this.id });
|
|
67
|
+
}
|
|
68
|
+
async onShutdown() {
|
|
69
|
+
log.i("QUERYAGENT", "shutdown_start", { id: this.id });
|
|
70
|
+
this.ttlCache.clear();
|
|
71
|
+
log.i("QUERYAGENT", "shutdown_done", { id: this.id });
|
|
72
|
+
}
|
|
73
|
+
canProcessTask(task) {
|
|
74
|
+
return task.type.startsWith("query:");
|
|
75
|
+
}
|
|
76
|
+
async processTask(task) {
|
|
77
|
+
const startTime = Date.now();
|
|
78
|
+
try {
|
|
79
|
+
const handler = this.taskDispatch.get(task.type);
|
|
80
|
+
if (!handler) throw new Error(`Unknown query type: ${task.type}`);
|
|
81
|
+
const result = await this.concurrencyLimiter(() => handler(task.payload));
|
|
82
|
+
this.stats.queries++;
|
|
83
|
+
this.stats.totalMs += Date.now() - startTime;
|
|
84
|
+
return result;
|
|
85
|
+
} catch (error) {
|
|
86
|
+
log.e("QUERYAGENT", "query_fail", { id: this.id, err: String(error) });
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
cacheGet(key) {
|
|
91
|
+
const entry = this.ttlCache.get(key);
|
|
92
|
+
if (!entry) return null;
|
|
93
|
+
if (Date.now() > entry.expiry) {
|
|
94
|
+
this.ttlCache.delete(key);
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
return entry.value;
|
|
98
|
+
}
|
|
99
|
+
cacheSet(key, value) {
|
|
100
|
+
this.ttlCache.set(key, { value, expiry: Date.now() + this.cacheTtlMs });
|
|
101
|
+
}
|
|
102
|
+
async findEntities(filter) {
|
|
103
|
+
if (!this.storage) return [];
|
|
104
|
+
const cacheKey = `entities:${JSON.stringify(filter)}`;
|
|
105
|
+
const cached = this.cacheGet(cacheKey);
|
|
106
|
+
if (cached) {
|
|
107
|
+
this.stats.hits++;
|
|
108
|
+
return cached;
|
|
109
|
+
}
|
|
110
|
+
this.stats.misses++;
|
|
111
|
+
const results = await this.storage.searchEntities({
|
|
112
|
+
namePattern: typeof filter.name === "string" ? filter.name : filter.name?.source,
|
|
113
|
+
types: Array.isArray(filter.type) ? filter.type : filter.type ? [filter.type] : void 0,
|
|
114
|
+
filePath: Array.isArray(filter.filePath) ? filter.filePath[0] : filter.filePath,
|
|
115
|
+
limit: 100
|
|
116
|
+
});
|
|
117
|
+
this.cacheSet(cacheKey, results);
|
|
118
|
+
return results;
|
|
119
|
+
}
|
|
120
|
+
async findRelationships(entityId, type) {
|
|
121
|
+
if (!this.storage) return [];
|
|
122
|
+
const cacheKey = `rels:${entityId}:${type ?? "all"}`;
|
|
123
|
+
const cached = this.cacheGet(cacheKey);
|
|
124
|
+
if (cached) {
|
|
125
|
+
this.stats.hits++;
|
|
126
|
+
return cached;
|
|
127
|
+
}
|
|
128
|
+
this.stats.misses++;
|
|
129
|
+
const results = await this.storage.getRelationshipsForEntity(entityId, type);
|
|
130
|
+
this.cacheSet(cacheKey, results);
|
|
131
|
+
return results;
|
|
132
|
+
}
|
|
133
|
+
async getGraph(query) {
|
|
134
|
+
if (!this.storage) return { entities: [], relationships: [] };
|
|
135
|
+
const result = await this.storage.executeQuery(query);
|
|
136
|
+
return { entities: result.entities, relationships: result.relationships };
|
|
137
|
+
}
|
|
138
|
+
async analyzeDependencies(entityId) {
|
|
139
|
+
if (!this.storage) return { root: entityId, children: [] };
|
|
140
|
+
const rels = await this.storage.getRelationshipsForEntity(entityId);
|
|
141
|
+
return {
|
|
142
|
+
root: entityId,
|
|
143
|
+
children: rels.filter((r) => r.fromId === entityId).map((r) => ({ root: r.toId, children: [] }))
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
async analyzeImpact(entityId) {
|
|
147
|
+
if (!this.storage) return { source: entityId, directImpact: [], transitiveImpact: [], riskLevel: "low" };
|
|
148
|
+
const rels = await this.storage.getRelationshipsForEntity(entityId);
|
|
149
|
+
const directImpact = rels.filter((r) => r.toId === entityId).map((r) => r.fromId);
|
|
150
|
+
const transitiveImpact = [];
|
|
151
|
+
for (const id of directImpact) {
|
|
152
|
+
const tRels = await this.storage.getRelationshipsForEntity(id);
|
|
153
|
+
for (const r of tRels) {
|
|
154
|
+
if (r.toId === id && !directImpact.includes(r.fromId) && r.fromId !== entityId) {
|
|
155
|
+
transitiveImpact.push(r.fromId);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
const total = directImpact.length + transitiveImpact.length;
|
|
160
|
+
const riskLevel = total > 50 ? "critical" : total > 20 ? "high" : total > 5 ? "medium" : "low";
|
|
161
|
+
return { source: entityId, directImpact, transitiveImpact, riskLevel };
|
|
162
|
+
}
|
|
163
|
+
async findPaths(_source, _target, _maxDepth) {
|
|
164
|
+
return [];
|
|
165
|
+
}
|
|
166
|
+
async findCycles(_entityId, _maxDepth) {
|
|
167
|
+
return [];
|
|
168
|
+
}
|
|
169
|
+
async analyzeHotspots(_filter) {
|
|
170
|
+
return [];
|
|
171
|
+
}
|
|
172
|
+
async analyzeRippleEffects(_changeSet) {
|
|
173
|
+
return [];
|
|
174
|
+
}
|
|
175
|
+
getQueryMetrics() {
|
|
176
|
+
const { queries, totalMs, hits, misses } = this.stats;
|
|
177
|
+
const total = hits + misses;
|
|
178
|
+
return {
|
|
179
|
+
totalQueries: queries,
|
|
180
|
+
totalTime: totalMs,
|
|
181
|
+
cacheHits: hits,
|
|
182
|
+
cacheMisses: misses,
|
|
183
|
+
avgQueryTime: queries > 0 ? Math.round(totalMs / queries) : 0,
|
|
184
|
+
cacheHitRate: total > 0 ? Math.round(hits / total * 100) : 0
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
export { QueryAgent };
|
|
190
|
+
//# sourceMappingURL=query-agent-HXQ3BMMF.js.map
|
|
191
|
+
//# sourceMappingURL=query-agent-HXQ3BMMF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-7YC4KTAW.js';import {b}from'./chunk-V5VLOVE7.js';import {d}from'./chunk-6K37BWK5.js';import'./chunk-RK5TLU72.js';import'./chunk-LESND2CW.js';import'./chunk-QUO46LUP.js';import'./chunk-3IFLFBQ4.js';import'./chunk-3X7W3DL2.js';import'./chunk-GVQNDMAK.js';import'./chunk-PZF7YC35.js';import'./chunk-NWQZW3Y6.js';import {g,b as b$1}from'./chunk-KXUWGHHN.js';import'./chunk-2KIPXYOB.js';import'./chunk-OG62YNVF.js';import {R,I}from'./chunk-4BI7EBPQ.js';import'./chunk-F45ISXCP.js';import'./chunk-DXB73IDG.js';import f from'p-limit';g();R();var y=class extends b{storage=null;ttlCache=new Map;cacheTtlMs=3e4;concurrencyLimiter;stats={queries:0,totalMs:0,hits:0,misses:0};taskDispatch=new Map([["query:entities",t=>this.findEntities(t)],["query:relationships",t=>{let{entityId:e,type:i}=t;return this.findRelationships(e,i)}],["query:graph",t=>this.getGraph(t)],["query:dependencies",t=>this.analyzeDependencies(t.entityId)],["query:impact",t=>this.analyzeImpact(t.entityId)]]);constructor(){let e=b$1().queryAgent,i=e?.maxConcurrency??10;super("query",{maxConcurrency:i,memoryLimit:e?.memoryLimit??112,priority:e?.priority??9}),this.concurrencyLimiter=f(i);}async handleMessage(t){}async onInitialize(){I.i("QUERYAGENT","init_start",{id:this.id}),this.storage=await d(),a.subscribe(this.id,"graph:updated",()=>{I.d("QUERYAGENT","graph_updated",{id:this.id}),this.ttlCache.clear();}),a.subscribe(this.id,"index:complete",()=>{I.d("QUERYAGENT","index_complete",{id:this.id}),this.ttlCache.clear();}),I.i("QUERYAGENT","init_done",{id:this.id});}async onShutdown(){I.i("QUERYAGENT","shutdown_start",{id:this.id}),this.ttlCache.clear(),I.i("QUERYAGENT","shutdown_done",{id:this.id});}canProcessTask(t){return t.type.startsWith("query:")}async processTask(t){let e=Date.now();try{let i=this.taskDispatch.get(t.type);if(!i)throw new Error(`Unknown query type: ${t.type}`);let s=await this.concurrencyLimiter(()=>i(t.payload));return this.stats.queries++,this.stats.totalMs+=Date.now()-e,s}catch(i){throw I.e("QUERYAGENT","query_fail",{id:this.id,err:String(i)}),i}}cacheGet(t){let e=this.ttlCache.get(t);return e?Date.now()>e.expiry?(this.ttlCache.delete(t),null):e.value:null}cacheSet(t,e){this.ttlCache.set(t,{value:e,expiry:Date.now()+this.cacheTtlMs});}async findEntities(t){if(!this.storage)return [];let e=`entities:${JSON.stringify(t)}`,i=this.cacheGet(e);if(i)return this.stats.hits++,i;this.stats.misses++;let s=await this.storage.searchEntities({namePattern:typeof t.name=="string"?t.name:t.name?.source,types:Array.isArray(t.type)?t.type:t.type?[t.type]:void 0,filePath:Array.isArray(t.filePath)?t.filePath[0]:t.filePath,limit:100});return this.cacheSet(e,s),s}async findRelationships(t,e){if(!this.storage)return [];let i=`rels:${t}:${e??"all"}`,s=this.cacheGet(i);if(s)return this.stats.hits++,s;this.stats.misses++;let r=await this.storage.getRelationshipsForEntity(t,e);return this.cacheSet(i,r),r}async getGraph(t){if(!this.storage)return {entities:[],relationships:[]};let e=await this.storage.executeQuery(t);return {entities:e.entities,relationships:e.relationships}}async analyzeDependencies(t){if(!this.storage)return {root:t,children:[]};let e=await this.storage.getRelationshipsForEntity(t);return {root:t,children:e.filter(i=>i.fromId===t).map(i=>({root:i.toId,children:[]}))}}async analyzeImpact(t){if(!this.storage)return {source:t,directImpact:[],transitiveImpact:[],riskLevel:"low"};let i=(await this.storage.getRelationshipsForEntity(t)).filter(a=>a.toId===t).map(a=>a.fromId),s=[];for(let a of i){let u=await this.storage.getRelationshipsForEntity(a);for(let o of u)o.toId===a&&!i.includes(o.fromId)&&o.fromId!==t&&s.push(o.fromId);}let r=i.length+s.length,m=r>50?"critical":r>20?"high":r>5?"medium":"low";return {source:t,directImpact:i,transitiveImpact:s,riskLevel:m}}async findPaths(t,e,i){return []}async findCycles(t,e){return []}async analyzeHotspots(t){return []}async analyzeRippleEffects(t){return []}getQueryMetrics(){let{queries:t,totalMs:e,hits:i,misses:s}=this.stats,r=i+s;return {totalQueries:t,totalTime:e,cacheHits:i,cacheMisses:s,avgQueryTime:t>0?Math.round(e/t):0,cacheHitRate:r>0?Math.round(i/r*100):0}}};export{y as QueryAgent};
|