@stackmemoryai/stackmemory 0.3.25 → 0.3.26

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.
@@ -268,7 +268,7 @@ ${contextResponse.context}`;
268
268
  console.log("\u{1F50D} Starting enhanced debugging...");
269
269
  await ralphDebugger.initialize();
270
270
  const loopId = options.loopId || "current";
271
- const debugSession = await ralphDebugger.startDebugSession(loopId, ".ralph");
271
+ await ralphDebugger.startDebugSession(loopId, ".ralph");
272
272
  if (options.generateReport) {
273
273
  const report = await ralphDebugger.generateDebugReport(loopId);
274
274
  console.log(`\u{1F4CB} Debug report generated: ${report.exportPath}`);
@@ -284,6 +284,158 @@ ${contextResponse.context}`;
284
284
  }
285
285
  });
286
286
  });
287
+ ralph.command("swarm-test").description("Comprehensive testing and validation for swarm functionality").option("--quick", "Run quick validation tests only").option("--stress", "Run stress tests with multiple parallel swarms").option("--error-injection", "Test error handling with deliberate failures").option("--cleanup-test", "Test cleanup mechanisms").option("--git-test", "Test git workflow integration").option("--report", "Generate detailed test report").action(async (options) => {
288
+ return trace.command("ralph-swarm-test", options, async () => {
289
+ try {
290
+ console.log("\u{1F9EA} Starting swarm testing and validation...");
291
+ await swarmCoordinator.initialize();
292
+ const testResults = [];
293
+ let passedTests = 0;
294
+ let totalTests = 0;
295
+ if (options.quick || !options.stress) {
296
+ console.log("\n\u26A1 Running quick validation tests...");
297
+ totalTests++;
298
+ try {
299
+ await swarmCoordinator.launchSwarm(
300
+ "Test: Basic functionality validation",
301
+ [{ role: "developer" }]
302
+ );
303
+ await swarmCoordinator.forceCleanup();
304
+ console.log(" \u2705 Basic swarm initialization");
305
+ passedTests++;
306
+ testResults.push({ test: "basic_init", status: "passed", duration: 0 });
307
+ } catch (error) {
308
+ console.log(" \u274C Basic swarm initialization failed:", error.message);
309
+ testResults.push({ test: "basic_init", status: "failed", error: error.message });
310
+ }
311
+ totalTests++;
312
+ try {
313
+ const usage = swarmCoordinator.getResourceUsage();
314
+ console.log(` \u2705 Resource monitoring: ${usage.activeAgents} agents, ${usage.memoryEstimate}MB`);
315
+ passedTests++;
316
+ testResults.push({ test: "resource_monitoring", status: "passed", data: usage });
317
+ } catch (error) {
318
+ console.log(" \u274C Resource monitoring failed:", error.message);
319
+ testResults.push({ test: "resource_monitoring", status: "failed", error: error.message });
320
+ }
321
+ }
322
+ if (options.stress) {
323
+ console.log("\n\u{1F525} Running stress tests...");
324
+ totalTests++;
325
+ try {
326
+ const stressPromises = [];
327
+ for (let i = 0; i < 3; i++) {
328
+ stressPromises.push(
329
+ swarmCoordinator.launchSwarm(
330
+ `Stress test swarm ${i}`,
331
+ [{ role: "developer" }, { role: "tester" }]
332
+ )
333
+ );
334
+ }
335
+ await Promise.all(stressPromises);
336
+ await swarmCoordinator.forceCleanup();
337
+ console.log(" \u2705 Parallel swarm stress test");
338
+ passedTests++;
339
+ testResults.push({ test: "stress_parallel", status: "passed" });
340
+ } catch (error) {
341
+ console.log(" \u274C Stress test failed:", error.message);
342
+ testResults.push({ test: "stress_parallel", status: "failed", error: error.message });
343
+ }
344
+ }
345
+ if (options.errorInjection) {
346
+ console.log("\n\u{1F4A5} Testing error handling...");
347
+ totalTests++;
348
+ try {
349
+ try {
350
+ await swarmCoordinator.launchSwarm(
351
+ "Error test: Invalid agents",
352
+ []
353
+ // Empty agents array
354
+ );
355
+ } catch {
356
+ console.log(" \u2705 Properly handled empty agents array");
357
+ passedTests++;
358
+ testResults.push({ test: "error_handling", status: "passed" });
359
+ }
360
+ } catch (error) {
361
+ console.log(" \u274C Error handling test failed:", error.message);
362
+ testResults.push({ test: "error_handling", status: "failed", error: error.message });
363
+ }
364
+ }
365
+ if (options.cleanupTest) {
366
+ console.log("\n\u{1F9F9} Testing cleanup mechanisms...");
367
+ totalTests++;
368
+ try {
369
+ await swarmCoordinator.launchSwarm(
370
+ "Cleanup test swarm",
371
+ [{ role: "developer" }]
372
+ );
373
+ await swarmCoordinator.forceCleanup();
374
+ const usage = swarmCoordinator.getResourceUsage();
375
+ if (usage.activeAgents === 0) {
376
+ console.log(" \u2705 Cleanup mechanism works correctly");
377
+ passedTests++;
378
+ testResults.push({ test: "cleanup", status: "passed" });
379
+ } else {
380
+ throw new Error(`Cleanup failed: ${usage.activeAgents} agents still active`);
381
+ }
382
+ } catch (error) {
383
+ console.log(" \u274C Cleanup test failed:", error.message);
384
+ testResults.push({ test: "cleanup", status: "failed", error: error.message });
385
+ }
386
+ }
387
+ if (options.gitTest) {
388
+ console.log("\n\u{1F500} Testing git workflow integration...");
389
+ totalTests++;
390
+ try {
391
+ const gitStatus = swarmCoordinator["gitWorkflowManager"].getGitStatus();
392
+ console.log(` \u2705 Git workflow status: ${gitStatus.enabled ? "enabled" : "disabled"}`);
393
+ passedTests++;
394
+ testResults.push({ test: "git_workflow", status: "passed", data: gitStatus });
395
+ } catch (error) {
396
+ console.log(" \u274C Git workflow test failed:", error.message);
397
+ testResults.push({ test: "git_workflow", status: "failed", error: error.message });
398
+ }
399
+ }
400
+ console.log("\n\u{1F4CA} Test Results Summary:");
401
+ console.log(` Total tests: ${totalTests}`);
402
+ console.log(` Passed: ${passedTests} \u2705`);
403
+ console.log(` Failed: ${totalTests - passedTests} \u274C`);
404
+ console.log(` Success rate: ${Math.round(passedTests / totalTests * 100)}%`);
405
+ if (options.report) {
406
+ const reportPath = ".swarm/test-report.json";
407
+ const fs = await import("fs");
408
+ const reportData = {
409
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
410
+ summary: {
411
+ totalTests,
412
+ passedTests,
413
+ failedTests: totalTests - passedTests,
414
+ successRate: passedTests / totalTests * 100
415
+ },
416
+ testResults,
417
+ systemInfo: {
418
+ nodeVersion: process.version,
419
+ platform: process.platform,
420
+ arch: process.arch
421
+ }
422
+ };
423
+ fs.writeFileSync(reportPath, JSON.stringify(reportData, null, 2));
424
+ console.log(`\u{1F4CB} Detailed report saved to: ${reportPath}`);
425
+ }
426
+ if (passedTests === totalTests) {
427
+ console.log("\n\u{1F389} All tests passed! Swarm functionality is working correctly.");
428
+ } else {
429
+ console.log("\n\u26A0\uFE0F Some tests failed. Check the errors above for details.");
430
+ process.exit(1);
431
+ }
432
+ } catch (error) {
433
+ logger.error("Swarm testing failed", error);
434
+ console.error("\u274C Test suite failed:", error.message);
435
+ process.exit(1);
436
+ }
437
+ });
438
+ });
287
439
  return ralph;
288
440
  }
289
441
  var ralph_default = createRalphCommand;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/cli/commands/ralph.ts"],
4
- "sourcesContent": ["/**\n * Ralph Wiggum Loop Commands\n * CLI interface for Ralph-StackMemory integration\n */\n\nimport { Command } from 'commander';\nimport { logger } from '../../core/monitoring/logger.js';\nimport { RalphLoop } from '../../../scripts/ralph-loop-implementation.js';\nimport { stackMemoryContextLoader } from '../../integrations/ralph/context/stackmemory-context-loader.js';\nimport { patternLearner } from '../../integrations/ralph/learning/pattern-learner.js';\nimport { multiLoopOrchestrator } from '../../integrations/ralph/orchestration/multi-loop-orchestrator.js';\nimport { swarmCoordinator } from '../../integrations/ralph/swarm/swarm-coordinator.js';\nimport { ralphDebugger } from '../../integrations/ralph/visualization/ralph-debugger.js';\nimport { existsSync, readFileSync, writeFileSync } from 'fs';\nimport { trace } from '../../core/trace/index.js';\n\nexport function createRalphCommand(): Command {\n const ralph = new Command('ralph')\n .description('Ralph Wiggum Loop integration with StackMemory');\n\n // Initialize a new Ralph loop\n ralph\n .command('init')\n .description('Initialize a new Ralph Wiggum loop')\n .argument('<task>', 'Task description')\n .option('-c, --criteria <criteria>', 'Completion criteria (comma separated)')\n .option('--max-iterations <n>', 'Maximum iterations', '50')\n .option('--use-context', 'Load relevant context from StackMemory')\n .option('--learn-from-similar', 'Apply patterns from similar completed tasks')\n .action(async (task, options) => {\n return trace.command('ralph-init', { task, ...options }, async () => {\n try {\n console.log('\uD83C\uDFAD Initializing Ralph Wiggum loop...');\n \n // Use basic Ralph loop for now (StackMemory integration requires DB setup)\n const loop = new RalphLoop({\n baseDir: '.ralph',\n maxIterations: parseInt(options.maxIterations),\n verbose: true\n });\n\n // Parse criteria\n const criteria = options.criteria \n ? options.criteria.split(',').map((c: string) => `- ${c.trim()}`).join('\\n')\n : '- All tests pass\\n- Code works correctly\\n- No lint errors';\n\n // Load StackMemory context if requested\n let enhancedTask = task;\n \n if (options.useContext || options.learnFromSimilar) {\n try {\n await stackMemoryContextLoader.initialize();\n \n const contextResponse = await stackMemoryContextLoader.loadInitialContext({\n task,\n usePatterns: true,\n useSimilarTasks: options.learnFromSimilar,\n maxTokens: 3000\n });\n \n if (contextResponse.context) {\n enhancedTask = `${task}\\n\\n${contextResponse.context}`;\n console.log(`\uD83D\uDCDA Loaded context from ${contextResponse.sources.length} sources`);\n console.log(`\uD83C\uDFAF Context tokens: ${contextResponse.metadata.totalTokens}`);\n }\n } catch (error: unknown) {\n console.log(`\u26A0\uFE0F Context loading failed: ${(error as Error).message}`);\n console.log('Proceeding without context...');\n }\n }\n\n await loop.initialize(enhancedTask, criteria);\n \n console.log('\u2705 Ralph loop initialized!');\n console.log(`\uD83D\uDCCB Task: ${task}`);\n console.log(`\uD83C\uDFAF Max iterations: ${options.maxIterations}`);\n console.log(`\uD83D\uDCC1 Loop directory: .ralph/`);\n console.log('\\nNext steps:');\n console.log(' stackmemory ralph run # Start the loop');\n console.log(' stackmemory ralph status # Check status');\n\n } catch (error: unknown) {\n logger.error('Failed to initialize Ralph loop', error as Error);\n console.error('\u274C Initialization failed:', (error as Error).message);\n process.exit(1);\n }\n });\n });\n\n // Run the Ralph loop\n ralph\n .command('run')\n .description('Run the Ralph Wiggum loop')\n .option('--verbose', 'Verbose output')\n .option('--pause-on-error', 'Pause on validation errors')\n .action(async (options) => {\n return trace.command('ralph-run', options, async () => {\n try {\n if (!existsSync('.ralph')) {\n console.error('\u274C No Ralph loop found. Run \"stackmemory ralph init\" first.');\n return;\n }\n\n console.log('\uD83C\uDFAD Starting Ralph Wiggum loop...');\n \n const loop = new RalphLoop({\n baseDir: '.ralph',\n verbose: options.verbose\n });\n\n await loop.run();\n \n } catch (error: unknown) {\n logger.error('Failed to run Ralph loop', error as Error);\n console.error('\u274C Loop execution failed:', (error as Error).message);\n process.exit(1);\n }\n });\n });\n\n // Show loop status\n ralph\n .command('status')\n .description('Show current Ralph loop status')\n .option('--detailed', 'Show detailed iteration history')\n .action(async (options) => {\n return trace.command('ralph-status', options, async () => {\n try {\n if (!existsSync('.ralph')) {\n console.log('\u274C No Ralph loop found in current directory');\n return;\n }\n\n // Get basic status from files\n \n // Read status from files\n const task = readFileSync('.ralph/task.md', 'utf8');\n const iteration = parseInt(readFileSync('.ralph/iteration.txt', 'utf8') || '0');\n const isComplete = existsSync('.ralph/work-complete.txt');\n const feedback = existsSync('.ralph/feedback.txt') ? readFileSync('.ralph/feedback.txt', 'utf8') : '';\n \n console.log('\uD83C\uDFAD Ralph Loop Status:');\n console.log(` Task: ${task.substring(0, 80)}...`);\n console.log(` Iteration: ${iteration}`);\n console.log(` Status: ${isComplete ? '\u2705 COMPLETE' : '\uD83D\uDD04 IN PROGRESS'}`);\n \n if (feedback) {\n console.log(` Last feedback: ${feedback.substring(0, 100)}...`);\n }\n\n if (options.detailed && existsSync('.ralph/progress.jsonl')) {\n console.log('\\n\uD83D\uDCCA Iteration History:');\n const progressLines = readFileSync('.ralph/progress.jsonl', 'utf8')\n .split('\\n')\n .filter(Boolean)\n .map(line => JSON.parse(line));\n \n progressLines.forEach((p: any) => {\n const progress = p as { iteration: number; validation?: { testsPass: boolean }; changes: number; errors: number };\n const status = progress.validation?.testsPass ? '\u2705' : '\u274C';\n console.log(` ${progress.iteration}: ${status} ${progress.changes} changes, ${progress.errors} errors`);\n });\n }\n\n // TODO: Show StackMemory integration status when available\n\n } catch (error: unknown) {\n logger.error('Failed to get Ralph status', error as Error);\n console.error('\u274C Status check failed:', (error as Error).message);\n }\n });\n });\n\n // Resume a crashed or paused loop\n ralph\n .command('resume')\n .description('Resume a crashed or paused Ralph loop')\n .option('--from-stackmemory', 'Restore from StackMemory backup')\n .action(async (options) => {\n return trace.command('ralph-resume', options, async () => {\n try {\n console.log('\uD83D\uDD04 Resuming Ralph loop...');\n \n const loop = new RalphLoop({ baseDir: '.ralph', verbose: true });\n \n if (options.fromStackmemory) {\n console.log('\uD83D\uDCDA StackMemory restore feature coming soon...');\n }\n\n await loop.run(); // Resume by continuing the loop\n \n } catch (error: unknown) {\n logger.error('Failed to resume Ralph loop', error as Error);\n console.error('\u274C Resume failed:', (error as Error).message);\n process.exit(1);\n }\n });\n });\n\n // Stop the current loop\n ralph\n .command('stop')\n .description('Stop the current Ralph loop')\n .option('--save-progress', 'Save current progress to StackMemory')\n .action(async (options) => {\n return trace.command('ralph-stop', options, async () => {\n try {\n if (!existsSync('.ralph')) {\n console.log('\u274C No active Ralph loop found');\n return;\n }\n\n console.log('\uD83D\uDED1 Stopping Ralph loop...');\n \n if (options.saveProgress) {\n console.log('\uD83D\uDCBE StackMemory progress save feature coming soon...');\n }\n\n // Create stop signal file\n writeFileSync('.ralph/stop-signal.txt', new Date().toISOString());\n console.log('\u2705 Stop signal sent');\n \n } catch (error: unknown) {\n logger.error('Failed to stop Ralph loop', error as Error);\n console.error('\u274C Stop failed:', (error as Error).message);\n }\n });\n });\n\n // Clean up loop artifacts\n ralph\n .command('clean')\n .description('Clean up Ralph loop artifacts')\n .option('--keep-history', 'Keep iteration history')\n .action(async (options) => {\n return trace.command('ralph-clean', options, async () => {\n try {\n // Clean up Ralph directory\n if (!options.keepHistory && existsSync('.ralph/history')) {\n const { execSync } = await import('child_process');\n execSync('rm -rf .ralph/history');\n }\n \n // Remove working files but keep task definition\n if (existsSync('.ralph/work-complete.txt')) {\n const fs = await import('fs');\n fs.unlinkSync('.ralph/work-complete.txt');\n }\n \n console.log('\uD83E\uDDF9 Ralph loop artifacts cleaned');\n \n } catch (error: unknown) {\n logger.error('Failed to clean Ralph artifacts', error as Error);\n console.error('\u274C Cleanup failed:', (error as Error).message);\n }\n });\n });\n\n // Debug and diagnostics\n ralph\n .command('debug')\n .description('Debug Ralph loop state and diagnostics')\n .option('--reconcile', 'Force state reconciliation')\n .option('--validate-context', 'Validate context budget')\n .action(async (options) => {\n return trace.command('ralph-debug', options, async () => {\n try {\n console.log('\uD83D\uDD0D Ralph Loop Debug Information:');\n \n if (options.reconcile) {\n console.log('\uD83D\uDD27 State reconciliation feature coming soon...');\n }\n\n if (options.validateContext) {\n console.log('\uD83D\uDCCA Context validation feature coming soon...');\n }\n\n // Show file structure\n if (existsSync('.ralph')) {\n console.log('\\n\uD83D\uDCC1 Ralph directory structure:');\n const { execSync } = await import('child_process');\n try {\n const tree = execSync('find .ralph -type f | head -20', { encoding: 'utf8' });\n console.log(tree);\n } catch {\n console.log(' (Unable to show directory tree)');\n }\n }\n \n } catch (error: unknown) {\n logger.error('Ralph debug failed', error as Error);\n console.error('\u274C Debug failed:', (error as Error).message);\n }\n });\n });\n\n // Swarm coordination commands\n ralph\n .command('swarm')\n .description('Launch a swarm of specialized agents')\n .argument('<project>', 'Project description')\n .option('--agents <agents>', 'Comma-separated list of agent roles (architect,developer,tester,etc)', 'developer,tester')\n .option('--max-agents <n>', 'Maximum number of agents', '5')\n .action(async (project, options) => {\n return trace.command('ralph-swarm', { project, ...options }, async () => {\n try {\n console.log('\uD83E\uDDBE Launching Ralph swarm...');\n \n await swarmCoordinator.initialize();\n \n const agentRoles = options.agents.split(',').map((r: string) => r.trim());\n const agentSpecs = agentRoles.map((role: string) => ({\n role: role as any,\n conflictResolution: 'defer_to_expertise',\n collaborationPreferences: []\n }));\n \n const swarmId = await swarmCoordinator.launchSwarm(project, agentSpecs);\n \n console.log(`\u2705 Swarm launched with ID: ${swarmId}`);\n console.log(`\uD83D\uDC65 ${agentSpecs.length} agents working on: ${project}`);\n console.log('\\nNext steps:');\n console.log(' stackmemory ralph swarm-status <swarmId> # Check progress');\n console.log(' stackmemory ralph swarm-stop <swarmId> # Stop swarm');\n \n } catch (error: unknown) {\n logger.error('Swarm launch failed', error as Error);\n console.error('\u274C Swarm launch failed:', (error as Error).message);\n }\n });\n });\n\n // Multi-loop orchestration for complex tasks\n ralph\n .command('orchestrate')\n .description('Orchestrate multiple Ralph loops for complex tasks')\n .argument('<description>', 'Complex task description')\n .option('--criteria <criteria>', 'Success criteria (comma separated)')\n .option('--max-loops <n>', 'Maximum parallel loops', '3')\n .option('--sequential', 'Force sequential execution')\n .action(async (description, options) => {\n return trace.command('ralph-orchestrate', { description, ...options }, async () => {\n try {\n console.log('\uD83C\uDFAD Orchestrating complex task...');\n \n await multiLoopOrchestrator.initialize();\n \n const criteria = options.criteria ? \n options.criteria.split(',').map((c: string) => c.trim()) :\n ['Task completed successfully', 'All components working', 'Tests pass'];\n \n const result = await multiLoopOrchestrator.orchestrateComplexTask(\n description,\n criteria,\n {\n maxLoops: parseInt(options.maxLoops),\n forceSequential: options.sequential\n }\n );\n \n console.log('\u2705 Orchestration completed!');\n console.log(`\uD83D\uDCCA Results: ${result.completedLoops.length} successful, ${result.failedLoops.length} failed`);\n console.log(`\u23F1\uFE0F Total duration: ${Math.round(result.totalDuration / 1000)}s`);\n \n if (result.insights.length > 0) {\n console.log('\\n\uD83D\uDCA1 Insights:');\n result.insights.forEach(insight => console.log(` \u2022 ${insight}`));\n }\n \n } catch (error: unknown) {\n logger.error('Orchestration failed', error as Error);\n console.error('\u274C Orchestration failed:', (error as Error).message);\n }\n });\n });\n\n // Pattern learning command\n ralph\n .command('learn')\n .description('Learn patterns from completed loops')\n .option('--task-type <type>', 'Learn patterns for specific task type')\n .action(async (options) => {\n return trace.command('ralph-learn', options, async () => {\n try {\n console.log('\uD83E\uDDE0 Learning patterns from completed loops...');\n \n await patternLearner.initialize();\n \n const patterns = options.taskType ?\n await patternLearner.learnForTaskType(options.taskType) :\n await patternLearner.learnFromCompletedLoops();\n \n console.log(`\u2705 Learned ${patterns.length} patterns`);\n \n if (patterns.length > 0) {\n console.log('\\n\uD83D\uDCCA Top patterns:');\n patterns.slice(0, 5).forEach(pattern => {\n console.log(` \u2022 ${pattern.pattern} (${Math.round(pattern.confidence * 100)}% confidence)`);\n });\n }\n \n } catch (error: unknown) {\n logger.error('Pattern learning failed', error as Error);\n console.error('\u274C Pattern learning failed:', (error as Error).message);\n }\n });\n });\n\n // Enhanced debug command with visualization\n ralph\n .command('debug-enhanced')\n .description('Advanced debugging with visualization')\n .option('--loop-id <id>', 'Specific loop to debug')\n .option('--generate-report', 'Generate comprehensive debug report')\n .option('--timeline', 'Generate timeline visualization')\n .action(async (options) => {\n return trace.command('ralph-debug-enhanced', options, async () => {\n try {\n if (!existsSync('.ralph') && !options.loopId) {\n console.log('\u274C No Ralph loop found. Run a loop first or specify --loop-id');\n return;\n }\n \n console.log('\uD83D\uDD0D Starting enhanced debugging...');\n \n await ralphDebugger.initialize();\n \n const loopId = options.loopId || 'current';\n const debugSession = await ralphDebugger.startDebugSession(loopId, '.ralph');\n \n if (options.generateReport) {\n const report = await ralphDebugger.generateDebugReport(loopId);\n console.log(`\uD83D\uDCCB Debug report generated: ${report.exportPath}`);\n }\n \n if (options.timeline) {\n const timelinePath = await ralphDebugger.generateLoopTimeline(loopId);\n console.log(`\uD83D\uDCCA Timeline visualization: ${timelinePath}`);\n }\n \n console.log('\uD83D\uDD0D Debug analysis complete');\n \n } catch (error: unknown) {\n logger.error('Enhanced debugging failed', error as Error);\n console.error('\u274C Debug failed:', (error as Error).message);\n }\n });\n });\n\n return ralph;\n}\n\nexport default createRalphCommand;"],
5
- "mappings": "AAKA,SAAS,eAAe;AACxB,SAAS,cAAc;AACvB,SAAS,iBAAiB;AAC1B,SAAS,gCAAgC;AACzC,SAAS,sBAAsB;AAC/B,SAAS,6BAA6B;AACtC,SAAS,wBAAwB;AACjC,SAAS,qBAAqB;AAC9B,SAAS,YAAY,cAAc,qBAAqB;AACxD,SAAS,aAAa;AAEf,SAAS,qBAA8B;AAC5C,QAAM,QAAQ,IAAI,QAAQ,OAAO,EAC9B,YAAY,gDAAgD;AAG/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AAQ,gBAAgB,EACxB,YAAY,uCAAuC,EACnD,OAAO,kBAAkB,wBAAwB,EACjD,OAAO,qBAAqB,qCAAqC,EACjE,OAAO,cAAc,iCAAiC,EACtD,OAAO,OAAO,YAAY;AACzB,WAAO,MAAM,QAAQ,wBAAwB,SAAS,YAAY;AAChE,UAAI;AACF,YAAI,CAAC,WAAW,QAAQ,KAAK,CAAC,QAAQ,QAAQ;AAC5C,kBAAQ,IAAI,mEAA8D;AAC1E;AAAA,QACF;AAEA,gBAAQ,IAAI,0CAAmC;AAE/C,cAAM,cAAc,WAAW;AAE/B,cAAM,SAAS,QAAQ,UAAU;AACjC,cAAM,eAAe,MAAM,cAAc,kBAAkB,QAAQ,QAAQ;AAE3E,YAAI,QAAQ,gBAAgB;AAC1B,gBAAM,SAAS,MAAM,cAAc,oBAAoB,MAAM;AAC7D,kBAAQ,IAAI,qCAA8B,OAAO,UAAU,EAAE;AAAA,QAC/D;AAEA,YAAI,QAAQ,UAAU;AACpB,gBAAM,eAAe,MAAM,cAAc,qBAAqB,MAAM;AACpE,kBAAQ,IAAI,qCAA8B,YAAY,EAAE;AAAA,QAC1D;AAEA,gBAAQ,IAAI,mCAA4B;AAAA,MAE1C,SAAS,OAAgB;AACvB,eAAO,MAAM,6BAA6B,KAAc;AACxD,gBAAQ,MAAM,wBAAoB,MAAgB,OAAO;AAAA,MAC3D;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AAEH,SAAO;AACT;AAEA,IAAO,gBAAQ;",
4
+ "sourcesContent": ["/**\n * Ralph Wiggum Loop Commands\n * CLI interface for Ralph-StackMemory integration\n */\n\nimport { Command } from 'commander';\nimport { logger } from '../../core/monitoring/logger.js';\nimport { RalphLoop } from '../../../scripts/ralph-loop-implementation.js';\nimport { stackMemoryContextLoader } from '../../integrations/ralph/context/stackmemory-context-loader.js';\nimport { patternLearner } from '../../integrations/ralph/learning/pattern-learner.js';\nimport { multiLoopOrchestrator } from '../../integrations/ralph/orchestration/multi-loop-orchestrator.js';\nimport { swarmCoordinator } from '../../integrations/ralph/swarm/swarm-coordinator.js';\nimport { ralphDebugger } from '../../integrations/ralph/visualization/ralph-debugger.js';\nimport { existsSync, readFileSync, writeFileSync } from 'fs';\nimport { trace } from '../../core/trace/index.js';\n\nexport function createRalphCommand(): Command {\n const ralph = new Command('ralph')\n .description('Ralph Wiggum Loop integration with StackMemory');\n\n // Initialize a new Ralph loop\n ralph\n .command('init')\n .description('Initialize a new Ralph Wiggum loop')\n .argument('<task>', 'Task description')\n .option('-c, --criteria <criteria>', 'Completion criteria (comma separated)')\n .option('--max-iterations <n>', 'Maximum iterations', '50')\n .option('--use-context', 'Load relevant context from StackMemory')\n .option('--learn-from-similar', 'Apply patterns from similar completed tasks')\n .action(async (task, options) => {\n return trace.command('ralph-init', { task, ...options }, async () => {\n try {\n console.log('\uD83C\uDFAD Initializing Ralph Wiggum loop...');\n \n // Use basic Ralph loop for now (StackMemory integration requires DB setup)\n const loop = new RalphLoop({\n baseDir: '.ralph',\n maxIterations: parseInt(options.maxIterations),\n verbose: true\n });\n\n // Parse criteria\n const criteria = options.criteria \n ? options.criteria.split(',').map((c: string) => `- ${c.trim()}`).join('\\n')\n : '- All tests pass\\n- Code works correctly\\n- No lint errors';\n\n // Load StackMemory context if requested\n let enhancedTask = task;\n \n if (options.useContext || options.learnFromSimilar) {\n try {\n await stackMemoryContextLoader.initialize();\n \n const contextResponse = await stackMemoryContextLoader.loadInitialContext({\n task,\n usePatterns: true,\n useSimilarTasks: options.learnFromSimilar,\n maxTokens: 3000\n });\n \n if (contextResponse.context) {\n enhancedTask = `${task}\\n\\n${contextResponse.context}`;\n console.log(`\uD83D\uDCDA Loaded context from ${contextResponse.sources.length} sources`);\n console.log(`\uD83C\uDFAF Context tokens: ${contextResponse.metadata.totalTokens}`);\n }\n } catch (error: unknown) {\n console.log(`\u26A0\uFE0F Context loading failed: ${(error as Error).message}`);\n console.log('Proceeding without context...');\n }\n }\n\n await loop.initialize(enhancedTask, criteria);\n \n console.log('\u2705 Ralph loop initialized!');\n console.log(`\uD83D\uDCCB Task: ${task}`);\n console.log(`\uD83C\uDFAF Max iterations: ${options.maxIterations}`);\n console.log(`\uD83D\uDCC1 Loop directory: .ralph/`);\n console.log('\\nNext steps:');\n console.log(' stackmemory ralph run # Start the loop');\n console.log(' stackmemory ralph status # Check status');\n\n } catch (error: unknown) {\n logger.error('Failed to initialize Ralph loop', error as Error);\n console.error('\u274C Initialization failed:', (error as Error).message);\n process.exit(1);\n }\n });\n });\n\n // Run the Ralph loop\n ralph\n .command('run')\n .description('Run the Ralph Wiggum loop')\n .option('--verbose', 'Verbose output')\n .option('--pause-on-error', 'Pause on validation errors')\n .action(async (options) => {\n return trace.command('ralph-run', options, async () => {\n try {\n if (!existsSync('.ralph')) {\n console.error('\u274C No Ralph loop found. Run \"stackmemory ralph init\" first.');\n return;\n }\n\n console.log('\uD83C\uDFAD Starting Ralph Wiggum loop...');\n \n const loop = new RalphLoop({\n baseDir: '.ralph',\n verbose: options.verbose\n });\n\n await loop.run();\n \n } catch (error: unknown) {\n logger.error('Failed to run Ralph loop', error as Error);\n console.error('\u274C Loop execution failed:', (error as Error).message);\n process.exit(1);\n }\n });\n });\n\n // Show loop status\n ralph\n .command('status')\n .description('Show current Ralph loop status')\n .option('--detailed', 'Show detailed iteration history')\n .action(async (options) => {\n return trace.command('ralph-status', options, async () => {\n try {\n if (!existsSync('.ralph')) {\n console.log('\u274C No Ralph loop found in current directory');\n return;\n }\n\n // Get basic status from files\n \n // Read status from files\n const task = readFileSync('.ralph/task.md', 'utf8');\n const iteration = parseInt(readFileSync('.ralph/iteration.txt', 'utf8') || '0');\n const isComplete = existsSync('.ralph/work-complete.txt');\n const feedback = existsSync('.ralph/feedback.txt') ? readFileSync('.ralph/feedback.txt', 'utf8') : '';\n \n console.log('\uD83C\uDFAD Ralph Loop Status:');\n console.log(` Task: ${task.substring(0, 80)}...`);\n console.log(` Iteration: ${iteration}`);\n console.log(` Status: ${isComplete ? '\u2705 COMPLETE' : '\uD83D\uDD04 IN PROGRESS'}`);\n \n if (feedback) {\n console.log(` Last feedback: ${feedback.substring(0, 100)}...`);\n }\n\n if (options.detailed && existsSync('.ralph/progress.jsonl')) {\n console.log('\\n\uD83D\uDCCA Iteration History:');\n const progressLines = readFileSync('.ralph/progress.jsonl', 'utf8')\n .split('\\n')\n .filter(Boolean)\n .map(line => JSON.parse(line));\n \n progressLines.forEach((p: any) => {\n const progress = p as { iteration: number; validation?: { testsPass: boolean }; changes: number; errors: number };\n const status = progress.validation?.testsPass ? '\u2705' : '\u274C';\n console.log(` ${progress.iteration}: ${status} ${progress.changes} changes, ${progress.errors} errors`);\n });\n }\n\n // TODO: Show StackMemory integration status when available\n\n } catch (error: unknown) {\n logger.error('Failed to get Ralph status', error as Error);\n console.error('\u274C Status check failed:', (error as Error).message);\n }\n });\n });\n\n // Resume a crashed or paused loop\n ralph\n .command('resume')\n .description('Resume a crashed or paused Ralph loop')\n .option('--from-stackmemory', 'Restore from StackMemory backup')\n .action(async (options) => {\n return trace.command('ralph-resume', options, async () => {\n try {\n console.log('\uD83D\uDD04 Resuming Ralph loop...');\n \n const loop = new RalphLoop({ baseDir: '.ralph', verbose: true });\n \n if (options.fromStackmemory) {\n console.log('\uD83D\uDCDA StackMemory restore feature coming soon...');\n }\n\n await loop.run(); // Resume by continuing the loop\n \n } catch (error: unknown) {\n logger.error('Failed to resume Ralph loop', error as Error);\n console.error('\u274C Resume failed:', (error as Error).message);\n process.exit(1);\n }\n });\n });\n\n // Stop the current loop\n ralph\n .command('stop')\n .description('Stop the current Ralph loop')\n .option('--save-progress', 'Save current progress to StackMemory')\n .action(async (options) => {\n return trace.command('ralph-stop', options, async () => {\n try {\n if (!existsSync('.ralph')) {\n console.log('\u274C No active Ralph loop found');\n return;\n }\n\n console.log('\uD83D\uDED1 Stopping Ralph loop...');\n \n if (options.saveProgress) {\n console.log('\uD83D\uDCBE StackMemory progress save feature coming soon...');\n }\n\n // Create stop signal file\n writeFileSync('.ralph/stop-signal.txt', new Date().toISOString());\n console.log('\u2705 Stop signal sent');\n \n } catch (error: unknown) {\n logger.error('Failed to stop Ralph loop', error as Error);\n console.error('\u274C Stop failed:', (error as Error).message);\n }\n });\n });\n\n // Clean up loop artifacts\n ralph\n .command('clean')\n .description('Clean up Ralph loop artifacts')\n .option('--keep-history', 'Keep iteration history')\n .action(async (options) => {\n return trace.command('ralph-clean', options, async () => {\n try {\n // Clean up Ralph directory\n if (!options.keepHistory && existsSync('.ralph/history')) {\n const { execSync } = await import('child_process');\n execSync('rm -rf .ralph/history');\n }\n \n // Remove working files but keep task definition\n if (existsSync('.ralph/work-complete.txt')) {\n const fs = await import('fs');\n fs.unlinkSync('.ralph/work-complete.txt');\n }\n \n console.log('\uD83E\uDDF9 Ralph loop artifacts cleaned');\n \n } catch (error: unknown) {\n logger.error('Failed to clean Ralph artifacts', error as Error);\n console.error('\u274C Cleanup failed:', (error as Error).message);\n }\n });\n });\n\n // Debug and diagnostics\n ralph\n .command('debug')\n .description('Debug Ralph loop state and diagnostics')\n .option('--reconcile', 'Force state reconciliation')\n .option('--validate-context', 'Validate context budget')\n .action(async (options) => {\n return trace.command('ralph-debug', options, async () => {\n try {\n console.log('\uD83D\uDD0D Ralph Loop Debug Information:');\n \n if (options.reconcile) {\n console.log('\uD83D\uDD27 State reconciliation feature coming soon...');\n }\n\n if (options.validateContext) {\n console.log('\uD83D\uDCCA Context validation feature coming soon...');\n }\n\n // Show file structure\n if (existsSync('.ralph')) {\n console.log('\\n\uD83D\uDCC1 Ralph directory structure:');\n const { execSync } = await import('child_process');\n try {\n const tree = execSync('find .ralph -type f | head -20', { encoding: 'utf8' });\n console.log(tree);\n } catch {\n console.log(' (Unable to show directory tree)');\n }\n }\n \n } catch (error: unknown) {\n logger.error('Ralph debug failed', error as Error);\n console.error('\u274C Debug failed:', (error as Error).message);\n }\n });\n });\n\n // Swarm coordination commands\n ralph\n .command('swarm')\n .description('Launch a swarm of specialized agents')\n .argument('<project>', 'Project description')\n .option('--agents <agents>', 'Comma-separated list of agent roles (architect,developer,tester,etc)', 'developer,tester')\n .option('--max-agents <n>', 'Maximum number of agents', '5')\n .action(async (project, options) => {\n return trace.command('ralph-swarm', { project, ...options }, async () => {\n try {\n console.log('\uD83E\uDDBE Launching Ralph swarm...');\n \n await swarmCoordinator.initialize();\n \n const agentRoles = options.agents.split(',').map((r: string) => r.trim());\n const agentSpecs = agentRoles.map((role: string) => ({\n role: role as any,\n conflictResolution: 'defer_to_expertise',\n collaborationPreferences: []\n }));\n \n const swarmId = await swarmCoordinator.launchSwarm(project, agentSpecs);\n \n console.log(`\u2705 Swarm launched with ID: ${swarmId}`);\n console.log(`\uD83D\uDC65 ${agentSpecs.length} agents working on: ${project}`);\n console.log('\\nNext steps:');\n console.log(' stackmemory ralph swarm-status <swarmId> # Check progress');\n console.log(' stackmemory ralph swarm-stop <swarmId> # Stop swarm');\n \n } catch (error: unknown) {\n logger.error('Swarm launch failed', error as Error);\n console.error('\u274C Swarm launch failed:', (error as Error).message);\n }\n });\n });\n\n // Multi-loop orchestration for complex tasks\n ralph\n .command('orchestrate')\n .description('Orchestrate multiple Ralph loops for complex tasks')\n .argument('<description>', 'Complex task description')\n .option('--criteria <criteria>', 'Success criteria (comma separated)')\n .option('--max-loops <n>', 'Maximum parallel loops', '3')\n .option('--sequential', 'Force sequential execution')\n .action(async (description, options) => {\n return trace.command('ralph-orchestrate', { description, ...options }, async () => {\n try {\n console.log('\uD83C\uDFAD Orchestrating complex task...');\n \n await multiLoopOrchestrator.initialize();\n \n const criteria = options.criteria ? \n options.criteria.split(',').map((c: string) => c.trim()) :\n ['Task completed successfully', 'All components working', 'Tests pass'];\n \n const result = await multiLoopOrchestrator.orchestrateComplexTask(\n description,\n criteria,\n {\n maxLoops: parseInt(options.maxLoops),\n forceSequential: options.sequential\n }\n );\n \n console.log('\u2705 Orchestration completed!');\n console.log(`\uD83D\uDCCA Results: ${result.completedLoops.length} successful, ${result.failedLoops.length} failed`);\n console.log(`\u23F1\uFE0F Total duration: ${Math.round(result.totalDuration / 1000)}s`);\n \n if (result.insights.length > 0) {\n console.log('\\n\uD83D\uDCA1 Insights:');\n result.insights.forEach(insight => console.log(` \u2022 ${insight}`));\n }\n \n } catch (error: unknown) {\n logger.error('Orchestration failed', error as Error);\n console.error('\u274C Orchestration failed:', (error as Error).message);\n }\n });\n });\n\n // Pattern learning command\n ralph\n .command('learn')\n .description('Learn patterns from completed loops')\n .option('--task-type <type>', 'Learn patterns for specific task type')\n .action(async (options) => {\n return trace.command('ralph-learn', options, async () => {\n try {\n console.log('\uD83E\uDDE0 Learning patterns from completed loops...');\n \n await patternLearner.initialize();\n \n const patterns = options.taskType ?\n await patternLearner.learnForTaskType(options.taskType) :\n await patternLearner.learnFromCompletedLoops();\n \n console.log(`\u2705 Learned ${patterns.length} patterns`);\n \n if (patterns.length > 0) {\n console.log('\\n\uD83D\uDCCA Top patterns:');\n patterns.slice(0, 5).forEach(pattern => {\n console.log(` \u2022 ${pattern.pattern} (${Math.round(pattern.confidence * 100)}% confidence)`);\n });\n }\n \n } catch (error: unknown) {\n logger.error('Pattern learning failed', error as Error);\n console.error('\u274C Pattern learning failed:', (error as Error).message);\n }\n });\n });\n\n // Enhanced debug command with visualization\n ralph\n .command('debug-enhanced')\n .description('Advanced debugging with visualization')\n .option('--loop-id <id>', 'Specific loop to debug')\n .option('--generate-report', 'Generate comprehensive debug report')\n .option('--timeline', 'Generate timeline visualization')\n .action(async (options) => {\n return trace.command('ralph-debug-enhanced', options, async () => {\n try {\n if (!existsSync('.ralph') && !options.loopId) {\n console.log('\u274C No Ralph loop found. Run a loop first or specify --loop-id');\n return;\n }\n \n console.log('\uD83D\uDD0D Starting enhanced debugging...');\n \n await ralphDebugger.initialize();\n \n const loopId = options.loopId || 'current';\n await ralphDebugger.startDebugSession(loopId, '.ralph');\n \n if (options.generateReport) {\n const report = await ralphDebugger.generateDebugReport(loopId);\n console.log(`\uD83D\uDCCB Debug report generated: ${report.exportPath}`);\n }\n \n if (options.timeline) {\n const timelinePath = await ralphDebugger.generateLoopTimeline(loopId);\n console.log(`\uD83D\uDCCA Timeline visualization: ${timelinePath}`);\n }\n \n console.log('\uD83D\uDD0D Debug analysis complete');\n \n } catch (error: unknown) {\n logger.error('Enhanced debugging failed', error as Error);\n console.error('\u274C Debug failed:', (error as Error).message);\n }\n });\n });\n\n // Swarm testing and validation command\n ralph\n .command('swarm-test')\n .description('Comprehensive testing and validation for swarm functionality')\n .option('--quick', 'Run quick validation tests only')\n .option('--stress', 'Run stress tests with multiple parallel swarms')\n .option('--error-injection', 'Test error handling with deliberate failures')\n .option('--cleanup-test', 'Test cleanup mechanisms')\n .option('--git-test', 'Test git workflow integration')\n .option('--report', 'Generate detailed test report')\n .action(async (options) => {\n return trace.command('ralph-swarm-test', options, async () => {\n try {\n console.log('\uD83E\uDDEA Starting swarm testing and validation...');\n \n await swarmCoordinator.initialize();\n \n const testResults: any[] = [];\n let passedTests = 0;\n let totalTests = 0;\n\n // Quick validation tests\n if (options.quick || !options.stress) {\n console.log('\\n\u26A1 Running quick validation tests...');\n \n // Test 1: Basic swarm initialization\n totalTests++;\n try {\n await swarmCoordinator.launchSwarm(\n 'Test: Basic functionality validation',\n [{ role: 'developer' as any }]\n );\n \n // Immediately cleanup\n await swarmCoordinator.forceCleanup();\n \n console.log(' \u2705 Basic swarm initialization');\n passedTests++;\n testResults.push({ test: 'basic_init', status: 'passed', duration: 0 });\n } catch (error) {\n console.log(' \u274C Basic swarm initialization failed:', (error as Error).message);\n testResults.push({ test: 'basic_init', status: 'failed', error: (error as Error).message });\n }\n\n // Test 2: Resource usage monitoring\n totalTests++;\n try {\n const usage = swarmCoordinator.getResourceUsage();\n console.log(` \u2705 Resource monitoring: ${usage.activeAgents} agents, ${usage.memoryEstimate}MB`);\n passedTests++;\n testResults.push({ test: 'resource_monitoring', status: 'passed', data: usage });\n } catch (error) {\n console.log(' \u274C Resource monitoring failed:', (error as Error).message);\n testResults.push({ test: 'resource_monitoring', status: 'failed', error: (error as Error).message });\n }\n }\n\n // Stress tests\n if (options.stress) {\n console.log('\\n\uD83D\uDD25 Running stress tests...');\n \n totalTests++;\n try {\n const stressPromises = [];\n for (let i = 0; i < 3; i++) {\n stressPromises.push(\n swarmCoordinator.launchSwarm(\n `Stress test swarm ${i}`,\n [{ role: 'developer' as any }, { role: 'tester' as any }]\n )\n );\n }\n \n await Promise.all(stressPromises);\n await swarmCoordinator.forceCleanup();\n \n console.log(' \u2705 Parallel swarm stress test');\n passedTests++;\n testResults.push({ test: 'stress_parallel', status: 'passed' });\n } catch (error) {\n console.log(' \u274C Stress test failed:', (error as Error).message);\n testResults.push({ test: 'stress_parallel', status: 'failed', error: (error as Error).message });\n }\n }\n\n // Error injection tests\n if (options.errorInjection) {\n console.log('\\n\uD83D\uDCA5 Testing error handling...');\n \n totalTests++;\n try {\n // Test with invalid agent configuration\n try {\n await swarmCoordinator.launchSwarm(\n 'Error test: Invalid agents',\n [] // Empty agents array\n );\n } catch {\n console.log(' \u2705 Properly handled empty agents array');\n passedTests++;\n testResults.push({ test: 'error_handling', status: 'passed' });\n }\n } catch (error) {\n console.log(' \u274C Error handling test failed:', (error as Error).message);\n testResults.push({ test: 'error_handling', status: 'failed', error: (error as Error).message });\n }\n }\n\n // Cleanup tests\n if (options.cleanupTest) {\n console.log('\\n\uD83E\uDDF9 Testing cleanup mechanisms...');\n \n totalTests++;\n try {\n // Create a swarm and test cleanup\n await swarmCoordinator.launchSwarm(\n 'Cleanup test swarm',\n [{ role: 'developer' as any }]\n );\n \n // Force cleanup\n await swarmCoordinator.forceCleanup();\n \n // Check if resources were cleaned\n const usage = swarmCoordinator.getResourceUsage();\n if (usage.activeAgents === 0) {\n console.log(' \u2705 Cleanup mechanism works correctly');\n passedTests++;\n testResults.push({ test: 'cleanup', status: 'passed' });\n } else {\n throw new Error(`Cleanup failed: ${usage.activeAgents} agents still active`);\n }\n } catch (error) {\n console.log(' \u274C Cleanup test failed:', (error as Error).message);\n testResults.push({ test: 'cleanup', status: 'failed', error: (error as Error).message });\n }\n }\n\n // Git workflow tests\n if (options.gitTest) {\n console.log('\\n\uD83D\uDD00 Testing git workflow integration...');\n \n totalTests++;\n try {\n // Test git workflow status\n const gitStatus = swarmCoordinator['gitWorkflowManager'].getGitStatus();\n console.log(` \u2705 Git workflow status: ${gitStatus.enabled ? 'enabled' : 'disabled'}`);\n passedTests++;\n testResults.push({ test: 'git_workflow', status: 'passed', data: gitStatus });\n } catch (error) {\n console.log(' \u274C Git workflow test failed:', (error as Error).message);\n testResults.push({ test: 'git_workflow', status: 'failed', error: (error as Error).message });\n }\n }\n\n // Display results\n console.log('\\n\uD83D\uDCCA Test Results Summary:');\n console.log(` Total tests: ${totalTests}`);\n console.log(` Passed: ${passedTests} \u2705`);\n console.log(` Failed: ${totalTests - passedTests} \u274C`);\n console.log(` Success rate: ${Math.round((passedTests / totalTests) * 100)}%`);\n\n // Generate report\n if (options.report) {\n const reportPath = '.swarm/test-report.json';\n const fs = await import('fs');\n const reportData = {\n timestamp: new Date().toISOString(),\n summary: {\n totalTests,\n passedTests,\n failedTests: totalTests - passedTests,\n successRate: (passedTests / totalTests) * 100\n },\n testResults,\n systemInfo: {\n nodeVersion: process.version,\n platform: process.platform,\n arch: process.arch\n }\n };\n \n fs.writeFileSync(reportPath, JSON.stringify(reportData, null, 2));\n console.log(`\uD83D\uDCCB Detailed report saved to: ${reportPath}`);\n }\n\n if (passedTests === totalTests) {\n console.log('\\n\uD83C\uDF89 All tests passed! Swarm functionality is working correctly.');\n } else {\n console.log('\\n\u26A0\uFE0F Some tests failed. Check the errors above for details.');\n process.exit(1);\n }\n \n } catch (error: unknown) {\n logger.error('Swarm testing failed', error as Error);\n console.error('\u274C Test suite failed:', (error as Error).message);\n process.exit(1);\n }\n });\n });\n\n return ralph;\n}\n\nexport default createRalphCommand;"],
5
+ "mappings": "AAKA,SAAS,eAAe;AACxB,SAAS,cAAc;AACvB,SAAS,iBAAiB;AAC1B,SAAS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AAA,YAC5C;AAAA,YACA;AAAA,YACA,YAAY;AAAA,cACV,aAAa,QAAQ;AAAA,cACrB,UAAU,QAAQ;AAAA,cAClB,MAAM,QAAQ;AAAA,YAChB;AAAA,UACF;AAEA,aAAG,cAAc,YAAY,KAAK,UAAU,YAAY,MAAM,CAAC,CAAC;AAChE,kBAAQ,IAAI,uCAAgC,UAAU,EAAE;AAAA,QAC1D;AAEA,YAAI,gBAAgB,YAAY;AAC9B,kBAAQ,IAAI,yEAAkE;AAAA,QAChF,OAAO;AACL,kBAAQ,IAAI,wEAA8D;AAC1E,kBAAQ,KAAK,CAAC;AAAA,QAChB;AAAA,MAEF,SAAS,OAAgB;AACvB,eAAO,MAAM,wBAAwB,KAAc;AACnD,gBAAQ,MAAM,6BAAyB,MAAgB,OAAO;AAC9D,gBAAQ,KAAK,CAAC;AAAA,MAChB;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AAEH,SAAO;AACT;AAEA,IAAO,gBAAQ;",
6
6
  "names": []
7
7
  }
@@ -5,6 +5,7 @@ import { execSync } from "child_process";
5
5
  import { logger } from "../../../core/monitoring/logger.js";
6
6
  import { FrameManager } from "../../../core/context/frame-manager.js";
7
7
  import { SessionManager } from "../../../core/session/session-manager.js";
8
+ import { SQLiteAdapter } from "../../../core/database/sqlite-adapter.js";
8
9
  import { ContextBudgetManager } from "../context/context-budget-manager.js";
9
10
  import { StateReconciler } from "../state/state-reconciler.js";
10
11
  import { IterationLifecycle } from "../lifecycle/iteration-lifecycle.js";
@@ -45,7 +46,11 @@ class RalphStackMemoryBridge {
45
46
  sessionId: options?.sessionId
46
47
  });
47
48
  this.state.currentSession = session;
48
- this.frameManager = new FrameManager();
49
+ const dbAdapter = await this.getDatabaseAdapter();
50
+ await dbAdapter.connect();
51
+ const db = dbAdapter.db;
52
+ const projectId = path.basename(this.ralphDir);
53
+ this.frameManager = new FrameManager(db, projectId, { skipContextBridge: true });
49
54
  if (options?.loopId) {
50
55
  await this.resumeLoop(options.loopId);
51
56
  } else if (options?.task && options?.criteria) {
@@ -380,7 +385,12 @@ class RalphStackMemoryBridge {
380
385
  status: "started"
381
386
  }
382
387
  };
383
- return await this.frameManager.pushFrame(frame);
388
+ return await this.frameManager.createFrame({
389
+ name: frame.name,
390
+ type: frame.type,
391
+ content: frame.content || "",
392
+ metadata: frame.metadata
393
+ });
384
394
  }
385
395
  /**
386
396
  * Load iteration context from StackMemory
@@ -480,6 +490,14 @@ class RalphStackMemoryBridge {
480
490
  };
481
491
  await this.state.performanceOptimizer.saveFrame(frame);
482
492
  }
493
+ /**
494
+ * Get database adapter for FrameManager
495
+ */
496
+ async getDatabaseAdapter() {
497
+ const dbPath = path.join(this.ralphDir, "stackmemory.db");
498
+ const projectId = path.basename(this.ralphDir);
499
+ return new SQLiteAdapter(projectId, { dbPath });
500
+ }
483
501
  /**
484
502
  * Additional helper methods
485
503
  */
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/integrations/ralph/bridge/ralph-stackmemory-bridge.ts"],
4
- "sourcesContent": ["/**\n * Ralph-StackMemory Bridge\n * Main integration point connecting Ralph Wiggum loops with StackMemory persistence\n */\n\nimport { v4 as uuidv4 } from 'uuid';\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\nimport { execSync } from 'child_process';\nimport { logger } from '../../../core/monitoring/logger.js';\nimport { FrameManager } from '../../../core/context/frame-manager.js';\nimport { SessionManager } from '../../../core/session/session-manager.js';\nimport { ContextBudgetManager } from '../context/context-budget-manager.js';\nimport { StateReconciler } from '../state/state-reconciler.js';\nimport { IterationLifecycle, LifecycleHooks } from '../lifecycle/iteration-lifecycle.js';\nimport { PerformanceOptimizer } from '../performance/performance-optimizer.js';\nimport {\n RalphLoopState,\n RalphIteration,\n BridgeState,\n BridgeOptions,\n RalphStackMemoryConfig,\n IterationContext,\n Frame,\n FrameType,\n RecoveryState,\n Checkpoint,\n StateSource,\n} from '../types.js';\n\nexport class RalphStackMemoryBridge {\n private state: BridgeState;\n private config: RalphStackMemoryConfig;\n private frameManager?: FrameManager;\n private sessionManager: SessionManager;\n private recoveryState?: RecoveryState;\n private readonly ralphDir = '.ralph';\n\n constructor(options?: BridgeOptions) {\n // Initialize configuration\n this.config = this.mergeConfig(options?.config);\n\n // Initialize managers\n this.state = {\n initialized: false,\n contextManager: new ContextBudgetManager(this.config.contextBudget),\n stateReconciler: new StateReconciler(this.config.stateReconciliation),\n performanceOptimizer: new PerformanceOptimizer(this.config.performance),\n };\n\n this.sessionManager = SessionManager.getInstance();\n\n // Setup lifecycle hooks\n this.setupLifecycleHooks(options);\n\n logger.info('Ralph-StackMemory Bridge initialized', {\n config: {\n maxTokens: this.config.contextBudget.maxTokens,\n asyncSaves: this.config.performance.asyncSaves,\n checkpoints: this.config.lifecycle.checkpoints.enabled,\n },\n });\n }\n\n /**\n * Initialize bridge with session\n */\n async initialize(options?: {\n sessionId?: string;\n loopId?: string;\n task?: string;\n criteria?: string;\n }): Promise<void> {\n logger.info('Initializing bridge', options);\n\n try {\n // Initialize session manager\n await this.sessionManager.initialize();\n\n // Get or create session\n const session = await this.sessionManager.getOrCreateSession({\n sessionId: options?.sessionId,\n });\n\n this.state.currentSession = session;\n\n // Initialize frame manager\n this.frameManager = new FrameManager();\n\n // Check for existing loop or create new\n if (options?.loopId) {\n await this.resumeLoop(options.loopId);\n } else if (options?.task && options?.criteria) {\n await this.createNewLoop(options.task, options.criteria);\n } else {\n // Try to recover from crash\n await this.attemptRecovery();\n }\n\n this.state.initialized = true;\n logger.info('Bridge initialized successfully');\n } catch (error: any) {\n logger.error('Bridge initialization failed', { error: error.message });\n throw error;\n }\n }\n\n /**\n * Create new Ralph loop with StackMemory integration\n */\n async createNewLoop(task: string, criteria: string): Promise<RalphLoopState> {\n logger.info('Creating new Ralph loop', { task: task.substring(0, 100) });\n\n const loopId = uuidv4();\n const startTime = Date.now();\n\n // Create Ralph loop state\n const loopState: RalphLoopState = {\n loopId,\n task,\n criteria,\n iteration: 0,\n status: 'initialized',\n startTime,\n lastUpdateTime: startTime,\n startCommit: await this.getCurrentGitCommit(),\n };\n\n // Initialize Ralph directory structure\n await this.initializeRalphDirectory(loopState);\n\n // Create root frame in StackMemory\n const rootFrame = await this.createRootFrame(loopState);\n\n // Save initial state\n await this.saveLoopState(loopState);\n\n this.state.activeLoop = loopState;\n\n logger.info('Ralph loop created', {\n loopId,\n frameId: rootFrame.frame_id,\n });\n\n return loopState;\n }\n\n /**\n * Resume existing loop\n */\n async resumeLoop(loopId: string): Promise<RalphLoopState> {\n logger.info('Resuming loop', { loopId });\n\n // Get state from all sources\n const sources = await this.gatherStateSources(loopId);\n\n // Reconcile state\n const reconciledState = await this.state.stateReconciler!.reconcile(sources);\n\n // Validate consistency\n if (this.config.stateReconciliation.validateConsistency) {\n const validation = await this.state.stateReconciler!.validateConsistency(reconciledState);\n \n if (validation.errors.length > 0) {\n logger.error('State validation failed', { errors: validation.errors });\n throw new Error(`Invalid state: ${validation.errors.join(', ')}`);\n }\n }\n\n this.state.activeLoop = reconciledState;\n\n // Load context from StackMemory\n const context = await this.loadIterationContext(reconciledState);\n\n logger.info('Loop resumed', {\n loopId,\n iteration: reconciledState.iteration,\n status: reconciledState.status,\n });\n\n return reconciledState;\n }\n\n /**\n * Run worker iteration\n */\n async runWorkerIteration(): Promise<RalphIteration> {\n if (!this.state.activeLoop) {\n throw new Error('No active loop');\n }\n\n const iterationNumber = this.state.activeLoop.iteration + 1;\n logger.info('Starting worker iteration', { iteration: iterationNumber });\n\n // Load and prepare context\n let context = await this.loadIterationContext(this.state.activeLoop);\n \n // Apply context budget management\n context = this.state.contextManager!.allocateBudget(context);\n \n if (this.config.contextBudget.compressionEnabled) {\n context = this.state.contextManager!.compressContext(context);\n }\n\n // Start iteration with lifecycle\n const lifecycle = this.getLifecycle();\n context = await lifecycle.startIteration(iterationNumber, context);\n\n // Execute iteration work\n const iteration = await this.executeWorkerIteration(context);\n\n // Save iteration results\n await this.saveIterationResults(iteration);\n\n // Complete iteration with lifecycle\n await lifecycle.completeIteration(iteration);\n\n // Update loop state\n this.state.activeLoop.iteration = iterationNumber;\n this.state.activeLoop.lastUpdateTime = Date.now();\n await this.saveLoopState(this.state.activeLoop);\n\n logger.info('Worker iteration completed', {\n iteration: iterationNumber,\n changes: iteration.changes.length,\n success: iteration.validation.testsPass,\n });\n\n return iteration;\n }\n\n /**\n * Run reviewer iteration\n */\n async runReviewerIteration(): Promise<{ complete: boolean; feedback?: string }> {\n if (!this.state.activeLoop) {\n throw new Error('No active loop');\n }\n\n logger.info('Starting reviewer iteration', {\n iteration: this.state.activeLoop.iteration,\n });\n\n // Evaluate against criteria\n const evaluation = await this.evaluateCompletion();\n\n if (evaluation.complete) {\n // Mark as complete\n this.state.activeLoop.status = 'completed';\n this.state.activeLoop.completionData = evaluation;\n await this.saveLoopState(this.state.activeLoop);\n\n // Handle completion\n const lifecycle = this.getLifecycle();\n await lifecycle.handleCompletion(this.state.activeLoop);\n\n logger.info('Task completed successfully');\n return { complete: true };\n }\n\n // Generate feedback for next iteration\n const feedback = this.generateFeedback(evaluation);\n this.state.activeLoop.feedback = feedback;\n \n await this.saveLoopState(this.state.activeLoop);\n\n logger.info('Reviewer iteration completed', {\n complete: false,\n feedbackLength: feedback.length,\n });\n\n return { complete: false, feedback };\n }\n\n /**\n * Rehydrate session from StackMemory\n */\n async rehydrateSession(sessionId: string): Promise<IterationContext> {\n logger.info('Rehydrating session', { sessionId });\n\n // Get session from StackMemory\n const session = await this.sessionManager.getSession(sessionId);\n \n if (!session) {\n throw new Error(`Session not found: ${sessionId}`);\n }\n\n // Load frames from session\n const frames = await this.loadSessionFrames(sessionId);\n\n // Extract Ralph loop information\n const ralphFrames = frames.filter(f => f.type === 'task' && f.name.startsWith('ralph-'));\n \n if (ralphFrames.length === 0) {\n throw new Error('No Ralph loops found in session');\n }\n\n // Get most recent Ralph loop\n const latestLoop = ralphFrames[ralphFrames.length - 1];\n\n // Reconstruct loop state\n const loopState = await this.reconstructLoopState(latestLoop);\n\n // Build context from frames\n const context = await this.buildContextFromFrames(frames, loopState);\n\n this.state.activeLoop = loopState;\n\n logger.info('Session rehydrated', {\n loopId: loopState.loopId,\n iteration: loopState.iteration,\n frameCount: frames.length,\n });\n\n return context;\n }\n\n /**\n * Create checkpoint\n */\n async createCheckpoint(): Promise<Checkpoint> {\n if (!this.state.activeLoop) {\n throw new Error('No active loop');\n }\n\n const lifecycle = this.getLifecycle();\n \n // Create dummy iteration for checkpoint\n const iteration: RalphIteration = {\n number: this.state.activeLoop.iteration,\n timestamp: Date.now(),\n analysis: {\n filesCount: 0,\n testsPass: true,\n testsFail: 0,\n lastChange: await this.getCurrentGitCommit(),\n },\n plan: {\n summary: 'Checkpoint',\n steps: [],\n priority: 'low',\n },\n changes: [],\n validation: {\n testsPass: true,\n lintClean: true,\n buildSuccess: true,\n errors: [],\n warnings: [],\n },\n };\n\n const checkpoint = await lifecycle.createCheckpoint(iteration);\n\n logger.info('Checkpoint created', {\n id: checkpoint.id,\n iteration: checkpoint.iteration,\n });\n\n return checkpoint;\n }\n\n /**\n * Restore from checkpoint\n */\n async restoreFromCheckpoint(checkpointId: string): Promise<void> {\n const lifecycle = this.getLifecycle();\n await lifecycle.restoreFromCheckpoint(checkpointId);\n\n // Reload loop state\n const sources = await this.gatherStateSources(this.state.activeLoop?.loopId || '');\n const reconciledState = await this.state.stateReconciler!.reconcile(sources);\n \n this.state.activeLoop = reconciledState;\n\n logger.info('Restored from checkpoint', {\n checkpointId,\n iteration: reconciledState.iteration,\n });\n }\n\n /**\n * Get performance metrics\n */\n getPerformanceMetrics() {\n return this.state.performanceOptimizer!.getMetrics();\n }\n\n /**\n * Cleanup resources\n */\n async cleanup(): Promise<void> {\n logger.info('Cleaning up bridge resources');\n\n // Flush any pending saves\n await this.state.performanceOptimizer!.flushBatch();\n\n // Clean up lifecycle\n this.getLifecycle().cleanup();\n\n // Clean up optimizer\n this.state.performanceOptimizer!.cleanup();\n\n logger.info('Bridge cleanup completed');\n }\n\n /**\n * Merge configuration with defaults\n */\n private mergeConfig(config?: Partial<RalphStackMemoryConfig>): RalphStackMemoryConfig {\n return {\n contextBudget: {\n maxTokens: 4000,\n priorityWeights: {\n task: 0.3,\n recentWork: 0.25,\n feedback: 0.2,\n gitHistory: 0.15,\n dependencies: 0.1,\n },\n compressionEnabled: true,\n adaptiveBudgeting: true,\n ...config?.contextBudget,\n },\n stateReconciliation: {\n precedence: ['git', 'files', 'memory'],\n conflictResolution: 'automatic',\n syncInterval: 5000,\n validateConsistency: true,\n ...config?.stateReconciliation,\n },\n lifecycle: {\n hooks: {\n preIteration: true,\n postIteration: true,\n onStateChange: true,\n onError: true,\n onComplete: true,\n },\n checkpoints: {\n enabled: true,\n frequency: 5,\n retentionDays: 7,\n },\n ...config?.lifecycle,\n },\n performance: {\n asyncSaves: true,\n batchSize: 10,\n compressionLevel: 2,\n cacheEnabled: true,\n parallelOperations: true,\n ...config?.performance,\n },\n };\n }\n\n /**\n * Setup lifecycle hooks\n */\n private setupLifecycleHooks(options?: BridgeOptions): void {\n const hooks: LifecycleHooks = {\n preIteration: async (context) => {\n logger.debug('Pre-iteration hook', {\n iteration: context.task.currentIteration,\n });\n return context;\n },\n postIteration: async (iteration) => {\n // Save to StackMemory\n await this.saveIterationFrame(iteration);\n },\n onStateChange: async (oldState, newState) => {\n // Update StackMemory with state change\n await this.updateStateFrame(oldState, newState);\n },\n onError: async (error, context) => {\n logger.error('Iteration error', { error: error.message, context });\n // Save error frame\n await this.saveErrorFrame(error, context);\n },\n onComplete: async (state) => {\n // Close root frame\n await this.closeRootFrame(state);\n },\n };\n\n const lifecycle = new IterationLifecycle(this.config.lifecycle, hooks);\n (this.state as any).lifecycle = lifecycle;\n }\n\n /**\n * Get lifecycle instance\n */\n private getLifecycle(): IterationLifecycle {\n return (this.state as any).lifecycle;\n }\n\n /**\n * Initialize Ralph directory structure\n */\n private async initializeRalphDirectory(state: RalphLoopState): Promise<void> {\n await fs.mkdir(this.ralphDir, { recursive: true });\n await fs.mkdir(path.join(this.ralphDir, 'history'), { recursive: true });\n\n // Write initial files\n await fs.writeFile(path.join(this.ralphDir, 'task.md'), state.task);\n await fs.writeFile(path.join(this.ralphDir, 'completion-criteria.md'), state.criteria);\n await fs.writeFile(path.join(this.ralphDir, 'iteration.txt'), '0');\n await fs.writeFile(path.join(this.ralphDir, 'feedback.txt'), '');\n await fs.writeFile(\n path.join(this.ralphDir, 'state.json'),\n JSON.stringify(state, null, 2)\n );\n }\n\n /**\n * Create root frame for Ralph loop\n */\n private async createRootFrame(state: RalphLoopState): Promise<Frame> {\n if (!this.frameManager) {\n throw new Error('Frame manager not initialized');\n }\n\n const frame: Partial<Frame> = {\n type: 'task' as FrameType,\n name: `ralph-${state.loopId}`,\n inputs: {\n task: state.task,\n criteria: state.criteria,\n loopId: state.loopId,\n },\n digest_json: {\n type: 'ralph_loop',\n status: 'started',\n },\n };\n\n return await this.frameManager.pushFrame(frame as any);\n }\n\n /**\n * Load iteration context from StackMemory\n */\n private async loadIterationContext(state: RalphLoopState): Promise<IterationContext> {\n const frames = await this.loadRelevantFrames(state.loopId);\n \n return {\n task: {\n description: state.task,\n criteria: state.criteria.split('\\n').filter(Boolean),\n currentIteration: state.iteration,\n feedback: state.feedback,\n priority: 'medium',\n },\n history: {\n recentIterations: await this.loadRecentIterations(state.loopId),\n gitCommits: await this.loadGitCommits(),\n changedFiles: await this.loadChangedFiles(),\n testResults: [],\n },\n environment: {\n projectPath: process.cwd(),\n branch: await this.getCurrentBranch(),\n dependencies: {},\n configuration: {},\n },\n memory: {\n relevantFrames: frames,\n decisions: [],\n patterns: [],\n blockers: [],\n },\n tokenCount: 0,\n };\n }\n\n /**\n * Execute worker iteration\n */\n private async executeWorkerIteration(context: IterationContext): Promise<RalphIteration> {\n // This would integrate with the actual Ralph loop implementation\n // For now, returning a mock iteration\n return {\n number: context.task.currentIteration + 1,\n timestamp: Date.now(),\n analysis: {\n filesCount: 10,\n testsPass: true,\n testsFail: 0,\n lastChange: 'Mock change',\n },\n plan: {\n summary: 'Mock iteration plan',\n steps: ['Step 1', 'Step 2'],\n priority: 'medium',\n },\n changes: [],\n validation: {\n testsPass: true,\n lintClean: true,\n buildSuccess: true,\n errors: [],\n warnings: [],\n },\n };\n }\n\n /**\n * Save iteration results\n */\n private async saveIterationResults(iteration: RalphIteration): Promise<void> {\n // Save with performance optimization\n await this.state.performanceOptimizer!.saveIteration(iteration);\n\n // Save iteration artifacts to Ralph directory\n const iterDir = path.join(\n this.ralphDir,\n 'history',\n `iteration-${String(iteration.number).padStart(3, '0')}`\n );\n \n await fs.mkdir(iterDir, { recursive: true });\n await fs.writeFile(\n path.join(iterDir, 'artifacts.json'),\n JSON.stringify(iteration, null, 2)\n );\n }\n\n /**\n * Save iteration frame to StackMemory\n */\n private async saveIterationFrame(iteration: RalphIteration): Promise<void> {\n if (!this.frameManager || !this.state.activeLoop) return;\n\n const frame: Partial<Frame> = {\n type: 'subtask' as FrameType,\n name: `iteration-${iteration.number}`,\n inputs: {\n iterationNumber: iteration.number,\n loopId: this.state.activeLoop.loopId,\n },\n outputs: {\n changes: iteration.changes.length,\n success: iteration.validation.testsPass,\n },\n digest_json: iteration,\n };\n\n await this.state.performanceOptimizer!.saveFrame(frame as Frame);\n }\n\n /**\n * Additional helper methods\n */\n private async getCurrentGitCommit(): Promise<string> {\n try {\n // execSync already imported at top\n return execSync('git rev-parse HEAD', { encoding: 'utf8' }).trim();\n } catch {\n return '';\n }\n }\n\n private async getCurrentBranch(): Promise<string> {\n try {\n // execSync already imported at top\n return execSync('git branch --show-current', { encoding: 'utf8' }).trim();\n } catch {\n return 'main';\n }\n }\n\n private async saveLoopState(state: RalphLoopState): Promise<void> {\n await fs.writeFile(\n path.join(this.ralphDir, 'state.json'),\n JSON.stringify(state, null, 2)\n );\n }\n\n private async gatherStateSources(loopId: string): Promise<StateSource[]> {\n const sources: StateSource[] = [];\n\n // Get git state\n sources.push(await this.state.stateReconciler!.getGitState());\n\n // Get file state\n sources.push(await this.state.stateReconciler!.getFileState());\n\n // Get memory state\n sources.push(await this.state.stateReconciler!.getMemoryState(loopId));\n\n return sources;\n }\n\n private async attemptRecovery(): Promise<void> {\n logger.info('Attempting crash recovery');\n\n try {\n // Check for incomplete loops in file system\n const stateFile = path.join(this.ralphDir, 'state.json');\n const exists = await fs.stat(stateFile).then(() => true).catch(() => false);\n\n if (exists) {\n const stateData = await fs.readFile(stateFile, 'utf8');\n const state = JSON.parse(stateData) as RalphLoopState;\n\n if (state.status !== 'completed') {\n logger.info('Found incomplete loop', { loopId: state.loopId });\n await this.resumeLoop(state.loopId);\n }\n }\n } catch (error: any) {\n logger.error('Recovery failed', { error: error.message });\n }\n }\n\n private async evaluateCompletion(): Promise<any> {\n // This would evaluate completion criteria\n // Placeholder implementation\n return {\n complete: false,\n criteria: {},\n unmet: ['criteria1', 'criteria2'],\n };\n }\n\n private generateFeedback(evaluation: any): string {\n if (evaluation.unmet.length === 0) {\n return 'All criteria met';\n }\n return `Still need to address:\\n${evaluation.unmet.map((c: string) => `- ${c}`).join('\\n')}`;\n }\n\n private async loadRelevantFrames(loopId: string): Promise<Frame[]> {\n // This would load frames from StackMemory\n // Placeholder implementation\n return [];\n }\n\n private async loadRecentIterations(loopId: string): Promise<any[]> {\n // Load recent iteration summaries\n return [];\n }\n\n private async loadGitCommits(): Promise<any[]> {\n // Load recent git commits\n return [];\n }\n\n private async loadChangedFiles(): Promise<string[]> {\n // Load recently changed files\n return [];\n }\n\n private async loadSessionFrames(sessionId: string): Promise<Frame[]> {\n // Load frames from session\n return [];\n }\n\n private async reconstructLoopState(frame: Frame): Promise<RalphLoopState> {\n // Reconstruct loop state from frame\n return {\n loopId: frame.inputs.loopId || '',\n task: frame.inputs.task || '',\n criteria: frame.inputs.criteria || '',\n iteration: 0,\n status: 'running',\n startTime: frame.created_at,\n lastUpdateTime: Date.now(),\n };\n }\n\n private async buildContextFromFrames(\n frames: Frame[],\n state: RalphLoopState\n ): Promise<IterationContext> {\n // Build context from frames\n return await this.loadIterationContext(state);\n }\n\n private async updateStateFrame(\n oldState: RalphLoopState,\n newState: RalphLoopState\n ): Promise<void> {\n // Update state in StackMemory\n logger.debug('State frame updated');\n }\n\n private async saveErrorFrame(error: Error, context: any): Promise<void> {\n // Save error as frame\n logger.debug('Error frame saved');\n }\n\n private async closeRootFrame(state: RalphLoopState): Promise<void> {\n // Close the root frame\n logger.debug('Root frame closed');\n }\n}"],
5
- "mappings": "AAKA,SAAS,MAAM,cAAc;AAC7B,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,SAAS,gBAAgB;AACzB,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,4BAA4B;AACrC,SAAS,uBAAuB;AAChC,SAAS,0BAA0C;AACnD,SAAS,4BAA4B;AAe9B,MAAM,uBAAuB;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACS,WAAW;AAAA,EAE5B,YAAY,SAAyB;AAEnC,SAAK,SAAS,KAAK,YAAY,SAAS,MAAM;AAG9C,SAAK,QAAQ;AAAA,MACX,aAAa;AAAA,MACb,gBAAgB,IAAI,qBAAqB,KAAK,OAAO,aAAa;AAAA,MAClE,iBAAiB,IAAI,gBAAgB,KAAK,OAAO,mBAAmB;AAAA,MACpE,sBAAsB,IAAI,qBAAqB,KAAK,OAAO,WAAW;AAAA,IACxE;AAEA,SAAK,iBAAiB,eAAe,YAAY;AAGjD,SAAK,oBAAoB,OAAO;AAEhC,WAAO,KAAK,wCAAwC;AAAA,MAClD,QAAQ;AAAA,QACN,WAAW,KAAK,OAAO,cAAc;AAAA,QACrC,YAAY,KAAK,OAAO,YAAY;AAAA,QACpC,aAAa,KAAK,OAAO,UAAU,YAAY;AAAA,MACjD;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,WAAW,SAKC;AAChB,WAAO,KAAK,uBAAuB,OAAO;AAE1C,QAAI;AAE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,mBAAsC;AAElD,WAAO,CAAC;AAAA,EACV;AAAA,EAEA,MAAc,kBAAkB,WAAqC;AAEnE,WAAO,CAAC;AAAA,EACV;AAAA,EAEA,MAAc,qBAAqB,OAAuC;AAExE,WAAO;AAAA,MACL,QAAQ,MAAM,OAAO,UAAU;AAAA,MAC/B,MAAM,MAAM,OAAO,QAAQ;AAAA,MAC3B,UAAU,MAAM,OAAO,YAAY;AAAA,MACnC,WAAW;AAAA,MACX,QAAQ;AAAA,MACR,WAAW,MAAM;AAAA,MACjB,gBAAgB,KAAK,IAAI;AAAA,IAC3B;AAAA,EACF;AAAA,EAEA,MAAc,uBACZ,QACA,OAC2B;AAE3B,WAAO,MAAM,KAAK,qBAAqB,KAAK;AAAA,EAC9C;AAAA,EAEA,MAAc,iBACZ,UACA,UACe;AAEf,WAAO,MAAM,qBAAqB;AAAA,EACpC;AAAA,EAEA,MAAc,eAAe,OAAc,SAA6B;AAEtE,WAAO,MAAM,mBAAmB;AAAA,EAClC;AAAA,EAEA,MAAc,eAAe,OAAsC;AAEjE,WAAO,MAAM,mBAAmB;AAAA,EAClC;AACF;",
4
+ "sourcesContent": ["/**\n * Ralph-StackMemory Bridge\n * Main integration point connecting Ralph Wiggum loops with StackMemory persistence\n */\n\nimport { v4 as uuidv4 } from 'uuid';\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\nimport { execSync } from 'child_process';\nimport { logger } from '../../../core/monitoring/logger.js';\nimport { FrameManager } from '../../../core/context/frame-manager.js';\nimport { SessionManager } from '../../../core/session/session-manager.js';\nimport { SQLiteAdapter } from '../../../core/database/sqlite-adapter.js';\nimport { ContextBudgetManager } from '../context/context-budget-manager.js';\nimport { StateReconciler } from '../state/state-reconciler.js';\nimport { IterationLifecycle, LifecycleHooks } from '../lifecycle/iteration-lifecycle.js';\nimport { PerformanceOptimizer } from '../performance/performance-optimizer.js';\nimport {\n RalphLoopState,\n RalphIteration,\n BridgeState,\n BridgeOptions,\n RalphStackMemoryConfig,\n IterationContext,\n Frame,\n FrameType,\n RecoveryState,\n Checkpoint,\n StateSource,\n} from '../types.js';\n\nexport class RalphStackMemoryBridge {\n private state: BridgeState;\n private config: RalphStackMemoryConfig;\n private frameManager?: FrameManager;\n private sessionManager: SessionManager;\n private recoveryState?: RecoveryState;\n private readonly ralphDir = '.ralph';\n\n constructor(options?: BridgeOptions) {\n // Initialize configuration\n this.config = this.mergeConfig(options?.config);\n\n // Initialize managers\n this.state = {\n initialized: false,\n contextManager: new ContextBudgetManager(this.config.contextBudget),\n stateReconciler: new StateReconciler(this.config.stateReconciliation),\n performanceOptimizer: new PerformanceOptimizer(this.config.performance),\n };\n\n this.sessionManager = SessionManager.getInstance();\n\n // Setup lifecycle hooks\n this.setupLifecycleHooks(options);\n\n logger.info('Ralph-StackMemory Bridge initialized', {\n config: {\n maxTokens: this.config.contextBudget.maxTokens,\n asyncSaves: this.config.performance.asyncSaves,\n checkpoints: this.config.lifecycle.checkpoints.enabled,\n },\n });\n }\n\n /**\n * Initialize bridge with session\n */\n async initialize(options?: {\n sessionId?: string;\n loopId?: string;\n task?: string;\n criteria?: string;\n }): Promise<void> {\n logger.info('Initializing bridge', options);\n\n try {\n // Initialize session manager\n await this.sessionManager.initialize();\n\n // Get or create session\n const session = await this.sessionManager.getOrCreateSession({\n sessionId: options?.sessionId,\n });\n\n this.state.currentSession = session;\n\n // Initialize frame manager with database\n const dbAdapter = await this.getDatabaseAdapter();\n await dbAdapter.connect();\n const db = (dbAdapter as any).db; // Get the actual Database instance\n const projectId = path.basename(this.ralphDir);\n this.frameManager = new FrameManager(db, projectId, { skipContextBridge: true });\n\n // Check for existing loop or create new\n if (options?.loopId) {\n await this.resumeLoop(options.loopId);\n } else if (options?.task && options?.criteria) {\n await this.createNewLoop(options.task, options.criteria);\n } else {\n // Try to recover from crash\n await this.attemptRecovery();\n }\n\n this.state.initialized = true;\n logger.info('Bridge initialized successfully');\n } catch (error: any) {\n logger.error('Bridge initialization failed', { error: error.message });\n throw error;\n }\n }\n\n /**\n * Create new Ralph loop with StackMemory integration\n */\n async createNewLoop(task: string, criteria: string): Promise<RalphLoopState> {\n logger.info('Creating new Ralph loop', { task: task.substring(0, 100) });\n\n const loopId = uuidv4();\n const startTime = Date.now();\n\n // Create Ralph loop state\n const loopState: RalphLoopState = {\n loopId,\n task,\n criteria,\n iteration: 0,\n status: 'initialized',\n startTime,\n lastUpdateTime: startTime,\n startCommit: await this.getCurrentGitCommit(),\n };\n\n // Initialize Ralph directory structure\n await this.initializeRalphDirectory(loopState);\n\n // Create root frame in StackMemory\n const rootFrame = await this.createRootFrame(loopState);\n\n // Save initial state\n await this.saveLoopState(loopState);\n\n this.state.activeLoop = loopState;\n\n logger.info('Ralph loop created', {\n loopId,\n frameId: rootFrame.frame_id,\n });\n\n return loopState;\n }\n\n /**\n * Resume existing loop\n */\n async resumeLoop(loopId: string): Promise<RalphLoopState> {\n logger.info('Resuming loop', { loopId });\n\n // Get state from all sources\n const sources = await this.gatherStateSources(loopId);\n\n // Reconcile state\n const reconciledState = await this.state.stateReconciler!.reconcile(sources);\n\n // Validate consistency\n if (this.config.stateReconciliation.validateConsistency) {\n const validation = await this.state.stateReconciler!.validateConsistency(reconciledState);\n \n if (validation.errors.length > 0) {\n logger.error('State validation failed', { errors: validation.errors });\n throw new Error(`Invalid state: ${validation.errors.join(', ')}`);\n }\n }\n\n this.state.activeLoop = reconciledState;\n\n // Load context from StackMemory\n const context = await this.loadIterationContext(reconciledState);\n\n logger.info('Loop resumed', {\n loopId,\n iteration: reconciledState.iteration,\n status: reconciledState.status,\n });\n\n return reconciledState;\n }\n\n /**\n * Run worker iteration\n */\n async runWorkerIteration(): Promise<RalphIteration> {\n if (!this.state.activeLoop) {\n throw new Error('No active loop');\n }\n\n const iterationNumber = this.state.activeLoop.iteration + 1;\n logger.info('Starting worker iteration', { iteration: iterationNumber });\n\n // Load and prepare context\n let context = await this.loadIterationContext(this.state.activeLoop);\n \n // Apply context budget management\n context = this.state.contextManager!.allocateBudget(context);\n \n if (this.config.contextBudget.compressionEnabled) {\n context = this.state.contextManager!.compressContext(context);\n }\n\n // Start iteration with lifecycle\n const lifecycle = this.getLifecycle();\n context = await lifecycle.startIteration(iterationNumber, context);\n\n // Execute iteration work\n const iteration = await this.executeWorkerIteration(context);\n\n // Save iteration results\n await this.saveIterationResults(iteration);\n\n // Complete iteration with lifecycle\n await lifecycle.completeIteration(iteration);\n\n // Update loop state\n this.state.activeLoop.iteration = iterationNumber;\n this.state.activeLoop.lastUpdateTime = Date.now();\n await this.saveLoopState(this.state.activeLoop);\n\n logger.info('Worker iteration completed', {\n iteration: iterationNumber,\n changes: iteration.changes.length,\n success: iteration.validation.testsPass,\n });\n\n return iteration;\n }\n\n /**\n * Run reviewer iteration\n */\n async runReviewerIteration(): Promise<{ complete: boolean; feedback?: string }> {\n if (!this.state.activeLoop) {\n throw new Error('No active loop');\n }\n\n logger.info('Starting reviewer iteration', {\n iteration: this.state.activeLoop.iteration,\n });\n\n // Evaluate against criteria\n const evaluation = await this.evaluateCompletion();\n\n if (evaluation.complete) {\n // Mark as complete\n this.state.activeLoop.status = 'completed';\n this.state.activeLoop.completionData = evaluation;\n await this.saveLoopState(this.state.activeLoop);\n\n // Handle completion\n const lifecycle = this.getLifecycle();\n await lifecycle.handleCompletion(this.state.activeLoop);\n\n logger.info('Task completed successfully');\n return { complete: true };\n }\n\n // Generate feedback for next iteration\n const feedback = this.generateFeedback(evaluation);\n this.state.activeLoop.feedback = feedback;\n \n await this.saveLoopState(this.state.activeLoop);\n\n logger.info('Reviewer iteration completed', {\n complete: false,\n feedbackLength: feedback.length,\n });\n\n return { complete: false, feedback };\n }\n\n /**\n * Rehydrate session from StackMemory\n */\n async rehydrateSession(sessionId: string): Promise<IterationContext> {\n logger.info('Rehydrating session', { sessionId });\n\n // Get session from StackMemory\n const session = await this.sessionManager.getSession(sessionId);\n \n if (!session) {\n throw new Error(`Session not found: ${sessionId}`);\n }\n\n // Load frames from session\n const frames = await this.loadSessionFrames(sessionId);\n\n // Extract Ralph loop information\n const ralphFrames = frames.filter(f => f.type === 'task' && f.name.startsWith('ralph-'));\n \n if (ralphFrames.length === 0) {\n throw new Error('No Ralph loops found in session');\n }\n\n // Get most recent Ralph loop\n const latestLoop = ralphFrames[ralphFrames.length - 1];\n\n // Reconstruct loop state\n const loopState = await this.reconstructLoopState(latestLoop);\n\n // Build context from frames\n const context = await this.buildContextFromFrames(frames, loopState);\n\n this.state.activeLoop = loopState;\n\n logger.info('Session rehydrated', {\n loopId: loopState.loopId,\n iteration: loopState.iteration,\n frameCount: frames.length,\n });\n\n return context;\n }\n\n /**\n * Create checkpoint\n */\n async createCheckpoint(): Promise<Checkpoint> {\n if (!this.state.activeLoop) {\n throw new Error('No active loop');\n }\n\n const lifecycle = this.getLifecycle();\n \n // Create dummy iteration for checkpoint\n const iteration: RalphIteration = {\n number: this.state.activeLoop.iteration,\n timestamp: Date.now(),\n analysis: {\n filesCount: 0,\n testsPass: true,\n testsFail: 0,\n lastChange: await this.getCurrentGitCommit(),\n },\n plan: {\n summary: 'Checkpoint',\n steps: [],\n priority: 'low',\n },\n changes: [],\n validation: {\n testsPass: true,\n lintClean: true,\n buildSuccess: true,\n errors: [],\n warnings: [],\n },\n };\n\n const checkpoint = await lifecycle.createCheckpoint(iteration);\n\n logger.info('Checkpoint created', {\n id: checkpoint.id,\n iteration: checkpoint.iteration,\n });\n\n return checkpoint;\n }\n\n /**\n * Restore from checkpoint\n */\n async restoreFromCheckpoint(checkpointId: string): Promise<void> {\n const lifecycle = this.getLifecycle();\n await lifecycle.restoreFromCheckpoint(checkpointId);\n\n // Reload loop state\n const sources = await this.gatherStateSources(this.state.activeLoop?.loopId || '');\n const reconciledState = await this.state.stateReconciler!.reconcile(sources);\n \n this.state.activeLoop = reconciledState;\n\n logger.info('Restored from checkpoint', {\n checkpointId,\n iteration: reconciledState.iteration,\n });\n }\n\n /**\n * Get performance metrics\n */\n getPerformanceMetrics() {\n return this.state.performanceOptimizer!.getMetrics();\n }\n\n /**\n * Cleanup resources\n */\n async cleanup(): Promise<void> {\n logger.info('Cleaning up bridge resources');\n\n // Flush any pending saves\n await this.state.performanceOptimizer!.flushBatch();\n\n // Clean up lifecycle\n this.getLifecycle().cleanup();\n\n // Clean up optimizer\n this.state.performanceOptimizer!.cleanup();\n\n logger.info('Bridge cleanup completed');\n }\n\n /**\n * Merge configuration with defaults\n */\n private mergeConfig(config?: Partial<RalphStackMemoryConfig>): RalphStackMemoryConfig {\n return {\n contextBudget: {\n maxTokens: 4000,\n priorityWeights: {\n task: 0.3,\n recentWork: 0.25,\n feedback: 0.2,\n gitHistory: 0.15,\n dependencies: 0.1,\n },\n compressionEnabled: true,\n adaptiveBudgeting: true,\n ...config?.contextBudget,\n },\n stateReconciliation: {\n precedence: ['git', 'files', 'memory'],\n conflictResolution: 'automatic',\n syncInterval: 5000,\n validateConsistency: true,\n ...config?.stateReconciliation,\n },\n lifecycle: {\n hooks: {\n preIteration: true,\n postIteration: true,\n onStateChange: true,\n onError: true,\n onComplete: true,\n },\n checkpoints: {\n enabled: true,\n frequency: 5,\n retentionDays: 7,\n },\n ...config?.lifecycle,\n },\n performance: {\n asyncSaves: true,\n batchSize: 10,\n compressionLevel: 2,\n cacheEnabled: true,\n parallelOperations: true,\n ...config?.performance,\n },\n };\n }\n\n /**\n * Setup lifecycle hooks\n */\n private setupLifecycleHooks(options?: BridgeOptions): void {\n const hooks: LifecycleHooks = {\n preIteration: async (context) => {\n logger.debug('Pre-iteration hook', {\n iteration: context.task.currentIteration,\n });\n return context;\n },\n postIteration: async (iteration) => {\n // Save to StackMemory\n await this.saveIterationFrame(iteration);\n },\n onStateChange: async (oldState, newState) => {\n // Update StackMemory with state change\n await this.updateStateFrame(oldState, newState);\n },\n onError: async (error, context) => {\n logger.error('Iteration error', { error: error.message, context });\n // Save error frame\n await this.saveErrorFrame(error, context);\n },\n onComplete: async (state) => {\n // Close root frame\n await this.closeRootFrame(state);\n },\n };\n\n const lifecycle = new IterationLifecycle(this.config.lifecycle, hooks);\n (this.state as any).lifecycle = lifecycle;\n }\n\n /**\n * Get lifecycle instance\n */\n private getLifecycle(): IterationLifecycle {\n return (this.state as any).lifecycle;\n }\n\n /**\n * Initialize Ralph directory structure\n */\n private async initializeRalphDirectory(state: RalphLoopState): Promise<void> {\n await fs.mkdir(this.ralphDir, { recursive: true });\n await fs.mkdir(path.join(this.ralphDir, 'history'), { recursive: true });\n\n // Write initial files\n await fs.writeFile(path.join(this.ralphDir, 'task.md'), state.task);\n await fs.writeFile(path.join(this.ralphDir, 'completion-criteria.md'), state.criteria);\n await fs.writeFile(path.join(this.ralphDir, 'iteration.txt'), '0');\n await fs.writeFile(path.join(this.ralphDir, 'feedback.txt'), '');\n await fs.writeFile(\n path.join(this.ralphDir, 'state.json'),\n JSON.stringify(state, null, 2)\n );\n }\n\n /**\n * Create root frame for Ralph loop\n */\n private async createRootFrame(state: RalphLoopState): Promise<Frame> {\n if (!this.frameManager) {\n throw new Error('Frame manager not initialized');\n }\n\n const frame: Partial<Frame> = {\n type: 'task' as FrameType,\n name: `ralph-${state.loopId}`,\n inputs: {\n task: state.task,\n criteria: state.criteria,\n loopId: state.loopId,\n },\n digest_json: {\n type: 'ralph_loop',\n status: 'started',\n },\n };\n\n return await this.frameManager.createFrame({\n name: frame.name,\n type: frame.type,\n content: frame.content || '',\n metadata: frame.metadata\n });\n }\n\n /**\n * Load iteration context from StackMemory\n */\n private async loadIterationContext(state: RalphLoopState): Promise<IterationContext> {\n const frames = await this.loadRelevantFrames(state.loopId);\n \n return {\n task: {\n description: state.task,\n criteria: state.criteria.split('\\n').filter(Boolean),\n currentIteration: state.iteration,\n feedback: state.feedback,\n priority: 'medium',\n },\n history: {\n recentIterations: await this.loadRecentIterations(state.loopId),\n gitCommits: await this.loadGitCommits(),\n changedFiles: await this.loadChangedFiles(),\n testResults: [],\n },\n environment: {\n projectPath: process.cwd(),\n branch: await this.getCurrentBranch(),\n dependencies: {},\n configuration: {},\n },\n memory: {\n relevantFrames: frames,\n decisions: [],\n patterns: [],\n blockers: [],\n },\n tokenCount: 0,\n };\n }\n\n /**\n * Execute worker iteration\n */\n private async executeWorkerIteration(context: IterationContext): Promise<RalphIteration> {\n // This would integrate with the actual Ralph loop implementation\n // For now, returning a mock iteration\n return {\n number: context.task.currentIteration + 1,\n timestamp: Date.now(),\n analysis: {\n filesCount: 10,\n testsPass: true,\n testsFail: 0,\n lastChange: 'Mock change',\n },\n plan: {\n summary: 'Mock iteration plan',\n steps: ['Step 1', 'Step 2'],\n priority: 'medium',\n },\n changes: [],\n validation: {\n testsPass: true,\n lintClean: true,\n buildSuccess: true,\n errors: [],\n warnings: [],\n },\n };\n }\n\n /**\n * Save iteration results\n */\n private async saveIterationResults(iteration: RalphIteration): Promise<void> {\n // Save with performance optimization\n await this.state.performanceOptimizer!.saveIteration(iteration);\n\n // Save iteration artifacts to Ralph directory\n const iterDir = path.join(\n this.ralphDir,\n 'history',\n `iteration-${String(iteration.number).padStart(3, '0')}`\n );\n \n await fs.mkdir(iterDir, { recursive: true });\n await fs.writeFile(\n path.join(iterDir, 'artifacts.json'),\n JSON.stringify(iteration, null, 2)\n );\n }\n\n /**\n * Save iteration frame to StackMemory\n */\n private async saveIterationFrame(iteration: RalphIteration): Promise<void> {\n if (!this.frameManager || !this.state.activeLoop) return;\n\n const frame: Partial<Frame> = {\n type: 'subtask' as FrameType,\n name: `iteration-${iteration.number}`,\n inputs: {\n iterationNumber: iteration.number,\n loopId: this.state.activeLoop.loopId,\n },\n outputs: {\n changes: iteration.changes.length,\n success: iteration.validation.testsPass,\n },\n digest_json: iteration,\n };\n\n await this.state.performanceOptimizer!.saveFrame(frame as Frame);\n }\n\n /**\n * Get database adapter for FrameManager\n */\n private async getDatabaseAdapter(): Promise<SQLiteAdapter> {\n const dbPath = path.join(this.ralphDir, 'stackmemory.db');\n const projectId = path.basename(this.ralphDir);\n return new SQLiteAdapter(projectId, { dbPath });\n }\n\n /**\n * Additional helper methods\n */\n private async getCurrentGitCommit(): Promise<string> {\n try {\n // execSync already imported at top\n return execSync('git rev-parse HEAD', { encoding: 'utf8' }).trim();\n } catch {\n return '';\n }\n }\n\n private async getCurrentBranch(): Promise<string> {\n try {\n // execSync already imported at top\n return execSync('git branch --show-current', { encoding: 'utf8' }).trim();\n } catch {\n return 'main';\n }\n }\n\n private async saveLoopState(state: RalphLoopState): Promise<void> {\n await fs.writeFile(\n path.join(this.ralphDir, 'state.json'),\n JSON.stringify(state, null, 2)\n );\n }\n\n private async gatherStateSources(loopId: string): Promise<StateSource[]> {\n const sources: StateSource[] = [];\n\n // Get git state\n sources.push(await this.state.stateReconciler!.getGitState());\n\n // Get file state\n sources.push(await this.state.stateReconciler!.getFileState());\n\n // Get memory state\n sources.push(await this.state.stateReconciler!.getMemoryState(loopId));\n\n return sources;\n }\n\n private async attemptRecovery(): Promise<void> {\n logger.info('Attempting crash recovery');\n\n try {\n // Check for incomplete loops in file system\n const stateFile = path.join(this.ralphDir, 'state.json');\n const exists = await fs.stat(stateFile).then(() => true).catch(() => false);\n\n if (exists) {\n const stateData = await fs.readFile(stateFile, 'utf8');\n const state = JSON.parse(stateData) as RalphLoopState;\n\n if (state.status !== 'completed') {\n logger.info('Found incomplete loop', { loopId: state.loopId });\n await this.resumeLoop(state.loopId);\n }\n }\n } catch (error: any) {\n logger.error('Recovery failed', { error: error.message });\n }\n }\n\n private async evaluateCompletion(): Promise<any> {\n // This would evaluate completion criteria\n // Placeholder implementation\n return {\n complete: false,\n criteria: {},\n unmet: ['criteria1', 'criteria2'],\n };\n }\n\n private generateFeedback(evaluation: any): string {\n if (evaluation.unmet.length === 0) {\n return 'All criteria met';\n }\n return `Still need to address:\\n${evaluation.unmet.map((c: string) => `- ${c}`).join('\\n')}`;\n }\n\n private async loadRelevantFrames(loopId: string): Promise<Frame[]> {\n // This would load frames from StackMemory\n // Placeholder implementation\n return [];\n }\n\n private async loadRecentIterations(loopId: string): Promise<any[]> {\n // Load recent iteration summaries\n return [];\n }\n\n private async loadGitCommits(): Promise<any[]> {\n // Load recent git commits\n return [];\n }\n\n private async loadChangedFiles(): Promise<string[]> {\n // Load recently changed files\n return [];\n }\n\n private async loadSessionFrames(sessionId: string): Promise<Frame[]> {\n // Load frames from session\n return [];\n }\n\n private async reconstructLoopState(frame: Frame): Promise<RalphLoopState> {\n // Reconstruct loop state from frame\n return {\n loopId: frame.inputs.loopId || '',\n task: frame.inputs.task || '',\n criteria: frame.inputs.criteria || '',\n iteration: 0,\n status: 'running',\n startTime: frame.created_at,\n lastUpdateTime: Date.now(),\n };\n }\n\n private async buildContextFromFrames(\n frames: Frame[],\n state: RalphLoopState\n ): Promise<IterationContext> {\n // Build context from frames\n return await this.loadIterationContext(state);\n }\n\n private async updateStateFrame(\n oldState: RalphLoopState,\n newState: RalphLoopState\n ): Promise<void> {\n // Update state in StackMemory\n logger.debug('State frame updated');\n }\n\n private async saveErrorFrame(error: Error, context: any): Promise<void> {\n // Save error as frame\n logger.debug('Error frame saved');\n }\n\n private async closeRootFrame(state: RalphLoopState): Promise<void> {\n // Close the root frame\n logger.debug('Root frame closed');\n }\n}"],
5
+ "mappings": "AAKA,SAAS,MAAM,cAAc;AAC7B,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,SAAS,gBAAgB;AACzB,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,qBAAqB;AAC9B,SAAS,4BAA4B;AACrC,SAAS,uBAAuB;AAChC,SAAS,0BAA0C;AACnD,SAAS,4BAA4B;AAe9B,MAAM,uBAAuB;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACS,WAAW;AAAA,EAE5B,YAAY,SAAyB;AAEnC,SAAK,SAAS,KAAK,YAAY,SAAS,MAAM;AAG9C,SAAK,QAAQ;AAAA,MACX,aAAa;AAAA,MACb,gBAAgB,IAAI,qBAAqB,KAAK,OAAO,aAAa;AAAA,MAClE,iBAAiB,IAAI,gBAAgB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,MACR,WAAW,MAAM;AAAA,MACjB,gBAAgB,KAAK,IAAI;AAAA,IAC3B;AAAA,EACF;AAAA,EAEA,MAAc,uBACZ,QACA,OAC2B;AAE3B,WAAO,MAAM,KAAK,qBAAqB,KAAK;AAAA,EAC9C;AAAA,EAEA,MAAc,iBACZ,UACA,UACe;AAEf,WAAO,MAAM,qBAAqB;AAAA,EACpC;AAAA,EAEA,MAAc,eAAe,OAAc,SAA6B;AAEtE,WAAO,MAAM,mBAAmB;AAAA,EAClC;AAAA,EAEA,MAAc,eAAe,OAAsC;AAEjE,WAAO,MAAM,mBAAmB;AAAA,EAClC;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,5 +1,12 @@
1
1
  import { execSync } from "child_process";
2
2
  import { logger } from "../../../core/monitoring/logger.js";
3
+ class GitWorkflowError extends Error {
4
+ constructor(message, context) {
5
+ super(message);
6
+ this.context = context;
7
+ this.name = "GitWorkflowError";
8
+ }
9
+ }
3
10
  class GitWorkflowManager {
4
11
  config;
5
12
  agentBranches = /* @__PURE__ */ new Map();
@@ -155,7 +162,12 @@ class GitWorkflowManager {
155
162
  }
156
163
  // Private helper methods
157
164
  getCurrentBranch() {
158
- return execSync("git rev-parse --abbrev-ref HEAD", { encoding: "utf8" }).trim();
165
+ try {
166
+ return execSync("git rev-parse --abbrev-ref HEAD", { encoding: "utf8" }).trim();
167
+ } catch (error) {
168
+ logger.warn("Failed to get current branch", error);
169
+ return "main";
170
+ }
159
171
  }
160
172
  getMainBranch() {
161
173
  try {
@@ -163,6 +175,7 @@ class GitWorkflowManager {
163
175
  if (branches.includes("origin/main")) return "main";
164
176
  if (branches.includes("origin/master")) return "master";
165
177
  } catch (error) {
178
+ logger.debug("Could not detect main branch from remotes", error);
166
179
  }
167
180
  return this.getCurrentBranch();
168
181
  }
@@ -179,10 +192,46 @@ class GitWorkflowManager {
179
192
  }
180
193
  }
181
194
  createBranch(branchName) {
182
- execSync(`git checkout -b ${branchName}`, { encoding: "utf8" });
195
+ try {
196
+ try {
197
+ const currentBranch = execSync("git branch --show-current", { encoding: "utf8" }).trim();
198
+ if (currentBranch === branchName) {
199
+ try {
200
+ execSync("git checkout main", { encoding: "utf8" });
201
+ } catch {
202
+ execSync("git checkout master", { encoding: "utf8" });
203
+ }
204
+ }
205
+ try {
206
+ const worktrees = execSync("git worktree list --porcelain", { encoding: "utf8" });
207
+ const lines = worktrees.split("\n");
208
+ for (let i = 0; i < lines.length; i++) {
209
+ if (lines[i].startsWith("branch ") && lines[i].includes(branchName)) {
210
+ const worktreetPath = lines[i - 1].replace("worktree ", "");
211
+ execSync(`git worktree remove --force "${worktreetPath}"`, { encoding: "utf8" });
212
+ logger.info(`Removed worktree at ${worktreetPath} for branch ${branchName}`);
213
+ }
214
+ }
215
+ } catch (worktreeError) {
216
+ logger.warn("Failed to check/remove worktrees", worktreeError);
217
+ }
218
+ execSync(`git branch -D ${branchName}`, { encoding: "utf8" });
219
+ logger.info(`Deleted existing branch ${branchName} for fresh start`);
220
+ } catch {
221
+ }
222
+ execSync(`git checkout -b ${branchName}`, { encoding: "utf8" });
223
+ } catch (error) {
224
+ logger.error(`Failed to create branch ${branchName}`, error);
225
+ throw new GitWorkflowError(`Failed to create branch: ${branchName}`, { branchName });
226
+ }
183
227
  }
184
228
  checkoutBranch(branchName) {
185
- execSync(`git checkout ${branchName}`, { encoding: "utf8" });
229
+ try {
230
+ execSync(`git checkout ${branchName}`, { encoding: "utf8" });
231
+ } catch (error) {
232
+ logger.error(`Failed to checkout branch ${branchName}`, error);
233
+ throw new GitWorkflowError(`Failed to checkout branch: ${branchName}`, { branchName });
234
+ }
186
235
  }
187
236
  branchExists(branchName) {
188
237
  try {
@@ -219,8 +268,13 @@ class GitWorkflowManager {
219
268
  }
220
269
  }
221
270
  hasUncommittedChanges() {
222
- const status = execSync("git status --porcelain", { encoding: "utf8" });
223
- return status.trim().length > 0;
271
+ try {
272
+ const status = execSync("git status --porcelain", { encoding: "utf8" });
273
+ return status.trim().length > 0;
274
+ } catch (error) {
275
+ logger.warn("Failed to check git status", error);
276
+ return false;
277
+ }
224
278
  }
225
279
  hasRemote() {
226
280
  try {
@@ -241,10 +295,16 @@ class GitWorkflowManager {
241
295
  }
242
296
  }
243
297
  isAgentFile(file, agent) {
298
+ if (!file || !agent?.role || !agent?.id) {
299
+ return false;
300
+ }
244
301
  return file.includes(agent.role) || file.includes(agent.id);
245
302
  }
246
303
  generateCommitMessage(agent, task) {
247
- return `[${agent.role}] ${task.title} - Iteration ${agent.performance?.tasksCompleted || 1}`;
304
+ const role = agent?.role || "agent";
305
+ const title = task?.title || "task";
306
+ const iteration = agent?.performance?.tasksCompleted || 1;
307
+ return `[${role}] ${title} - Iteration ${iteration}`;
248
308
  }
249
309
  scheduleAutoCommit(agent, task) {
250
310
  const intervalMs = this.config.commitFrequency * 60 * 1e3;
@@ -303,6 +363,7 @@ Generated by Swarm Coordinator
303
363
  }
304
364
  const gitWorkflowManager = new GitWorkflowManager();
305
365
  export {
366
+ GitWorkflowError,
306
367
  GitWorkflowManager,
307
368
  gitWorkflowManager
308
369
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/integrations/ralph/swarm/git-workflow-manager.ts"],
4
- "sourcesContent": ["/**\n * Git Workflow Manager for Swarm Agents\n * Manages git operations, branching, and commits for each agent\n */\n\nimport { execSync } from 'child_process';\nimport { logger } from '../../../core/monitoring/logger.js';\nimport { Agent, SwarmTask } from '../types.js';\n\nexport interface GitConfig {\n enableGitWorkflow: boolean;\n branchStrategy: 'feature' | 'agent' | 'task';\n autoCommit: boolean;\n commitFrequency: number; // minutes\n mergStrategy: 'squash' | 'merge' | 'rebase';\n requirePR: boolean;\n}\n\nexport class GitWorkflowManager {\n private config: GitConfig;\n private agentBranches: Map<string, string> = new Map();\n private baselineBranch: string;\n private mainBranch: string;\n\n constructor(config?: Partial<GitConfig>) {\n this.config = {\n enableGitWorkflow: true,\n branchStrategy: 'agent',\n autoCommit: true,\n commitFrequency: 5,\n mergStrategy: 'squash',\n requirePR: false,\n ...config\n };\n\n // Get current branch as baseline\n try {\n this.baselineBranch = this.getCurrentBranch();\n this.mainBranch = this.getMainBranch();\n } catch (error) {\n logger.warn('Git not initialized, workflow features disabled');\n this.config.enableGitWorkflow = false;\n }\n }\n\n /**\n * Initialize git workflow for an agent\n */\n async initializeAgentWorkflow(agent: Agent, task: SwarmTask): Promise<void> {\n if (!this.config.enableGitWorkflow) return;\n\n const branchName = this.generateBranchName(agent, task);\n \n try {\n // Create and checkout new branch\n this.createBranch(branchName);\n this.agentBranches.set(agent.id, branchName);\n \n logger.info(`Created git branch for agent ${agent.role}: ${branchName}`);\n\n // Set up commit timer if auto-commit enabled\n if (this.config.autoCommit) {\n this.scheduleAutoCommit(agent, task);\n }\n } catch (error: unknown) {\n logger.error(`Failed to initialize git workflow for agent ${agent.role}`, error as Error);\n }\n }\n\n /**\n * Commit agent work\n */\n async commitAgentWork(\n agent: Agent, \n task: SwarmTask,\n message?: string\n ): Promise<void> {\n if (!this.config.enableGitWorkflow) return;\n\n const branchName = this.agentBranches.get(agent.id);\n if (!branchName) {\n logger.warn(`No branch found for agent ${agent.id}`);\n return;\n }\n\n try {\n // Ensure we're on the agent's branch\n this.checkoutBranch(branchName);\n\n // Check for changes\n const hasChanges = this.hasUncommittedChanges();\n if (!hasChanges) {\n logger.debug(`No changes to commit for agent ${agent.role}`);\n return;\n }\n\n // Stage all changes\n execSync('git add -A', { encoding: 'utf8' });\n\n // Generate commit message\n const commitMessage = message || this.generateCommitMessage(agent, task);\n \n // Commit changes\n execSync(`git commit -m \"${commitMessage}\"`, { encoding: 'utf8' });\n \n logger.info(`Agent ${agent.role} committed: ${commitMessage}`);\n\n // Push if remote exists\n if (this.hasRemote()) {\n try {\n execSync(`git push origin ${branchName}`, { encoding: 'utf8' });\n logger.info(`Pushed branch ${branchName} to remote`);\n } catch (error) {\n logger.warn(`Could not push to remote: ${error}`);\n }\n }\n } catch (error: unknown) {\n logger.error(`Failed to commit agent work`, error as Error);\n }\n }\n\n /**\n * Merge agent work back to baseline\n */\n async mergeAgentWork(agent: Agent, task: SwarmTask): Promise<void> {\n if (!this.config.enableGitWorkflow) return;\n\n const branchName = this.agentBranches.get(agent.id);\n if (!branchName) {\n logger.warn(`No branch found for agent ${agent.id}`);\n return;\n }\n\n try {\n // Switch to baseline branch\n this.checkoutBranch(this.baselineBranch);\n\n if (this.config.requirePR) {\n // Create pull request\n await this.createPullRequest(agent, task, branchName);\n } else {\n // Direct merge based on strategy\n this.mergeBranch(branchName);\n logger.info(`Merged agent ${agent.role} work from ${branchName}`);\n }\n\n // Clean up branch\n this.deleteBranch(branchName);\n this.agentBranches.delete(agent.id);\n\n } catch (error: unknown) {\n logger.error(`Failed to merge agent work`, error as Error);\n }\n }\n\n /**\n * Coordinate merges between multiple agents\n */\n async coordinateMerges(agents: Agent[]): Promise<void> {\n if (!this.config.enableGitWorkflow) return;\n\n logger.info('Coordinating merges from all agents');\n\n // Create integration branch\n const integrationBranch = `swarm-integration-${Date.now()}`;\n this.createBranch(integrationBranch);\n\n // Merge each agent's work\n for (const agent of agents) {\n const branchName = this.agentBranches.get(agent.id);\n if (branchName && this.branchExists(branchName)) {\n try {\n this.mergeBranch(branchName);\n logger.info(`Integrated ${agent.role} work`);\n } catch (error) {\n logger.error(`Failed to integrate ${agent.role} work: ${error}`);\n }\n }\n }\n\n // Run tests on integration branch\n const testsPass = await this.runIntegrationTests();\n \n if (testsPass) {\n // Merge to baseline\n this.checkoutBranch(this.baselineBranch);\n this.mergeBranch(integrationBranch);\n logger.info('Successfully integrated all agent work');\n } else {\n logger.warn('Integration tests failed, keeping changes in branch: ' + integrationBranch);\n }\n }\n\n /**\n * Handle merge conflicts\n */\n async resolveConflicts(agent: Agent): Promise<void> {\n const conflicts = this.getConflictedFiles();\n \n if (conflicts.length === 0) return;\n\n logger.warn(`Agent ${agent.role} encountering merge conflicts: ${conflicts.join(', ')}`);\n\n // Strategy 1: Try to auto-resolve\n for (const file of conflicts) {\n try {\n // Accept current changes for agent's own files\n if (this.isAgentFile(file, agent)) {\n execSync(`git checkout --ours ${file}`, { encoding: 'utf8' });\n execSync(`git add ${file}`, { encoding: 'utf8' });\n } else {\n // Accept incoming changes for other files\n execSync(`git checkout --theirs ${file}`, { encoding: 'utf8' });\n execSync(`git add ${file}`, { encoding: 'utf8' });\n }\n } catch (error) {\n logger.error(`Could not auto-resolve conflict in ${file}`);\n }\n }\n\n // Complete merge if all conflicts resolved\n const remainingConflicts = this.getConflictedFiles();\n if (remainingConflicts.length === 0) {\n execSync('git commit --no-edit', { encoding: 'utf8' });\n logger.info('All conflicts resolved automatically');\n } else {\n logger.error(`Manual intervention needed for: ${remainingConflicts.join(', ')}`);\n }\n }\n\n // Private helper methods\n private getCurrentBranch(): string {\n return execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf8' }).trim();\n }\n\n private getMainBranch(): string {\n try {\n // Try to detect main branch\n const branches = execSync('git branch -r', { encoding: 'utf8' });\n if (branches.includes('origin/main')) return 'main';\n if (branches.includes('origin/master')) return 'master';\n } catch (error) {\n // Fallback to current branch\n }\n return this.getCurrentBranch();\n }\n\n private generateBranchName(agent: Agent, task: SwarmTask): string {\n const sanitizedTitle = task.title.toLowerCase()\n .replace(/\\s+/g, '-')\n .replace(/[^a-z0-9-]/g, '')\n .substring(0, 30);\n\n switch (this.config.branchStrategy) {\n case 'feature':\n return `feature/${sanitizedTitle}`;\n case 'task':\n return `task/${task.id}`;\n case 'agent':\n default:\n return `swarm/${agent.role}-${sanitizedTitle}`;\n }\n }\n\n private createBranch(branchName: string): void {\n execSync(`git checkout -b ${branchName}`, { encoding: 'utf8' });\n }\n\n private checkoutBranch(branchName: string): void {\n execSync(`git checkout ${branchName}`, { encoding: 'utf8' });\n }\n\n private branchExists(branchName: string): boolean {\n try {\n execSync(`git rev-parse --verify ${branchName}`, { \n encoding: 'utf8',\n stdio: 'pipe'\n });\n return true;\n } catch {\n return false;\n }\n }\n\n private deleteBranch(branchName: string): void {\n try {\n execSync(`git branch -d ${branchName}`, { encoding: 'utf8' });\n } catch (error) {\n // Force delete if needed\n execSync(`git branch -D ${branchName}`, { encoding: 'utf8' });\n }\n }\n\n private mergeBranch(branchName: string): void {\n const strategy = this.config.mergStrategy;\n \n switch (strategy) {\n case 'squash':\n execSync(`git merge --squash ${branchName}`, { encoding: 'utf8' });\n execSync('git commit -m \"Squashed agent changes\"', { encoding: 'utf8' });\n break;\n case 'rebase':\n execSync(`git rebase ${branchName}`, { encoding: 'utf8' });\n break;\n case 'merge':\n default:\n execSync(`git merge ${branchName}`, { encoding: 'utf8' });\n break;\n }\n }\n\n private hasUncommittedChanges(): boolean {\n const status = execSync('git status --porcelain', { encoding: 'utf8' });\n return status.trim().length > 0;\n }\n\n private hasRemote(): boolean {\n try {\n execSync('git remote get-url origin', { encoding: 'utf8' });\n return true;\n } catch {\n return false;\n }\n }\n\n private getConflictedFiles(): string[] {\n try {\n const conflicts = execSync('git diff --name-only --diff-filter=U', { \n encoding: 'utf8' \n });\n return conflicts.trim().split('\\n').filter(f => f.length > 0);\n } catch {\n return [];\n }\n }\n\n private isAgentFile(file: string, agent: Agent): boolean {\n // Simple heuristic: check if file is in agent's working directory\n return file.includes(agent.role) || file.includes(agent.id);\n }\n\n private generateCommitMessage(agent: Agent, task: SwarmTask): string {\n return `[${agent.role}] ${task.title} - Iteration ${agent.performance?.tasksCompleted || 1}`;\n }\n\n private scheduleAutoCommit(agent: Agent, task: SwarmTask): void {\n const intervalMs = this.config.commitFrequency * 60 * 1000;\n \n setInterval(async () => {\n await this.commitAgentWork(agent, task, `[${agent.role}] Auto-commit: ${task.title}`);\n }, intervalMs);\n }\n\n private async createPullRequest(agent: Agent, task: SwarmTask, branchName: string): Promise<void> {\n try {\n const title = `[Swarm ${agent.role}] ${task.title}`;\n const body = `\n## Agent: ${agent.role}\n## Task: ${task.title}\n\n### Acceptance Criteria:\n${task.acceptanceCriteria.map(c => `- ${c}`).join('\\n')}\n\n### Status:\n- Tasks Completed: ${agent.performance?.tasksCompleted || 0}\n- Success Rate: ${agent.performance?.successRate || 0}%\n\nGenerated by Swarm Coordinator\n `;\n\n execSync(`gh pr create --title \"${title}\" --body \"${body}\" --base ${this.baselineBranch}`, {\n encoding: 'utf8'\n });\n \n logger.info(`Created PR for agent ${agent.role}`);\n } catch (error) {\n logger.warn(`Could not create PR: ${error}`);\n }\n }\n\n private async runIntegrationTests(): Promise<boolean> {\n try {\n // Try to run tests\n execSync('npm test', { encoding: 'utf8' });\n return true;\n } catch {\n // Tests failed or not available\n return false;\n }\n }\n\n /**\n * Get status of all agent branches\n */\n getGitStatus(): object {\n const status: any = {\n enabled: this.config.enableGitWorkflow,\n currentBranch: this.getCurrentBranch(),\n agentBranches: Array.from(this.agentBranches.entries()).map(([agentId, branch]) => ({\n agentId,\n branch,\n exists: this.branchExists(branch)\n })),\n hasUncommittedChanges: this.hasUncommittedChanges()\n };\n\n return status;\n }\n}\n\nexport const gitWorkflowManager = new GitWorkflowManager();"],
5
- "mappings": "AAKA,SAAS,gBAAgB;AACzB,SAAS,cAAc;AAYhB,MAAM,mBAAmB;AAAA,EACtB;AAAA,EACA,gBAAqC,oBAAI,IAAI;AAAA,EAC7C;AAAA,EACA;AAAA,EAER,YAAY,QAA6B;AACvC,SAAK,SAAS;AAAA,MACZ,mBAAmB;AAAA,MACnB,gBAAgB;AAAA,MAChB,YAAY;AAAA,MACZ,iBAAiB;AAAA,MACjB,cAAc;AAAA,MACd,WAAW;AAAA,MACX,GAAG;AAAA,IACL;AAGA,QAAI;AACF,WAAK,iBAAiB,KAAK,iBAAiB;AAC5C,WAAK,aAAa,KAAK,cAAc;AAAA,IACvC,SAAS,OAAO;AACd,aAAO,KAAK,iDAAiD;AAC7D,WAAK,OAAO,oBAAoB;AAAA,IAClC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,wBAAwB,OAAc,MAAgC;AAC1E,QAAI,CAAC,KAAK,OAAO,kBAAmB;AA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YAAM,QAAQ,UAAU,MAAM,IAAI,KAAK,KAAK,KAAK;AACjD,YAAM,OAAO;AAAA,YACP,MAAM,IAAI;AAAA,WACX,KAAK,KAAK;AAAA;AAAA;AAAA,EAGnB,KAAK,mBAAmB,IAAI,OAAK,KAAK,CAAC,EAAE,EAAE,KAAK,IAAI,CAAC;AAAA;AAAA;AAAA,qBAGlC,MAAM,aAAa,kBAAkB,CAAC;AAAA,kBACzC,MAAM,aAAa,eAAe,CAAC;AAAA;AAAA;AAAA;AAK/C,eAAS,yBAAyB,KAAK,aAAa,IAAI,YAAY,KAAK,cAAc,IAAI;AAAA,QACzF,UAAU;AAAA,MACZ,CAAC;AAED,aAAO,KAAK,wBAAwB,MAAM,IAAI,EAAE;AAAA,IAClD,SAAS,OAAO;AACd,aAAO,KAAK,wBAAwB,KAAK,EAAE;AAAA,IAC7C;AAAA,EACF;AAAA,EAEA,MAAc,sBAAwC;AACpD,QAAI;AAEF,eAAS,YAAY,EAAE,UAAU,OAAO,CAAC;AACzC,aAAO;AAAA,IACT,QAAQ;AAEN,aAAO;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,eAAuB;AACrB,UAAM,SAAc;AAAA,MAClB,SAAS,KAAK,OAAO;AAAA,MACrB,eAAe,KAAK,iBAAiB;AAAA,MACrC,eAAe,MAAM,KAAK,KAAK,cAAc,QAAQ,CAAC,EAAE,IAAI,CAAC,CAAC,SAAS,MAAM,OAAO;AAAA,QAClF;AAAA,QACA;AAAA,QACA,QAAQ,KAAK,aAAa,MAAM;AAAA,MAClC,EAAE;AAAA,MACF,uBAAuB,KAAK,sBAAsB;AAAA,IACpD;AAEA,WAAO;AAAA,EACT;AACF;AAEO,MAAM,qBAAqB,IAAI,mBAAmB;",
4
+ "sourcesContent": ["/**\n * Git Workflow Manager for Swarm Agents\n * Manages git operations, branching, and commits for each agent\n */\n\nimport { execSync } from 'child_process';\nimport { logger } from '../../../core/monitoring/logger.js';\nimport { Agent, SwarmTask } from '../types.js';\n\nexport class GitWorkflowError extends Error {\n constructor(message: string, public context?: Record<string, unknown>) {\n super(message);\n this.name = 'GitWorkflowError';\n }\n}\n\nexport interface GitConfig {\n enableGitWorkflow: boolean;\n branchStrategy: 'feature' | 'agent' | 'task';\n autoCommit: boolean;\n commitFrequency: number; // minutes\n mergStrategy: 'squash' | 'merge' | 'rebase';\n requirePR: boolean;\n}\n\nexport class GitWorkflowManager {\n private config: GitConfig;\n private agentBranches: Map<string, string> = new Map();\n private baselineBranch: string;\n private mainBranch: string;\n\n constructor(config?: Partial<GitConfig>) {\n this.config = {\n enableGitWorkflow: true,\n branchStrategy: 'agent',\n autoCommit: true,\n commitFrequency: 5,\n mergStrategy: 'squash',\n requirePR: false,\n ...config\n };\n\n // Get current branch as baseline\n try {\n this.baselineBranch = this.getCurrentBranch();\n this.mainBranch = this.getMainBranch();\n } catch (error) {\n logger.warn('Git not initialized, workflow features disabled');\n this.config.enableGitWorkflow = false;\n }\n }\n\n /**\n * Initialize git workflow for an agent\n */\n async initializeAgentWorkflow(agent: Agent, task: SwarmTask): Promise<void> {\n if (!this.config.enableGitWorkflow) return;\n\n const branchName = this.generateBranchName(agent, task);\n \n try {\n // Create and checkout new branch\n this.createBranch(branchName);\n this.agentBranches.set(agent.id, branchName);\n \n logger.info(`Created git branch for agent ${agent.role}: ${branchName}`);\n\n // Set up commit timer if auto-commit enabled\n if (this.config.autoCommit) {\n this.scheduleAutoCommit(agent, task);\n }\n } catch (error: unknown) {\n logger.error(`Failed to initialize git workflow for agent ${agent.role}`, error as Error);\n }\n }\n\n /**\n * Commit agent work\n */\n async commitAgentWork(\n agent: Agent, \n task: SwarmTask,\n message?: string\n ): Promise<void> {\n if (!this.config.enableGitWorkflow) return;\n\n const branchName = this.agentBranches.get(agent.id);\n if (!branchName) {\n logger.warn(`No branch found for agent ${agent.id}`);\n return;\n }\n\n try {\n // Ensure we're on the agent's branch\n this.checkoutBranch(branchName);\n\n // Check for changes\n const hasChanges = this.hasUncommittedChanges();\n if (!hasChanges) {\n logger.debug(`No changes to commit for agent ${agent.role}`);\n return;\n }\n\n // Stage all changes\n execSync('git add -A', { encoding: 'utf8' });\n\n // Generate commit message\n const commitMessage = message || this.generateCommitMessage(agent, task);\n \n // Commit changes\n execSync(`git commit -m \"${commitMessage}\"`, { encoding: 'utf8' });\n \n logger.info(`Agent ${agent.role} committed: ${commitMessage}`);\n\n // Push if remote exists\n if (this.hasRemote()) {\n try {\n execSync(`git push origin ${branchName}`, { encoding: 'utf8' });\n logger.info(`Pushed branch ${branchName} to remote`);\n } catch (error) {\n logger.warn(`Could not push to remote: ${error}`);\n }\n }\n } catch (error: unknown) {\n logger.error(`Failed to commit agent work`, error as Error);\n }\n }\n\n /**\n * Merge agent work back to baseline\n */\n async mergeAgentWork(agent: Agent, task: SwarmTask): Promise<void> {\n if (!this.config.enableGitWorkflow) return;\n\n const branchName = this.agentBranches.get(agent.id);\n if (!branchName) {\n logger.warn(`No branch found for agent ${agent.id}`);\n return;\n }\n\n try {\n // Switch to baseline branch\n this.checkoutBranch(this.baselineBranch);\n\n if (this.config.requirePR) {\n // Create pull request\n await this.createPullRequest(agent, task, branchName);\n } else {\n // Direct merge based on strategy\n this.mergeBranch(branchName);\n logger.info(`Merged agent ${agent.role} work from ${branchName}`);\n }\n\n // Clean up branch\n this.deleteBranch(branchName);\n this.agentBranches.delete(agent.id);\n\n } catch (error: unknown) {\n logger.error(`Failed to merge agent work`, error as Error);\n }\n }\n\n /**\n * Coordinate merges between multiple agents\n */\n async coordinateMerges(agents: Agent[]): Promise<void> {\n if (!this.config.enableGitWorkflow) return;\n\n logger.info('Coordinating merges from all agents');\n\n // Create integration branch\n const integrationBranch = `swarm-integration-${Date.now()}`;\n this.createBranch(integrationBranch);\n\n // Merge each agent's work\n for (const agent of agents) {\n const branchName = this.agentBranches.get(agent.id);\n if (branchName && this.branchExists(branchName)) {\n try {\n this.mergeBranch(branchName);\n logger.info(`Integrated ${agent.role} work`);\n } catch (error) {\n logger.error(`Failed to integrate ${agent.role} work: ${error}`);\n }\n }\n }\n\n // Run tests on integration branch\n const testsPass = await this.runIntegrationTests();\n \n if (testsPass) {\n // Merge to baseline\n this.checkoutBranch(this.baselineBranch);\n this.mergeBranch(integrationBranch);\n logger.info('Successfully integrated all agent work');\n } else {\n logger.warn('Integration tests failed, keeping changes in branch: ' + integrationBranch);\n }\n }\n\n /**\n * Handle merge conflicts\n */\n async resolveConflicts(agent: Agent): Promise<void> {\n const conflicts = this.getConflictedFiles();\n \n if (conflicts.length === 0) return;\n\n logger.warn(`Agent ${agent.role} encountering merge conflicts: ${conflicts.join(', ')}`);\n\n // Strategy 1: Try to auto-resolve\n for (const file of conflicts) {\n try {\n // Accept current changes for agent's own files\n if (this.isAgentFile(file, agent)) {\n execSync(`git checkout --ours ${file}`, { encoding: 'utf8' });\n execSync(`git add ${file}`, { encoding: 'utf8' });\n } else {\n // Accept incoming changes for other files\n execSync(`git checkout --theirs ${file}`, { encoding: 'utf8' });\n execSync(`git add ${file}`, { encoding: 'utf8' });\n }\n } catch (error) {\n logger.error(`Could not auto-resolve conflict in ${file}`);\n }\n }\n\n // Complete merge if all conflicts resolved\n const remainingConflicts = this.getConflictedFiles();\n if (remainingConflicts.length === 0) {\n execSync('git commit --no-edit', { encoding: 'utf8' });\n logger.info('All conflicts resolved automatically');\n } else {\n logger.error(`Manual intervention needed for: ${remainingConflicts.join(', ')}`);\n }\n }\n\n // Private helper methods\n private getCurrentBranch(): string {\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf8' }).trim();\n } catch (error: unknown) {\n logger.warn('Failed to get current branch', error as Error);\n return 'main';\n }\n }\n\n private getMainBranch(): string {\n try {\n const branches = execSync('git branch -r', { encoding: 'utf8' });\n if (branches.includes('origin/main')) return 'main';\n if (branches.includes('origin/master')) return 'master';\n } catch (error: unknown) {\n logger.debug('Could not detect main branch from remotes', error as Error);\n }\n return this.getCurrentBranch();\n }\n\n private generateBranchName(agent: Agent, task: SwarmTask): string {\n const sanitizedTitle = task.title.toLowerCase()\n .replace(/\\s+/g, '-')\n .replace(/[^a-z0-9-]/g, '')\n .substring(0, 30);\n\n switch (this.config.branchStrategy) {\n case 'feature':\n return `feature/${sanitizedTitle}`;\n case 'task':\n return `task/${task.id}`;\n case 'agent':\n default:\n return `swarm/${agent.role}-${sanitizedTitle}`;\n }\n }\n\n private createBranch(branchName: string): void {\n try {\n // Check if branch already exists and delete it for clean test runs\n try {\n // First check if this is the current branch\n const currentBranch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();\n if (currentBranch === branchName) {\n // Switch to main/master before deleting\n try {\n execSync('git checkout main', { encoding: 'utf8' });\n } catch {\n execSync('git checkout master', { encoding: 'utf8' });\n }\n }\n \n // Remove any worktrees using this branch\n try {\n const worktrees = execSync('git worktree list --porcelain', { encoding: 'utf8' });\n const lines = worktrees.split('\\n');\n for (let i = 0; i < lines.length; i++) {\n if (lines[i].startsWith('branch ') && lines[i].includes(branchName)) {\n const worktreetPath = lines[i-1].replace('worktree ', '');\n execSync(`git worktree remove --force \"${worktreetPath}\"`, { encoding: 'utf8' });\n logger.info(`Removed worktree at ${worktreetPath} for branch ${branchName}`);\n }\n }\n } catch (worktreeError) {\n logger.warn('Failed to check/remove worktrees', worktreeError as Error);\n }\n \n execSync(`git branch -D ${branchName}`, { encoding: 'utf8' });\n logger.info(`Deleted existing branch ${branchName} for fresh start`);\n } catch {\n // Branch doesn't exist, which is fine\n }\n \n execSync(`git checkout -b ${branchName}`, { encoding: 'utf8' });\n } catch (error: unknown) {\n logger.error(`Failed to create branch ${branchName}`, error as Error);\n throw new GitWorkflowError(`Failed to create branch: ${branchName}`, { branchName });\n }\n }\n\n private checkoutBranch(branchName: string): void {\n try {\n execSync(`git checkout ${branchName}`, { encoding: 'utf8' });\n } catch (error: unknown) {\n logger.error(`Failed to checkout branch ${branchName}`, error as Error);\n throw new GitWorkflowError(`Failed to checkout branch: ${branchName}`, { branchName });\n }\n }\n\n private branchExists(branchName: string): boolean {\n try {\n execSync(`git rev-parse --verify ${branchName}`, { \n encoding: 'utf8',\n stdio: 'pipe'\n });\n return true;\n } catch {\n return false;\n }\n }\n\n private deleteBranch(branchName: string): void {\n try {\n execSync(`git branch -d ${branchName}`, { encoding: 'utf8' });\n } catch (error) {\n // Force delete if needed\n execSync(`git branch -D ${branchName}`, { encoding: 'utf8' });\n }\n }\n\n private mergeBranch(branchName: string): void {\n const strategy = this.config.mergStrategy;\n \n switch (strategy) {\n case 'squash':\n execSync(`git merge --squash ${branchName}`, { encoding: 'utf8' });\n execSync('git commit -m \"Squashed agent changes\"', { encoding: 'utf8' });\n break;\n case 'rebase':\n execSync(`git rebase ${branchName}`, { encoding: 'utf8' });\n break;\n case 'merge':\n default:\n execSync(`git merge ${branchName}`, { encoding: 'utf8' });\n break;\n }\n }\n\n private hasUncommittedChanges(): boolean {\n try {\n const status = execSync('git status --porcelain', { encoding: 'utf8' });\n return status.trim().length > 0;\n } catch (error: unknown) {\n logger.warn('Failed to check git status', error as Error);\n return false;\n }\n }\n\n private hasRemote(): boolean {\n try {\n execSync('git remote get-url origin', { encoding: 'utf8' });\n return true;\n } catch {\n return false;\n }\n }\n\n private getConflictedFiles(): string[] {\n try {\n const conflicts = execSync('git diff --name-only --diff-filter=U', { \n encoding: 'utf8' \n });\n return conflicts.trim().split('\\n').filter(f => f.length > 0);\n } catch {\n return [];\n }\n }\n\n private isAgentFile(file: string, agent: Agent): boolean {\n if (!file || !agent?.role || !agent?.id) {\n return false;\n }\n return file.includes(agent.role) || file.includes(agent.id);\n }\n\n private generateCommitMessage(agent: Agent, task: SwarmTask): string {\n const role = agent?.role || 'agent';\n const title = task?.title || 'task';\n const iteration = agent?.performance?.tasksCompleted || 1;\n return `[${role}] ${title} - Iteration ${iteration}`;\n }\n\n private scheduleAutoCommit(agent: Agent, task: SwarmTask): void {\n const intervalMs = this.config.commitFrequency * 60 * 1000;\n \n setInterval(async () => {\n await this.commitAgentWork(agent, task, `[${agent.role}] Auto-commit: ${task.title}`);\n }, intervalMs);\n }\n\n private async createPullRequest(agent: Agent, task: SwarmTask, branchName: string): Promise<void> {\n try {\n const title = `[Swarm ${agent.role}] ${task.title}`;\n const body = `\n## Agent: ${agent.role}\n## Task: ${task.title}\n\n### Acceptance Criteria:\n${task.acceptanceCriteria.map(c => `- ${c}`).join('\\n')}\n\n### Status:\n- Tasks Completed: ${agent.performance?.tasksCompleted || 0}\n- Success Rate: ${agent.performance?.successRate || 0}%\n\nGenerated by Swarm Coordinator\n `;\n\n execSync(`gh pr create --title \"${title}\" --body \"${body}\" --base ${this.baselineBranch}`, {\n encoding: 'utf8'\n });\n \n logger.info(`Created PR for agent ${agent.role}`);\n } catch (error) {\n logger.warn(`Could not create PR: ${error}`);\n }\n }\n\n private async runIntegrationTests(): Promise<boolean> {\n try {\n // Try to run tests\n execSync('npm test', { encoding: 'utf8' });\n return true;\n } catch {\n // Tests failed or not available\n return false;\n }\n }\n\n /**\n * Get status of all agent branches\n */\n getGitStatus(): object {\n const status: any = {\n enabled: this.config.enableGitWorkflow,\n currentBranch: this.getCurrentBranch(),\n agentBranches: Array.from(this.agentBranches.entries()).map(([agentId, branch]) => ({\n agentId,\n branch,\n exists: this.branchExists(branch)\n })),\n hasUncommittedChanges: this.hasUncommittedChanges()\n };\n\n return status;\n }\n}\n\nexport const gitWorkflowManager = new GitWorkflowManager();"],
5
+ "mappings": "AAKA,SAAS,gBAAgB;AACzB,SAAS,cAAc;AAGhB,MAAM,yBAAyB,MAAM;AAAA,EAC1C,YAAY,SAAwB,SAAmC;AACrE,UAAM,OAAO;AADqB;AAElC,SAAK,OAAO;AAAA,EACd;AACF;AAWO,MAAM,mBAAmB;AAAA,EACtB;AAAA,EACA,gBAAqC,oBAAI,IAAI;AAAA,EAC7C;AAAA,EACA;AAAA,EAER,YAAY,QAA6B;AACvC,SAAK,SAAS;AAAA,MACZ,mBAAmB;AAAA,MACnB,gBAAgB;AAAA,MAChB,YAAY;AAAA,MACZ,iBA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;AAAA,EAEA,MAAc,sBAAwC;AACpD,QAAI;AAEF,eAAS,YAAY,EAAE,UAAU,OAAO,CAAC;AACzC,aAAO;AAAA,IACT,QAAQ;AAEN,aAAO;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,eAAuB;AACrB,UAAM,SAAc;AAAA,MAClB,SAAS,KAAK,OAAO;AAAA,MACrB,eAAe,KAAK,iBAAiB;AAAA,MACrC,eAAe,MAAM,KAAK,KAAK,cAAc,QAAQ,CAAC,EAAE,IAAI,CAAC,CAAC,SAAS,MAAM,OAAO;AAAA,QAClF;AAAA,QACA;AAAA,QACA,QAAQ,KAAK,aAAa,MAAM;AAAA,MAClC,EAAE;AAAA,MACF,uBAAuB,KAAK,sBAAsB;AAAA,IACpD;AAEA,WAAO;AAAA,EACT;AACF;AAEO,MAAM,qBAAqB,IAAI,mBAAmB;",
6
6
  "names": []
7
7
  }
@@ -7,6 +7,30 @@ import { sessionManager } from "../../../core/session/index.js";
7
7
  import { sharedContextLayer } from "../../../core/context/shared-context-layer.js";
8
8
  import { RalphStackMemoryBridge } from "../bridge/ralph-stackmemory-bridge.js";
9
9
  import { GitWorkflowManager } from "./git-workflow-manager.js";
10
+ class SwarmCoordinationError extends Error {
11
+ constructor(message, context) {
12
+ super(message);
13
+ this.context = context;
14
+ this.name = "SwarmCoordinationError";
15
+ }
16
+ }
17
+ class AgentExecutionError extends Error {
18
+ constructor(message, agentId, taskId, context) {
19
+ super(message);
20
+ this.agentId = agentId;
21
+ this.taskId = taskId;
22
+ this.context = context;
23
+ this.name = "AgentExecutionError";
24
+ }
25
+ }
26
+ class TaskAllocationError extends Error {
27
+ constructor(message, taskId, context) {
28
+ super(message);
29
+ this.taskId = taskId;
30
+ this.context = context;
31
+ this.name = "TaskAllocationError";
32
+ }
33
+ }
10
34
  class SwarmCoordinator {
11
35
  frameManager;
12
36
  activeAgents = /* @__PURE__ */ new Map();
@@ -279,7 +303,24 @@ class SwarmCoordinator {
279
303
  criteria: task.acceptanceCriteria.join("\n")
280
304
  });
281
305
  this.setupAgentCoordination(agent, ralph, assignment);
282
- await ralph.run();
306
+ let iteration = 1;
307
+ const maxIterations = this.calculateMaxIterations(task);
308
+ while (iteration <= maxIterations) {
309
+ try {
310
+ const result = await ralph.runWorkerIteration();
311
+ if (result.isComplete) {
312
+ logger.info(`Task completed in ${iteration} iterations`);
313
+ break;
314
+ }
315
+ iteration++;
316
+ } catch (error) {
317
+ logger.error(`Iteration ${iteration} failed:`, error);
318
+ if (iteration >= maxIterations) {
319
+ throw error;
320
+ }
321
+ iteration++;
322
+ }
323
+ }
283
324
  await this.gitWorkflowManager.commitAgentWork(agent, task);
284
325
  this.updateAgentPerformance(agent, true);
285
326
  await this.gitWorkflowManager.mergeAgentWork(agent, task);
@@ -646,11 +687,108 @@ You are a PROJECT COORDINATOR. Your role is to:
646
687
  this.swarmState.performance.throughput = this.swarmState.completedTaskCount / ((Date.now() - this.swarmState.startTime) / 1e3);
647
688
  this.swarmState.performance.efficiency = activeCount > 0 ? this.swarmState.completedTaskCount / activeCount : 0;
648
689
  }
690
+ /**
691
+ * Cleanup completed swarms and their resources
692
+ */
693
+ async cleanupCompletedSwarms() {
694
+ if (this.swarmState.status !== "completed") {
695
+ return;
696
+ }
697
+ try {
698
+ logger.info("Cleaning up completed swarm resources");
699
+ if (this.coordinationTimer) {
700
+ clearInterval(this.coordinationTimer);
701
+ this.coordinationTimer = void 0;
702
+ }
703
+ for (const agent of this.activeAgents.values()) {
704
+ try {
705
+ await fs.rmdir(agent.workingDirectory, { recursive: true });
706
+ logger.debug(`Cleaned up working directory for agent ${agent.id}`);
707
+ } catch (error) {
708
+ logger.warn(`Could not clean up directory for agent ${agent.id}`, error);
709
+ }
710
+ }
711
+ await this.gitWorkflowManager.coordinateMerges(Array.from(this.activeAgents.values()));
712
+ this.activeAgents.clear();
713
+ this.swarmState = {
714
+ id: uuidv4(),
715
+ status: "idle",
716
+ startTime: Date.now(),
717
+ activeTaskCount: 0,
718
+ completedTaskCount: 0,
719
+ coordination: {
720
+ events: [],
721
+ conflicts: [],
722
+ resolutions: []
723
+ },
724
+ performance: {
725
+ throughput: 0,
726
+ efficiency: 0,
727
+ coordination_overhead: 0
728
+ }
729
+ };
730
+ logger.info("Swarm cleanup completed successfully");
731
+ } catch (error) {
732
+ logger.error("Failed to cleanup completed swarm", error);
733
+ throw new SwarmCoordinationError("Cleanup failed", { swarmId: this.swarmState.id, error });
734
+ }
735
+ }
736
+ /**
737
+ * Force cleanup of a swarm (for emergency situations)
738
+ */
739
+ async forceCleanup() {
740
+ logger.warn("Force cleanup initiated");
741
+ try {
742
+ if (this.coordinationTimer) {
743
+ clearInterval(this.coordinationTimer);
744
+ this.coordinationTimer = void 0;
745
+ }
746
+ for (const agent of this.activeAgents.values()) {
747
+ agent.status = "stopped";
748
+ }
749
+ this.swarmState.status = "stopped";
750
+ await this.cleanupCompletedSwarms();
751
+ } catch (error) {
752
+ logger.error("Force cleanup failed", error);
753
+ }
754
+ }
755
+ /**
756
+ * Get swarm resource usage and cleanup recommendations
757
+ */
758
+ getResourceUsage() {
759
+ const workingDirs = Array.from(this.activeAgents.values()).map((a) => a.workingDirectory);
760
+ const memoryEstimate = this.activeAgents.size * 50;
761
+ const isStale = Date.now() - this.swarmState.startTime > 36e5;
762
+ const hasCompletedTasks = this.swarmState.completedTaskCount > 0 && this.swarmState.activeTaskCount === 0;
763
+ const recommendations = [];
764
+ let cleanupRecommended = false;
765
+ if (isStale) {
766
+ recommendations.push("Swarm has been running for over 1 hour - consider cleanup");
767
+ cleanupRecommended = true;
768
+ }
769
+ if (hasCompletedTasks) {
770
+ recommendations.push("All tasks completed - cleanup is recommended");
771
+ cleanupRecommended = true;
772
+ }
773
+ if (this.activeAgents.size > 5) {
774
+ recommendations.push("High agent count - monitor resource usage");
775
+ }
776
+ return {
777
+ activeAgents: this.activeAgents.size,
778
+ workingDirectories: workingDirs,
779
+ memoryEstimate,
780
+ cleanupRecommended,
781
+ recommendations
782
+ };
783
+ }
649
784
  [Symbol.toStringTag] = "SwarmCoordinator";
650
785
  }
651
786
  const swarmCoordinator = new SwarmCoordinator();
652
787
  export {
788
+ AgentExecutionError,
789
+ SwarmCoordinationError,
653
790
  SwarmCoordinator,
791
+ TaskAllocationError,
654
792
  swarmCoordinator
655
793
  };
656
794
  //# sourceMappingURL=swarm-coordinator.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/integrations/ralph/swarm/swarm-coordinator.ts"],
4
- "sourcesContent": ["/**\n * Swarm Coordination System for StackMemory\n * Orchestrates multiple specialized agents working together on the same codebase\n * Addresses multi-agent coordination challenges with role specialization and dynamic planning\n */\n\nimport { v4 as uuidv4 } from 'uuid';\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\nimport { logger } from '../../../core/monitoring/logger.js';\nimport { FrameManager } from '../../../core/context/frame-manager.js';\nimport { sessionManager } from '../../../core/session/index.js';\nimport { sharedContextLayer } from '../../../core/context/shared-context-layer.js';\nimport { RalphStackMemoryBridge } from '../bridge/ralph-stackmemory-bridge.js';\nimport { GitWorkflowManager } from './git-workflow-manager.js';\nimport {\n SwarmConfiguration,\n Agent,\n AgentRole,\n SwarmTask,\n CoordinationEvent,\n SwarmState,\n TaskAllocation,\n AgentSpecialization\n} from '../types.js';\n\nexport interface SwarmCoordinatorConfig {\n maxAgents: number;\n coordinationInterval: number;\n driftDetectionThreshold: number;\n freshStartInterval: number;\n conflictResolutionStrategy: 'democratic' | 'hierarchical' | 'expertise';\n enableDynamicPlanning: boolean;\n pathologicalBehaviorDetection: boolean;\n}\n\nexport class SwarmCoordinator {\n private frameManager?: FrameManager;\n private activeAgents: Map<string, Agent> = new Map();\n private swarmState: SwarmState;\n private config: SwarmCoordinatorConfig;\n private coordinationTimer?: NodeJS.Timeout;\n private plannerWakeupQueue: Map<string, () => void> = new Map();\n private gitWorkflowManager: GitWorkflowManager;\n\n constructor(config?: Partial<SwarmCoordinatorConfig>) {\n this.config = {\n maxAgents: 10,\n coordinationInterval: 30000, // 30 seconds\n driftDetectionThreshold: 5, // 5 failed iterations before considering drift\n freshStartInterval: 3600000, // 1 hour\n conflictResolutionStrategy: 'expertise',\n enableDynamicPlanning: true,\n pathologicalBehaviorDetection: true,\n ...config\n };\n\n this.swarmState = {\n id: uuidv4(),\n status: 'idle',\n startTime: Date.now(),\n activeTaskCount: 0,\n completedTaskCount: 0,\n coordination: {\n events: [],\n conflicts: [],\n resolutions: []\n },\n performance: {\n throughput: 0,\n efficiency: 0,\n coordination_overhead: 0\n }\n };\n\n // Initialize git workflow manager\n this.gitWorkflowManager = new GitWorkflowManager({\n enableGitWorkflow: true,\n branchStrategy: 'agent',\n autoCommit: true,\n commitFrequency: 5,\n mergStrategy: 'squash'\n });\n\n logger.info('Swarm coordinator initialized', this.config);\n }\n\n async initialize(): Promise<void> {\n try {\n await sessionManager.initialize();\n await sharedContextLayer.initialize();\n\n const session = await sessionManager.getOrCreateSession({});\n if (session.database) {\n this.frameManager = new FrameManager(session.database, session.projectId);\n }\n\n // Start coordination monitoring\n this.startCoordinationLoop();\n\n logger.info('Swarm coordinator initialized successfully');\n } catch (error: unknown) {\n logger.error('Failed to initialize swarm coordinator', error as Error);\n throw error;\n }\n }\n\n /**\n * Launch a swarm of agents to work on a complex project\n */\n async launchSwarm(\n projectDescription: string,\n agents: AgentSpecialization[],\n coordination?: SwarmConfiguration\n ): Promise<string> {\n logger.info('Launching swarm', {\n project: projectDescription.substring(0, 100),\n agentCount: agents.length\n });\n\n const swarmId = uuidv4();\n \n try {\n // 1. Validate swarm configuration\n if (agents.length > this.config.maxAgents) {\n throw new Error(`Too many agents requested: ${agents.length} > ${this.config.maxAgents}`);\n }\n\n // 2. Break down project into swarm tasks\n const swarmTasks = await this.decomposeProjectIntoSwarmTasks(projectDescription);\n\n // 3. Initialize specialized agents\n const initializedAgents = await this.initializeSpecializedAgents(agents, swarmTasks);\n\n // 4. Create task allocation plan\n const allocation = await this.allocateTasksToAgents(swarmTasks, initializedAgents);\n\n // 5. Begin swarm execution\n this.swarmState = {\n ...this.swarmState,\n id: swarmId,\n status: 'active',\n activeTaskCount: swarmTasks.length,\n project: projectDescription,\n agents: initializedAgents,\n tasks: swarmTasks,\n allocation\n };\n\n // 6. Start agent execution\n await this.executeSwarmTasks(allocation);\n\n logger.info('Swarm launched successfully', { swarmId, agentCount: initializedAgents.length });\n return swarmId;\n\n } catch (error: unknown) {\n logger.error('Failed to launch swarm', error as Error);\n throw error;\n }\n }\n\n /**\n * Decompose project into tasks suitable for swarm execution\n */\n private async decomposeProjectIntoSwarmTasks(projectDescription: string): Promise<SwarmTask[]> {\n const tasks: SwarmTask[] = [];\n \n // Analyze project complexity and decompose based on patterns\n const complexity = this.analyzeProjectComplexity(projectDescription);\n \n // Pattern 1: Architecture and Planning\n if (complexity.needsArchitecture) {\n tasks.push({\n id: uuidv4(),\n type: 'architecture',\n title: 'System Architecture Design',\n description: 'Design overall system architecture and component relationships',\n priority: 1,\n estimatedEffort: 'high',\n requiredRoles: ['architect', 'system_designer'],\n dependencies: [],\n acceptanceCriteria: [\n 'Architecture diagram created',\n 'Component interfaces defined',\n 'Data flow documented'\n ]\n });\n }\n\n // Pattern 2: Core Implementation Tasks\n const coreFeatures = this.extractCoreFeatures(projectDescription);\n for (const feature of coreFeatures) {\n tasks.push({\n id: uuidv4(),\n type: 'implementation',\n title: `Implement ${feature.name}`,\n description: feature.description,\n priority: 2,\n estimatedEffort: feature.complexity,\n requiredRoles: ['developer', feature.specialization || 'fullstack'],\n dependencies: complexity.needsArchitecture ? [tasks[0].id] : [],\n acceptanceCriteria: feature.criteria\n });\n }\n\n // Pattern 3: Testing and Validation\n if (complexity.needsTesting) {\n tasks.push({\n id: uuidv4(),\n type: 'testing',\n title: 'Comprehensive Testing Suite',\n description: 'Create unit, integration, and end-to-end tests',\n priority: 3,\n estimatedEffort: 'medium',\n requiredRoles: ['qa_engineer', 'test_automation'],\n dependencies: tasks.filter(t => t.type === 'implementation').map(t => t.id),\n acceptanceCriteria: [\n 'Unit tests achieve >90% coverage',\n 'Integration tests pass',\n 'Performance benchmarks met'\n ]\n });\n }\n\n // Pattern 4: Documentation and Polish\n if (complexity.needsDocumentation) {\n tasks.push({\n id: uuidv4(),\n type: 'documentation',\n title: 'Documentation and Examples',\n description: 'Create user documentation, API docs, and usage examples',\n priority: 4,\n estimatedEffort: 'low',\n requiredRoles: ['technical_writer', 'developer'],\n dependencies: [], // Can run in parallel\n acceptanceCriteria: [\n 'README with setup instructions',\n 'API documentation complete',\n 'Usage examples provided'\n ]\n });\n }\n\n return tasks;\n }\n\n /**\n * Initialize specialized agents with role-specific configurations\n */\n private async initializeSpecializedAgents(\n specifications: AgentSpecialization[],\n tasks: SwarmTask[]\n ): Promise<Agent[]> {\n const agents: Agent[] = [];\n\n for (const spec of specifications) {\n const agent: Agent = {\n id: uuidv4(),\n role: spec.role,\n specialization: spec,\n status: 'initializing',\n capabilities: this.defineCapabilities(spec.role),\n workingDirectory: `.swarm/${spec.role}-${Date.now()}`,\n currentTask: null,\n performance: {\n tasksCompleted: 0,\n successRate: 1.0,\n averageTaskTime: 0,\n driftDetected: false,\n lastFreshStart: Date.now()\n },\n coordination: {\n communicationStyle: this.defineCommuncationStyle(spec.role),\n conflictResolution: spec.conflictResolution || 'defer_to_expertise',\n collaborationPreferences: spec.collaborationPreferences || []\n }\n };\n\n // Initialize agent's working environment\n await this.setupAgentEnvironment(agent);\n\n // Configure role-specific prompting strategies\n await this.configureAgentPrompts(agent);\n\n agents.push(agent);\n this.activeAgents.set(agent.id, agent);\n }\n\n logger.info(`Initialized ${agents.length} specialized agents`);\n return agents;\n }\n\n /**\n * Allocate tasks to agents based on specialization and workload\n */\n private async allocateTasksToAgents(\n tasks: SwarmTask[],\n agents: Agent[]\n ): Promise<TaskAllocation> {\n const allocation: TaskAllocation = {\n assignments: new Map(),\n loadBalancing: 'capability_based',\n conflictResolution: this.config.conflictResolutionStrategy\n };\n\n // Sort tasks by priority and dependencies\n const sortedTasks = this.topologicalSort(tasks);\n\n for (const task of sortedTasks) {\n // Find best-suited agents for this task\n const suitableAgents = agents.filter(agent =>\n task.requiredRoles.some(role => this.agentCanHandle(agent, role))\n );\n\n if (suitableAgents.length === 0) {\n logger.warn(`No suitable agents found for task: ${task.title}`);\n continue;\n }\n\n // Select agent based on workload and expertise\n const selectedAgent = this.selectOptimalAgent(suitableAgents, task);\n \n allocation.assignments.set(task.id, {\n agentId: selectedAgent.id,\n taskId: task.id,\n assignedAt: Date.now(),\n estimatedCompletion: Date.now() + this.estimateTaskDuration(task),\n coordination: {\n collaborators: this.findCollaborators(selectedAgent, task, agents),\n reviewers: this.findReviewers(selectedAgent, task, agents)\n }\n });\n\n // Update agent workload\n selectedAgent.currentTask = task.id;\n }\n\n return allocation;\n }\n\n /**\n * Execute swarm tasks with coordination\n */\n private async executeSwarmTasks(allocation: TaskAllocation): Promise<void> {\n const executionPromises: Promise<void>[] = [];\n\n for (const [taskId, assignment] of allocation.assignments) {\n const agent = this.activeAgents.get(assignment.agentId);\n const task = this.swarmState.tasks?.find(t => t.id === taskId);\n\n if (!agent || !task) continue;\n\n // Create execution promise for each agent\n const executionPromise = this.executeAgentTask(agent, task, assignment);\n executionPromises.push(executionPromise);\n }\n\n // Monitor all executions\n await Promise.allSettled(executionPromises);\n }\n\n /**\n * Execute a single agent task with coordination\n */\n private async executeAgentTask(\n agent: Agent,\n task: SwarmTask,\n assignment: any\n ): Promise<void> {\n logger.info(`Agent ${agent.role} starting task: ${task.title}`);\n\n try {\n agent.status = 'active';\n \n // Initialize git workflow for this agent\n await this.gitWorkflowManager.initializeAgentWorkflow(agent, task);\n \n // Create Ralph loop for this agent/task\n const ralph = new RalphStackMemoryBridge({\n baseDir: path.join(agent.workingDirectory, task.id),\n maxIterations: this.calculateMaxIterations(task),\n useStackMemory: true\n });\n\n // Initialize with context from other agents\n const contextualPrompt = await this.synthesizeContextualPrompt(agent, task);\n \n await ralph.initialize({\n task: contextualPrompt,\n criteria: task.acceptanceCriteria.join('\\n')\n });\n\n // Set up coordination hooks\n this.setupAgentCoordination(agent, ralph, assignment);\n\n // Run the task\n await ralph.run();\n\n // Commit agent's work\n await this.gitWorkflowManager.commitAgentWork(agent, task);\n\n // Update performance metrics\n this.updateAgentPerformance(agent, true);\n \n // Merge agent's work back\n await this.gitWorkflowManager.mergeAgentWork(agent, task);\n \n // Notify planners and collaborators\n await this.notifyTaskCompletion(agent, task, true);\n\n agent.status = 'idle';\n logger.info(`Agent ${agent.role} completed task: ${task.title}`);\n\n } catch (error: unknown) {\n logger.error(`Agent ${agent.role} failed task: ${task.title}`, error as Error);\n \n // Update performance metrics\n this.updateAgentPerformance(agent, false);\n \n // Trigger conflict resolution or reassignment\n await this.handleTaskFailure(agent, task, error as Error);\n \n agent.status = 'error';\n }\n }\n\n /**\n * Synthesize contextual prompt incorporating swarm knowledge\n */\n private async synthesizeContextualPrompt(agent: Agent, task: SwarmTask): Promise<string> {\n const basePrompt = task.description;\n const roleSpecificInstructions = this.getRoleSpecificInstructions(agent.role);\n const swarmContext = await this.getSwarmContext(task);\n const coordinationInstructions = this.getCoordinationInstructions(agent);\n\n return `\n${roleSpecificInstructions}\n\nTASK: ${basePrompt}\n\nSWARM CONTEXT:\n${swarmContext}\n\nCOORDINATION GUIDELINES:\n${coordinationInstructions}\n\nRemember:\n- You are part of a swarm working on: ${this.swarmState.project}\n- Other agents are working on related tasks\n- Communicate findings through StackMemory shared context\n- Focus on your specialization while being aware of the bigger picture\n- Detect and avoid pathological behaviors (infinite loops, tunnel vision)\n- Request fresh starts if you detect drift in your approach\n\nACCEPTANCE CRITERIA:\n${task.acceptanceCriteria.map(c => `- ${c}`).join('\\n')}\n`;\n }\n\n /**\n * Start coordination monitoring loop\n */\n private startCoordinationLoop(): void {\n this.coordinationTimer = setInterval(() => {\n this.performCoordinationCycle().catch(error => {\n logger.error('Coordination cycle failed', error as Error);\n });\n }, this.config.coordinationInterval);\n }\n\n /**\n * Perform coordination cycle\n */\n private async performCoordinationCycle(): Promise<void> {\n if (this.swarmState.status !== 'active') return;\n\n logger.debug('Performing coordination cycle');\n\n // 1. Detect pathological behaviors\n if (this.config.pathologicalBehaviorDetection) {\n await this.detectPathologicalBehaviors();\n }\n\n // 2. Check for task completion and wake planners\n if (this.config.enableDynamicPlanning) {\n await this.wakeUpPlanners();\n }\n\n // 3. Resolve conflicts\n await this.resolveActiveConflicts();\n\n // 4. Rebalance workload if needed\n await this.rebalanceWorkload();\n\n // 5. Trigger fresh starts if needed\n await this.triggerFreshStartsIfNeeded();\n\n // 6. Update swarm performance metrics\n this.updateSwarmMetrics();\n }\n\n /**\n * Detect pathological behaviors in agents\n */\n private async detectPathologicalBehaviors(): Promise<void> {\n for (const agent of this.activeAgents.values()) {\n if (agent.status !== 'active') continue;\n\n // Check for drift (repeated failures)\n if (agent.performance.driftDetected) {\n logger.warn(`Drift detected in agent ${agent.role}, triggering fresh start`);\n await this.triggerFreshStart(agent);\n continue;\n }\n\n // Check for tunnel vision (same approach repeated)\n if (await this.detectTunnelVision(agent)) {\n logger.warn(`Tunnel vision detected in agent ${agent.role}, providing alternative approach`);\n await this.provideAlternativeApproach(agent);\n }\n\n // Check for excessive runtime (running too long)\n if (await this.detectExcessiveRuntime(agent)) {\n logger.warn(`Excessive runtime detected in agent ${agent.role}, requesting checkpoint`);\n await this.requestCheckpoint(agent);\n }\n }\n }\n\n /**\n * Wake up planners when their tasks complete\n */\n private async wakeUpPlanners(): Promise<void> {\n for (const [agentId, wakeupCallback] of this.plannerWakeupQueue) {\n const agent = this.activeAgents.get(agentId);\n if (!agent || agent.status !== 'idle') continue;\n\n logger.info(`Waking up planner agent: ${agent.role}`);\n wakeupCallback();\n this.plannerWakeupQueue.delete(agentId);\n }\n }\n\n // Helper methods for role specialization and coordination\n private defineCapabilities(role: AgentRole): string[] {\n const capabilityMap: Record<AgentRole, string[]> = {\n 'architect': ['system_design', 'component_modeling', 'architecture_validation'],\n 'planner': ['task_decomposition', 'dependency_analysis', 'resource_planning'],\n 'developer': ['code_implementation', 'debugging', 'refactoring'],\n 'reviewer': ['code_review', 'quality_assessment', 'best_practice_enforcement'],\n 'tester': ['test_design', 'automation', 'validation'],\n 'optimizer': ['performance_analysis', 'resource_optimization', 'bottleneck_identification'],\n 'documenter': ['technical_writing', 'api_documentation', 'example_creation'],\n 'coordinator': ['task_coordination', 'conflict_resolution', 'progress_tracking']\n };\n\n return capabilityMap[role] || [];\n }\n\n private defineCommuncationStyle(role: AgentRole): string {\n const styleMap: Record<AgentRole, string> = {\n 'architect': 'high_level_design_focused',\n 'planner': 'structured_and_methodical',\n 'developer': 'implementation_focused',\n 'reviewer': 'quality_focused_constructive',\n 'tester': 'validation_focused',\n 'optimizer': 'performance_metrics_focused',\n 'documenter': 'clarity_focused',\n 'coordinator': 'facilitative_and_diplomatic'\n };\n\n return styleMap[role] || 'collaborative';\n }\n\n private getRoleSpecificInstructions(role: AgentRole): string {\n const instructionMap: Record<AgentRole, string> = {\n 'architect': `\nYou are a SYSTEM ARCHITECT. Your role is to:\n- Design high-level system architecture\n- Define component interfaces and relationships\n- Ensure architectural consistency across the project\n- Think in terms of scalability, maintainability, and extensibility\n- Collaborate with developers to validate feasibility`,\n\n 'planner': `\nYou are a PROJECT PLANNER. Your role is to:\n- Break down complex tasks into manageable steps\n- Identify dependencies and critical path\n- Coordinate with other agents on sequencing\n- Wake up when tasks complete to plan next steps\n- Adapt plans based on actual progress`,\n\n 'developer': `\nYou are a SPECIALIZED DEVELOPER. Your role is to:\n- Implement features according to specifications\n- Write clean, maintainable code\n- Follow established patterns and conventions\n- Integrate with other components\n- Communicate implementation details clearly`,\n\n 'reviewer': `\nYou are a CODE REVIEWER. Your role is to:\n- Review code for quality, correctness, and best practices\n- Provide constructive feedback\n- Ensure consistency with project standards\n- Identify potential issues before they become problems\n- Approve or request changes`,\n\n 'tester': `\nYou are a QA ENGINEER. Your role is to:\n- Design comprehensive test strategies\n- Implement automated tests\n- Validate functionality and performance\n- Report bugs clearly and reproducibly\n- Ensure quality gates are met`,\n\n 'optimizer': `\nYou are a PERFORMANCE OPTIMIZER. Your role is to:\n- Analyze system performance and identify bottlenecks\n- Implement optimizations\n- Monitor resource usage\n- Establish performance benchmarks\n- Ensure scalability requirements are met`,\n\n 'documenter': `\nYou are a TECHNICAL WRITER. Your role is to:\n- Create clear, comprehensive documentation\n- Write API documentation and usage examples\n- Ensure documentation stays up-to-date\n- Focus on user experience and clarity\n- Collaborate with developers to understand features`,\n\n 'coordinator': `\nYou are a PROJECT COORDINATOR. Your role is to:\n- Facilitate communication between agents\n- Resolve conflicts and blockers\n- Track overall project progress\n- Ensure no tasks fall through cracks\n- Maintain project timeline and quality`\n };\n\n return instructionMap[role] || 'You are a specialized agent contributing to a larger project.';\n }\n\n // Additional helper methods would be implemented here...\n private analyzeProjectComplexity(description: string): any {\n // Analyze project description to determine decomposition strategy\n return {\n needsArchitecture: description.length > 500 || description.includes('system') || description.includes('platform'),\n needsTesting: true, // Almost all projects need testing\n needsDocumentation: description.includes('API') || description.includes('library'),\n complexity: 'medium'\n };\n }\n\n private extractCoreFeatures(description: string): any[] {\n // Extract core features from project description\n // This would use NLP in a real implementation\n return [{\n name: 'Core Feature',\n description: 'Main functionality implementation',\n complexity: 'medium',\n criteria: ['Feature works correctly', 'Handles edge cases', 'Follows coding standards']\n }];\n }\n\n // Implement remaining helper methods...\n private async setupAgentEnvironment(agent: Agent): Promise<void> {\n // Create working directory for agent\n try {\n await fs.mkdir(agent.workingDirectory, { recursive: true });\n logger.debug(`Created working directory for agent ${agent.id}: ${agent.workingDirectory}`);\n } catch (error: unknown) {\n logger.warn(`Could not create working directory for agent ${agent.id}`, error as Error);\n }\n }\n\n private async configureAgentPrompts(agent: Agent): Promise<void> {\n // Configure agent with role-specific prompts\n // This would be expanded with actual prompt templates\n logger.debug(`Configured prompts for agent ${agent.role}`);\n }\n\n private topologicalSort(tasks: SwarmTask[]): SwarmTask[] {\n // Simple topological sort for task dependencies\n const sorted: SwarmTask[] = [];\n const visited = new Set<string>();\n const visiting = new Set<string>();\n\n const visit = (task: SwarmTask) => {\n if (visited.has(task.id)) return;\n if (visiting.has(task.id)) {\n logger.warn(`Circular dependency detected for task: ${task.id}`);\n return;\n }\n\n visiting.add(task.id);\n\n for (const depId of task.dependencies) {\n const depTask = tasks.find(t => t.id === depId);\n if (depTask) visit(depTask);\n }\n\n visiting.delete(task.id);\n visited.add(task.id);\n sorted.push(task);\n };\n\n tasks.forEach(visit);\n return sorted;\n }\n\n private agentCanHandle(agent: Agent, role: string): boolean {\n return agent.role === role || agent.capabilities.includes(role);\n }\n\n private selectOptimalAgent(agents: Agent[], task: SwarmTask): Agent {\n // Select agent with lowest workload\n return agents.reduce((best, current) => {\n const bestLoad = best.currentTask ? 1 : 0;\n const currentLoad = current.currentTask ? 1 : 0;\n return currentLoad < bestLoad ? current : best;\n });\n }\n\n private estimateTaskDuration(task: SwarmTask): number {\n // Estimate based on complexity\n const durations: Record<string, number> = {\n low: 60000, // 1 minute\n medium: 300000, // 5 minutes\n high: 900000 // 15 minutes\n };\n return durations[task.estimatedEffort] || 300000;\n }\n\n private findCollaborators(agent: Agent, task: SwarmTask, agents: Agent[]): string[] {\n // Find other agents working on related tasks\n return agents\n .filter(a => a.id !== agent.id && a.currentTask)\n .map(a => a.id)\n .slice(0, 2); // Limit to 2 collaborators\n }\n\n private findReviewers(agent: Agent, task: SwarmTask, agents: Agent[]): string[] {\n // Find agents with reviewer role\n return agents\n .filter(a => a.role === 'reviewer' && a.id !== agent.id)\n .map(a => a.id);\n }\n\n private calculateMaxIterations(task: SwarmTask): number {\n // Calculate based on task complexity\n const iterations: Record<string, number> = {\n low: 5,\n medium: 10,\n high: 20\n };\n return iterations[task.estimatedEffort] || 10;\n }\n\n private async getSwarmContext(task: SwarmTask): Promise<string> {\n // Get relevant context from other swarm members\n const relatedTasks = Array.from(this.activeAgents.values())\n .filter(a => a.currentTask)\n .map(a => `- Agent ${a.role} is working on task ${a.currentTask}`)\n .join('\\n');\n \n return relatedTasks || 'No other agents currently active';\n }\n\n private getCoordinationInstructions(agent: Agent): string {\n return `\n- Save progress to shared context regularly\n- Check for updates from collaborators\n- Request help if blocked for more than 2 iterations\n- Report completion immediately`;\n }\n\n private setupAgentCoordination(agent: Agent, ralph: any, assignment: any): void {\n // Setup coordination hooks\n logger.debug(`Setting up coordination for agent ${agent.id}`);\n }\n\n private updateAgentPerformance(agent: Agent, success: boolean): void {\n agent.performance.tasksCompleted++;\n if (!success) {\n agent.performance.successRate = \n (agent.performance.successRate * (agent.performance.tasksCompleted - 1)) / \n agent.performance.tasksCompleted;\n }\n }\n\n private async notifyTaskCompletion(agent: Agent, task: SwarmTask, success: boolean): Promise<void> {\n const event: CoordinationEvent = {\n type: 'task_completion',\n agentId: agent.id,\n timestamp: Date.now(),\n data: {\n taskId: task.id,\n success,\n agent: agent.role\n }\n };\n\n this.swarmState.coordination?.events.push(event);\n logger.info(`Task ${task.id} completed by agent ${agent.role}: ${success ? 'SUCCESS' : 'FAILED'}`);\n }\n\n private async handleTaskFailure(agent: Agent, task: SwarmTask, error: Error): Promise<void> {\n logger.error(`Agent ${agent.role} failed task ${task.id}`, error);\n \n // Record conflict\n if (this.swarmState.coordination) {\n this.swarmState.coordination.conflicts.push({\n type: 'task_failure',\n agents: [agent.id],\n timestamp: Date.now(),\n description: error.message\n });\n }\n }\n\n private async detectTunnelVision(agent: Agent): Promise<boolean> {\n // Check if agent is stuck in same approach\n // Simplified implementation\n return false;\n }\n\n private async provideAlternativeApproach(agent: Agent): Promise<void> {\n logger.info(`Providing alternative approach to agent ${agent.role}`);\n }\n\n private async detectExcessiveRuntime(agent: Agent): Promise<boolean> {\n // Check if agent has been running too long\n if (!agent.performance.lastFreshStart) return false;\n return Date.now() - agent.performance.lastFreshStart > 3600000; // 1 hour\n }\n\n private async requestCheckpoint(agent: Agent): Promise<void> {\n logger.info(`Requesting checkpoint from agent ${agent.role}`);\n }\n\n private async triggerFreshStart(agent: Agent): Promise<void> {\n logger.info(`Triggering fresh start for agent ${agent.role}`);\n agent.performance.lastFreshStart = Date.now();\n agent.performance.driftDetected = false;\n }\n\n private async resolveActiveConflicts(): Promise<void> {\n // Resolve any active conflicts\n if (this.swarmState.coordination?.conflicts.length) {\n logger.debug(`Resolving ${this.swarmState.coordination.conflicts.length} conflicts`);\n }\n }\n\n private async rebalanceWorkload(): Promise<void> {\n // Rebalance workload among agents\n const activeAgents = Array.from(this.activeAgents.values()).filter(a => a.status === 'active');\n if (activeAgents.length > 0) {\n logger.debug(`Rebalancing workload among ${activeAgents.length} active agents`);\n }\n }\n\n private async triggerFreshStartsIfNeeded(): Promise<void> {\n for (const agent of this.activeAgents.values()) {\n if (agent.performance.driftDetected) {\n await this.triggerFreshStart(agent);\n }\n }\n }\n\n private updateSwarmMetrics(): void {\n if (!this.swarmState.performance) return;\n\n const activeCount = Array.from(this.activeAgents.values())\n .filter(a => a.status === 'active').length;\n \n this.swarmState.performance.throughput = \n this.swarmState.completedTaskCount / \n ((Date.now() - this.swarmState.startTime) / 1000);\n \n this.swarmState.performance.efficiency = \n activeCount > 0 ? this.swarmState.completedTaskCount / activeCount : 0;\n }\n\n [Symbol.toStringTag] = 'SwarmCoordinator';\n}\n\n// Export default instance\nexport const swarmCoordinator = new SwarmCoordinator();"],
5
- "mappings": "AAMA,SAAS,MAAM,cAAc;AAC7B,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AAsB5B,MAAM,iBAAiB;AAAA,EACpB;AAAA,EACA,eAAmC,oBAAI,IAAI;AAAA,EAC3C;AAAA,EACA;AAAA,EACA;AAAA,EACA,qBAA8C,oBAAI,IAAI;AAAA,EACtD;AAAA,EAER,YAAY,QAA0C;AACpD,SAAK,SAAS;AAAA,MACZ,WAAW;AAAA,MACX,sBAAsB;AAAA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,KAAK,KAAK,aAAa,OAAO,CAAC,EACtD,OAAO,OAAK,EAAE,WAAW,QAAQ,EAAE;AAEtC,SAAK,WAAW,YAAY,aAC1B,KAAK,WAAW,uBACd,KAAK,IAAI,IAAI,KAAK,WAAW,aAAa;AAE9C,SAAK,WAAW,YAAY,aAC1B,cAAc,IAAI,KAAK,WAAW,qBAAqB,cAAc;AAAA,EACzE;AAAA,EAEA,CAAC,OAAO,WAAW,IAAI;AACzB;AAGO,MAAM,mBAAmB,IAAI,iBAAiB;",
4
+ "sourcesContent": ["/**\n * Swarm Coordination System for StackMemory\n * Orchestrates multiple specialized agents working together on the same codebase\n * Addresses multi-agent coordination challenges with role specialization and dynamic planning\n */\n\nimport { v4 as uuidv4 } from 'uuid';\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\nimport { logger } from '../../../core/monitoring/logger.js';\nimport { FrameManager } from '../../../core/context/frame-manager.js';\nimport { sessionManager } from '../../../core/session/index.js';\nimport { sharedContextLayer } from '../../../core/context/shared-context-layer.js';\nimport { RalphStackMemoryBridge } from '../bridge/ralph-stackmemory-bridge.js';\nimport { GitWorkflowManager } from './git-workflow-manager.js';\nimport {\n SwarmConfiguration,\n Agent,\n AgentRole,\n SwarmTask,\n CoordinationEvent,\n SwarmState,\n TaskAllocation,\n AgentSpecialization\n} from '../types.js';\n\nexport class SwarmCoordinationError extends Error {\n constructor(message: string, public context?: Record<string, unknown>) {\n super(message);\n this.name = 'SwarmCoordinationError';\n }\n}\n\nexport class AgentExecutionError extends Error {\n constructor(message: string, public agentId: string, public taskId: string, public context?: Record<string, unknown>) {\n super(message);\n this.name = 'AgentExecutionError';\n }\n}\n\nexport class TaskAllocationError extends Error {\n constructor(message: string, public taskId: string, public context?: Record<string, unknown>) {\n super(message);\n this.name = 'TaskAllocationError';\n }\n}\n\nexport interface SwarmCoordinatorConfig {\n maxAgents: number;\n coordinationInterval: number;\n driftDetectionThreshold: number;\n freshStartInterval: number;\n conflictResolutionStrategy: 'democratic' | 'hierarchical' | 'expertise';\n enableDynamicPlanning: boolean;\n pathologicalBehaviorDetection: boolean;\n}\n\nexport class SwarmCoordinator {\n private frameManager?: FrameManager;\n private activeAgents: Map<string, Agent> = new Map();\n private swarmState: SwarmState;\n private config: SwarmCoordinatorConfig;\n private coordinationTimer?: NodeJS.Timeout;\n private plannerWakeupQueue: Map<string, () => void> = new Map();\n private gitWorkflowManager: GitWorkflowManager;\n\n constructor(config?: Partial<SwarmCoordinatorConfig>) {\n this.config = {\n maxAgents: 10,\n coordinationInterval: 30000, // 30 seconds\n driftDetectionThreshold: 5, // 5 failed iterations before considering drift\n freshStartInterval: 3600000, // 1 hour\n conflictResolutionStrategy: 'expertise',\n enableDynamicPlanning: true,\n pathologicalBehaviorDetection: true,\n ...config\n };\n\n this.swarmState = {\n id: uuidv4(),\n status: 'idle',\n startTime: Date.now(),\n activeTaskCount: 0,\n completedTaskCount: 0,\n coordination: {\n events: [],\n conflicts: [],\n resolutions: []\n },\n performance: {\n throughput: 0,\n efficiency: 0,\n coordination_overhead: 0\n }\n };\n\n // Initialize git workflow manager\n this.gitWorkflowManager = new GitWorkflowManager({\n enableGitWorkflow: true,\n branchStrategy: 'agent',\n autoCommit: true,\n commitFrequency: 5,\n mergStrategy: 'squash'\n });\n\n logger.info('Swarm coordinator initialized', this.config);\n }\n\n async initialize(): Promise<void> {\n try {\n await sessionManager.initialize();\n await sharedContextLayer.initialize();\n\n const session = await sessionManager.getOrCreateSession({});\n if (session.database) {\n this.frameManager = new FrameManager(session.database, session.projectId);\n }\n\n // Start coordination monitoring\n this.startCoordinationLoop();\n\n logger.info('Swarm coordinator initialized successfully');\n } catch (error: unknown) {\n logger.error('Failed to initialize swarm coordinator', error as Error);\n throw error;\n }\n }\n\n /**\n * Launch a swarm of agents to work on a complex project\n */\n async launchSwarm(\n projectDescription: string,\n agents: AgentSpecialization[],\n coordination?: SwarmConfiguration\n ): Promise<string> {\n logger.info('Launching swarm', {\n project: projectDescription.substring(0, 100),\n agentCount: agents.length\n });\n\n const swarmId = uuidv4();\n \n try {\n // 1. Validate swarm configuration\n if (agents.length > this.config.maxAgents) {\n throw new Error(`Too many agents requested: ${agents.length} > ${this.config.maxAgents}`);\n }\n\n // 2. Break down project into swarm tasks\n const swarmTasks = await this.decomposeProjectIntoSwarmTasks(projectDescription);\n\n // 3. Initialize specialized agents\n const initializedAgents = await this.initializeSpecializedAgents(agents, swarmTasks);\n\n // 4. Create task allocation plan\n const allocation = await this.allocateTasksToAgents(swarmTasks, initializedAgents);\n\n // 5. Begin swarm execution\n this.swarmState = {\n ...this.swarmState,\n id: swarmId,\n status: 'active',\n activeTaskCount: swarmTasks.length,\n project: projectDescription,\n agents: initializedAgents,\n tasks: swarmTasks,\n allocation\n };\n\n // 6. Start agent execution\n await this.executeSwarmTasks(allocation);\n\n logger.info('Swarm launched successfully', { swarmId, agentCount: initializedAgents.length });\n return swarmId;\n\n } catch (error: unknown) {\n logger.error('Failed to launch swarm', error as Error);\n throw error;\n }\n }\n\n /**\n * Decompose project into tasks suitable for swarm execution\n */\n private async decomposeProjectIntoSwarmTasks(projectDescription: string): Promise<SwarmTask[]> {\n const tasks: SwarmTask[] = [];\n \n // Analyze project complexity and decompose based on patterns\n const complexity = this.analyzeProjectComplexity(projectDescription);\n \n // Pattern 1: Architecture and Planning\n if (complexity.needsArchitecture) {\n tasks.push({\n id: uuidv4(),\n type: 'architecture',\n title: 'System Architecture Design',\n description: 'Design overall system architecture and component relationships',\n priority: 1,\n estimatedEffort: 'high',\n requiredRoles: ['architect', 'system_designer'],\n dependencies: [],\n acceptanceCriteria: [\n 'Architecture diagram created',\n 'Component interfaces defined',\n 'Data flow documented'\n ]\n });\n }\n\n // Pattern 2: Core Implementation Tasks\n const coreFeatures = this.extractCoreFeatures(projectDescription);\n for (const feature of coreFeatures) {\n tasks.push({\n id: uuidv4(),\n type: 'implementation',\n title: `Implement ${feature.name}`,\n description: feature.description,\n priority: 2,\n estimatedEffort: feature.complexity,\n requiredRoles: ['developer', feature.specialization || 'fullstack'],\n dependencies: complexity.needsArchitecture ? [tasks[0].id] : [],\n acceptanceCriteria: feature.criteria\n });\n }\n\n // Pattern 3: Testing and Validation\n if (complexity.needsTesting) {\n tasks.push({\n id: uuidv4(),\n type: 'testing',\n title: 'Comprehensive Testing Suite',\n description: 'Create unit, integration, and end-to-end tests',\n priority: 3,\n estimatedEffort: 'medium',\n requiredRoles: ['qa_engineer', 'test_automation'],\n dependencies: tasks.filter(t => t.type === 'implementation').map(t => t.id),\n acceptanceCriteria: [\n 'Unit tests achieve >90% coverage',\n 'Integration tests pass',\n 'Performance benchmarks met'\n ]\n });\n }\n\n // Pattern 4: Documentation and Polish\n if (complexity.needsDocumentation) {\n tasks.push({\n id: uuidv4(),\n type: 'documentation',\n title: 'Documentation and Examples',\n description: 'Create user documentation, API docs, and usage examples',\n priority: 4,\n estimatedEffort: 'low',\n requiredRoles: ['technical_writer', 'developer'],\n dependencies: [], // Can run in parallel\n acceptanceCriteria: [\n 'README with setup instructions',\n 'API documentation complete',\n 'Usage examples provided'\n ]\n });\n }\n\n return tasks;\n }\n\n /**\n * Initialize specialized agents with role-specific configurations\n */\n private async initializeSpecializedAgents(\n specifications: AgentSpecialization[],\n tasks: SwarmTask[]\n ): Promise<Agent[]> {\n const agents: Agent[] = [];\n\n for (const spec of specifications) {\n const agent: Agent = {\n id: uuidv4(),\n role: spec.role,\n specialization: spec,\n status: 'initializing',\n capabilities: this.defineCapabilities(spec.role),\n workingDirectory: `.swarm/${spec.role}-${Date.now()}`,\n currentTask: null,\n performance: {\n tasksCompleted: 0,\n successRate: 1.0,\n averageTaskTime: 0,\n driftDetected: false,\n lastFreshStart: Date.now()\n },\n coordination: {\n communicationStyle: this.defineCommuncationStyle(spec.role),\n conflictResolution: spec.conflictResolution || 'defer_to_expertise',\n collaborationPreferences: spec.collaborationPreferences || []\n }\n };\n\n // Initialize agent's working environment\n await this.setupAgentEnvironment(agent);\n\n // Configure role-specific prompting strategies\n await this.configureAgentPrompts(agent);\n\n agents.push(agent);\n this.activeAgents.set(agent.id, agent);\n }\n\n logger.info(`Initialized ${agents.length} specialized agents`);\n return agents;\n }\n\n /**\n * Allocate tasks to agents based on specialization and workload\n */\n private async allocateTasksToAgents(\n tasks: SwarmTask[],\n agents: Agent[]\n ): Promise<TaskAllocation> {\n const allocation: TaskAllocation = {\n assignments: new Map(),\n loadBalancing: 'capability_based',\n conflictResolution: this.config.conflictResolutionStrategy\n };\n\n // Sort tasks by priority and dependencies\n const sortedTasks = this.topologicalSort(tasks);\n\n for (const task of sortedTasks) {\n // Find best-suited agents for this task\n const suitableAgents = agents.filter(agent =>\n task.requiredRoles.some(role => this.agentCanHandle(agent, role))\n );\n\n if (suitableAgents.length === 0) {\n logger.warn(`No suitable agents found for task: ${task.title}`);\n continue;\n }\n\n // Select agent based on workload and expertise\n const selectedAgent = this.selectOptimalAgent(suitableAgents, task);\n \n allocation.assignments.set(task.id, {\n agentId: selectedAgent.id,\n taskId: task.id,\n assignedAt: Date.now(),\n estimatedCompletion: Date.now() + this.estimateTaskDuration(task),\n coordination: {\n collaborators: this.findCollaborators(selectedAgent, task, agents),\n reviewers: this.findReviewers(selectedAgent, task, agents)\n }\n });\n\n // Update agent workload\n selectedAgent.currentTask = task.id;\n }\n\n return allocation;\n }\n\n /**\n * Execute swarm tasks with coordination\n */\n private async executeSwarmTasks(allocation: TaskAllocation): Promise<void> {\n const executionPromises: Promise<void>[] = [];\n\n for (const [taskId, assignment] of allocation.assignments) {\n const agent = this.activeAgents.get(assignment.agentId);\n const task = this.swarmState.tasks?.find(t => t.id === taskId);\n\n if (!agent || !task) continue;\n\n // Create execution promise for each agent\n const executionPromise = this.executeAgentTask(agent, task, assignment);\n executionPromises.push(executionPromise);\n }\n\n // Monitor all executions\n await Promise.allSettled(executionPromises);\n }\n\n /**\n * Execute a single agent task with coordination\n */\n private async executeAgentTask(\n agent: Agent,\n task: SwarmTask,\n assignment: TaskAllocation['assignments'] extends Map<string, infer T> ? T : any\n ): Promise<void> {\n logger.info(`Agent ${agent.role} starting task: ${task.title}`);\n\n try {\n agent.status = 'active';\n \n // Initialize git workflow for this agent\n await this.gitWorkflowManager.initializeAgentWorkflow(agent, task);\n \n // Create Ralph loop for this agent/task\n const ralph = new RalphStackMemoryBridge({\n baseDir: path.join(agent.workingDirectory, task.id),\n maxIterations: this.calculateMaxIterations(task),\n useStackMemory: true\n });\n\n // Initialize with context from other agents\n const contextualPrompt = await this.synthesizeContextualPrompt(agent, task);\n \n await ralph.initialize({\n task: contextualPrompt,\n criteria: task.acceptanceCriteria.join('\\n')\n });\n\n // Set up coordination hooks\n this.setupAgentCoordination(agent, ralph, assignment);\n\n // Run the task using worker iterations\n let iteration = 1;\n const maxIterations = this.calculateMaxIterations(task);\n \n while (iteration <= maxIterations) {\n try {\n const result = await ralph.runWorkerIteration();\n if (result.isComplete) {\n logger.info(`Task completed in ${iteration} iterations`);\n break;\n }\n iteration++;\n } catch (error: unknown) {\n logger.error(`Iteration ${iteration} failed:`, error as Error);\n if (iteration >= maxIterations) {\n throw error;\n }\n iteration++;\n }\n }\n\n // Commit agent's work\n await this.gitWorkflowManager.commitAgentWork(agent, task);\n\n // Update performance metrics\n this.updateAgentPerformance(agent, true);\n \n // Merge agent's work back\n await this.gitWorkflowManager.mergeAgentWork(agent, task);\n \n // Notify planners and collaborators\n await this.notifyTaskCompletion(agent, task, true);\n\n agent.status = 'idle';\n logger.info(`Agent ${agent.role} completed task: ${task.title}`);\n\n } catch (error: unknown) {\n logger.error(`Agent ${agent.role} failed task: ${task.title}`, error as Error);\n \n // Update performance metrics\n this.updateAgentPerformance(agent, false);\n \n // Trigger conflict resolution or reassignment\n await this.handleTaskFailure(agent, task, error as Error);\n \n agent.status = 'error';\n }\n }\n\n /**\n * Synthesize contextual prompt incorporating swarm knowledge\n */\n private async synthesizeContextualPrompt(agent: Agent, task: SwarmTask): Promise<string> {\n const basePrompt = task.description;\n const roleSpecificInstructions = this.getRoleSpecificInstructions(agent.role);\n const swarmContext = await this.getSwarmContext(task);\n const coordinationInstructions = this.getCoordinationInstructions(agent);\n\n return `\n${roleSpecificInstructions}\n\nTASK: ${basePrompt}\n\nSWARM CONTEXT:\n${swarmContext}\n\nCOORDINATION GUIDELINES:\n${coordinationInstructions}\n\nRemember:\n- You are part of a swarm working on: ${this.swarmState.project}\n- Other agents are working on related tasks\n- Communicate findings through StackMemory shared context\n- Focus on your specialization while being aware of the bigger picture\n- Detect and avoid pathological behaviors (infinite loops, tunnel vision)\n- Request fresh starts if you detect drift in your approach\n\nACCEPTANCE CRITERIA:\n${task.acceptanceCriteria.map(c => `- ${c}`).join('\\n')}\n`;\n }\n\n /**\n * Start coordination monitoring loop\n */\n private startCoordinationLoop(): void {\n this.coordinationTimer = setInterval(() => {\n this.performCoordinationCycle().catch(error => {\n logger.error('Coordination cycle failed', error as Error);\n });\n }, this.config.coordinationInterval);\n }\n\n /**\n * Perform coordination cycle\n */\n private async performCoordinationCycle(): Promise<void> {\n if (this.swarmState.status !== 'active') return;\n\n logger.debug('Performing coordination cycle');\n\n // 1. Detect pathological behaviors\n if (this.config.pathologicalBehaviorDetection) {\n await this.detectPathologicalBehaviors();\n }\n\n // 2. Check for task completion and wake planners\n if (this.config.enableDynamicPlanning) {\n await this.wakeUpPlanners();\n }\n\n // 3. Resolve conflicts\n await this.resolveActiveConflicts();\n\n // 4. Rebalance workload if needed\n await this.rebalanceWorkload();\n\n // 5. Trigger fresh starts if needed\n await this.triggerFreshStartsIfNeeded();\n\n // 6. Update swarm performance metrics\n this.updateSwarmMetrics();\n }\n\n /**\n * Detect pathological behaviors in agents\n */\n private async detectPathologicalBehaviors(): Promise<void> {\n for (const agent of this.activeAgents.values()) {\n if (agent.status !== 'active') continue;\n\n // Check for drift (repeated failures)\n if (agent.performance.driftDetected) {\n logger.warn(`Drift detected in agent ${agent.role}, triggering fresh start`);\n await this.triggerFreshStart(agent);\n continue;\n }\n\n // Check for tunnel vision (same approach repeated)\n if (await this.detectTunnelVision(agent)) {\n logger.warn(`Tunnel vision detected in agent ${agent.role}, providing alternative approach`);\n await this.provideAlternativeApproach(agent);\n }\n\n // Check for excessive runtime (running too long)\n if (await this.detectExcessiveRuntime(agent)) {\n logger.warn(`Excessive runtime detected in agent ${agent.role}, requesting checkpoint`);\n await this.requestCheckpoint(agent);\n }\n }\n }\n\n /**\n * Wake up planners when their tasks complete\n */\n private async wakeUpPlanners(): Promise<void> {\n for (const [agentId, wakeupCallback] of this.plannerWakeupQueue) {\n const agent = this.activeAgents.get(agentId);\n if (!agent || agent.status !== 'idle') continue;\n\n logger.info(`Waking up planner agent: ${agent.role}`);\n wakeupCallback();\n this.plannerWakeupQueue.delete(agentId);\n }\n }\n\n // Helper methods for role specialization and coordination\n private defineCapabilities(role: AgentRole): string[] {\n const capabilityMap: Record<AgentRole, string[]> = {\n 'architect': ['system_design', 'component_modeling', 'architecture_validation'],\n 'planner': ['task_decomposition', 'dependency_analysis', 'resource_planning'],\n 'developer': ['code_implementation', 'debugging', 'refactoring'],\n 'reviewer': ['code_review', 'quality_assessment', 'best_practice_enforcement'],\n 'tester': ['test_design', 'automation', 'validation'],\n 'optimizer': ['performance_analysis', 'resource_optimization', 'bottleneck_identification'],\n 'documenter': ['technical_writing', 'api_documentation', 'example_creation'],\n 'coordinator': ['task_coordination', 'conflict_resolution', 'progress_tracking']\n };\n\n return capabilityMap[role] || [];\n }\n\n private defineCommuncationStyle(role: AgentRole): string {\n const styleMap: Record<AgentRole, string> = {\n 'architect': 'high_level_design_focused',\n 'planner': 'structured_and_methodical',\n 'developer': 'implementation_focused',\n 'reviewer': 'quality_focused_constructive',\n 'tester': 'validation_focused',\n 'optimizer': 'performance_metrics_focused',\n 'documenter': 'clarity_focused',\n 'coordinator': 'facilitative_and_diplomatic'\n };\n\n return styleMap[role] || 'collaborative';\n }\n\n private getRoleSpecificInstructions(role: AgentRole): string {\n const instructionMap: Record<AgentRole, string> = {\n 'architect': `\nYou are a SYSTEM ARCHITECT. Your role is to:\n- Design high-level system architecture\n- Define component interfaces and relationships\n- Ensure architectural consistency across the project\n- Think in terms of scalability, maintainability, and extensibility\n- Collaborate with developers to validate feasibility`,\n\n 'planner': `\nYou are a PROJECT PLANNER. Your role is to:\n- Break down complex tasks into manageable steps\n- Identify dependencies and critical path\n- Coordinate with other agents on sequencing\n- Wake up when tasks complete to plan next steps\n- Adapt plans based on actual progress`,\n\n 'developer': `\nYou are a SPECIALIZED DEVELOPER. Your role is to:\n- Implement features according to specifications\n- Write clean, maintainable code\n- Follow established patterns and conventions\n- Integrate with other components\n- Communicate implementation details clearly`,\n\n 'reviewer': `\nYou are a CODE REVIEWER. Your role is to:\n- Review code for quality, correctness, and best practices\n- Provide constructive feedback\n- Ensure consistency with project standards\n- Identify potential issues before they become problems\n- Approve or request changes`,\n\n 'tester': `\nYou are a QA ENGINEER. Your role is to:\n- Design comprehensive test strategies\n- Implement automated tests\n- Validate functionality and performance\n- Report bugs clearly and reproducibly\n- Ensure quality gates are met`,\n\n 'optimizer': `\nYou are a PERFORMANCE OPTIMIZER. Your role is to:\n- Analyze system performance and identify bottlenecks\n- Implement optimizations\n- Monitor resource usage\n- Establish performance benchmarks\n- Ensure scalability requirements are met`,\n\n 'documenter': `\nYou are a TECHNICAL WRITER. Your role is to:\n- Create clear, comprehensive documentation\n- Write API documentation and usage examples\n- Ensure documentation stays up-to-date\n- Focus on user experience and clarity\n- Collaborate with developers to understand features`,\n\n 'coordinator': `\nYou are a PROJECT COORDINATOR. Your role is to:\n- Facilitate communication between agents\n- Resolve conflicts and blockers\n- Track overall project progress\n- Ensure no tasks fall through cracks\n- Maintain project timeline and quality`\n };\n\n return instructionMap[role] || 'You are a specialized agent contributing to a larger project.';\n }\n\n // Additional helper methods would be implemented here...\n private analyzeProjectComplexity(description: string): any {\n // Analyze project description to determine decomposition strategy\n return {\n needsArchitecture: description.length > 500 || description.includes('system') || description.includes('platform'),\n needsTesting: true, // Almost all projects need testing\n needsDocumentation: description.includes('API') || description.includes('library'),\n complexity: 'medium'\n };\n }\n\n private extractCoreFeatures(description: string): any[] {\n // Extract core features from project description\n // This would use NLP in a real implementation\n return [{\n name: 'Core Feature',\n description: 'Main functionality implementation',\n complexity: 'medium',\n criteria: ['Feature works correctly', 'Handles edge cases', 'Follows coding standards']\n }];\n }\n\n // Implement remaining helper methods...\n private async setupAgentEnvironment(agent: Agent): Promise<void> {\n // Create working directory for agent\n try {\n await fs.mkdir(agent.workingDirectory, { recursive: true });\n logger.debug(`Created working directory for agent ${agent.id}: ${agent.workingDirectory}`);\n } catch (error: unknown) {\n logger.warn(`Could not create working directory for agent ${agent.id}`, error as Error);\n }\n }\n\n private async configureAgentPrompts(agent: Agent): Promise<void> {\n // Configure agent with role-specific prompts\n // This would be expanded with actual prompt templates\n logger.debug(`Configured prompts for agent ${agent.role}`);\n }\n\n private topologicalSort(tasks: SwarmTask[]): SwarmTask[] {\n // Simple topological sort for task dependencies\n const sorted: SwarmTask[] = [];\n const visited = new Set<string>();\n const visiting = new Set<string>();\n\n const visit = (task: SwarmTask) => {\n if (visited.has(task.id)) return;\n if (visiting.has(task.id)) {\n logger.warn(`Circular dependency detected for task: ${task.id}`);\n return;\n }\n\n visiting.add(task.id);\n\n for (const depId of task.dependencies) {\n const depTask = tasks.find(t => t.id === depId);\n if (depTask) visit(depTask);\n }\n\n visiting.delete(task.id);\n visited.add(task.id);\n sorted.push(task);\n };\n\n tasks.forEach(visit);\n return sorted;\n }\n\n private agentCanHandle(agent: Agent, role: string): boolean {\n return agent.role === role || agent.capabilities.includes(role);\n }\n\n private selectOptimalAgent(agents: Agent[], task: SwarmTask): Agent {\n // Select agent with lowest workload\n return agents.reduce((best, current) => {\n const bestLoad = best.currentTask ? 1 : 0;\n const currentLoad = current.currentTask ? 1 : 0;\n return currentLoad < bestLoad ? current : best;\n });\n }\n\n private estimateTaskDuration(task: SwarmTask): number {\n // Estimate based on complexity\n const durations: Record<string, number> = {\n low: 60000, // 1 minute\n medium: 300000, // 5 minutes\n high: 900000 // 15 minutes\n };\n return durations[task.estimatedEffort] || 300000;\n }\n\n private findCollaborators(agent: Agent, task: SwarmTask, agents: Agent[]): string[] {\n // Find other agents working on related tasks\n return agents\n .filter(a => a.id !== agent.id && a.currentTask)\n .map(a => a.id)\n .slice(0, 2); // Limit to 2 collaborators\n }\n\n private findReviewers(agent: Agent, task: SwarmTask, agents: Agent[]): string[] {\n // Find agents with reviewer role\n return agents\n .filter(a => a.role === 'reviewer' && a.id !== agent.id)\n .map(a => a.id);\n }\n\n private calculateMaxIterations(task: SwarmTask): number {\n // Calculate based on task complexity\n const iterations: Record<string, number> = {\n low: 5,\n medium: 10,\n high: 20\n };\n return iterations[task.estimatedEffort] || 10;\n }\n\n private async getSwarmContext(task: SwarmTask): Promise<string> {\n // Get relevant context from other swarm members\n const relatedTasks = Array.from(this.activeAgents.values())\n .filter(a => a.currentTask)\n .map(a => `- Agent ${a.role} is working on task ${a.currentTask}`)\n .join('\\n');\n \n return relatedTasks || 'No other agents currently active';\n }\n\n private getCoordinationInstructions(agent: Agent): string {\n return `\n- Save progress to shared context regularly\n- Check for updates from collaborators\n- Request help if blocked for more than 2 iterations\n- Report completion immediately`;\n }\n\n private setupAgentCoordination(agent: Agent, ralph: any, assignment: any): void {\n // Setup coordination hooks\n logger.debug(`Setting up coordination for agent ${agent.id}`);\n }\n\n private updateAgentPerformance(agent: Agent, success: boolean): void {\n agent.performance.tasksCompleted++;\n if (!success) {\n agent.performance.successRate = \n (agent.performance.successRate * (agent.performance.tasksCompleted - 1)) / \n agent.performance.tasksCompleted;\n }\n }\n\n private async notifyTaskCompletion(agent: Agent, task: SwarmTask, success: boolean): Promise<void> {\n const event: CoordinationEvent = {\n type: 'task_completion',\n agentId: agent.id,\n timestamp: Date.now(),\n data: {\n taskId: task.id,\n success,\n agent: agent.role\n }\n };\n\n this.swarmState.coordination?.events.push(event);\n logger.info(`Task ${task.id} completed by agent ${agent.role}: ${success ? 'SUCCESS' : 'FAILED'}`);\n }\n\n private async handleTaskFailure(agent: Agent, task: SwarmTask, error: Error): Promise<void> {\n logger.error(`Agent ${agent.role} failed task ${task.id}`, error);\n \n // Record conflict\n if (this.swarmState.coordination) {\n this.swarmState.coordination.conflicts.push({\n type: 'task_failure',\n agents: [agent.id],\n timestamp: Date.now(),\n description: error.message\n });\n }\n }\n\n private async detectTunnelVision(agent: Agent): Promise<boolean> {\n // Check if agent is stuck in same approach\n // Simplified implementation\n return false;\n }\n\n private async provideAlternativeApproach(agent: Agent): Promise<void> {\n logger.info(`Providing alternative approach to agent ${agent.role}`);\n }\n\n private async detectExcessiveRuntime(agent: Agent): Promise<boolean> {\n // Check if agent has been running too long\n if (!agent.performance.lastFreshStart) return false;\n return Date.now() - agent.performance.lastFreshStart > 3600000; // 1 hour\n }\n\n private async requestCheckpoint(agent: Agent): Promise<void> {\n logger.info(`Requesting checkpoint from agent ${agent.role}`);\n }\n\n private async triggerFreshStart(agent: Agent): Promise<void> {\n logger.info(`Triggering fresh start for agent ${agent.role}`);\n agent.performance.lastFreshStart = Date.now();\n agent.performance.driftDetected = false;\n }\n\n private async resolveActiveConflicts(): Promise<void> {\n // Resolve any active conflicts\n if (this.swarmState.coordination?.conflicts.length) {\n logger.debug(`Resolving ${this.swarmState.coordination.conflicts.length} conflicts`);\n }\n }\n\n private async rebalanceWorkload(): Promise<void> {\n // Rebalance workload among agents\n const activeAgents = Array.from(this.activeAgents.values()).filter(a => a.status === 'active');\n if (activeAgents.length > 0) {\n logger.debug(`Rebalancing workload among ${activeAgents.length} active agents`);\n }\n }\n\n private async triggerFreshStartsIfNeeded(): Promise<void> {\n for (const agent of this.activeAgents.values()) {\n if (agent.performance.driftDetected) {\n await this.triggerFreshStart(agent);\n }\n }\n }\n\n private updateSwarmMetrics(): void {\n if (!this.swarmState.performance) return;\n\n const activeCount = Array.from(this.activeAgents.values())\n .filter(a => a.status === 'active').length;\n \n this.swarmState.performance.throughput = \n this.swarmState.completedTaskCount / \n ((Date.now() - this.swarmState.startTime) / 1000);\n \n this.swarmState.performance.efficiency = \n activeCount > 0 ? this.swarmState.completedTaskCount / activeCount : 0;\n }\n\n /**\n * Cleanup completed swarms and their resources\n */\n async cleanupCompletedSwarms(): Promise<void> {\n if (this.swarmState.status !== 'completed') {\n return;\n }\n\n try {\n logger.info('Cleaning up completed swarm resources');\n\n // Clear coordination timer\n if (this.coordinationTimer) {\n clearInterval(this.coordinationTimer);\n this.coordinationTimer = undefined;\n }\n\n // Clean up agent working directories\n for (const agent of this.activeAgents.values()) {\n try {\n await fs.rmdir(agent.workingDirectory, { recursive: true });\n logger.debug(`Cleaned up working directory for agent ${agent.id}`);\n } catch (error: unknown) {\n logger.warn(`Could not clean up directory for agent ${agent.id}`, error as Error);\n }\n }\n\n // Clean up git branches\n await this.gitWorkflowManager.coordinateMerges(Array.from(this.activeAgents.values()));\n\n // Clear active agents\n this.activeAgents.clear();\n\n // Reset state\n this.swarmState = {\n id: uuidv4(),\n status: 'idle',\n startTime: Date.now(),\n activeTaskCount: 0,\n completedTaskCount: 0,\n coordination: {\n events: [],\n conflicts: [],\n resolutions: []\n },\n performance: {\n throughput: 0,\n efficiency: 0,\n coordination_overhead: 0\n }\n };\n\n logger.info('Swarm cleanup completed successfully');\n } catch (error: unknown) {\n logger.error('Failed to cleanup completed swarm', error as Error);\n throw new SwarmCoordinationError('Cleanup failed', { swarmId: this.swarmState.id, error });\n }\n }\n\n /**\n * Force cleanup of a swarm (for emergency situations)\n */\n async forceCleanup(): Promise<void> {\n logger.warn('Force cleanup initiated');\n \n try {\n if (this.coordinationTimer) {\n clearInterval(this.coordinationTimer);\n this.coordinationTimer = undefined;\n }\n\n // Force stop all agents\n for (const agent of this.activeAgents.values()) {\n agent.status = 'stopped';\n }\n\n this.swarmState.status = 'stopped';\n await this.cleanupCompletedSwarms();\n } catch (error: unknown) {\n logger.error('Force cleanup failed', error as Error);\n }\n }\n\n /**\n * Get swarm resource usage and cleanup recommendations\n */\n getResourceUsage(): {\n activeAgents: number;\n workingDirectories: string[];\n memoryEstimate: number;\n cleanupRecommended: boolean;\n recommendations: string[];\n } {\n const workingDirs = Array.from(this.activeAgents.values()).map(a => a.workingDirectory);\n const memoryEstimate = this.activeAgents.size * 50; // 50MB per agent estimate\n const isStale = (Date.now() - this.swarmState.startTime) > 3600000; // 1 hour\n const hasCompletedTasks = this.swarmState.completedTaskCount > 0 && this.swarmState.activeTaskCount === 0;\n \n const recommendations: string[] = [];\n let cleanupRecommended = false;\n\n if (isStale) {\n recommendations.push('Swarm has been running for over 1 hour - consider cleanup');\n cleanupRecommended = true;\n }\n\n if (hasCompletedTasks) {\n recommendations.push('All tasks completed - cleanup is recommended');\n cleanupRecommended = true;\n }\n\n if (this.activeAgents.size > 5) {\n recommendations.push('High agent count - monitor resource usage');\n }\n\n return {\n activeAgents: this.activeAgents.size,\n workingDirectories: workingDirs,\n memoryEstimate,\n cleanupRecommended,\n recommendations\n };\n }\n\n [Symbol.toStringTag] = 'SwarmCoordinator';\n}\n\n// Export default instance\nexport const swarmCoordinator = new SwarmCoordinator();"],
5
+ "mappings": "AAMA,SAAS,MAAM,cAAc;AAC7B,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AAY5B,MAAM,+BAA+B,MAAM;AAAA,EAChD,YAAY,SAAwB,SAAmC;AACrE,UAAM,OAAO;AADqB;AAElC,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,4BAA4B,MAAM;AAAA,EAC7C,YAAY,SAAwB,SAAwB,QAAuB,SAAmC;AACpH,UAAM,OAAO;AADqB;AAAwB;AAAuB;AAEjF,SAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAM,4BAA4B,MAAM;AAAA,EAC7C,YAAY,SAAwB,QAAuB,SAAmC;AAC5F,UAAM,OAAO;AADqB;AAAuB;AAEzD,SAAK,OAAO;AAAA,EACd;AACF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UAAM,UAAW,KAAK,IAAI,IAAI,KAAK,WAAW,YAAa;AAC3D,UAAM,oBAAoB,KAAK,WAAW,qBAAqB,KAAK,KAAK,WAAW,oBAAoB;AAExG,UAAM,kBAA4B,CAAC;AACnC,QAAI,qBAAqB;AAEzB,QAAI,SAAS;AACX,sBAAgB,KAAK,2DAA2D;AAChF,2BAAqB;AAAA,IACvB;AAEA,QAAI,mBAAmB;AACrB,sBAAgB,KAAK,8CAA8C;AACnE,2BAAqB;AAAA,IACvB;AAEA,QAAI,KAAK,aAAa,OAAO,GAAG;AAC9B,sBAAgB,KAAK,2CAA2C;AAAA,IAClE;AAEA,WAAO;AAAA,MACL,cAAc,KAAK,aAAa;AAAA,MAChC,oBAAoB;AAAA,MACpB;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EAEA,CAAC,OAAO,WAAW,IAAI;AACzB;AAGO,MAAM,mBAAmB,IAAI,iBAAiB;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackmemoryai/stackmemory",
3
- "version": "0.3.25",
3
+ "version": "0.3.26",
4
4
  "description": "Lossless memory runtime for AI coding tools - organizes context as a call stack instead of linear chat logs, with team collaboration and infinite retention",
5
5
  "engines": {
6
6
  "node": ">=20.0.0",