@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.
- package/LICENSE +131 -64
- package/README.md +107 -24
- package/bin/claude-sm +16 -1
- package/bin/claude-smd +16 -1
- package/bin/codex-smd +16 -1
- package/bin/gemini-sm +16 -1
- package/bin/hermes-sm +21 -0
- package/bin/hermes-smd +21 -0
- package/bin/opencode-sm +16 -1
- package/dist/src/cli/claude-sm.js +266 -84
- package/dist/src/cli/codex-sm.js +225 -33
- package/dist/src/cli/commands/bench.js +209 -2
- package/dist/src/cli/commands/brain.js +206 -0
- package/dist/src/cli/commands/cache.js +126 -0
- package/dist/src/cli/commands/company-os.js +184 -0
- package/dist/src/cli/commands/context.js +5 -0
- package/dist/src/cli/commands/daemon.js +41 -0
- package/dist/src/cli/commands/handoff.js +40 -9
- package/dist/src/cli/commands/onboard.js +70 -3
- package/dist/src/cli/commands/operator.js +127 -0
- package/dist/src/cli/commands/optimize.js +117 -0
- package/dist/src/cli/commands/orchestrate.js +232 -5
- package/dist/src/cli/commands/orchestrator.js +315 -26
- package/dist/src/cli/commands/pack.js +322 -0
- package/dist/src/cli/commands/patterns.js +254 -0
- package/dist/src/cli/commands/portal.js +161 -0
- package/dist/src/cli/commands/scaffold.js +92 -0
- package/dist/src/cli/commands/search.js +40 -1
- package/dist/src/cli/commands/setup.js +178 -11
- package/dist/src/cli/commands/skills.js +10 -1
- package/dist/src/cli/commands/state.js +265 -0
- package/dist/src/cli/commands/sync.js +253 -0
- package/dist/src/cli/commands/tasks.js +130 -1
- package/dist/src/cli/commands/vision.js +221 -0
- package/dist/src/cli/gemini-sm.js +19 -29
- package/dist/src/cli/hermes-sm.js +224 -0
- package/dist/src/cli/index.js +105 -39
- package/dist/src/cli/opencode-sm.js +38 -21
- package/dist/src/cli/utils/determinism-watcher.js +66 -0
- package/dist/src/cli/utils/real-cli-bin.js +116 -0
- package/dist/src/core/brain/brain-store.js +187 -0
- package/dist/src/core/brain/brain-sync.js +193 -0
- package/dist/src/core/brain/index.js +78 -0
- package/dist/src/core/brain/types.js +10 -0
- package/dist/src/core/cache/content-cache.js +238 -0
- package/dist/src/{integrations/diffmem → core/cache}/index.js +5 -5
- package/dist/src/core/cache/token-estimator.js +39 -0
- package/dist/src/core/config/feature-flags.js +2 -6
- package/dist/src/core/context/frame-database.js +79 -27
- package/dist/src/core/context/recursive-context-manager.js +1 -1
- package/dist/src/core/context/rehydration.js +2 -1
- package/dist/src/core/cross-search/cross-project-search.js +269 -0
- package/dist/src/core/cross-search/index.js +10 -0
- package/dist/src/core/database/sqlite-adapter.js +14 -84
- package/dist/src/core/extensions/provider-adapter.js +5 -0
- package/dist/src/core/models/model-router.js +54 -2
- package/dist/src/core/models/provider-pricing.js +58 -4
- package/dist/src/core/monitoring/logger.js +2 -1
- package/dist/src/core/optimization/trace-optimizer.js +413 -0
- package/dist/src/core/patterns/index.js +22 -0
- package/dist/src/core/patterns/pattern-applier.js +39 -0
- package/dist/src/core/patterns/pattern-observer.js +157 -0
- package/dist/src/core/patterns/pattern-store.js +259 -0
- package/dist/src/core/patterns/types.js +19 -0
- package/dist/src/core/provenance/confidence-scorer.js +128 -0
- package/dist/src/core/provenance/index.js +40 -0
- package/dist/src/core/provenance/provenance-store.js +194 -0
- package/dist/src/core/provenance/types.js +82 -0
- package/dist/src/core/retrieval/llm-context-retrieval.js +5 -4
- package/dist/src/core/retrieval/unified-context-assembler.js +11 -66
- package/dist/src/core/session/project-handoff.js +64 -0
- package/dist/src/core/session/session-manager.js +28 -0
- package/dist/src/core/shared-state/canonical-store.js +564 -0
- package/dist/src/core/skill-packs/index.js +18 -0
- package/dist/src/core/skill-packs/parser.js +42 -0
- package/dist/src/core/skill-packs/registry.js +224 -0
- package/dist/src/core/skill-packs/types.js +79 -0
- package/dist/src/core/storage/cloud-sync-manager.js +116 -0
- package/dist/src/core/storage/cloud-sync.js +574 -0
- package/dist/src/core/storage/two-tier-storage.js +5 -1
- package/dist/src/core/tasks/master-tasks-template.js +43 -0
- package/dist/src/core/tasks/md-task-parser.js +138 -0
- package/dist/src/core/trace/trace-event-store.js +282 -0
- package/dist/src/core/vision/index.js +27 -0
- package/dist/src/core/vision/signals.js +79 -0
- package/dist/src/core/vision/types.js +22 -0
- package/dist/src/core/vision/vision-file.js +146 -0
- package/dist/src/core/vision/vision-loop.js +220 -0
- package/dist/src/core/wiki/wiki-compiler.js +103 -1
- package/dist/src/daemon/daemon-config.js +52 -0
- package/dist/src/daemon/services/desire-path-service.js +566 -0
- package/dist/src/daemon/services/github-service.js +126 -0
- package/dist/src/daemon/services/research-stream-service.js +320 -0
- package/dist/src/daemon/services/telemetry-service.js +192 -0
- package/dist/src/daemon/unified-daemon.js +58 -1
- package/dist/src/features/browser/cli-browser-agent.js +417 -0
- package/dist/src/features/browser/stagehand-workflows.js +578 -0
- package/dist/src/features/operator/adapter-factory.js +62 -0
- package/dist/src/features/operator/browser-adapter.js +109 -0
- package/dist/src/features/operator/desktop-adapter.js +125 -0
- package/dist/src/features/operator/index.js +39 -0
- package/dist/src/features/operator/llm-decision.js +137 -0
- package/dist/src/features/operator/operator-logger.js +92 -0
- package/dist/src/features/operator/overnight-runner.js +327 -0
- package/dist/src/features/operator/screen-adapter.js +91 -0
- package/dist/src/features/operator/session-manager.js +127 -0
- package/dist/src/features/operator/state-machine.js +227 -0
- package/dist/src/features/operator/task-queue.js +81 -0
- package/dist/src/features/portal/index.js +26 -0
- package/dist/src/features/portal/server.js +240 -0
- package/dist/src/features/portal/types.js +14 -0
- package/dist/src/features/portal/ui.js +195 -0
- package/dist/src/features/sweep/pty-wrapper.js +13 -5
- package/dist/src/features/tasks/task-aware-context.js +2 -1
- package/dist/src/features/tui/simple-monitor.js +0 -23
- package/dist/src/features/tui/swarm-monitor.js +8 -66
- package/dist/src/features/web/client/hooks/use-socket.js +12 -0
- package/dist/src/{core/merge/index.js → features/web/client/lib/utils.js} +8 -4
- package/dist/src/features/web/client/next-env.d.js +4 -0
- package/dist/src/features/web/client/stores/session-store.js +12 -0
- package/dist/src/features/web/server/gcp-billing.js +76 -0
- package/dist/src/features/web/server/index.js +10 -0
- package/dist/src/features/web/server/spend-calculator.js +228 -0
- package/dist/src/hooks/schemas.js +6 -1
- package/dist/src/integrations/anthropic/client.js +3 -2
- package/dist/src/integrations/claude-code/agent-bridge.js +0 -3
- package/dist/src/integrations/claude-code/subagent-client.js +307 -11
- package/dist/src/integrations/claude-code/task-coordinator.js +2 -1
- package/dist/src/integrations/github/pr-state.js +158 -0
- package/dist/src/integrations/linear/client.js +4 -1
- package/dist/src/integrations/linear/webhook-retry.js +196 -0
- package/dist/src/integrations/linear/webhook-server.js +18 -22
- package/dist/src/integrations/mcp/handlers/cloud-sync-handlers.js +101 -0
- package/dist/src/integrations/mcp/handlers/index.js +40 -84
- package/dist/src/integrations/mcp/server.js +542 -641
- package/dist/src/integrations/mcp/tool-alias-registry.js +297 -0
- package/dist/src/integrations/mcp/tool-definitions.js +152 -682
- package/dist/src/mcp/stackmemory-mcp-server.js +571 -231
- package/dist/src/orchestrators/multimodal/determinism.js +244 -0
- package/dist/src/orchestrators/multimodal/harness.js +149 -78
- package/dist/src/orchestrators/multimodal/providers.js +44 -3
- package/dist/src/skills/recursive-agent-orchestrator.js +2 -4
- package/dist/src/utils/hook-installer.js +0 -8
- package/dist/src/utils/process-cleanup.js +1 -7
- package/docs/README.md +42 -0
- package/docs/guides/README_INSTALL.md +208 -0
- package/package.json +27 -9
- package/packs/coding/python-fastapi/instructions.md +60 -0
- package/packs/coding/python-fastapi/pack.yaml +28 -0
- package/packs/coding/typescript-react/instructions.md +47 -0
- package/packs/coding/typescript-react/pack.yaml +28 -0
- package/packs/core/commands/capture.md +32 -0
- package/packs/core/commands/learn.md +73 -0
- package/packs/core/commands/next.md +36 -0
- package/packs/core/commands/restart.md +58 -0
- package/packs/core/commands/restore.md +29 -0
- package/packs/core/commands/start.md +57 -0
- package/packs/core/commands/stop.md +65 -0
- package/packs/core/commands/summary.md +40 -0
- package/packs/core/manifest.json +24 -0
- package/packs/ops/decision-recovery/instructions.md +65 -0
- package/packs/ops/decision-recovery/pack.yaml +89 -0
- package/scripts/claude-code-wrapper.sh +11 -0
- package/scripts/claude-sm-setup.sh +12 -1
- package/scripts/codex-wrapper.sh +11 -0
- package/scripts/git-hooks/branch-context-manager.sh +11 -0
- package/scripts/git-hooks/post-checkout-stackmemory.sh +11 -0
- package/scripts/git-hooks/post-commit-stackmemory.sh +11 -0
- package/scripts/git-hooks/pre-commit-stackmemory.sh +11 -0
- package/scripts/hooks/cleanup-shell.sh +12 -1
- package/scripts/hooks/task-complete.sh +12 -1
- package/scripts/install-code-execution-hooks.sh +12 -1
- package/scripts/install-sweep-hook.sh +12 -0
- package/scripts/install.sh +11 -0
- package/scripts/opencode-wrapper.sh +11 -0
- package/scripts/portal/cloud-init.yaml +69 -0
- package/scripts/portal/setup.sh +69 -0
- package/scripts/portal/stackmemory-portal.service +34 -0
- package/scripts/setup-claude-integration.sh +12 -1
- package/scripts/smoke-init-db.sh +23 -0
- package/scripts/stackmemory-daemon.sh +11 -0
- package/scripts/verify-dist.cjs +11 -4
- package/dist/src/cli/commands/ralph.js +0 -1053
- package/dist/src/cli/commands/team.js +0 -168
- package/dist/src/core/context/shared-context-layer.js +0 -620
- package/dist/src/core/context/stack-merge-resolver.js +0 -748
- package/dist/src/core/merge/conflict-detector.js +0 -430
- package/dist/src/core/merge/resolution-engine.js +0 -557
- package/dist/src/core/merge/stack-diff.js +0 -531
- package/dist/src/core/merge/unified-merge-resolver.js +0 -302
- package/dist/src/hooks/diffmem-hooks.js +0 -376
- package/dist/src/integrations/diffmem/client.js +0 -208
- package/dist/src/integrations/diffmem/config.js +0 -14
- package/dist/src/integrations/greptile/client.js +0 -101
- package/dist/src/integrations/greptile/config.js +0 -14
- package/dist/src/integrations/greptile/index.js +0 -11
- package/dist/src/integrations/mcp/handlers/cord-handlers.js +0 -397
- package/dist/src/integrations/mcp/handlers/diffmem-handlers.js +0 -455
- package/dist/src/integrations/mcp/handlers/greptile-handlers.js +0 -456
- package/dist/src/integrations/mcp/handlers/provider-handlers.js +0 -227
- package/dist/src/integrations/mcp/handlers/team-handlers.js +0 -211
- package/dist/src/integrations/ralph/bridge/ralph-stackmemory-bridge.js +0 -863
- package/dist/src/integrations/ralph/context/context-budget-manager.js +0 -308
- package/dist/src/integrations/ralph/context/stackmemory-context-loader.js +0 -391
- package/dist/src/integrations/ralph/index.js +0 -17
- package/dist/src/integrations/ralph/learning/pattern-learner.js +0 -435
- package/dist/src/integrations/ralph/lifecycle/iteration-lifecycle.js +0 -448
- package/dist/src/integrations/ralph/loopmax.js +0 -488
- package/dist/src/integrations/ralph/monitoring/swarm-dashboard.js +0 -293
- package/dist/src/integrations/ralph/monitoring/swarm-registry.js +0 -107
- package/dist/src/integrations/ralph/orchestration/multi-loop-orchestrator.js +0 -508
- package/dist/src/integrations/ralph/patterns/compounding-engineering-pattern.js +0 -407
- package/dist/src/integrations/ralph/patterns/extended-coherence-sessions.js +0 -495
- package/dist/src/integrations/ralph/patterns/oracle-worker-pattern.js +0 -387
- package/dist/src/integrations/ralph/performance/performance-optimizer.js +0 -357
- package/dist/src/integrations/ralph/recovery/crash-recovery.js +0 -461
- package/dist/src/integrations/ralph/state/state-reconciler.js +0 -420
- package/dist/src/integrations/ralph/swarm/git-workflow-manager.js +0 -444
- package/dist/src/integrations/ralph/swarm/swarm-coordinator.js +0 -1007
- package/dist/src/integrations/ralph/visualization/ralph-debugger.js +0 -635
- package/scripts/ralph-loop-implementation.js +0 -404
- /package/dist/src/core/{merge → cache}/types.js +0 -0
- /package/dist/src/{integrations/diffmem/types.js → core/storage/cloud-sync-types.js} +0 -0
- /package/dist/src/{integrations/greptile/types.js → core/trace/trace-event.js} +0 -0
- /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
|
-
};
|