@stackmemoryai/stackmemory 0.3.21 → 0.3.24

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.
Files changed (66) hide show
  1. package/dist/cli/commands/linear-unified.js +2 -3
  2. package/dist/cli/commands/linear-unified.js.map +2 -2
  3. package/dist/cli/commands/ralph.js +294 -0
  4. package/dist/cli/commands/ralph.js.map +7 -0
  5. package/dist/cli/commands/tasks.js +1 -1
  6. package/dist/cli/commands/tasks.js.map +2 -2
  7. package/dist/cli/index.js +2 -0
  8. package/dist/cli/index.js.map +2 -2
  9. package/dist/integrations/mcp/handlers/code-execution-handlers.js +262 -0
  10. package/dist/integrations/mcp/handlers/code-execution-handlers.js.map +7 -0
  11. package/dist/integrations/mcp/tool-definitions-code.js +121 -0
  12. package/dist/integrations/mcp/tool-definitions-code.js.map +7 -0
  13. package/dist/integrations/ralph/bridge/ralph-stackmemory-bridge.js +586 -0
  14. package/dist/integrations/ralph/bridge/ralph-stackmemory-bridge.js.map +7 -0
  15. package/dist/integrations/ralph/context/context-budget-manager.js +297 -0
  16. package/dist/integrations/ralph/context/context-budget-manager.js.map +7 -0
  17. package/dist/integrations/ralph/context/stackmemory-context-loader.js +356 -0
  18. package/dist/integrations/ralph/context/stackmemory-context-loader.js.map +7 -0
  19. package/dist/integrations/ralph/index.js +14 -0
  20. package/dist/integrations/ralph/index.js.map +7 -0
  21. package/dist/integrations/ralph/learning/pattern-learner.js +397 -0
  22. package/dist/integrations/ralph/learning/pattern-learner.js.map +7 -0
  23. package/dist/integrations/ralph/lifecycle/iteration-lifecycle.js +444 -0
  24. package/dist/integrations/ralph/lifecycle/iteration-lifecycle.js.map +7 -0
  25. package/dist/integrations/ralph/orchestration/multi-loop-orchestrator.js +459 -0
  26. package/dist/integrations/ralph/orchestration/multi-loop-orchestrator.js.map +7 -0
  27. package/dist/integrations/ralph/performance/performance-optimizer.js +354 -0
  28. package/dist/integrations/ralph/performance/performance-optimizer.js.map +7 -0
  29. package/dist/integrations/ralph/ralph-integration-demo.js +178 -0
  30. package/dist/integrations/ralph/ralph-integration-demo.js.map +7 -0
  31. package/dist/integrations/ralph/state/state-reconciler.js +400 -0
  32. package/dist/integrations/ralph/state/state-reconciler.js.map +7 -0
  33. package/dist/integrations/ralph/swarm/swarm-coordinator.js +487 -0
  34. package/dist/integrations/ralph/swarm/swarm-coordinator.js.map +7 -0
  35. package/dist/integrations/ralph/types.js +1 -0
  36. package/dist/integrations/ralph/types.js.map +7 -0
  37. package/dist/integrations/ralph/visualization/ralph-debugger.js +581 -0
  38. package/dist/integrations/ralph/visualization/ralph-debugger.js.map +7 -0
  39. package/dist/servers/railway/index.js +98 -92
  40. package/dist/servers/railway/index.js.map +3 -3
  41. package/package.json +1 -2
  42. package/scripts/claude-sm-autostart.js +1 -1
  43. package/scripts/clean-linear-backlog.js +2 -2
  44. package/scripts/debug-linear-update.js +1 -1
  45. package/scripts/debug-railway-build.js +87 -0
  46. package/scripts/delete-linear-tasks.js +2 -2
  47. package/scripts/deploy-ralph-swarm.sh +365 -0
  48. package/scripts/install-code-execution-hooks.sh +96 -0
  49. package/scripts/linear-task-review.js +1 -1
  50. package/scripts/ralph-integration-test.js +274 -0
  51. package/scripts/ralph-loop-implementation.js +404 -0
  52. package/scripts/swarm-monitor.js +509 -0
  53. package/scripts/sync-and-clean-tasks.js +1 -1
  54. package/scripts/sync-linear-graphql.js +3 -3
  55. package/scripts/sync-linear-tasks.js +1 -1
  56. package/scripts/test-code-execution.js +143 -0
  57. package/scripts/test-parallel-swarms.js +443 -0
  58. package/scripts/testing/ralph-cli-test.js +88 -0
  59. package/scripts/testing/ralph-integration-validation.js +727 -0
  60. package/scripts/testing/ralph-swarm-test-scenarios.js +613 -0
  61. package/scripts/update-linear-tasks-fixed.js +1 -1
  62. package/scripts/validate-railway-deployment.js +137 -0
  63. package/templates/claude-hooks/hook-config.json +59 -0
  64. package/templates/claude-hooks/pre-tool-use +189 -0
  65. package/dist/servers/railway/minimal.js +0 -91
  66. package/dist/servers/railway/minimal.js.map +0 -7
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/integrations/ralph/context/stackmemory-context-loader.ts"],
4
+ "sourcesContent": ["/**\n * StackMemory Context Loader for Ralph Loops\n * Provides intelligent context loading with historical pattern recognition\n */\n\nimport { logger } from '../../../core/monitoring/logger.js';\nimport { FrameManager } from '../../../core/context/frame-manager.js';\nimport { sharedContextLayer } from '../../../core/context/shared-context-layer.js';\nimport { ContextRetriever } from '../../../core/retrieval/context-retriever.js';\nimport { sessionManager } from '../../../core/session/index.js';\nimport { ContextBudgetManager } from './context-budget-manager.js';\nimport { \n RalphContextRequest, \n RalphContextResponse, \n HistoricalPattern,\n TaskSimilarity,\n ContextSource\n} from '../types.js';\n\nexport interface StackMemoryContextConfig {\n maxTokens: number;\n lookbackDays: number;\n similarityThreshold: number;\n patternDetectionEnabled: boolean;\n includeFailedAttempts: boolean;\n crossSessionSearch: boolean;\n}\n\nexport class StackMemoryContextLoader {\n private frameManager?: FrameManager;\n private contextRetriever?: ContextRetriever;\n private budgetManager: ContextBudgetManager;\n private config: StackMemoryContextConfig;\n\n constructor(config?: Partial<StackMemoryContextConfig>) {\n this.config = {\n maxTokens: 3200, // Leave room for task description\n lookbackDays: 30,\n similarityThreshold: 0.7,\n patternDetectionEnabled: true,\n includeFailedAttempts: true,\n crossSessionSearch: true,\n ...config\n };\n \n this.budgetManager = new ContextBudgetManager({\n maxTokens: this.config.maxTokens,\n priorityWeights: {\n task: 0.15,\n recentWork: 0.30,\n patterns: 0.25,\n decisions: 0.20,\n dependencies: 0.10\n }\n });\n\n logger.info('StackMemory context loader initialized', {\n maxTokens: this.config.maxTokens,\n lookbackDays: this.config.lookbackDays,\n patternDetection: this.config.patternDetectionEnabled\n });\n }\n\n async initialize(): Promise<void> {\n try {\n // Initialize StackMemory components\n await sessionManager.initialize();\n await sharedContextLayer.initialize();\n\n // Get current session\n const session = await sessionManager.getOrCreateSession({});\n \n if (session.database) {\n this.frameManager = new FrameManager(session.database, session.projectId);\n this.contextRetriever = new ContextRetriever(session.database);\n }\n\n logger.info('Context loader initialized successfully');\n } catch (error: unknown) {\n logger.error('Failed to initialize context loader', error as Error);\n throw error;\n }\n }\n\n /**\n * Load context for Ralph loop initialization\n */\n async loadInitialContext(request: RalphContextRequest): Promise<RalphContextResponse> {\n logger.info('Loading initial context for Ralph loop', {\n task: request.task.substring(0, 100),\n usePatterns: request.usePatterns,\n useSimilarTasks: request.useSimilarTasks\n });\n\n const sources: ContextSource[] = [];\n let totalTokens = 0;\n\n try {\n // 1. Find similar tasks if requested\n if (request.useSimilarTasks) {\n const similarTasks = await this.findSimilarTasks(request.task);\n if (similarTasks.length > 0) {\n const tasksContext = await this.extractTaskContext(similarTasks);\n sources.push({\n type: 'similar_tasks',\n weight: 0.3,\n content: tasksContext,\n tokens: this.budgetManager.estimateTokens(tasksContext)\n });\n totalTokens += sources[sources.length - 1].tokens;\n }\n }\n\n // 2. Extract relevant patterns if requested\n if (request.usePatterns) {\n const patterns = await this.extractRelevantPatterns(request.task);\n if (patterns.length > 0) {\n const patternsContext = await this.formatPatterns(patterns);\n sources.push({\n type: 'historical_patterns',\n weight: 0.25,\n content: patternsContext,\n tokens: this.budgetManager.estimateTokens(patternsContext)\n });\n totalTokens += sources[sources.length - 1].tokens;\n }\n }\n\n // 3. Load recent decisions and learnings\n const decisions = await this.loadRecentDecisions();\n if (decisions.length > 0) {\n const decisionsContext = this.formatDecisions(decisions);\n sources.push({\n type: 'recent_decisions',\n weight: 0.2,\n content: decisionsContext,\n tokens: this.budgetManager.estimateTokens(decisionsContext)\n });\n totalTokens += sources[sources.length - 1].tokens;\n }\n\n // 4. Load project-specific context\n const projectContext = await this.loadProjectContext(request.task);\n if (projectContext) {\n sources.push({\n type: 'project_context',\n weight: 0.15,\n content: projectContext,\n tokens: this.budgetManager.estimateTokens(projectContext)\n });\n totalTokens += sources[sources.length - 1].tokens;\n }\n\n // 5. Apply budget constraints and synthesize\n const budgetedSources = this.budgetManager.allocateBudget({ sources });\n const synthesizedContext = this.synthesizeContext(budgetedSources.sources);\n\n logger.info('Context loaded successfully', {\n totalSources: sources.length,\n totalTokens,\n budgetedTokens: budgetedSources.sources.reduce((sum, s) => sum + s.tokens, 0)\n });\n\n return {\n context: synthesizedContext,\n sources: budgetedSources.sources,\n metadata: {\n totalTokens: budgetedSources.sources.reduce((sum, s) => sum + s.tokens, 0),\n sourcesCount: budgetedSources.sources.length,\n patterns: request.usePatterns ? patterns : [],\n similarTasks: request.useSimilarTasks ? similarTasks : []\n }\n };\n\n } catch (error: unknown) {\n logger.error('Failed to load context', error as Error);\n throw error;\n }\n }\n\n /**\n * Find similar tasks from StackMemory history\n */\n private async findSimilarTasks(taskDescription: string): Promise<TaskSimilarity[]> {\n if (!this.frameManager || !this.contextRetriever) {\n return [];\n }\n\n try {\n // Search for similar task frames\n const searchResults = await this.contextRetriever.search(taskDescription, {\n maxResults: 10,\n types: ['task', 'subtask'],\n timeFilter: {\n days: this.config.lookbackDays\n }\n });\n\n const similarities: TaskSimilarity[] = [];\n\n for (const result of searchResults) {\n // Calculate similarity score\n const similarity = this.calculateTaskSimilarity(taskDescription, result.content);\n \n if (similarity >= this.config.similarityThreshold) {\n similarities.push({\n frameId: result.frameId,\n task: result.content,\n similarity,\n outcome: await this.determineTaskOutcome(result.frameId),\n createdAt: result.timestamp,\n sessionId: result.sessionId || 'unknown'\n });\n }\n }\n\n // Sort by similarity and recent success\n return similarities\n .sort((a, b) => {\n // Prioritize successful outcomes and higher similarity\n const aScore = a.similarity * (a.outcome === 'success' ? 1.2 : 1.0);\n const bScore = b.similarity * (b.outcome === 'success' ? 1.2 : 1.0);\n return bScore - aScore;\n })\n .slice(0, 5); // Top 5 most relevant\n\n } catch (error: unknown) {\n logger.error('Failed to find similar tasks', error as Error);\n return [];\n }\n }\n\n /**\n * Extract relevant patterns from historical data\n */\n private async extractRelevantPatterns(taskDescription: string): Promise<HistoricalPattern[]> {\n try {\n const context = await sharedContextLayer.getSharedContext();\n if (!context) return [];\n\n const relevantPatterns: HistoricalPattern[] = [];\n\n // Filter patterns by relevance to current task\n for (const pattern of context.globalPatterns) {\n const relevance = this.calculatePatternRelevance(taskDescription, pattern.pattern);\n \n if (relevance >= 0.5) {\n relevantPatterns.push({\n pattern: pattern.pattern,\n type: pattern.type,\n frequency: pattern.frequency,\n lastSeen: pattern.lastSeen,\n relevance,\n resolution: pattern.resolution,\n examples: await this.getPatternExamples(pattern.pattern)\n });\n }\n }\n\n // Sort by relevance and frequency\n return relevantPatterns\n .sort((a, b) => (b.relevance * Math.log(b.frequency + 1)) - (a.relevance * Math.log(a.frequency + 1)))\n .slice(0, 8); // Top 8 most relevant patterns\n\n } catch (error: unknown) {\n logger.error('Failed to extract patterns', error as Error);\n return [];\n }\n }\n\n /**\n * Load recent decisions that might be relevant\n */\n private async loadRecentDecisions(): Promise<any[]> {\n try {\n const context = await sharedContextLayer.getSharedContext();\n if (!context) return [];\n\n // Get recent successful decisions\n const cutoff = Date.now() - (7 * 24 * 60 * 60 * 1000); // Last 7 days\n \n return context.decisionLog\n .filter(d => d.timestamp >= cutoff && d.outcome === 'success')\n .sort((a, b) => b.timestamp - a.timestamp)\n .slice(0, 5);\n\n } catch (error: unknown) {\n logger.error('Failed to load recent decisions', error as Error);\n return [];\n }\n }\n\n /**\n * Load project-specific context\n */\n private async loadProjectContext(taskDescription: string): Promise<string | null> {\n try {\n if (!this.contextRetriever) return null;\n\n // Search for project-relevant information\n const projectInfo = await this.contextRetriever.search(taskDescription, {\n maxResults: 3,\n types: ['task'],\n projectSpecific: true\n });\n\n if (projectInfo.length === 0) return null;\n\n const contextParts: string[] = [];\n \n for (const info of projectInfo) {\n contextParts.push(`Project context: ${info.content}`);\n }\n\n return contextParts.join('\\n\\n');\n\n } catch (error: unknown) {\n logger.error('Failed to load project context', error as Error);\n return null;\n }\n }\n\n /**\n * Calculate similarity between task descriptions\n */\n private calculateTaskSimilarity(task1: string, task2: string): number {\n // Simple similarity calculation - in production would use embeddings\n const words1 = new Set(task1.toLowerCase().split(/\\s+/));\n const words2 = new Set(task2.toLowerCase().split(/\\s+/));\n \n const intersection = new Set([...words1].filter(x => words2.has(x)));\n const union = new Set([...words1, ...words2]);\n \n return intersection.size / union.size;\n }\n\n /**\n * Calculate pattern relevance to current task\n */\n private calculatePatternRelevance(taskDescription: string, pattern: string): number {\n // Simple keyword matching - in production would use semantic analysis\n const taskWords = taskDescription.toLowerCase().split(/\\s+/);\n const patternWords = pattern.toLowerCase().split(/\\s+/);\n \n let matches = 0;\n for (const word of taskWords) {\n if (patternWords.some(p => p.includes(word) || word.includes(p))) {\n matches++;\n }\n }\n \n return matches / taskWords.length;\n }\n\n /**\n * Extract context from similar tasks\n */\n private async extractTaskContext(similarities: TaskSimilarity[]): Promise<string> {\n const contextParts: string[] = [];\n \n contextParts.push('Similar tasks from history:');\n \n for (const sim of similarities) {\n contextParts.push(`\nTask: ${sim.task}\nOutcome: ${sim.outcome}\nSimilarity: ${Math.round(sim.similarity * 100)}%\n${sim.outcome === 'success' ? '\u2705 Successfully completed' : '\u274C Had issues'}\n `.trim());\n }\n \n return contextParts.join('\\n\\n');\n }\n\n /**\n * Format patterns for context inclusion\n */\n private async formatPatterns(patterns: HistoricalPattern[]): Promise<string> {\n const contextParts: string[] = [];\n \n contextParts.push('Relevant patterns from experience:');\n \n for (const pattern of patterns) {\n contextParts.push(`\nPattern: ${pattern.pattern}\nType: ${pattern.type}\nFrequency: ${pattern.frequency} occurrences\n${pattern.resolution ? `Resolution: ${pattern.resolution}` : ''}\nRelevance: ${Math.round(pattern.relevance * 100)}%\n `.trim());\n }\n \n return contextParts.join('\\n\\n');\n }\n\n /**\n * Format decisions for context inclusion\n */\n private formatDecisions(decisions: any[]): string {\n const contextParts: string[] = [];\n \n contextParts.push('Recent successful decisions:');\n \n for (const decision of decisions) {\n contextParts.push(`\nDecision: ${decision.decision}\nReasoning: ${decision.reasoning}\nDate: ${new Date(decision.timestamp).toLocaleDateString()}\n `.trim());\n }\n \n return contextParts.join('\\n\\n');\n }\n\n /**\n * Synthesize all context sources into coherent input\n */\n private synthesizeContext(sources: ContextSource[]): string {\n if (sources.length === 0) {\n return 'No relevant historical context found.';\n }\n\n const contextParts: string[] = [];\n \n contextParts.push('Context from StackMemory:');\n \n // Sort by weight (importance)\n const sortedSources = sources.sort((a, b) => b.weight - a.weight);\n \n for (const source of sortedSources) {\n contextParts.push(`\\n--- ${source.type.replace('_', ' ').toUpperCase()} ---`);\n contextParts.push(source.content);\n }\n \n contextParts.push('\\nUse this context to inform your approach to the current task.');\n \n return contextParts.join('\\n');\n }\n\n /**\n * Determine task outcome from frame history\n */\n private async determineTaskOutcome(frameId: string): Promise<'success' | 'failure' | 'unknown'> {\n try {\n if (!this.frameManager) return 'unknown';\n \n const frame = await this.frameManager.getFrame(frameId);\n if (!frame) return 'unknown';\n \n // Simple heuristic - check if frame was properly closed\n if (frame.state === 'closed' && frame.outputs) {\n return 'success';\n }\n \n return frame.state === 'closed' ? 'failure' : 'unknown';\n \n } catch {\n return 'unknown';\n }\n }\n\n /**\n * Get examples of a specific pattern\n */\n private async getPatternExamples(pattern: string): Promise<string[]> {\n // Would search for concrete examples of this pattern\n // For now, return empty array\n return [];\n }\n}\n\n// Export default instance\nexport const stackMemoryContextLoader = new StackMemoryContextLoader();"],
5
+ "mappings": "AAKA,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC,SAAS,wBAAwB;AACjC,SAAS,sBAAsB;AAC/B,SAAS,4BAA4B;AAkB9B,MAAM,yBAAyB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAER,YAAY,QAA4C;AACtD,SAAK,SAAS;AAAA,MACZ,WAAW;AAAA;AAAA,MACX,cAAc;AAAA,MACd,qBAAqB;AAAA,MACrB,yBAAyB;AAAA,MACzB,uBAAuB;AAAA,MACvB,oBAAoB;AAAA,MAC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emory-bridge.js";
2
+ import { ContextBudgetManager } from "./context/context-budget-manager.js";
3
+ import { StateReconciler } from "./state/state-reconciler.js";
4
+ import { IterationLifecycle } from "./lifecycle/iteration-lifecycle.js";
5
+ import { PerformanceOptimizer } from "./performance/performance-optimizer.js";
6
+ export * from "./types.js";
7
+ export {
8
+ ContextBudgetManager,
9
+ IterationLifecycle,
10
+ PerformanceOptimizer,
11
+ RalphStackMemoryBridge,
12
+ StateReconciler
13
+ };
14
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/integrations/ralph/index.ts"],
4
+ "sourcesContent": ["/**\n * Ralph Wiggum Loop - StackMemory Integration\n * Core module for bridging Ralph's iteration-based loops with StackMemory's persistence\n */\n\nexport { RalphStackMemoryBridge } from './bridge/ralph-stackmemory-bridge.js';\nexport { ContextBudgetManager } from './context/context-budget-manager.js';\nexport { StateReconciler } from './state/state-reconciler.js';\nexport { IterationLifecycle } from './lifecycle/iteration-lifecycle.js';\nexport { PerformanceOptimizer } from './performance/performance-optimizer.js';\nexport * from './types.js';"],
5
+ "mappings": "AAKA,SAAS,8BAA8B;AACvC,SAAS,4BAA4B;AACrC,SAAS,uBAAuB;AAChC,SAAS,0BAA0B;AACnC,SAAS,4BAA4B;AACrC,cAAc;",
6
+ "names": []
7
+ }
@@ -0,0 +1,397 @@
1
+ import { logger } from "../../../core/monitoring/logger.js";
2
+ import { FrameManager } from "../../../core/context/frame-manager.js";
3
+ import { sharedContextLayer } from "../../../core/context/shared-context-layer.js";
4
+ import { sessionManager } from "../../../core/session/index.js";
5
+ class PatternLearner {
6
+ frameManager;
7
+ config;
8
+ constructor(config) {
9
+ this.config = {
10
+ minLoopCountForPattern: 3,
11
+ confidenceThreshold: 0.7,
12
+ maxPatternsPerType: 10,
13
+ analysisDepth: "deep",
14
+ ...config
15
+ };
16
+ logger.info("Pattern learner initialized", this.config);
17
+ }
18
+ async initialize() {
19
+ try {
20
+ await sessionManager.initialize();
21
+ await sharedContextLayer.initialize();
22
+ const session = await sessionManager.getOrCreateSession({});
23
+ if (session.database) {
24
+ this.frameManager = new FrameManager(session.database, session.projectId);
25
+ }
26
+ logger.info("Pattern learner initialized successfully");
27
+ } catch (error) {
28
+ logger.error("Failed to initialize pattern learner", error);
29
+ throw error;
30
+ }
31
+ }
32
+ /**
33
+ * Learn patterns from all completed Ralph loops
34
+ */
35
+ async learnFromCompletedLoops() {
36
+ logger.info("Starting pattern learning from completed loops");
37
+ try {
38
+ const completedLoops = await this.getCompletedRalphLoops();
39
+ logger.info(`Found ${completedLoops.length} completed loops for analysis`);
40
+ if (completedLoops.length < this.config.minLoopCountForPattern) {
41
+ logger.info("Not enough loops for pattern extraction");
42
+ return [];
43
+ }
44
+ const patterns = [];
45
+ const successPatterns = await this.extractSuccessPatterns(completedLoops);
46
+ patterns.push(...successPatterns);
47
+ const failurePatterns = await this.extractFailurePatterns(completedLoops);
48
+ patterns.push(...failurePatterns);
49
+ const iterationPatterns = await this.extractIterationPatterns(completedLoops);
50
+ patterns.push(...iterationPatterns);
51
+ const taskPatterns = await this.extractTaskPatterns(completedLoops);
52
+ patterns.push(...taskPatterns);
53
+ await this.saveLearnedPatterns(patterns);
54
+ logger.info(`Learned ${patterns.length} patterns from ${completedLoops.length} loops`);
55
+ return patterns;
56
+ } catch (error) {
57
+ logger.error("Failed to learn patterns", error);
58
+ throw error;
59
+ }
60
+ }
61
+ /**
62
+ * Learn patterns specific to a task type
63
+ */
64
+ async learnForTaskType(taskType) {
65
+ logger.info(`Learning patterns for task type: ${taskType}`);
66
+ const completedLoops = await this.getCompletedRalphLoops();
67
+ const relevantLoops = completedLoops.filter(
68
+ (loop) => this.classifyTaskType(loop.task) === taskType
69
+ );
70
+ if (relevantLoops.length < this.config.minLoopCountForPattern) {
71
+ return [];
72
+ }
73
+ return this.extractSpecializedPatterns(relevantLoops, taskType);
74
+ }
75
+ /**
76
+ * Get all completed Ralph loops from StackMemory
77
+ */
78
+ async getCompletedRalphLoops() {
79
+ if (!this.frameManager) {
80
+ throw new Error("Frame manager not initialized");
81
+ }
82
+ try {
83
+ const ralphFrames = await this.frameManager.searchFrames({
84
+ type: "task",
85
+ namePattern: "ralph-*",
86
+ state: "closed"
87
+ });
88
+ const analyses = [];
89
+ for (const frame of ralphFrames) {
90
+ try {
91
+ const analysis = await this.analyzeCompletedLoop(frame);
92
+ if (analysis) {
93
+ analyses.push(analysis);
94
+ }
95
+ } catch (error) {
96
+ logger.warn(`Failed to analyze loop ${frame.frame_id}`, error);
97
+ }
98
+ }
99
+ return analyses;
100
+ } catch (error) {
101
+ logger.error("Failed to get completed loops", error);
102
+ return [];
103
+ }
104
+ }
105
+ /**
106
+ * Analyze a completed loop for patterns
107
+ */
108
+ async analyzeCompletedLoop(ralphFrame) {
109
+ if (!this.frameManager) return null;
110
+ try {
111
+ const loopState = ralphFrame.inputs;
112
+ const iterationFrames = await this.frameManager.searchFrames({
113
+ type: "subtask",
114
+ namePattern: "iteration-*",
115
+ parentId: ralphFrame.frame_id
116
+ });
117
+ const successMetrics = this.calculateSuccessMetrics(iterationFrames);
118
+ const iterationAnalysis = this.analyzeIterations(iterationFrames);
119
+ const outcome = this.determineLoopOutcome(ralphFrame, iterationFrames);
120
+ return {
121
+ loopId: loopState.loopId,
122
+ task: loopState.task,
123
+ criteria: loopState.criteria,
124
+ taskType: this.classifyTaskType(loopState.task),
125
+ iterationCount: iterationFrames.length,
126
+ outcome,
127
+ successMetrics,
128
+ iterationAnalysis,
129
+ duration: ralphFrame.updated_at - ralphFrame.created_at,
130
+ startTime: ralphFrame.created_at,
131
+ endTime: ralphFrame.updated_at
132
+ };
133
+ } catch (error) {
134
+ logger.error("Failed to analyze loop", error);
135
+ return null;
136
+ }
137
+ }
138
+ /**
139
+ * Extract patterns from successful loops
140
+ */
141
+ async extractSuccessPatterns(loops) {
142
+ const successfulLoops = loops.filter((l) => l.outcome === "success");
143
+ if (successfulLoops.length < this.config.minLoopCountForPattern) {
144
+ return [];
145
+ }
146
+ const patterns = [];
147
+ const avgIterations = successfulLoops.reduce((sum, l) => sum + l.iterationCount, 0) / successfulLoops.length;
148
+ patterns.push({
149
+ id: "optimal-iterations",
150
+ type: "iteration_strategy",
151
+ pattern: `Successful tasks typically complete in ${Math.round(avgIterations)} iterations`,
152
+ confidence: this.calculateConfidence(successfulLoops.length),
153
+ frequency: successfulLoops.length,
154
+ strategy: `Target ${Math.round(avgIterations)} iterations for similar tasks`,
155
+ examples: successfulLoops.slice(0, 3).map((l) => l.task),
156
+ metadata: {
157
+ avgIterations,
158
+ minIterations: Math.min(...successfulLoops.map((l) => l.iterationCount)),
159
+ maxIterations: Math.max(...successfulLoops.map((l) => l.iterationCount))
160
+ }
161
+ });
162
+ const criteriaPatterns = this.extractCriteriaPatterns(successfulLoops);
163
+ patterns.push(...criteriaPatterns);
164
+ const successFactors = this.extractSuccessFactors(successfulLoops);
165
+ patterns.push(...successFactors);
166
+ return patterns.filter((p) => p.confidence >= this.config.confidenceThreshold);
167
+ }
168
+ /**
169
+ * Extract patterns from failed loops to avoid
170
+ */
171
+ async extractFailurePatterns(loops) {
172
+ const failedLoops = loops.filter((l) => l.outcome === "failure");
173
+ if (failedLoops.length < this.config.minLoopCountForPattern) {
174
+ return [];
175
+ }
176
+ const patterns = [];
177
+ const commonFailures = this.analyzeFailurePoints(failedLoops);
178
+ for (const failure of commonFailures) {
179
+ patterns.push({
180
+ id: `avoid-${failure.type}`,
181
+ type: "failure_avoidance",
182
+ pattern: `Avoid: ${failure.pattern}`,
183
+ confidence: this.calculateConfidence(failure.frequency),
184
+ frequency: failure.frequency,
185
+ strategy: failure.avoidanceStrategy,
186
+ examples: failure.examples,
187
+ metadata: { failureType: failure.type }
188
+ });
189
+ }
190
+ return patterns.filter((p) => p.confidence >= this.config.confidenceThreshold);
191
+ }
192
+ /**
193
+ * Extract iteration-specific patterns
194
+ */
195
+ async extractIterationPatterns(loops) {
196
+ const patterns = [];
197
+ const iterationSequences = this.analyzeIterationSequences(loops);
198
+ for (const sequence of iterationSequences) {
199
+ if (sequence.frequency >= this.config.minLoopCountForPattern) {
200
+ patterns.push({
201
+ id: `iteration-sequence-${sequence.id}`,
202
+ type: "iteration_sequence",
203
+ pattern: sequence.description,
204
+ confidence: this.calculateConfidence(sequence.frequency),
205
+ frequency: sequence.frequency,
206
+ strategy: sequence.strategy,
207
+ examples: sequence.examples,
208
+ metadata: { sequenceType: sequence.type }
209
+ });
210
+ }
211
+ }
212
+ return patterns;
213
+ }
214
+ /**
215
+ * Extract task-specific patterns
216
+ */
217
+ async extractTaskPatterns(loops) {
218
+ const taskGroups = this.groupByTaskType(loops);
219
+ const patterns = [];
220
+ for (const [taskType, taskLoops] of Object.entries(taskGroups)) {
221
+ if (taskLoops.length >= this.config.minLoopCountForPattern) {
222
+ const taskSpecificPatterns = await this.extractSpecializedPatterns(taskLoops, taskType);
223
+ patterns.push(...taskSpecificPatterns);
224
+ }
225
+ }
226
+ return patterns;
227
+ }
228
+ /**
229
+ * Extract specialized patterns for specific task types
230
+ */
231
+ async extractSpecializedPatterns(loops, taskType) {
232
+ const patterns = [];
233
+ const successful = loops.filter((l) => l.outcome === "success");
234
+ if (successful.length === 0) return patterns;
235
+ patterns.push({
236
+ id: `${taskType}-success-pattern`,
237
+ type: "task_specific",
238
+ pattern: `${taskType} tasks: ${this.summarizeSuccessPattern(successful)}`,
239
+ confidence: this.calculateConfidence(successful.length),
240
+ frequency: successful.length,
241
+ strategy: this.generateTaskStrategy(successful),
242
+ examples: successful.slice(0, 2).map((l) => l.task),
243
+ metadata: { taskType, totalAttempts: loops.length }
244
+ });
245
+ return patterns;
246
+ }
247
+ /**
248
+ * Calculate success metrics for iterations
249
+ */
250
+ calculateSuccessMetrics(iterations) {
251
+ const total = iterations.length;
252
+ const successful = iterations.filter((i) => i.outputs?.success).length;
253
+ return {
254
+ iterationCount: total,
255
+ successRate: total > 0 ? successful / total : 0,
256
+ averageProgress: this.calculateAverageProgress(iterations),
257
+ timeToCompletion: total > 0 ? iterations[total - 1].updated_at - iterations[0].created_at : 0
258
+ };
259
+ }
260
+ /**
261
+ * Classify task type based on description
262
+ */
263
+ classifyTaskType(task) {
264
+ const taskLower = task.toLowerCase();
265
+ if (taskLower.includes("test") || taskLower.includes("unit")) return "testing";
266
+ if (taskLower.includes("fix") || taskLower.includes("bug")) return "bugfix";
267
+ if (taskLower.includes("refactor")) return "refactoring";
268
+ if (taskLower.includes("add") || taskLower.includes("implement")) return "feature";
269
+ if (taskLower.includes("document")) return "documentation";
270
+ if (taskLower.includes("optimize") || taskLower.includes("performance")) return "optimization";
271
+ return "general";
272
+ }
273
+ /**
274
+ * Determine loop outcome
275
+ */
276
+ determineLoopOutcome(ralphFrame, iterations) {
277
+ if (ralphFrame.digest_json?.status === "completed") return "success";
278
+ if (iterations.length === 0) return "unknown";
279
+ const lastIteration = iterations[iterations.length - 1];
280
+ if (lastIteration.outputs?.success) return "success";
281
+ return "failure";
282
+ }
283
+ /**
284
+ * Calculate confidence based on frequency
285
+ */
286
+ calculateConfidence(frequency) {
287
+ return Math.min(0.95, Math.log(frequency + 1) / Math.log(10));
288
+ }
289
+ /**
290
+ * Save learned patterns to shared context
291
+ */
292
+ async saveLearnedPatterns(patterns) {
293
+ try {
294
+ const context = await sharedContextLayer.getSharedContext();
295
+ if (!context) return;
296
+ const contextPatterns = patterns.map((p) => ({
297
+ pattern: p.pattern,
298
+ type: this.mapPatternType(p.type),
299
+ frequency: p.frequency,
300
+ lastSeen: Date.now(),
301
+ resolution: p.strategy
302
+ }));
303
+ context.globalPatterns.push(...contextPatterns);
304
+ context.globalPatterns.sort((a, b) => b.frequency - a.frequency);
305
+ context.globalPatterns = context.globalPatterns.slice(0, 100);
306
+ await sharedContextLayer.updateSharedContext(context);
307
+ logger.info(`Saved ${patterns.length} patterns to shared context`);
308
+ } catch (error) {
309
+ logger.error("Failed to save patterns", error);
310
+ }
311
+ }
312
+ /**
313
+ * Map pattern types to shared context types
314
+ */
315
+ mapPatternType(patternType) {
316
+ switch (patternType) {
317
+ case "failure_avoidance":
318
+ return "error";
319
+ case "success_strategy":
320
+ return "success";
321
+ case "task_specific":
322
+ return "learning";
323
+ default:
324
+ return "learning";
325
+ }
326
+ }
327
+ // Additional helper methods for pattern analysis
328
+ analyzeIterations(iterations) {
329
+ return {
330
+ avgDuration: iterations.length > 0 ? iterations.reduce((sum, i) => sum + (i.updated_at - i.created_at), 0) / iterations.length : 0,
331
+ progressPattern: this.extractProgressPattern(iterations),
332
+ commonIssues: this.extractCommonIssues(iterations)
333
+ };
334
+ }
335
+ extractProgressPattern(iterations) {
336
+ const progressSteps = iterations.map((_, i) => {
337
+ const progress = i / iterations.length;
338
+ return Math.round(progress * 100);
339
+ });
340
+ return progressSteps.join(" \u2192 ") + "%";
341
+ }
342
+ extractCommonIssues(iterations) {
343
+ return iterations.filter((i) => i.outputs?.errors?.length > 0).flatMap((i) => i.outputs.errors).slice(0, 3);
344
+ }
345
+ extractCriteriaPatterns(loops) {
346
+ const criteriaWords = loops.flatMap((l) => l.criteria.toLowerCase().split(/\s+/));
347
+ const wordCounts = criteriaWords.reduce((acc, word) => {
348
+ acc[word] = (acc[word] || 0) + 1;
349
+ return acc;
350
+ }, {});
351
+ const commonCriteria = Object.entries(wordCounts).filter(([_, count]) => count >= this.config.minLoopCountForPattern).sort((a, b) => b[1] - a[1]).slice(0, 3);
352
+ return commonCriteria.map(([word, count]) => ({
353
+ id: `criteria-${word}`,
354
+ type: "success_strategy",
355
+ pattern: `Successful tasks often include "${word}" in completion criteria`,
356
+ confidence: this.calculateConfidence(count),
357
+ frequency: count,
358
+ strategy: `Consider including "${word}" in task completion criteria`,
359
+ examples: loops.filter((l) => l.criteria.toLowerCase().includes(word)).slice(0, 2).map((l) => l.task),
360
+ metadata: { criteriaWord: word }
361
+ }));
362
+ }
363
+ extractSuccessFactors(loops) {
364
+ return [];
365
+ }
366
+ analyzeFailurePoints(loops) {
367
+ return [];
368
+ }
369
+ analyzeIterationSequences(loops) {
370
+ return [];
371
+ }
372
+ groupByTaskType(loops) {
373
+ return loops.reduce((acc, loop) => {
374
+ const type = loop.taskType;
375
+ if (!acc[type]) acc[type] = [];
376
+ acc[type].push(loop);
377
+ return acc;
378
+ }, {});
379
+ }
380
+ summarizeSuccessPattern(loops) {
381
+ const avgIterations = loops.reduce((sum, l) => sum + l.iterationCount, 0) / loops.length;
382
+ return `typically complete in ${Math.round(avgIterations)} iterations with ${Math.round(loops[0]?.successMetrics?.successRate * 100 || 0)}% success rate`;
383
+ }
384
+ generateTaskStrategy(loops) {
385
+ const avgIterations = loops.reduce((sum, l) => sum + l.iterationCount, 0) / loops.length;
386
+ return `Plan for approximately ${Math.round(avgIterations)} iterations and focus on iterative improvement`;
387
+ }
388
+ calculateAverageProgress(iterations) {
389
+ return iterations.length > 0 ? iterations.length / 10 : 0;
390
+ }
391
+ }
392
+ const patternLearner = new PatternLearner();
393
+ export {
394
+ PatternLearner,
395
+ patternLearner
396
+ };
397
+ //# sourceMappingURL=pattern-learner.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/integrations/ralph/learning/pattern-learner.ts"],
4
+ "sourcesContent": ["/**\n * Pattern Learning Engine for Ralph Loops\n * Analyzes completed loops to extract reusable patterns and strategies\n */\n\nimport { logger } from '../../../core/monitoring/logger.js';\nimport { FrameManager } from '../../../core/context/frame-manager.js';\nimport { sharedContextLayer } from '../../../core/context/shared-context-layer.js';\nimport { sessionManager } from '../../../core/session/index.js';\nimport {\n LearnedPattern,\n LoopAnalysis,\n PatternType,\n SuccessMetrics,\n FailureAnalysis,\n RalphLoopState\n} from '../types.js';\n\nexport interface PatternLearningConfig {\n minLoopCountForPattern: number;\n confidenceThreshold: number;\n maxPatternsPerType: number;\n analysisDepth: 'shallow' | 'deep' | 'comprehensive';\n}\n\nexport class PatternLearner {\n private frameManager?: FrameManager;\n private config: PatternLearningConfig;\n\n constructor(config?: Partial<PatternLearningConfig>) {\n this.config = {\n minLoopCountForPattern: 3,\n confidenceThreshold: 0.7,\n maxPatternsPerType: 10,\n analysisDepth: 'deep',\n ...config\n };\n\n logger.info('Pattern learner 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 logger.info('Pattern learner initialized successfully');\n } catch (error: unknown) {\n logger.error('Failed to initialize pattern learner', error as Error);\n throw error;\n }\n }\n\n /**\n * Learn patterns from all completed Ralph loops\n */\n async learnFromCompletedLoops(): Promise<LearnedPattern[]> {\n logger.info('Starting pattern learning from completed loops');\n\n try {\n const completedLoops = await this.getCompletedRalphLoops();\n logger.info(`Found ${completedLoops.length} completed loops for analysis`);\n\n if (completedLoops.length < this.config.minLoopCountForPattern) {\n logger.info('Not enough loops for pattern extraction');\n return [];\n }\n\n const patterns: LearnedPattern[] = [];\n\n // Learn success patterns\n const successPatterns = await this.extractSuccessPatterns(completedLoops);\n patterns.push(...successPatterns);\n\n // Learn failure patterns (to avoid)\n const failurePatterns = await this.extractFailurePatterns(completedLoops);\n patterns.push(...failurePatterns);\n\n // Learn iteration patterns\n const iterationPatterns = await this.extractIterationPatterns(completedLoops);\n patterns.push(...iterationPatterns);\n\n // Learn task-specific patterns\n const taskPatterns = await this.extractTaskPatterns(completedLoops);\n patterns.push(...taskPatterns);\n\n // Save patterns to shared context\n await this.saveLearnedPatterns(patterns);\n\n logger.info(`Learned ${patterns.length} patterns from ${completedLoops.length} loops`);\n return patterns;\n\n } catch (error: unknown) {\n logger.error('Failed to learn patterns', error as Error);\n throw error;\n }\n }\n\n /**\n * Learn patterns specific to a task type\n */\n async learnForTaskType(taskType: string): Promise<LearnedPattern[]> {\n logger.info(`Learning patterns for task type: ${taskType}`);\n\n const completedLoops = await this.getCompletedRalphLoops();\n const relevantLoops = completedLoops.filter(loop => \n this.classifyTaskType(loop.task) === taskType\n );\n\n if (relevantLoops.length < this.config.minLoopCountForPattern) {\n return [];\n }\n\n return this.extractSpecializedPatterns(relevantLoops, taskType);\n }\n\n /**\n * Get all completed Ralph loops from StackMemory\n */\n private async getCompletedRalphLoops(): Promise<LoopAnalysis[]> {\n if (!this.frameManager) {\n throw new Error('Frame manager not initialized');\n }\n\n try {\n // Get all Ralph loop frames\n const ralphFrames = await this.frameManager.searchFrames({\n type: 'task',\n namePattern: 'ralph-*',\n state: 'closed'\n });\n\n const analyses: LoopAnalysis[] = [];\n\n for (const frame of ralphFrames) {\n try {\n const analysis = await this.analyzeCompletedLoop(frame);\n if (analysis) {\n analyses.push(analysis);\n }\n } catch (error: unknown) {\n logger.warn(`Failed to analyze loop ${frame.frame_id}`, error as Error);\n }\n }\n\n return analyses;\n\n } catch (error: unknown) {\n logger.error('Failed to get completed loops', error as Error);\n return [];\n }\n }\n\n /**\n * Analyze a completed loop for patterns\n */\n private async analyzeCompletedLoop(ralphFrame: any): Promise<LoopAnalysis | null> {\n if (!this.frameManager) return null;\n\n try {\n // Get loop state from frame inputs\n const loopState = ralphFrame.inputs as RalphLoopState;\n \n // Get all iteration frames for this loop\n const iterationFrames = await this.frameManager.searchFrames({\n type: 'subtask',\n namePattern: 'iteration-*',\n parentId: ralphFrame.frame_id\n });\n\n // Calculate success metrics\n const successMetrics = this.calculateSuccessMetrics(iterationFrames);\n \n // Analyze iteration patterns\n const iterationAnalysis = this.analyzeIterations(iterationFrames);\n \n // Determine outcome\n const outcome = this.determineLoopOutcome(ralphFrame, iterationFrames);\n\n return {\n loopId: loopState.loopId,\n task: loopState.task,\n criteria: loopState.criteria,\n taskType: this.classifyTaskType(loopState.task),\n iterationCount: iterationFrames.length,\n outcome,\n successMetrics,\n iterationAnalysis,\n duration: ralphFrame.updated_at - ralphFrame.created_at,\n startTime: ralphFrame.created_at,\n endTime: ralphFrame.updated_at\n };\n\n } catch (error: unknown) {\n logger.error('Failed to analyze loop', error as Error);\n return null;\n }\n }\n\n /**\n * Extract patterns from successful loops\n */\n private async extractSuccessPatterns(loops: LoopAnalysis[]): Promise<LearnedPattern[]> {\n const successfulLoops = loops.filter(l => l.outcome === 'success');\n \n if (successfulLoops.length < this.config.minLoopCountForPattern) {\n return [];\n }\n\n const patterns: LearnedPattern[] = [];\n\n // Pattern: Optimal iteration count\n const avgIterations = successfulLoops.reduce((sum, l) => sum + l.iterationCount, 0) / successfulLoops.length;\n patterns.push({\n id: 'optimal-iterations',\n type: 'iteration_strategy',\n pattern: `Successful tasks typically complete in ${Math.round(avgIterations)} iterations`,\n confidence: this.calculateConfidence(successfulLoops.length),\n frequency: successfulLoops.length,\n strategy: `Target ${Math.round(avgIterations)} iterations for similar tasks`,\n examples: successfulLoops.slice(0, 3).map(l => l.task),\n metadata: {\n avgIterations,\n minIterations: Math.min(...successfulLoops.map(l => l.iterationCount)),\n maxIterations: Math.max(...successfulLoops.map(l => l.iterationCount))\n }\n });\n\n // Pattern: Task completion criteria\n const criteriaPatterns = this.extractCriteriaPatterns(successfulLoops);\n patterns.push(...criteriaPatterns);\n\n // Pattern: Common success factors\n const successFactors = this.extractSuccessFactors(successfulLoops);\n patterns.push(...successFactors);\n\n return patterns.filter(p => p.confidence >= this.config.confidenceThreshold);\n }\n\n /**\n * Extract patterns from failed loops to avoid\n */\n private async extractFailurePatterns(loops: LoopAnalysis[]): Promise<LearnedPattern[]> {\n const failedLoops = loops.filter(l => l.outcome === 'failure');\n \n if (failedLoops.length < this.config.minLoopCountForPattern) {\n return [];\n }\n\n const patterns: LearnedPattern[] = [];\n\n // Pattern: Common failure points\n const commonFailures = this.analyzeFailurePoints(failedLoops);\n for (const failure of commonFailures) {\n patterns.push({\n id: `avoid-${failure.type}`,\n type: 'failure_avoidance',\n pattern: `Avoid: ${failure.pattern}`,\n confidence: this.calculateConfidence(failure.frequency),\n frequency: failure.frequency,\n strategy: failure.avoidanceStrategy,\n examples: failure.examples,\n metadata: { failureType: failure.type }\n });\n }\n\n return patterns.filter(p => p.confidence >= this.config.confidenceThreshold);\n }\n\n /**\n * Extract iteration-specific patterns\n */\n private async extractIterationPatterns(loops: LoopAnalysis[]): Promise<LearnedPattern[]> {\n const patterns: LearnedPattern[] = [];\n\n // Analyze iteration sequences\n const iterationSequences = this.analyzeIterationSequences(loops);\n \n for (const sequence of iterationSequences) {\n if (sequence.frequency >= this.config.minLoopCountForPattern) {\n patterns.push({\n id: `iteration-sequence-${sequence.id}`,\n type: 'iteration_sequence',\n pattern: sequence.description,\n confidence: this.calculateConfidence(sequence.frequency),\n frequency: sequence.frequency,\n strategy: sequence.strategy,\n examples: sequence.examples,\n metadata: { sequenceType: sequence.type }\n });\n }\n }\n\n return patterns;\n }\n\n /**\n * Extract task-specific patterns\n */\n private async extractTaskPatterns(loops: LoopAnalysis[]): Promise<LearnedPattern[]> {\n const taskGroups = this.groupByTaskType(loops);\n const patterns: LearnedPattern[] = [];\n\n for (const [taskType, taskLoops] of Object.entries(taskGroups)) {\n if (taskLoops.length >= this.config.minLoopCountForPattern) {\n const taskSpecificPatterns = await this.extractSpecializedPatterns(taskLoops, taskType);\n patterns.push(...taskSpecificPatterns);\n }\n }\n\n return patterns;\n }\n\n /**\n * Extract specialized patterns for specific task types\n */\n private async extractSpecializedPatterns(loops: LoopAnalysis[], taskType: string): Promise<LearnedPattern[]> {\n const patterns: LearnedPattern[] = [];\n const successful = loops.filter(l => l.outcome === 'success');\n\n if (successful.length === 0) return patterns;\n\n // Task-specific success pattern\n patterns.push({\n id: `${taskType}-success-pattern`,\n type: 'task_specific',\n pattern: `${taskType} tasks: ${this.summarizeSuccessPattern(successful)}`,\n confidence: this.calculateConfidence(successful.length),\n frequency: successful.length,\n strategy: this.generateTaskStrategy(successful),\n examples: successful.slice(0, 2).map(l => l.task),\n metadata: { taskType, totalAttempts: loops.length }\n });\n\n return patterns;\n }\n\n /**\n * Calculate success metrics for iterations\n */\n private calculateSuccessMetrics(iterations: any[]): SuccessMetrics {\n const total = iterations.length;\n const successful = iterations.filter(i => i.outputs?.success).length;\n \n return {\n iterationCount: total,\n successRate: total > 0 ? successful / total : 0,\n averageProgress: this.calculateAverageProgress(iterations),\n timeToCompletion: total > 0 ? iterations[total - 1].updated_at - iterations[0].created_at : 0\n };\n }\n\n /**\n * Classify task type based on description\n */\n private classifyTaskType(task: string): string {\n const taskLower = task.toLowerCase();\n \n if (taskLower.includes('test') || taskLower.includes('unit')) return 'testing';\n if (taskLower.includes('fix') || taskLower.includes('bug')) return 'bugfix';\n if (taskLower.includes('refactor')) return 'refactoring';\n if (taskLower.includes('add') || taskLower.includes('implement')) return 'feature';\n if (taskLower.includes('document')) return 'documentation';\n if (taskLower.includes('optimize') || taskLower.includes('performance')) return 'optimization';\n \n return 'general';\n }\n\n /**\n * Determine loop outcome\n */\n private determineLoopOutcome(ralphFrame: any, iterations: any[]): 'success' | 'failure' | 'unknown' {\n if (ralphFrame.digest_json?.status === 'completed') return 'success';\n if (iterations.length === 0) return 'unknown';\n \n const lastIteration = iterations[iterations.length - 1];\n if (lastIteration.outputs?.success) return 'success';\n \n return 'failure';\n }\n\n /**\n * Calculate confidence based on frequency\n */\n private calculateConfidence(frequency: number): number {\n // Simple confidence calculation based on sample size\n return Math.min(0.95, Math.log(frequency + 1) / Math.log(10));\n }\n\n /**\n * Save learned patterns to shared context\n */\n private async saveLearnedPatterns(patterns: LearnedPattern[]): Promise<void> {\n try {\n const context = await sharedContextLayer.getSharedContext();\n if (!context) return;\n\n // Convert to shared context format\n const contextPatterns = patterns.map(p => ({\n pattern: p.pattern,\n type: this.mapPatternType(p.type),\n frequency: p.frequency,\n lastSeen: Date.now(),\n resolution: p.strategy\n }));\n\n // Add to global patterns\n context.globalPatterns.push(...contextPatterns);\n\n // Keep only the most relevant patterns\n context.globalPatterns.sort((a, b) => b.frequency - a.frequency);\n context.globalPatterns = context.globalPatterns.slice(0, 100);\n\n await sharedContextLayer.updateSharedContext(context);\n \n logger.info(`Saved ${patterns.length} patterns to shared context`);\n\n } catch (error: unknown) {\n logger.error('Failed to save patterns', error as Error);\n }\n }\n\n /**\n * Map pattern types to shared context types\n */\n private mapPatternType(patternType: PatternType): 'error' | 'success' | 'decision' | 'learning' {\n switch (patternType) {\n case 'failure_avoidance': return 'error';\n case 'success_strategy': return 'success';\n case 'task_specific': return 'learning';\n default: return 'learning';\n }\n }\n\n // Additional helper methods for pattern analysis\n private analyzeIterations(iterations: any[]): any {\n return {\n avgDuration: iterations.length > 0 ? \n iterations.reduce((sum, i) => sum + (i.updated_at - i.created_at), 0) / iterations.length : 0,\n progressPattern: this.extractProgressPattern(iterations),\n commonIssues: this.extractCommonIssues(iterations)\n };\n }\n\n private extractProgressPattern(iterations: any[]): string {\n // Analyze how progress typically unfolds\n const progressSteps = iterations.map((_, i) => {\n const progress = i / iterations.length;\n return Math.round(progress * 100);\n });\n \n return progressSteps.join(' \u2192 ') + '%';\n }\n\n private extractCommonIssues(iterations: any[]): string[] {\n // Extract common error patterns from iteration outputs\n return iterations\n .filter(i => i.outputs?.errors?.length > 0)\n .flatMap(i => i.outputs.errors)\n .slice(0, 3);\n }\n\n private extractCriteriaPatterns(loops: LoopAnalysis[]): LearnedPattern[] {\n // Analyze common successful completion criteria\n const criteriaWords = loops.flatMap(l => l.criteria.toLowerCase().split(/\\s+/));\n const wordCounts = criteriaWords.reduce((acc, word) => {\n acc[word] = (acc[word] || 0) + 1;\n return acc;\n }, {} as Record<string, number>);\n\n const commonCriteria = Object.entries(wordCounts)\n .filter(([_, count]) => count >= this.config.minLoopCountForPattern)\n .sort((a, b) => b[1] - a[1])\n .slice(0, 3);\n\n return commonCriteria.map(([word, count]) => ({\n id: `criteria-${word}`,\n type: 'success_strategy' as PatternType,\n pattern: `Successful tasks often include \"${word}\" in completion criteria`,\n confidence: this.calculateConfidence(count),\n frequency: count,\n strategy: `Consider including \"${word}\" in task completion criteria`,\n examples: loops.filter(l => l.criteria.toLowerCase().includes(word)).slice(0, 2).map(l => l.task),\n metadata: { criteriaWord: word }\n }));\n }\n\n private extractSuccessFactors(loops: LoopAnalysis[]): LearnedPattern[] {\n // Placeholder for success factor analysis\n return [];\n }\n\n private analyzeFailurePoints(loops: LoopAnalysis[]): FailureAnalysis[] {\n // Placeholder for failure analysis\n return [];\n }\n\n private analyzeIterationSequences(loops: LoopAnalysis[]): any[] {\n // Placeholder for iteration sequence analysis\n return [];\n }\n\n private groupByTaskType(loops: LoopAnalysis[]): Record<string, LoopAnalysis[]> {\n return loops.reduce((acc, loop) => {\n const type = loop.taskType;\n if (!acc[type]) acc[type] = [];\n acc[type].push(loop);\n return acc;\n }, {} as Record<string, LoopAnalysis[]>);\n }\n\n private summarizeSuccessPattern(loops: LoopAnalysis[]): string {\n const avgIterations = loops.reduce((sum, l) => sum + l.iterationCount, 0) / loops.length;\n return `typically complete in ${Math.round(avgIterations)} iterations with ${Math.round(loops[0]?.successMetrics?.successRate * 100 || 0)}% success rate`;\n }\n\n private generateTaskStrategy(loops: LoopAnalysis[]): string {\n const avgIterations = loops.reduce((sum, l) => sum + l.iterationCount, 0) / loops.length;\n return `Plan for approximately ${Math.round(avgIterations)} iterations and focus on iterative improvement`;\n }\n\n private calculateAverageProgress(iterations: any[]): number {\n // Simple progress calculation\n return iterations.length > 0 ? iterations.length / 10 : 0; // Assume 10 iterations is 100% progress\n }\n}\n\n// Export default instance\nexport const patternLearner = new PatternLearner();"],
5
+ "mappings": "AAKA,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC,SAAS,sBAAsB;AAiBxB,MAAM,eAAe;AAAA,EAClB;AAAA,EACA;AAAA,EAER,YAAY,QAAyC;AACnD,SAAK,SAAS;AAAA,MACZ,wBAAwB;AAAA,MACxB,qBAAqB;AAAA,MACrB,oBAAoB;AAAA,MACpB,eAAe;AAAA,MACf,GAAG;AAAA,IACL;AAEA,WAAO,KAAK,+BAA+B,KAAK,MAAM;AAAA,EACxD;AAAA,EAEA,MAAM,aAA4B;AAChC,QAAI;AACF,YAAM,eAAe,WAAW;AAChC,YAAM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