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