agentic-qe 3.8.12 → 3.8.13
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/.claude/skills/qe-code-intelligence/SKILL.md +29 -20
- package/.claude/skills/qe-code-intelligence/evals/qe-code-intelligence.yaml +3 -3
- package/.claude/skills/qe-quality-assessment/SKILL.md +1 -1
- package/.claude/skills/qe-test-generation/SKILL.md +1 -1
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +21 -0
- package/README.md +9 -0
- package/assets/skills/qe-code-intelligence/SKILL.md +29 -20
- package/assets/skills/qe-code-intelligence/evals/qe-code-intelligence.yaml +3 -3
- package/assets/skills/qe-quality-assessment/SKILL.md +1 -1
- package/assets/skills/qe-test-generation/SKILL.md +1 -1
- package/dist/cli/bundle.js +716 -696
- package/dist/cli/commands/code.js +149 -11
- package/dist/cli/commands/init.js +3 -2
- package/dist/cli/handlers/init-handler.d.ts +1 -0
- package/dist/cli/handlers/init-handler.js +15 -10
- package/dist/cli/utils/file-discovery.d.ts +1 -0
- package/dist/cli/utils/file-discovery.js +1 -1
- package/dist/init/orchestrator.js +1 -0
- package/dist/init/phases/08-mcp.js +4 -4
- package/dist/init/phases/phase-interface.d.ts +3 -1
- package/dist/mcp/bundle.js +1 -1
- package/package.json +1 -1
package/dist/mcp/bundle.js
CHANGED
|
@@ -5782,7 +5782,7 @@ Pattern extracted from ${e.count} successful experiences.`}checkPromotion(e){let
|
|
|
5782
5782
|
`);for(let n of r.slice(0,10))t.push(`- \`${n}\``);t.push("")}return t.join(`
|
|
5783
5783
|
`)}generateOutputs(e){let t=e.reduce((i,o)=>i+o.totalTests,0),u=e.reduce((i,o)=>i+o.passed,0),a=e.reduce((i,o)=>i+o.failed,0),r=e.every(i=>i.success),n=e.length>0?e.reduce((i,o)=>i+o.coverage,0)/e.length:0;return{test_result:r?"success":"failure",total_tests:String(t),passed_tests:String(u),failed_tests:String(a),coverage_percent:String((n*100).toFixed(1)),phases_completed:String(e.length),phases_passed:String(e.filter(i=>i.success).length),has_flaky_tests:String(e.some(i=>i.flakyTests.length>0))}}writeAnnotation(e){let t=[`file=${e.file}`,`line=${e.line}`,`title=${e.title}`].join(",");console.log(`::${e.level} ${t}::${e.message}`)}extractLineNumber(e){if(!e)return;let t=e.match(/:(\d+):\d+/);return t?parseInt(t[1],10):void 0}formatDuration(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${(e/6e4).toFixed(1)}m`}generateCoverageBar(e){let t=Math.round(e*10),u=10-t;return"\u2588".repeat(t)+"\u2591".repeat(u)}}});var EW={};ue(EW,{DAGAttentionScheduler:()=>d0,createDAGAttentionScheduler:()=>UT});function UT(s){return new d0(s)}var d0,$T=f(()=>{"use strict";d0=class{executionHistory=[];learnedDurations=new Map;runCount=0;lastPrunedCount=0;learningRate;maxHistorySize;constructor(e){this.learningRate=e?.learningRate??.3,this.maxHistorySize=e?.maxHistorySize??1e4}buildTestDAG(e){let t=new Map,u=new Map;for(let n of e){let i=this.applyLearnedDuration(n);t.set(i.id,i),u.set(i.id,[])}for(let n of e)for(let i of n.dependencies){if(!t.has(i))throw new Error(`Test '${n.id}' depends on '${i}' which does not exist in the test set`);u.get(i).push(n.id)}let a=this.computeCriticalPath(t,u),r=this.computeParallelGroups(t,u);return{nodes:t,edges:u,criticalPath:a,parallelGroups:r}}findCriticalPath(e){return e.criticalPath.map(t=>e.nodes.get(t)).filter(t=>t!==void 0)}findParallelBranches(e){return e.parallelGroups.map(t=>t.map(u=>e.nodes.get(u)).filter(u=>u!==void 0))}pruneByMinCut(e,t){let u=this.sumDurations(e.nodes);if(u<=t)return this.lastPrunedCount=0,e;let a=this.computeAttentionScores(e),r=Array.from(a.entries()).sort((c,d)=>c[1]-d[1]),n=new Set(e.criticalPath),i=new Set,o=u;for(let[c]of r){if(o<=t)break;if(n.has(c)||(e.edges.get(c)??[]).some(p=>!i.has(p)))continue;let m=e.nodes.get(c);m&&(i.add(c),o-=m.estimatedDuration)}this.lastPrunedCount=i.size;let l=Array.from(e.nodes.values()).filter(c=>!i.has(c.id));return this.buildTestDAG(l)}schedule(e){if(e.length===0)return{phases:[],totalEstimatedTime:0,criticalPathTime:0,parallelism:0};let t=this.buildTestDAG(e),a=this.findParallelBranches(t).map(l=>({tests:l,canRunInParallel:l.length>1})),r=this.computeCriticalPathDuration(t),n=this.sumDurations(t.nodes),i=a.reduce((l,c)=>c.canRunInParallel?l+Math.max(...c.tests.map(d=>d.estimatedDuration)):l+c.tests.reduce((d,m)=>d+m.estimatedDuration,0),0),o=i>0?n/i:1;return this.runCount++,{phases:a,totalEstimatedTime:i,criticalPathTime:r,parallelism:o}}getOptimizationStats(){return{totalTests:0,criticalPathLength:0,parallelGroupCount:0,prunedTests:this.lastPrunedCount,estimatedTimeSaved:0,historicalRuns:this.runCount,usingNativeBackend:!1}}recordExecution(e,t,u){this.executionHistory.push({testId:e,actualDuration:t,result:u,timestamp:Date.now()}),this.executionHistory.length>this.maxHistorySize&&(this.executionHistory=this.executionHistory.slice(-this.maxHistorySize));let a=this.learnedDurations.get(e);a!==void 0?this.learnedDurations.set(e,a*(1-this.learningRate)+t*this.learningRate):this.learnedDurations.set(e,t)}getLearnedDuration(e){return this.learnedDurations.get(e)}isNativeBackendAvailable(){return!1}computeCriticalPath(e,t){let u=this.topologicalSort(e,t);if(u.length===0)return[];let a=new Map,r=new Map;for(let c of u)a.set(c,e.get(c).estimatedDuration),r.set(c,null);for(let c of u){let d=a.get(c);for(let m of t.get(c)??[]){let p=e.get(m);if(!p)continue;let g=d+p.estimatedDuration;g>(a.get(m)??0)&&(a.set(m,g),r.set(m,c))}}let n=0,i=null;for(let[c,d]of a)d>n&&(n=d,i=c);if(!i)return[];let o=[],l=i;for(;l!==null;)o.unshift(l),l=r.get(l)??null;return o}computeCriticalPathDuration(e){return e.criticalPath.reduce((t,u)=>t+(e.nodes.get(u)?.estimatedDuration??0),0)}computeParallelGroups(e,t){let u=this.topologicalSort(e,t);if(u.length===0)return[];let a=new Map;for(let[l,c]of e)a.set(l,new Set(c.dependencies));let r=new Map;for(let l of u){let c=-1;for(let d of a.get(l)??new Set){let m=r.get(d);m!==void 0&&m>c&&(c=m)}r.set(l,c+1)}let n=new Map;for(let l of u){let c=r.get(l)??0;n.has(c)||n.set(c,[]),n.get(c).push(l)}let i=Math.max(...Array.from(n.keys()),-1),o=[];for(let l=0;l<=i;l++){let c=n.get(l);c&&c.length>0&&o.push(c)}return o}computeAttentionScores(e){let t=new Map,u=this.countTransitiveDependents(e);for(let[a,r]of e.nodes){let n=r.lastResult==="fail"?2:1,i=u.get(a)??0;t.set(a,r.priority*n*(1+i))}return t}countTransitiveDependents(e){let t=new Map,u=new Map,a=r=>{if(u.has(r))return u.get(r);let n=new Set;for(let i of e.edges.get(r)??[]){n.add(i);for(let o of a(i))n.add(o)}return u.set(r,n),n};for(let r of e.nodes.keys())t.set(r,a(r).size);return t}topologicalSort(e,t){let u=new Map;for(let n of e.keys())u.set(n,0);for(let n of t.values())for(let i of n)u.has(i)&&u.set(i,(u.get(i)??0)+1);let a=[];for(let[n,i]of u)i===0&&a.push(n);let r=[];for(;a.length>0;){let n=a.shift();r.push(n);for(let i of t.get(n)??[]){let o=(u.get(i)??0)-1;u.set(i,o),o===0&&a.push(i)}}if(r.length!==e.size)throw new Error(`Cycle detected in test DAG: sorted ${r.length} of ${e.size} nodes`);return r}applyLearnedDuration(e){let t=this.learnedDurations.get(e.id);return t!==void 0?{...e,estimatedDuration:Math.round(t)}:e}sumDurations(e){let t=0;for(let u of e.values())t+=u.estimatedDuration;return t}}});async function WT(s){return ep.create(s)}async function fW(s){return(await WT(s)).run()}var ep,yW=f(()=>{"use strict";GT();VT();jT();KT();qT();ep=class s{constructor(e,t,u,a,r,n){this.config=e;this.selector=t,this.executor=u,this.scheduler=a,this.flakyTracker=r,this.reporter=n,this.ciEnvironment=Ey()}selector;executor;scheduler;flakyTracker;reporter;ciEnvironment;static async create(e){let t=e.flakyHistoryPath?await gy(e.flakyHistoryPath,e.flakyTracker):Zm(e.flakyTracker),u=new _i({...e.vitest,cwd:e.cwd,flakyTracker:t}),{ImpactAnalyzerService:a}=await Promise.resolve().then(()=>(Ks(),aO)),r=new a(e.memory),n=Jm({cwd:e.cwd,baseRef:e.baseRef,impactAnalyzer:r}),i=py(u,{...e.scheduler,phases:e.phases}),o=Xm(e.reporter);return new s(e,n,u,i,t,o)}async run(){let e=Date.now(),t=[],u=this.config.runAllTests??!1,a=performance.now();if(!u){let h=await this.selector.selectAffectedTests();h.runAllTests?(u=!0,console.log(`[TestSchedulingPipeline] Running all tests: ${h.runAllReason}`)):h.selectedTests.length===0?(console.log("[TestSchedulingPipeline] No affected tests found, running all"),u=!0):(t=h.selectedTests,console.log(`[TestSchedulingPipeline] Selected ${t.length} affected tests`))}let r=performance.now()-a;if(this.config.useDAGAttention&&t.length>0)try{let{isDAGAttentionEnabled:h}=await Promise.resolve().then(()=>(Be(),os));if(h()){let{createDAGAttentionScheduler:y}=await Promise.resolve().then(()=>($T(),EW)),D=y(),C=t.map(T=>({id:T,name:T,estimatedDuration:1e3,dependencies:[],priority:1,tags:[]})),k=D.schedule(C),F=[];for(let T of k.phases)F.push(...T.tests.map(P=>P.id));F.length>0&&(t=F)}}catch(h){process.env.DEBUG&&console.debug("[Pipeline] DAG attention scheduling skipped:",h instanceof Error?h.message:h)}let n=performance.now(),i;u?i=await this.scheduler.run():i=await this.runWithSelectedTests(t);let o=performance.now()-n,l=performance.now(),c=this.flakyTracker.analyze();this.config.flakyHistoryPath&&await hy(this.flakyTracker,this.config.flakyHistoryPath);let d=performance.now()-l,m=performance.now();this.ciEnvironment.isCI&&await this.reporter.writeOutput(i);let p=performance.now()-m,g=Date.now()-e;return{phaseResults:i,selectedTests:t,ranAllTests:u,flakyAnalysis:c,ciEnvironment:this.ciEnvironment,totalDurationMs:g,stepLatencies:{selectionMs:r,executionMs:o,analysisMs:d,reportingMs:p}}}async runPhase(e){return this.scheduler.runPhase(e)}getFlakyTracker(){return this.flakyTracker}getSelector(){return this.selector}getStats(){return this.scheduler.getStats()}async abort(){await this.scheduler.abort()}async runWithSelectedTests(e){let t=[],u=this.config.phases??[];for(let a of u){let r=e.filter(n=>a.testPatterns.some(i=>i.startsWith("!")?!1:this.patternToRegex(i).test(n)));if(r.length>0){let n=await this.executor.execute(a,r);t.push(n)}}return t}patternToRegex(e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*");return new RegExp(t)}}});var DW={};ue(DW,{DAGAttentionScheduler:()=>d0,DEFAULT_TEST_PHASES:()=>Um,FlakyTestTracker:()=>Qm,GitAwareTestSelector:()=>Wm,GitHubActionsReporter:()=>Ym,PhaseScheduler:()=>$m,TestSchedulingPipeline:()=>ep,VitestPhaseExecutor:()=>_i,checkQualityThresholds:()=>dW,createDAGAttentionScheduler:()=>UT,createFlakyTracker:()=>Zm,createGitHubActionsReporter:()=>Xm,createPhaseScheduler:()=>py,createTestPipeline:()=>WT,createTestSelector:()=>Jm,createVitestExecutor:()=>mW,detectCIEnvironment:()=>Ey,getAffectedTests:()=>gW,loadFlakyTracker:()=>gy,reportToGitHubActions:()=>hW,runTestPipeline:()=>fW,saveFlakyTracker:()=>hy});var CW=f(()=>{"use strict";HT();GT();VT();jT();KT();qT();yW();$T()});var fy,vW=f(()=>{"use strict";ke();B();fy=class extends J{config={name:"qe/tests/schedule",description:"Schedule and execute tests using phase-based pipeline with git-aware selection and flaky tracking. Runs tests in phases (unit, integration, e2e), selects affected tests from git changes, and tracks flaky tests.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{cwd:{type:"string",description:"Working directory for test execution (defaults to project root)"},gitRef:{type:"string",description:'Git ref to compare for affected test selection (e.g., "main", "HEAD~3")'},useGitAware:{type:"boolean",description:"Enable git-aware test selection to only run affected tests",default:!0},trackFlaky:{type:"boolean",description:"Enable flaky test tracking and quarantine",default:!0}}}}async execute(e,t){try{let{runTestPipeline:u}=await Promise.resolve().then(()=>(CW(),DW)),a=await d2(t),r=await u({cwd:e.cwd||process.cwd(),memory:a,baseRef:e.gitRef,flakyHistoryPath:e.trackFlaky!==!1?".agentic-qe/flaky-history.json":void 0,runAllTests:e.useGitAware===!1}),n=r.phaseResults.reduce((l,c)=>l+c.totalTests,0),i=r.phaseResults.reduce((l,c)=>l+c.passed,0),o=r.phaseResults.reduce((l,c)=>l+c.failed,0);return{success:!0,data:{pipelineId:t.requestId,phases:r.phaseResults.map(l=>({phaseId:l.phaseId,phaseName:l.phaseName,totalTests:l.totalTests,passed:l.passed,failed:l.failed,passRate:l.passRate,durationMs:l.durationMs})),gitAware:{enabled:!r.ranAllTests,selectedTests:r.selectedTests.length,gitRef:e.gitRef},flakyTracking:{enabled:e.trackFlaky!==!1},totalDuration:r.totalDurationMs,ranAllTests:r.ranAllTests,summary:`Executed ${r.phaseResults.length} phases, ${n} tests (${i} passed, ${o} failed) in ${r.totalDurationMs}ms`}}}catch(u){return{success:!1,error:A(u)}}}}});function yy(s){return new tp(s)}var Dyt,tp,JT=f(()=>{"use strict";Z1();Dyt={maxEvents:1e5,memorySampleInterval:1e3,enableTimeline:!0,timelineSampleInterval:1e3},tp=class{config;activeAgents=new Map;peakAgentCount=0;totalAgentsSpawned=0;activeTasks=new Map;totalTasksStarted=0;totalTasksCompleted=0;coordinationLatencies;taskDurations;memorySnapshots;peakMemoryUsed=0;memorySum=0;memorySamples=0;agentTimeline=[];latencyTimeline=[];memoryTimeline=[];startTime=0;endTime=0;running=!1;memorySamplerTimer=null;timelineSamplerTimer=null;issues=[];constructor(e={}){this.config={...Dyt,...e},this.coordinationLatencies=new rt(this.config.maxEvents),this.taskDurations=new rt(this.config.maxEvents),this.memorySnapshots=new rt(1e4)}start(){this.running||(this.running=!0,this.startTime=Date.now(),this.memorySamplerTimer=setInterval(()=>{this.sampleMemory()},this.config.memorySampleInterval),this.config.enableTimeline&&(this.timelineSamplerTimer=setInterval(()=>{this.sampleTimeline()},this.config.timelineSampleInterval)))}stop(){this.running&&(this.running=!1,this.endTime=Date.now(),this.memorySamplerTimer&&(clearInterval(this.memorySamplerTimer),this.memorySamplerTimer=null),this.timelineSamplerTimer&&(clearInterval(this.timelineSamplerTimer),this.timelineSamplerTimer=null))}reset(){this.stop(),this.activeAgents.clear(),this.peakAgentCount=0,this.totalAgentsSpawned=0,this.activeTasks.clear(),this.totalTasksStarted=0,this.totalTasksCompleted=0,this.coordinationLatencies.clear(),this.taskDurations.clear(),this.memorySnapshots.clear(),this.peakMemoryUsed=0,this.memorySum=0,this.memorySamples=0,this.agentTimeline.length=0,this.latencyTimeline.length=0,this.memoryTimeline.length=0,this.startTime=0,this.endTime=0,this.issues.length=0}recordAgentSpawn(e,t=Date.now()){this.activeAgents.set(e,t),this.totalAgentsSpawned++;let u=this.activeAgents.size;u>this.peakAgentCount&&(this.peakAgentCount=u)}recordAgentTerminate(e,t=Date.now()){this.activeAgents.delete(e)}recordTaskStart(e,t,u=Date.now()){this.activeTasks.set(t,{agentId:e,startTime:u}),this.totalTasksStarted++}recordTaskComplete(e,t,u,a=Date.now()){let r=this.activeTasks.get(t);r&&r.agentId===e&&(this.activeTasks.delete(t),this.taskDurations.push(u),this.totalTasksCompleted++)}recordCoordination(e,t,u=Date.now()){this.coordinationLatencies.push(t),t>100&&this.issues.push(`High coordination latency for agent ${e}: ${t}ms`)}recordMemoryUsage(e,t){let u={timestamp:Date.now(),heapUsed:e,heapTotal:t,external:0,rss:0};this.memorySnapshots.push(u),this.memorySum+=e,this.memorySamples++,e>this.peakMemoryUsed&&(this.peakMemoryUsed=e);let a=4*1024*1024*1024;e>a&&this.issues.push(`Memory exceeded 4GB limit: ${(e/1024/1024/1024).toFixed(2)}GB`)}recordIssue(e){this.issues.push(e)}getAgentCount(){return this.activeAgents.size}getPeakAgentCount(){return this.peakAgentCount}getTotalAgentsSpawned(){return this.totalAgentsSpawned}getP95CoordinationLatency(){return this.calculatePercentile(this.coordinationLatencies.toArray(),.95)}getP99CoordinationLatency(){return this.calculatePercentile(this.coordinationLatencies.toArray(),.99)}getCoordinationLatencyPercentiles(){return this.calculatePercentiles(this.coordinationLatencies.toArray())}getTaskLatencyPercentiles(){return this.calculatePercentiles(this.taskDurations.toArray())}getMaxMemoryUsage(){return this.peakMemoryUsed}getAverageMemoryUsage(){return this.memorySamples>0?this.memorySum/this.memorySamples:0}getThroughput(){let t=this.getDuration()/1e3;return{tasks:this.totalTasksCompleted,tasksPerSecond:t>0?this.totalTasksCompleted/t:0,agents:this.totalAgentsSpawned,agentsPerSecond:t>0?this.totalAgentsSpawned/t:0}}getDuration(){return this.startTime===0?0:(this.endTime>0?this.endTime:Date.now())-this.startTime}hasAgentStarvation(){let e=this.activeAgents.size,t=this.activeTasks.size;return e>0&&t===0&&this.totalTasksCompleted>0}hasDeadlocks(){let e=Date.now(),t=6e4,u=Array.from(this.activeTasks.values());for(let a of u)if(e-a.startTime>t)return!0;return!1}exportReport(){let e=this.getDuration(),t=this.getCoordinationLatencyPercentiles(),u=this.getTaskLatencyPercentiles(),a=this.getThroughput(),r=100,n=4*1024*1024*1024,o={agentCount:this.peakAgentCount>=r,memoryLimit:this.peakMemoryUsed<n,coordinationLatency:t.p95<=100,noDeadlocks:!this.hasDeadlocks(),noStarvation:!this.hasAgentStarvation()},l=Object.values(o).every(Boolean),c=this.generateRecommendations(t,this.peakMemoryUsed,a);return{summary:{totalAgents:this.totalAgentsSpawned,peakAgents:this.peakAgentCount,totalTasks:this.totalTasksCompleted,duration:e,success:l,successCriteria:o},performance:{coordinationLatency:t,taskLatency:u,throughput:a},resources:{memoryPeak:this.peakMemoryUsed,memoryAverage:this.getAverageMemoryUsage(),cpuPeak:0,cpuAverage:0},timeline:{agentCounts:[...this.agentTimeline],latencies:[...this.latencyTimeline],memoryUsage:[...this.memoryTimeline]},issues:[...this.issues],recommendations:c}}sampleMemory(){let e=process.memoryUsage();this.recordMemoryUsage(e.heapUsed,e.heapTotal)}sampleTimeline(){let e=Date.now();this.agentTimeline.push({timestamp:e,count:this.activeAgents.size});let t=this.coordinationLatencies.toArray();t.length>0&&this.latencyTimeline.push({timestamp:e,p95:this.calculatePercentile(t,.95)});let u=process.memoryUsage();this.memoryTimeline.push({timestamp:e,heapUsed:u.heapUsed});let a=1e3;this.agentTimeline.length>a&&this.agentTimeline.shift(),this.latencyTimeline.length>a&&this.latencyTimeline.shift(),this.memoryTimeline.length>a&&this.memoryTimeline.shift()}calculatePercentile(e,t){if(e.length===0)return 0;let u=[...e].sort((r,n)=>r-n),a=Math.ceil(u.length*t)-1;return u[Math.max(0,a)]}calculatePercentiles(e){if(e.length===0)return{p50:0,p95:0,p99:0,max:0,min:0,avg:0,count:0};let t=[...e].sort((a,r)=>a-r),u=t.reduce((a,r)=>a+r,0);return{p50:this.calculatePercentile(t,.5),p95:this.calculatePercentile(t,.95),p99:this.calculatePercentile(t,.99),max:t[t.length-1],min:t[0],avg:u/t.length,count:t.length}}generateRecommendations(e,t,u){let a=[];e.p95>100&&a.push(`P95 coordination latency (${e.p95.toFixed(1)}ms) exceeds 100ms target. Consider optimizing gossip protocol or reducing agent count.`),e.p99>e.p95*2&&a.push("High P99/P95 ratio indicates latency outliers. Investigate specific agents or network conditions.");let r=t/1024/1024/1024;return r>3&&a.push(`Memory usage (${r.toFixed(2)}GB) approaching 4GB limit. Consider implementing agent pooling or reducing per-agent memory.`),u.tasksPerSecond<10&&a.push(`Task throughput (${u.tasksPerSecond.toFixed(1)}/s) is low. Consider parallelizing task execution or reducing task complexity.`),this.issues.length>10&&a.push(`${this.issues.length} issues recorded. Review issue log for patterns and prioritize fixes.`),a}}});function Dy(s){return new m0(s)}function Cy(s){return new m0({thresholds:{...up,...s}})}var up,QT,m0,ZT=f(()=>{"use strict";up={memoryWarning:3*1024*1024*1024,memoryCritical:4*1024*1024*1024,latencyP95Warning:75,latencyP95Critical:100,latencyP99Warning:150,latencyP99Critical:200,agentStarvationTime:3e4,deadlockTimeout:6e4,minTasksPerSecond:5,minAgentUtilization:.5,gossipConvergenceTime:5e3,gossipMaxPartitions:0},QT={thresholds:up,enableDetailedAnalysis:!0},m0=class{config;constructor(e={}){this.config={...QT,...e,thresholds:{...up,...e.thresholds}}}analyze(e){let t=[];t.push(this.checkMemoryPressure(e)),t.push(this.checkCoordinationLatencyP95(e)),t.push(this.checkCoordinationLatencyP99(e)),t.push(this.checkAgentStarvation(e)),t.push(this.checkDeadlocks(e)),t.push(this.checkThroughput(e));let u=t.filter(i=>i.detected),a={totalChecks:t.length,detected:u.length,critical:u.filter(i=>i.severity==="critical").length,high:u.filter(i=>i.severity==="high").length,medium:u.filter(i=>i.severity==="medium").length,low:u.filter(i=>i.severity==="low").length},r="low";a.critical>0?r="critical":a.high>0?r="high":a.medium>0&&(r="medium");let n=this.generatePrioritizedRecommendations(u);return{overallSeverity:r,hasCritical:a.critical>0,bottlenecks:t,summary:a,recommendations:n,timestamp:new Date}}analyzeReport(e){let t=[];t.push(this.checkMemoryFromReport(e)),t.push(this.checkLatencyP95FromReport(e)),t.push(this.checkLatencyP99FromReport(e)),t.push(this.checkThroughputFromReport(e)),t.push(this.checkSuccessCriteria(e));let u=t.filter(i=>i.detected),a={totalChecks:t.length,detected:u.length,critical:u.filter(i=>i.severity==="critical").length,high:u.filter(i=>i.severity==="high").length,medium:u.filter(i=>i.severity==="medium").length,low:u.filter(i=>i.severity==="low").length},r="low";a.critical>0?r="critical":a.high>0?r="high":a.medium>0&&(r="medium");let n=this.generatePrioritizedRecommendations(u);return{overallSeverity:r,hasCritical:a.critical>0,bottlenecks:t,summary:a,recommendations:n,timestamp:new Date}}checkMemoryPressure(e){let t=e?.getMaxMemoryUsage()??process.memoryUsage().heapUsed,{memoryWarning:u,memoryCritical:a}=this.config.thresholds,r=t>=u,n="low",i="Memory usage is within acceptable limits.";return t>=a?(n="critical",i="Memory usage exceeds 4GB limit. Implement agent pooling, reduce per-agent state, or decrease concurrent agent count."):t>=u&&(n="high",i="Memory usage approaching critical threshold. Consider optimizing agent memory footprint or implementing memory pressure relief mechanisms."),{detected:r,severity:n,metric:"memory_pressure",threshold:a,actual:t,recommendation:i,context:{usedGB:t/1024/1024/1024,warningThresholdGB:u/1024/1024/1024,criticalThresholdGB:a/1024/1024/1024}}}checkCoordinationLatency(){return this.checkCoordinationLatencyP95()}checkCoordinationLatencyP95(e){let t=e?.getP95CoordinationLatency()??0,{latencyP95Warning:u,latencyP95Critical:a}=this.config.thresholds,r=t>=u,n="low",i="P95 coordination latency is within acceptable limits.";return t>=a?(n="critical",i="P95 coordination latency exceeds 100ms target. Optimize gossip protocol, reduce message size, or implement batching."):t>=u&&(n="medium",i="P95 coordination latency approaching target. Monitor closely and consider proactive optimization."),{detected:r,severity:n,metric:"coordination_latency_p95",threshold:a,actual:t,recommendation:i}}checkCoordinationLatencyP99(e){let t=e?.getP99CoordinationLatency()??0,{latencyP99Warning:u,latencyP99Critical:a}=this.config.thresholds,r=t>=u,n="low",i="P99 coordination latency is within acceptable limits.";return t>=a?(n="high",i="P99 coordination latency indicates outliers. Investigate specific agents or network conditions causing delays."):t>=u&&(n="medium",i="P99 coordination latency elevated. Some agents may be experiencing delays."),{detected:r,severity:n,metric:"coordination_latency_p99",threshold:a,actual:t,recommendation:i}}checkAgentStarvation(e){let t=e?.hasAgentStarvation()??!1;return{detected:t,severity:t?"high":"low",metric:"agent_starvation",threshold:this.config.thresholds.agentStarvationTime,actual:t?1:0,recommendation:t?"Agent starvation detected. Agents are idle without tasks. Review task distribution algorithm and work stealing configuration.":"No agent starvation detected."}}checkDeadlocks(e){let t=e?.hasDeadlocks()??!1;return{detected:t,severity:t?"critical":"low",metric:"deadlock_detection",threshold:this.config.thresholds.deadlockTimeout,actual:t?1:0,recommendation:t?"Potential deadlock detected. Tasks running for extended period. Review lock ordering and add timeout mechanisms.":"No deadlocks detected."}}checkGossipStability(){return{detected:!1,severity:"low",metric:"gossip_stability",threshold:this.config.thresholds.gossipMaxPartitions,actual:0,recommendation:"Gossip protocol stability check requires integration with gossip metrics."}}checkThroughput(e){let u=e?.getThroughput()?.tasksPerSecond??0,a=this.config.thresholds.minTasksPerSecond,r=u<a&&u>0;return{detected:r,severity:r?"medium":"low",metric:"throughput",threshold:a,actual:u,recommendation:r?`Task throughput (${u.toFixed(1)}/s) below minimum (${a}/s). Consider parallelizing task execution or optimizing task handlers.`:"Task throughput is acceptable."}}checkMemoryFromReport(e){let t=e.resources.memoryPeak,{memoryCritical:u}=this.config.thresholds;return{detected:t>=u,severity:t>=u?"critical":"low",metric:"memory_pressure",threshold:u,actual:t,recommendation:t>=u?"Memory exceeded 4GB limit during test.":"Memory usage within limits."}}checkLatencyP95FromReport(e){let t=e.performance.coordinationLatency.p95,{latencyP95Critical:u}=this.config.thresholds;return{detected:t>=u,severity:t>=u?"critical":"low",metric:"coordination_latency_p95",threshold:u,actual:t,recommendation:t>=u?"P95 coordination latency exceeded 100ms target.":"P95 latency within target."}}checkLatencyP99FromReport(e){let t=e.performance.coordinationLatency.p99,{latencyP99Critical:u}=this.config.thresholds;return{detected:t>=u,severity:t>=u?"high":"low",metric:"coordination_latency_p99",threshold:u,actual:t,recommendation:t>=u?"P99 coordination latency indicates significant outliers.":"P99 latency acceptable."}}checkThroughputFromReport(e){let t=e.performance.throughput.tasksPerSecond,u=this.config.thresholds.minTasksPerSecond;return{detected:t<u&&t>0,severity:t<u?"medium":"low",metric:"throughput",threshold:u,actual:t,recommendation:t<u?"Throughput below minimum target.":"Throughput acceptable."}}checkSuccessCriteria(e){let t=e.summary.successCriteria,u=Object.entries(t).filter(([a,r])=>!r).map(([a])=>a);return{detected:u.length>0,severity:u.length>0?"high":"low",metric:"success_criteria",threshold:0,actual:u.length,recommendation:u.length>0?`Failed criteria: ${u.join(", ")}`:"All success criteria met.",context:{failedCriteria:u}}}generatePrioritizedRecommendations(e){let t={critical:0,high:1,medium:2,low:3},u=[...e].sort((n,i)=>t[n.severity]-t[i.severity]),a=new Set,r=[];for(let n of u)a.has(n.recommendation)||(a.add(n.recommendation),r.push(`[${n.severity.toUpperCase()}] ${n.metric}: ${n.recommendation}`));return r}}});function FW(s,e,t){return new p0(s,e,t)}function SW(s,e="medium"){return new p0({maxAgents:s,workloadProfile:e,mockMode:!0})}var YT,XT,ap,bW,AW,xW,kW,p0,BW=f(()=>{"use strict";O();JT();B();ZT();YT={maxAgents:100,memoryLimit:4*1024*1024*1024,coordinationTimeout:100,workloadProfile:"medium",mockMode:!0},XT={agentCount:100,memoryLimit:4*1024*1024*1024,coordinationLatency:100,noAgentStarvation:!0,noDeadlocks:!0,gossipStable:!0},ap={light:{taskCount:5,taskDuration:50,memoryUsage:5*1024*1024,coordinationFrequency:2,durationVariance:.1},medium:{taskCount:10,taskDuration:100,memoryUsage:10*1024*1024,coordinationFrequency:5,durationVariance:.2},heavy:{taskCount:20,taskDuration:200,memoryUsage:20*1024*1024,coordinationFrequency:10,durationVariance:.3}},bW={name:"ramp-up-100",description:"Gradually add agents until reaching 100",steps:[{agents:25,holdTime:3e4},{agents:50,holdTime:3e4},{agents:75,holdTime:3e4},{agents:100,holdTime:6e4}],workload:ap.medium},AW={name:"burst-100",description:"Instantly spawn 100 agents",steps:[{agents:100,holdTime:12e4}],workload:{taskCount:20,taskDuration:50,memoryUsage:10*1024*1024,coordinationFrequency:5}},xW={name:"churn-100",description:"Maintain 100 agents with continuous spawn/terminate",steps:[{agents:100,holdTime:18e4,churnRate:.1}],workload:{taskCount:15,taskDuration:75,memoryUsage:10*1024*1024,coordinationFrequency:5}},kW={name:"stress-150",description:"Push beyond 100 agents to find limits",steps:[{agents:100,holdTime:3e4},{agents:125,holdTime:3e4},{agents:150,holdTime:6e4}],workload:ap.heavy,criteria:{agentCount:150}},p0=class{config;metrics;analyzer;running=!1;stopRequested=!1;mockAgents=new Map;mockTaskTimers=new Map;mockCoordinationTimers=new Map;churnTimer=null;random;constructor(e={},t,u){this.config={...YT,...e},this.metrics=yy(t),this.analyzer=u?Cy(u):Dy(),this.random=this.config.seed!==void 0?this.seededRandom(this.config.seed):Math.random.bind(Math)}async runTest(e,t){let u={name:"custom",description:`Custom test with ${e} agents for ${t}ms`,steps:[{agents:e,holdTime:t}],workload:this.getWorkload()};return this.runScenario(u)}async runScenario(e){if(this.running)throw new Error("Load test already running");this.running=!0,this.stopRequested=!1;let t=Date.now();try{this.metrics.reset(),this.metrics.start();for(let i of e.steps){if(this.stopRequested)break;await this.executeStep(i,e.workload)}this.metrics.stop();let u=this.metrics.exportReport(),a=this.analyzer.analyzeReport(u),r={...XT,...e.criteria};return{success:this.evaluateSuccess(u,r),report:u,bottlenecks:a,config:this.config,duration:Date.now()-t}}catch(u){return this.metrics.stop(),{success:!1,report:this.metrics.exportReport(),bottlenecks:this.analyzer.analyze(this.metrics),config:this.config,duration:Date.now()-t,error:A(u)}}finally{await this.cleanup(),this.running=!1}}async rampUp(e,t){let u=this.mockAgents.size,a=e-u;if(a<=0)return;let r=t/a,n=this.getWorkload();for(let i=0;i<a&&!this.stopRequested;i++)await this.spawnMockAgent(n),await this.delay(r)}async simulateAgent(e,t){let u=Date.now(),a=0,r=0;for(let n=0;n<t.taskCount&&!this.stopRequested;n++){let i=`${e}_task_${n}`,o=Date.now();this.metrics.recordTaskStart(e,i,o);let l=t.durationVariance??.2,c=t.taskDuration*(1+(this.random()-.5)*2*l);await this.delay(c),this.metrics.recordTaskComplete(e,i,Date.now()-o),a++;let d=this.simulateCoordinationLatency();this.metrics.recordCoordination(e,d),r++}return{agentId:e,tasksCompleted:a,totalDuration:Date.now()-u,coordinationEvents:r}}async stop(){this.stopRequested=!0,await this.delay(100),await this.cleanup()}getMetrics(){return this.metrics}getAgentCount(){return this.mockAgents.size}isRunning(){return this.running}async executeStep(e,t){let u=e.agents,a=this.mockAgents.size;u>a?await this.spawnAgents(u-a,t):u<a&&await this.terminateAgents(a-u),e.churnRate&&e.churnRate>0&&this.startChurn(e.churnRate,u,t),await this.hold(e.holdTime),this.stopChurn()}async spawnAgents(e,t){let u=[];for(let a=0;a<e&&!this.stopRequested;a++)u.push(this.spawnMockAgent(t)),u.length>=10&&(await Promise.all(u),u.length=0,await this.delay(10));u.length>0&&await Promise.all(u)}async terminateAgents(e){let t=Array.from(this.mockAgents.keys()).slice(0,e);for(let u of t)await this.terminateMockAgent(u)}async hold(e){let u=0;for(;u<e&&!this.stopRequested;)await this.delay(100),u+=100}startChurn(e,t,u){let r=6e4/Math.ceil(t*e);this.churnTimer=setInterval(async()=>{if(this.random()<.5){let n=Array.from(this.mockAgents.keys());if(n.length>0){let i=n[Math.floor(this.random()*n.length)];await this.terminateMockAgent(i)}}this.mockAgents.size<t&&await this.spawnMockAgent(u)},r)}stopChurn(){this.churnTimer&&(clearInterval(this.churnTimer),this.churnTimer=null)}async spawnMockAgent(e){let t=`agent_${x().slice(0,8)}`,u=Date.now(),a={id:t,domain:this.getRandomDomain(),spawnedAt:u,workload:e,activeTasks:0,totalTasks:0,terminated:!1};this.mockAgents.set(t,a),this.metrics.recordAgentSpawn(t,u),this.startAgentTasks(a),this.startAgentCoordination(a),this.simulateMemoryUsage()}async terminateMockAgent(e){let t=this.mockAgents.get(e);if(!t)return;t.terminated=!0;let u=this.mockTaskTimers.get(e);u&&(clearInterval(u),this.mockTaskTimers.delete(e));let a=this.mockCoordinationTimers.get(e);a&&(clearInterval(a),this.mockCoordinationTimers.delete(e)),this.mockAgents.delete(e),this.metrics.recordAgentTerminate(e,Date.now())}startAgentTasks(e){let t=e.workload.taskDuration*1.5,u=setInterval(()=>{if(e.terminated||e.totalTasks>=e.workload.taskCount){clearInterval(u),this.mockTaskTimers.delete(e.id);return}let a=`${e.id}_task_${e.totalTasks}`,r=Date.now();e.activeTasks++,e.totalTasks++,this.metrics.recordTaskStart(e.id,a,r);let n=e.workload.durationVariance??.2,i=e.workload.taskDuration*(1+(this.random()-.5)*2*n);setTimeout(()=>{e.terminated||(e.activeTasks--,this.metrics.recordTaskComplete(e.id,a,Date.now()-r))},i)},t);this.mockTaskTimers.set(e.id,u)}startAgentCoordination(e){let t=1e3/e.workload.coordinationFrequency,u=setInterval(()=>{if(e.terminated){clearInterval(u),this.mockCoordinationTimers.delete(e.id);return}let a=this.simulateCoordinationLatency();this.metrics.recordCoordination(e.id,a)},t);this.mockCoordinationTimers.set(e.id,u)}simulateCoordinationLatency(){let t=this.random()*30,u=this.random()<.05?this.random()*100:0,r=Math.min(this.mockAgents.size/100,2)*10;return 5+t+u+r}simulateMemoryUsage(){let e=this.mockAgents.size,t=this.getWorkload().memoryUsage,u=50*1024*1024,a=e*t,r=e*1024*100,n=u+a+r,i=n*1.5;this.metrics.recordMemoryUsage(n,i)}getRandomDomain(){let e=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","security-compliance"];return e[Math.floor(this.random()*e.length)]}getWorkload(){return this.config.customWorkload?this.config.customWorkload:ap[this.config.workloadProfile]}evaluateSuccess(e,t){let{summary:u,performance:a}=e;return!(u.peakAgents<t.agentCount||e.resources.memoryPeak>=t.memoryLimit||a.coordinationLatency.p95>t.coordinationLatency||t.noAgentStarvation&&!u.successCriteria.noStarvation||t.noDeadlocks&&!u.successCriteria.noDeadlocks)}async cleanup(){this.stopChurn();let e=Array.from(this.mockAgents.keys());for(let t of e)await this.terminateMockAgent(t);this.mockTaskTimers.forEach(t=>{clearInterval(t)}),this.mockTaskTimers.clear(),this.mockCoordinationTimers.forEach(t=>{clearInterval(t)}),this.mockCoordinationTimers.clear()}delay(e){return new Promise(t=>setTimeout(t,e))}seededRandom(e){return function(){let t=e+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}}}});var TW={};ue(TW,{AgentLoadTester:()=>p0,BottleneckAnalyzer:()=>m0,DEFAULT_ANALYZER_CONFIG:()=>QT,DEFAULT_LOAD_TEST_CONFIG:()=>YT,DEFAULT_SUCCESS_CRITERIA:()=>XT,DEFAULT_THRESHOLDS:()=>up,MetricsCollector:()=>tp,SCENARIO_BURST_100:()=>AW,SCENARIO_CHURN_100:()=>xW,SCENARIO_RAMP_UP_100:()=>bW,SCENARIO_STRESS_150:()=>kW,WORKLOAD_PROFILES:()=>ap,createAgentLoadTester:()=>FW,createBottleneckAnalyzer:()=>Dy,createBottleneckAnalyzerWithThresholds:()=>Cy,createLoadTesterForTarget:()=>SW,createMetricsCollector:()=>yy});var wW=f(()=>{"use strict";BW();JT();ZT()});var vy,RW=f(()=>{"use strict";ke();B();vy=class extends J{config={name:"qe/tests/load",description:"Run agent load tests to validate fleet scalability. Supports light, medium, and heavy workload profiles. Uses mock agents by default (safe); set mockMode=false to test with real fleet agents (requires fleet_init). Reports bottlenecks and pass/fail criteria.",domain:"test-execution",schema:this.buildSchema(),timeout:3e5};buildSchema(){return{type:"object",properties:{targetAgents:{type:"number",description:"Target number of concurrent agents to simulate",default:10,minimum:1,maximum:200},profile:{type:"string",description:"Workload profile: light, medium, or heavy",enum:["light","medium","heavy"],default:"medium"},durationMs:{type:"number",description:"Test duration in milliseconds",default:3e4,minimum:5e3,maximum:3e5},mockMode:{type:"boolean",description:"Use mock agents (true, default) or real fleet agents (false, requires fleet_init)",default:!0}}}}async execute(e,t){try{let{createAgentLoadTester:u}=await Promise.resolve().then(()=>(wW(),TW)),a=e.profile||"medium",r=e.targetAgents||10,n=e.durationMs||3e4,i=e.mockMode!==!1,l=await u({maxAgents:r,workloadProfile:a,mockMode:i}).runTest(r,n),c=l.bottlenecks;return{success:!0,data:{testId:t.requestId,profile:a,targetAgents:r,duration:l.duration,mockMode:i,passed:l.success,bottleneckCount:c?.bottlenecks?.length??0,report:{overallSeverity:c?.overallSeverity??"none",hasCritical:c?.hasCritical??!1,checksPerformed:c?.summary?.totalChecks??0,bottlenecksDetected:c?.summary?.detected??0},summary:`Load test (${a}, ${i?"mock":"real"}): ${r} agents, ${n}ms \u2014 ${l.success?"PASSED":"FAILED"}`+(c?.hasCritical?" [CRITICAL BOTTLENECKS]":"")}}}catch(u){return{success:!1,error:A(u)}}}}});var Cyt,by,PW=f(()=>{"use strict";ke();B();Cyt=[{type:"email",pattern:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,mask:s=>s[0]+"***@"+s.split("@")[1]},{type:"ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g,mask:()=>"***-**-****"},{type:"credit-card",pattern:/\b(?:\d[ -]*?){13,19}\b/g,mask:s=>"****-****-****-"+s.replace(/\D/g,"").slice(-4)},{type:"phone",pattern:/\b(?:\+?1[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}\b/g,mask:s=>s.slice(0,3)+"***"+s.slice(-2)},{type:"api-key",pattern:/(?:key|token|api_key|apikey|secret|password|passwd|auth)=([A-Za-z0-9_\-]{16,})/gi,mask:()=>"***REDACTED***"}],by=class extends J{config={name:"qe/security/url-validate",description:"Validate URL security: checks for XSS/injection patterns, unsafe protocols, and scans URL query parameters for PII exposure (emails, SSNs, credit cards, API keys).",domain:"security-compliance",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{url:{type:"string",description:"URL to validate for security threats and PII exposure"},enablePII:{type:"boolean",description:"Enable PII exposure scanning in URL and query parameters",default:!0}},required:["url"]}}async execute(e,t){try{let u=this.validateURLSecurity(e.url),a=e.enablePII!==!1?this.scanForPII(e.url):{scanned:!1,found:!1,types:[],details:[]},n=u.issues.length+(a.found?a.types.length:0)===0?`URL passed all checks (security: clean, PII: ${a.scanned?"none found":"not scanned"})`:`URL has ${u.issues.length} security issue(s)${a.found?` and ${a.types.length} PII type(s) exposed in URL`:""}`;return{success:!0,data:{url:e.url,urlSecurity:u,piiExposure:a,summary:n}}}catch(u){return{success:!1,error:A(u)}}}validateURLSecurity(e){let t=[],u="none";try{let a=new URL(e);["http:","https:"].includes(a.protocol)||(t.push({type:"unsafe-protocol",description:`Protocol ${a.protocol} is not allowed`,severity:"high"}),u="high");let r=[/<script/i,/javascript:/i,/on\w+=/i,/data:text\/html/i];for(let o of r)if(o.test(e)){t.push({type:"xss",description:"Potential XSS pattern detected in URL",severity:"critical"}),u="critical";break}let n=[/'.*or.*'/i,/union.*select/i,/drop.*table/i,/;\s*--/i];for(let o of n)if(o.test(e)){t.push({type:"sql-injection",description:"Potential SQL injection pattern detected in URL",severity:"critical"}),u="critical";break}/\.\.[/\\]/.test(e)&&(t.push({type:"path-traversal",description:"Potential path traversal pattern (../) detected",severity:"high"}),u!=="critical"&&(u="high"));let i=["redirect","url","next","return","returnUrl","goto"];for(let o of i){let l=a.searchParams.get(o);l&&/^https?:\/\//.test(l)&&(t.push({type:"open-redirect",description:`Query parameter "${o}" contains an external URL \u2014 potential open redirect`,severity:"medium"}),u==="none"&&(u="medium"))}}catch{t.push({type:"invalid-url",description:"URL could not be parsed",severity:"critical"}),u="critical"}return{valid:t.length===0,riskLevel:u,issues:t}}scanForPII(e){let t=[],u=new Set,a;try{a=decodeURIComponent(e)}catch{a=e}let r="",n="";try{let i=new URL(a);r=i.search,n=i.pathname}catch{r=a}for(let{type:i,pattern:o,mask:l}of Cyt){o.lastIndex=0;let c;for(;(c=o.exec(a))!==null;){u.add(i);let d=r.includes(c[0])?"query-parameter":n.includes(c[0])?"path":"url";t.push({type:i,location:d,masked:l(c[0])})}}return{scanned:!0,found:u.size>0,types:Array.from(u),details:t}}}});import{readFile as MW,readdir as vyt}from"fs/promises";import{join as e9,basename as byt}from"path";import{parse as IW}from"yaml";function t9(s,e){return s.replace(/\{\{([^}]+)\}\}/g,(t,u)=>{let r=u.trim().split("."),n=e;for(let i of r)if(n&&typeof n=="object"&&i in n)n=n[i];else return t;return n!=null?String(n):t})}function LW(s,e){let t={...e.variables,result:e.results.get("__last_result__")},u=t9(s,t);return zh(u,t,!1)}var rp,NW,zW=f(()=>{"use strict";UA();rp=class{templatesDir;cache=new Map;constructor(e){this.templatesDir=e||e9(__dirname,"templates")}async load(e){if(this.cache.has(e))return this.cache.get(e);try{let t=e9(this.templatesDir,`${e}.yaml`),u=await MW(t,"utf-8"),a=IW(u),r=await this.validate(a);if(!r.valid)throw new Error(`Invalid workflow template ${e}:
|
|
5784
5784
|
${r.errors.join(`
|
|
5785
|
-
`)}`);return this.cache.set(e,a),a}catch(t){throw t.code==="ENOENT"?new Error(`Workflow template not found: ${e}`):t}}async list(){try{return(await vyt(this.templatesDir)).filter(t=>t.endsWith(".yaml")||t.endsWith(".yml")).map(t=>byt(t,t.endsWith(".yaml")?".yaml":".yml")).sort()}catch(e){if(e.code==="ENOENT")return[];throw e}}async validate(e){let t=[],u=[];if(e.name||t.push("Workflow must have a name"),e.version||t.push("Workflow must have a version"),e.description||u.push("Workflow should have a description"),Array.isArray(e.variables)?e.variables.forEach((a,r)=>{a.name||t.push(`Variable at index ${r} must have a name`),a.type||t.push(`Variable ${a.name} must have a type`),a.required===void 0&&u.push(`Variable ${a.name} should specify if it's required`)}):t.push("Workflow must have a variables array"),!Array.isArray(e.steps))t.push("Workflow must have a steps array");else if(e.steps.length===0)t.push("Workflow must have at least one step");else{e.steps.forEach((n,i)=>{n.name||t.push(`Step at index ${i} must have a name`),n.action||t.push(`Step ${n.name||i} must have an action`),(!n.config||typeof n.config!="object")&&t.push(`Step ${n.name||i} must have a config object`),n.assertions&&Array.isArray(n.assertions)&&n.assertions.forEach((o,l)=>{o.condition||t.push(`Assertion ${l} in step ${n.name||i} must have a condition`),o.message||u.push(`Assertion ${l} in step ${n.name||i} should have a message`)})});let a=e.steps.map(n=>n.name),r=a.filter((n,i)=>a.indexOf(n)!==i);r.length>0&&t.push(`Duplicate step names found: ${r.join(", ")}`)}return{valid:t.length===0,errors:t,warnings:u}}async createContext(e,t){let u=await this.load(e),a=u.variables.filter(n=>n.required&&!(n.name in t)).map(n=>n.name);if(a.length>0)throw new Error(`Missing required variables: ${a.join(", ")}`);let r={};return u.variables.forEach(n=>{n.name in t?r[n.name]=t[n.name]:"default"in n&&(r[n.name]=n.default)}),{variables:r,results:new Map,metadata:{startTime:Date.now(),workflow:u.name,templateName:e}}}async getMetadata(e){try{let t=e9(this.templatesDir,`${e}.yaml`),u=await MW(t,"utf-8"),a=IW(u);return{name:a.name,version:a.version,description:a.description}}catch(t){throw t.code==="ENOENT"?new Error(`Workflow template not found: ${e}`):t}}clearCache(){this.cache.clear()}async reload(e){return this.cache.delete(e),this.load(e)}},NW=new rp});var OW={};ue(OW,{WORKFLOW_CATEGORIES:()=>a9,WORKFLOW_DESCRIPTIONS:()=>_W,WORKFLOW_TEMPLATES:()=>u9,WorkflowLoader:()=>rp,defaultWorkflowLoader:()=>NW,evaluateCondition:()=>LW,getAllWorkflowTemplates:()=>kyt,getWorkflowsByCategory:()=>Ayt,interpolateVariables:()=>t9,isValidWorkflowTemplate:()=>xyt});function Ayt(s){return a9[s]}function xyt(s){return u9.includes(s)}function kyt(){return u9.map(s=>{let e=Object.entries(a9).find(([t,u])=>u.includes(s))?.[0]||"other";return{name:s,description:_W[s],category:e}})}var u9,_W,a9,HW=f(()=>{"use strict";zW();u9=["login-flow","oauth-flow","scraping-workflow","visual-regression","form-validation","navigation-flow","api-integration","performance-audit","accessibility-audit"],_W={"login-flow":"Authentication testing workflow for login forms with credential validation","oauth-flow":"OAuth2/OIDC authentication testing workflow with provider integration","scraping-workflow":"Data extraction workflow for web scraping with pagination and structured output","visual-regression":"Screenshot comparison workflow for visual regression testing across breakpoints","form-validation":"Input validation testing workflow for form fields with error handling","navigation-flow":"Multi-page navigation workflow for testing user journeys and state persistence","api-integration":"Browser-API hybrid testing workflow for validating frontend-backend integration","performance-audit":"Lighthouse-style performance audit workflow with Core Web Vitals","accessibility-audit":"WCAG 2.1 Level AA compliance audit workflow with automated accessibility testing"},a9={authentication:["login-flow","oauth-flow"],testing:["form-validation","navigation-flow","api-integration"],quality:["visual-regression","performance-audit","accessibility-audit"],automation:["scraping-workflow"]}});var Ay,GW=f(()=>{"use strict";ke();B();Ay=class extends J{config={name:"qe/workflows/browser-load",description:"Load, validate, and prepare browser automation workflows from inline YAML or built-in templates. Returns the resolved workflow with steps and variable bindings, ready for browser execution. Templates: login-flow, form-validation, visual-regression, oauth-flow, etc.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{workflowYaml:{type:"string",description:"Inline YAML workflow definition. Mutually exclusive with templateName."},templateName:{type:"string",description:"Built-in template name to load.",enum:["login-flow","oauth-flow","scraping-workflow","visual-regression","form-validation","navigation-flow","api-integration","performance-audit","accessibility-audit"]},variables:{type:"object",description:'Runtime variable overrides (e.g., { "baseUrl": "https://example.com" })'}}}}async execute(e,t){try{let{WorkflowLoader:u,WORKFLOW_TEMPLATES:a,WORKFLOW_DESCRIPTIONS:r,interpolateVariables:n}=await Promise.resolve().then(()=>(HW(),OW)),{parse:i}=await import("yaml"),o=new u,l=[...a],c=r;if(!e.workflowYaml&&!e.templateName)return{success:!0,data:{workflowName:"none",description:"No workflow specified. Use templateName or workflowYaml.",source:"none",templateUsed:null,steps:[],variables:{defined:[],provided:{}},validation:{valid:!0,errors:[],warnings:[]},availableTemplates:l,summary:`Available templates: ${l.join(", ")}`}};let d,m,p=null;e.workflowYaml?(m="inline-yaml",d=i(e.workflowYaml)):(m="template",p=e.templateName,d=await o.load(e.templateName));let g=await o.validate(d),h=(d.steps??[]).map(y=>{let D=y.config;if(e.variables){let C={};for(let[k,F]of Object.entries(D))C[k]=typeof F=="string"?n(F,e.variables):F;D=C}return{name:y.name,action:y.action,config:D,optional:y.optional??!1,assertionCount:y.assertions?.length??0}});return{success:!0,data:{workflowName:d.name||p||"custom",description:d.description||p&&c[p]||"",source:m,templateUsed:p,steps:h,variables:{defined:(d.variables??[]).map(y=>({name:y.name,type:y.type,required:y.required,hasDefault:y.default!==void 0})),provided:e.variables||{}},validation:{valid:g.valid,errors:g.errors,warnings:g.warnings},availableTemplates:l,summary:g.valid?`Workflow "${d.name}" loaded (${m}): ${h.length} steps, ${(d.variables??[]).length} variables`:`Workflow "${d.name}" has validation errors: ${g.errors.join("; ")}`}}}catch(u){return{success:!1,error:A(u)}}}}});function VW(){for(let s of r9)s.resetInstanceCache()}var RMu,r9,n9=f(()=>{"use strict";VU();jU();r$();n$();i$();s$();g$();h$();y$();C$();v$();b$();k$();F$();N$();W$();Q$();iW();cW();vW();RW();PW();GW();RMu={TEST_GENERATE:"qe/tests/generate",TEST_EXECUTE:"qe/tests/execute",COVERAGE_ANALYZE:"qe/coverage/analyze",COVERAGE_GAPS:"qe/coverage/gaps",QUALITY_EVALUATE:"qe/quality/evaluate",DEFECT_PREDICT:"qe/defects/predict",REQUIREMENTS_VALIDATE:"qe/requirements/validate",QUALITY_CRITERIA:"qe/requirements/quality-criteria",CODE_ANALYZE:"qe/code/analyze",SECURITY_SCAN:"qe/security/scan",CONTRACT_VALIDATE:"qe/contracts/validate",VISUAL_COMPARE:"qe/visual/compare",A11Y_AUDIT:"qe/a11y/audit",CHAOS_INJECT:"qe/chaos/inject",LEARNING_OPTIMIZE:"qe/learning/optimize",LEARNING_DREAM:"qe/learning/dream",TOKEN_USAGE:"qe/analysis/token_usage",GOAP_PLAN:"qe/planning/goap_plan",GOAP_EXECUTE:"qe/planning/goap_execute",GOAP_STATUS:"qe/planning/goap_status",...Lm,EMBEDDING_GENERATE:"qe/embeddings/generate",EMBEDDING_COMPARE:"qe/embeddings/compare",EMBEDDING_SEARCH:"qe/embeddings/search",EMBEDDING_STORE:"qe/embeddings/store",EMBEDDING_STATS:"qe/embeddings/stats",...nW,QX_ANALYZE:"qe/qx/analyze",TEST_SCHEDULE:"qe/tests/schedule",LOAD_TEST:"qe/tests/load",URL_VALIDATE:"qe/security/url-validate",BROWSER_WORKFLOW:"qe/workflows/browser-load"},r9=[new zf,new _f,new Hf,new Gf,new Vf,new Kf,new qf,new Sm,new $f,new Wf,new Jf,new Qf,new Zf,new Yf,new Bm,new Tm,new Xf,new Mm,new Im,new Nm,...$$,new r0,new n0,new i0,new s0,new o0,...rW,new qm,new fy,new vy,new by,new Ay]});var cn,xy,jW=f(()=>{"use strict";O();z();Ec();B();cn={ProtocolStarted:"coordination.ProtocolStarted",ProtocolCompleted:"coordination.ProtocolCompleted",ProtocolFailed:"coordination.ProtocolFailed",ProtocolCancelled:"coordination.ProtocolCancelled",ActionStarted:"coordination.ActionStarted",ActionCompleted:"coordination.ActionCompleted",ActionFailed:"coordination.ActionFailed"},xy=class{constructor(e,t,u){this.eventBus=e;this.memory=t;this.getDomainAPI=u}protocols=new Map;executions=new Map;scheduledProtocols=new Map;schedulerRunning=!1;registerProtocol(e){this.protocols.set(e.id,e),e.schedule.type==="event"&&e.enabled&&this.setupEventTriggers(e),(e.schedule.type==="cron"||e.schedule.type==="interval")&&e.enabled&&this.scheduleProtocol(e)}unregisterProtocol(e){if(!this.protocols.get(e))return!1;let u=this.scheduledProtocols.get(e);return u?.intervalId&&clearInterval(u.intervalId),this.scheduledProtocols.delete(e),this.protocols.delete(e),!0}getProtocol(e){return this.protocols.get(e)}listProtocols(){return Array.from(this.protocols.values())}async execute(e,t){let u=this.protocols.get(e);return u?u.enabled?this.executeProtocol(u,t):E(new Error(`Protocol is disabled: ${e}`)):E(new Error(`Protocol not found: ${e}`))}async executeOnEvent(e,t){let u=this.protocols.get(e);return u?u.enabled?this.executeProtocol(u,void 0,t):E(new Error(`Protocol is disabled: ${e}`)):E(new Error(`Protocol not found: ${e}`))}getExecution(e){let t=this.executions.get(e);if(t)return this.toImmutableExecution(t.execution)}listActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.execution.status==="running"||e.execution.status==="paused").map(e=>this.toImmutableExecution(e.execution))}async cancelExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"&&t.execution.status!=="paused"?E(new Error(`Cannot cancel execution in status: ${t.execution.status}`)):(t.cancelled=!0,t.execution.status="cancelled",t.execution.completedAt=new Date,await this.publishEvent(cn.ProtocolCancelled,{executionId:e,protocolId:t.protocol.id}),v(void 0)):E(new Error(`Execution not found: ${e}`))}async pauseExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"?E(new Error(`Cannot pause execution in status: ${t.execution.status}`)):(t.paused=!0,t.execution.status="paused",v(void 0)):E(new Error(`Execution not found: ${e}`))}async resumeExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="paused"?E(new Error(`Cannot resume execution in status: ${t.execution.status}`)):(t.paused=!1,t.execution.status="running",v(void 0)):E(new Error(`Execution not found: ${e}`))}startScheduler(){if(!this.schedulerRunning){this.schedulerRunning=!0;for(let e of this.protocols.values())e.enabled&&(e.schedule.type==="interval"||e.schedule.type==="cron")&&this.scheduleProtocol(e)}}stopScheduler(){this.schedulerRunning=!1;for(let e of this.scheduledProtocols.values())e.intervalId&&(clearInterval(e.intervalId),e.intervalId=void 0)}async dispose(){this.stopScheduler(),this.protocols.clear(),this.executions.clear(),this.scheduledProtocols.clear()}async executeProtocol(e,t,u){let a=x(),r=u?.correlationId??a,n={executionId:a,protocolId:e.id,status:"running",participants:[...e.participants],results:new Map,startedAt:new Date,correlationId:r,triggeredBy:u},i={execution:n,protocol:e,params:t,actionResults:new Map,cancelled:!1,paused:!1};this.executions.set(a,i),await this.publishEvent(cn.ProtocolStarted,{executionId:a,protocolId:e.id,participants:e.participants},r);try{await this.executeActions(i);let o=Array.from(i.actionResults.values()).some(l=>l.status==="failed");return i.cancelled?n.status="cancelled":o?(n.status="failed",await this.publishEvent(cn.ProtocolFailed,{executionId:a,protocolId:e.id,failedActions:Array.from(i.actionResults.values()).filter(l=>l.status==="failed").map(l=>l.actionId)},r)):(n.status="completed",await this.publishEvent(cn.ProtocolCompleted,{executionId:a,protocolId:e.id,duration:Date.now()-n.startedAt.getTime()},r)),n.completedAt=new Date,n.results=i.actionResults,await this.storeExecutionHistory(n),v(this.toImmutableExecution(n))}catch(o){return n.status="failed",n.completedAt=new Date,await this.publishEvent(cn.ProtocolFailed,{executionId:a,protocolId:e.id,error:A(o)},r),E(b(o))}}async executeActions(e){let{protocol:t,actionResults:u}=e,a=new Set(t.actions.map(n=>n.id)),r=new Set;for(;a.size>0&&!e.cancelled;){for(;e.paused&&!e.cancelled;)await this.sleep(100);if(e.cancelled)break;let n=t.actions.filter(o=>a.has(o.id)&&this.dependenciesSatisfied(o,r));if(n.length===0&&a.size>0)throw new Error(`Deadlock detected: actions ${Array.from(a).join(", ")} cannot proceed`);let i=await Promise.allSettled(n.map(o=>this.executeAction(o,e)));for(let o=0;o<n.length;o++){let l=n[o],c=i[o],d;c.status==="fulfilled"?d=c.value:d={actionId:l.id,status:"failed",error:c.reason instanceof Error?c.reason.message:String(c.reason)},u.set(l.id,d),a.delete(l.id),d.status==="completed"&&r.add(l.id)}}for(let n of a)u.set(n,{actionId:n,status:e.cancelled?"cancelled":"skipped"})}async executeAction(e,t){let u=new Date;await this.publishEvent(cn.ActionStarted,{executionId:t.execution.executionId,actionId:e.id,actionName:e.name,targetDomain:e.targetDomain},t.execution.correlationId);let a=0,r=e.retry?.maxAttempts??1,n;for(;a<r;){a++;try{let o=this.getDomainAPI(e.targetDomain);if(!o)throw new Error(`Domain API not available: ${e.targetDomain}`);let l=o[e.method];if(typeof l!="function")throw new Error(`Method ${e.method} not found on domain ${e.targetDomain}`);let c={...e.params,...t.params},d=await this.executeWithTimeout(l.bind(o)(c),e.timeout??3e4),m=new Date;return await this.publishEvent(cn.ActionCompleted,{executionId:t.execution.executionId,actionId:e.id,duration:m.getTime()-u.getTime()},t.execution.correlationId),{actionId:e.id,status:"completed",startedAt:u,completedAt:m,duration:m.getTime()-u.getTime(),result:d,retryAttempts:a>1?a-1:void 0}}catch(o){if(n=b(o),a<r&&e.retry){let l=e.retry.backoffMs*Math.pow(e.retry.backoffMultiplier??2,a-1);await this.sleep(l)}}}let i=new Date;return await this.publishEvent(cn.ActionFailed,{executionId:t.execution.executionId,actionId:e.id,error:n?.message??"Unknown error",attempts:a},t.execution.correlationId),{actionId:e.id,status:"failed",startedAt:u,completedAt:i,duration:i.getTime()-u.getTime(),error:n?.message??"Unknown error",retryAttempts:a>1?a-1:void 0}}dependenciesSatisfied(e,t){return!e.dependsOn||e.dependsOn.length===0?!0:e.dependsOn.every(u=>t.has(u))}async executeWithTimeout(e,t){return Promise.race([e,new Promise((u,a)=>setTimeout(()=>a(new Error("Action timeout")),t))])}setupEventTriggers(e){if(e.schedule.type==="event")for(let t of e.schedule.triggerEvents)this.eventBus.subscribe(t,async u=>{await this.executeOnEvent(e.id,u)})}scheduleProtocol(e){if(e.schedule.type==="interval"){let t={protocolId:e.id,schedule:e.schedule};t.intervalId=setInterval(async()=>{this.schedulerRunning&&await this.execute(e.id)},e.schedule.intervalMs),this.scheduledProtocols.set(e.id,t)}}async storeExecutionHistory(e){let t=`protocol-execution:${e.executionId}`;await this.memory.set(t,{...e,results:Object.fromEntries(e.results)},{namespace:"coordination",ttl:864e5})}toImmutableExecution(e){return{executionId:e.executionId,protocolId:e.protocolId,status:e.status,participants:[...e.participants],results:new Map(e.results),startedAt:e.startedAt,completedAt:e.completedAt,correlationId:e.correlationId,triggeredBy:e.triggeredBy}}async publishEvent(e,t,u){let a=X(e,"learning-optimization",t,u);await this.eventBus.publish(a)}sleep(e){return new Promise(t=>setTimeout(t,e))}}});async function Oi(s){return i9.getInstance(s)}async function KW(s,e,t){return(await Oi()).startTaskTrajectory(s,e,t)}async function ky(s,e,t){return(await Oi()).endTaskTrajectory(s,e,t)}var Fyt,i9,qW=f(()=>{"use strict";CS();Qd();X3();Fyt={enableLearning:!0,enableRouting:!0,enableGuidance:!0,enableTrajectories:!0,enableExperienceReplay:!0,autoStoreExperiences:!0,minQualityThreshold:.6},i9=class s{static instance=null;static initPromise=null;config;enhancedAdapter;disposed=!1;patternsLoaded=!1;qualityThresholdsFromPatterns=null;tasksRecorded=0;successfulTasks=0;failedTasks=0;patternsStored=0;routingRequests=0;activeTrajectories=new Map;constructor(e,t){this.config=e,this.enhancedAdapter=t}static async getInstance(e){if(s.instance&&!s.instance.disposed)return s.instance;if(s.initPromise)return s.initPromise;s.initPromise=s.create(e);try{return s.instance=await s.initPromise,s.instance}finally{s.initPromise=null}}static async create(e){let t={...Fyt,...e},u=Xj({enableTrajectories:t.enableTrajectories,enableExperienceReplay:t.enableExperienceReplay,enablePatternEvolution:!0,autoStoreExperiences:t.autoStoreExperiences,autoConsolidate:!0});await u.initialize();let a=new s(t,u);return await a.loadPatternsFromLoader(),await a.seedInitialPatternsIfNeeded(),console.error("[ReasoningBankService] Initialized with EnhancedReasoningBankAdapter (trajectory + experience + evolution)"),a}async loadPatternsFromLoader(){try{let t=await Si().getQualityGateThresholds();if(t){this.qualityThresholdsFromPatterns=t,this.patternsLoaded=!0,console.error("[ReasoningBankService] Loaded quality thresholds from PatternLoader",{tiers:Object.keys(t)});return}console.error("[ReasoningBankService] PatternLoader returned no thresholds, using defaults")}catch(e){console.error("[ReasoningBankService] Failed to load patterns from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.patternsLoaded=!1}async seedInitialPatternsIfNeeded(){try{let e=await this.enhancedAdapter.getStats();if(e.reasoningBank.totalPatterns>0){console.error(`[ReasoningBankService] Found ${e.reasoningBank.totalPatterns} existing patterns, skipping seed`);return}console.error("[ReasoningBankService] Seeding initial QE patterns...");let t=(a,r="string",n=!1)=>({name:a,type:r,required:n,description:`${a} parameter`}),u=[{patternType:"test-template",name:"unit-test-generation",description:"Generate comprehensive unit tests for TypeScript/JavaScript modules",domain:"test-generation",template:{type:"workflow",content:"Analyze module exports, identify edge cases, generate Jest/Vitest tests with proper mocking",variables:[t("modulePath"),t("framework")]},context:{tags:["unit","typescript","jest","vitest"]}},{patternType:"coverage-strategy",name:"coverage-gap-analysis",description:"Identify untested code paths and recommend targeted tests",domain:"coverage-analysis",template:{type:"workflow",content:"Parse coverage report, identify uncovered branches, prioritize by risk, generate recommendations",variables:[t("coveragePath"),t("threshold","number")]},context:{tags:["coverage","analysis","risk"]}},{patternType:"test-template",name:"integration-test-generation",description:"Generate integration tests for API endpoints and service interactions",domain:"test-generation",template:{type:"workflow",content:"Identify API contracts, generate request/response tests, validate error handling",variables:[t("apiPath"),t("framework")]},context:{tags:["integration","api","contract"]}},{patternType:"flaky-fix",name:"flaky-test-remediation",description:"Detect and fix flaky tests through pattern analysis",domain:"test-execution",template:{type:"workflow",content:"Analyze test history, identify timing/race conditions, apply stabilization patterns",variables:[t("testPath"),t("retryCount","number")]},context:{tags:["flaky","stability","retry"]}},{patternType:"error-handling",name:"security-vulnerability-scan",description:"Scan code for security vulnerabilities using OWASP patterns",domain:"security-compliance",template:{type:"workflow",content:"Run SAST analysis, check for injection risks, validate authentication/authorization",variables:[t("targetPath"),t("severity")]},context:{tags:["security","owasp","sast"]}}];for(let a of u)try{await this.enhancedAdapter.storePattern(a),this.patternsStored++}catch(r){console.error(`[ReasoningBankService] Failed to seed pattern ${a.name}:`,r)}console.error(`[ReasoningBankService] Seeded ${u.length} initial patterns`)}catch(e){console.error("[ReasoningBankService] Failed to seed patterns:",e)}}getPatternsLoaded(){return this.patternsLoaded}getQualityThresholdsFromPatterns(){return this.qualityThresholdsFromPatterns}async startTaskTrajectory(e,t,u={}){if(!this.config.enableTrajectories||this.disposed)return e;try{let a=await this.enhancedAdapter.startTaskTrajectory(t,u);return this.activeTrajectories.set(e,a),console.error(`[ReasoningBankService] Started trajectory: task=${e} trajectory=${a}`),a}catch(a){return console.error("[ReasoningBankService] Failed to start trajectory:",a),e}}async recordTrajectoryStep(e,t,u,a){if(!this.config.enableTrajectories||this.disposed)return;let r=this.activeTrajectories.get(e);if(!r){console.error(`[ReasoningBankService] No active trajectory for task ${e}`);return}try{await this.enhancedAdapter.recordTaskStep(r,t,u,a)}catch(n){console.error("[ReasoningBankService] Failed to record trajectory step:",n)}}async endTaskTrajectory(e,t,u){if(!this.config.enableTrajectories||this.disposed)return null;let a=this.activeTrajectories.get(e);if(!a)return console.error(`[ReasoningBankService] No active trajectory for task ${e}`),null;try{let r=await this.enhancedAdapter.endTaskTrajectory(a,t,u);return this.activeTrajectories.delete(e),console.error(`[ReasoningBankService] Ended trajectory: task=${e} success=${t} steps=${r.steps.length} quality=${r.metrics.averageQuality.toFixed(2)}`),r}catch(r){return console.error("[ReasoningBankService] Failed to end trajectory:",r),this.activeTrajectories.delete(e),null}}getActiveTrajectoryId(e){return this.activeTrajectories.get(e)}async recordTaskOutcome(e){if(!(!this.config.enableLearning||this.disposed)){this.tasksRecorded++,e.success?this.successfulTasks++:this.failedTasks++;try{let t={patternId:`task-${e.taskId}`,success:e.success,metrics:{executionTimeMs:e.executionTimeMs,testsPassed:e.metrics?.testsPassed,testsFailed:e.metrics?.testsGenerated?e.metrics.testsGenerated-(e.metrics.testsPassed||0):void 0,coverageImprovement:e.metrics?.coverageImprovement},feedback:e.error};await this.enhancedAdapter.recordPatternOutcome(t),e.success&&(e.qualityScore||.5)>=this.config.minQualityThreshold&&(await this.storeTaskPattern(e),this.patternsStored++),e.agentId&&await this.updateAgentPerformanceFromOutcome(e),console.error(`[ReasoningBankService] Recorded outcome: task=${e.taskId} success=${e.success} quality=${e.qualityScore?.toFixed(2)||"N/A"}`)}catch(t){throw console.error("[ReasoningBankService] Failed to record outcome:",t),t}}}async updateAgentPerformanceFromOutcome(e){if(e.agentId)try{pK(e.agentId,{success:e.success,executionTimeMs:e.executionTimeMs,qualityScore:e.qualityScore}),console.error(`[ReasoningBankService] Updated agent performance: agent=${e.agentId} success=${e.success} duration=${e.executionTimeMs}ms`)}catch(t){console.error("[ReasoningBankService] Failed to update agent performance:",t)}}async storeTaskPattern(e){try{let t=[e.taskType,e.domain||"general",e.agentId?`agent:${e.agentId}`:void 0,e.modelTier?`tier:${e.modelTier}`:void 0,e.executionTimeMs?`duration:${e.executionTimeMs}ms`:void 0].filter(u=>u!==void 0);await this.enhancedAdapter.storePattern({patternType:"test-template",name:`${e.taskType}-${e.domain||"general"}`,description:e.task,template:{type:"workflow",content:e.task,variables:[]},context:{tags:t}})}catch(t){console.error("[ReasoningBankService] Failed to store pattern:",t)}}async getRoutingRecommendation(e){if(!this.config.enableRouting||this.disposed)return this.createFallbackRouting(e);this.routingRequests++;try{let t=await this.enhancedAdapter.routeTaskWithExperience(e);if(!t.success)return console.error("[ReasoningBankService] Routing returned error:",t.error),this.createFallbackRouting(e);let u=t.value;return u.experienceGuidance&&console.error(`[ReasoningBankService] Experience guidance: strategy="${u.experienceGuidance.recommendedStrategy}" confidence=${u.experienceGuidance.confidence.toFixed(2)} tokenSavings=${u.experienceGuidance.estimatedTokenSavings}`),console.error(`[ReasoningBankService] Routing: task="${e.task.slice(0,50)}..." -> agent=${u.recommendedAgent} confidence=${u.confidence.toFixed(2)}`),u}catch(t){return console.error("[ReasoningBankService] Routing failed:",t),this.createFallbackRouting(e)}}async getExperienceGuidance(e,t){if(!this.config.enableExperienceReplay||this.disposed)return null;try{return await this.enhancedAdapter.getExperienceGuidance(e,t)}catch(u){return console.error("[ReasoningBankService] Failed to get experience guidance:",u),null}}async getTaskGuidance(e,t){if(!this.config.enableGuidance||this.disposed)return[];try{let u=await this.enhancedAdapter.routeTaskWithExperience({task:e,domain:t});return u.success?u.value.guidance:[]}catch(u){return console.error("[ReasoningBankService] Guidance failed:",u),[]}}async searchPatterns(e,t){if(this.disposed)return[];try{let u=await this.enhancedAdapter.searchPatterns(e,{limit:t?.limit||10,domain:t?.domain});return u.success?u.value.map(a=>a.pattern):(console.error("[ReasoningBankService] Search returned error:",u.error),[])}catch(u){return console.error("[ReasoningBankService] Search failed:",u),[]}}async getStats(){let e=await this.enhancedAdapter.getStats();return{service:{tasksRecorded:this.tasksRecorded,successfulTasks:this.successfulTasks,failedTasks:this.failedTasks,successRate:this.tasksRecorded>0?this.successfulTasks/this.tasksRecorded:0,patternsStored:this.patternsStored,routingRequests:this.routingRequests,patternsLoaded:this.patternsLoaded,activeTrajectories:this.activeTrajectories.size},reasoningBank:e.reasoningBank,adapter:e.adapter}}createFallbackRouting(e){return{recommendedAgent:"qe-test-architect",confidence:.5,alternatives:[],domains:e.domain?[e.domain]:["test-generation"],patterns:[],guidance:[],reasoning:"Fallback routing - ReasoningBank unavailable",latencyMs:0}}isHealthy(){return!this.disposed}async dispose(){this.disposed||(this.disposed=!0,await this.enhancedAdapter.dispose(),this.activeTrajectories.clear(),s.instance=null,console.error("[ReasoningBankService] Disposed"))}static reset(){s.instance&&s.instance.dispose(),s.instance=null,s.initPromise=null}}});var o9={};ue(o9,{handleModelRoute:()=>Ry,handleReasoningBankStats:()=>Ryt,handleRoutingEconomics:()=>My,handleRoutingMetrics:()=>Py,handleTaskCancel:()=>Ty,handleTaskList:()=>Sy,handleTaskOrchestrate:()=>wy,handleTaskOutcomeRecord:()=>wyt,handleTaskStatus:()=>By,handleTaskStatusWithLearning:()=>Pyt,handleTaskSubmit:()=>Fy,subscribeTrajectoryEvents:()=>Myt,unsubscribeTrajectoryEvents:()=>WW});async function Fy(s){if(!ye())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=fe();try{let t=await e.submitTask({type:s.type,priority:s.priority||"p1",targetDomains:s.targetDomains||[],payload:s.payload||{},timeout:s.timeout||3e5});if(!t.success)return{success:!1,error:t.error.message};let u=e.getTaskStatus(t.value);return{success:!0,data:{taskId:t.value,type:s.type,priority:s.priority||"p1",status:u?.status==="running"?"pending":"queued",assignedDomain:u?.assignedDomain}}}catch(t){return{success:!1,error:`Failed to submit task: ${A(t)}`}}}async function Sy(s){if(!ye())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=fe();try{let t=e.listTasks({status:s.status,priority:s.priority,domain:s.domain});return{success:!0,data:(typeof s.limit=="number"?t.slice(0,s.limit):t).map(r=>({taskId:r.taskId,type:r.task.type,status:r.status,priority:r.task.priority,assignedDomain:r.assignedDomain,assignedAgents:r.assignedAgents,result:r.result,error:r.error,createdAt:r.task.createdAt.toISOString(),startedAt:r.startedAt?.toISOString(),completedAt:r.completedAt?.toISOString(),duration:r.completedAt&&r.startedAt?r.completedAt.getTime()-r.startedAt.getTime():void 0}))}}catch(t){return{success:!1,error:`Failed to list tasks: ${A(t)}`}}}async function By(s){if(!ye())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=fe();try{let t=e.getTaskStatus(s.taskId);return t?{success:!0,data:{taskId:t.taskId,type:t.task.type,status:t.status,priority:t.task.priority,assignedDomain:t.assignedDomain,assignedAgents:t.assignedAgents,result:s.detailed?t.result:void 0,error:t.error,createdAt:t.task.createdAt.toISOString(),startedAt:t.startedAt?.toISOString(),completedAt:t.completedAt?.toISOString(),duration:t.completedAt&&t.startedAt?t.completedAt.getTime()-t.startedAt.getTime():void 0}}:{success:!1,error:`Task not found: ${s.taskId}`}}catch(t){return{success:!1,error:`Failed to get task status: ${A(t)}`}}}async function Ty(s){if(!ye())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=fe();try{let t=await e.cancelTask(s.taskId);return t.success?{success:!0,data:{taskId:s.taskId,cancelled:!0}}:{success:!1,error:t.error.message}}catch(t){return{success:!1,error:`Failed to cancel task: ${A(t)}`}}}async function wy(s){if(!ye())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e,workflowOrchestrator:t}=fe();try{let u=s.context?.project||$W(s.task),a=s.priority==="critical"||/\b(security|vulnerability|cve|owasp|critical|production|exploit)\b/i.test(s.task),n=await(await rn()).routeTask({task:s.task,codeContext:s.codeContext,filePaths:s.filePaths,manualTier:s.manualTier,isCritical:a,agentType:`qe-${u}`,domain:u,metadata:{inferredDomain:u,hasCodeContext:!!s.codeContext,fileCount:s.filePaths?.length}}),o=await(await Oi()).getExperienceGuidance(s.task,s.context?.project),l=Byt(s.task),c=Tyt(s.priority||"medium"),d=Syt[l];if(d&&t){console.log(`[TaskOrchestrate] Task type '${l}' has workflow '${d}' - executing workflow`);let h=s.task.match(/https?:\/\/[^\s]+/i),y=h?h[0]:void 0;y&&console.log(`[TaskOrchestrate] Detected URL for analysis: ${y}`);let D={targetId:s.context?.project||y||`task-${Date.now()}`,targetType:y?"website":"epic",description:s.task,acceptanceCriteria:s.context?.requirements||[],url:y,routing:{tier:n.decision.tier,modelId:n.modelId,executionStrategy:n.executionStrategy,complexity:n.decision.complexityAnalysis.overall}},C=await t.executeWorkflow(d,D);return C.success?{success:!0,data:{taskId:C.value,type:l,priority:c,strategy:s.strategy||"adaptive",status:"workflow-started",message:`Workflow '${d}' started for task: ${s.task}`,routing:{tier:n.decision.tier,tierName:n.tierInfo.name,modelId:n.modelId,executionStrategy:n.executionStrategy,complexity:n.decision.complexityAnalysis.overall,confidence:n.decision.confidence,useAgentBooster:n.useAgentBooster,rationale:n.decision.rationale,decisionTimeMs:n.decision.metadata.decisionTimeMs}}}:{success:!1,error:`Workflow execution failed: ${C.error.message}`}}let m={description:s.task,strategy:s.strategy||"adaptive",maxAgents:s.maxAgents,context:s.context};l==="generate-tests"&&(m.sourceFiles=s.filePaths||[],m.sourceCode=s.codeContext||"",m.language=m.language||"typescript",m.testType=m.testType||"unit");let p=await e.submitTask({type:l,priority:c,targetDomains:[],payload:{...m,routing:{tier:n.decision.tier,modelId:n.modelId,executionStrategy:n.executionStrategy,useAgentBooster:n.useAgentBooster,agentBoosterTransform:n.decision.agentBoosterTransform,complexity:n.decision.complexityAnalysis.overall,confidence:n.decision.confidence},experienceGuidance:o?{strategy:o.recommendedStrategy,actions:o.suggestedActions,confidence:o.confidence,tokenSavings:o.estimatedTokenSavings}:void 0},timeout:6e5});if(!p.success)return{success:!1,error:p.error.message};let g=p.value;return await KW(g,s.task,{agent:"queen-coordinator",domain:s.context?.project}),{success:!0,data:{taskId:g,type:l,priority:c,strategy:s.strategy||"adaptive",status:"submitted",message:`Task orchestrated: ${s.task}${o?" (with experience guidance)":""}`,routing:{tier:n.decision.tier,tierName:n.tierInfo.name,modelId:n.modelId,executionStrategy:n.executionStrategy,complexity:n.decision.complexityAnalysis.overall,confidence:n.decision.confidence,useAgentBooster:n.useAgentBooster,rationale:n.decision.rationale,decisionTimeMs:n.decision.metadata.decisionTimeMs}}}}catch(u){return{success:!1,error:`Failed to orchestrate task: ${A(u)}`}}}async function Ry(s){try{let e=await rn(),t=s.domain||$W(s.task),u=s.isCritical??/\b(security|vulnerability|cve|owasp|critical|production|exploit)\b/i.test(s.task),a=await e.routeTask({task:s.task,codeContext:s.codeContext,filePaths:s.filePaths,manualTier:s.manualTier,isCritical:u,agentType:s.agentType||`qe-${t}`,domain:t,metadata:{inferredDomain:t,hasCodeContext:!!s.codeContext,fileCount:s.filePaths?.length}});return{success:!0,data:{tier:a.decision.tier,tierName:a.tierInfo.name,modelId:a.modelId,executionStrategy:a.executionStrategy,useAgentBooster:a.useAgentBooster,agentBoosterTransform:a.decision.agentBoosterTransform,complexity:{overall:a.decision.complexityAnalysis.overall,code:a.decision.complexityAnalysis.codeComplexity,reasoning:a.decision.complexityAnalysis.reasoningComplexity,scope:a.decision.complexityAnalysis.scopeComplexity},confidence:a.decision.confidence,rationale:a.decision.rationale,warnings:a.decision.warnings,budget:{allowed:a.decision.budgetDecision.allowed,wasDowngraded:a.decision.budgetDecision.wasDowngraded,estimatedCostUsd:a.decision.budgetDecision.estimatedCostUsd},decisionTimeMs:a.decision.metadata.decisionTimeMs}}}catch(e){return{success:!1,error:`Failed to route task: ${A(e)}`}}}async function Py(s){try{let e=await rn(),t=e.getRoutingStats(),u=e.getMetrics(),a={stats:t,modelRouterMetrics:{totalDecisions:u.totalDecisions,avgDecisionTimeMs:u.avgDecisionTimeMs,agentBoosterStats:u.agentBoosterStats,budgetStats:u.budgetStats}};return s.includeLog&&(a.log=e.getRoutingLog(s.logLimit||100)),{success:!0,data:a}}catch(e){return{success:!1,error:`Failed to get routing metrics: ${A(e)}`}}}async function My(s){try{let{createRoutingFeedbackCollector:e}=await Promise.resolve().then(()=>(DB(),mq)),{getGlobalCostTracker:t}=await Promise.resolve().then(()=>(EB(),dq)),u=e(100);await u.initialize(),u.enableEconomicRouting({...s.taskComplexity!=null?{}:{}},t());let a=u.getEconomicReport();return a?{success:!0,data:{tierEfficiency:a.tierEfficiency.map(n=>({...n,qualityPerDollar:isFinite(n.qualityPerDollar)?n.qualityPerDollar:"Infinity"})),currentHourlyCostUsd:a.currentHourlyCostUsd,currentDailyCostUsd:a.currentDailyCostUsd,budgetRemaining:a.budgetRemaining,recommendation:a.recommendation,savingsOpportunity:a.savingsOpportunity}}:{success:!1,error:"Economic routing is not available"}}catch(e){return{success:!1,error:`Failed to get economic routing report: ${A(e)}`}}}function $W(s){let e=s.toLowerCase();return/\b(security|vulnerabilit|cve|owasp|secret|credential|injection|xss|csrf)\b/.test(e)?"security-compliance":/\b(chaos|resilience|fault.?inject|disaster|failover)\b/.test(e)?"chaos-resilience":/\b(defect|bug.?predict|risk.?assess|mutation)\b/.test(e)?"defect-intelligence":/\b(coverage|uncovered|gap.?analy)\b/.test(e)?"coverage-analysis":/\b(quality|code.?review|maintain|tech.?debt)\b/.test(e)?"quality-assessment":/\b(contract|api.?compat|breaking.?change|pact)\b/.test(e)?"contract-testing":/\b(index|knowledge.?graph|semantic|code.?intel)\b/.test(e)?"code-intelligence":/\b(accessib|a11y|wcag|screen.?read)\b/.test(e)?"visual-accessibility":/\b(requirement|bdd|acceptance|user.?stor)\b/.test(e)?"requirements-validation":/\b(generat.*test|test.*generat|write.*test|create.*test)\b/.test(e)?"test-generation":/\b(run.*test|execut.*test)\b/.test(e)?"test-execution":"test-generation"}function Byt(s){let e=s.toLowerCase();return/run\s+(?:\w+\s+)*tests?/.test(e)||/execute\s+(?:\w+\s+)*tests?/.test(e)||e.includes("run tests")||e.includes("execute tests")?"execute-tests":e.includes("generate test")||e.includes("create test")||e.includes("write test")?"generate-tests":e.includes("coverage")||e.includes("uncovered")?"analyze-coverage":e.includes("quality")||e.includes("code quality")?"assess-quality":e.includes("defect")||e.includes("bug")||e.includes("predict")?"predict-defects":e.includes("requirement")||e.includes("bdd")||e.includes("acceptance")?"validate-requirements":e.includes("index")||e.includes("knowledge graph")||e.includes("semantic")?"index-code":e.includes("security")||e.includes("vulnerability")||e.includes("owasp")?"scan-security":e.includes("contract")||e.includes("api contract")||e.includes("pact")?"validate-contracts":e.includes("accessibility")||e.includes("a11y")||e.includes("wcag")?"test-accessibility":e.includes("chaos")||e.includes("resilience")||e.includes("fault")?"run-chaos":e.includes("learn")||e.includes("optimize")||e.includes("improve")?"optimize-learning":e.includes("ideation")||e.includes("quality criteria")||e.includes("htsm")||e.includes("qcsd")||e.includes("testability")||e.includes("pi planning")||e.includes("sprint planning")?"ideation-assessment":"generate-tests"}function Tyt(s){switch(s){case"critical":return"p0";case"high":return"p1";case"medium":return"p2";case"low":return"p3";default:return"p1"}}async function wyt(s){try{let e=await Oi(),t={taskId:s.taskId,task:s.task,taskType:s.taskType,success:s.success,executionTimeMs:s.executionTimeMs,agentId:s.agentId,domain:s.domain,modelTier:s.modelTier,qualityScore:s.qualityScore,error:s.error,metrics:s.metrics};await e.recordTaskOutcome(t);let u=s.success&&(s.qualityScore||.5)>=.6;return{success:!0,data:{recorded:!0,patternStored:u,message:u?`Outcome recorded and pattern stored for task ${s.taskId}`:`Outcome recorded for task ${s.taskId}`}}}catch(e){return{success:!1,error:`Failed to record task outcome: ${A(e)}`}}}async function Ryt(){try{let e=await(await Oi()).getStats();return{success:!0,data:{service:e.service,patterns:{totalPatterns:e.reasoningBank.totalPatterns,byDomain:e.reasoningBank.byDomain,byTier:e.reasoningBank.byTier,learningOutcomes:e.reasoningBank.learningOutcomes,patternSuccessRate:e.reasoningBank.patternSuccessRate},embeddings:{cacheSize:e.reasoningBank.embeddingCacheSize,dimension:e.reasoningBank.embeddingDimension,transformerAvailable:e.reasoningBank.transformerAvailable},performance:{avgRoutingLatencyMs:e.reasoningBank.avgRoutingLatencyMs,p95RoutingLatencyMs:e.reasoningBank.p95RoutingLatencyMs}}}}catch(s){return{success:!1,error:`Failed to get ReasoningBank stats: ${A(s)}`}}}async function Pyt(s){if(!ye())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=fe();try{let t=e.getTaskStatus(s.taskId);if(!t)return{success:!1,error:`Task not found: ${s.taskId}`};let u={taskId:t.taskId,type:t.task.type,status:t.status,priority:t.task.priority,assignedDomain:t.assignedDomain,assignedAgents:t.assignedAgents,result:s.detailed?t.result:void 0,error:t.error,createdAt:t.task.createdAt.toISOString(),startedAt:t.startedAt?.toISOString(),completedAt:t.completedAt?.toISOString(),duration:t.completedAt&&t.startedAt?t.completedAt.getTime()-t.startedAt.getTime():void 0};if((t.status==="completed"||t.status==="failed")&&!UW.has(s.taskId)){UW.add(s.taskId);try{let a=await Oi(),r=u.duration||0,n=t.status==="completed",i=t.task.payload||{},o=typeof i.description=="string"?i.description:t.task.type,l=i.routing,c=await ky(s.taskId,n,t.error),d=c?.metrics.averageQuality??(n?.7:.3);await a.recordTaskOutcome({taskId:s.taskId,task:o,taskType:t.task.type,success:n,executionTimeMs:r,agentId:t.assignedAgents?.[0],domain:t.assignedDomain,modelTier:l?.tier,qualityScore:d,error:t.error,metrics:{testsGenerated:typeof t.result=="object"&&t.result?t.result.testsGenerated:void 0,testsPassed:typeof t.result=="object"&&t.result?t.result.testsPassed:void 0}}),console.error(`[TaskHandler] Recorded learning outcome: task=${s.taskId} success=${n} quality=${d.toFixed(2)} trajectorySteps=${c?.steps.length??0}`)}catch(a){console.error("[TaskHandler] Failed to record outcome:",a)}}return{success:!0,data:u}}catch(t){return{success:!1,error:`Failed to get task status: ${A(t)}`}}}function Myt(s){WW(s);let e=s.subscribeToEventType("TaskCompleted",async u=>{let{taskId:a}=u.payload;a&&await ky(a,!0).catch(()=>{})}),t=s.subscribeToEventType("TaskFailed",async u=>{let{taskId:a,error:r}=u.payload;a&&await ky(a,!1,r).catch(()=>{})});s9=[e,t]}function WW(s){for(let e of s9)s.unsubscribe(e);s9=[]}var Syt,UW,s9,Iy=f(()=>{"use strict";on();of();qW();B();Syt={"ideation-assessment":"qcsd-ideation-swarm"};UW=new Set;s9=[]});var QW={};ue(QW,{DEFAULT_STRUCTURAL_HEALTH_CONFIG:()=>JW,StructuralHealthMonitor:()=>Ny,createStructuralHealthMonitor:()=>Iyt});function Iyt(s){return new Ny(s)}var JW,Ny,ZW=f(()=>{"use strict";zS();JW={healthyThreshold:.4,warningThreshold:.2,maxHistoryEntries:100,enableLogging:!1},Ny=class{config;minCutService;history=[];constructor(e){this.config={...JW,...e},this.minCutService=Z3()}computeFleetHealth(e){if(e.length===0)return this.emptyFleetResult();let t=this.minCutService.buildTaskGraphFromTopology(e);return this.computeFleetHealthFromGraph(t,e.length)}computeFleetHealthFromGraph(e,t){if(e.nodes.length===0)return this.emptyFleetResult();let u=this.minCutService.getStructuralHealth(e),a=this.determineStatus(u.normalizedLambda),r={lambda:u.lambda,healthy:u.healthy,weakPoints:u.weakPoints,normalizedLambda:u.normalizedLambda,riskScore:u.riskScore,status:a,suggestions:u.suggestions,measuredAt:new Date};return this.addHistoryEntry({lambda:u.lambda,healthy:u.healthy,weakPointCount:u.weakPoints.length,agentCount:t??e.nodes.length,timestamp:r.measuredAt}),this.config.enableLogging&&this.logHealth(r),r}getTrend(){if(this.history.length<2)return"stable";let e=Math.min(5,this.history.length),t=this.history.slice(-e),u=t[0].lambda,r=t[t.length-1].lambda-u;return Math.abs(r)<.05?"stable":r>0?"improving":"degrading"}getHistory(e){let t=[...this.history];return e!==void 0&&e<t.length?t.slice(-e):t}clearHistory(){this.history.length=0}getMinCutService(){return this.minCutService}determineStatus(e){return e>=this.config.healthyThreshold?"healthy":e>=this.config.warningThreshold?"warning":"critical"}addHistoryEntry(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}emptyFleetResult(){return{lambda:0,healthy:!1,weakPoints:[],normalizedLambda:0,riskScore:1,status:"empty",suggestions:["No agents in fleet. Spawn agents to build a topology."],measuredAt:new Date}}logHealth(e){console.error(`[StructuralHealth] Status: ${e.status} | Lambda: ${e.normalizedLambda.toFixed(3)} | Weak points: ${e.weakPoints.length} | Risk: ${(e.riskScore*100).toFixed(0)}%`)}}});function fe(){return q}function ye(){return q.initialized&&q.kernel!==null&&q.queen!==null}function XW(s,e){if(q.topology!=="hierarchical"){let r={agentId:s,domain:e,level:"worker",spawnedAt:new Date};return q.agentLevels.set(s,r),"worker"}let u=Array.from(q.agentLevels.values()).find(r=>r.domain===e&&r.level==="lead")?"worker":"lead",a={agentId:s,domain:e,level:u,spawnedAt:new Date};return q.agentLevels.set(s,a),u}function eJ(s){return q.agentLevels.get(s)}async function np(s){try{if(q.initialized&&q.kernel&&q.queen)return{success:!0,data:{fleetId:q.fleetId,topology:s.topology||"hierarchical",maxAgents:s.maxAgents||15,enabledDomains:s.enabledDomains||YW,status:"ready"}};q.fleetId=`fleet-${x().slice(0,8)}`;let e=s.enabledDomains||[...ne],t=e.filter(o=>o!=="coordination");q.kernel=new J1({maxConcurrentAgents:s.maxAgents||15,memoryBackend:s.memoryBackend||"hybrid",hnswEnabled:!0,lazyLoading:s.lazyLoading!==!1,enabledDomains:e}),await q.kernel.initialize(),q.router=new w3(q.kernel.eventBus),await q.router.initialize();let u=o=>q.kernel.getDomainAPI(o),a=new xy(q.kernel.eventBus,q.kernel.memory,u),r=q.kernel.plugins;await r.loadAll();let n=new Map;for(let o of r.getLoaded()){let l=r.getPlugin(o);l&&n.set(o,l)}q.queen=Sj(q.kernel,q.router,a,void 0,n),await q.queen.initialize(),q.workflowOrchestrator=new Id(q.kernel.eventBus,q.kernel.memory,q.kernel.coordinator),await q.workflowOrchestrator.initialize(),Nyt(q.kernel,q.workflowOrchestrator);let{subscribeTrajectoryEvents:i}=await Promise.resolve().then(()=>(Iy(),o9));return i(q.router),q.initialized=!0,q.initTime=new Date,q.topology=s.topology||"hierarchical",q.agentLevels.clear(),{success:!0,data:{fleetId:q.fleetId,topology:q.topology,maxAgents:s.maxAgents||15,enabledDomains:t,status:"initialized"}}}catch(e){return{success:!1,error:`Failed to initialize fleet: ${A(e)}`}}}async function l9(s){if(!ye())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{let e=q.queen.getHealth(),t=q.queen.getMetrics(),u={status:e.status,uptime:t.uptime,agents:{total:e.totalAgents,active:e.activeAgents,idle:e.totalAgents-e.activeAgents},tasks:{pending:e.pendingTasks,running:e.runningTasks,completed:t.tasksCompleted,failed:t.tasksFailed}};if(s.includeDomains){let r=[];for(let[n,i]of e.domainHealth)r.push({domain:n,status:i.status,agents:i.agents.total,load:q.queen.getDomainLoad(n)});u.domains=r}let a=q.queen.getDomainTeamManager?.();if(a){let r=a.listDomainTeams(),n=0,i=0;for(let o of r)n+=1+o.teammateIds.length,a.getTeamHealth(o.domain)?.healthy&&i++;u.teams={active:r.length,totalAgentsInTeams:n,healthyCount:i}}s.includeMetrics&&(u.metrics={tasksReceived:t.tasksReceived,tasksCompleted:t.tasksCompleted,tasksFailed:t.tasksFailed,agentUtilization:t.agentUtilization,averageTaskDuration:t.averageTaskDuration});try{let{getUnifiedMemory:r}=await Promise.resolve().then(()=>(re(),Er)),n=r();if(n.isInitialized()){let i=l=>{try{return n.queryCount(l)}catch{return 0}},o=await n.vectorCount();u.learning={totalPatterns:i("qe_patterns"),totalExperiences:i("captured_experiences"),totalTrajectories:i("qe_trajectories"),vectorCount:o,experienceApplications:i("experience_applications"),dreamCycles:i("dream_cycles"),embeddingDimension:384}}}catch{}return{success:!0,data:u}}catch(e){return{success:!1,error:`Failed to get fleet status: ${A(e)}`}}}async function c9(s){if(!ye())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{if(s.domain){let u=q.queen.getDomainHealth(s.domain);return u?{success:!0,data:{domain:s.domain,status:u.status,agents:u.agents,errors:u.errors,lastActivity:u.lastActivity?.toISOString()}}:{success:!1,error:`Domain not found: ${s.domain}`}}let e=q.queen.getHealth(),t={status:e.status,totalAgents:e.totalAgents,activeAgents:e.activeAgents,pendingTasks:e.pendingTasks,runningTasks:e.runningTasks,workStealingActive:e.workStealingActive,lastHealthCheck:e.lastHealthCheck.toISOString()};if(s.detailed){let u={};for(let[a,r]of e.domainHealth)u[a]={status:r.status,agents:r.agents,errors:r.errors.length,lastActivity:r.lastActivity?.toISOString()};t.domains=u,t.issues=e.issues.map(a=>({severity:a.severity,message:a.message,domain:a.domain,timestamp:a.timestamp.toISOString()}))}try{let{StructuralHealthMonitor:u}=await Promise.resolve().then(()=>(ZW(),QW)),a=new u,r=[];for(let[o]of e.domainHealth){let l=q.queen.getAgentsByDomain(o);for(let c of l)r.push({id:c.id,name:c.name,domain:c.domain})}let n=r.map(o=>({id:o.id,name:o.name,domain:o.domain,capabilities:[o.domain],dependsOn:[],weight:1})),i=a.computeFleetHealth(n);t.structuralHealth={lambda:i.lambda,healthy:i.healthy,normalizedLambda:i.normalizedLambda,riskScore:i.riskScore,status:i.status,weakPoints:i.weakPoints,suggestions:i.suggestions}}catch{}return{success:!0,data:t}}catch(e){return{success:!1,error:`Failed to get fleet health: ${A(e)}`}}}async function d9(){if(JK(),Rf(),VW(),q.workflowOrchestrator&&(await q.workflowOrchestrator.dispose(),q.workflowOrchestrator=null),q.queen&&(await q.queen.dispose(),q.queen=null),q.router){try{let{unsubscribeTrajectoryEvents:s}=await Promise.resolve().then(()=>(Iy(),o9));s(q.router)}catch{}await q.router.dispose(),q.router=null}q.kernel&&(await q.kernel.dispose(),q.kernel=null),q.initialized=!1,q.fleetId=null,q.initTime=null,q.topology="hierarchical",q.agentLevels.clear()}async function m9(){let s=performance.now();try{let e=ye(),t=q.initTime?Date.now()-q.initTime.getTime():0,u={connected:!1,totalEntries:0,namespaces:0},a={enabled:!1,vectorCount:0},r=0;if(e&&q.kernel){let c=q.kernel.memory;try{u.connected=!0;let d=await c.count("default"),m=await c.count("learning"),p=await c.count("patterns");u.totalEntries=d+m+p;let g=0;for(let h of["default","learning","patterns","mcp-tools","coordination"])await c.count(h)>0&&g++;u.namespaces=g}catch{}try{let d=process.env.AQE_V3_HNSW_ENABLED==="true";a.enabled=d;let m=c;d&&typeof m.getVectorCount=="function"&&(a.vectorCount=await m.getVectorCount())}catch{}try{r=(await c.search("pattern:*",1e3)).length}catch{}}let n=e&&q.kernel?(q.kernel.getLoadedDomains?.()??YW).length:0,i=null;try{let{getSharedRvfDualWriterSync:c}=await Promise.resolve().then(()=>(Jr(),pi)),d=c();if(d){let m=d.status(),p=d.getDivergenceReport();i={mode:m.mode,vectorCount:m.rvf?.totalVectors??0,divergences:p.divergences,promotionSafe:d.isPromotionSafe()}}}catch{}let o=null;try{let{SQLitePatternStore:c}=await Promise.resolve().then(()=>(tm(),jj)),d=new c;await d.initialize(),o=d.getGhostPatternCount(),d.close()}catch{}return{success:!0,data:{status:e?"healthy":"unhealthy",version:"3.8.12",loadedDomains:n,memory:u,hnsw:a,rvf:i??void 0,ghostPatterns:o??void 0,loadedPatterns:r,uptimeMs:t,timestamp:new Date().toISOString()},metadata:{executionTime:performance.now()-s,timestamp:new Date().toISOString(),requestId:x(),toolName:"aqe_health"}}}catch(e){return{success:!1,error:A(e),metadata:{executionTime:performance.now()-s,timestamp:new Date().toISOString(),requestId:x(),toolName:"aqe_health"}}}}function Nyt(s,e){let t=s.getDomainAPI("requirements-validation");t?.registerWorkflowActions&&(t.registerWorkflowActions(e),console.log("[Fleet] Registered requirements-validation workflow actions (includes QCSD Ideation)"));let u=s.getDomainAPI("visual-accessibility");u?.registerWorkflowActions&&(u.registerWorkflowActions(e),console.log("[Fleet] Registered visual-accessibility workflow actions"))}var YW,q,on=f(()=>{"use strict";O();lV();z();Bj();Nk();Tj();aB();Pf();n9();jW();B();YW=ne.filter(s=>s!=="coordination"),q={fleetId:null,kernel:null,queen:null,router:null,workflowOrchestrator:null,initialized:!1,initTime:null,topology:"hierarchical",agentLevels:new Map}});import{randomUUID as CDt}from"crypto";var Ge,ou=f(()=>{"use strict";B();Ge=class{constructor(e){this.config=e}_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let t=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let u,a;for(let n=0;n<=this.config.retryCount;n++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");a=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(i){u=b(i),e.logger.warn(`Worker ${this.config.id} attempt ${n+1} failed: ${u.message}`),n<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let r=Date.now()-t;return a?(this._successfulExecutions++,this._lastResult=a):(this._failedExecutions++,a=this.createErrorResult(u,r),this._lastResult=a),this._executionDurations.push(r),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:a.success,durationMs:r}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=a.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:a.success,durationMs:r,findingsCount:a.findings.length,healthScore:a.metrics.healthScore}}),a}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((u,a)=>u+a,0)/this._executionDurations.length:0,t=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(t*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,t,u){return new Promise((a,r)=>{let n=setTimeout(()=>{r(new Error(`Worker execution timed out after ${t}ms`))},t),i=()=>{clearTimeout(n),r(new Error("Worker execution aborted"))};u.addEventListener("abort",i,{once:!0}),e().then(o=>{clearTimeout(n),u.removeEventListener("abort",i),a(o)}).catch(o=>{clearTimeout(n),u.removeEventListener("abort",i),r(o)})})}createErrorResult(e,t){return{workerId:this.config.id,timestamp:new Date,durationMs:t,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,t,u,a){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:t,findings:u,recommendations:a}}delay(e){return new Promise(t=>setTimeout(t,e))}generateId(){return`${Date.now()}-${CDt().slice(0,9)}`}}});var vDt,y0,Z9=f(()=>{"use strict";ou();oy();re();IT();B();vDt={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},y0=class extends Ge{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(vDt),this.dailyLogger=new Hm}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=Y();await e.initialize();let t=e.getDatabase();return this.lifecycleManager=Om(t,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return Y().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let t=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let u=[],a=[],r=await this.getLifecycleManager();if(!r)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-t,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let n=0,i=0;try{let D=r.promoteEligiblePatterns();n=D.promoted,i=D.checked,n>0&&u.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${n} of ${i} short-term patterns promoted to long-term`})}catch(D){e.logger.warn("Pattern promotion failed",{error:A(D)})}let o=0,l=0;try{let D=r.deprecateStalePatterns();o=D.deprecated,l=D.checked,o>0&&u.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${o} of ${l} patterns deprecated (stale, failed, or low confidence)`})}catch(D){e.logger.warn("Stale pattern detection failed",{error:A(D)})}let c=0;try{let D=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;c=r.applyConfidenceDecay(Math.min(D,7)).decayed}catch(D){e.logger.warn("Confidence decay failed",{error:A(D)})}let d=this.getPendingExperienceCount(),m={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{m=r.getStats()}catch(D){e.logger.warn("Stats retrieval failed",{error:A(D)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${n} promoted, ${o} deprecated, ${c} decayed, ${d} pending exp, ${m.activePatterns} active patterns (avg conf: ${m.avgConfidence.toFixed(2)})`,details:{promoted:n,deprecated:o,decayed:c,pendingExperiences:d,totalPatterns:m.totalPatterns,activePatterns:m.activePatterns,avgConfidence:m.avgConfidence,avgSuccessRate:m.avgSuccessRate}}),this.dailyLogger.flush()}catch(D){e.logger.warn("Daily log write failed",{error:A(D)})}this.lastRunTimestamp=Date.now(),m.activePatterns>0&&m.patternsNearDeprecation/m.activePatterns>.5&&a.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${m.patternsNearDeprecation} of ${m.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let p=this.calculateHealthScore(m,n,o),g=this.determineTrend(n,o,m.activePatterns),h=Math.max(i,l),y=n+o+m.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:n,deprecated:o,decayed:c,pendingExperiences:d,healthScore:p}),this.createResult(Date.now()-t,{itemsAnalyzed:h,issuesFound:y,healthScore:p,trend:g,domainMetrics:{promoted:n,deprecated:o,decayed:c,stalePatterns:m.patternsNearDeprecation,pendingExperiences:d,avgConfidence:Number(m.avgConfidence.toFixed(3)),avgSuccessRate:Number(m.avgSuccessRate.toFixed(3))}},u,a)}calculateHealthScore(e,t,u){let a=70;if(a+=Math.min(15,t*5),e.avgConfidence>0&&(a+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let r=u/e.activePatterns;a-=Math.round(r*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(a-=10),Math.max(0,Math.min(100,Math.round(a)))}determineTrend(e,t,u){return u===0?"stable":e>t?"improving":t>e&&t/u>.1?"degrading":"stable"}}});var pw,gw,hw,LD,zD,_D,wY=f(()=>{"use strict";pw=class{handlers=[];async publish(e){for(let t of this.handlers)try{t(e)}catch(u){console.debug("[WorkerManager] Event handler error:",u instanceof Error?u.message:u)}}subscribe(e){return this.handlers.push(e),()=>{let t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)}}dispose(){this.handlers=[]}get handlerCount(){return this.handlers.length}},gw=class{store=new Map;async get(e){return this.store.get(e)}async set(e,t){this.store.set(e,t)}async search(e){let t=new RegExp(e.replace(/\*/g,".*"));return Array.from(this.store.keys()).filter(u=>t.test(u))}clear(){this.store.clear()}get size(){return this.store.size}},hw=class{constructor(e){this.workerId=e}format(e,t,u){let a=new Date().toISOString(),r=u?` ${JSON.stringify(u)}`:"";return`[${a}] [${e}] [${this.workerId}] ${t}${r}`}debug(e,t){process.env.DEBUG&&console.debug(this.format("DEBUG",e,t))}info(e,t){console.info(this.format("INFO",e,t))}warn(e,t){console.warn(this.format("WARN",e,t))}error(e,t){console.error(this.format("ERROR",e,t))}},LD=class{constructor(e){this.kernelGetter=e}getDomainAPI(e){let t=this.kernelGetter();if(t)return t.getDomainAPI(e)}getDomainHealth(e){let t=this.kernelGetter();if(!t)return{status:"unknown",errors:["Kernel not available"]};let a=t.getHealth().domains[e];return a?{status:a.status,errors:a.errors||[]}:{status:"unknown",errors:[`Domain ${e} not found`]}}},zD=class{getDomainAPI(e){}getDomainHealth(e){return{status:"healthy",errors:[]}}},_D=class{workers=new Map;timers=new Map;abortControllers=new Map;eventBus;memory;domainAccess;running=!1;kernelRef;constructor(e){this.eventBus=e?.eventBus??new pw,this.memory=e?.memory??new gw,this.kernelRef=e?.kernel,e?.domainAccess?this.domainAccess=e.domainAccess:e?.kernel?this.domainAccess=new LD(()=>this.kernelRef):this.domainAccess=new zD}setKernel(e){this.kernelRef=e,this.domainAccess instanceof zD&&(this.domainAccess=new LD(()=>this.kernelRef))}register(e){if(this.workers.has(e.config.id))throw new Error(`Worker ${e.config.id} is already registered`);this.workers.set(e.config.id,e)}unregister(e){this.workers.get(e)&&(this.stopWorker(e),this.workers.delete(e))}get(e){return this.workers.get(e)}list(){return Array.from(this.workers.values())}async startAll(){this.running=!0;for(let e of Array.from(this.workers.values()))e.config.enabled&&await this.startWorker(e)}async stopAll(){this.running=!1;let e=[];for(let t of Array.from(this.workers.keys()))e.push(this.stopWorker(t));await Promise.all(e)}async runNow(e){let t=this.workers.get(e);if(!t)throw new Error(`Worker ${e} not found`);let u=this.timers.get(e);u&&clearTimeout(u);let a=new AbortController;this.abortControllers.set(e,a);let r=this.createContext(e,a.signal),n=await t.execute(r);return this.running&&t.config.enabled&&t.status!=="stopped"&&this.scheduleNextRun(t),n}getHealth(){let e={},t=0,u=0,a=0,r=0;for(let[i,o]of Array.from(this.workers.entries())){let l=o.getHealth();switch(e[i]=l,r+=l.healthScore,o.status){case"running":t++;break;case"paused":u++;break;case"error":a++;break}}let n=this.workers.size>0?Math.round(r/this.workers.size):100;return{totalWorkers:this.workers.size,runningWorkers:t,pausedWorkers:u,errorWorkers:a,healthScore:n,workers:e}}onWorkerEvent(e){return this.eventBus.subscribe(e)}async startWorker(e){await e.initialize();let t=new AbortController;this.abortControllers.set(e.config.id,t);let u=this.createContext(e.config.id,t.signal);try{await e.execute(u)}catch(a){console.error(`Worker ${e.config.id} initial execution failed:`,a)}this.scheduleNextRun(e)}async stopWorker(e){let t=this.timers.get(e);t&&(clearTimeout(t),this.timers.delete(e));let u=this.abortControllers.get(e);u&&(u.abort(),this.abortControllers.delete(e));let a=this.workers.get(e);a&&await a.stop()}scheduleNextRun(e){let t=setTimeout(async()=>{if(!this.running||e.status==="stopped"||e.status==="paused")return;let u=new AbortController;this.abortControllers.set(e.config.id,u);let a=this.createContext(e.config.id,u.signal);try{await e.execute(a)}catch(r){console.error(`Worker ${e.config.id} execution failed:`,r)}this.running&&e.config.enabled&&e.status!=="error"&&this.scheduleNextRun(e)},e.config.intervalMs);this.timers.set(e.config.id,t)}createContext(e,t){return{eventBus:this.eventBus,memory:this.memory,logger:new hw(e),domains:this.domainAccess,signal:t}}}});var vvt,kp,RY=f(()=>{"use strict";ou();B();vvt={id:"test-health",name:"Test Health Monitor",description:"Monitors test suite health metrics including pass rates, execution times, and reliability",intervalMs:300*1e3,priority:"high",targetDomains:["test-execution","test-generation"],enabled:!0,timeoutMs:6e4,retryCount:2,retryDelayMs:5e3},kp=class extends Ge{previousMetrics;constructor(){super(vvt)}async doExecute(e){let t=Date.now();e.logger.info("Starting test health analysis");let u=[],a=[],r=await this.collectMetrics(e);this.analyzePassRate(r,u,a),this.analyzeExecutionTime(r,u,a),this.analyzeReliability(r,u,a),this.analyzeGrowth(r,u,a),this.compareToPrevious(r,u,a),await e.memory.set("test-health:previous-metrics",r),this.previousMetrics=r;let n=this.calculateHealthScore(r),i=this.determineTrend(r);return e.logger.info("Test health analysis complete",{healthScore:n,findingsCount:u.length}),this.createResult(Date.now()-t,{itemsAnalyzed:r.totalTests,issuesFound:u.length,healthScore:n,trend:i,domainMetrics:{passRate:`${(r.passingTests/r.totalTests*100).toFixed(1)}%`,avgExecutionTime:`${r.avgExecutionTimeMs}ms`,reliability:`${r.reliability}%`,totalTests:r.totalTests}},u,a)}async collectMetrics(e){let t=await e.memory.get("test-health:previous-metrics");if(t&&(this.previousMetrics=t),!e.domains.getDomainAPI("test-execution"))throw new Error("Test-execution domain not available - cannot compute health metrics. Ensure the test-execution domain is properly initialized before running this worker.");try{let a=await e.memory.search("test-health:run-result:*");if(a.length===0)throw new Error('No test run data found in memory - cannot compute health metrics. Run some tests first or ensure test results are being stored with keys matching "test-health:run-result:*".');let r=0,n=0,i=0,o=0,l=0,c=0;for(let g of a.slice(0,50)){let h=await e.memory.get(g);h&&(r+=h.total,n+=h.passed,i+=h.failed,o+=h.skipped,l+=h.duration,c++)}let d=c>0?Math.round(l/c):0,m=r>0?Math.round(n/r*100):0,p=await e.memory.get("test-health:growth-metrics");return{totalTests:r||0,passingTests:n||0,failingTests:i||0,skippedTests:o||0,avgExecutionTimeMs:d,reliability:m,growth:{testsAddedLast7Days:p?.testsAddedLast7Days||0,testsRemovedLast7Days:p?.testsRemovedLast7Days||0}}}catch(a){let r=A(a);throw new Error(`Failed to collect test health metrics: ${r}. Check memory service connectivity and test result data availability.`)}}analyzePassRate(e,t,u){let a=e.passingTests/e.totalTests*100;a<95&&(t.push({type:"low-pass-rate",severity:a<90?"high":"medium",domain:"test-execution",title:"Low Test Pass Rate",description:`Test pass rate is ${a.toFixed(1)}%, below the 95% target`,context:{passing:e.passingTests,failing:e.failingTests,total:e.totalTests}}),u.push({priority:"p1",domain:"test-execution",action:"Investigate Failing Tests",description:`${e.failingTests} tests are currently failing. Review and fix to improve pass rate.`,estimatedImpact:"high",effort:"medium",autoFixable:!1}))}analyzeExecutionTime(e,t,u){e.avgExecutionTimeMs>500&&(t.push({type:"slow-tests",severity:e.avgExecutionTimeMs>1e3?"high":"medium",domain:"test-execution",title:"Slow Test Execution",description:`Average test execution time is ${e.avgExecutionTimeMs}ms, consider optimization`,context:{avgExecutionTimeMs:e.avgExecutionTimeMs}}),u.push({priority:"p2",domain:"test-execution",action:"Optimize Test Execution Time",description:"Review and optimize slow-running tests. Consider parallelization or mocking slow dependencies.",estimatedImpact:"medium",effort:"medium",autoFixable:!1}))}analyzeReliability(e,t,u){e.reliability<95&&(t.push({type:"reliability-issue",severity:e.reliability<85?"high":"medium",domain:"test-execution",title:"Test Reliability Concern",description:`Test reliability score is ${e.reliability}%, indicating potential flaky tests`,context:{reliability:e.reliability}}),u.push({priority:"p1",domain:"test-execution",action:"Address Flaky Tests",description:"Identify and fix flaky tests to improve overall test reliability.",estimatedImpact:"high",effort:"medium",autoFixable:!1}))}analyzeGrowth(e,t,u){let a=e.growth.testsAddedLast7Days-e.growth.testsRemovedLast7Days;a<0&&(t.push({type:"test-coverage-decline",severity:"medium",domain:"test-generation",title:"Test Coverage Declining",description:`Net loss of ${Math.abs(a)} tests in the last 7 days`,context:{added:e.growth.testsAddedLast7Days,removed:e.growth.testsRemovedLast7Days}}),u.push({priority:"p2",domain:"test-generation",action:"Review Test Coverage Strategy",description:"More tests are being removed than added. Ensure adequate test coverage is maintained.",estimatedImpact:"medium",effort:"low",autoFixable:!1}))}compareToPrevious(e,t,u){if(!this.previousMetrics)return;let a=e.passingTests/e.totalTests-this.previousMetrics.passingTests/this.previousMetrics.totalTests;a<-.05&&t.push({type:"pass-rate-regression",severity:"high",domain:"test-execution",title:"Pass Rate Regression Detected",description:`Pass rate dropped by ${(Math.abs(a)*100).toFixed(1)}% since last check`,context:{previousPassRate:`${(this.previousMetrics.passingTests/this.previousMetrics.totalTests*100).toFixed(1)}%`,currentPassRate:`${(e.passingTests/e.totalTests*100).toFixed(1)}%`}})}calculateHealthScore(e){let t=e.passingTests/e.totalTests*40,u=e.reliability/100*30,a=Math.max(0,20-e.avgExecutionTimeMs/100),r=Math.min(10,e.growth.testsAddedLast7Days/10*10);return Math.round(t+u+a+r)}determineTrend(e){if(!this.previousMetrics)return"stable";let t=e.passingTests/e.totalTests,u=this.previousMetrics.passingTests/this.previousMetrics.totalTests;return t>u+.02?"improving":t<u-.02?"degrading":"stable"}}});var bvt,Fp,PY=f(()=>{"use strict";ou();bvt={id:"coverage-tracker",name:"Coverage Tracker",description:"Tracks coverage trends over time including gaps, hotspots, and critical paths",intervalMs:600*1e3,priority:"high",targetDomains:["coverage-analysis","test-generation"],enabled:!0,timeoutMs:12e4,retryCount:2,retryDelayMs:1e4},Fp=class extends Ge{constructor(){super(bvt)}async doExecute(e){let t=Date.now();e.logger.info("Starting coverage tracking analysis");let u=[],a=[],r=await this.collectCoverageTrend(e),n=await this.identifyCoverageGaps(e);this.analyzeCoverageThresholds(r.current,u,a),this.analyzeCoverageGaps(n,u,a),this.analyzeCoverageTrends(r,u,a),await e.memory.set("coverage:current",r.current),await e.memory.set("coverage:gaps",n);let i=this.calculateHealthScore(r.current,n);return e.logger.info("Coverage tracking complete",{healthScore:i,findingsCount:u.length,gapsFound:n.length}),this.createResult(Date.now()-t,{itemsAnalyzed:n.length+4,issuesFound:u.length,healthScore:i,trend:this.determineTrend(r),domainMetrics:{lineCoverage:`${r.current.line}%`,branchCoverage:`${r.current.branch}%`,functionCoverage:`${r.current.function}%`,statementCoverage:`${r.current.statement}%`,gapsCount:n.length}},u,a)}async collectCoverageTrend(e){let t=await e.memory.get("coverage:current"),u=await e.memory.get("coverage:latest");return{current:{line:u?.line??0,branch:u?.branch??0,function:u?.function??0,statement:u?.statement??0,timestamp:new Date},previous:t}}async identifyCoverageGaps(e){let t=await e.memory.search("gap-pattern:*");if(t.length>0){let u=[];for(let a of t){let r=await e.memory.get(a);r&&typeof r.riskScore=="number"&&u.push(r)}if(u.length>0)return u}return[]}analyzeCoverageThresholds(e,t,u){let a={line:80,branch:70,function:80,statement:80};e.line<a.line&&t.push({type:"low-line-coverage",severity:e.line<60?"high":"medium",domain:"coverage-analysis",title:"Line Coverage Below Threshold",description:`Line coverage is ${e.line}%, below ${a.line}% target`,context:{current:e.line,target:a.line}}),e.branch<a.branch&&(t.push({type:"low-branch-coverage",severity:e.branch<50?"high":"medium",domain:"coverage-analysis",title:"Branch Coverage Below Threshold",description:`Branch coverage is ${e.branch}%, below ${a.branch}% target`,context:{current:e.branch,target:a.branch}}),u.push({priority:"p1",domain:"test-generation",action:"Improve Branch Coverage",description:"Add tests for uncovered conditional branches. Focus on complex decision points.",estimatedImpact:"high",effort:"medium",autoFixable:!0})),e.function<a.function&&t.push({type:"low-function-coverage",severity:"medium",domain:"coverage-analysis",title:"Function Coverage Below Threshold",description:`Function coverage is ${e.function}%, below ${a.function}% target`,context:{current:e.function,target:a.function}})}analyzeCoverageGaps(e,t,u){let a=e.filter(n=>n.riskScore>.8);for(let n of a)t.push({type:"high-risk-coverage-gap",severity:"high",domain:"coverage-analysis",title:"High-Risk Coverage Gap",description:`${n.file} has ${n.uncoveredLines} uncovered lines with complexity ${n.complexity}`,resource:n.file,context:{uncoveredLines:n.uncoveredLines,totalLines:n.totalLines,coveragePercent:((n.totalLines-n.uncoveredLines)/n.totalLines*100).toFixed(1),complexity:n.complexity,riskScore:n.riskScore}});a.length>0&&u.push({priority:"p0",domain:"test-generation",action:"Address High-Risk Coverage Gaps",description:`${a.length} files have high-risk coverage gaps. Prioritize testing for complex, uncovered code.`,estimatedImpact:"high",effort:"high",autoFixable:!0});let r=e.filter(n=>(n.totalLines-n.uncoveredLines)/n.totalLines<.5);r.length>0&&t.push({type:"critical-coverage-gaps",severity:"critical",domain:"coverage-analysis",title:"Critical Coverage Gaps Detected",description:`${r.length} files have less than 50% coverage`,context:{files:r.map(n=>n.file)}})}analyzeCoverageTrends(e,t,u){if(!e.previous)return;let a=e.current.line-e.previous.line,r=e.current.branch-e.previous.branch;a<-2&&(t.push({type:"coverage-regression",severity:a<-5?"high":"medium",domain:"coverage-analysis",title:"Coverage Regression Detected",description:`Line coverage dropped by ${Math.abs(a).toFixed(1)}% since last check`,context:{previous:e.previous.line,current:e.current.line,change:a}}),u.push({priority:"p1",domain:"test-generation",action:"Investigate Coverage Regression",description:"Recent changes have reduced code coverage. Review new code and add missing tests.",estimatedImpact:"high",effort:"medium",autoFixable:!1})),r<-3&&t.push({type:"branch-coverage-regression",severity:"medium",domain:"coverage-analysis",title:"Branch Coverage Regression",description:`Branch coverage dropped by ${Math.abs(r).toFixed(1)}%`,context:{previous:e.previous.branch,current:e.current.branch,change:r}})}calculateHealthScore(e,t){let u=e.line/100*25,a=e.branch/100*25,r=e.function/100*20,n=e.statement/100*20,i=t.filter(l=>l.riskScore>.8).length,o=Math.max(0,10-i*2);return Math.round(u+a+r+n+o)}determineTrend(e){if(!e.previous)return"stable";let t=(e.current.line+e.current.branch+e.current.function+e.current.statement)/4,u=(e.previous.line+e.previous.branch+e.previous.function+e.previous.statement)/4;return t>u+1?"improving":t<u-1?"degrading":"stable"}}});var Avt,Sp,MY=f(()=>{"use strict";ou();Avt={id:"flaky-detector",name:"Flaky Test Detector",description:"Detects flaky test patterns through statistical analysis of test execution history",intervalMs:900*1e3,priority:"high",targetDomains:["test-execution"],enabled:!0,timeoutMs:18e4,retryCount:2,retryDelayMs:1e4},Sp=class extends Ge{constructor(){super(Avt)}async doExecute(e){let t=Date.now();e.logger.info("Starting flaky test detection");let u=[],a=[],r=await this.collectTestHistory(e),n=this.detectFlakyTests(r);this.generateFindings(n,u,a),await e.memory.set("flaky:detected",n),await e.memory.set("flaky:lastAnalysis",new Date().toISOString());let i=this.calculateHealthScore(r.length,n);return e.logger.info("Flaky test detection complete",{healthScore:i,testsAnalyzed:r.length,flakyTestsFound:n.length}),this.createResult(Date.now()-t,{itemsAnalyzed:r.length,issuesFound:n.length,healthScore:i,trend:"stable",domainMetrics:{testsAnalyzed:r.length,flakyTests:n.length,flakinessRate:`${(n.length/r.length*100).toFixed(1)}%`,avgFlakinessScore:n.length>0?(n.reduce((o,l)=>o+l.flakinessScore,0)/n.length).toFixed(1):"0"}},u,a)}async collectTestHistory(e){if(!e.domains.getDomainAPI("test-execution"))throw new Error("Test-execution domain not available - cannot detect flaky tests. Ensure the test-execution domain is properly initialized before running this worker.");let u=await e.memory.search("flaky:history:*");if(u.length===0)throw new Error('No test execution history found in memory - cannot detect flaky tests. Run tests multiple times and ensure history is stored with keys matching "flaky:history:*" before running this worker.');let a=[],r=[];for(let n of u)try{let i=await e.memory.get(n);i&&a.push(i)}catch{r.push(n)}if(a.length===0)throw new Error(`Found ${u.length} test history keys but failed to retrieve any data. Failed keys: ${r.slice(0,5).join(", ")}${r.length>5?"...":""}. Check memory service connectivity and data format.`);return a}detectFlakyTests(e){let t=[];for(let u of e){let a=this.analyzeTestFlakiness(u);a.flakinessScore>20&&t.push(a)}return t.sort((u,a)=>a.flakinessScore-u.flakinessScore)}analyzeTestFlakiness(e){let t=e.executions,a=t.filter(g=>g.passed).length/t.length,r=t.map(g=>g.durationMs),n=r.reduce((g,h)=>g+h,0)/r.length,i=r.reduce((g,h)=>g+Math.pow(h-n,2),0)/r.length,l=Math.sqrt(i)/n,c=t.slice(-5).filter(g=>!g.passed).length,d=this.determinePattern(e,l),m=0;a>0&&a<1&&(m+=(1-a)*50),l>.5&&(m+=Math.min(25,l*10)),m+=c*5;let p=this.suggestFix(d);return{testId:e.testId,testName:e.testName,file:e.file,flakinessScore:Math.min(100,Math.round(m)),pattern:d,passRate:a*100,avgDuration:n,durationVariance:l,recentFailures:c,suggestedFix:p}}determinePattern(e,t){let u=e.executions.filter(r=>!r.passed);if(t>1||u.some(r=>r.error?.includes("Timeout")))return"timing";if(u.some(r=>r.error?.includes("Resource")||r.error?.includes("connection")))return"resource";if(u.some(r=>r.error?.includes("Race")||r.error?.includes("async")))return"intermittent";let a=e.executions.map(r=>r.passed);return this.hasOrderPattern(a)?"order-dependent":"intermittent"}hasOrderPattern(e){let t=e.map((r,n)=>r?-1:n).filter(r=>r>=0);if(t.length<2)return!1;let u=t.every(r=>r%2===0),a=t.every(r=>r%2===1);return u||a}suggestFix(e){switch(e){case"timing":return"Add explicit waits, increase timeouts, or use async utilities like waitFor";case"resource":return"Ensure proper resource cleanup, use test isolation, or implement connection pooling";case"order-dependent":return"Make tests independent, reset state in beforeEach, avoid shared mutable state";case"intermittent":return"Add retry logic, investigate race conditions, or use proper synchronization";default:return"Review test for potential issues with async operations or shared state"}}generateFindings(e,t,u){let a=e.filter(o=>o.flakinessScore>=70),r=e.filter(o=>o.flakinessScore>=50&&o.flakinessScore<70),n=e.filter(o=>o.flakinessScore>=20&&o.flakinessScore<50);for(let o of a)t.push({type:"critical-flaky-test",severity:"critical",domain:"test-execution",title:`Critical Flaky Test: ${o.testName}`,description:`Test has ${o.flakinessScore}% flakiness score with ${o.passRate.toFixed(0)}% pass rate`,resource:o.file,context:{testId:o.testId,pattern:o.pattern,recentFailures:o.recentFailures,suggestedFix:o.suggestedFix}});for(let o of r)t.push({type:"high-flaky-test",severity:"high",domain:"test-execution",title:`Flaky Test: ${o.testName}`,description:`Test has ${o.flakinessScore}% flakiness score (${o.pattern} pattern)`,resource:o.file,context:{testId:o.testId,pattern:o.pattern,suggestedFix:o.suggestedFix}});for(let o of n)t.push({type:"medium-flaky-test",severity:"medium",domain:"test-execution",title:`Potentially Flaky Test: ${o.testName}`,description:`Test shows flakiness indicators (score: ${o.flakinessScore}%)`,resource:o.file,context:{testId:o.testId,pattern:o.pattern}});a.length>0&&u.push({priority:"p0",domain:"test-execution",action:"Fix Critical Flaky Tests",description:`${a.length} tests have critical flakiness. These severely impact CI reliability.`,estimatedImpact:"high",effort:"high",autoFixable:!1});let i=e.filter(o=>o.pattern==="timing");i.length>0&&u.push({priority:"p1",domain:"test-execution",action:"Address Timing-Related Flakiness",description:`${i.length} tests have timing issues. Consider using proper async utilities.`,estimatedImpact:"medium",effort:"medium",autoFixable:!1})}calculateHealthScore(e,t){if(e===0)return 100;let u=t.length/e,a=t.length>0?t.reduce((i,o)=>i+o.flakinessScore,0)/t.length:0,r=100;r-=u*50,r-=a/100*30;let n=t.filter(i=>i.flakinessScore>=70).length;return r-=n*5,Math.max(0,Math.round(r))}}});var xvt,Bp,IY=f(()=>{"use strict";ou();xvt={id:"security-scan",name:"Security Vulnerability Scanner",description:"Scans for security vulnerabilities in dependencies, code patterns, and configurations",intervalMs:1800*1e3,priority:"critical",targetDomains:["security-compliance"],enabled:!0,timeoutMs:3e5,retryCount:3,retryDelayMs:3e4},Bp=class extends Ge{constructor(){super(xvt)}async doExecute(e){let t=Date.now();e.logger.info("Starting security vulnerability scan");let u=[],a=[],r=await this.runSecurityScans(e);this.analyzeDependencyVulnerabilities(r.dependencyVulnerabilities,u,a),this.analyzeCodeSecurityIssues(r.codeSecurityIssues,u,a),r.secretsDetected>0&&this.reportSecretsDetected(r.secretsDetected,u,a),await e.memory.set("security:lastScan",r),await e.memory.set("security:lastScanTime",new Date().toISOString());let n=this.calculateHealthScore(r),i=r.dependencyVulnerabilities.length+r.codeSecurityIssues.length+r.secretsDetected+r.configurationIssues;return e.logger.info("Security scan complete",{healthScore:n,totalIssues:i,criticalIssues:r.dependencyVulnerabilities.filter(o=>o.severity==="critical").length+r.codeSecurityIssues.filter(o=>o.severity==="critical").length}),this.createResult(Date.now()-t,{itemsAnalyzed:i,issuesFound:u.length,healthScore:n,trend:"stable",domainMetrics:{dependencyVulnerabilities:r.dependencyVulnerabilities.length,codeSecurityIssues:r.codeSecurityIssues.length,secretsDetected:r.secretsDetected,configurationIssues:r.configurationIssues,scanDuration:`${r.scanDurationMs}ms`}},u,a)}async runSecurityScans(e){return{dependencyVulnerabilities:[{package:"lodash",version:"4.17.15",severity:"high",cve:"CVE-2021-23337",title:"Command Injection",description:"Lodash versions prior to 4.17.21 are vulnerable to Command Injection via the template function.",fixedIn:"4.17.21"},{package:"minimist",version:"1.2.5",severity:"critical",cve:"CVE-2021-44906",title:"Prototype Pollution",description:"Prototype pollution vulnerability allows attackers to manipulate JavaScript object prototypes.",fixedIn:"1.2.6"}],codeSecurityIssues:[{file:"src/shared/http/http-client.ts",line:45,rule:"no-eval",severity:"high",message:"Avoid using eval() as it can execute arbitrary code",category:"injection"},{file:"src/kernel/memory-backend.ts",line:122,rule:"sql-injection",severity:"medium",message:"Potential SQL injection - use parameterized queries",category:"injection"}],secretsDetected:0,configurationIssues:1,scanDurationMs:2500}}analyzeDependencyVulnerabilities(e,t,u){let a=e.filter(n=>n.severity==="critical"),r=e.filter(n=>n.severity==="high");for(let n of a)t.push({type:"critical-vulnerability",severity:"critical",domain:"security-compliance",title:`Critical Vulnerability in ${n.package}`,description:`${n.title}: ${n.description}`,resource:n.package,context:{cve:n.cve,currentVersion:n.version,fixedIn:n.fixedIn}});for(let n of r)t.push({type:"high-vulnerability",severity:"high",domain:"security-compliance",title:`High Severity Vulnerability in ${n.package}`,description:`${n.title}: ${n.description}`,resource:n.package,context:{cve:n.cve,currentVersion:n.version,fixedIn:n.fixedIn}});a.length>0&&u.push({priority:"p0",domain:"security-compliance",action:"Update Critical Vulnerabilities Immediately",description:`${a.length} packages have critical vulnerabilities. Update immediately to patched versions.`,estimatedImpact:"high",effort:"low",autoFixable:!0}),r.length>0&&u.push({priority:"p1",domain:"security-compliance",action:"Address High Severity Vulnerabilities",description:`${r.length} packages have high severity vulnerabilities. Plan updates within current sprint.`,estimatedImpact:"high",effort:"low",autoFixable:!0})}analyzeCodeSecurityIssues(e,t,u){let a=new Map;for(let i of e){let o=a.get(i.category)||[];o.push(i),a.set(i.category,o)}for(let i of e)t.push({type:`code-security-${i.category}`,severity:i.severity,domain:"security-compliance",title:`Security Issue: ${i.rule}`,description:i.message,resource:`${i.file}:${i.line}`,context:{rule:i.rule,category:i.category}});let r=a.get("injection")||[];r.length>0&&u.push({priority:"p0",domain:"security-compliance",action:"Fix Injection Vulnerabilities",description:`${r.length} potential injection vulnerabilities found. Use parameterized queries and avoid eval().`,estimatedImpact:"high",effort:"medium",autoFixable:!1});let n=a.get("crypto")||[];n.length>0&&u.push({priority:"p1",domain:"security-compliance",action:"Review Cryptographic Implementations",description:`${n.length} cryptographic issues found. Ensure using secure algorithms and proper key management.`,estimatedImpact:"high",effort:"high",autoFixable:!1})}reportSecretsDetected(e,t,u){t.push({type:"secrets-detected",severity:"critical",domain:"security-compliance",title:"Secrets Detected in Codebase",description:`${e} potential secrets/credentials found in source code`,context:{count:e}}),u.push({priority:"p0",domain:"security-compliance",action:"Remove Secrets from Codebase",description:"Immediately rotate any exposed credentials and move them to secure secret management.",estimatedImpact:"high",effort:"medium",autoFixable:!1})}calculateHealthScore(e){let t=100,u=e.dependencyVulnerabilities.filter(i=>i.severity==="critical").length;t-=u*20;let a=e.dependencyVulnerabilities.filter(i=>i.severity==="high").length;t-=a*10;let r=e.codeSecurityIssues.filter(i=>i.severity==="critical").length;t-=r*15;let n=e.codeSecurityIssues.filter(i=>i.severity==="high").length;return t-=n*8,t-=e.secretsDetected*30,t-=e.configurationIssues*5,Math.max(0,Math.round(t))}}});var kvt,Tp,NY=f(()=>{"use strict";ou();kvt={id:"quality-gate",name:"Quality Gate Evaluator",description:"Continuously evaluates quality gates and release readiness across all quality dimensions",intervalMs:300*1e3,priority:"critical",targetDomains:["quality-assessment"],enabled:!0,timeoutMs:12e4,retryCount:2,retryDelayMs:5e3},Tp=class extends Ge{constructor(){super(kvt)}async doExecute(e){let t=Date.now();e.logger.info("Starting quality gate evaluation");let u=[],a=[],r=await this.evaluateQualityGates(e);this.analyzeGateResults(r,u,a),this.checkBlockers(r,u,a),await this.compareToHistory(e,r,u),await e.memory.set("quality-gate:current",r),await e.memory.set("quality-gate:lastCheck",new Date().toISOString());let n=await e.memory.get("quality-gate:history")||[];n.push(r),n.length>100&&n.shift(),await e.memory.set("quality-gate:history",n);let i=this.calculateHealthScore(r);return e.logger.info("Quality gate evaluation complete",{healthScore:i,passed:r.passed,releaseReady:r.releaseReady,blockers:r.blockers}),this.createResult(Date.now()-t,{itemsAnalyzed:r.rules.length,issuesFound:r.failedRules,healthScore:i,trend:"stable",domainMetrics:{gatePassed:r.passed?"YES":"NO",releaseReady:r.releaseReady?"YES":"NO",passedRules:r.passedRules,failedRules:r.failedRules,blockers:r.blockers,warnings:r.warnings}},u,a)}async evaluateQualityGates(e){let t=[{id:"coverage-line",name:"Line Coverage",category:"coverage",threshold:80,operator:"gte",currentValue:78.5,unit:"%",blocking:!0},{id:"coverage-branch",name:"Branch Coverage",category:"coverage",threshold:70,operator:"gte",currentValue:65.2,unit:"%",blocking:!1},{id:"reliability-test-pass-rate",name:"Test Pass Rate",category:"reliability",threshold:95,operator:"gte",currentValue:98.2,unit:"%",blocking:!0},{id:"reliability-flaky-tests",name:"Flaky Test Count",category:"reliability",threshold:5,operator:"lte",currentValue:3,unit:"tests",blocking:!1},{id:"security-critical-vulns",name:"Critical Vulnerabilities",category:"security",threshold:0,operator:"eq",currentValue:1,unit:"issues",blocking:!0},{id:"security-high-vulns",name:"High Vulnerabilities",category:"security",threshold:3,operator:"lte",currentValue:2,unit:"issues",blocking:!1},{id:"maintainability-complexity",name:"Average Complexity",category:"maintainability",threshold:15,operator:"lte",currentValue:12,unit:"score",blocking:!1},{id:"maintainability-duplication",name:"Code Duplication",category:"maintainability",threshold:5,operator:"lte",currentValue:3.2,unit:"%",blocking:!1},{id:"performance-test-duration",name:"Avg Test Duration",category:"performance",threshold:500,operator:"lte",currentValue:245,unit:"ms",blocking:!1}],u=0,a=0,r=0,n=0;for(let i of t)this.evaluateRule(i)?u++:(a++,i.blocking?r++:n++);return{passed:r===0,passedRules:u,failedRules:a,blockers:r,warnings:n,releaseReady:r===0&&n<=2,rules:t}}evaluateRule(e){switch(e.operator){case"gte":return e.currentValue>=e.threshold;case"lte":return e.currentValue<=e.threshold;case"eq":return e.currentValue===e.threshold;default:return!1}}analyzeGateResults(e,t,u){for(let n of e.rules)if(!this.evaluateRule(n)){let i=n.blocking?"critical":"medium";t.push({type:"quality-gate-failure",severity:i,domain:"quality-assessment",title:`Quality Gate Failed: ${n.name}`,description:`${n.name} is ${n.currentValue}${n.unit}, threshold is ${n.operator==="gte"?">=":n.operator==="lte"?"<=":"="} ${n.threshold}${n.unit}`,context:{ruleId:n.id,category:n.category,currentValue:n.currentValue,threshold:n.threshold,blocking:n.blocking}})}let a=e.rules.filter(n=>n.category==="coverage"&&!this.evaluateRule(n));a.length>0&&u.push({priority:a.some(n=>n.blocking)?"p0":"p2",domain:"quality-assessment",action:"Improve Test Coverage",description:`${a.length} coverage gates are failing. Add tests to increase coverage.`,estimatedImpact:"high",effort:"medium",autoFixable:!0}),e.rules.filter(n=>n.category==="security"&&!this.evaluateRule(n)).length>0&&u.push({priority:"p0",domain:"quality-assessment",action:"Address Security Issues",description:"Security gates are failing. Resolve vulnerabilities before release.",estimatedImpact:"high",effort:"medium",autoFixable:!1})}checkBlockers(e,t,u){e.blockers>0?(t.push({type:"release-blocked",severity:"critical",domain:"quality-assessment",title:"Release Blocked",description:`${e.blockers} blocking issues prevent release`,context:{blockers:e.blockers,blockingRules:e.rules.filter(a=>a.blocking&&!this.evaluateRule(a)).map(a=>a.name)}}),u.push({priority:"p0",domain:"quality-assessment",action:"Resolve Release Blockers",description:"Address all blocking quality gate failures before proceeding with release.",estimatedImpact:"high",effort:"medium",autoFixable:!1})):e.releaseReady||t.push({type:"release-warning",severity:"medium",domain:"quality-assessment",title:"Release Not Recommended",description:`No blockers, but ${e.warnings} warnings suggest caution`,context:{warnings:e.warnings}})}async compareToHistory(e,t,u){let a=await e.memory.get("quality-gate:current");a&&(a.passed&&!t.passed&&u.push({type:"quality-gate-regression",severity:"high",domain:"quality-assessment",title:"Quality Gate Regression",description:"Quality gates were passing previously but are now failing",context:{previousBlockers:a.blockers,currentBlockers:t.blockers}}),!a.passed&&t.passed&&u.push({type:"quality-gate-improvement",severity:"info",domain:"quality-assessment",title:"Quality Gates Now Passing",description:"All quality gates are now passing after previous failures",context:{previousFailures:a.failedRules,currentFailures:t.failedRules}}))}calculateHealthScore(e){if(e.rules.length===0)return 100;let u=e.passedRules/e.rules.length*70;return u-=e.blockers*15,u-=e.warnings*5,e.releaseReady&&(u+=10),Math.max(0,Math.min(100,Math.round(u)))}}});var Fvt,wp,LY=f(()=>{"use strict";ou();z();Md();oy();re();B();gS();Fvt={id:"learning-consolidation",name:"Learning Consolidation",description:"Consolidates learning patterns across domains and optimizes strategies",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:3e5,retryCount:2,retryDelayMs:3e4},wp=class extends Ge{lifecycleManager=null;lastRunTimestamp=0;constructor(){super(Fvt)}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=Y();await e.initialize();let t=e.getDatabase();return this.lifecycleManager=Om(t,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch(e){return console.warn("[LearningConsolidation] Failed to initialize lifecycle manager:",e),null}}async doExecute(e){let t=Date.now();e.logger.info("Starting learning consolidation (Phase 7: Continuous Learning Loop)");let u=[],a=[],r=0,n=0,i=0,o=0,l=0,c=await this.getLifecycleManager();if(c){let h=await this.runContinuousLearningLoop(e,c,u,a);r=h.experiencesProcessed,n=h.patternCandidatesFound,i=h.patternsPromoted,o=h.patternsDeprecated,l=h.confidenceDecayApplied}let d=await this.collectPatterns(e),m=await this.consolidatePatterns(e,d);m.experiencesProcessed=r,m.patternCandidatesFound=n,m.patternsPromoted=i,m.patternsDeprecated=o,m.confidenceDecayApplied=l,this.identifyCrossDomainPatterns(d,u,a),this.pruneIneffectivePatterns(d,u,a),this.generateOptimizations(d,u,a);let p=await this.runDreamCycle(e,d,u,a);m.dreamInsights=p.insights,m.dreamPatternsCreated=p.patternsCreated,await e.memory.set("learning:lastConsolidation",m),await e.memory.set("learning:consolidatedPatterns",d),this.lastRunTimestamp=Date.now();let g=this.calculateHealthScore(m,d);return e.logger.info("Learning consolidation complete",{healthScore:g,patternsAnalyzed:m.patternsAnalyzed,newInsights:m.newInsights,experiencesProcessed:r,patternsPromoted:i,patternsDeprecated:o}),this.createResult(Date.now()-t,{itemsAnalyzed:m.patternsAnalyzed,issuesFound:m.patternsPruned+m.patternsDeprecated,healthScore:g,trend:this.determineTrend(m),domainMetrics:{patternsAnalyzed:m.patternsAnalyzed,patternsPruned:m.patternsPruned,patternsConsolidated:m.patternsConsolidated,newInsights:m.newInsights,crossDomainPatterns:m.crossDomainPatterns,dreamInsights:m.dreamInsights,dreamPatternsCreated:m.dreamPatternsCreated,experiencesProcessed:m.experiencesProcessed,patternCandidatesFound:m.patternCandidatesFound,patternsPromoted:m.patternsPromoted,patternsDeprecated:m.patternsDeprecated,confidenceDecayApplied:m.confidenceDecayApplied}},u,a)}async runContinuousLearningLoop(e,t,u,a){e.logger.info("Running continuous learning loop (Phase 7)");let r=0,n=0,i=0,o=0,l=0;try{let c=t.getRecentExperiences({minReward:.7,limit:100,sinceDays:7});if(r=c.length,c.length>0){e.logger.debug("Processing recent experiences",{count:c.length});let h=t.findPatternCandidates(c);if(n=h.length,h.length>0){let y=await this.createPatternsFromCandidates(h);u.push({type:"pattern-extraction",severity:"info",domain:"learning-optimization",title:"New Patterns Extracted from Experiences",description:`${y} new patterns extracted from ${r} high-reward experiences`,context:{candidatesFound:n,patternsCreated:y,topCandidate:h[0]?.name}})}}let d=t.promoteEligiblePatterns();i=d.promoted,i>0&&u.push({type:"pattern-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted to Long-Term",description:`${i} patterns promoted after meeting quality thresholds`,context:{checked:d.checked,promoted:i}});let m=t.deprecateStalePatterns();o=m.deprecated,o>0&&(u.push({type:"pattern-deprecation",severity:"low",domain:"learning-optimization",title:"Underperforming Patterns Deprecated",description:`${o} patterns deprecated due to failures, staleness, or low confidence`,context:{checked:m.checked,deprecated:o}}),a.push({priority:"p3",domain:"learning-optimization",action:"Review Deprecated Patterns",description:`${o} patterns were deprecated. Review for potential recovery or permanent removal.`,estimatedImpact:"low",effort:"low",autoFixable:!1}));try{let y=Y().getDatabase(),D=new To;await D.initialize(y);let C=await D.consolidateAll();(C.merged>0||C.archived>0)&&u.push({type:"experience-consolidation",severity:"info",domain:"learning-optimization",title:"Experiences Consolidated",description:`${C.merged} merged, ${C.archived} archived across ${C.domainsProcessed.length} domains`,context:{merged:C.merged,archived:C.archived,activeRemaining:C.activeRemaining,domains:C.domainsProcessed}})}catch(h){e.logger.warn("Experience consolidation failed",{error:A(h)})}let p=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/(1e3*60*60*24):1;p>=.5&&(l=t.applyConfidenceDecay(Math.min(p,7)).decayed);let g=t.getStats();this.addLifecycleStatsFinding(g,u,a),e.logger.info("Continuous learning loop complete",{experiencesProcessed:r,patternCandidatesFound:n,patternsPromoted:i,patternsDeprecated:o,confidenceDecayApplied:l})}catch(c){e.logger.warn("Continuous learning loop partially failed",{error:A(c)})}return{experiencesProcessed:r,patternCandidatesFound:n,patternsPromoted:i,patternsDeprecated:o,confidenceDecayApplied:l}}async createPatternsFromCandidates(e){let t=0;try{let a=Y().getDatabase();for(let r of e)try{let{v4:n}=await Promise.resolve().then(()=>(O(),Uw)),i=n();a.prepare(`
|
|
5785
|
+
`)}`);return this.cache.set(e,a),a}catch(t){throw t.code==="ENOENT"?new Error(`Workflow template not found: ${e}`):t}}async list(){try{return(await vyt(this.templatesDir)).filter(t=>t.endsWith(".yaml")||t.endsWith(".yml")).map(t=>byt(t,t.endsWith(".yaml")?".yaml":".yml")).sort()}catch(e){if(e.code==="ENOENT")return[];throw e}}async validate(e){let t=[],u=[];if(e.name||t.push("Workflow must have a name"),e.version||t.push("Workflow must have a version"),e.description||u.push("Workflow should have a description"),Array.isArray(e.variables)?e.variables.forEach((a,r)=>{a.name||t.push(`Variable at index ${r} must have a name`),a.type||t.push(`Variable ${a.name} must have a type`),a.required===void 0&&u.push(`Variable ${a.name} should specify if it's required`)}):t.push("Workflow must have a variables array"),!Array.isArray(e.steps))t.push("Workflow must have a steps array");else if(e.steps.length===0)t.push("Workflow must have at least one step");else{e.steps.forEach((n,i)=>{n.name||t.push(`Step at index ${i} must have a name`),n.action||t.push(`Step ${n.name||i} must have an action`),(!n.config||typeof n.config!="object")&&t.push(`Step ${n.name||i} must have a config object`),n.assertions&&Array.isArray(n.assertions)&&n.assertions.forEach((o,l)=>{o.condition||t.push(`Assertion ${l} in step ${n.name||i} must have a condition`),o.message||u.push(`Assertion ${l} in step ${n.name||i} should have a message`)})});let a=e.steps.map(n=>n.name),r=a.filter((n,i)=>a.indexOf(n)!==i);r.length>0&&t.push(`Duplicate step names found: ${r.join(", ")}`)}return{valid:t.length===0,errors:t,warnings:u}}async createContext(e,t){let u=await this.load(e),a=u.variables.filter(n=>n.required&&!(n.name in t)).map(n=>n.name);if(a.length>0)throw new Error(`Missing required variables: ${a.join(", ")}`);let r={};return u.variables.forEach(n=>{n.name in t?r[n.name]=t[n.name]:"default"in n&&(r[n.name]=n.default)}),{variables:r,results:new Map,metadata:{startTime:Date.now(),workflow:u.name,templateName:e}}}async getMetadata(e){try{let t=e9(this.templatesDir,`${e}.yaml`),u=await MW(t,"utf-8"),a=IW(u);return{name:a.name,version:a.version,description:a.description}}catch(t){throw t.code==="ENOENT"?new Error(`Workflow template not found: ${e}`):t}}clearCache(){this.cache.clear()}async reload(e){return this.cache.delete(e),this.load(e)}},NW=new rp});var OW={};ue(OW,{WORKFLOW_CATEGORIES:()=>a9,WORKFLOW_DESCRIPTIONS:()=>_W,WORKFLOW_TEMPLATES:()=>u9,WorkflowLoader:()=>rp,defaultWorkflowLoader:()=>NW,evaluateCondition:()=>LW,getAllWorkflowTemplates:()=>kyt,getWorkflowsByCategory:()=>Ayt,interpolateVariables:()=>t9,isValidWorkflowTemplate:()=>xyt});function Ayt(s){return a9[s]}function xyt(s){return u9.includes(s)}function kyt(){return u9.map(s=>{let e=Object.entries(a9).find(([t,u])=>u.includes(s))?.[0]||"other";return{name:s,description:_W[s],category:e}})}var u9,_W,a9,HW=f(()=>{"use strict";zW();u9=["login-flow","oauth-flow","scraping-workflow","visual-regression","form-validation","navigation-flow","api-integration","performance-audit","accessibility-audit"],_W={"login-flow":"Authentication testing workflow for login forms with credential validation","oauth-flow":"OAuth2/OIDC authentication testing workflow with provider integration","scraping-workflow":"Data extraction workflow for web scraping with pagination and structured output","visual-regression":"Screenshot comparison workflow for visual regression testing across breakpoints","form-validation":"Input validation testing workflow for form fields with error handling","navigation-flow":"Multi-page navigation workflow for testing user journeys and state persistence","api-integration":"Browser-API hybrid testing workflow for validating frontend-backend integration","performance-audit":"Lighthouse-style performance audit workflow with Core Web Vitals","accessibility-audit":"WCAG 2.1 Level AA compliance audit workflow with automated accessibility testing"},a9={authentication:["login-flow","oauth-flow"],testing:["form-validation","navigation-flow","api-integration"],quality:["visual-regression","performance-audit","accessibility-audit"],automation:["scraping-workflow"]}});var Ay,GW=f(()=>{"use strict";ke();B();Ay=class extends J{config={name:"qe/workflows/browser-load",description:"Load, validate, and prepare browser automation workflows from inline YAML or built-in templates. Returns the resolved workflow with steps and variable bindings, ready for browser execution. Templates: login-flow, form-validation, visual-regression, oauth-flow, etc.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{workflowYaml:{type:"string",description:"Inline YAML workflow definition. Mutually exclusive with templateName."},templateName:{type:"string",description:"Built-in template name to load.",enum:["login-flow","oauth-flow","scraping-workflow","visual-regression","form-validation","navigation-flow","api-integration","performance-audit","accessibility-audit"]},variables:{type:"object",description:'Runtime variable overrides (e.g., { "baseUrl": "https://example.com" })'}}}}async execute(e,t){try{let{WorkflowLoader:u,WORKFLOW_TEMPLATES:a,WORKFLOW_DESCRIPTIONS:r,interpolateVariables:n}=await Promise.resolve().then(()=>(HW(),OW)),{parse:i}=await import("yaml"),o=new u,l=[...a],c=r;if(!e.workflowYaml&&!e.templateName)return{success:!0,data:{workflowName:"none",description:"No workflow specified. Use templateName or workflowYaml.",source:"none",templateUsed:null,steps:[],variables:{defined:[],provided:{}},validation:{valid:!0,errors:[],warnings:[]},availableTemplates:l,summary:`Available templates: ${l.join(", ")}`}};let d,m,p=null;e.workflowYaml?(m="inline-yaml",d=i(e.workflowYaml)):(m="template",p=e.templateName,d=await o.load(e.templateName));let g=await o.validate(d),h=(d.steps??[]).map(y=>{let D=y.config;if(e.variables){let C={};for(let[k,F]of Object.entries(D))C[k]=typeof F=="string"?n(F,e.variables):F;D=C}return{name:y.name,action:y.action,config:D,optional:y.optional??!1,assertionCount:y.assertions?.length??0}});return{success:!0,data:{workflowName:d.name||p||"custom",description:d.description||p&&c[p]||"",source:m,templateUsed:p,steps:h,variables:{defined:(d.variables??[]).map(y=>({name:y.name,type:y.type,required:y.required,hasDefault:y.default!==void 0})),provided:e.variables||{}},validation:{valid:g.valid,errors:g.errors,warnings:g.warnings},availableTemplates:l,summary:g.valid?`Workflow "${d.name}" loaded (${m}): ${h.length} steps, ${(d.variables??[]).length} variables`:`Workflow "${d.name}" has validation errors: ${g.errors.join("; ")}`}}}catch(u){return{success:!1,error:A(u)}}}}});function VW(){for(let s of r9)s.resetInstanceCache()}var RMu,r9,n9=f(()=>{"use strict";VU();jU();r$();n$();i$();s$();g$();h$();y$();C$();v$();b$();k$();F$();N$();W$();Q$();iW();cW();vW();RW();PW();GW();RMu={TEST_GENERATE:"qe/tests/generate",TEST_EXECUTE:"qe/tests/execute",COVERAGE_ANALYZE:"qe/coverage/analyze",COVERAGE_GAPS:"qe/coverage/gaps",QUALITY_EVALUATE:"qe/quality/evaluate",DEFECT_PREDICT:"qe/defects/predict",REQUIREMENTS_VALIDATE:"qe/requirements/validate",QUALITY_CRITERIA:"qe/requirements/quality-criteria",CODE_ANALYZE:"qe/code/analyze",SECURITY_SCAN:"qe/security/scan",CONTRACT_VALIDATE:"qe/contracts/validate",VISUAL_COMPARE:"qe/visual/compare",A11Y_AUDIT:"qe/a11y/audit",CHAOS_INJECT:"qe/chaos/inject",LEARNING_OPTIMIZE:"qe/learning/optimize",LEARNING_DREAM:"qe/learning/dream",TOKEN_USAGE:"qe/analysis/token_usage",GOAP_PLAN:"qe/planning/goap_plan",GOAP_EXECUTE:"qe/planning/goap_execute",GOAP_STATUS:"qe/planning/goap_status",...Lm,EMBEDDING_GENERATE:"qe/embeddings/generate",EMBEDDING_COMPARE:"qe/embeddings/compare",EMBEDDING_SEARCH:"qe/embeddings/search",EMBEDDING_STORE:"qe/embeddings/store",EMBEDDING_STATS:"qe/embeddings/stats",...nW,QX_ANALYZE:"qe/qx/analyze",TEST_SCHEDULE:"qe/tests/schedule",LOAD_TEST:"qe/tests/load",URL_VALIDATE:"qe/security/url-validate",BROWSER_WORKFLOW:"qe/workflows/browser-load"},r9=[new zf,new _f,new Hf,new Gf,new Vf,new Kf,new qf,new Sm,new $f,new Wf,new Jf,new Qf,new Zf,new Yf,new Bm,new Tm,new Xf,new Mm,new Im,new Nm,...$$,new r0,new n0,new i0,new s0,new o0,...rW,new qm,new fy,new vy,new by,new Ay]});var cn,xy,jW=f(()=>{"use strict";O();z();Ec();B();cn={ProtocolStarted:"coordination.ProtocolStarted",ProtocolCompleted:"coordination.ProtocolCompleted",ProtocolFailed:"coordination.ProtocolFailed",ProtocolCancelled:"coordination.ProtocolCancelled",ActionStarted:"coordination.ActionStarted",ActionCompleted:"coordination.ActionCompleted",ActionFailed:"coordination.ActionFailed"},xy=class{constructor(e,t,u){this.eventBus=e;this.memory=t;this.getDomainAPI=u}protocols=new Map;executions=new Map;scheduledProtocols=new Map;schedulerRunning=!1;registerProtocol(e){this.protocols.set(e.id,e),e.schedule.type==="event"&&e.enabled&&this.setupEventTriggers(e),(e.schedule.type==="cron"||e.schedule.type==="interval")&&e.enabled&&this.scheduleProtocol(e)}unregisterProtocol(e){if(!this.protocols.get(e))return!1;let u=this.scheduledProtocols.get(e);return u?.intervalId&&clearInterval(u.intervalId),this.scheduledProtocols.delete(e),this.protocols.delete(e),!0}getProtocol(e){return this.protocols.get(e)}listProtocols(){return Array.from(this.protocols.values())}async execute(e,t){let u=this.protocols.get(e);return u?u.enabled?this.executeProtocol(u,t):E(new Error(`Protocol is disabled: ${e}`)):E(new Error(`Protocol not found: ${e}`))}async executeOnEvent(e,t){let u=this.protocols.get(e);return u?u.enabled?this.executeProtocol(u,void 0,t):E(new Error(`Protocol is disabled: ${e}`)):E(new Error(`Protocol not found: ${e}`))}getExecution(e){let t=this.executions.get(e);if(t)return this.toImmutableExecution(t.execution)}listActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.execution.status==="running"||e.execution.status==="paused").map(e=>this.toImmutableExecution(e.execution))}async cancelExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"&&t.execution.status!=="paused"?E(new Error(`Cannot cancel execution in status: ${t.execution.status}`)):(t.cancelled=!0,t.execution.status="cancelled",t.execution.completedAt=new Date,await this.publishEvent(cn.ProtocolCancelled,{executionId:e,protocolId:t.protocol.id}),v(void 0)):E(new Error(`Execution not found: ${e}`))}async pauseExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"?E(new Error(`Cannot pause execution in status: ${t.execution.status}`)):(t.paused=!0,t.execution.status="paused",v(void 0)):E(new Error(`Execution not found: ${e}`))}async resumeExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="paused"?E(new Error(`Cannot resume execution in status: ${t.execution.status}`)):(t.paused=!1,t.execution.status="running",v(void 0)):E(new Error(`Execution not found: ${e}`))}startScheduler(){if(!this.schedulerRunning){this.schedulerRunning=!0;for(let e of this.protocols.values())e.enabled&&(e.schedule.type==="interval"||e.schedule.type==="cron")&&this.scheduleProtocol(e)}}stopScheduler(){this.schedulerRunning=!1;for(let e of this.scheduledProtocols.values())e.intervalId&&(clearInterval(e.intervalId),e.intervalId=void 0)}async dispose(){this.stopScheduler(),this.protocols.clear(),this.executions.clear(),this.scheduledProtocols.clear()}async executeProtocol(e,t,u){let a=x(),r=u?.correlationId??a,n={executionId:a,protocolId:e.id,status:"running",participants:[...e.participants],results:new Map,startedAt:new Date,correlationId:r,triggeredBy:u},i={execution:n,protocol:e,params:t,actionResults:new Map,cancelled:!1,paused:!1};this.executions.set(a,i),await this.publishEvent(cn.ProtocolStarted,{executionId:a,protocolId:e.id,participants:e.participants},r);try{await this.executeActions(i);let o=Array.from(i.actionResults.values()).some(l=>l.status==="failed");return i.cancelled?n.status="cancelled":o?(n.status="failed",await this.publishEvent(cn.ProtocolFailed,{executionId:a,protocolId:e.id,failedActions:Array.from(i.actionResults.values()).filter(l=>l.status==="failed").map(l=>l.actionId)},r)):(n.status="completed",await this.publishEvent(cn.ProtocolCompleted,{executionId:a,protocolId:e.id,duration:Date.now()-n.startedAt.getTime()},r)),n.completedAt=new Date,n.results=i.actionResults,await this.storeExecutionHistory(n),v(this.toImmutableExecution(n))}catch(o){return n.status="failed",n.completedAt=new Date,await this.publishEvent(cn.ProtocolFailed,{executionId:a,protocolId:e.id,error:A(o)},r),E(b(o))}}async executeActions(e){let{protocol:t,actionResults:u}=e,a=new Set(t.actions.map(n=>n.id)),r=new Set;for(;a.size>0&&!e.cancelled;){for(;e.paused&&!e.cancelled;)await this.sleep(100);if(e.cancelled)break;let n=t.actions.filter(o=>a.has(o.id)&&this.dependenciesSatisfied(o,r));if(n.length===0&&a.size>0)throw new Error(`Deadlock detected: actions ${Array.from(a).join(", ")} cannot proceed`);let i=await Promise.allSettled(n.map(o=>this.executeAction(o,e)));for(let o=0;o<n.length;o++){let l=n[o],c=i[o],d;c.status==="fulfilled"?d=c.value:d={actionId:l.id,status:"failed",error:c.reason instanceof Error?c.reason.message:String(c.reason)},u.set(l.id,d),a.delete(l.id),d.status==="completed"&&r.add(l.id)}}for(let n of a)u.set(n,{actionId:n,status:e.cancelled?"cancelled":"skipped"})}async executeAction(e,t){let u=new Date;await this.publishEvent(cn.ActionStarted,{executionId:t.execution.executionId,actionId:e.id,actionName:e.name,targetDomain:e.targetDomain},t.execution.correlationId);let a=0,r=e.retry?.maxAttempts??1,n;for(;a<r;){a++;try{let o=this.getDomainAPI(e.targetDomain);if(!o)throw new Error(`Domain API not available: ${e.targetDomain}`);let l=o[e.method];if(typeof l!="function")throw new Error(`Method ${e.method} not found on domain ${e.targetDomain}`);let c={...e.params,...t.params},d=await this.executeWithTimeout(l.bind(o)(c),e.timeout??3e4),m=new Date;return await this.publishEvent(cn.ActionCompleted,{executionId:t.execution.executionId,actionId:e.id,duration:m.getTime()-u.getTime()},t.execution.correlationId),{actionId:e.id,status:"completed",startedAt:u,completedAt:m,duration:m.getTime()-u.getTime(),result:d,retryAttempts:a>1?a-1:void 0}}catch(o){if(n=b(o),a<r&&e.retry){let l=e.retry.backoffMs*Math.pow(e.retry.backoffMultiplier??2,a-1);await this.sleep(l)}}}let i=new Date;return await this.publishEvent(cn.ActionFailed,{executionId:t.execution.executionId,actionId:e.id,error:n?.message??"Unknown error",attempts:a},t.execution.correlationId),{actionId:e.id,status:"failed",startedAt:u,completedAt:i,duration:i.getTime()-u.getTime(),error:n?.message??"Unknown error",retryAttempts:a>1?a-1:void 0}}dependenciesSatisfied(e,t){return!e.dependsOn||e.dependsOn.length===0?!0:e.dependsOn.every(u=>t.has(u))}async executeWithTimeout(e,t){return Promise.race([e,new Promise((u,a)=>setTimeout(()=>a(new Error("Action timeout")),t))])}setupEventTriggers(e){if(e.schedule.type==="event")for(let t of e.schedule.triggerEvents)this.eventBus.subscribe(t,async u=>{await this.executeOnEvent(e.id,u)})}scheduleProtocol(e){if(e.schedule.type==="interval"){let t={protocolId:e.id,schedule:e.schedule};t.intervalId=setInterval(async()=>{this.schedulerRunning&&await this.execute(e.id)},e.schedule.intervalMs),this.scheduledProtocols.set(e.id,t)}}async storeExecutionHistory(e){let t=`protocol-execution:${e.executionId}`;await this.memory.set(t,{...e,results:Object.fromEntries(e.results)},{namespace:"coordination",ttl:864e5})}toImmutableExecution(e){return{executionId:e.executionId,protocolId:e.protocolId,status:e.status,participants:[...e.participants],results:new Map(e.results),startedAt:e.startedAt,completedAt:e.completedAt,correlationId:e.correlationId,triggeredBy:e.triggeredBy}}async publishEvent(e,t,u){let a=X(e,"learning-optimization",t,u);await this.eventBus.publish(a)}sleep(e){return new Promise(t=>setTimeout(t,e))}}});async function Oi(s){return i9.getInstance(s)}async function KW(s,e,t){return(await Oi()).startTaskTrajectory(s,e,t)}async function ky(s,e,t){return(await Oi()).endTaskTrajectory(s,e,t)}var Fyt,i9,qW=f(()=>{"use strict";CS();Qd();X3();Fyt={enableLearning:!0,enableRouting:!0,enableGuidance:!0,enableTrajectories:!0,enableExperienceReplay:!0,autoStoreExperiences:!0,minQualityThreshold:.6},i9=class s{static instance=null;static initPromise=null;config;enhancedAdapter;disposed=!1;patternsLoaded=!1;qualityThresholdsFromPatterns=null;tasksRecorded=0;successfulTasks=0;failedTasks=0;patternsStored=0;routingRequests=0;activeTrajectories=new Map;constructor(e,t){this.config=e,this.enhancedAdapter=t}static async getInstance(e){if(s.instance&&!s.instance.disposed)return s.instance;if(s.initPromise)return s.initPromise;s.initPromise=s.create(e);try{return s.instance=await s.initPromise,s.instance}finally{s.initPromise=null}}static async create(e){let t={...Fyt,...e},u=Xj({enableTrajectories:t.enableTrajectories,enableExperienceReplay:t.enableExperienceReplay,enablePatternEvolution:!0,autoStoreExperiences:t.autoStoreExperiences,autoConsolidate:!0});await u.initialize();let a=new s(t,u);return await a.loadPatternsFromLoader(),await a.seedInitialPatternsIfNeeded(),console.error("[ReasoningBankService] Initialized with EnhancedReasoningBankAdapter (trajectory + experience + evolution)"),a}async loadPatternsFromLoader(){try{let t=await Si().getQualityGateThresholds();if(t){this.qualityThresholdsFromPatterns=t,this.patternsLoaded=!0,console.error("[ReasoningBankService] Loaded quality thresholds from PatternLoader",{tiers:Object.keys(t)});return}console.error("[ReasoningBankService] PatternLoader returned no thresholds, using defaults")}catch(e){console.error("[ReasoningBankService] Failed to load patterns from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.patternsLoaded=!1}async seedInitialPatternsIfNeeded(){try{let e=await this.enhancedAdapter.getStats();if(e.reasoningBank.totalPatterns>0){console.error(`[ReasoningBankService] Found ${e.reasoningBank.totalPatterns} existing patterns, skipping seed`);return}console.error("[ReasoningBankService] Seeding initial QE patterns...");let t=(a,r="string",n=!1)=>({name:a,type:r,required:n,description:`${a} parameter`}),u=[{patternType:"test-template",name:"unit-test-generation",description:"Generate comprehensive unit tests for TypeScript/JavaScript modules",domain:"test-generation",template:{type:"workflow",content:"Analyze module exports, identify edge cases, generate Jest/Vitest tests with proper mocking",variables:[t("modulePath"),t("framework")]},context:{tags:["unit","typescript","jest","vitest"]}},{patternType:"coverage-strategy",name:"coverage-gap-analysis",description:"Identify untested code paths and recommend targeted tests",domain:"coverage-analysis",template:{type:"workflow",content:"Parse coverage report, identify uncovered branches, prioritize by risk, generate recommendations",variables:[t("coveragePath"),t("threshold","number")]},context:{tags:["coverage","analysis","risk"]}},{patternType:"test-template",name:"integration-test-generation",description:"Generate integration tests for API endpoints and service interactions",domain:"test-generation",template:{type:"workflow",content:"Identify API contracts, generate request/response tests, validate error handling",variables:[t("apiPath"),t("framework")]},context:{tags:["integration","api","contract"]}},{patternType:"flaky-fix",name:"flaky-test-remediation",description:"Detect and fix flaky tests through pattern analysis",domain:"test-execution",template:{type:"workflow",content:"Analyze test history, identify timing/race conditions, apply stabilization patterns",variables:[t("testPath"),t("retryCount","number")]},context:{tags:["flaky","stability","retry"]}},{patternType:"error-handling",name:"security-vulnerability-scan",description:"Scan code for security vulnerabilities using OWASP patterns",domain:"security-compliance",template:{type:"workflow",content:"Run SAST analysis, check for injection risks, validate authentication/authorization",variables:[t("targetPath"),t("severity")]},context:{tags:["security","owasp","sast"]}}];for(let a of u)try{await this.enhancedAdapter.storePattern(a),this.patternsStored++}catch(r){console.error(`[ReasoningBankService] Failed to seed pattern ${a.name}:`,r)}console.error(`[ReasoningBankService] Seeded ${u.length} initial patterns`)}catch(e){console.error("[ReasoningBankService] Failed to seed patterns:",e)}}getPatternsLoaded(){return this.patternsLoaded}getQualityThresholdsFromPatterns(){return this.qualityThresholdsFromPatterns}async startTaskTrajectory(e,t,u={}){if(!this.config.enableTrajectories||this.disposed)return e;try{let a=await this.enhancedAdapter.startTaskTrajectory(t,u);return this.activeTrajectories.set(e,a),console.error(`[ReasoningBankService] Started trajectory: task=${e} trajectory=${a}`),a}catch(a){return console.error("[ReasoningBankService] Failed to start trajectory:",a),e}}async recordTrajectoryStep(e,t,u,a){if(!this.config.enableTrajectories||this.disposed)return;let r=this.activeTrajectories.get(e);if(!r){console.error(`[ReasoningBankService] No active trajectory for task ${e}`);return}try{await this.enhancedAdapter.recordTaskStep(r,t,u,a)}catch(n){console.error("[ReasoningBankService] Failed to record trajectory step:",n)}}async endTaskTrajectory(e,t,u){if(!this.config.enableTrajectories||this.disposed)return null;let a=this.activeTrajectories.get(e);if(!a)return console.error(`[ReasoningBankService] No active trajectory for task ${e}`),null;try{let r=await this.enhancedAdapter.endTaskTrajectory(a,t,u);return this.activeTrajectories.delete(e),console.error(`[ReasoningBankService] Ended trajectory: task=${e} success=${t} steps=${r.steps.length} quality=${r.metrics.averageQuality.toFixed(2)}`),r}catch(r){return console.error("[ReasoningBankService] Failed to end trajectory:",r),this.activeTrajectories.delete(e),null}}getActiveTrajectoryId(e){return this.activeTrajectories.get(e)}async recordTaskOutcome(e){if(!(!this.config.enableLearning||this.disposed)){this.tasksRecorded++,e.success?this.successfulTasks++:this.failedTasks++;try{let t={patternId:`task-${e.taskId}`,success:e.success,metrics:{executionTimeMs:e.executionTimeMs,testsPassed:e.metrics?.testsPassed,testsFailed:e.metrics?.testsGenerated?e.metrics.testsGenerated-(e.metrics.testsPassed||0):void 0,coverageImprovement:e.metrics?.coverageImprovement},feedback:e.error};await this.enhancedAdapter.recordPatternOutcome(t),e.success&&(e.qualityScore||.5)>=this.config.minQualityThreshold&&(await this.storeTaskPattern(e),this.patternsStored++),e.agentId&&await this.updateAgentPerformanceFromOutcome(e),console.error(`[ReasoningBankService] Recorded outcome: task=${e.taskId} success=${e.success} quality=${e.qualityScore?.toFixed(2)||"N/A"}`)}catch(t){throw console.error("[ReasoningBankService] Failed to record outcome:",t),t}}}async updateAgentPerformanceFromOutcome(e){if(e.agentId)try{pK(e.agentId,{success:e.success,executionTimeMs:e.executionTimeMs,qualityScore:e.qualityScore}),console.error(`[ReasoningBankService] Updated agent performance: agent=${e.agentId} success=${e.success} duration=${e.executionTimeMs}ms`)}catch(t){console.error("[ReasoningBankService] Failed to update agent performance:",t)}}async storeTaskPattern(e){try{let t=[e.taskType,e.domain||"general",e.agentId?`agent:${e.agentId}`:void 0,e.modelTier?`tier:${e.modelTier}`:void 0,e.executionTimeMs?`duration:${e.executionTimeMs}ms`:void 0].filter(u=>u!==void 0);await this.enhancedAdapter.storePattern({patternType:"test-template",name:`${e.taskType}-${e.domain||"general"}`,description:e.task,template:{type:"workflow",content:e.task,variables:[]},context:{tags:t}})}catch(t){console.error("[ReasoningBankService] Failed to store pattern:",t)}}async getRoutingRecommendation(e){if(!this.config.enableRouting||this.disposed)return this.createFallbackRouting(e);this.routingRequests++;try{let t=await this.enhancedAdapter.routeTaskWithExperience(e);if(!t.success)return console.error("[ReasoningBankService] Routing returned error:",t.error),this.createFallbackRouting(e);let u=t.value;return u.experienceGuidance&&console.error(`[ReasoningBankService] Experience guidance: strategy="${u.experienceGuidance.recommendedStrategy}" confidence=${u.experienceGuidance.confidence.toFixed(2)} tokenSavings=${u.experienceGuidance.estimatedTokenSavings}`),console.error(`[ReasoningBankService] Routing: task="${e.task.slice(0,50)}..." -> agent=${u.recommendedAgent} confidence=${u.confidence.toFixed(2)}`),u}catch(t){return console.error("[ReasoningBankService] Routing failed:",t),this.createFallbackRouting(e)}}async getExperienceGuidance(e,t){if(!this.config.enableExperienceReplay||this.disposed)return null;try{return await this.enhancedAdapter.getExperienceGuidance(e,t)}catch(u){return console.error("[ReasoningBankService] Failed to get experience guidance:",u),null}}async getTaskGuidance(e,t){if(!this.config.enableGuidance||this.disposed)return[];try{let u=await this.enhancedAdapter.routeTaskWithExperience({task:e,domain:t});return u.success?u.value.guidance:[]}catch(u){return console.error("[ReasoningBankService] Guidance failed:",u),[]}}async searchPatterns(e,t){if(this.disposed)return[];try{let u=await this.enhancedAdapter.searchPatterns(e,{limit:t?.limit||10,domain:t?.domain});return u.success?u.value.map(a=>a.pattern):(console.error("[ReasoningBankService] Search returned error:",u.error),[])}catch(u){return console.error("[ReasoningBankService] Search failed:",u),[]}}async getStats(){let e=await this.enhancedAdapter.getStats();return{service:{tasksRecorded:this.tasksRecorded,successfulTasks:this.successfulTasks,failedTasks:this.failedTasks,successRate:this.tasksRecorded>0?this.successfulTasks/this.tasksRecorded:0,patternsStored:this.patternsStored,routingRequests:this.routingRequests,patternsLoaded:this.patternsLoaded,activeTrajectories:this.activeTrajectories.size},reasoningBank:e.reasoningBank,adapter:e.adapter}}createFallbackRouting(e){return{recommendedAgent:"qe-test-architect",confidence:.5,alternatives:[],domains:e.domain?[e.domain]:["test-generation"],patterns:[],guidance:[],reasoning:"Fallback routing - ReasoningBank unavailable",latencyMs:0}}isHealthy(){return!this.disposed}async dispose(){this.disposed||(this.disposed=!0,await this.enhancedAdapter.dispose(),this.activeTrajectories.clear(),s.instance=null,console.error("[ReasoningBankService] Disposed"))}static reset(){s.instance&&s.instance.dispose(),s.instance=null,s.initPromise=null}}});var o9={};ue(o9,{handleModelRoute:()=>Ry,handleReasoningBankStats:()=>Ryt,handleRoutingEconomics:()=>My,handleRoutingMetrics:()=>Py,handleTaskCancel:()=>Ty,handleTaskList:()=>Sy,handleTaskOrchestrate:()=>wy,handleTaskOutcomeRecord:()=>wyt,handleTaskStatus:()=>By,handleTaskStatusWithLearning:()=>Pyt,handleTaskSubmit:()=>Fy,subscribeTrajectoryEvents:()=>Myt,unsubscribeTrajectoryEvents:()=>WW});async function Fy(s){if(!ye())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=fe();try{let t=await e.submitTask({type:s.type,priority:s.priority||"p1",targetDomains:s.targetDomains||[],payload:s.payload||{},timeout:s.timeout||3e5});if(!t.success)return{success:!1,error:t.error.message};let u=e.getTaskStatus(t.value);return{success:!0,data:{taskId:t.value,type:s.type,priority:s.priority||"p1",status:u?.status==="running"?"pending":"queued",assignedDomain:u?.assignedDomain}}}catch(t){return{success:!1,error:`Failed to submit task: ${A(t)}`}}}async function Sy(s){if(!ye())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=fe();try{let t=e.listTasks({status:s.status,priority:s.priority,domain:s.domain});return{success:!0,data:(typeof s.limit=="number"?t.slice(0,s.limit):t).map(r=>({taskId:r.taskId,type:r.task.type,status:r.status,priority:r.task.priority,assignedDomain:r.assignedDomain,assignedAgents:r.assignedAgents,result:r.result,error:r.error,createdAt:r.task.createdAt.toISOString(),startedAt:r.startedAt?.toISOString(),completedAt:r.completedAt?.toISOString(),duration:r.completedAt&&r.startedAt?r.completedAt.getTime()-r.startedAt.getTime():void 0}))}}catch(t){return{success:!1,error:`Failed to list tasks: ${A(t)}`}}}async function By(s){if(!ye())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=fe();try{let t=e.getTaskStatus(s.taskId);return t?{success:!0,data:{taskId:t.taskId,type:t.task.type,status:t.status,priority:t.task.priority,assignedDomain:t.assignedDomain,assignedAgents:t.assignedAgents,result:s.detailed?t.result:void 0,error:t.error,createdAt:t.task.createdAt.toISOString(),startedAt:t.startedAt?.toISOString(),completedAt:t.completedAt?.toISOString(),duration:t.completedAt&&t.startedAt?t.completedAt.getTime()-t.startedAt.getTime():void 0}}:{success:!1,error:`Task not found: ${s.taskId}`}}catch(t){return{success:!1,error:`Failed to get task status: ${A(t)}`}}}async function Ty(s){if(!ye())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=fe();try{let t=await e.cancelTask(s.taskId);return t.success?{success:!0,data:{taskId:s.taskId,cancelled:!0}}:{success:!1,error:t.error.message}}catch(t){return{success:!1,error:`Failed to cancel task: ${A(t)}`}}}async function wy(s){if(!ye())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e,workflowOrchestrator:t}=fe();try{let u=s.context?.project||$W(s.task),a=s.priority==="critical"||/\b(security|vulnerability|cve|owasp|critical|production|exploit)\b/i.test(s.task),n=await(await rn()).routeTask({task:s.task,codeContext:s.codeContext,filePaths:s.filePaths,manualTier:s.manualTier,isCritical:a,agentType:`qe-${u}`,domain:u,metadata:{inferredDomain:u,hasCodeContext:!!s.codeContext,fileCount:s.filePaths?.length}}),o=await(await Oi()).getExperienceGuidance(s.task,s.context?.project),l=Byt(s.task),c=Tyt(s.priority||"medium"),d=Syt[l];if(d&&t){console.log(`[TaskOrchestrate] Task type '${l}' has workflow '${d}' - executing workflow`);let h=s.task.match(/https?:\/\/[^\s]+/i),y=h?h[0]:void 0;y&&console.log(`[TaskOrchestrate] Detected URL for analysis: ${y}`);let D={targetId:s.context?.project||y||`task-${Date.now()}`,targetType:y?"website":"epic",description:s.task,acceptanceCriteria:s.context?.requirements||[],url:y,routing:{tier:n.decision.tier,modelId:n.modelId,executionStrategy:n.executionStrategy,complexity:n.decision.complexityAnalysis.overall}},C=await t.executeWorkflow(d,D);return C.success?{success:!0,data:{taskId:C.value,type:l,priority:c,strategy:s.strategy||"adaptive",status:"workflow-started",message:`Workflow '${d}' started for task: ${s.task}`,routing:{tier:n.decision.tier,tierName:n.tierInfo.name,modelId:n.modelId,executionStrategy:n.executionStrategy,complexity:n.decision.complexityAnalysis.overall,confidence:n.decision.confidence,useAgentBooster:n.useAgentBooster,rationale:n.decision.rationale,decisionTimeMs:n.decision.metadata.decisionTimeMs}}}:{success:!1,error:`Workflow execution failed: ${C.error.message}`}}let m={description:s.task,strategy:s.strategy||"adaptive",maxAgents:s.maxAgents,context:s.context};l==="generate-tests"&&(m.sourceFiles=s.filePaths||[],m.sourceCode=s.codeContext||"",m.language=m.language||"typescript",m.testType=m.testType||"unit");let p=await e.submitTask({type:l,priority:c,targetDomains:[],payload:{...m,routing:{tier:n.decision.tier,modelId:n.modelId,executionStrategy:n.executionStrategy,useAgentBooster:n.useAgentBooster,agentBoosterTransform:n.decision.agentBoosterTransform,complexity:n.decision.complexityAnalysis.overall,confidence:n.decision.confidence},experienceGuidance:o?{strategy:o.recommendedStrategy,actions:o.suggestedActions,confidence:o.confidence,tokenSavings:o.estimatedTokenSavings}:void 0},timeout:6e5});if(!p.success)return{success:!1,error:p.error.message};let g=p.value;return await KW(g,s.task,{agent:"queen-coordinator",domain:s.context?.project}),{success:!0,data:{taskId:g,type:l,priority:c,strategy:s.strategy||"adaptive",status:"submitted",message:`Task orchestrated: ${s.task}${o?" (with experience guidance)":""}`,routing:{tier:n.decision.tier,tierName:n.tierInfo.name,modelId:n.modelId,executionStrategy:n.executionStrategy,complexity:n.decision.complexityAnalysis.overall,confidence:n.decision.confidence,useAgentBooster:n.useAgentBooster,rationale:n.decision.rationale,decisionTimeMs:n.decision.metadata.decisionTimeMs}}}}catch(u){return{success:!1,error:`Failed to orchestrate task: ${A(u)}`}}}async function Ry(s){try{let e=await rn(),t=s.domain||$W(s.task),u=s.isCritical??/\b(security|vulnerability|cve|owasp|critical|production|exploit)\b/i.test(s.task),a=await e.routeTask({task:s.task,codeContext:s.codeContext,filePaths:s.filePaths,manualTier:s.manualTier,isCritical:u,agentType:s.agentType||`qe-${t}`,domain:t,metadata:{inferredDomain:t,hasCodeContext:!!s.codeContext,fileCount:s.filePaths?.length}});return{success:!0,data:{tier:a.decision.tier,tierName:a.tierInfo.name,modelId:a.modelId,executionStrategy:a.executionStrategy,useAgentBooster:a.useAgentBooster,agentBoosterTransform:a.decision.agentBoosterTransform,complexity:{overall:a.decision.complexityAnalysis.overall,code:a.decision.complexityAnalysis.codeComplexity,reasoning:a.decision.complexityAnalysis.reasoningComplexity,scope:a.decision.complexityAnalysis.scopeComplexity},confidence:a.decision.confidence,rationale:a.decision.rationale,warnings:a.decision.warnings,budget:{allowed:a.decision.budgetDecision.allowed,wasDowngraded:a.decision.budgetDecision.wasDowngraded,estimatedCostUsd:a.decision.budgetDecision.estimatedCostUsd},decisionTimeMs:a.decision.metadata.decisionTimeMs}}}catch(e){return{success:!1,error:`Failed to route task: ${A(e)}`}}}async function Py(s){try{let e=await rn(),t=e.getRoutingStats(),u=e.getMetrics(),a={stats:t,modelRouterMetrics:{totalDecisions:u.totalDecisions,avgDecisionTimeMs:u.avgDecisionTimeMs,agentBoosterStats:u.agentBoosterStats,budgetStats:u.budgetStats}};return s.includeLog&&(a.log=e.getRoutingLog(s.logLimit||100)),{success:!0,data:a}}catch(e){return{success:!1,error:`Failed to get routing metrics: ${A(e)}`}}}async function My(s){try{let{createRoutingFeedbackCollector:e}=await Promise.resolve().then(()=>(DB(),mq)),{getGlobalCostTracker:t}=await Promise.resolve().then(()=>(EB(),dq)),u=e(100);await u.initialize(),u.enableEconomicRouting({...s.taskComplexity!=null?{}:{}},t());let a=u.getEconomicReport();return a?{success:!0,data:{tierEfficiency:a.tierEfficiency.map(n=>({...n,qualityPerDollar:isFinite(n.qualityPerDollar)?n.qualityPerDollar:"Infinity"})),currentHourlyCostUsd:a.currentHourlyCostUsd,currentDailyCostUsd:a.currentDailyCostUsd,budgetRemaining:a.budgetRemaining,recommendation:a.recommendation,savingsOpportunity:a.savingsOpportunity}}:{success:!1,error:"Economic routing is not available"}}catch(e){return{success:!1,error:`Failed to get economic routing report: ${A(e)}`}}}function $W(s){let e=s.toLowerCase();return/\b(security|vulnerabilit|cve|owasp|secret|credential|injection|xss|csrf)\b/.test(e)?"security-compliance":/\b(chaos|resilience|fault.?inject|disaster|failover)\b/.test(e)?"chaos-resilience":/\b(defect|bug.?predict|risk.?assess|mutation)\b/.test(e)?"defect-intelligence":/\b(coverage|uncovered|gap.?analy)\b/.test(e)?"coverage-analysis":/\b(quality|code.?review|maintain|tech.?debt)\b/.test(e)?"quality-assessment":/\b(contract|api.?compat|breaking.?change|pact)\b/.test(e)?"contract-testing":/\b(index|knowledge.?graph|semantic|code.?intel)\b/.test(e)?"code-intelligence":/\b(accessib|a11y|wcag|screen.?read)\b/.test(e)?"visual-accessibility":/\b(requirement|bdd|acceptance|user.?stor)\b/.test(e)?"requirements-validation":/\b(generat.*test|test.*generat|write.*test|create.*test)\b/.test(e)?"test-generation":/\b(run.*test|execut.*test)\b/.test(e)?"test-execution":"test-generation"}function Byt(s){let e=s.toLowerCase();return/run\s+(?:\w+\s+)*tests?/.test(e)||/execute\s+(?:\w+\s+)*tests?/.test(e)||e.includes("run tests")||e.includes("execute tests")?"execute-tests":e.includes("generate test")||e.includes("create test")||e.includes("write test")?"generate-tests":e.includes("coverage")||e.includes("uncovered")?"analyze-coverage":e.includes("quality")||e.includes("code quality")?"assess-quality":e.includes("defect")||e.includes("bug")||e.includes("predict")?"predict-defects":e.includes("requirement")||e.includes("bdd")||e.includes("acceptance")?"validate-requirements":e.includes("index")||e.includes("knowledge graph")||e.includes("semantic")?"index-code":e.includes("security")||e.includes("vulnerability")||e.includes("owasp")?"scan-security":e.includes("contract")||e.includes("api contract")||e.includes("pact")?"validate-contracts":e.includes("accessibility")||e.includes("a11y")||e.includes("wcag")?"test-accessibility":e.includes("chaos")||e.includes("resilience")||e.includes("fault")?"run-chaos":e.includes("learn")||e.includes("optimize")||e.includes("improve")?"optimize-learning":e.includes("ideation")||e.includes("quality criteria")||e.includes("htsm")||e.includes("qcsd")||e.includes("testability")||e.includes("pi planning")||e.includes("sprint planning")?"ideation-assessment":"generate-tests"}function Tyt(s){switch(s){case"critical":return"p0";case"high":return"p1";case"medium":return"p2";case"low":return"p3";default:return"p1"}}async function wyt(s){try{let e=await Oi(),t={taskId:s.taskId,task:s.task,taskType:s.taskType,success:s.success,executionTimeMs:s.executionTimeMs,agentId:s.agentId,domain:s.domain,modelTier:s.modelTier,qualityScore:s.qualityScore,error:s.error,metrics:s.metrics};await e.recordTaskOutcome(t);let u=s.success&&(s.qualityScore||.5)>=.6;return{success:!0,data:{recorded:!0,patternStored:u,message:u?`Outcome recorded and pattern stored for task ${s.taskId}`:`Outcome recorded for task ${s.taskId}`}}}catch(e){return{success:!1,error:`Failed to record task outcome: ${A(e)}`}}}async function Ryt(){try{let e=await(await Oi()).getStats();return{success:!0,data:{service:e.service,patterns:{totalPatterns:e.reasoningBank.totalPatterns,byDomain:e.reasoningBank.byDomain,byTier:e.reasoningBank.byTier,learningOutcomes:e.reasoningBank.learningOutcomes,patternSuccessRate:e.reasoningBank.patternSuccessRate},embeddings:{cacheSize:e.reasoningBank.embeddingCacheSize,dimension:e.reasoningBank.embeddingDimension,transformerAvailable:e.reasoningBank.transformerAvailable},performance:{avgRoutingLatencyMs:e.reasoningBank.avgRoutingLatencyMs,p95RoutingLatencyMs:e.reasoningBank.p95RoutingLatencyMs}}}}catch(s){return{success:!1,error:`Failed to get ReasoningBank stats: ${A(s)}`}}}async function Pyt(s){if(!ye())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:e}=fe();try{let t=e.getTaskStatus(s.taskId);if(!t)return{success:!1,error:`Task not found: ${s.taskId}`};let u={taskId:t.taskId,type:t.task.type,status:t.status,priority:t.task.priority,assignedDomain:t.assignedDomain,assignedAgents:t.assignedAgents,result:s.detailed?t.result:void 0,error:t.error,createdAt:t.task.createdAt.toISOString(),startedAt:t.startedAt?.toISOString(),completedAt:t.completedAt?.toISOString(),duration:t.completedAt&&t.startedAt?t.completedAt.getTime()-t.startedAt.getTime():void 0};if((t.status==="completed"||t.status==="failed")&&!UW.has(s.taskId)){UW.add(s.taskId);try{let a=await Oi(),r=u.duration||0,n=t.status==="completed",i=t.task.payload||{},o=typeof i.description=="string"?i.description:t.task.type,l=i.routing,c=await ky(s.taskId,n,t.error),d=c?.metrics.averageQuality??(n?.7:.3);await a.recordTaskOutcome({taskId:s.taskId,task:o,taskType:t.task.type,success:n,executionTimeMs:r,agentId:t.assignedAgents?.[0],domain:t.assignedDomain,modelTier:l?.tier,qualityScore:d,error:t.error,metrics:{testsGenerated:typeof t.result=="object"&&t.result?t.result.testsGenerated:void 0,testsPassed:typeof t.result=="object"&&t.result?t.result.testsPassed:void 0}}),console.error(`[TaskHandler] Recorded learning outcome: task=${s.taskId} success=${n} quality=${d.toFixed(2)} trajectorySteps=${c?.steps.length??0}`)}catch(a){console.error("[TaskHandler] Failed to record outcome:",a)}}return{success:!0,data:u}}catch(t){return{success:!1,error:`Failed to get task status: ${A(t)}`}}}function Myt(s){WW(s);let e=s.subscribeToEventType("TaskCompleted",async u=>{let{taskId:a}=u.payload;a&&await ky(a,!0).catch(()=>{})}),t=s.subscribeToEventType("TaskFailed",async u=>{let{taskId:a,error:r}=u.payload;a&&await ky(a,!1,r).catch(()=>{})});s9=[e,t]}function WW(s){for(let e of s9)s.unsubscribe(e);s9=[]}var Syt,UW,s9,Iy=f(()=>{"use strict";on();of();qW();B();Syt={"ideation-assessment":"qcsd-ideation-swarm"};UW=new Set;s9=[]});var QW={};ue(QW,{DEFAULT_STRUCTURAL_HEALTH_CONFIG:()=>JW,StructuralHealthMonitor:()=>Ny,createStructuralHealthMonitor:()=>Iyt});function Iyt(s){return new Ny(s)}var JW,Ny,ZW=f(()=>{"use strict";zS();JW={healthyThreshold:.4,warningThreshold:.2,maxHistoryEntries:100,enableLogging:!1},Ny=class{config;minCutService;history=[];constructor(e){this.config={...JW,...e},this.minCutService=Z3()}computeFleetHealth(e){if(e.length===0)return this.emptyFleetResult();let t=this.minCutService.buildTaskGraphFromTopology(e);return this.computeFleetHealthFromGraph(t,e.length)}computeFleetHealthFromGraph(e,t){if(e.nodes.length===0)return this.emptyFleetResult();let u=this.minCutService.getStructuralHealth(e),a=this.determineStatus(u.normalizedLambda),r={lambda:u.lambda,healthy:u.healthy,weakPoints:u.weakPoints,normalizedLambda:u.normalizedLambda,riskScore:u.riskScore,status:a,suggestions:u.suggestions,measuredAt:new Date};return this.addHistoryEntry({lambda:u.lambda,healthy:u.healthy,weakPointCount:u.weakPoints.length,agentCount:t??e.nodes.length,timestamp:r.measuredAt}),this.config.enableLogging&&this.logHealth(r),r}getTrend(){if(this.history.length<2)return"stable";let e=Math.min(5,this.history.length),t=this.history.slice(-e),u=t[0].lambda,r=t[t.length-1].lambda-u;return Math.abs(r)<.05?"stable":r>0?"improving":"degrading"}getHistory(e){let t=[...this.history];return e!==void 0&&e<t.length?t.slice(-e):t}clearHistory(){this.history.length=0}getMinCutService(){return this.minCutService}determineStatus(e){return e>=this.config.healthyThreshold?"healthy":e>=this.config.warningThreshold?"warning":"critical"}addHistoryEntry(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}emptyFleetResult(){return{lambda:0,healthy:!1,weakPoints:[],normalizedLambda:0,riskScore:1,status:"empty",suggestions:["No agents in fleet. Spawn agents to build a topology."],measuredAt:new Date}}logHealth(e){console.error(`[StructuralHealth] Status: ${e.status} | Lambda: ${e.normalizedLambda.toFixed(3)} | Weak points: ${e.weakPoints.length} | Risk: ${(e.riskScore*100).toFixed(0)}%`)}}});function fe(){return q}function ye(){return q.initialized&&q.kernel!==null&&q.queen!==null}function XW(s,e){if(q.topology!=="hierarchical"){let r={agentId:s,domain:e,level:"worker",spawnedAt:new Date};return q.agentLevels.set(s,r),"worker"}let u=Array.from(q.agentLevels.values()).find(r=>r.domain===e&&r.level==="lead")?"worker":"lead",a={agentId:s,domain:e,level:u,spawnedAt:new Date};return q.agentLevels.set(s,a),u}function eJ(s){return q.agentLevels.get(s)}async function np(s){try{if(q.initialized&&q.kernel&&q.queen)return{success:!0,data:{fleetId:q.fleetId,topology:s.topology||"hierarchical",maxAgents:s.maxAgents||15,enabledDomains:s.enabledDomains||YW,status:"ready"}};q.fleetId=`fleet-${x().slice(0,8)}`;let e=s.enabledDomains||[...ne],t=e.filter(o=>o!=="coordination");q.kernel=new J1({maxConcurrentAgents:s.maxAgents||15,memoryBackend:s.memoryBackend||"hybrid",hnswEnabled:!0,lazyLoading:s.lazyLoading!==!1,enabledDomains:e}),await q.kernel.initialize(),q.router=new w3(q.kernel.eventBus),await q.router.initialize();let u=o=>q.kernel.getDomainAPI(o),a=new xy(q.kernel.eventBus,q.kernel.memory,u),r=q.kernel.plugins;await r.loadAll();let n=new Map;for(let o of r.getLoaded()){let l=r.getPlugin(o);l&&n.set(o,l)}q.queen=Sj(q.kernel,q.router,a,void 0,n),await q.queen.initialize(),q.workflowOrchestrator=new Id(q.kernel.eventBus,q.kernel.memory,q.kernel.coordinator),await q.workflowOrchestrator.initialize(),Nyt(q.kernel,q.workflowOrchestrator);let{subscribeTrajectoryEvents:i}=await Promise.resolve().then(()=>(Iy(),o9));return i(q.router),q.initialized=!0,q.initTime=new Date,q.topology=s.topology||"hierarchical",q.agentLevels.clear(),{success:!0,data:{fleetId:q.fleetId,topology:q.topology,maxAgents:s.maxAgents||15,enabledDomains:t,status:"initialized"}}}catch(e){return{success:!1,error:`Failed to initialize fleet: ${A(e)}`}}}async function l9(s){if(!ye())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{let e=q.queen.getHealth(),t=q.queen.getMetrics(),u={status:e.status,uptime:t.uptime,agents:{total:e.totalAgents,active:e.activeAgents,idle:e.totalAgents-e.activeAgents},tasks:{pending:e.pendingTasks,running:e.runningTasks,completed:t.tasksCompleted,failed:t.tasksFailed}};if(s.includeDomains){let r=[];for(let[n,i]of e.domainHealth)r.push({domain:n,status:i.status,agents:i.agents.total,load:q.queen.getDomainLoad(n)});u.domains=r}let a=q.queen.getDomainTeamManager?.();if(a){let r=a.listDomainTeams(),n=0,i=0;for(let o of r)n+=1+o.teammateIds.length,a.getTeamHealth(o.domain)?.healthy&&i++;u.teams={active:r.length,totalAgentsInTeams:n,healthyCount:i}}s.includeMetrics&&(u.metrics={tasksReceived:t.tasksReceived,tasksCompleted:t.tasksCompleted,tasksFailed:t.tasksFailed,agentUtilization:t.agentUtilization,averageTaskDuration:t.averageTaskDuration});try{let{getUnifiedMemory:r}=await Promise.resolve().then(()=>(re(),Er)),n=r();if(n.isInitialized()){let i=l=>{try{return n.queryCount(l)}catch{return 0}},o=await n.vectorCount();u.learning={totalPatterns:i("qe_patterns"),totalExperiences:i("captured_experiences"),totalTrajectories:i("qe_trajectories"),vectorCount:o,experienceApplications:i("experience_applications"),dreamCycles:i("dream_cycles"),embeddingDimension:384}}}catch{}return{success:!0,data:u}}catch(e){return{success:!1,error:`Failed to get fleet status: ${A(e)}`}}}async function c9(s){if(!ye())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{if(s.domain){let u=q.queen.getDomainHealth(s.domain);return u?{success:!0,data:{domain:s.domain,status:u.status,agents:u.agents,errors:u.errors,lastActivity:u.lastActivity?.toISOString()}}:{success:!1,error:`Domain not found: ${s.domain}`}}let e=q.queen.getHealth(),t={status:e.status,totalAgents:e.totalAgents,activeAgents:e.activeAgents,pendingTasks:e.pendingTasks,runningTasks:e.runningTasks,workStealingActive:e.workStealingActive,lastHealthCheck:e.lastHealthCheck.toISOString()};if(s.detailed){let u={};for(let[a,r]of e.domainHealth)u[a]={status:r.status,agents:r.agents,errors:r.errors.length,lastActivity:r.lastActivity?.toISOString()};t.domains=u,t.issues=e.issues.map(a=>({severity:a.severity,message:a.message,domain:a.domain,timestamp:a.timestamp.toISOString()}))}try{let{StructuralHealthMonitor:u}=await Promise.resolve().then(()=>(ZW(),QW)),a=new u,r=[];for(let[o]of e.domainHealth){let l=q.queen.getAgentsByDomain(o);for(let c of l)r.push({id:c.id,name:c.name,domain:c.domain})}let n=r.map(o=>({id:o.id,name:o.name,domain:o.domain,capabilities:[o.domain],dependsOn:[],weight:1})),i=a.computeFleetHealth(n);t.structuralHealth={lambda:i.lambda,healthy:i.healthy,normalizedLambda:i.normalizedLambda,riskScore:i.riskScore,status:i.status,weakPoints:i.weakPoints,suggestions:i.suggestions}}catch{}return{success:!0,data:t}}catch(e){return{success:!1,error:`Failed to get fleet health: ${A(e)}`}}}async function d9(){if(JK(),Rf(),VW(),q.workflowOrchestrator&&(await q.workflowOrchestrator.dispose(),q.workflowOrchestrator=null),q.queen&&(await q.queen.dispose(),q.queen=null),q.router){try{let{unsubscribeTrajectoryEvents:s}=await Promise.resolve().then(()=>(Iy(),o9));s(q.router)}catch{}await q.router.dispose(),q.router=null}q.kernel&&(await q.kernel.dispose(),q.kernel=null),q.initialized=!1,q.fleetId=null,q.initTime=null,q.topology="hierarchical",q.agentLevels.clear()}async function m9(){let s=performance.now();try{let e=ye(),t=q.initTime?Date.now()-q.initTime.getTime():0,u={connected:!1,totalEntries:0,namespaces:0},a={enabled:!1,vectorCount:0},r=0;if(e&&q.kernel){let c=q.kernel.memory;try{u.connected=!0;let d=await c.count("default"),m=await c.count("learning"),p=await c.count("patterns");u.totalEntries=d+m+p;let g=0;for(let h of["default","learning","patterns","mcp-tools","coordination"])await c.count(h)>0&&g++;u.namespaces=g}catch{}try{let d=process.env.AQE_V3_HNSW_ENABLED==="true";a.enabled=d;let m=c;d&&typeof m.getVectorCount=="function"&&(a.vectorCount=await m.getVectorCount())}catch{}try{r=(await c.search("pattern:*",1e3)).length}catch{}}let n=e&&q.kernel?(q.kernel.getLoadedDomains?.()??YW).length:0,i=null;try{let{getSharedRvfDualWriterSync:c}=await Promise.resolve().then(()=>(Jr(),pi)),d=c();if(d){let m=d.status(),p=d.getDivergenceReport();i={mode:m.mode,vectorCount:m.rvf?.totalVectors??0,divergences:p.divergences,promotionSafe:d.isPromotionSafe()}}}catch{}let o=null;try{let{SQLitePatternStore:c}=await Promise.resolve().then(()=>(tm(),jj)),d=new c;await d.initialize(),o=d.getGhostPatternCount(),d.close()}catch{}return{success:!0,data:{status:e?"healthy":"unhealthy",version:"3.8.13",loadedDomains:n,memory:u,hnsw:a,rvf:i??void 0,ghostPatterns:o??void 0,loadedPatterns:r,uptimeMs:t,timestamp:new Date().toISOString()},metadata:{executionTime:performance.now()-s,timestamp:new Date().toISOString(),requestId:x(),toolName:"aqe_health"}}}catch(e){return{success:!1,error:A(e),metadata:{executionTime:performance.now()-s,timestamp:new Date().toISOString(),requestId:x(),toolName:"aqe_health"}}}}function Nyt(s,e){let t=s.getDomainAPI("requirements-validation");t?.registerWorkflowActions&&(t.registerWorkflowActions(e),console.log("[Fleet] Registered requirements-validation workflow actions (includes QCSD Ideation)"));let u=s.getDomainAPI("visual-accessibility");u?.registerWorkflowActions&&(u.registerWorkflowActions(e),console.log("[Fleet] Registered visual-accessibility workflow actions"))}var YW,q,on=f(()=>{"use strict";O();lV();z();Bj();Nk();Tj();aB();Pf();n9();jW();B();YW=ne.filter(s=>s!=="coordination"),q={fleetId:null,kernel:null,queen:null,router:null,workflowOrchestrator:null,initialized:!1,initTime:null,topology:"hierarchical",agentLevels:new Map}});import{randomUUID as CDt}from"crypto";var Ge,ou=f(()=>{"use strict";B();Ge=class{constructor(e){this.config=e}_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let t=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let u,a;for(let n=0;n<=this.config.retryCount;n++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");a=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(i){u=b(i),e.logger.warn(`Worker ${this.config.id} attempt ${n+1} failed: ${u.message}`),n<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let r=Date.now()-t;return a?(this._successfulExecutions++,this._lastResult=a):(this._failedExecutions++,a=this.createErrorResult(u,r),this._lastResult=a),this._executionDurations.push(r),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:a.success,durationMs:r}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=a.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:a.success,durationMs:r,findingsCount:a.findings.length,healthScore:a.metrics.healthScore}}),a}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((u,a)=>u+a,0)/this._executionDurations.length:0,t=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(t*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,t,u){return new Promise((a,r)=>{let n=setTimeout(()=>{r(new Error(`Worker execution timed out after ${t}ms`))},t),i=()=>{clearTimeout(n),r(new Error("Worker execution aborted"))};u.addEventListener("abort",i,{once:!0}),e().then(o=>{clearTimeout(n),u.removeEventListener("abort",i),a(o)}).catch(o=>{clearTimeout(n),u.removeEventListener("abort",i),r(o)})})}createErrorResult(e,t){return{workerId:this.config.id,timestamp:new Date,durationMs:t,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,t,u,a){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:t,findings:u,recommendations:a}}delay(e){return new Promise(t=>setTimeout(t,e))}generateId(){return`${Date.now()}-${CDt().slice(0,9)}`}}});var vDt,y0,Z9=f(()=>{"use strict";ou();oy();re();IT();B();vDt={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},y0=class extends Ge{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(vDt),this.dailyLogger=new Hm}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=Y();await e.initialize();let t=e.getDatabase();return this.lifecycleManager=Om(t,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return Y().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let t=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let u=[],a=[],r=await this.getLifecycleManager();if(!r)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-t,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let n=0,i=0;try{let D=r.promoteEligiblePatterns();n=D.promoted,i=D.checked,n>0&&u.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${n} of ${i} short-term patterns promoted to long-term`})}catch(D){e.logger.warn("Pattern promotion failed",{error:A(D)})}let o=0,l=0;try{let D=r.deprecateStalePatterns();o=D.deprecated,l=D.checked,o>0&&u.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${o} of ${l} patterns deprecated (stale, failed, or low confidence)`})}catch(D){e.logger.warn("Stale pattern detection failed",{error:A(D)})}let c=0;try{let D=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;c=r.applyConfidenceDecay(Math.min(D,7)).decayed}catch(D){e.logger.warn("Confidence decay failed",{error:A(D)})}let d=this.getPendingExperienceCount(),m={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{m=r.getStats()}catch(D){e.logger.warn("Stats retrieval failed",{error:A(D)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${n} promoted, ${o} deprecated, ${c} decayed, ${d} pending exp, ${m.activePatterns} active patterns (avg conf: ${m.avgConfidence.toFixed(2)})`,details:{promoted:n,deprecated:o,decayed:c,pendingExperiences:d,totalPatterns:m.totalPatterns,activePatterns:m.activePatterns,avgConfidence:m.avgConfidence,avgSuccessRate:m.avgSuccessRate}}),this.dailyLogger.flush()}catch(D){e.logger.warn("Daily log write failed",{error:A(D)})}this.lastRunTimestamp=Date.now(),m.activePatterns>0&&m.patternsNearDeprecation/m.activePatterns>.5&&a.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${m.patternsNearDeprecation} of ${m.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let p=this.calculateHealthScore(m,n,o),g=this.determineTrend(n,o,m.activePatterns),h=Math.max(i,l),y=n+o+m.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:n,deprecated:o,decayed:c,pendingExperiences:d,healthScore:p}),this.createResult(Date.now()-t,{itemsAnalyzed:h,issuesFound:y,healthScore:p,trend:g,domainMetrics:{promoted:n,deprecated:o,decayed:c,stalePatterns:m.patternsNearDeprecation,pendingExperiences:d,avgConfidence:Number(m.avgConfidence.toFixed(3)),avgSuccessRate:Number(m.avgSuccessRate.toFixed(3))}},u,a)}calculateHealthScore(e,t,u){let a=70;if(a+=Math.min(15,t*5),e.avgConfidence>0&&(a+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let r=u/e.activePatterns;a-=Math.round(r*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(a-=10),Math.max(0,Math.min(100,Math.round(a)))}determineTrend(e,t,u){return u===0?"stable":e>t?"improving":t>e&&t/u>.1?"degrading":"stable"}}});var pw,gw,hw,LD,zD,_D,wY=f(()=>{"use strict";pw=class{handlers=[];async publish(e){for(let t of this.handlers)try{t(e)}catch(u){console.debug("[WorkerManager] Event handler error:",u instanceof Error?u.message:u)}}subscribe(e){return this.handlers.push(e),()=>{let t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)}}dispose(){this.handlers=[]}get handlerCount(){return this.handlers.length}},gw=class{store=new Map;async get(e){return this.store.get(e)}async set(e,t){this.store.set(e,t)}async search(e){let t=new RegExp(e.replace(/\*/g,".*"));return Array.from(this.store.keys()).filter(u=>t.test(u))}clear(){this.store.clear()}get size(){return this.store.size}},hw=class{constructor(e){this.workerId=e}format(e,t,u){let a=new Date().toISOString(),r=u?` ${JSON.stringify(u)}`:"";return`[${a}] [${e}] [${this.workerId}] ${t}${r}`}debug(e,t){process.env.DEBUG&&console.debug(this.format("DEBUG",e,t))}info(e,t){console.info(this.format("INFO",e,t))}warn(e,t){console.warn(this.format("WARN",e,t))}error(e,t){console.error(this.format("ERROR",e,t))}},LD=class{constructor(e){this.kernelGetter=e}getDomainAPI(e){let t=this.kernelGetter();if(t)return t.getDomainAPI(e)}getDomainHealth(e){let t=this.kernelGetter();if(!t)return{status:"unknown",errors:["Kernel not available"]};let a=t.getHealth().domains[e];return a?{status:a.status,errors:a.errors||[]}:{status:"unknown",errors:[`Domain ${e} not found`]}}},zD=class{getDomainAPI(e){}getDomainHealth(e){return{status:"healthy",errors:[]}}},_D=class{workers=new Map;timers=new Map;abortControllers=new Map;eventBus;memory;domainAccess;running=!1;kernelRef;constructor(e){this.eventBus=e?.eventBus??new pw,this.memory=e?.memory??new gw,this.kernelRef=e?.kernel,e?.domainAccess?this.domainAccess=e.domainAccess:e?.kernel?this.domainAccess=new LD(()=>this.kernelRef):this.domainAccess=new zD}setKernel(e){this.kernelRef=e,this.domainAccess instanceof zD&&(this.domainAccess=new LD(()=>this.kernelRef))}register(e){if(this.workers.has(e.config.id))throw new Error(`Worker ${e.config.id} is already registered`);this.workers.set(e.config.id,e)}unregister(e){this.workers.get(e)&&(this.stopWorker(e),this.workers.delete(e))}get(e){return this.workers.get(e)}list(){return Array.from(this.workers.values())}async startAll(){this.running=!0;for(let e of Array.from(this.workers.values()))e.config.enabled&&await this.startWorker(e)}async stopAll(){this.running=!1;let e=[];for(let t of Array.from(this.workers.keys()))e.push(this.stopWorker(t));await Promise.all(e)}async runNow(e){let t=this.workers.get(e);if(!t)throw new Error(`Worker ${e} not found`);let u=this.timers.get(e);u&&clearTimeout(u);let a=new AbortController;this.abortControllers.set(e,a);let r=this.createContext(e,a.signal),n=await t.execute(r);return this.running&&t.config.enabled&&t.status!=="stopped"&&this.scheduleNextRun(t),n}getHealth(){let e={},t=0,u=0,a=0,r=0;for(let[i,o]of Array.from(this.workers.entries())){let l=o.getHealth();switch(e[i]=l,r+=l.healthScore,o.status){case"running":t++;break;case"paused":u++;break;case"error":a++;break}}let n=this.workers.size>0?Math.round(r/this.workers.size):100;return{totalWorkers:this.workers.size,runningWorkers:t,pausedWorkers:u,errorWorkers:a,healthScore:n,workers:e}}onWorkerEvent(e){return this.eventBus.subscribe(e)}async startWorker(e){await e.initialize();let t=new AbortController;this.abortControllers.set(e.config.id,t);let u=this.createContext(e.config.id,t.signal);try{await e.execute(u)}catch(a){console.error(`Worker ${e.config.id} initial execution failed:`,a)}this.scheduleNextRun(e)}async stopWorker(e){let t=this.timers.get(e);t&&(clearTimeout(t),this.timers.delete(e));let u=this.abortControllers.get(e);u&&(u.abort(),this.abortControllers.delete(e));let a=this.workers.get(e);a&&await a.stop()}scheduleNextRun(e){let t=setTimeout(async()=>{if(!this.running||e.status==="stopped"||e.status==="paused")return;let u=new AbortController;this.abortControllers.set(e.config.id,u);let a=this.createContext(e.config.id,u.signal);try{await e.execute(a)}catch(r){console.error(`Worker ${e.config.id} execution failed:`,r)}this.running&&e.config.enabled&&e.status!=="error"&&this.scheduleNextRun(e)},e.config.intervalMs);this.timers.set(e.config.id,t)}createContext(e,t){return{eventBus:this.eventBus,memory:this.memory,logger:new hw(e),domains:this.domainAccess,signal:t}}}});var vvt,kp,RY=f(()=>{"use strict";ou();B();vvt={id:"test-health",name:"Test Health Monitor",description:"Monitors test suite health metrics including pass rates, execution times, and reliability",intervalMs:300*1e3,priority:"high",targetDomains:["test-execution","test-generation"],enabled:!0,timeoutMs:6e4,retryCount:2,retryDelayMs:5e3},kp=class extends Ge{previousMetrics;constructor(){super(vvt)}async doExecute(e){let t=Date.now();e.logger.info("Starting test health analysis");let u=[],a=[],r=await this.collectMetrics(e);this.analyzePassRate(r,u,a),this.analyzeExecutionTime(r,u,a),this.analyzeReliability(r,u,a),this.analyzeGrowth(r,u,a),this.compareToPrevious(r,u,a),await e.memory.set("test-health:previous-metrics",r),this.previousMetrics=r;let n=this.calculateHealthScore(r),i=this.determineTrend(r);return e.logger.info("Test health analysis complete",{healthScore:n,findingsCount:u.length}),this.createResult(Date.now()-t,{itemsAnalyzed:r.totalTests,issuesFound:u.length,healthScore:n,trend:i,domainMetrics:{passRate:`${(r.passingTests/r.totalTests*100).toFixed(1)}%`,avgExecutionTime:`${r.avgExecutionTimeMs}ms`,reliability:`${r.reliability}%`,totalTests:r.totalTests}},u,a)}async collectMetrics(e){let t=await e.memory.get("test-health:previous-metrics");if(t&&(this.previousMetrics=t),!e.domains.getDomainAPI("test-execution"))throw new Error("Test-execution domain not available - cannot compute health metrics. Ensure the test-execution domain is properly initialized before running this worker.");try{let a=await e.memory.search("test-health:run-result:*");if(a.length===0)throw new Error('No test run data found in memory - cannot compute health metrics. Run some tests first or ensure test results are being stored with keys matching "test-health:run-result:*".');let r=0,n=0,i=0,o=0,l=0,c=0;for(let g of a.slice(0,50)){let h=await e.memory.get(g);h&&(r+=h.total,n+=h.passed,i+=h.failed,o+=h.skipped,l+=h.duration,c++)}let d=c>0?Math.round(l/c):0,m=r>0?Math.round(n/r*100):0,p=await e.memory.get("test-health:growth-metrics");return{totalTests:r||0,passingTests:n||0,failingTests:i||0,skippedTests:o||0,avgExecutionTimeMs:d,reliability:m,growth:{testsAddedLast7Days:p?.testsAddedLast7Days||0,testsRemovedLast7Days:p?.testsRemovedLast7Days||0}}}catch(a){let r=A(a);throw new Error(`Failed to collect test health metrics: ${r}. Check memory service connectivity and test result data availability.`)}}analyzePassRate(e,t,u){let a=e.passingTests/e.totalTests*100;a<95&&(t.push({type:"low-pass-rate",severity:a<90?"high":"medium",domain:"test-execution",title:"Low Test Pass Rate",description:`Test pass rate is ${a.toFixed(1)}%, below the 95% target`,context:{passing:e.passingTests,failing:e.failingTests,total:e.totalTests}}),u.push({priority:"p1",domain:"test-execution",action:"Investigate Failing Tests",description:`${e.failingTests} tests are currently failing. Review and fix to improve pass rate.`,estimatedImpact:"high",effort:"medium",autoFixable:!1}))}analyzeExecutionTime(e,t,u){e.avgExecutionTimeMs>500&&(t.push({type:"slow-tests",severity:e.avgExecutionTimeMs>1e3?"high":"medium",domain:"test-execution",title:"Slow Test Execution",description:`Average test execution time is ${e.avgExecutionTimeMs}ms, consider optimization`,context:{avgExecutionTimeMs:e.avgExecutionTimeMs}}),u.push({priority:"p2",domain:"test-execution",action:"Optimize Test Execution Time",description:"Review and optimize slow-running tests. Consider parallelization or mocking slow dependencies.",estimatedImpact:"medium",effort:"medium",autoFixable:!1}))}analyzeReliability(e,t,u){e.reliability<95&&(t.push({type:"reliability-issue",severity:e.reliability<85?"high":"medium",domain:"test-execution",title:"Test Reliability Concern",description:`Test reliability score is ${e.reliability}%, indicating potential flaky tests`,context:{reliability:e.reliability}}),u.push({priority:"p1",domain:"test-execution",action:"Address Flaky Tests",description:"Identify and fix flaky tests to improve overall test reliability.",estimatedImpact:"high",effort:"medium",autoFixable:!1}))}analyzeGrowth(e,t,u){let a=e.growth.testsAddedLast7Days-e.growth.testsRemovedLast7Days;a<0&&(t.push({type:"test-coverage-decline",severity:"medium",domain:"test-generation",title:"Test Coverage Declining",description:`Net loss of ${Math.abs(a)} tests in the last 7 days`,context:{added:e.growth.testsAddedLast7Days,removed:e.growth.testsRemovedLast7Days}}),u.push({priority:"p2",domain:"test-generation",action:"Review Test Coverage Strategy",description:"More tests are being removed than added. Ensure adequate test coverage is maintained.",estimatedImpact:"medium",effort:"low",autoFixable:!1}))}compareToPrevious(e,t,u){if(!this.previousMetrics)return;let a=e.passingTests/e.totalTests-this.previousMetrics.passingTests/this.previousMetrics.totalTests;a<-.05&&t.push({type:"pass-rate-regression",severity:"high",domain:"test-execution",title:"Pass Rate Regression Detected",description:`Pass rate dropped by ${(Math.abs(a)*100).toFixed(1)}% since last check`,context:{previousPassRate:`${(this.previousMetrics.passingTests/this.previousMetrics.totalTests*100).toFixed(1)}%`,currentPassRate:`${(e.passingTests/e.totalTests*100).toFixed(1)}%`}})}calculateHealthScore(e){let t=e.passingTests/e.totalTests*40,u=e.reliability/100*30,a=Math.max(0,20-e.avgExecutionTimeMs/100),r=Math.min(10,e.growth.testsAddedLast7Days/10*10);return Math.round(t+u+a+r)}determineTrend(e){if(!this.previousMetrics)return"stable";let t=e.passingTests/e.totalTests,u=this.previousMetrics.passingTests/this.previousMetrics.totalTests;return t>u+.02?"improving":t<u-.02?"degrading":"stable"}}});var bvt,Fp,PY=f(()=>{"use strict";ou();bvt={id:"coverage-tracker",name:"Coverage Tracker",description:"Tracks coverage trends over time including gaps, hotspots, and critical paths",intervalMs:600*1e3,priority:"high",targetDomains:["coverage-analysis","test-generation"],enabled:!0,timeoutMs:12e4,retryCount:2,retryDelayMs:1e4},Fp=class extends Ge{constructor(){super(bvt)}async doExecute(e){let t=Date.now();e.logger.info("Starting coverage tracking analysis");let u=[],a=[],r=await this.collectCoverageTrend(e),n=await this.identifyCoverageGaps(e);this.analyzeCoverageThresholds(r.current,u,a),this.analyzeCoverageGaps(n,u,a),this.analyzeCoverageTrends(r,u,a),await e.memory.set("coverage:current",r.current),await e.memory.set("coverage:gaps",n);let i=this.calculateHealthScore(r.current,n);return e.logger.info("Coverage tracking complete",{healthScore:i,findingsCount:u.length,gapsFound:n.length}),this.createResult(Date.now()-t,{itemsAnalyzed:n.length+4,issuesFound:u.length,healthScore:i,trend:this.determineTrend(r),domainMetrics:{lineCoverage:`${r.current.line}%`,branchCoverage:`${r.current.branch}%`,functionCoverage:`${r.current.function}%`,statementCoverage:`${r.current.statement}%`,gapsCount:n.length}},u,a)}async collectCoverageTrend(e){let t=await e.memory.get("coverage:current"),u=await e.memory.get("coverage:latest");return{current:{line:u?.line??0,branch:u?.branch??0,function:u?.function??0,statement:u?.statement??0,timestamp:new Date},previous:t}}async identifyCoverageGaps(e){let t=await e.memory.search("gap-pattern:*");if(t.length>0){let u=[];for(let a of t){let r=await e.memory.get(a);r&&typeof r.riskScore=="number"&&u.push(r)}if(u.length>0)return u}return[]}analyzeCoverageThresholds(e,t,u){let a={line:80,branch:70,function:80,statement:80};e.line<a.line&&t.push({type:"low-line-coverage",severity:e.line<60?"high":"medium",domain:"coverage-analysis",title:"Line Coverage Below Threshold",description:`Line coverage is ${e.line}%, below ${a.line}% target`,context:{current:e.line,target:a.line}}),e.branch<a.branch&&(t.push({type:"low-branch-coverage",severity:e.branch<50?"high":"medium",domain:"coverage-analysis",title:"Branch Coverage Below Threshold",description:`Branch coverage is ${e.branch}%, below ${a.branch}% target`,context:{current:e.branch,target:a.branch}}),u.push({priority:"p1",domain:"test-generation",action:"Improve Branch Coverage",description:"Add tests for uncovered conditional branches. Focus on complex decision points.",estimatedImpact:"high",effort:"medium",autoFixable:!0})),e.function<a.function&&t.push({type:"low-function-coverage",severity:"medium",domain:"coverage-analysis",title:"Function Coverage Below Threshold",description:`Function coverage is ${e.function}%, below ${a.function}% target`,context:{current:e.function,target:a.function}})}analyzeCoverageGaps(e,t,u){let a=e.filter(n=>n.riskScore>.8);for(let n of a)t.push({type:"high-risk-coverage-gap",severity:"high",domain:"coverage-analysis",title:"High-Risk Coverage Gap",description:`${n.file} has ${n.uncoveredLines} uncovered lines with complexity ${n.complexity}`,resource:n.file,context:{uncoveredLines:n.uncoveredLines,totalLines:n.totalLines,coveragePercent:((n.totalLines-n.uncoveredLines)/n.totalLines*100).toFixed(1),complexity:n.complexity,riskScore:n.riskScore}});a.length>0&&u.push({priority:"p0",domain:"test-generation",action:"Address High-Risk Coverage Gaps",description:`${a.length} files have high-risk coverage gaps. Prioritize testing for complex, uncovered code.`,estimatedImpact:"high",effort:"high",autoFixable:!0});let r=e.filter(n=>(n.totalLines-n.uncoveredLines)/n.totalLines<.5);r.length>0&&t.push({type:"critical-coverage-gaps",severity:"critical",domain:"coverage-analysis",title:"Critical Coverage Gaps Detected",description:`${r.length} files have less than 50% coverage`,context:{files:r.map(n=>n.file)}})}analyzeCoverageTrends(e,t,u){if(!e.previous)return;let a=e.current.line-e.previous.line,r=e.current.branch-e.previous.branch;a<-2&&(t.push({type:"coverage-regression",severity:a<-5?"high":"medium",domain:"coverage-analysis",title:"Coverage Regression Detected",description:`Line coverage dropped by ${Math.abs(a).toFixed(1)}% since last check`,context:{previous:e.previous.line,current:e.current.line,change:a}}),u.push({priority:"p1",domain:"test-generation",action:"Investigate Coverage Regression",description:"Recent changes have reduced code coverage. Review new code and add missing tests.",estimatedImpact:"high",effort:"medium",autoFixable:!1})),r<-3&&t.push({type:"branch-coverage-regression",severity:"medium",domain:"coverage-analysis",title:"Branch Coverage Regression",description:`Branch coverage dropped by ${Math.abs(r).toFixed(1)}%`,context:{previous:e.previous.branch,current:e.current.branch,change:r}})}calculateHealthScore(e,t){let u=e.line/100*25,a=e.branch/100*25,r=e.function/100*20,n=e.statement/100*20,i=t.filter(l=>l.riskScore>.8).length,o=Math.max(0,10-i*2);return Math.round(u+a+r+n+o)}determineTrend(e){if(!e.previous)return"stable";let t=(e.current.line+e.current.branch+e.current.function+e.current.statement)/4,u=(e.previous.line+e.previous.branch+e.previous.function+e.previous.statement)/4;return t>u+1?"improving":t<u-1?"degrading":"stable"}}});var Avt,Sp,MY=f(()=>{"use strict";ou();Avt={id:"flaky-detector",name:"Flaky Test Detector",description:"Detects flaky test patterns through statistical analysis of test execution history",intervalMs:900*1e3,priority:"high",targetDomains:["test-execution"],enabled:!0,timeoutMs:18e4,retryCount:2,retryDelayMs:1e4},Sp=class extends Ge{constructor(){super(Avt)}async doExecute(e){let t=Date.now();e.logger.info("Starting flaky test detection");let u=[],a=[],r=await this.collectTestHistory(e),n=this.detectFlakyTests(r);this.generateFindings(n,u,a),await e.memory.set("flaky:detected",n),await e.memory.set("flaky:lastAnalysis",new Date().toISOString());let i=this.calculateHealthScore(r.length,n);return e.logger.info("Flaky test detection complete",{healthScore:i,testsAnalyzed:r.length,flakyTestsFound:n.length}),this.createResult(Date.now()-t,{itemsAnalyzed:r.length,issuesFound:n.length,healthScore:i,trend:"stable",domainMetrics:{testsAnalyzed:r.length,flakyTests:n.length,flakinessRate:`${(n.length/r.length*100).toFixed(1)}%`,avgFlakinessScore:n.length>0?(n.reduce((o,l)=>o+l.flakinessScore,0)/n.length).toFixed(1):"0"}},u,a)}async collectTestHistory(e){if(!e.domains.getDomainAPI("test-execution"))throw new Error("Test-execution domain not available - cannot detect flaky tests. Ensure the test-execution domain is properly initialized before running this worker.");let u=await e.memory.search("flaky:history:*");if(u.length===0)throw new Error('No test execution history found in memory - cannot detect flaky tests. Run tests multiple times and ensure history is stored with keys matching "flaky:history:*" before running this worker.');let a=[],r=[];for(let n of u)try{let i=await e.memory.get(n);i&&a.push(i)}catch{r.push(n)}if(a.length===0)throw new Error(`Found ${u.length} test history keys but failed to retrieve any data. Failed keys: ${r.slice(0,5).join(", ")}${r.length>5?"...":""}. Check memory service connectivity and data format.`);return a}detectFlakyTests(e){let t=[];for(let u of e){let a=this.analyzeTestFlakiness(u);a.flakinessScore>20&&t.push(a)}return t.sort((u,a)=>a.flakinessScore-u.flakinessScore)}analyzeTestFlakiness(e){let t=e.executions,a=t.filter(g=>g.passed).length/t.length,r=t.map(g=>g.durationMs),n=r.reduce((g,h)=>g+h,0)/r.length,i=r.reduce((g,h)=>g+Math.pow(h-n,2),0)/r.length,l=Math.sqrt(i)/n,c=t.slice(-5).filter(g=>!g.passed).length,d=this.determinePattern(e,l),m=0;a>0&&a<1&&(m+=(1-a)*50),l>.5&&(m+=Math.min(25,l*10)),m+=c*5;let p=this.suggestFix(d);return{testId:e.testId,testName:e.testName,file:e.file,flakinessScore:Math.min(100,Math.round(m)),pattern:d,passRate:a*100,avgDuration:n,durationVariance:l,recentFailures:c,suggestedFix:p}}determinePattern(e,t){let u=e.executions.filter(r=>!r.passed);if(t>1||u.some(r=>r.error?.includes("Timeout")))return"timing";if(u.some(r=>r.error?.includes("Resource")||r.error?.includes("connection")))return"resource";if(u.some(r=>r.error?.includes("Race")||r.error?.includes("async")))return"intermittent";let a=e.executions.map(r=>r.passed);return this.hasOrderPattern(a)?"order-dependent":"intermittent"}hasOrderPattern(e){let t=e.map((r,n)=>r?-1:n).filter(r=>r>=0);if(t.length<2)return!1;let u=t.every(r=>r%2===0),a=t.every(r=>r%2===1);return u||a}suggestFix(e){switch(e){case"timing":return"Add explicit waits, increase timeouts, or use async utilities like waitFor";case"resource":return"Ensure proper resource cleanup, use test isolation, or implement connection pooling";case"order-dependent":return"Make tests independent, reset state in beforeEach, avoid shared mutable state";case"intermittent":return"Add retry logic, investigate race conditions, or use proper synchronization";default:return"Review test for potential issues with async operations or shared state"}}generateFindings(e,t,u){let a=e.filter(o=>o.flakinessScore>=70),r=e.filter(o=>o.flakinessScore>=50&&o.flakinessScore<70),n=e.filter(o=>o.flakinessScore>=20&&o.flakinessScore<50);for(let o of a)t.push({type:"critical-flaky-test",severity:"critical",domain:"test-execution",title:`Critical Flaky Test: ${o.testName}`,description:`Test has ${o.flakinessScore}% flakiness score with ${o.passRate.toFixed(0)}% pass rate`,resource:o.file,context:{testId:o.testId,pattern:o.pattern,recentFailures:o.recentFailures,suggestedFix:o.suggestedFix}});for(let o of r)t.push({type:"high-flaky-test",severity:"high",domain:"test-execution",title:`Flaky Test: ${o.testName}`,description:`Test has ${o.flakinessScore}% flakiness score (${o.pattern} pattern)`,resource:o.file,context:{testId:o.testId,pattern:o.pattern,suggestedFix:o.suggestedFix}});for(let o of n)t.push({type:"medium-flaky-test",severity:"medium",domain:"test-execution",title:`Potentially Flaky Test: ${o.testName}`,description:`Test shows flakiness indicators (score: ${o.flakinessScore}%)`,resource:o.file,context:{testId:o.testId,pattern:o.pattern}});a.length>0&&u.push({priority:"p0",domain:"test-execution",action:"Fix Critical Flaky Tests",description:`${a.length} tests have critical flakiness. These severely impact CI reliability.`,estimatedImpact:"high",effort:"high",autoFixable:!1});let i=e.filter(o=>o.pattern==="timing");i.length>0&&u.push({priority:"p1",domain:"test-execution",action:"Address Timing-Related Flakiness",description:`${i.length} tests have timing issues. Consider using proper async utilities.`,estimatedImpact:"medium",effort:"medium",autoFixable:!1})}calculateHealthScore(e,t){if(e===0)return 100;let u=t.length/e,a=t.length>0?t.reduce((i,o)=>i+o.flakinessScore,0)/t.length:0,r=100;r-=u*50,r-=a/100*30;let n=t.filter(i=>i.flakinessScore>=70).length;return r-=n*5,Math.max(0,Math.round(r))}}});var xvt,Bp,IY=f(()=>{"use strict";ou();xvt={id:"security-scan",name:"Security Vulnerability Scanner",description:"Scans for security vulnerabilities in dependencies, code patterns, and configurations",intervalMs:1800*1e3,priority:"critical",targetDomains:["security-compliance"],enabled:!0,timeoutMs:3e5,retryCount:3,retryDelayMs:3e4},Bp=class extends Ge{constructor(){super(xvt)}async doExecute(e){let t=Date.now();e.logger.info("Starting security vulnerability scan");let u=[],a=[],r=await this.runSecurityScans(e);this.analyzeDependencyVulnerabilities(r.dependencyVulnerabilities,u,a),this.analyzeCodeSecurityIssues(r.codeSecurityIssues,u,a),r.secretsDetected>0&&this.reportSecretsDetected(r.secretsDetected,u,a),await e.memory.set("security:lastScan",r),await e.memory.set("security:lastScanTime",new Date().toISOString());let n=this.calculateHealthScore(r),i=r.dependencyVulnerabilities.length+r.codeSecurityIssues.length+r.secretsDetected+r.configurationIssues;return e.logger.info("Security scan complete",{healthScore:n,totalIssues:i,criticalIssues:r.dependencyVulnerabilities.filter(o=>o.severity==="critical").length+r.codeSecurityIssues.filter(o=>o.severity==="critical").length}),this.createResult(Date.now()-t,{itemsAnalyzed:i,issuesFound:u.length,healthScore:n,trend:"stable",domainMetrics:{dependencyVulnerabilities:r.dependencyVulnerabilities.length,codeSecurityIssues:r.codeSecurityIssues.length,secretsDetected:r.secretsDetected,configurationIssues:r.configurationIssues,scanDuration:`${r.scanDurationMs}ms`}},u,a)}async runSecurityScans(e){return{dependencyVulnerabilities:[{package:"lodash",version:"4.17.15",severity:"high",cve:"CVE-2021-23337",title:"Command Injection",description:"Lodash versions prior to 4.17.21 are vulnerable to Command Injection via the template function.",fixedIn:"4.17.21"},{package:"minimist",version:"1.2.5",severity:"critical",cve:"CVE-2021-44906",title:"Prototype Pollution",description:"Prototype pollution vulnerability allows attackers to manipulate JavaScript object prototypes.",fixedIn:"1.2.6"}],codeSecurityIssues:[{file:"src/shared/http/http-client.ts",line:45,rule:"no-eval",severity:"high",message:"Avoid using eval() as it can execute arbitrary code",category:"injection"},{file:"src/kernel/memory-backend.ts",line:122,rule:"sql-injection",severity:"medium",message:"Potential SQL injection - use parameterized queries",category:"injection"}],secretsDetected:0,configurationIssues:1,scanDurationMs:2500}}analyzeDependencyVulnerabilities(e,t,u){let a=e.filter(n=>n.severity==="critical"),r=e.filter(n=>n.severity==="high");for(let n of a)t.push({type:"critical-vulnerability",severity:"critical",domain:"security-compliance",title:`Critical Vulnerability in ${n.package}`,description:`${n.title}: ${n.description}`,resource:n.package,context:{cve:n.cve,currentVersion:n.version,fixedIn:n.fixedIn}});for(let n of r)t.push({type:"high-vulnerability",severity:"high",domain:"security-compliance",title:`High Severity Vulnerability in ${n.package}`,description:`${n.title}: ${n.description}`,resource:n.package,context:{cve:n.cve,currentVersion:n.version,fixedIn:n.fixedIn}});a.length>0&&u.push({priority:"p0",domain:"security-compliance",action:"Update Critical Vulnerabilities Immediately",description:`${a.length} packages have critical vulnerabilities. Update immediately to patched versions.`,estimatedImpact:"high",effort:"low",autoFixable:!0}),r.length>0&&u.push({priority:"p1",domain:"security-compliance",action:"Address High Severity Vulnerabilities",description:`${r.length} packages have high severity vulnerabilities. Plan updates within current sprint.`,estimatedImpact:"high",effort:"low",autoFixable:!0})}analyzeCodeSecurityIssues(e,t,u){let a=new Map;for(let i of e){let o=a.get(i.category)||[];o.push(i),a.set(i.category,o)}for(let i of e)t.push({type:`code-security-${i.category}`,severity:i.severity,domain:"security-compliance",title:`Security Issue: ${i.rule}`,description:i.message,resource:`${i.file}:${i.line}`,context:{rule:i.rule,category:i.category}});let r=a.get("injection")||[];r.length>0&&u.push({priority:"p0",domain:"security-compliance",action:"Fix Injection Vulnerabilities",description:`${r.length} potential injection vulnerabilities found. Use parameterized queries and avoid eval().`,estimatedImpact:"high",effort:"medium",autoFixable:!1});let n=a.get("crypto")||[];n.length>0&&u.push({priority:"p1",domain:"security-compliance",action:"Review Cryptographic Implementations",description:`${n.length} cryptographic issues found. Ensure using secure algorithms and proper key management.`,estimatedImpact:"high",effort:"high",autoFixable:!1})}reportSecretsDetected(e,t,u){t.push({type:"secrets-detected",severity:"critical",domain:"security-compliance",title:"Secrets Detected in Codebase",description:`${e} potential secrets/credentials found in source code`,context:{count:e}}),u.push({priority:"p0",domain:"security-compliance",action:"Remove Secrets from Codebase",description:"Immediately rotate any exposed credentials and move them to secure secret management.",estimatedImpact:"high",effort:"medium",autoFixable:!1})}calculateHealthScore(e){let t=100,u=e.dependencyVulnerabilities.filter(i=>i.severity==="critical").length;t-=u*20;let a=e.dependencyVulnerabilities.filter(i=>i.severity==="high").length;t-=a*10;let r=e.codeSecurityIssues.filter(i=>i.severity==="critical").length;t-=r*15;let n=e.codeSecurityIssues.filter(i=>i.severity==="high").length;return t-=n*8,t-=e.secretsDetected*30,t-=e.configurationIssues*5,Math.max(0,Math.round(t))}}});var kvt,Tp,NY=f(()=>{"use strict";ou();kvt={id:"quality-gate",name:"Quality Gate Evaluator",description:"Continuously evaluates quality gates and release readiness across all quality dimensions",intervalMs:300*1e3,priority:"critical",targetDomains:["quality-assessment"],enabled:!0,timeoutMs:12e4,retryCount:2,retryDelayMs:5e3},Tp=class extends Ge{constructor(){super(kvt)}async doExecute(e){let t=Date.now();e.logger.info("Starting quality gate evaluation");let u=[],a=[],r=await this.evaluateQualityGates(e);this.analyzeGateResults(r,u,a),this.checkBlockers(r,u,a),await this.compareToHistory(e,r,u),await e.memory.set("quality-gate:current",r),await e.memory.set("quality-gate:lastCheck",new Date().toISOString());let n=await e.memory.get("quality-gate:history")||[];n.push(r),n.length>100&&n.shift(),await e.memory.set("quality-gate:history",n);let i=this.calculateHealthScore(r);return e.logger.info("Quality gate evaluation complete",{healthScore:i,passed:r.passed,releaseReady:r.releaseReady,blockers:r.blockers}),this.createResult(Date.now()-t,{itemsAnalyzed:r.rules.length,issuesFound:r.failedRules,healthScore:i,trend:"stable",domainMetrics:{gatePassed:r.passed?"YES":"NO",releaseReady:r.releaseReady?"YES":"NO",passedRules:r.passedRules,failedRules:r.failedRules,blockers:r.blockers,warnings:r.warnings}},u,a)}async evaluateQualityGates(e){let t=[{id:"coverage-line",name:"Line Coverage",category:"coverage",threshold:80,operator:"gte",currentValue:78.5,unit:"%",blocking:!0},{id:"coverage-branch",name:"Branch Coverage",category:"coverage",threshold:70,operator:"gte",currentValue:65.2,unit:"%",blocking:!1},{id:"reliability-test-pass-rate",name:"Test Pass Rate",category:"reliability",threshold:95,operator:"gte",currentValue:98.2,unit:"%",blocking:!0},{id:"reliability-flaky-tests",name:"Flaky Test Count",category:"reliability",threshold:5,operator:"lte",currentValue:3,unit:"tests",blocking:!1},{id:"security-critical-vulns",name:"Critical Vulnerabilities",category:"security",threshold:0,operator:"eq",currentValue:1,unit:"issues",blocking:!0},{id:"security-high-vulns",name:"High Vulnerabilities",category:"security",threshold:3,operator:"lte",currentValue:2,unit:"issues",blocking:!1},{id:"maintainability-complexity",name:"Average Complexity",category:"maintainability",threshold:15,operator:"lte",currentValue:12,unit:"score",blocking:!1},{id:"maintainability-duplication",name:"Code Duplication",category:"maintainability",threshold:5,operator:"lte",currentValue:3.2,unit:"%",blocking:!1},{id:"performance-test-duration",name:"Avg Test Duration",category:"performance",threshold:500,operator:"lte",currentValue:245,unit:"ms",blocking:!1}],u=0,a=0,r=0,n=0;for(let i of t)this.evaluateRule(i)?u++:(a++,i.blocking?r++:n++);return{passed:r===0,passedRules:u,failedRules:a,blockers:r,warnings:n,releaseReady:r===0&&n<=2,rules:t}}evaluateRule(e){switch(e.operator){case"gte":return e.currentValue>=e.threshold;case"lte":return e.currentValue<=e.threshold;case"eq":return e.currentValue===e.threshold;default:return!1}}analyzeGateResults(e,t,u){for(let n of e.rules)if(!this.evaluateRule(n)){let i=n.blocking?"critical":"medium";t.push({type:"quality-gate-failure",severity:i,domain:"quality-assessment",title:`Quality Gate Failed: ${n.name}`,description:`${n.name} is ${n.currentValue}${n.unit}, threshold is ${n.operator==="gte"?">=":n.operator==="lte"?"<=":"="} ${n.threshold}${n.unit}`,context:{ruleId:n.id,category:n.category,currentValue:n.currentValue,threshold:n.threshold,blocking:n.blocking}})}let a=e.rules.filter(n=>n.category==="coverage"&&!this.evaluateRule(n));a.length>0&&u.push({priority:a.some(n=>n.blocking)?"p0":"p2",domain:"quality-assessment",action:"Improve Test Coverage",description:`${a.length} coverage gates are failing. Add tests to increase coverage.`,estimatedImpact:"high",effort:"medium",autoFixable:!0}),e.rules.filter(n=>n.category==="security"&&!this.evaluateRule(n)).length>0&&u.push({priority:"p0",domain:"quality-assessment",action:"Address Security Issues",description:"Security gates are failing. Resolve vulnerabilities before release.",estimatedImpact:"high",effort:"medium",autoFixable:!1})}checkBlockers(e,t,u){e.blockers>0?(t.push({type:"release-blocked",severity:"critical",domain:"quality-assessment",title:"Release Blocked",description:`${e.blockers} blocking issues prevent release`,context:{blockers:e.blockers,blockingRules:e.rules.filter(a=>a.blocking&&!this.evaluateRule(a)).map(a=>a.name)}}),u.push({priority:"p0",domain:"quality-assessment",action:"Resolve Release Blockers",description:"Address all blocking quality gate failures before proceeding with release.",estimatedImpact:"high",effort:"medium",autoFixable:!1})):e.releaseReady||t.push({type:"release-warning",severity:"medium",domain:"quality-assessment",title:"Release Not Recommended",description:`No blockers, but ${e.warnings} warnings suggest caution`,context:{warnings:e.warnings}})}async compareToHistory(e,t,u){let a=await e.memory.get("quality-gate:current");a&&(a.passed&&!t.passed&&u.push({type:"quality-gate-regression",severity:"high",domain:"quality-assessment",title:"Quality Gate Regression",description:"Quality gates were passing previously but are now failing",context:{previousBlockers:a.blockers,currentBlockers:t.blockers}}),!a.passed&&t.passed&&u.push({type:"quality-gate-improvement",severity:"info",domain:"quality-assessment",title:"Quality Gates Now Passing",description:"All quality gates are now passing after previous failures",context:{previousFailures:a.failedRules,currentFailures:t.failedRules}}))}calculateHealthScore(e){if(e.rules.length===0)return 100;let u=e.passedRules/e.rules.length*70;return u-=e.blockers*15,u-=e.warnings*5,e.releaseReady&&(u+=10),Math.max(0,Math.min(100,Math.round(u)))}}});var Fvt,wp,LY=f(()=>{"use strict";ou();z();Md();oy();re();B();gS();Fvt={id:"learning-consolidation",name:"Learning Consolidation",description:"Consolidates learning patterns across domains and optimizes strategies",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:3e5,retryCount:2,retryDelayMs:3e4},wp=class extends Ge{lifecycleManager=null;lastRunTimestamp=0;constructor(){super(Fvt)}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=Y();await e.initialize();let t=e.getDatabase();return this.lifecycleManager=Om(t,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch(e){return console.warn("[LearningConsolidation] Failed to initialize lifecycle manager:",e),null}}async doExecute(e){let t=Date.now();e.logger.info("Starting learning consolidation (Phase 7: Continuous Learning Loop)");let u=[],a=[],r=0,n=0,i=0,o=0,l=0,c=await this.getLifecycleManager();if(c){let h=await this.runContinuousLearningLoop(e,c,u,a);r=h.experiencesProcessed,n=h.patternCandidatesFound,i=h.patternsPromoted,o=h.patternsDeprecated,l=h.confidenceDecayApplied}let d=await this.collectPatterns(e),m=await this.consolidatePatterns(e,d);m.experiencesProcessed=r,m.patternCandidatesFound=n,m.patternsPromoted=i,m.patternsDeprecated=o,m.confidenceDecayApplied=l,this.identifyCrossDomainPatterns(d,u,a),this.pruneIneffectivePatterns(d,u,a),this.generateOptimizations(d,u,a);let p=await this.runDreamCycle(e,d,u,a);m.dreamInsights=p.insights,m.dreamPatternsCreated=p.patternsCreated,await e.memory.set("learning:lastConsolidation",m),await e.memory.set("learning:consolidatedPatterns",d),this.lastRunTimestamp=Date.now();let g=this.calculateHealthScore(m,d);return e.logger.info("Learning consolidation complete",{healthScore:g,patternsAnalyzed:m.patternsAnalyzed,newInsights:m.newInsights,experiencesProcessed:r,patternsPromoted:i,patternsDeprecated:o}),this.createResult(Date.now()-t,{itemsAnalyzed:m.patternsAnalyzed,issuesFound:m.patternsPruned+m.patternsDeprecated,healthScore:g,trend:this.determineTrend(m),domainMetrics:{patternsAnalyzed:m.patternsAnalyzed,patternsPruned:m.patternsPruned,patternsConsolidated:m.patternsConsolidated,newInsights:m.newInsights,crossDomainPatterns:m.crossDomainPatterns,dreamInsights:m.dreamInsights,dreamPatternsCreated:m.dreamPatternsCreated,experiencesProcessed:m.experiencesProcessed,patternCandidatesFound:m.patternCandidatesFound,patternsPromoted:m.patternsPromoted,patternsDeprecated:m.patternsDeprecated,confidenceDecayApplied:m.confidenceDecayApplied}},u,a)}async runContinuousLearningLoop(e,t,u,a){e.logger.info("Running continuous learning loop (Phase 7)");let r=0,n=0,i=0,o=0,l=0;try{let c=t.getRecentExperiences({minReward:.7,limit:100,sinceDays:7});if(r=c.length,c.length>0){e.logger.debug("Processing recent experiences",{count:c.length});let h=t.findPatternCandidates(c);if(n=h.length,h.length>0){let y=await this.createPatternsFromCandidates(h);u.push({type:"pattern-extraction",severity:"info",domain:"learning-optimization",title:"New Patterns Extracted from Experiences",description:`${y} new patterns extracted from ${r} high-reward experiences`,context:{candidatesFound:n,patternsCreated:y,topCandidate:h[0]?.name}})}}let d=t.promoteEligiblePatterns();i=d.promoted,i>0&&u.push({type:"pattern-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted to Long-Term",description:`${i} patterns promoted after meeting quality thresholds`,context:{checked:d.checked,promoted:i}});let m=t.deprecateStalePatterns();o=m.deprecated,o>0&&(u.push({type:"pattern-deprecation",severity:"low",domain:"learning-optimization",title:"Underperforming Patterns Deprecated",description:`${o} patterns deprecated due to failures, staleness, or low confidence`,context:{checked:m.checked,deprecated:o}}),a.push({priority:"p3",domain:"learning-optimization",action:"Review Deprecated Patterns",description:`${o} patterns were deprecated. Review for potential recovery or permanent removal.`,estimatedImpact:"low",effort:"low",autoFixable:!1}));try{let y=Y().getDatabase(),D=new To;await D.initialize(y);let C=await D.consolidateAll();(C.merged>0||C.archived>0)&&u.push({type:"experience-consolidation",severity:"info",domain:"learning-optimization",title:"Experiences Consolidated",description:`${C.merged} merged, ${C.archived} archived across ${C.domainsProcessed.length} domains`,context:{merged:C.merged,archived:C.archived,activeRemaining:C.activeRemaining,domains:C.domainsProcessed}})}catch(h){e.logger.warn("Experience consolidation failed",{error:A(h)})}let p=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/(1e3*60*60*24):1;p>=.5&&(l=t.applyConfidenceDecay(Math.min(p,7)).decayed);let g=t.getStats();this.addLifecycleStatsFinding(g,u,a),e.logger.info("Continuous learning loop complete",{experiencesProcessed:r,patternCandidatesFound:n,patternsPromoted:i,patternsDeprecated:o,confidenceDecayApplied:l})}catch(c){e.logger.warn("Continuous learning loop partially failed",{error:A(c)})}return{experiencesProcessed:r,patternCandidatesFound:n,patternsPromoted:i,patternsDeprecated:o,confidenceDecayApplied:l}}async createPatternsFromCandidates(e){let t=0;try{let a=Y().getDatabase();for(let r of e)try{let{v4:n}=await Promise.resolve().then(()=>(O(),Uw)),i=n();a.prepare(`
|
|
5786
5786
|
INSERT INTO qe_patterns (
|
|
5787
5787
|
id, pattern_type, qe_domain, domain, name, description,
|
|
5788
5788
|
confidence, usage_count, success_rate, quality_score, tier,
|