@stackmemoryai/stackmemory 0.4.2 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/commands/ralph.js +305 -0
- package/dist/cli/commands/ralph.js.map +2 -2
- package/dist/cli/streamlined-cli.js +144 -0
- package/dist/cli/streamlined-cli.js.map +7 -0
- package/dist/core/events/event-bus.js +110 -0
- package/dist/core/events/event-bus.js.map +7 -0
- package/dist/core/plugins/plugin-interface.js +87 -0
- package/dist/core/plugins/plugin-interface.js.map +7 -0
- package/dist/core/storage/simplified-storage.js +328 -0
- package/dist/core/storage/simplified-storage.js.map +7 -0
- package/dist/integrations/claude-code/agent-bridge.js +764 -0
- package/dist/integrations/claude-code/agent-bridge.js.map +7 -0
- package/dist/integrations/claude-code/task-coordinator.js +356 -0
- package/dist/integrations/claude-code/task-coordinator.js.map +7 -0
- package/dist/integrations/ralph/bridge/ralph-stackmemory-bridge.js +33 -11
- package/dist/integrations/ralph/bridge/ralph-stackmemory-bridge.js.map +2 -2
- package/dist/integrations/ralph/monitoring/swarm-registry.js +10 -1
- package/dist/integrations/ralph/monitoring/swarm-registry.js.map +2 -2
- package/dist/integrations/ralph/patterns/compounding-engineering-pattern.js +396 -0
- package/dist/integrations/ralph/patterns/compounding-engineering-pattern.js.map +7 -0
- package/dist/integrations/ralph/patterns/extended-coherence-sessions.js +469 -0
- package/dist/integrations/ralph/patterns/extended-coherence-sessions.js.map +7 -0
- package/dist/integrations/ralph/patterns/oracle-worker-pattern.js +384 -0
- package/dist/integrations/ralph/patterns/oracle-worker-pattern.js.map +7 -0
- package/dist/integrations/ralph/swarm/git-workflow-manager.js +71 -18
- package/dist/integrations/ralph/swarm/git-workflow-manager.js.map +2 -2
- package/dist/integrations/ralph/swarm/swarm-coordinator.js +243 -49
- package/dist/integrations/ralph/swarm/swarm-coordinator.js.map +2 -2
- package/dist/plugins/linear/index.js +166 -0
- package/dist/plugins/linear/index.js.map +7 -0
- package/dist/plugins/loader.js +57 -0
- package/dist/plugins/loader.js.map +7 -0
- package/dist/plugins/plugin-interface.js +67 -0
- package/dist/plugins/plugin-interface.js.map +7 -0
- package/dist/plugins/ralph/simple-ralph-plugin.js +305 -0
- package/dist/plugins/ralph/simple-ralph-plugin.js.map +7 -0
- package/dist/plugins/ralph/use-cases/code-generator.js +151 -0
- package/dist/plugins/ralph/use-cases/code-generator.js.map +7 -0
- package/dist/plugins/ralph/use-cases/test-generator.js +201 -0
- package/dist/plugins/ralph/use-cases/test-generator.js.map +7 -0
- package/package.json +1 -8
- package/scripts/simple-swarm-demo.ts +114 -0
- package/scripts/test-ralph-iterations.ts +164 -0
- package/scripts/test-swarm-fixes.ts +161 -0
- package/scripts/testing/ab-test-runner.ts +4 -2
- package/scripts/testing/collect-metrics.ts +2 -2
- package/scripts/testing/real-performance-test.js +1 -1
- package/scripts/testing/run-effectiveness-tests.sh +1 -1
- package/scripts/testing/simple-effectiveness-test.js +1 -1
|
@@ -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 { SwarmRegistry } from '../monitoring/swarm-registry.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 private registeredSwarmId?: string;\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 // Register with global swarm registry for TUI monitoring\n const registry = SwarmRegistry.getInstance();\n this.registeredSwarmId = registry.registerSwarm(this, `Swarm ${this.swarmState.id.substring(0, 8)}`);\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;AACnC,SAAS,qBAAqB;AAsBvB,MAAM,iBAAiB;AAAA,EACpB;AAAA,EACA,eAAmC,oBAAI,IAAI;AAAA,EAC3C;AAAA,EACA;AAAA,EACA;AAAA,EACA,qBAA8C,oBAAI,IAAI;AAAA,EACtD;AAAA,EACA;AAAA,EAER,YAAY,QAA0C;AACpD,SAAK,SAAS;AAAA,MACZ,WAAW;AAAA,MACX,sBAAsB;AAAA;AAAA,MACtB,yBAAyB;AAAA;AAAA,MACzB,oBAAoB;AAAA;AAAA,MACpB,4BAA4B;AAAA,MAC5B,uBAAuB;AAAA,MACvB,+BAA+B;AAAA,MAC/B,GAAG;AAAA,IACL;AAEA,SAAK,aAAa;AAAA,MAChB,IAAI,OAAO;AAAA,MACX,QAAQ;AAAA,MACR,WAAW,KAAK,IAAI;AAAA,MACpB,iBAAiB;AAAA,MACjB,oBAAoB;AAAA,MACpB,cAAc;AAAA,QACZ,QAAQ,CAAC;AAAA,QACT,WAAW,CAAC;AAAA,QACZ,aAAa,CAAC;AAAA,MAChB;AAAA,MACA,aAAa;AAAA,QACX,YAAY;AAAA,QACZ,YAAY;AAAA,QACZ,uBAAuB;AAAA,MACzB;AAAA,IACF;AAGA,SAAK,qBAAqB,IAAI,mBAAmB;AAAA,MAC/C,mBAAmB;AAAA,MACnB,gBAAgB;AAAA,MAChB,YAAY;AAAA,MACZ,iBAAiB;AAAA,MACjB,cAAc;AAAA,IA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,WAAO,KAAK,oCAAoC,MAAM,IAAI,EAAE;AAC5D,UAAM,YAAY,iBAAiB,KAAK,IAAI;AAC5C,UAAM,YAAY,gBAAgB;AAAA,EACpC;AAAA,EAEA,MAAc,yBAAwC;AAEpD,QAAI,KAAK,WAAW,cAAc,UAAU,QAAQ;AAClD,aAAO,MAAM,aAAa,KAAK,WAAW,aAAa,UAAU,MAAM,YAAY;AAAA,IACrF;AAAA,EACF;AAAA,EAEA,MAAc,oBAAmC;AAE/C,UAAM,eAAe,MAAM,KAAK,KAAK,aAAa,OAAO,CAAC,EAAE,OAAO,OAAK,EAAE,WAAW,QAAQ;AAC7F,QAAI,aAAa,SAAS,GAAG;AAC3B,aAAO,MAAM,8BAA8B,aAAa,MAAM,gBAAgB;AAAA,IAChF;AAAA,EACF;AAAA,EAEA,MAAc,6BAA4C;AACxD,eAAW,SAAS,KAAK,aAAa,OAAO,GAAG;AAC9C,UAAI,MAAM,YAAY,eAAe;AACnC,cAAM,KAAK,kBAAkB,KAAK;AAAA,MACpC;AAAA,IACF;AAAA,EACF;AAAA,EAEQ,qBAA2B;AACjC,QAAI,CAAC,KAAK,WAAW,YAAa;AAElC,UAAM,cAAc,MAAM,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 { SwarmRegistry } from '../monitoring/swarm-registry.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 private registeredSwarmId?: string;\n\n get swarmId(): string | undefined {\n return this.registeredSwarmId;\n }\n\n get agents(): Agent[] {\n return Array.from(this.activeAgents.values());\n }\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(\n session.database,\n session.projectId\n );\n }\n\n // Start coordination monitoring\n this.startCoordinationLoop();\n\n // Register with global swarm registry for TUI monitoring\n const registry = SwarmRegistry.getInstance();\n this.registeredSwarmId = registry.registerSwarm(\n this,\n `Swarm ${this.swarmState.id.substring(0, 8)}`\n );\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(\n `Too many agents requested: ${agents.length} > ${this.config.maxAgents}`\n );\n }\n\n // 2. Break down project into swarm tasks\n const swarmTasks =\n await this.decomposeProjectIntoSwarmTasks(projectDescription);\n\n // 3. Initialize specialized agents\n const initializedAgents = await this.initializeSpecializedAgents(\n agents,\n swarmTasks\n );\n\n // 4. Create task allocation plan\n const allocation = await this.allocateTasksToAgents(\n swarmTasks,\n initializedAgents\n );\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', {\n swarmId,\n agentCount: initializedAgents.length,\n });\n return swarmId;\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(\n projectDescription: string\n ): 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:\n '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\n .filter((t) => t.type === 'implementation')\n .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(\n agent,\n task\n );\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 } catch (error: unknown) {\n logger.error(\n `Agent ${agent.role} failed task: ${task.title}`,\n error as Error\n );\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(\n agent: Agent,\n task: SwarmTask\n ): Promise<string> {\n const basePrompt = task.description;\n const roleSpecificInstructions = this.getRoleSpecificInstructions(\n agent.role\n );\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(\n `Drift detected in agent ${agent.role}, triggering fresh start`\n );\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(\n `Tunnel vision detected in agent ${agent.role}, providing alternative approach`\n );\n await this.provideAlternativeApproach(agent);\n }\n\n // Check for excessive runtime (running too long)\n if (await this.detectExcessiveRuntime(agent)) {\n logger.warn(\n `Excessive runtime detected in agent ${agent.role}, requesting checkpoint`\n );\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 /**\n * Get status of a specific swarm\n */\n getSwarmStatus(swarmId: string): any {\n const registry = SwarmRegistry.getInstance();\n const swarm = registry.getSwarm(swarmId);\n\n if (!swarm) {\n return null;\n }\n\n return {\n id: swarmId,\n state: swarm.status || 'running',\n activeAgents: swarm.agents?.length || 0,\n startTime: swarm.startTime || Date.now(),\n agents: swarm.agents?.map((agent: any) => ({\n role: agent.role,\n status: agent.status || 'active',\n task: agent.task || 'Working',\n })),\n };\n }\n\n /**\n * Get all active swarms\n */\n getAllActiveSwarms(): any[] {\n const registry = SwarmRegistry.getInstance();\n const activeSwarms = registry.listActiveSwarms();\n\n return activeSwarms.map((swarm) => ({\n id: swarm.id,\n description: swarm.description,\n agentCount: swarm.agents?.length || 0,\n status: swarm.status || 'running',\n startTime: swarm.startTime || Date.now(),\n }));\n }\n\n /**\n * Stop a specific swarm gracefully\n */\n async stopSwarm(swarmId?: string): Promise<void> {\n const targetId = swarmId || this.swarmId;\n\n if (!targetId) {\n throw new Error('No swarm ID provided');\n }\n\n logger.info('Stopping swarm', { swarmId: targetId });\n\n // Stop all agents\n for (const agent of this.agents) {\n try {\n await this.stopAgent(agent);\n } catch (error: any) {\n logger.error('Failed to stop agent', {\n agent: agent.id,\n error: error.message,\n });\n }\n }\n\n // Cleanup git workflow if enabled\n if (this.gitWorkflowManager) {\n try {\n await this.gitWorkflowManager.cleanup();\n } catch (error: any) {\n logger.error('Git cleanup failed', { error: error.message });\n }\n }\n\n // Unregister from registry\n const registry = SwarmRegistry.getInstance();\n registry.unregisterSwarm(targetId);\n\n logger.info('Swarm stopped', { swarmId: targetId });\n }\n\n /**\n * Force stop a swarm without saving state\n */\n async forceStopSwarm(swarmId: string): Promise<void> {\n logger.info('Force stopping swarm', { swarmId });\n\n const registry = SwarmRegistry.getInstance();\n\n // Force unregister\n registry.unregisterSwarm(swarmId);\n\n // Kill all agent processes if any\n this.activeAgents.clear();\n\n logger.info('Swarm force stopped', { swarmId });\n }\n\n /**\n * Cleanup all resources\n */\n async cleanup(): Promise<void> {\n logger.info('Cleaning up SwarmCoordinator resources');\n\n // Stop all active swarms\n const activeSwarms = this.getAllActiveSwarms();\n for (const swarm of activeSwarms) {\n try {\n await this.stopSwarm(swarm.id);\n } catch (error: any) {\n logger.error('Failed to stop swarm during cleanup', {\n swarmId: swarm.id,\n error: error.message,\n });\n }\n }\n\n // Clear registries\n const registry = SwarmRegistry.getInstance();\n registry.cleanup();\n\n // Clear agent list\n this.activeAgents.clear();\n\n logger.info('SwarmCoordinator cleanup completed');\n }\n\n /**\n * Stop an individual agent\n */\n private async stopAgent(agent: any): Promise<void> {\n logger.debug('Stopping agent', { agentId: agent.id, role: agent.role });\n\n // Mark agent as stopped\n agent.status = 'stopped';\n\n // Clean up any agent-specific resources\n if (agent.ralphBridge) {\n try {\n await agent.ralphBridge.cleanup();\n } catch (error: any) {\n logger.error('Failed to cleanup agent bridge', {\n error: error.message,\n });\n }\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: [\n 'system_design',\n 'component_modeling',\n 'architecture_validation',\n ],\n planner: [\n 'task_decomposition',\n 'dependency_analysis',\n 'resource_planning',\n ],\n developer: ['code_implementation', 'debugging', 'refactoring'],\n reviewer: [\n 'code_review',\n 'quality_assessment',\n 'best_practice_enforcement',\n ],\n tester: ['test_design', 'automation', 'validation'],\n optimizer: [\n 'performance_analysis',\n 'resource_optimization',\n 'bottleneck_identification',\n ],\n documenter: [\n 'technical_writing',\n 'api_documentation',\n 'example_creation',\n ],\n coordinator: [\n 'task_coordination',\n 'conflict_resolution',\n 'progress_tracking',\n ],\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 (\n instructionMap[role] ||\n 'You are a specialized agent contributing to a larger project.'\n );\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:\n description.length > 500 ||\n description.includes('system') ||\n description.includes('platform'),\n needsTesting: true, // Almost all projects need testing\n needsDocumentation:\n 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 {\n name: 'Core Feature',\n description: 'Main functionality implementation',\n complexity: 'medium',\n criteria: [\n 'Feature works correctly',\n 'Handles edge cases',\n 'Follows coding standards',\n ],\n },\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(\n `Created working directory for agent ${agent.id}: ${agent.workingDirectory}`\n );\n } catch (error: unknown) {\n logger.warn(\n `Could not create working directory for agent ${agent.id}`,\n error as Error\n );\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(\n agent: Agent,\n task: SwarmTask,\n agents: Agent[]\n ): 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(\n agent: Agent,\n task: SwarmTask,\n agents: Agent[]\n ): 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(\n agent: Agent,\n ralph: any,\n assignment: any\n ): 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 *\n (agent.performance.tasksCompleted - 1)) /\n agent.performance.tasksCompleted;\n }\n }\n\n private async notifyTaskCompletion(\n agent: Agent,\n task: SwarmTask,\n success: boolean\n ): 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(\n `Task ${task.id} completed by agent ${agent.role}: ${success ? 'SUCCESS' : 'FAILED'}`\n );\n }\n\n private async handleTaskFailure(\n agent: Agent,\n task: SwarmTask,\n error: Error\n ): 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(\n `Resolving ${this.swarmState.coordination.conflicts.length} conflicts`\n );\n }\n }\n\n private async rebalanceWorkload(): Promise<void> {\n // Rebalance workload among agents\n const activeAgents = Array.from(this.activeAgents.values()).filter(\n (a) => a.status === 'active'\n );\n if (activeAgents.length > 0) {\n logger.debug(\n `Rebalancing workload among ${activeAgents.length} active agents`\n );\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()).filter(\n (a) => a.status === 'active'\n ).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();\n"],
|
|
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;AACnC,SAAS,qBAAqB;AAsBvB,MAAM,iBAAiB;AAAA,EACpB;AAAA,EACA,eAAmC,oBAAI,IAAI;AAAA,EAC3C;AAAA,EACA;AAAA,EACA;AAAA,EACA,qBAA8C,oBAAI,IAAI;AAAA,EACtD;AAAA,EACA;AAAA,EAER,IAAI,UAA8B;AAChC,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,SAAkB;AACpB,WAAO,MAAM,KAAK,KAAK,aAAa,OAAO,CAAC;AAAA,EAC9C;AAAA,EAEA,YAAY,QAA0C;AACpD,SAAK,SAAS;AAAA,MACZ,WAAW;AAAA,MACX,sBAAsB;AAAA;AAAA,MACtB,yBAAyB;AAAA;AAAA,MACzB,oBAAoB;AAAA;AAAA,MACpB,4BAA4B;AAAA,MAC5B,uBAAuB;AAAA,MACvB,+BAA+B;AAAA,MAC/B,GAAG;AAAA,IACL;AAEA,SAAK,aAAa;AAAA,MAChB,IAAI,OAAO;AAAA,MACX,QAAQ;AAAA,MACR,WAAW,KAAK,IAAI;AAAA,MACpB,iBAAiB;AAAA,MACjB,oBAAoB;AAAA,MACpB,cAAc;AAAA,QACZ,QAAQ,CAAC;AAAA,QACT,WAAW,CAAC;AAAA,QACZ,aAAa,CAAC;AAAA,MAChB;AAAA,MACA,aAAa;AAAA,QACX,YAAY;A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,qBAA2B;AACjC,QAAI,CAAC,KAAK,WAAW,YAAa;AAElC,UAAM,cAAc,MAAM,KAAK,KAAK,aAAa,OAAO,CAAC,EAAE;AAAA,MACzD,CAAC,MAAM,EAAE,WAAW;AAAA,IACtB,EAAE;AAEF,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;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { LinearClient } from "@linear/sdk";
|
|
2
|
+
import { logger } from "../../core/monitoring/logger.js";
|
|
3
|
+
class LinearPlugin {
|
|
4
|
+
name = "linear-integration";
|
|
5
|
+
version = "1.0.0";
|
|
6
|
+
description = "Linear task synchronization for StackMemory";
|
|
7
|
+
client = null;
|
|
8
|
+
apiKey = null;
|
|
9
|
+
async initialize() {
|
|
10
|
+
this.apiKey = process.env["LINEAR_API_KEY"] || null;
|
|
11
|
+
if (!this.apiKey) {
|
|
12
|
+
logger.info("Linear plugin: No API key found, running in offline mode");
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
try {
|
|
16
|
+
this.client = new LinearClient({ apiKey: this.apiKey });
|
|
17
|
+
await this.client.me;
|
|
18
|
+
logger.info("Linear plugin initialized successfully");
|
|
19
|
+
} catch (error) {
|
|
20
|
+
logger.warn("Linear plugin: Failed to connect", error);
|
|
21
|
+
this.client = null;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
async shutdown() {
|
|
25
|
+
this.client = null;
|
|
26
|
+
logger.info("Linear plugin shut down");
|
|
27
|
+
}
|
|
28
|
+
registerCommands() {
|
|
29
|
+
return [
|
|
30
|
+
{
|
|
31
|
+
name: "linear-sync",
|
|
32
|
+
description: "Sync tasks with Linear",
|
|
33
|
+
action: this.syncTasks.bind(this),
|
|
34
|
+
options: [
|
|
35
|
+
{
|
|
36
|
+
flag: "--team <id>",
|
|
37
|
+
description: "Linear team ID"
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
flag: "--project <id>",
|
|
41
|
+
description: "Linear project ID"
|
|
42
|
+
}
|
|
43
|
+
]
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
name: "linear-create",
|
|
47
|
+
description: "Create a Linear issue from current context",
|
|
48
|
+
action: this.createIssue.bind(this),
|
|
49
|
+
options: [
|
|
50
|
+
{
|
|
51
|
+
flag: "--title <title>",
|
|
52
|
+
description: "Issue title"
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
flag: "--description <desc>",
|
|
56
|
+
description: "Issue description"
|
|
57
|
+
}
|
|
58
|
+
]
|
|
59
|
+
}
|
|
60
|
+
];
|
|
61
|
+
}
|
|
62
|
+
registerTools() {
|
|
63
|
+
return [
|
|
64
|
+
{
|
|
65
|
+
name: "linear_sync",
|
|
66
|
+
description: "Sync current context with Linear tasks",
|
|
67
|
+
inputSchema: {
|
|
68
|
+
type: "object",
|
|
69
|
+
properties: {
|
|
70
|
+
teamId: { type: "string", description: "Linear team ID" },
|
|
71
|
+
projectId: { type: "string", description: "Linear project ID" }
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
handler: async (input) => {
|
|
75
|
+
return await this.syncTasks(input);
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
name: "linear_create_issue",
|
|
80
|
+
description: "Create a Linear issue",
|
|
81
|
+
inputSchema: {
|
|
82
|
+
type: "object",
|
|
83
|
+
properties: {
|
|
84
|
+
title: { type: "string" },
|
|
85
|
+
description: { type: "string" },
|
|
86
|
+
teamId: { type: "string" }
|
|
87
|
+
},
|
|
88
|
+
required: ["title"]
|
|
89
|
+
},
|
|
90
|
+
handler: async (input) => {
|
|
91
|
+
return await this.createIssue(input);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
];
|
|
95
|
+
}
|
|
96
|
+
onFrameCreated(frame) {
|
|
97
|
+
if (frame.type === "task" && this.client) {
|
|
98
|
+
this.syncFrameToLinear(frame).catch((error) => {
|
|
99
|
+
logger.debug("Failed to sync frame to Linear", error);
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
async syncTasks(options) {
|
|
104
|
+
if (!this.client) {
|
|
105
|
+
return { success: false, message: "Linear not connected" };
|
|
106
|
+
}
|
|
107
|
+
try {
|
|
108
|
+
const issues = await this.client.issues({
|
|
109
|
+
filter: {
|
|
110
|
+
team: { id: { eq: options.teamId } }
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
return {
|
|
114
|
+
success: true,
|
|
115
|
+
synced: issues.nodes.length,
|
|
116
|
+
message: `Synced ${issues.nodes.length} issues from Linear`
|
|
117
|
+
};
|
|
118
|
+
} catch (error) {
|
|
119
|
+
logger.error("Linear sync failed", error);
|
|
120
|
+
return { success: false, error: error.message };
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
async createIssue(options) {
|
|
124
|
+
if (!this.client) {
|
|
125
|
+
return { success: false, message: "Linear not connected" };
|
|
126
|
+
}
|
|
127
|
+
try {
|
|
128
|
+
const issue = await this.client.createIssue({
|
|
129
|
+
title: options.title,
|
|
130
|
+
description: options.description,
|
|
131
|
+
teamId: options.teamId || await this.getDefaultTeamId()
|
|
132
|
+
});
|
|
133
|
+
return {
|
|
134
|
+
success: true,
|
|
135
|
+
issueId: issue.issue?.id,
|
|
136
|
+
url: issue.issue?.url,
|
|
137
|
+
message: `Created Linear issue: ${issue.issue?.identifier}`
|
|
138
|
+
};
|
|
139
|
+
} catch (error) {
|
|
140
|
+
logger.error("Failed to create Linear issue", error);
|
|
141
|
+
return { success: false, error: error.message };
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
async syncFrameToLinear(frame) {
|
|
145
|
+
if (frame.name && frame.content) {
|
|
146
|
+
await this.createIssue({
|
|
147
|
+
title: frame.name,
|
|
148
|
+
description: frame.content
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
async getDefaultTeamId() {
|
|
153
|
+
if (!this.client) throw new Error("Linear not connected");
|
|
154
|
+
const teams = await this.client.teams();
|
|
155
|
+
if (teams.nodes.length > 0) {
|
|
156
|
+
return teams.nodes[0].id;
|
|
157
|
+
}
|
|
158
|
+
throw new Error("No Linear teams found");
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
var linear_default = LinearPlugin;
|
|
162
|
+
export {
|
|
163
|
+
LinearPlugin,
|
|
164
|
+
linear_default as default
|
|
165
|
+
};
|
|
166
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/plugins/linear/index.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Linear Integration Plugin for StackMemory\n * Provides task synchronization with Linear as an optional feature\n */\n\nimport { StackMemoryPlugin, PluginCommand, PluginTool } from '../plugin-interface.js';\nimport { LinearClient } from '@linear/sdk';\nimport { logger } from '../../core/monitoring/logger.js';\n\nexport class LinearPlugin implements StackMemoryPlugin {\n name = 'linear-integration';\n version = '1.0.0';\n description = 'Linear task synchronization for StackMemory';\n \n private client: LinearClient | null = null;\n private apiKey: string | null = null;\n \n async initialize(): Promise<void> {\n this.apiKey = process.env['LINEAR_API_KEY'] || null;\n \n if (!this.apiKey) {\n logger.info('Linear plugin: No API key found, running in offline mode');\n return;\n }\n \n try {\n this.client = new LinearClient({ apiKey: this.apiKey });\n await this.client.me; // Test connection\n logger.info('Linear plugin initialized successfully');\n } catch (error) {\n logger.warn('Linear plugin: Failed to connect', error);\n this.client = null;\n }\n }\n \n async shutdown(): Promise<void> {\n this.client = null;\n logger.info('Linear plugin shut down');\n }\n \n registerCommands(): PluginCommand[] {\n return [\n {\n name: 'linear-sync',\n description: 'Sync tasks with Linear',\n action: this.syncTasks.bind(this),\n options: [\n {\n flag: '--team <id>',\n description: 'Linear team ID',\n },\n {\n flag: '--project <id>',\n description: 'Linear project ID',\n }\n ]\n },\n {\n name: 'linear-create',\n description: 'Create a Linear issue from current context',\n action: this.createIssue.bind(this),\n options: [\n {\n flag: '--title <title>',\n description: 'Issue title',\n },\n {\n flag: '--description <desc>',\n description: 'Issue description',\n }\n ]\n }\n ];\n }\n \n registerTools(): PluginTool[] {\n return [\n {\n name: 'linear_sync',\n description: 'Sync current context with Linear tasks',\n inputSchema: {\n type: 'object',\n properties: {\n teamId: { type: 'string', description: 'Linear team ID' },\n projectId: { type: 'string', description: 'Linear project ID' }\n }\n },\n handler: async (input) => {\n return await this.syncTasks(input);\n }\n },\n {\n name: 'linear_create_issue',\n description: 'Create a Linear issue',\n inputSchema: {\n type: 'object',\n properties: {\n title: { type: 'string' },\n description: { type: 'string' },\n teamId: { type: 'string' }\n },\n required: ['title']\n },\n handler: async (input) => {\n return await this.createIssue(input);\n }\n }\n ];\n }\n \n onFrameCreated(frame: any): void {\n // Auto-sync with Linear when a task frame is created\n if (frame.type === 'task' && this.client) {\n this.syncFrameToLinear(frame).catch(error => {\n logger.debug('Failed to sync frame to Linear', error);\n });\n }\n }\n \n private async syncTasks(options: any): Promise<any> {\n if (!this.client) {\n return { success: false, message: 'Linear not connected' };\n }\n \n try {\n // Basic sync implementation\n const issues = await this.client.issues({\n filter: {\n team: { id: { eq: options.teamId } }\n }\n });\n \n return {\n success: true,\n synced: issues.nodes.length,\n message: `Synced ${issues.nodes.length} issues from Linear`\n };\n } catch (error) {\n logger.error('Linear sync failed', error);\n return { success: false, error: (error as Error).message };\n }\n }\n \n private async createIssue(options: any): Promise<any> {\n if (!this.client) {\n return { success: false, message: 'Linear not connected' };\n }\n \n try {\n const issue = await this.client.createIssue({\n title: options.title,\n description: options.description,\n teamId: options.teamId || (await this.getDefaultTeamId())\n });\n \n return {\n success: true,\n issueId: issue.issue?.id,\n url: issue.issue?.url,\n message: `Created Linear issue: ${issue.issue?.identifier}`\n };\n } catch (error) {\n logger.error('Failed to create Linear issue', error);\n return { success: false, error: (error as Error).message };\n }\n }\n \n private async syncFrameToLinear(frame: any): Promise<void> {\n // Simple frame to Linear sync\n if (frame.name && frame.content) {\n await this.createIssue({\n title: frame.name,\n description: frame.content\n });\n }\n }\n \n private async getDefaultTeamId(): Promise<string> {\n if (!this.client) throw new Error('Linear not connected');\n \n const teams = await this.client.teams();\n if (teams.nodes.length > 0) {\n return teams.nodes[0].id;\n }\n throw new Error('No Linear teams found');\n }\n}\n\n// Export for plugin registration\nexport default LinearPlugin;"],
|
|
5
|
+
"mappings": "AAMA,SAAS,oBAAoB;AAC7B,SAAS,cAAc;AAEhB,MAAM,aAA0C;AAAA,EACrD,OAAO;AAAA,EACP,UAAU;AAAA,EACV,cAAc;AAAA,EAEN,SAA8B;AAAA,EAC9B,SAAwB;AAAA,EAEhC,MAAM,aAA4B;AAChC,SAAK,SAAS,QAAQ,IAAI,gBAAgB,KAAK;AAE/C,QAAI,CAAC,KAAK,QAAQ;AAChB,aAAO,KAAK,0DAA0D;AACtE;AAAA,IACF;AAEA,QAAI;AACF,WAAK,SAAS,IAAI,aAAa,EAAE,QAAQ,KAAK,OAAO,CAAC;AACtD,YAAM,KAAK,OAAO;AAClB,aAAO,KAAK,wCAAwC;AAAA,IACtD,SAAS,OAAO;AACd,aAAO,KAAK,oCAAoC,KAAK;AACrD,WAAK,SAAS;AAAA,IAChB;AAAA,EACF;AAAA,EAEA,MAAM,WAA0B;AAC9B,SAAK,SAAS;AACd,WAAO,KAAK,yBAAyB;AAAA,EACvC;AAAA,EAEA,mBAAoC;AAClC,WAAO;AAAA,MACL;AAAA,QACE,MAAM;AAAA,QACN,aAAa;AAAA,QACb,QAAQ,KAAK,UAAU,KAAK,IAAI;AAAA,QAChC,SAAS;AAAA,UACP;AAAA,YACE,MAAM;AA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OAAO,MAAM;AAAA,QACb,aAAa,MAAM;AAAA,MACrB,CAAC;AAAA,IACH;AAAA,EACF;AAAA,EAEA,MAAc,mBAAoC;AAChD,QAAI,CAAC,KAAK,OAAQ,OAAM,IAAI,MAAM,sBAAsB;AAExD,UAAM,QAAQ,MAAM,KAAK,OAAO,MAAM;AACtC,QAAI,MAAM,MAAM,SAAS,GAAG;AAC1B,aAAO,MAAM,MAAM,CAAC,EAAE;AAAA,IACxB;AACA,UAAM,IAAI,MAAM,uBAAuB;AAAA,EACzC;AACF;AAGA,IAAO,iBAAQ;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { pluginManager } from "./plugin-interface.js";
|
|
2
|
+
import { logger } from "../core/monitoring/logger.js";
|
|
3
|
+
import { existsSync, readFileSync } from "fs";
|
|
4
|
+
import { join } from "path";
|
|
5
|
+
async function loadPlugins() {
|
|
6
|
+
const configPath = join(process.cwd(), ".stackmemory", "plugins.json");
|
|
7
|
+
let enabledPlugins = [];
|
|
8
|
+
if (existsSync(configPath)) {
|
|
9
|
+
try {
|
|
10
|
+
const config = JSON.parse(readFileSync(configPath, "utf-8"));
|
|
11
|
+
enabledPlugins = config.enabled || [];
|
|
12
|
+
} catch (error) {
|
|
13
|
+
logger.warn("Failed to load plugin configuration", error);
|
|
14
|
+
}
|
|
15
|
+
} else {
|
|
16
|
+
enabledPlugins = [];
|
|
17
|
+
if (process.env["ENABLE_LINEAR_PLUGIN"] === "true") {
|
|
18
|
+
enabledPlugins.push("linear");
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
for (const pluginName of enabledPlugins) {
|
|
22
|
+
try {
|
|
23
|
+
await loadPlugin(pluginName);
|
|
24
|
+
} catch (error) {
|
|
25
|
+
logger.warn(`Failed to load plugin ${pluginName}`, error);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
const loadedPlugins = pluginManager.getAllPlugins();
|
|
29
|
+
if (loadedPlugins.length > 0) {
|
|
30
|
+
logger.info(
|
|
31
|
+
`Loaded ${loadedPlugins.length} plugins: ${loadedPlugins.map((p) => p.name).join(", ")}`
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
async function loadPlugin(name) {
|
|
36
|
+
switch (name) {
|
|
37
|
+
case "linear": {
|
|
38
|
+
const { LinearPlugin } = await import("./linear/index.js");
|
|
39
|
+
const plugin = new LinearPlugin();
|
|
40
|
+
await pluginManager.register(plugin);
|
|
41
|
+
break;
|
|
42
|
+
}
|
|
43
|
+
// Future plugins can be added here
|
|
44
|
+
// case 'github': {
|
|
45
|
+
// const { GitHubPlugin } = await import('./github/index.js');
|
|
46
|
+
// await pluginManager.register(new GitHubPlugin());
|
|
47
|
+
// break;
|
|
48
|
+
// }
|
|
49
|
+
default:
|
|
50
|
+
logger.warn(`Unknown plugin: ${name}`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
export {
|
|
54
|
+
loadPlugins,
|
|
55
|
+
pluginManager
|
|
56
|
+
};
|
|
57
|
+
//# sourceMappingURL=loader.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/plugins/loader.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Plugin Loader for StackMemory\n * Automatically loads plugins based on configuration\n */\n\nimport { pluginManager } from './plugin-interface.js';\nimport { logger } from '../core/monitoring/logger.js';\nimport { existsSync, readFileSync } from 'fs';\nimport { join } from 'path';\n\nexport async function loadPlugins(): Promise<void> {\n // Check for plugin configuration\n const configPath = join(process.cwd(), '.stackmemory', 'plugins.json');\n\n let enabledPlugins: string[] = [];\n\n if (existsSync(configPath)) {\n try {\n const config = JSON.parse(readFileSync(configPath, 'utf-8'));\n enabledPlugins = config.enabled || [];\n } catch (error) {\n logger.warn('Failed to load plugin configuration', error);\n }\n } else {\n // Default plugins (none by default, all optional)\n enabledPlugins = [];\n\n // Check environment variables for opt-in plugins\n if (process.env['ENABLE_LINEAR_PLUGIN'] === 'true') {\n enabledPlugins.push('linear');\n }\n }\n\n // Load enabled plugins\n for (const pluginName of enabledPlugins) {\n try {\n await loadPlugin(pluginName);\n } catch (error) {\n logger.warn(`Failed to load plugin ${pluginName}`, error);\n }\n }\n\n const loadedPlugins = pluginManager.getAllPlugins();\n if (loadedPlugins.length > 0) {\n logger.info(\n `Loaded ${loadedPlugins.length} plugins: ${loadedPlugins.map((p) => p.name).join(', ')}`\n );\n }\n}\n\nasync function loadPlugin(name: string): Promise<void> {\n switch (name) {\n case 'linear': {\n const { LinearPlugin } = await import('./linear/index.js');\n const plugin = new LinearPlugin();\n await pluginManager.register(plugin);\n break;\n }\n\n // Future plugins can be added here\n // case 'github': {\n // const { GitHubPlugin } = await import('./github/index.js');\n // await pluginManager.register(new GitHubPlugin());\n // break;\n // }\n\n default:\n logger.warn(`Unknown plugin: ${name}`);\n }\n}\n\nexport { pluginManager };\n"],
|
|
5
|
+
"mappings": "AAKA,SAAS,qBAAqB;AAC9B,SAAS,cAAc;AACvB,SAAS,YAAY,oBAAoB;AACzC,SAAS,YAAY;AAErB,eAAsB,cAA6B;AAEjD,QAAM,aAAa,KAAK,QAAQ,IAAI,GAAG,gBAAgB,cAAc;AAErE,MAAI,iBAA2B,CAAC;AAEhC,MAAI,WAAW,UAAU,GAAG;AAC1B,QAAI;AACF,YAAM,SAAS,KAAK,MAAM,aAAa,YAAY,OAAO,CAAC;AAC3D,uBAAiB,OAAO,WAAW,CAAC;AAAA,IACtC,SAAS,OAAO;AACd,aAAO,KAAK,uCAAuC,KAAK;AAAA,IAC1D;AAAA,EACF,OAAO;AAEL,qBAAiB,CAAC;AAGlB,QAAI,QAAQ,IAAI,sBAAsB,MAAM,QAAQ;AAClD,qBAAe,KAAK,QAAQ;AAAA,IAC9B;AAAA,EACF;AAGA,aAAW,cAAc,gBAAgB;AACvC,QAAI;AACF,YAAM,WAAW,UAAU;AAAA,IAC7B,SAAS,OAAO;AACd,aAAO,KAAK,yBAAyB,UAAU,IAAI,KAAK;AAAA,IAC1D;AAAA,EACF;AAEA,QAAM,gBAAgB,cAAc,cAAc;AAClD,MAAI,cAAc,SAAS,GAAG;AAC5B,WAAO;AAAA,MACL,UAAU,cAAc,MAAM,aAAa,cAAc,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,IAAI,CAAC;AAAA,IACxF;AAAA,EACF;AACF;AAEA,eAAe,WAAW,MAA6B;AACrD,UAAQ,MAAM;AAAA,IACZ,KAAK,UAAU;AACb,YAAM,EAAE,aAAa,IAAI,MAAM,OAAO,mBAAmB;AACzD,YAAM,SAAS,IAAI,aAAa;AAChC,YAAM,cAAc,SAAS,MAAM;AACnC;AAAA,IACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASA;AACE,aAAO,KAAK,mBAAmB,IAAI,EAAE;AAAA,EACzC;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
class PluginManager {
|
|
2
|
+
plugins = /* @__PURE__ */ new Map();
|
|
3
|
+
async register(plugin) {
|
|
4
|
+
if (this.plugins.has(plugin.name)) {
|
|
5
|
+
throw new Error(`Plugin ${plugin.name} already registered`);
|
|
6
|
+
}
|
|
7
|
+
this.plugins.set(plugin.name, plugin);
|
|
8
|
+
if (plugin.initialize) {
|
|
9
|
+
await plugin.initialize();
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
async unregister(name) {
|
|
13
|
+
const plugin = this.plugins.get(name);
|
|
14
|
+
if (!plugin) return;
|
|
15
|
+
if (plugin.shutdown) {
|
|
16
|
+
await plugin.shutdown();
|
|
17
|
+
}
|
|
18
|
+
this.plugins.delete(name);
|
|
19
|
+
}
|
|
20
|
+
getPlugin(name) {
|
|
21
|
+
return this.plugins.get(name);
|
|
22
|
+
}
|
|
23
|
+
getAllPlugins() {
|
|
24
|
+
return Array.from(this.plugins.values());
|
|
25
|
+
}
|
|
26
|
+
// Get all commands from all plugins
|
|
27
|
+
getAllCommands() {
|
|
28
|
+
const commands = [];
|
|
29
|
+
for (const plugin of this.plugins.values()) {
|
|
30
|
+
if (plugin.registerCommands) {
|
|
31
|
+
commands.push(...plugin.registerCommands());
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return commands;
|
|
35
|
+
}
|
|
36
|
+
// Get all tools from all plugins
|
|
37
|
+
getAllTools() {
|
|
38
|
+
const tools = [];
|
|
39
|
+
for (const plugin of this.plugins.values()) {
|
|
40
|
+
if (plugin.registerTools) {
|
|
41
|
+
tools.push(...plugin.registerTools());
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return tools;
|
|
45
|
+
}
|
|
46
|
+
// Emit events to all plugins
|
|
47
|
+
async emitFrameCreated(frame) {
|
|
48
|
+
for (const plugin of this.plugins.values()) {
|
|
49
|
+
if (plugin.onFrameCreated) {
|
|
50
|
+
plugin.onFrameCreated(frame);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
async emitContextSaved(context) {
|
|
55
|
+
for (const plugin of this.plugins.values()) {
|
|
56
|
+
if (plugin.onContextSaved) {
|
|
57
|
+
plugin.onContextSaved(context);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const pluginManager = new PluginManager();
|
|
63
|
+
export {
|
|
64
|
+
PluginManager,
|
|
65
|
+
pluginManager
|
|
66
|
+
};
|
|
67
|
+
//# sourceMappingURL=plugin-interface.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/plugins/plugin-interface.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Plugin Interface for StackMemory\n * Allows optional features to be added without core dependencies\n */\n\nexport interface StackMemoryPlugin {\n name: string;\n version: string;\n description: string;\n\n // Lifecycle hooks\n initialize?(): Promise<void>;\n shutdown?(): Promise<void>;\n\n // Register CLI commands\n registerCommands?(): PluginCommand[];\n\n // Register MCP tools\n registerTools?(): PluginTool[];\n\n // Event handlers\n onFrameCreated?(frame: any): void;\n onFrameUpdated?(frame: any): void;\n onContextSaved?(context: any): void;\n onContextLoaded?(context: any): void;\n}\n\nexport interface PluginCommand {\n name: string;\n description: string;\n action: (options: any) => Promise<void>;\n options?: CommandOption[];\n}\n\nexport interface CommandOption {\n flag: string;\n description: string;\n defaultValue?: any;\n}\n\nexport interface PluginTool {\n name: string;\n description: string;\n inputSchema: any;\n handler: (input: any) => Promise<any>;\n}\n\nexport class PluginManager {\n private plugins: Map<string, StackMemoryPlugin> = new Map();\n\n async register(plugin: StackMemoryPlugin): Promise<void> {\n if (this.plugins.has(plugin.name)) {\n throw new Error(`Plugin ${plugin.name} already registered`);\n }\n\n this.plugins.set(plugin.name, plugin);\n\n if (plugin.initialize) {\n await plugin.initialize();\n }\n }\n\n async unregister(name: string): Promise<void> {\n const plugin = this.plugins.get(name);\n if (!plugin) return;\n\n if (plugin.shutdown) {\n await plugin.shutdown();\n }\n\n this.plugins.delete(name);\n }\n\n getPlugin(name: string): StackMemoryPlugin | undefined {\n return this.plugins.get(name);\n }\n\n getAllPlugins(): StackMemoryPlugin[] {\n return Array.from(this.plugins.values());\n }\n\n // Get all commands from all plugins\n getAllCommands(): PluginCommand[] {\n const commands: PluginCommand[] = [];\n for (const plugin of this.plugins.values()) {\n if (plugin.registerCommands) {\n commands.push(...plugin.registerCommands());\n }\n }\n return commands;\n }\n\n // Get all tools from all plugins\n getAllTools(): PluginTool[] {\n const tools: PluginTool[] = [];\n for (const plugin of this.plugins.values()) {\n if (plugin.registerTools) {\n tools.push(...plugin.registerTools());\n }\n }\n return tools;\n }\n\n // Emit events to all plugins\n async emitFrameCreated(frame: any): Promise<void> {\n for (const plugin of this.plugins.values()) {\n if (plugin.onFrameCreated) {\n plugin.onFrameCreated(frame);\n }\n }\n }\n\n async emitContextSaved(context: any): Promise<void> {\n for (const plugin of this.plugins.values()) {\n if (plugin.onContextSaved) {\n plugin.onContextSaved(context);\n }\n }\n }\n}\n\n// Singleton instance\nexport const pluginManager = new PluginManager();\n"],
|
|
5
|
+
"mappings": "AA+CO,MAAM,cAAc;AAAA,EACjB,UAA0C,oBAAI,IAAI;AAAA,EAE1D,MAAM,SAAS,QAA0C;AACvD,QAAI,KAAK,QAAQ,IAAI,OAAO,IAAI,GAAG;AACjC,YAAM,IAAI,MAAM,UAAU,OAAO,IAAI,qBAAqB;AAAA,IAC5D;AAEA,SAAK,QAAQ,IAAI,OAAO,MAAM,MAAM;AAEpC,QAAI,OAAO,YAAY;AACrB,YAAM,OAAO,WAAW;AAAA,IAC1B;AAAA,EACF;AAAA,EAEA,MAAM,WAAW,MAA6B;AAC5C,UAAM,SAAS,KAAK,QAAQ,IAAI,IAAI;AACpC,QAAI,CAAC,OAAQ;AAEb,QAAI,OAAO,UAAU;AACnB,YAAM,OAAO,SAAS;AAAA,IACxB;AAEA,SAAK,QAAQ,OAAO,IAAI;AAAA,EAC1B;AAAA,EAEA,UAAU,MAA6C;AACrD,WAAO,KAAK,QAAQ,IAAI,IAAI;AAAA,EAC9B;AAAA,EAEA,gBAAqC;AACnC,WAAO,MAAM,KAAK,KAAK,QAAQ,OAAO,CAAC;AAAA,EACzC;AAAA;AAAA,EAGA,iBAAkC;AAChC,UAAM,WAA4B,CAAC;AACnC,eAAW,UAAU,KAAK,QAAQ,OAAO,GAAG;AAC1C,UAAI,OAAO,kBAAkB;AAC3B,iBAAS,KAAK,GAAG,OAAO,iBAAiB,CAAC;AAAA,MAC5C;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,cAA4B;AAC1B,UAAM,QAAsB,CAAC;AAC7B,eAAW,UAAU,KAAK,QAAQ,OAAO,GAAG;AAC1C,UAAI,OAAO,eAAe;AACxB,cAAM,KAAK,GAAG,OAAO,cAAc,CAAC;AAAA,MACtC;AAAA,IACF;AACA,WAAO;AAAA,EACT;AA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