π The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
π Checkpoint: Edit /workspaces/claude-code-flow/src/cli/simple-commands/training-pipeline.js
rUv92d67f63f5da
diff --git a/.claude/checkpoints/1755017942.json b/.claude/checkpoints/1755017942.jsonnew file mode 100644index 0000000000..3c38333d7d--- /dev/null+++ b/.claude/checkpoints/1755017942.json@@ -0,0 +1 @@+{"branch": "checkpoint/pre-edit-20250812-165901", "file": "/workspaces/claude-code-flow/src/cli/command-registry.js", "timestamp": "2025-08-12T16:59:02Z", "type": "pre-edit", "original_branch": "alpha-89"}diff --git a/.claude/checkpoints/1755017943.json b/.claude/checkpoints/1755017943.jsonnew file mode 100644index 0000000000..016606cfba--- /dev/null+++ b/.claude/checkpoints/1755017943.json@@ -0,0 +1 @@+{"tag": "checkpoint-20250812-165903", "file": "/workspaces/claude-code-flow/src/cli/command-registry.js", "timestamp": "2025-08-12T16:59:03Z", "type": "post-edit", "branch": "alpha-89", "diff_summary": " .claude-flow/metrics/performance.json | 2 +- .claude-flow/metrics/system-metrics.json | 12 +++++++++ .claude-flow/metrics/task-metrics.json | 6 ++--- .claude/checkpoints/task-1755017915.json | 1 + claude-flow-wiki | 0 src/cli/command-registry.js | 42 ++++++++++++++------------------ 6 files changed, 35 insertions(+), 28 deletions(-) "}diff --git a/src/cli/simple-commands/training-pipeline-old.js.bak b/src/cli/simple-commands/training-pipeline-old.js.baknew file mode 100644index 0000000000..567a8da96d--- /dev/null+++ b/src/cli/simple-commands/training-pipeline-old.js.bak@@ -0,0 +1,763 @@+#!/usr/bin/env node+/**+ * Training Pipeline for Continuous Agent Improvement+ * Creates feedback loops that actually improve agent performance+ */++import fs from 'fs/promises';+import path from 'path';+import { execSync, spawn } from 'child_process';+import { promisify } from 'util';+import { exec } from 'child_process';++const execAsync = promisify(exec);++/**+ * Training Pipeline that creates real improvement cycles+ */+export class TrainingPipeline {+ constructor() {+ this.pipelineConfig = '.claude-flow/pipeline-config.json';+ this.trainingLog = '.claude-flow/training/pipeline-log.jsonl';+ this.improvementMetrics = '.claude-flow/metrics/improvements.json';+ this.agentProfiles = '.claude-flow/agents/profiles.json';+ this.initialized = false;+ }++ /**+ * Initialize the training pipeline+ */+ async initialize() {+ // Create necessary directories+ const dirs = [+ '.claude-flow/pipeline',+ '.claude-flow/training',+ '.claude-flow/metrics',+ '.claude-flow/agents',+ '.claude-flow/validation',+ '.claude-flow/benchmarks'+ ];++ for (const dir of dirs) {+ await fs.mkdir(dir, { recursive: true });+ }++ // Load or create pipeline configuration+ await this.loadPipelineConfig();++ console.log('π Training Pipeline initialized');+ this.initialized = true;+ }++ /**+ * STAGE 1: Generate Training Tasks+ * Creates real-world tasks for agents to learn from+ */+ async generateTrainingTasks(complexity = 'medium') {+ const tasks = {+ easy: [+ { type: 'code', task: 'Create a function to validate email addresses', expectedChecks: ['test', 'lint'] },+ { type: 'test', task: 'Write unit tests for array utilities', expectedChecks: ['coverage', 'test'] },+ { type: 'docs', task: 'Document API endpoints', expectedChecks: ['lint'] },+ ],+ medium: [+ { type: 'api', task: 'Build REST API with authentication', expectedChecks: ['test', 'lint', 'typecheck'] },+ { type: 'refactor', task: 'Refactor legacy code to modern patterns', expectedChecks: ['test', 'lint'] },+ { type: 'debug', task: 'Fix performance bottlenecks', expectedChecks: ['test', 'benchmark'] },+ ],+ hard: [+ { type: 'architecture', task: 'Design microservices architecture', expectedChecks: ['design-review', 'scalability'] },+ { type: 'optimization', task: 'Optimize database queries for scale', expectedChecks: ['benchmark', 'test'] },+ { type: 'security', task: 'Implement secure payment processing', expectedChecks: ['security', 'test', 'compliance'] },+ ]+ };++ const selectedTasks = tasks[complexity] || tasks.medium;++ // Save training tasks+ const taskFile = `.claude-flow/training/tasks-${Date.now()}.json`;+ await fs.writeFile(taskFile, JSON.stringify({+ complexity,+ tasks: selectedTasks,+ created: new Date().toISOString()+ }, null, 2));++ console.log(`π Generated ${selectedTasks.length} ${complexity} training tasks`);+ return selectedTasks;+ }++ /**+ * STAGE 2: Execute Tasks with Different Agent Configurations+ * Runs tasks with various agent settings to find optimal configurations+ */+ async executeTrainingRun(tasks, agentConfig = {}) {+ const results = [];++ for (const task of tasks) {+ console.log(`\nπ Executing: ${task.task}`);++ // Create a test environment+ const testDir = `.claude-flow/training/test-${Date.now()}`;+ await fs.mkdir(testDir, { recursive: true });++ // Simulate agent execution with different strategies+ const strategies = agentConfig.strategies || ['conservative', 'balanced', 'aggressive'];++ for (const strategy of strategies) {+ const result = await this.executeTaskWithStrategy(task, strategy, testDir);+ results.push({+ task: task.task,+ type: task.type,+ strategy,+ ...result,+ timestamp: new Date().toISOString()+ });+ }++ // Clean up test directory+ await fs.rm(testDir, { recursive: true, force: true });+ }++ // Save results+ const resultsFile = `.claude-flow/training/results-${Date.now()}.json`;+ await fs.writeFile(resultsFile, JSON.stringify(results, null, 2));++ return results;+ }++ /**+ * Execute a task with a specific strategy+ */+ async executeTaskWithStrategy(task, strategy, testDir) {+ const startTime = Date.now();++ // Create a simple test file based on task type+ const testFile = path.join(testDir, `test-${strategy}.js`);+ const content = this.generateTestContent(task.type, strategy);+ await fs.writeFile(testFile, content);++ // Run verification checks+ const checks = {};+ for (const check of task.expectedChecks) {+ checks[check] = await this.runCheck(check, testFile);+ }++ // Calculate performance metrics+ const executionTime = Date.now() - startTime;+ const successRate = Object.values(checks).filter(c => c.passed).length / Object.values(checks).length;++ return {+ executionTime,+ successRate,+ checks,+ strategy,+ score: this.calculateScore(checks, executionTime, strategy)+ };+ }++ /**+ * STAGE 3: Learn from Results+ * Updates agent profiles based on performance+ */+ async learnFromResults(results) {+ console.log('\nπ§ Learning from results...');++ // Load current agent profiles+ let profiles = {};+ try {+ const data = await fs.readFile(this.agentProfiles, 'utf8');+ profiles = JSON.parse(data);+ } catch {+ profiles = this.getDefaultProfiles();+ }++ // Analyze results by strategy+ const strategyPerformance = {};+ for (const result of results) {+ if (!strategyPerformance[result.strategy]) {+ strategyPerformance[result.strategy] = {+ totalScore: 0,+ count: 0,+ avgExecutionTime: 0,+ successRate: 0+ };+ }++ const perf = strategyPerformance[result.strategy];+ perf.totalScore += result.score;+ perf.count++;+ perf.avgExecutionTime += result.executionTime;+ perf.successRate += result.successRate;+ }++ // Calculate averages and update profiles+ for (const [strategy, perf] of Object.entries(strategyPerformance)) {+ perf.avgScore = perf.totalScore / perf.count;+ perf.avgExecutionTime = perf.avgExecutionTime / perf.count;+ perf.successRate = perf.successRate / perf.count;++ // Update agent profiles based on performance+ this.updateAgentProfile(profiles, strategy, perf);+ }++ // Save updated profiles+ await fs.writeFile(this.agentProfiles, JSON.stringify(profiles, null, 2));++ // Generate improvement recommendations+ const recommendations = this.generateRecommendations(strategyPerformance);++ console.log('\nπ Learning Results:');+ for (const [strategy, perf] of Object.entries(strategyPerformance)) {+ console.log(` ${strategy}: Score ${perf.avgScore.toFixed(2)}, Success ${(perf.successRate * 100).toFixed(1)}%`);+ }++ return { profiles, recommendations };+ }++ /**+ * STAGE 4: Validate Improvements+ * Tests if the training actually improved performance+ */+ async validateImprovements(beforeMetrics, afterMetrics) {+ console.log('\nβ Validating improvements...');++ const validation = {+ improved: [],+ declined: [],+ unchanged: [],+ summary: {}+ };++ // Compare metrics+ const metrics = ['successRate', 'executionTime', 'score'];++ for (const metric of metrics) {+ const before = beforeMetrics[metric] || 0;+ const after = afterMetrics[metric] || 0;+ const change = after - before;+ const percentChange = before > 0 ? (change / before) * 100 : 0;++ if (percentChange > 5) {+ validation.improved.push({ metric, change: percentChange });+ } else if (percentChange < -5) {+ validation.declined.push({ metric, change: percentChange });+ } else {+ validation.unchanged.push({ metric, change: percentChange });+ }+ }++ validation.summary = {+ overallImprovement: validation.improved.length > validation.declined.length,+ improvementScore: validation.improved.length - validation.declined.length,+ timestamp: new Date().toISOString()+ };++ // Save validation results+ const validationFile = `.claude-flow/validation/validation-${Date.now()}.json`;+ await fs.writeFile(validationFile, JSON.stringify(validation, null, 2));++ console.log(` Improved: ${validation.improved.length} metrics`);+ console.log(` Declined: ${validation.declined.length} metrics`);+ console.log(` Unchanged: ${validation.unchanged.length} metrics`);++ return validation;+ }++ /**+ * STAGE 5: Apply Improvements to Production+ * Updates the actual agent configurations with learned improvements+ */+ async applyImprovements(profiles, recommendations) {+ console.log('\nπ Applying improvements to production...');++ // Update swarm configuration+ const swarmConfig = {+ defaultStrategy: this.selectBestStrategy(profiles),+ agentProfiles: profiles,+ optimizations: recommendations,+ appliedAt: new Date().toISOString()+ };++ await fs.writeFile('.claude-flow/swarm-config.json', JSON.stringify(swarmConfig, null, 2));++ // Create improved command templates+ const improvedCommands = this.generateImprovedCommands(profiles);+ await fs.writeFile('.claude/commands/improved-workflows.js', improvedCommands);++ console.log('β Improvements applied successfully');++ return swarmConfig;+ }++ /**+ * Full Training Pipeline Execution+ */+ async runFullPipeline(options = {}) {+ const {+ complexity = 'medium',+ iterations = 3,+ validate = true+ } = options;++ console.log('π― Starting Full Training Pipeline');+ console.log('β'.repeat(50));++ await this.initialize();++ // Capture baseline metrics+ const baselineMetrics = await this.captureMetrics();++ let cumulativeResults = [];++ for (let i = 1; i <= iterations; i++) {+ console.log(`\nπ Iteration ${i}/${iterations}`);+ console.log('β'.repeat(40));++ // Stage 1: Generate tasks+ const tasks = await this.generateTrainingTasks(complexity);++ // Stage 2: Execute with different configurations+ const results = await this.executeTrainingRun(tasks);+ cumulativeResults = [...cumulativeResults, ...results];++ // Stage 3: Learn from results+ const { profiles, recommendations } = await this.learnFromResults(results);++ // Stage 4: Validate if enabled+ if (validate && i === iterations) {+ const currentMetrics = await this.captureMetrics();+ const validation = await this.validateImprovements(baselineMetrics, currentMetrics);++ if (!validation.summary.overallImprovement) {+ console.log('β οΈ No significant improvement detected');+ // Consider reverting or adjusting learning parameters+ }+ }++ // Stage 5: Apply improvements+ if (i === iterations || (results.length > 10)) {+ await this.applyImprovements(profiles, recommendations);+ }+ }++ // Generate final report+ const report = await this.generateFinalReport(cumulativeResults);+ console.log('\n' + report);++ return {+ success: true,+ totalTasks: cumulativeResults.length,+ improvements: await this.calculateOverallImprovement(baselineMetrics)+ };+ }++ // Helper methods++ generateTestContent(taskType, strategy) {+ const templates = {+ code: `+// Strategy: ${strategy}+function processData(input) {+ ${strategy === 'aggressive' ? '// Fast but risky' : '// Safe but slower'}+ ${strategy === 'aggressive' ? 'return input.map(x => x * 2);' : 'if (!input) return []; return input.map(x => x * 2);'}+}+module.exports = { processData };+`,+ test: `+// Test strategy: ${strategy}+describe('Test Suite', () => {+ test('should pass', () => {+ expect(true).toBe(true);+ });+});+`,+ api: `+// API strategy: ${strategy}+const express = require('express');+const app = express();+${strategy === 'aggressive' ? '' : 'app.use(helmet());'}+app.get('/api', (req, res) => res.json({ status: 'ok' }));+module.exports = app;+`+ };++ return templates[taskType] || templates.code;+ }++ async runCheck(checkType, file) {+ // Simulate running actual checks+ const checks = {+ test: async () => {+ try {+ // In real implementation, would run actual tests+ return { passed: Math.random() > 0.3, score: Math.random() };+ } catch {+ return { passed: false, score: 0 };+ }+ },+ lint: async () => {+ try {+ // In real implementation, would run eslint+ return { passed: Math.random() > 0.2, score: Math.random() };+ } catch {+ return { passed: false, score: 0 };+ }+ },+ typecheck: async () => {+ try {+ // In real implementation, would run tsc+ return { passed: Math.random() > 0.4, score: Math.random() };+ } catch {+ return { passed: false, score: 0 };+ }+ },+ coverage: async () => {+ return { passed: Math.random() > 0.5, score: Math.random() };+ },+ benchmark: async () => {+ return { passed: true, score: Math.random(), time: Math.random() * 1000 };+ }+ };++ const check = checks[checkType] || checks.test;+ return await check();+ }++ calculateScore(checks, executionTime, strategy) {+ let score = 0;++ // Success rate (40% weight)+ const successRate = Object.values(checks).filter(c => c.passed).length / Object.values(checks).length;+ score += successRate * 40;++ // Execution time (30% weight) - faster is better+ const timeScore = Math.max(0, 1 - (executionTime / 10000));+ score += timeScore * 30;++ // Strategy bonus (30% weight)+ const strategyScores = {+ conservative: 0.7, // Safe but slower+ balanced: 0.85, // Good balance+ aggressive: 0.6 // Fast but risky+ };+ score += (strategyScores[strategy] || 0.5) * 30;++ return score;+ }++ updateAgentProfile(profiles, strategy, performance) {+ if (!profiles[strategy]) {+ profiles[strategy] = {+ successRate: 0,+ avgScore: 0,+ avgExecutionTime: 0,+ uses: 0+ };+ }++ const profile = profiles[strategy];+ const weight = 0.3; // Learning rate++ // Update with exponential moving average+ profile.successRate = profile.successRate * (1 - weight) + performance.successRate * weight;+ profile.avgScore = profile.avgScore * (1 - weight) + performance.avgScore * weight;+ profile.avgExecutionTime = profile.avgExecutionTime * (1 - weight) + performance.avgExecutionTime * weight;+ profile.uses++;++ // Add performance trend+ if (!profile.trend) profile.trend = [];+ profile.trend.push({+ score: performance.avgScore,+ timestamp: new Date().toISOString()+ });+ if (profile.trend.length > 20) {+ profile.trend = profile.trend.slice(-20);+ }+ }++ generateRecommendations(strategyPerformance) {+ const recommendations = [];++ for (const [strategy, perf] of Object.entries(strategyPerformance)) {+ if (perf.successRate < 0.7) {+ recommendations.push({+ type: 'improve_success_rate',+ strategy,+ action: `Focus on reliability for ${strategy} strategy`,+ priority: 'high'+ });+ }++ if (perf.avgExecutionTime > 5000) {+ recommendations.push({+ type: 'optimize_performance',+ strategy,+ action: `Optimize execution time for ${strategy} strategy`,+ priority: 'medium'+ });+ }++ if (perf.avgScore < 50) {+ recommendations.push({+ type: 'enhance_quality',+ strategy,+ action: `Improve overall quality for ${strategy} strategy`,+ priority: 'high'+ });+ }+ }++ return recommendations;+ }++ selectBestStrategy(profiles) {+ let bestStrategy = 'balanced';+ let bestScore = 0;++ for (const [strategy, profile] of Object.entries(profiles)) {+ if (profile.avgScore > bestScore) {+ bestScore = profile.avgScore;+ bestStrategy = strategy;+ }+ }++ return bestStrategy;+ }++ generateImprovedCommands(profiles) {+ const bestStrategy = this.selectBestStrategy(profiles);++ return `+/**+ * Improved Workflow Commands+ * Generated by Training Pipeline+ * Best Strategy: ${bestStrategy}+ */++export const improvedWorkflows = {+ strategy: '${bestStrategy}',++ execute: async (task) => {+ // Use learned optimal configuration+ const config = ${JSON.stringify(profiles[bestStrategy], null, 2)};++ // Apply learned optimizations+ console.log('Using optimized strategy: ${bestStrategy}');++ // Execute with improved parameters+ return await executeWithConfig(task, config);+ }+};+`;+ }++ async captureMetrics() {+ // Capture current system metrics+ try {+ const verifyData = await fs.readFile('.swarm/verification-memory.json', 'utf8');+ const memory = JSON.parse(verifyData);++ const history = memory.history || [];+ const recent = history.slice(-20);++ return {+ successRate: recent.filter(h => h.passed).length / recent.length,+ executionTime: recent.reduce((sum, h) => sum + (h.executionTime || 0), 0) / recent.length,+ score: recent.reduce((sum, h) => sum + h.score, 0) / recent.length+ };+ } catch {+ return {+ successRate: 0,+ executionTime: 0,+ score: 0+ };+ }+ }++ async calculateOverallImprovement(baselineMetrics) {+ const currentMetrics = await this.captureMetrics();++ return {+ successRate: ((currentMetrics.successRate - baselineMetrics.successRate) / baselineMetrics.successRate) * 100,+ executionTime: ((baselineMetrics.executionTime - currentMetrics.executionTime) / baselineMetrics.executionTime) * 100,+ score: ((currentMetrics.score - baselineMetrics.score) / baselineMetrics.score) * 100+ };+ }++ async generateFinalReport(results) {+ const successRates = {};+ const scores = {};++ for (const result of results) {+ if (!successRates[result.strategy]) {+ successRates[result.strategy] = [];+ scores[result.strategy] = [];+ }+ successRates[result.strategy].push(result.successRate);+ scores[result.strategy].push(result.score);+ }++ let report = 'π Training Pipeline Report\n';+ report += 'β'.repeat(50) + '\n\n';++ for (const strategy of Object.keys(successRates)) {+ const avgSuccess = successRates[strategy].reduce((a, b) => a + b, 0) / successRates[strategy].length;+ const avgScore = scores[strategy].reduce((a, b) => a + b, 0) / scores[strategy].length;++ report += `Strategy: ${strategy}\n`;+ report += ` Average Success Rate: ${(avgSuccess * 100).toFixed(1)}%\n`;+ report += ` Average Score: ${avgScore.toFixed(2)}\n`;+ report += '\n';+ }++ return report;+ }++ getDefaultProfiles() {+ return {+ conservative: {+ successRate: 0.8,+ avgScore: 70,+ avgExecutionTime: 3000,+ uses: 0+ },+ balanced: {+ successRate: 0.75,+ avgScore: 75,+ avgExecutionTime: 2000,+ uses: 0+ },+ aggressive: {+ successRate: 0.6,+ avgScore: 65,+ avgExecutionTime: 1000,+ uses: 0+ }+ };+ }++ async loadPipelineConfig() {+ try {+ const data = await fs.readFile(this.pipelineConfig, 'utf8');+ return JSON.parse(data);+ } catch {+ const defaultConfig = {+ version: '1.0.0',+ strategies: ['conservative', 'balanced', 'aggressive'],+ learningRate: 0.3,+ minSamplesForUpdate: 5,+ created: new Date().toISOString()+ };++ await fs.writeFile(this.pipelineConfig, JSON.stringify(defaultConfig, null, 2));+ return defaultConfig;+ }+ }+}++/**+ * CLI Command Handler+ */+export async function trainingPipelineCommand(args, flags) {+ const pipeline = new TrainingPipeline();+ const subcommand = args[0] || 'run';++ switch (subcommand) {+ case 'run':+ // Run full pipeline+ const options = {+ complexity: flags.complexity || 'medium',+ iterations: parseInt(flags.iterations) || 3,+ validate: flags.validate !== false+ };++ console.log('π Starting Training Pipeline');+ console.log(` Complexity: ${options.complexity}`);+ console.log(` Iterations: ${options.iterations}`);+ console.log(` Validation: ${options.validate ? 'Enabled' : 'Disabled'}`);++ const result = await pipeline.runFullPipeline(options);++ if (result.success) {+ console.log('\nβ Training Pipeline completed successfully');+ console.log(` Total tasks executed: ${result.totalTasks}`);++ if (result.improvements) {+ console.log('\nπ Improvements:');+ console.log(` Success Rate: ${result.improvements.successRate > 0 ? '+' : ''}${result.improvements.successRate.toFixed(1)}%`);+ console.log(` Execution Time: ${result.improvements.executionTime > 0 ? '+' : ''}${result.improvements.executionTime.toFixed(1)}%`);+ console.log(` Score: ${result.improvements.score > 0 ? '+' : ''}${result.improvements.score.toFixed(1)}%`);+ }+ }+ break;++ case 'generate':+ // Just generate training tasks+ await pipeline.initialize();+ const tasks = await pipeline.generateTrainingTasks(flags.complexity || 'medium');+ console.log(`\nβ Generated ${tasks.length} training tasks`);+ for (const task of tasks) {+ console.log(` β’ ${task.task}`);+ }+ break;++ case 'validate':+ // Validate current performance+ await pipeline.initialize();+ const baseline = await pipeline.captureMetrics();+ console.log('\nπ Current Performance Metrics:');+ console.log(` Success Rate: ${(baseline.successRate * 100).toFixed(1)}%`);+ console.log(` Avg Execution Time: ${baseline.executionTime.toFixed(0)}ms`);+ console.log(` Average Score: ${baseline.score.toFixed(2)}`);+ break;++ case 'status':+ // Show pipeline status+ await pipeline.initialize();++ // Load agent profiles+ let profiles = {};+ try {+ const data = await fs.readFile(pipeline.agentProfiles, 'utf8');+ profiles = JSON.parse(data);+ } catch {+ profiles = pipeline.getDefaultProfiles();+ }++ console.log('\nπ Training Pipeline Status');+ console.log('β'.repeat(50));++ console.log('\nπ€ Agent Profiles:');+ for (const [strategy, profile] of Object.entries(profiles)) {+ console.log(` ${strategy}:`);+ console.log(` Success Rate: ${(profile.successRate * 100).toFixed(1)}%`);+ console.log(` Average Score: ${profile.avgScore.toFixed(2)}`);+ console.log(` Execution Time: ${profile.avgExecutionTime.toFixed(0)}ms`);+ console.log(` Total Uses: ${profile.uses}`);+ }++ // Check for improvement files+ try {+ const improvements = await fs.readdir('.claude-flow/validation');+ console.log(`\nβ Validation Runs: ${improvements.length}`);+ } catch {+ console.log('\nβ οΈ No validation runs found');+ }++ break;++ default:+ console.log('Usage: training-pipeline <command> [options]');+ console.log('\nCommands:');+ console.log(' run - Run full training pipeline');+ console.log(' generate - Generate training tasks');+ console.log(' validate - Validate current performance');+ console.log(' status - Show pipeline status');+ console.log('\nOptions:');+ console.log(' --complexity <level> - Task complexity (easy/medium/hard)');+ console.log(' --iterations <n> - Number of training iterations');+ console.log(' --validate - Enable validation');+ }+}++export default TrainingPipeline;\ No newline at end of filediff --git a/src/cli/simple-commands/training-pipeline.js b/src/cli/simple-commands/training-pipeline.jsindex 567a8da96d..4119fd2458 100644--- a/src/cli/simple-commands/training-pipeline.js+++ b/src/cli/simple-commands/training-pipeline.js@@ -1,7 +1,7 @@#!/usr/bin/env node/**- * Training Pipeline for Continuous Agent Improvement- * Creates feedback loops that actually improve agent performance+ * Training Pipeline with Real Task Execution+ * Executes actual code and learns from real test results*/import fs from 'fs/promises';@@ -13,7 +13,7 @@ import { exec } from 'child_process';const execAsync = promisify(exec);/**- * Training Pipeline that creates real improvement cycles+ * Training Pipeline that executes real tasks and learns from actual results*/export class TrainingPipeline {constructor() {@@ -21,6 +21,7 @@ export class TrainingPipeline {this.trainingLog = '.claude-flow/training/pipeline-log.jsonl';this.improvementMetrics = '.claude-flow/metrics/improvements.json';this.agentProfiles = '.claude-flow/agents/profiles.json';+ this.realTasksDir = '.claude-flow/training/real-tasks';this.initialized = false;}@@ -32,6 +33,7 @@ export class TrainingPipeline {const dirs = ['.claude-flow/pipeline','.claude-flow/training',+ '.claude-flow/training/real-tasks','.claude-flow/metrics','.claude-flow/agents','.claude-flow/validation',@@ -45,66 +47,237 @@ export class TrainingPipeline {// Load or create pipeline configurationawait this.loadPipelineConfig();- console.log('π Training Pipeline initialized');+ console.log('π Real Training Pipeline initialized');this.initialized = true;}/**- * STAGE 1: Generate Training Tasks- * Creates real-world tasks for agents to learn from+ * STAGE 1: Generate REAL Training Tasks+ * Creates actual code files that can be tested*/- async generateTrainingTasks(complexity = 'medium') {+ async generateRealTrainingTasks(complexity = 'medium') {+ const taskId = Date.now();+ const taskDir = path.join(this.realTasksDir, `task-${taskId}`);+ await fs.mkdir(taskDir, { recursive: true });+const tasks = {easy: [- { type: 'code', task: 'Create a function to validate email addresses', expectedChecks: ['test', 'lint'] },- { type: 'test', task: 'Write unit tests for array utilities', expectedChecks: ['coverage', 'test'] },- { type: 'docs', task: 'Document API endpoints', expectedChecks: ['lint'] },+ {+ type: 'function',+ name: 'validateEmail',+ task: 'Create email validation function',+ code: `function validateEmail(email) {+ const regex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;+ return regex.test(email);+}++module.exports = { validateEmail };`,+ test: `+const { validateEmail } = require('./index');++describe('validateEmail', () => {+ test('validates correct email', () => {+ expect(validateEmail('[email protected]')).toBe(true);+ });++ test('rejects invalid email', () => {+ expect(validateEmail('invalid')).toBe(false);+ });+});+`+ }],medium: [- { type: 'api', task: 'Build REST API with authentication', expectedChecks: ['test', 'lint', 'typecheck'] },- { type: 'refactor', task: 'Refactor legacy code to modern patterns', expectedChecks: ['test', 'lint'] },- { type: 'debug', task: 'Fix performance bottlenecks', expectedChecks: ['test', 'benchmark'] },+ {+ type: 'api',+ name: 'userApi',+ task: 'Build user API endpoint',+ code: `+const express = require('express');+const app = express();++app.use(express.json());++const users = [];++app.get('/users', (req, res) => {+ res.json(users);+});++app.post('/users', (req, res) => {+ const { name, email } = req.body;+ if (!name || !email) {+ return res.status(400).json({ error: 'Name and email required' });+ }+ const user = { id: users.length + 1, name, email };+ users.push(user);+ res.status(201).json(user);+});++module.exports = app;+`,+ test: `+const request = require('supertest');+const app = require('./index');++describe('User API', () => {+ test('GET /users returns empty array initially', async () => {+ const res = await request(app).get('/users');+ expect(res.status).toBe(200);+ expect(res.body).toEqual([]);+ });++ test('POST /users creates a user', async () => {+ const res = await request(app)+ .post('/users')+ .send({ name: 'Test', email: '[email protected]' });+ expect(res.status).toBe(201);+ expect(res.body.name).toBe('Test');+ });+});+`+ }],hard: [- { type: 'architecture', task: 'Design microservices architecture', expectedChecks: ['design-review', 'scalability'] },- { type: 'optimization', task: 'Optimize database queries for scale', expectedChecks: ['benchmark', 'test'] },- { type: 'security', task: 'Implement secure payment processing', expectedChecks: ['security', 'test', 'compliance'] },+ {+ type: 'algorithm',+ name: 'sortAlgorithm',+ task: 'Implement efficient sorting',+ code: `+function quickSort(arr) {+ if (arr.length <= 1) return arr;++ const pivot = arr[Math.floor(arr.length / 2)];+ const left = arr.filter(x => x < pivot);+ const middle = arr.filter(x => x === pivot);+ const right = arr.filter(x => x > pivot);++ return [...quickSort(left), ...middle, ...quickSort(right)];+}++function mergeSort(arr) {+ if (arr.length <= 1) return arr;++ const mid = Math.floor(arr.length / 2);+ const left = mergeSort(arr.slice(0, mid));+ const right = mergeSort(arr.slice(mid));++ const result = [];+ let i = 0, j = 0;++ while (i < left.length && j < right.length) {+ if (left[i] < right[j]) {+ result.push(left[i++]);+ } else {+ result.push(right[j++]);+ }+ }++ return result.concat(left.slice(i)).concat(right.slice(j));+}++module.exports = { quickSort, mergeSort };+`,+ test: `+const { quickSort, mergeSort } = require('./index');++describe('Sorting Algorithms', () => {+ const unsorted = [3, 1, 4, 1, 5, 9, 2, 6];+ const sorted = [1, 1, 2, 3, 4, 5, 6, 9];++ test('quickSort sorts correctly', () => {+ expect(quickSort(unsorted)).toEqual(sorted);+ });++ test('mergeSort sorts correctly', () => {+ expect(mergeSort(unsorted)).toEqual(sorted);+ });++ test('handles empty arrays', () => {+ expect(quickSort([])).toEqual([]);+ expect(mergeSort([])).toEqual([]);+ });+});+`+ }]};const selectedTasks = tasks[complexity] || tasks.medium;-- // Save training tasks- const taskFile = `.claude-flow/training/tasks-${Date.now()}.json`;- await fs.writeFile(taskFile, JSON.stringify({- complexity,- tasks: selectedTasks,- created: new Date().toISOString()- }, null, 2));-- console.log(`π Generated ${selectedTasks.length} ${complexity} training tasks`);- return selectedTasks;+ const realTasks = [];++ // Create real task files+ for (const task of selectedTasks) {+ const projectDir = path.join(taskDir, task.name);+ await fs.mkdir(projectDir, { recursive: true });++ // Write actual code file+ await fs.writeFile(path.join(projectDir, 'index.js'), task.code);++ // Write test file+ await fs.writeFile(path.join(projectDir, 'index.test.js'), task.test);++ // Create package.json with real dependencies+ const packageJson = {+ name: task.name,+ version: "1.0.0",+ scripts: {+ test: "jest --silent",+ lint: "eslint index.js || true",+ typecheck: "echo 'No TypeScript' || true"+ },+ devDependencies: {+ jest: "^29.0.0",+ eslint: "^8.0.0",+ supertest: "^6.0.0"+ },+ dependencies: {+ express: task.type === 'api' ? "^4.18.0" : undefined+ }+ };++ await fs.writeFile(+ path.join(projectDir, 'package.json'),+ JSON.stringify(packageJson, null, 2)+ );++ realTasks.push({+ ...task,+ projectDir,+ taskId+ });+ }++ console.log(`π Generated ${realTasks.length} REAL ${complexity} training tasks`);+ return realTasks;}/**- * STAGE 2: Execute Tasks with Different Agent Configurations- * Runs tasks with various agent settings to find optimal configurations+ * STAGE 2: Execute REAL Tasks with Different Strategies+ * Actually runs npm install, tests, and measures real performance*/- async executeTrainingRun(tasks, agentConfig = {}) {+ async executeRealTrainingRun(tasks, agentConfig = {}) {const results = [];for (const task of tasks) {- console.log(`\nπ Executing: ${task.task}`);+ console.log(`\nπ Executing REAL task: ${task.task}`);- // Create a test environment- const testDir = `.claude-flow/training/test-${Date.now()}`;- await fs.mkdir(testDir, { recursive: true });+ // Install dependencies (only once per task)+ try {+ console.log(` π¦ Installing dependencies...`);+ execSync('npm install --silent', {+ cwd: task.projectDir,+ stdio: 'pipe'+ });+ } catch (e) {+ console.log(` β οΈ Install warning: ${e.message.slice(0, 50)}`);+ }- // Simulate agent execution with different strategies+ // Test different strategies with REAL variationsconst strategies = agentConfig.strategies || ['conservative', 'balanced', 'aggressive'];for (const strategy of strategies) {- const result = await this.executeTaskWithStrategy(task, strategy, testDir);+ const result = await this.executeRealTaskWithStrategy(task, strategy);results.push({task: task.task,type: task.type,@@ -113,54 +286,118 @@ export class TrainingPipeline {timestamp: new Date().toISOString()});}-- // Clean up test directory- await fs.rm(testDir, { recursive: true, force: true });}- // Save results- const resultsFile = `.claude-flow/training/results-${Date.now()}.json`;+ // Save real results+ const resultsFile = `.claude-flow/training/real-results-${Date.now()}.json`;await fs.writeFile(resultsFile, JSON.stringify(results, null, 2));return results;}/**- * Execute a task with a specific strategy+ * Execute a REAL task with a specific strategy+ * Strategies affect how we modify and test the code*/- async executeTaskWithStrategy(task, strategy, testDir) {+ async executeRealTaskWithStrategy(task, strategy) {const startTime = Date.now();+ const checks = {};++ // Save original code+ const originalCode = await fs.readFile(path.join(task.projectDir, 'index.js'), 'utf8');- // Create a simple test file based on task type- const testFile = path.join(testDir, `test-${strategy}.js`);- const content = this.generateTestContent(task.type, strategy);- await fs.writeFile(testFile, content);+ // Modify code based on strategy (but more carefully!)+ if (strategy === 'aggressive') {+ // Aggressive: Skip some validation (but keep valid syntax)+ const aggressiveCode = originalCode.replace(+ /if \(!(\w+)\)/g,+ 'if (false && !$1)'+ );+ await fs.writeFile(path.join(task.projectDir, 'index.js'), aggressiveCode);+ } else if (strategy === 'conservative') {+ // Conservative: Add validation at the top of functions+ const conservativeCode = originalCode.replace(+ /function (\w+)\((.*?)\) {/g,+ 'function $1($2) {\n // Extra validation for conservative strategy\n if (arguments.length === 0) throw new Error("No arguments provided");'+ );+ await fs.writeFile(path.join(task.projectDir, 'index.js'), conservativeCode);+ }+ // Balanced: Keep original code- // Run verification checks- const checks = {};- for (const check of task.expectedChecks) {- checks[check] = await this.runCheck(check, testFile);+ // Run REAL tests+ try {+ const testResult = execSync('npm test', {+ cwd: task.projectDir,+ encoding: 'utf8',+ stdio: 'pipe'+ });+ checks.test = {+ passed: true,+ score: 1.0,+ output: testResult.slice(0, 100)+ };+ } catch (e) {+ checks.test = {+ passed: false,+ score: 0.3,+ error: e.message.slice(0, 100)+ };+ }++ // Run REAL lint+ try {+ const lintResult = execSync('npm run lint', {+ cwd: task.projectDir,+ encoding: 'utf8',+ stdio: 'pipe'+ });+ const hasErrors = lintResult.includes('error');+ checks.lint = {+ passed: !hasErrors,+ score: hasErrors ? 0.5 : 1.0+ };+ } catch (e) {+ checks.lint = {+ passed: false,+ score: 0.3+ };}- // Calculate performance metrics+ // Restore original code after testing+ await fs.writeFile(path.join(task.projectDir, 'index.js'), originalCode);++ // Calculate REAL performance metricsconst executionTime = Date.now() - startTime;const successRate = Object.values(checks).filter(c => c.passed).length / Object.values(checks).length;+ // Strategy-specific scoring based on REAL results+ let strategyBonus = 0;+ if (strategy === 'aggressive' && executionTime < 1000) {+ strategyBonus = 0.2; // Bonus for fast execution+ } else if (strategy === 'conservative' && successRate === 1.0) {+ strategyBonus = 0.3; // Bonus for perfect reliability+ } else if (strategy === 'balanced' && successRate > 0.5 && executionTime < 2000) {+ strategyBonus = 0.25; // Bonus for good balance+ }++ const score = (successRate * 60) + (Math.max(0, 1 - executionTime/5000) * 20) + (strategyBonus * 20);+return {executionTime,successRate,checks,strategy,- score: this.calculateScore(checks, executionTime, strategy)+ score,+ real: true // Mark as real execution};}/**- * STAGE 3: Learn from Results- * Updates agent profiles based on performance+ * STAGE 3: Learn from REAL Results+ * Updates profiles based on actual performance*/- async learnFromResults(results) {- console.log('\nπ§ Learning from results...');+ async learnFromRealResults(results) {+ console.log('\nπ§ Learning from REAL results...');// Load current agent profileslet profiles = {};@@ -171,7 +408,7 @@ export class TrainingPipeline {profiles = this.getDefaultProfiles();}- // Analyze results by strategy+ // Analyze REAL results by strategyconst strategyPerformance = {};for (const result of results) {if (!strategyPerformance[result.strategy]) {@@ -179,7 +416,8 @@ export class TrainingPipeline {totalScore: 0,count: 0,avgExecutionTime: 0,- successRate: 0+ successRate: 0,+ realExecutions: 0};}@@ -188,118 +426,122 @@ export class TrainingPipeline {perf.count++;perf.avgExecutionTime += result.executionTime;perf.successRate += result.successRate;+ if (result.real) perf.realExecutions++;}- // Calculate averages and update profiles+ // Calculate averages and update profiles with REAL datafor (const [strategy, perf] of Object.entries(strategyPerformance)) {perf.avgScore = perf.totalScore / perf.count;perf.avgExecutionTime = perf.avgExecutionTime / perf.count;perf.successRate = perf.successRate / perf.count;- // Update agent profiles based on performance- this.updateAgentProfile(profiles, strategy, perf);+ // Update with stronger learning for real executions+ const learningRate = perf.realExecutions > 0 ? 0.4 : 0.1;+ this.updateAgentProfile(profiles, strategy, perf, learningRate);}// Save updated profilesawait fs.writeFile(this.agentProfiles, JSON.stringify(profiles, null, 2));- // Generate improvement recommendations- const recommendations = this.generateRecommendations(strategyPerformance);+ // Generate recommendations based on REAL performance+ const recommendations = this.generateRealRecommendations(strategyPerformance);- console.log('\nπ Learning Results:');+ console.log('\nπ Real Learning Results:');for (const [strategy, perf] of Object.entries(strategyPerformance)) {- console.log(` ${strategy}: Score ${perf.avgScore.toFixed(2)}, Success ${(perf.successRate * 100).toFixed(1)}%`);+ console.log(` ${strategy}: Score ${perf.avgScore.toFixed(2)}, Success ${(perf.successRate * 100).toFixed(1)}%, Time ${perf.avgExecutionTime.toFixed(0)}ms`);}return { profiles, recommendations };}- /**- * STAGE 4: Validate Improvements- * Tests if the training actually improved performance- */- async validateImprovements(beforeMetrics, afterMetrics) {- console.log('\nβ Validating improvements...');-- const validation = {- improved: [],- declined: [],- unchanged: [],- summary: {}- };+ updateAgentProfile(profiles, strategy, performance, learningRate = 0.3) {+ if (!profiles[strategy]) {+ profiles[strategy] = {+ successRate: 0.5,+ avgScore: 50,+ avgExecutionTime: 2000,+ uses: 0,+ realExecutions: 0+ };+ }- // Compare metrics- const metrics = ['successRate', 'executionTime', 'score'];+ const profile = profiles[strategy];- for (const metric of metrics) {- const before = beforeMetrics[metric] || 0;- const after = afterMetrics[metric] || 0;- const change = after - before;- const percentChange = before > 0 ? (change / before) * 100 : 0;-- if (percentChange > 5) {- validation.improved.push({ metric, change: percentChange });- } else if (percentChange < -5) {- validation.declined.push({ metric, change: percentChange });- } else {- validation.unchanged.push({ metric, change: percentChange });- }+ // Update with exponential moving average+ profile.successRate = profile.successRate * (1 - learningRate) + performance.successRate * learningRate;+ profile.avgScore = profile.avgScore * (1 - learningRate) + performance.avgScore * learningRate;+ profile.avgExecutionTime = profile.avgExecutionTime * (1 - learningRate) + performance.avgExecutionTime * learningRate;+ profile.uses++;+ if (performance.realExecutions) {+ profile.realExecutions = (profile.realExecutions || 0) + performance.realExecutions;}- validation.summary = {- overallImprovement: validation.improved.length > validation.declined.length,- improvementScore: validation.improved.length - validation.declined.length,- timestamp: new Date().toISOString()- };-- // Save validation results- const validationFile = `.claude-flow/validation/validation-${Date.now()}.json`;- await fs.writeFile(validationFile, JSON.stringify(validation, null, 2));-- console.log(` Improved: ${validation.improved.length} metrics`);- console.log(` Declined: ${validation.declined.length} metrics`);- console.log(` Unchanged: ${validation.unchanged.length} metrics`);+ // Add performance trend+ if (!profile.trend) profile.trend = [];+ profile.trend.push({+ score: performance.avgScore,+ timestamp: new Date().toISOString(),+ real: performance.realExecutions > 0+ });+ if (profile.trend.length > 20) {+ profile.trend = profile.trend.slice(-20);+ }- return validation;+ // Mark improvement+ if (profile.trend.length > 1) {+ const recent = profile.trend.slice(-5).reduce((sum, t) => sum + t.score, 0) / Math.min(5, profile.trend.length);+ const older = profile.trend.slice(0, -5).reduce((sum, t) => sum + t.score, 0) / Math.max(1, profile.trend.length - 5);+ profile.improving = recent > older;+ profile.improvementRate = ((recent - older) / older * 100).toFixed(1);+ }}- /**- * STAGE 5: Apply Improvements to Production- * Updates the actual agent configurations with learned improvements- */- async applyImprovements(profiles, recommendations) {- console.log('\nπ Applying improvements to production...');-- // Update swarm configuration- const swarmConfig = {- defaultStrategy: this.selectBestStrategy(profiles),- agentProfiles: profiles,- optimizations: recommendations,- appliedAt: new Date().toISOString()- };+ generateRealRecommendations(strategyPerformance) {+ const recommendations = [];- await fs.writeFile('.claude-flow/swarm-config.json', JSON.stringify(swarmConfig, null, 2));+ for (const [strategy, perf] of Object.entries(strategyPerformance)) {+ if (perf.successRate < 0.7) {+ recommendations.push({+ type: 'improve_reliability',+ strategy,+ action: `${strategy} needs better error handling (${(perf.successRate * 100).toFixed(1)}% success)`,+ priority: 'high'+ });+ }- // Create improved command templates- const improvedCommands = this.generateImprovedCommands(profiles);- await fs.writeFile('.claude/commands/improved-workflows.js', improvedCommands);+ if (perf.avgExecutionTime > 3000) {+ recommendations.push({+ type: 'optimize_speed',+ strategy,+ action: `${strategy} is too slow (${perf.avgExecutionTime.toFixed(0)}ms avg)`,+ priority: 'medium'+ });+ }- console.log('β Improvements applied successfully');-- return swarmConfig;+ if (perf.avgScore > 75) {+ recommendations.push({+ type: 'good_performance',+ strategy,+ action: `${strategy} performing well (${perf.avgScore.toFixed(1)} score)`,+ priority: 'info'+ });+ }+ }++ return recommendations;}/**- * Full Training Pipeline Execution+ * Full Real Training Pipeline Execution*/- async runFullPipeline(options = {}) {+ async runRealPipeline(options = {}) {const {complexity = 'medium',iterations = 3,validate = true} = options;- console.log('π― Starting Full Training Pipeline');+ console.log('π― Starting REAL Training Pipeline');console.log('β'.repeat(50));await this.initialize();@@ -313,31 +555,35 @@ export class TrainingPipeline {console.log(`\nπ Iteration ${i}/${iterations}`);console.log('β'.repeat(40));- // Stage 1: Generate tasks- const tasks = await this.generateTrainingTasks(complexity);+ // Stage 1: Generate REAL tasks+ const tasks = await this.generateRealTrainingTasks(complexity);- // Stage 2: Execute with different configurations- const results = await this.executeTrainingRun(tasks);+ // Stage 2: Execute with REAL code+ const results = await this.executeRealTrainingRun(tasks);cumulativeResults = [...cumulativeResults, ...results];- // Stage 3: Learn from results- const { profiles, recommendations } = await this.learnFromResults(results);+ // Stage 3: Learn from REAL results+ const { profiles, recommendations } = await this.learnFromRealResults(results);++ // Show recommendations+ if (recommendations.length > 0) {+ console.log('\nπ‘ Recommendations:');+ for (const rec of recommendations.slice(0, 3)) {+ console.log(` β’ ${rec.action}`);+ }+ }// Stage 4: Validate if enabledif (validate && i === iterations) {const currentMetrics = await this.captureMetrics();const validation = await this.validateImprovements(baselineMetrics, currentMetrics);- if (!validation.summary.overallImprovement) {- console.log('β οΈ No significant improvement detected');- // Consider reverting or adjusting learning parameters+ if (validation.summary.overallImprovement) {+ console.log('β Real improvement detected!');+ } else {+ console.log('β οΈ More training needed for significant improvement');}}-- // Stage 5: Apply improvements- if (i === iterations || (results.length > 10)) {- await this.applyImprovements(profiles, recommendations);- }}// Generate final report@@ -347,266 +593,131 @@ export class TrainingPipeline {return {success: true,totalTasks: cumulativeResults.length,+ realExecutions: cumulativeResults.filter(r => r.real).length,improvements: await this.calculateOverallImprovement(baselineMetrics)};}- // Helper methods-- generateTestContent(taskType, strategy) {- const templates = {- code: `-// Strategy: ${strategy}-function processData(input) {- ${strategy === 'aggressive' ? '// Fast but risky' : '// Safe but slower'}- ${strategy === 'aggressive' ? 'return input.map(x => x * 2);' : 'if (!input) return []; return input.map(x => x * 2);'}-}-module.exports = { processData };-`,- test: `-// Test strategy: ${strategy}-describe('Test Suite', () => {- test('should pass', () => {- expect(true).toBe(true);- });-});-`,- api: `-// API strategy: ${strategy}-const express = require('express');-const app = express();-${strategy === 'aggressive' ? '' : 'app.use(helmet());'}-app.get('/api', (req, res) => res.json({ status: 'ok' }));-module.exports = app;-`- };-- return templates[taskType] || templates.code;- }-- async runCheck(checkType, file) {- // Simulate running actual checks- const checks = {- test: async () => {- try {- // In real implementation, would run actual tests- return { passed: Math.random() > 0.3, score: Math.random() };- } catch {- return { passed: false, score: 0 };- }- },- lint: async () => {- try {- // In real implementation, would run eslint- return { passed: Math.random() > 0.2, score: Math.random() };- } catch {- return { passed: false, score: 0 };- }- },- typecheck: async () => {- try {- // In real implementation, would run tsc- return { passed: Math.random() > 0.4, score: Math.random() };- } catch {- return { passed: false, score: 0 };+ // Reuse helper methods from original+ async captureMetrics() {+ try {+ const data = await fs.readFile(this.agentProfiles, 'utf8');+ const profiles = JSON.parse(data);++ // Calculate weighted average from all strategies+ let totalScore = 0;+ let totalSuccess = 0;+ let totalTime = 0;+ let count = 0;++ for (const profile of Object.values(profiles)) {+ if (profile.uses > 0) {+ totalScore += profile.avgScore;+ totalSuccess += profile.successRate;+ totalTime += profile.avgExecutionTime;+ count++;}- },- coverage: async () => {- return { passed: Math.random() > 0.5, score: Math.random() };- },- benchmark: async () => {- return { passed: true, score: Math.random(), time: Math.random() * 1000 };}- };-- const check = checks[checkType] || checks.test;- return await check();- }-- calculateScore(checks, executionTime, strategy) {- let score = 0;-- // Success rate (40% weight)- const successRate = Object.values(checks).filter(c => c.passed).length / Object.values(checks).length;- score += successRate * 40;-- // Execution time (30% weight) - faster is better- const timeScore = Math.max(0, 1 - (executionTime / 10000));- score += timeScore * 30;-- // Strategy bonus (30% weight)- const strategyScores = {- conservative: 0.7, // Safe but slower- balanced: 0.85, // Good balance- aggressive: 0.6 // Fast but risky- };- score += (strategyScores[strategy] || 0.5) * 30;-- return score;- }-- updateAgentProfile(profiles, strategy, performance) {- if (!profiles[strategy]) {- profiles[strategy] = {++ return {+ successRate: count > 0 ? totalSuccess / count : 0,+ executionTime: count > 0 ? totalTime / count : 0,+ score: count > 0 ? totalScore / count : 0+ };+ } catch {+ return {successRate: 0,- avgScore: 0,- avgExecutionTime: 0,- uses: 0+ executionTime: 0,+ score: 0};}-- const profile = profiles[strategy];- const weight = 0.3; // Learning rate-- // Update with exponential moving average- profile.successRate = profile.successRate * (1 - weight) + performance.successRate * weight;- profile.avgScore = profile.avgScore * (1 - weight) + performance.avgScore * weight;- profile.avgExecutionTime = profile.avgExecutionTime * (1 - weight) + performance.avgExecutionTime * weight;- profile.uses++;-- // Add performance trend- if (!profile.trend) profile.trend = [];- profile.trend.push({- score: performance.avgScore,- timestamp: new Date().toISOString()- });- if (profile.trend.length > 20) {- profile.trend = profile.trend.slice(-20);- }}- generateRecommendations(strategyPerformance) {- const recommendations = [];-- for (const [strategy, perf] of Object.entries(strategyPerformance)) {- if (perf.successRate < 0.7) {- recommendations.push({- type: 'improve_success_rate',- strategy,- action: `Focus on reliability for ${strategy} strategy`,- priority: 'high'- });- }-- if (perf.avgExecutionTime > 5000) {- recommendations.push({- type: 'optimize_performance',- strategy,- action: `Optimize execution time for ${strategy} strategy`,- priority: 'medium'- });- }-- if (perf.avgScore < 50) {- recommendations.push({- type: 'enhance_quality',- strategy,- action: `Improve overall quality for ${strategy} strategy`,- priority: 'high'- });- }- }-- return recommendations;- }+ async validateImprovements(beforeMetrics, afterMetrics) {+ const validation = {+ improved: [],+ declined: [],+ unchanged: [],+ summary: {}+ };- selectBestStrategy(profiles) {- let bestStrategy = 'balanced';- let bestScore = 0;+ const metrics = ['successRate', 'executionTime', 'score'];++ for (const metric of metrics) {+ const before = beforeMetrics[metric] || 0.01; // Avoid division by zero+ const after = afterMetrics[metric] || 0;+ const change = after - before;+ const percentChange = (change / before) * 100;- for (const [strategy, profile] of Object.entries(profiles)) {- if (profile.avgScore > bestScore) {- bestScore = profile.avgScore;- bestStrategy = strategy;+ if (percentChange > 5) {+ validation.improved.push({ metric, change: percentChange });+ } else if (percentChange < -5) {+ validation.declined.push({ metric, change: percentChange });+ } else {+ validation.unchanged.push({ metric, change: percentChange });}}- return bestStrategy;- }-- generateImprovedCommands(profiles) {- const bestStrategy = this.selectBestStrategy(profiles);-- return `-/**- * Improved Workflow Commands- * Generated by Training Pipeline- * Best Strategy: ${bestStrategy}- */+ validation.summary = {+ overallImprovement: validation.improved.length > validation.declined.length,+ improvementScore: validation.improved.length - validation.declined.length,+ timestamp: new Date().toISOString()+ };-export const improvedWorkflows = {- strategy: '${bestStrategy}',-- execute: async (task) => {- // Use learned optimal configuration- const config = ${JSON.stringify(profiles[bestStrategy], null, 2)};-- // Apply learned optimizations- console.log('Using optimized strategy: ${bestStrategy}');-- // Execute with improved parameters- return await executeWithConfig(task, config);- }-};-`;- }+ console.log(`\nβ Validating improvements...`);+ console.log(` Improved: ${validation.improved.length} metrics`);+ console.log(` Declined: ${validation.declined.length} metrics`);+ console.log(` Unchanged: ${validation.unchanged.length} metrics`);- async captureMetrics() {- // Capture current system metrics- try {- const verifyData = await fs.readFile('.swarm/verification-memory.json', 'utf8');- const memory = JSON.parse(verifyData);-- const history = memory.history || [];- const recent = history.slice(-20);-- return {- successRate: recent.filter(h => h.passed).length / recent.length,- executionTime: recent.reduce((sum, h) => sum + (h.executionTime || 0), 0) / recent.length,- score: recent.reduce((sum, h) => sum + h.score, 0) / recent.length- };- } catch {- return {- successRate: 0,- executionTime: 0,- score: 0- };- }+ return validation;}async calculateOverallImprovement(baselineMetrics) {const currentMetrics = await this.captureMetrics();+ const base = {+ successRate: baselineMetrics.successRate || 0.01,+ executionTime: baselineMetrics.executionTime || 1,+ score: baselineMetrics.score || 0.01+ };+return {- successRate: ((currentMetrics.successRate - baselineMetrics.successRate) / baselineMetrics.successRate) * 100,- executionTime: ((baselineMetrics.executionTime - currentMetrics.executionTime) / baselineMetrics.executionTime) * 100,- score: ((currentMetrics.score - baselineMetrics.score) / baselineMetrics.score) * 100+ successRate: ((currentMetrics.successRate - base.successRate) / base.successRate) * 100,+ executionTime: ((base.executionTime - currentMetrics.executionTime) / base.executionTime) * 100,+ score: ((currentMetrics.score - base.score) / base.score) * 100};}async generateFinalReport(results) {+ const realResults = results.filter(r => r.real);const successRates = {};const scores = {};+ const times = {};- for (const result of results) {+ for (const result of realResults) {if (!successRates[result.strategy]) {successRates[result.strategy] = [];scores[result.strategy] = [];+ times[result.strategy] = [];}successRates[result.strategy].push(result.successRate);scores[result.strategy].push(result.score);+ times[result.strategy].push(result.executionTime);}- let report = 'π Training Pipeline Report\n';+ let report = 'π Real Training Pipeline Report\n';report += 'β'.repeat(50) + '\n\n';for (const strategy of Object.keys(successRates)) {const avgSuccess = successRates[strategy].reduce((a, b) => a + b, 0) / successRates[strategy].length;const avgScore = scores[strategy].reduce((a, b) => a + b, 0) / scores[strategy].length;+ const avgTime = times[strategy].reduce((a, b) => a + b, 0) / times[strategy].length;report += `Strategy: ${strategy}\n`;report += ` Average Success Rate: ${(avgSuccess * 100).toFixed(1)}%\n`;report += ` Average Score: ${avgScore.toFixed(2)}\n`;+ report += ` Average Time: ${avgTime.toFixed(0)}ms\n`;+ report += ` Real Executions: ${successRates[strategy].length}\n`;report += '\n';}@@ -616,22 +727,25 @@ export const improvedWorkflows = {getDefaultProfiles() {return {conservative: {- successRate: 0.8,- avgScore: 70,+ successRate: 0.5,+ avgScore: 50,avgExecutionTime: 3000,- uses: 0+ uses: 0,+ realExecutions: 0},balanced: {- successRate: 0.75,- avgScore: 75,+ successRate: 0.5,+ avgScore: 50,avgExecutionTime: 2000,- uses: 0+ uses: 0,+ realExecutions: 0},aggressive: {- successRate: 0.6,- avgScore: 65,+ successRate: 0.5,+ avgScore: 50,avgExecutionTime: 1000,- uses: 0+ uses: 0,+ realExecutions: 0}};}@@ -642,10 +756,11 @@ export const improvedWorkflows = {return JSON.parse(data);} catch {const defaultConfig = {- version: '1.0.0',+ version: '2.0.0',strategies: ['conservative', 'balanced', 'aggressive'],- learningRate: 0.3,- minSamplesForUpdate: 5,+ learningRate: 0.4,+ minSamplesForUpdate: 3,+ useRealExecution: true,created: new Date().toISOString()};@@ -658,32 +773,34 @@ export const improvedWorkflows = {/*** CLI Command Handler*/-export async function trainingPipelineCommand(args, flags) {- const pipeline = new TrainingPipeline();+export async function realTrainingPipelineCommand(args, flags) {+ const pipeline = new RealTrainingPipeline();const subcommand = args[0] || 'run';switch (subcommand) {case 'run':- // Run full pipeline+ // Run real pipelineconst options = {complexity: flags.complexity || 'medium',iterations: parseInt(flags.iterations) || 3,validate: flags.validate !== false};- console.log('π Starting Training Pipeline');+ console.log('π Starting REAL Training Pipeline');console.log(` Complexity: ${options.complexity}`);console.log(` Iterations: ${options.iterations}`);console.log(` Validation: ${options.validate ? 'Enabled' : 'Disabled'}`);+ console.log(' Mode: REAL EXECUTION\n');- const result = await pipeline.runFullPipeline(options);+ const result = await pipeline.runRealPipeline(options);if (result.success) {- console.log('\nβ Training Pipeline completed successfully');- console.log(` Total tasks executed: ${result.totalTasks}`);+ console.log('\nβ Real Training Pipeline completed');+ console.log(` Total tasks: ${result.totalTasks}`);+ console.log(` Real executions: ${result.realExecutions}`);if (result.improvements) {- console.log('\nπ Improvements:');+ console.log('\nπ Real Improvements:');console.log(` Success Rate: ${result.improvements.successRate > 0 ? '+' : ''}${result.improvements.successRate.toFixed(1)}%`);console.log(` Execution Time: ${result.improvements.executionTime > 0 ? '+' : ''}${result.improvements.executionTime.toFixed(1)}%`);console.log(` Score: ${result.improvements.score > 0 ? '+' : ''}${result.improvements.score.toFixed(1)}%`);@@ -691,31 +808,10 @@ export async function trainingPipelineCommand(args, flags) {}break;- case 'generate':- // Just generate training tasks- await pipeline.initialize();- const tasks = await pipeline.generateTrainingTasks(flags.complexity || 'medium');- console.log(`\nβ Generated ${tasks.length} training tasks`);- for (const task of tasks) {- console.log(` β’ ${task.task}`);- }- break;-- case 'validate':- // Validate current performance- await pipeline.initialize();- const baseline = await pipeline.captureMetrics();- console.log('\nπ Current Performance Metrics:');- console.log(` Success Rate: ${(baseline.successRate * 100).toFixed(1)}%`);- console.log(` Avg Execution Time: ${baseline.executionTime.toFixed(0)}ms`);- console.log(` Average Score: ${baseline.score.toFixed(2)}`);- break;-case 'status':- // Show pipeline status+ // Show real pipeline statusawait pipeline.initialize();- // Load agent profileslet profiles = {};try {const data = await fs.readFile(pipeline.agentProfiles, 'utf8');@@ -724,40 +820,43 @@ export async function trainingPipelineCommand(args, flags) {profiles = pipeline.getDefaultProfiles();}- console.log('\nπ Training Pipeline Status');+ console.log('\nπ Real Training Pipeline Status');console.log('β'.repeat(50));- console.log('\nπ€ Agent Profiles:');+ console.log('\nπ€ Strategy Profiles:');for (const [strategy, profile] of Object.entries(profiles)) {console.log(` ${strategy}:`);console.log(` Success Rate: ${(profile.successRate * 100).toFixed(1)}%`);console.log(` Average Score: ${profile.avgScore.toFixed(2)}`);console.log(` Execution Time: ${profile.avgExecutionTime.toFixed(0)}ms`);console.log(` Total Uses: ${profile.uses}`);+ console.log(` Real Executions: ${profile.realExecutions || 0}`);+ if (profile.improving !== undefined) {+ console.log(` Trend: ${profile.improving ? 'π Improving' : 'π Declining'} (${profile.improvementRate}%)`);+ }}+ break;- // Check for improvement files- try {- const improvements = await fs.readdir('.claude-flow/validation');- console.log(`\nβ Validation Runs: ${improvements.length}`);- } catch {- console.log('\nβ οΈ No validation runs found');- }-+ case 'validate':+ // Validate current performance+ await pipeline.initialize();+ const metrics = await pipeline.captureMetrics();+ console.log('\nπ Current Real Performance:');+ console.log(` Success Rate: ${(metrics.successRate * 100).toFixed(1)}%`);+ console.log(` Avg Execution Time: ${metrics.executionTime.toFixed(0)}ms`);+ console.log(` Average Score: ${metrics.score.toFixed(2)}`);break;default:- console.log('Usage: training-pipeline <command> [options]');+ console.log('Usage: real-train-pipeline <command> [options]');console.log('\nCommands:');- console.log(' run - Run full training pipeline');- console.log(' generate - Generate training tasks');- console.log(' validate - Validate current performance');+ console.log(' run - Run real training pipeline');console.log(' status - Show pipeline status');+ console.log(' validate - Check current performance');console.log('\nOptions:');- console.log(' --complexity <level> - Task complexity (easy/medium/hard)');- console.log(' --iterations <n> - Number of training iterations');- console.log(' --validate - Enable validation');+ console.log(' --complexity <level> - easy/medium/hard');+ console.log(' --iterations <n> - Training cycles');}}-export default TrainingPipeline;\ No newline at end of file+export default RealTrainingPipeline;\ No newline at end of file