@stackmemoryai/stackmemory 1.10.5 → 1.14.0

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 (225) hide show
  1. package/LICENSE +131 -64
  2. package/README.md +107 -24
  3. package/bin/claude-sm +16 -1
  4. package/bin/claude-smd +16 -1
  5. package/bin/codex-smd +16 -1
  6. package/bin/gemini-sm +16 -1
  7. package/bin/hermes-sm +21 -0
  8. package/bin/hermes-smd +21 -0
  9. package/bin/opencode-sm +16 -1
  10. package/dist/src/cli/claude-sm.js +266 -84
  11. package/dist/src/cli/codex-sm.js +225 -33
  12. package/dist/src/cli/commands/bench.js +209 -2
  13. package/dist/src/cli/commands/brain.js +206 -0
  14. package/dist/src/cli/commands/cache.js +126 -0
  15. package/dist/src/cli/commands/company-os.js +184 -0
  16. package/dist/src/cli/commands/context.js +5 -0
  17. package/dist/src/cli/commands/daemon.js +41 -0
  18. package/dist/src/cli/commands/handoff.js +40 -9
  19. package/dist/src/cli/commands/onboard.js +70 -3
  20. package/dist/src/cli/commands/operator.js +127 -0
  21. package/dist/src/cli/commands/optimize.js +117 -0
  22. package/dist/src/cli/commands/orchestrate.js +232 -5
  23. package/dist/src/cli/commands/orchestrator.js +315 -26
  24. package/dist/src/cli/commands/pack.js +322 -0
  25. package/dist/src/cli/commands/patterns.js +254 -0
  26. package/dist/src/cli/commands/portal.js +161 -0
  27. package/dist/src/cli/commands/scaffold.js +92 -0
  28. package/dist/src/cli/commands/search.js +40 -1
  29. package/dist/src/cli/commands/setup.js +178 -11
  30. package/dist/src/cli/commands/skills.js +10 -1
  31. package/dist/src/cli/commands/state.js +265 -0
  32. package/dist/src/cli/commands/sync.js +253 -0
  33. package/dist/src/cli/commands/tasks.js +130 -1
  34. package/dist/src/cli/commands/vision.js +221 -0
  35. package/dist/src/cli/gemini-sm.js +19 -29
  36. package/dist/src/cli/hermes-sm.js +224 -0
  37. package/dist/src/cli/index.js +105 -39
  38. package/dist/src/cli/opencode-sm.js +38 -21
  39. package/dist/src/cli/utils/determinism-watcher.js +66 -0
  40. package/dist/src/cli/utils/real-cli-bin.js +116 -0
  41. package/dist/src/core/brain/brain-store.js +187 -0
  42. package/dist/src/core/brain/brain-sync.js +193 -0
  43. package/dist/src/core/brain/index.js +78 -0
  44. package/dist/src/core/brain/types.js +10 -0
  45. package/dist/src/core/cache/content-cache.js +238 -0
  46. package/dist/src/{integrations/diffmem → core/cache}/index.js +5 -5
  47. package/dist/src/core/cache/token-estimator.js +39 -0
  48. package/dist/src/core/config/feature-flags.js +2 -6
  49. package/dist/src/core/context/frame-database.js +79 -27
  50. package/dist/src/core/context/recursive-context-manager.js +1 -1
  51. package/dist/src/core/context/rehydration.js +2 -1
  52. package/dist/src/core/cross-search/cross-project-search.js +269 -0
  53. package/dist/src/core/cross-search/index.js +10 -0
  54. package/dist/src/core/database/sqlite-adapter.js +14 -84
  55. package/dist/src/core/extensions/provider-adapter.js +5 -0
  56. package/dist/src/core/models/model-router.js +54 -2
  57. package/dist/src/core/models/provider-pricing.js +58 -4
  58. package/dist/src/core/monitoring/logger.js +2 -1
  59. package/dist/src/core/optimization/trace-optimizer.js +413 -0
  60. package/dist/src/core/patterns/index.js +22 -0
  61. package/dist/src/core/patterns/pattern-applier.js +39 -0
  62. package/dist/src/core/patterns/pattern-observer.js +157 -0
  63. package/dist/src/core/patterns/pattern-store.js +259 -0
  64. package/dist/src/core/patterns/types.js +19 -0
  65. package/dist/src/core/provenance/confidence-scorer.js +128 -0
  66. package/dist/src/core/provenance/index.js +40 -0
  67. package/dist/src/core/provenance/provenance-store.js +194 -0
  68. package/dist/src/core/provenance/types.js +82 -0
  69. package/dist/src/core/retrieval/llm-context-retrieval.js +5 -4
  70. package/dist/src/core/retrieval/unified-context-assembler.js +11 -66
  71. package/dist/src/core/session/project-handoff.js +64 -0
  72. package/dist/src/core/session/session-manager.js +28 -0
  73. package/dist/src/core/shared-state/canonical-store.js +564 -0
  74. package/dist/src/core/skill-packs/index.js +18 -0
  75. package/dist/src/core/skill-packs/parser.js +42 -0
  76. package/dist/src/core/skill-packs/registry.js +224 -0
  77. package/dist/src/core/skill-packs/types.js +79 -0
  78. package/dist/src/core/storage/cloud-sync-manager.js +116 -0
  79. package/dist/src/core/storage/cloud-sync.js +574 -0
  80. package/dist/src/core/storage/two-tier-storage.js +5 -1
  81. package/dist/src/core/tasks/master-tasks-template.js +43 -0
  82. package/dist/src/core/tasks/md-task-parser.js +138 -0
  83. package/dist/src/core/trace/trace-event-store.js +282 -0
  84. package/dist/src/core/vision/index.js +27 -0
  85. package/dist/src/core/vision/signals.js +79 -0
  86. package/dist/src/core/vision/types.js +22 -0
  87. package/dist/src/core/vision/vision-file.js +146 -0
  88. package/dist/src/core/vision/vision-loop.js +220 -0
  89. package/dist/src/core/wiki/wiki-compiler.js +103 -1
  90. package/dist/src/daemon/daemon-config.js +52 -0
  91. package/dist/src/daemon/services/desire-path-service.js +566 -0
  92. package/dist/src/daemon/services/github-service.js +126 -0
  93. package/dist/src/daemon/services/research-stream-service.js +320 -0
  94. package/dist/src/daemon/services/telemetry-service.js +192 -0
  95. package/dist/src/daemon/unified-daemon.js +58 -1
  96. package/dist/src/features/browser/cli-browser-agent.js +417 -0
  97. package/dist/src/features/browser/stagehand-workflows.js +578 -0
  98. package/dist/src/features/operator/adapter-factory.js +62 -0
  99. package/dist/src/features/operator/browser-adapter.js +109 -0
  100. package/dist/src/features/operator/desktop-adapter.js +125 -0
  101. package/dist/src/features/operator/index.js +39 -0
  102. package/dist/src/features/operator/llm-decision.js +137 -0
  103. package/dist/src/features/operator/operator-logger.js +92 -0
  104. package/dist/src/features/operator/overnight-runner.js +327 -0
  105. package/dist/src/features/operator/screen-adapter.js +91 -0
  106. package/dist/src/features/operator/session-manager.js +127 -0
  107. package/dist/src/features/operator/state-machine.js +227 -0
  108. package/dist/src/features/operator/task-queue.js +81 -0
  109. package/dist/src/features/portal/index.js +26 -0
  110. package/dist/src/features/portal/server.js +240 -0
  111. package/dist/src/features/portal/types.js +14 -0
  112. package/dist/src/features/portal/ui.js +195 -0
  113. package/dist/src/features/sweep/pty-wrapper.js +13 -5
  114. package/dist/src/features/tasks/task-aware-context.js +2 -1
  115. package/dist/src/features/tui/simple-monitor.js +0 -23
  116. package/dist/src/features/tui/swarm-monitor.js +8 -66
  117. package/dist/src/features/web/client/hooks/use-socket.js +12 -0
  118. package/dist/src/{core/merge/index.js → features/web/client/lib/utils.js} +8 -4
  119. package/dist/src/features/web/client/next-env.d.js +4 -0
  120. package/dist/src/features/web/client/stores/session-store.js +12 -0
  121. package/dist/src/features/web/server/gcp-billing.js +76 -0
  122. package/dist/src/features/web/server/index.js +10 -0
  123. package/dist/src/features/web/server/spend-calculator.js +228 -0
  124. package/dist/src/hooks/schemas.js +6 -1
  125. package/dist/src/integrations/anthropic/client.js +3 -2
  126. package/dist/src/integrations/claude-code/agent-bridge.js +0 -3
  127. package/dist/src/integrations/claude-code/subagent-client.js +307 -11
  128. package/dist/src/integrations/claude-code/task-coordinator.js +2 -1
  129. package/dist/src/integrations/github/pr-state.js +158 -0
  130. package/dist/src/integrations/linear/client.js +4 -1
  131. package/dist/src/integrations/linear/webhook-retry.js +196 -0
  132. package/dist/src/integrations/linear/webhook-server.js +18 -22
  133. package/dist/src/integrations/mcp/handlers/cloud-sync-handlers.js +101 -0
  134. package/dist/src/integrations/mcp/handlers/index.js +40 -84
  135. package/dist/src/integrations/mcp/server.js +542 -641
  136. package/dist/src/integrations/mcp/tool-alias-registry.js +297 -0
  137. package/dist/src/integrations/mcp/tool-definitions.js +152 -682
  138. package/dist/src/mcp/stackmemory-mcp-server.js +571 -231
  139. package/dist/src/orchestrators/multimodal/determinism.js +244 -0
  140. package/dist/src/orchestrators/multimodal/harness.js +149 -78
  141. package/dist/src/orchestrators/multimodal/providers.js +44 -3
  142. package/dist/src/skills/recursive-agent-orchestrator.js +2 -4
  143. package/dist/src/utils/hook-installer.js +0 -8
  144. package/dist/src/utils/process-cleanup.js +1 -7
  145. package/docs/README.md +42 -0
  146. package/docs/guides/README_INSTALL.md +208 -0
  147. package/package.json +27 -9
  148. package/packs/coding/python-fastapi/instructions.md +60 -0
  149. package/packs/coding/python-fastapi/pack.yaml +28 -0
  150. package/packs/coding/typescript-react/instructions.md +47 -0
  151. package/packs/coding/typescript-react/pack.yaml +28 -0
  152. package/packs/core/commands/capture.md +32 -0
  153. package/packs/core/commands/learn.md +73 -0
  154. package/packs/core/commands/next.md +36 -0
  155. package/packs/core/commands/restart.md +58 -0
  156. package/packs/core/commands/restore.md +29 -0
  157. package/packs/core/commands/start.md +57 -0
  158. package/packs/core/commands/stop.md +65 -0
  159. package/packs/core/commands/summary.md +40 -0
  160. package/packs/core/manifest.json +24 -0
  161. package/packs/ops/decision-recovery/instructions.md +65 -0
  162. package/packs/ops/decision-recovery/pack.yaml +89 -0
  163. package/scripts/claude-code-wrapper.sh +11 -0
  164. package/scripts/claude-sm-setup.sh +12 -1
  165. package/scripts/codex-wrapper.sh +11 -0
  166. package/scripts/git-hooks/branch-context-manager.sh +11 -0
  167. package/scripts/git-hooks/post-checkout-stackmemory.sh +11 -0
  168. package/scripts/git-hooks/post-commit-stackmemory.sh +11 -0
  169. package/scripts/git-hooks/pre-commit-stackmemory.sh +11 -0
  170. package/scripts/hooks/cleanup-shell.sh +12 -1
  171. package/scripts/hooks/task-complete.sh +12 -1
  172. package/scripts/install-code-execution-hooks.sh +12 -1
  173. package/scripts/install-sweep-hook.sh +12 -0
  174. package/scripts/install.sh +11 -0
  175. package/scripts/opencode-wrapper.sh +11 -0
  176. package/scripts/portal/cloud-init.yaml +69 -0
  177. package/scripts/portal/setup.sh +69 -0
  178. package/scripts/portal/stackmemory-portal.service +34 -0
  179. package/scripts/setup-claude-integration.sh +12 -1
  180. package/scripts/smoke-init-db.sh +23 -0
  181. package/scripts/stackmemory-daemon.sh +11 -0
  182. package/scripts/verify-dist.cjs +11 -4
  183. package/dist/src/cli/commands/ralph.js +0 -1053
  184. package/dist/src/cli/commands/team.js +0 -168
  185. package/dist/src/core/context/shared-context-layer.js +0 -620
  186. package/dist/src/core/context/stack-merge-resolver.js +0 -748
  187. package/dist/src/core/merge/conflict-detector.js +0 -430
  188. package/dist/src/core/merge/resolution-engine.js +0 -557
  189. package/dist/src/core/merge/stack-diff.js +0 -531
  190. package/dist/src/core/merge/unified-merge-resolver.js +0 -302
  191. package/dist/src/hooks/diffmem-hooks.js +0 -376
  192. package/dist/src/integrations/diffmem/client.js +0 -208
  193. package/dist/src/integrations/diffmem/config.js +0 -14
  194. package/dist/src/integrations/greptile/client.js +0 -101
  195. package/dist/src/integrations/greptile/config.js +0 -14
  196. package/dist/src/integrations/greptile/index.js +0 -11
  197. package/dist/src/integrations/mcp/handlers/cord-handlers.js +0 -397
  198. package/dist/src/integrations/mcp/handlers/diffmem-handlers.js +0 -455
  199. package/dist/src/integrations/mcp/handlers/greptile-handlers.js +0 -456
  200. package/dist/src/integrations/mcp/handlers/provider-handlers.js +0 -227
  201. package/dist/src/integrations/mcp/handlers/team-handlers.js +0 -211
  202. package/dist/src/integrations/ralph/bridge/ralph-stackmemory-bridge.js +0 -863
  203. package/dist/src/integrations/ralph/context/context-budget-manager.js +0 -308
  204. package/dist/src/integrations/ralph/context/stackmemory-context-loader.js +0 -391
  205. package/dist/src/integrations/ralph/index.js +0 -17
  206. package/dist/src/integrations/ralph/learning/pattern-learner.js +0 -435
  207. package/dist/src/integrations/ralph/lifecycle/iteration-lifecycle.js +0 -448
  208. package/dist/src/integrations/ralph/loopmax.js +0 -488
  209. package/dist/src/integrations/ralph/monitoring/swarm-dashboard.js +0 -293
  210. package/dist/src/integrations/ralph/monitoring/swarm-registry.js +0 -107
  211. package/dist/src/integrations/ralph/orchestration/multi-loop-orchestrator.js +0 -508
  212. package/dist/src/integrations/ralph/patterns/compounding-engineering-pattern.js +0 -407
  213. package/dist/src/integrations/ralph/patterns/extended-coherence-sessions.js +0 -495
  214. package/dist/src/integrations/ralph/patterns/oracle-worker-pattern.js +0 -387
  215. package/dist/src/integrations/ralph/performance/performance-optimizer.js +0 -357
  216. package/dist/src/integrations/ralph/recovery/crash-recovery.js +0 -461
  217. package/dist/src/integrations/ralph/state/state-reconciler.js +0 -420
  218. package/dist/src/integrations/ralph/swarm/git-workflow-manager.js +0 -444
  219. package/dist/src/integrations/ralph/swarm/swarm-coordinator.js +0 -1007
  220. package/dist/src/integrations/ralph/visualization/ralph-debugger.js +0 -635
  221. package/scripts/ralph-loop-implementation.js +0 -404
  222. /package/dist/src/core/{merge → cache}/types.js +0 -0
  223. /package/dist/src/{integrations/diffmem/types.js → core/storage/cloud-sync-types.js} +0 -0
  224. /package/dist/src/{integrations/greptile/types.js → core/trace/trace-event.js} +0 -0
  225. /package/dist/src/{integrations/ralph → features/operator}/types.js +0 -0
@@ -1,435 +0,0 @@
1
- import { fileURLToPath as __fileURLToPath } from 'url';
2
- import { dirname as __pathDirname } from 'path';
3
- const __filename = __fileURLToPath(import.meta.url);
4
- const __dirname = __pathDirname(__filename);
5
- import { logger } from "../../../core/monitoring/logger.js";
6
- import { FrameManager } from "../../../core/context/index.js";
7
- import { sharedContextLayer } from "../../../core/context/shared-context-layer.js";
8
- import { sessionManager } from "../../../core/session/index.js";
9
- class PatternLearner {
10
- frameManager;
11
- config;
12
- constructor(config) {
13
- this.config = {
14
- minLoopCountForPattern: 3,
15
- confidenceThreshold: 0.7,
16
- maxPatternsPerType: 10,
17
- analysisDepth: "deep",
18
- ...config
19
- };
20
- logger.info("Pattern learner initialized", this.config);
21
- }
22
- async initialize() {
23
- try {
24
- await sessionManager.initialize();
25
- await sharedContextLayer.initialize();
26
- const session = await sessionManager.getOrCreateSession({});
27
- if (session.database) {
28
- this.frameManager = new FrameManager(
29
- session.database,
30
- session.projectId
31
- );
32
- }
33
- logger.info("Pattern learner initialized successfully");
34
- } catch (error) {
35
- logger.error("Failed to initialize pattern learner", error);
36
- throw error;
37
- }
38
- }
39
- /**
40
- * Learn patterns from all completed Ralph loops
41
- */
42
- async learnFromCompletedLoops() {
43
- logger.info("Starting pattern learning from completed loops");
44
- try {
45
- const completedLoops = await this.getCompletedRalphLoops();
46
- logger.info(
47
- `Found ${completedLoops.length} completed loops for analysis`
48
- );
49
- if (completedLoops.length < this.config.minLoopCountForPattern) {
50
- logger.info("Not enough loops for pattern extraction");
51
- return [];
52
- }
53
- const patterns = [];
54
- const successPatterns = await this.extractSuccessPatterns(completedLoops);
55
- patterns.push(...successPatterns);
56
- const failurePatterns = await this.extractFailurePatterns(completedLoops);
57
- patterns.push(...failurePatterns);
58
- const iterationPatterns = await this.extractIterationPatterns(completedLoops);
59
- patterns.push(...iterationPatterns);
60
- const taskPatterns = await this.extractTaskPatterns(completedLoops);
61
- patterns.push(...taskPatterns);
62
- await this.saveLearnedPatterns(patterns);
63
- logger.info(
64
- `Learned ${patterns.length} patterns from ${completedLoops.length} loops`
65
- );
66
- return patterns;
67
- } catch (error) {
68
- logger.error("Failed to learn patterns", error);
69
- throw error;
70
- }
71
- }
72
- /**
73
- * Learn patterns specific to a task type
74
- */
75
- async learnForTaskType(taskType) {
76
- logger.info(`Learning patterns for task type: ${taskType}`);
77
- const completedLoops = await this.getCompletedRalphLoops();
78
- const relevantLoops = completedLoops.filter(
79
- (loop) => this.classifyTaskType(loop.task) === taskType
80
- );
81
- if (relevantLoops.length < this.config.minLoopCountForPattern) {
82
- return [];
83
- }
84
- return this.extractSpecializedPatterns(relevantLoops, taskType);
85
- }
86
- /**
87
- * Get all completed Ralph loops from StackMemory
88
- */
89
- async getCompletedRalphLoops() {
90
- if (!this.frameManager) {
91
- throw new Error("Frame manager not initialized");
92
- }
93
- try {
94
- const ralphFrames = await this.frameManager.searchFrames({
95
- type: "task",
96
- namePattern: "ralph-*",
97
- state: "closed"
98
- });
99
- const analyses = [];
100
- for (const frame of ralphFrames) {
101
- try {
102
- const analysis = await this.analyzeCompletedLoop(frame);
103
- if (analysis) {
104
- analyses.push(analysis);
105
- }
106
- } catch (error) {
107
- logger.warn(
108
- `Failed to analyze loop ${frame.frame_id}`,
109
- error
110
- );
111
- }
112
- }
113
- return analyses;
114
- } catch (error) {
115
- logger.error("Failed to get completed loops", error);
116
- return [];
117
- }
118
- }
119
- /**
120
- * Analyze a completed loop for patterns
121
- */
122
- async analyzeCompletedLoop(ralphFrame) {
123
- if (!this.frameManager) return null;
124
- try {
125
- const loopState = ralphFrame.inputs;
126
- const iterationFrames = await this.frameManager.searchFrames({
127
- type: "subtask",
128
- namePattern: "iteration-*",
129
- parentId: ralphFrame.frame_id
130
- });
131
- const successMetrics = this.calculateSuccessMetrics(iterationFrames);
132
- const iterationAnalysis = this.analyzeIterations(iterationFrames);
133
- const outcome = this.determineLoopOutcome(ralphFrame, iterationFrames);
134
- return {
135
- loopId: loopState.loopId,
136
- task: loopState.task,
137
- criteria: loopState.criteria,
138
- taskType: this.classifyTaskType(loopState.task),
139
- iterationCount: iterationFrames.length,
140
- outcome,
141
- successMetrics,
142
- iterationAnalysis,
143
- duration: ralphFrame.updated_at - ralphFrame.created_at,
144
- startTime: ralphFrame.created_at,
145
- endTime: ralphFrame.updated_at
146
- };
147
- } catch (error) {
148
- logger.error("Failed to analyze loop", error);
149
- return null;
150
- }
151
- }
152
- /**
153
- * Extract patterns from successful loops
154
- */
155
- async extractSuccessPatterns(loops) {
156
- const successfulLoops = loops.filter((l) => l.outcome === "success");
157
- if (successfulLoops.length < this.config.minLoopCountForPattern) {
158
- return [];
159
- }
160
- const patterns = [];
161
- const avgIterations = successfulLoops.reduce((sum, l) => sum + l.iterationCount, 0) / successfulLoops.length;
162
- patterns.push({
163
- id: "optimal-iterations",
164
- type: "iteration_strategy",
165
- pattern: `Successful tasks typically complete in ${Math.round(avgIterations)} iterations`,
166
- confidence: this.calculateConfidence(successfulLoops.length),
167
- frequency: successfulLoops.length,
168
- strategy: `Target ${Math.round(avgIterations)} iterations for similar tasks`,
169
- examples: successfulLoops.slice(0, 3).map((l) => l.task),
170
- metadata: {
171
- avgIterations,
172
- minIterations: Math.min(
173
- ...successfulLoops.map((l) => l.iterationCount)
174
- ),
175
- maxIterations: Math.max(
176
- ...successfulLoops.map((l) => l.iterationCount)
177
- )
178
- }
179
- });
180
- const criteriaPatterns = this.extractCriteriaPatterns(successfulLoops);
181
- patterns.push(...criteriaPatterns);
182
- const successFactors = this.extractSuccessFactors(successfulLoops);
183
- patterns.push(...successFactors);
184
- return patterns.filter(
185
- (p) => p.confidence >= this.config.confidenceThreshold
186
- );
187
- }
188
- /**
189
- * Extract patterns from failed loops to avoid
190
- */
191
- async extractFailurePatterns(loops) {
192
- const failedLoops = loops.filter((l) => l.outcome === "failure");
193
- if (failedLoops.length < this.config.minLoopCountForPattern) {
194
- return [];
195
- }
196
- const patterns = [];
197
- const commonFailures = this.analyzeFailurePoints(failedLoops);
198
- for (const failure of commonFailures) {
199
- patterns.push({
200
- id: `avoid-${failure.type}`,
201
- type: "failure_avoidance",
202
- pattern: `Avoid: ${failure.pattern}`,
203
- confidence: this.calculateConfidence(failure.frequency),
204
- frequency: failure.frequency,
205
- strategy: failure.avoidanceStrategy,
206
- examples: failure.examples,
207
- metadata: { failureType: failure.type }
208
- });
209
- }
210
- return patterns.filter(
211
- (p) => p.confidence >= this.config.confidenceThreshold
212
- );
213
- }
214
- /**
215
- * Extract iteration-specific patterns
216
- */
217
- async extractIterationPatterns(loops) {
218
- const patterns = [];
219
- const iterationSequences = this.analyzeIterationSequences(loops);
220
- for (const sequence of iterationSequences) {
221
- if (sequence.frequency >= this.config.minLoopCountForPattern) {
222
- patterns.push({
223
- id: `iteration-sequence-${sequence.id}`,
224
- type: "iteration_sequence",
225
- pattern: sequence.description,
226
- confidence: this.calculateConfidence(sequence.frequency),
227
- frequency: sequence.frequency,
228
- strategy: sequence.strategy,
229
- examples: sequence.examples,
230
- metadata: { sequenceType: sequence.type }
231
- });
232
- }
233
- }
234
- return patterns;
235
- }
236
- /**
237
- * Extract task-specific patterns
238
- */
239
- async extractTaskPatterns(loops) {
240
- const taskGroups = this.groupByTaskType(loops);
241
- const patterns = [];
242
- for (const [taskType, taskLoops] of Object.entries(taskGroups)) {
243
- if (taskLoops.length >= this.config.minLoopCountForPattern) {
244
- const taskSpecificPatterns = await this.extractSpecializedPatterns(
245
- taskLoops,
246
- taskType
247
- );
248
- patterns.push(...taskSpecificPatterns);
249
- }
250
- }
251
- return patterns;
252
- }
253
- /**
254
- * Extract specialized patterns for specific task types
255
- */
256
- async extractSpecializedPatterns(loops, taskType) {
257
- const patterns = [];
258
- const successful = loops.filter((l) => l.outcome === "success");
259
- if (successful.length === 0) return patterns;
260
- patterns.push({
261
- id: `${taskType}-success-pattern`,
262
- type: "task_specific",
263
- pattern: `${taskType} tasks: ${this.summarizeSuccessPattern(successful)}`,
264
- confidence: this.calculateConfidence(successful.length),
265
- frequency: successful.length,
266
- strategy: this.generateTaskStrategy(successful),
267
- examples: successful.slice(0, 2).map((l) => l.task),
268
- metadata: { taskType, totalAttempts: loops.length }
269
- });
270
- return patterns;
271
- }
272
- /**
273
- * Calculate success metrics for iterations
274
- */
275
- calculateSuccessMetrics(iterations) {
276
- const total = iterations.length;
277
- const successful = iterations.filter((i) => i.outputs?.success).length;
278
- return {
279
- iterationCount: total,
280
- successRate: total > 0 ? successful / total : 0,
281
- averageProgress: this.calculateAverageProgress(iterations),
282
- timeToCompletion: total > 0 ? iterations[total - 1].updated_at - iterations[0].created_at : 0
283
- };
284
- }
285
- /**
286
- * Classify task type based on description
287
- */
288
- classifyTaskType(task) {
289
- const taskLower = task.toLowerCase();
290
- if (taskLower.includes("test") || taskLower.includes("unit"))
291
- return "testing";
292
- if (taskLower.includes("fix") || taskLower.includes("bug")) return "bugfix";
293
- if (taskLower.includes("refactor")) return "refactoring";
294
- if (taskLower.includes("add") || taskLower.includes("implement"))
295
- return "feature";
296
- if (taskLower.includes("document")) return "documentation";
297
- if (taskLower.includes("optimize") || taskLower.includes("performance"))
298
- return "optimization";
299
- return "general";
300
- }
301
- /**
302
- * Determine loop outcome
303
- */
304
- determineLoopOutcome(ralphFrame, iterations) {
305
- if (ralphFrame.digest_json?.status === "completed") return "success";
306
- if (iterations.length === 0) return "unknown";
307
- const lastIteration = iterations[iterations.length - 1];
308
- if (lastIteration.outputs?.success) return "success";
309
- return "failure";
310
- }
311
- /**
312
- * Calculate confidence based on frequency
313
- */
314
- calculateConfidence(frequency) {
315
- return Math.min(0.95, Math.log(frequency + 1) / Math.log(10));
316
- }
317
- /**
318
- * Save learned patterns to shared context
319
- */
320
- async saveLearnedPatterns(patterns) {
321
- try {
322
- const context = await sharedContextLayer.getSharedContext();
323
- if (!context) return;
324
- const contextPatterns = patterns.map((p) => ({
325
- pattern: p.pattern,
326
- type: this.mapPatternType(p.type),
327
- frequency: p.frequency,
328
- lastSeen: Date.now(),
329
- resolution: p.strategy
330
- }));
331
- context.globalPatterns.push(...contextPatterns);
332
- context.globalPatterns.sort((a, b) => b.frequency - a.frequency);
333
- context.globalPatterns = context.globalPatterns.slice(0, 100);
334
- await sharedContextLayer.updateSharedContext(context);
335
- logger.info(`Saved ${patterns.length} patterns to shared context`);
336
- } catch (error) {
337
- logger.error("Failed to save patterns", error);
338
- }
339
- }
340
- /**
341
- * Map pattern types to shared context types
342
- */
343
- mapPatternType(patternType) {
344
- switch (patternType) {
345
- case "failure_avoidance":
346
- return "error";
347
- case "success_strategy":
348
- return "success";
349
- case "task_specific":
350
- return "learning";
351
- default:
352
- return "learning";
353
- }
354
- }
355
- // Additional helper methods for pattern analysis
356
- analyzeIterations(iterations) {
357
- return {
358
- avgDuration: iterations.length > 0 ? iterations.reduce(
359
- (sum, i) => sum + (i.updated_at - i.created_at),
360
- 0
361
- ) / iterations.length : 0,
362
- progressPattern: this.extractProgressPattern(iterations),
363
- commonIssues: this.extractCommonIssues(iterations)
364
- };
365
- }
366
- extractProgressPattern(iterations) {
367
- const progressSteps = iterations.map((_, i) => {
368
- const progress = i / iterations.length;
369
- return Math.round(progress * 100);
370
- });
371
- return progressSteps.join(" \u2192 ") + "%";
372
- }
373
- extractCommonIssues(iterations) {
374
- return iterations.filter((i) => i.outputs?.errors?.length > 0).flatMap((i) => i.outputs.errors).slice(0, 3);
375
- }
376
- extractCriteriaPatterns(loops) {
377
- const criteriaWords = loops.flatMap(
378
- (l) => l.criteria.toLowerCase().split(/\s+/)
379
- );
380
- const wordCounts = criteriaWords.reduce(
381
- (acc, word) => {
382
- acc[word] = (acc[word] || 0) + 1;
383
- return acc;
384
- },
385
- {}
386
- );
387
- const commonCriteria = Object.entries(wordCounts).filter(([_, count]) => count >= this.config.minLoopCountForPattern).sort((a, b) => b[1] - a[1]).slice(0, 3);
388
- return commonCriteria.map(([word, count]) => ({
389
- id: `criteria-${word}`,
390
- type: "success_strategy",
391
- pattern: `Successful tasks often include "${word}" in completion criteria`,
392
- confidence: this.calculateConfidence(count),
393
- frequency: count,
394
- strategy: `Consider including "${word}" in task completion criteria`,
395
- examples: loops.filter((l) => l.criteria.toLowerCase().includes(word)).slice(0, 2).map((l) => l.task),
396
- metadata: { criteriaWord: word }
397
- }));
398
- }
399
- extractSuccessFactors(_loops) {
400
- return [];
401
- }
402
- analyzeFailurePoints(_loops) {
403
- return [];
404
- }
405
- analyzeIterationSequences(_loops) {
406
- return [];
407
- }
408
- groupByTaskType(loops) {
409
- return loops.reduce(
410
- (acc, loop) => {
411
- const type = loop.taskType;
412
- if (!acc[type]) acc[type] = [];
413
- acc[type].push(loop);
414
- return acc;
415
- },
416
- {}
417
- );
418
- }
419
- summarizeSuccessPattern(loops) {
420
- const avgIterations = loops.reduce((sum, l) => sum + l.iterationCount, 0) / loops.length;
421
- return `typically complete in ${Math.round(avgIterations)} iterations with ${Math.round(loops[0]?.successMetrics?.successRate * 100 || 0)}% success rate`;
422
- }
423
- generateTaskStrategy(loops) {
424
- const avgIterations = loops.reduce((sum, l) => sum + l.iterationCount, 0) / loops.length;
425
- return `Plan for approximately ${Math.round(avgIterations)} iterations and focus on iterative improvement`;
426
- }
427
- calculateAverageProgress(iterations) {
428
- return iterations.length > 0 ? iterations.length / 10 : 0;
429
- }
430
- }
431
- const patternLearner = new PatternLearner();
432
- export {
433
- PatternLearner,
434
- patternLearner
435
- };