@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,495 +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 { v4 as uuidv4 } from "uuid";
6
- import * as fs from "fs/promises";
7
- import * as path from "path";
8
- import { logger } from "../../../core/monitoring/logger.js";
9
- import { RalphStackMemoryBridge } from "../bridge/ralph-stackmemory-bridge.js";
10
- class ExtendedCoherenceManager {
11
- activeSessions = /* @__PURE__ */ new Map();
12
- baseDir;
13
- monitoringInterval;
14
- performanceHistory = /* @__PURE__ */ new Map();
15
- constructor(baseDir = "./.coherence-sessions") {
16
- this.baseDir = baseDir;
17
- }
18
- /**
19
- * Initialize the coherence management system
20
- */
21
- async initialize() {
22
- await fs.mkdir(this.baseDir, { recursive: true });
23
- this.monitoringInterval = setInterval(
24
- () => this.monitorActiveSessionsHealth(),
25
- 6e4
26
- // Check every minute
27
- );
28
- logger.info("Extended Coherence Manager initialized", {
29
- baseDir: this.baseDir,
30
- monitoringEnabled: true
31
- });
32
- }
33
- /**
34
- * Start an extended coherence work session
35
- */
36
- async startCoherenceSession(agentConfig, taskConfig, sessionConfig) {
37
- const sessionId = uuidv4();
38
- const defaultConfig = this.generateConfigForComplexity(
39
- taskConfig.complexity
40
- );
41
- const config = { ...defaultConfig, ...sessionConfig };
42
- const session = {
43
- id: sessionId,
44
- agent: agentConfig,
45
- task: {
46
- ...taskConfig,
47
- breakpoints: taskConfig.breakpoints || this.generateBreakpoints(taskConfig)
48
- },
49
- config,
50
- state: {
51
- status: "active",
52
- currentPhase: "initialization",
53
- completedMilestones: [],
54
- lastCheckpoint: Date.now(),
55
- interventionCount: 0,
56
- refreshCount: 0
57
- },
58
- metrics: [],
59
- interventions: []
60
- };
61
- this.activeSessions.set(sessionId, session);
62
- await this.initializeSessionWorkspace(session);
63
- await this.launchAgentSession(session);
64
- logger.info("Extended coherence session started", {
65
- sessionId,
66
- agent: agentConfig.role,
67
- estimatedDuration: taskConfig.estimatedDuration,
68
- maxDuration: config.maxDuration
69
- });
70
- return sessionId;
71
- }
72
- /**
73
- * Generate configuration optimized for task complexity
74
- */
75
- generateConfigForComplexity(complexity) {
76
- const configs = {
77
- low: {
78
- maxDuration: 60,
79
- // 1 hour
80
- coherenceThreshold: 0.7,
81
- checkpointInterval: 15,
82
- // 15 minutes
83
- refreshStrategy: "checkpoint",
84
- enableMemoryPalace: false,
85
- enableProgressTracking: true,
86
- enableAutoRefresh: false,
87
- enableHealthMonitoring: true
88
- },
89
- medium: {
90
- maxDuration: 180,
91
- // 3 hours
92
- coherenceThreshold: 0.8,
93
- checkpointInterval: 10,
94
- // 10 minutes
95
- refreshStrategy: "context_refresh",
96
- enableMemoryPalace: true,
97
- enableProgressTracking: true,
98
- enableAutoRefresh: true,
99
- enableHealthMonitoring: true
100
- },
101
- high: {
102
- maxDuration: 360,
103
- // 6 hours
104
- coherenceThreshold: 0.85,
105
- checkpointInterval: 8,
106
- // 8 minutes
107
- refreshStrategy: "context_refresh",
108
- enableMemoryPalace: true,
109
- enableProgressTracking: true,
110
- enableAutoRefresh: true,
111
- enableHealthMonitoring: true
112
- },
113
- very_high: {
114
- maxDuration: 720,
115
- // 12 hours
116
- coherenceThreshold: 0.9,
117
- checkpointInterval: 5,
118
- // 5 minutes
119
- refreshStrategy: "full_restart",
120
- enableMemoryPalace: true,
121
- enableProgressTracking: true,
122
- enableAutoRefresh: true,
123
- enableHealthMonitoring: true
124
- }
125
- };
126
- return configs[complexity];
127
- }
128
- /**
129
- * Monitor active sessions for coherence degradation
130
- */
131
- async monitorActiveSessionsHealth() {
132
- for (const [_sessionId, session] of this.activeSessions) {
133
- if (session.state.status === "active") {
134
- await this.assessSessionCoherence(session);
135
- }
136
- }
137
- }
138
- /**
139
- * Assess session coherence and intervene if necessary
140
- */
141
- async assessSessionCoherence(session) {
142
- const metrics = await this.calculateCoherenceMetrics(session);
143
- session.metrics.push(metrics);
144
- if (session.metrics.length > 10) {
145
- session.metrics.shift();
146
- }
147
- const overallCoherence = this.calculateOverallCoherence(metrics);
148
- logger.debug("Session coherence assessment", {
149
- sessionId: session.id,
150
- coherence: overallCoherence,
151
- threshold: session.config.coherenceThreshold,
152
- duration: metrics.duration
153
- });
154
- if (overallCoherence < session.config.coherenceThreshold) {
155
- await this.interventeInSession(
156
- session,
157
- "coherence_degradation",
158
- overallCoherence
159
- );
160
- }
161
- const timeSinceCheckpoint = Date.now() - session.state.lastCheckpoint;
162
- const checkpointDue = timeSinceCheckpoint > session.config.checkpointInterval * 60 * 1e3;
163
- if (checkpointDue) {
164
- await this.checkpointSession(session);
165
- }
166
- }
167
- /**
168
- * Calculate comprehensive coherence metrics
169
- */
170
- async calculateCoherenceMetrics(session) {
171
- const now = Date.now();
172
- const duration = (now - session.metrics[0]?.startTime || now) / (1e3 * 60);
173
- const recentOutputs = await this.getRecentAgentOutputs(session);
174
- const outputQuality = this.assessOutputQuality(recentOutputs);
175
- const contextRetention = this.assessContextRetention(
176
- recentOutputs,
177
- session.task
178
- );
179
- const taskRelevance = this.assessTaskRelevance(recentOutputs, session.task);
180
- const repetitionRate = this.calculateRepetitionRate(recentOutputs);
181
- const divergenceRate = this.calculateDivergenceRate(
182
- recentOutputs,
183
- session.task
184
- );
185
- const errorRate = this.calculateErrorRate(recentOutputs);
186
- const progressRate = this.calculateProgressRate(session);
187
- return {
188
- sessionId: session.id,
189
- startTime: session.metrics[0]?.startTime || now,
190
- currentTime: now,
191
- duration,
192
- outputQuality,
193
- contextRetention,
194
- taskRelevance,
195
- progressRate,
196
- repetitionRate,
197
- divergenceRate,
198
- errorRate,
199
- memoryUsage: await this.getMemoryUsage(session),
200
- contextWindowUsage: await this.getContextWindowUsage(session),
201
- stateCheckpoints: session.interventions.filter(
202
- (i) => i.type === "checkpoint"
203
- ).length
204
- };
205
- }
206
- /**
207
- * Calculate overall coherence score
208
- */
209
- calculateOverallCoherence(metrics) {
210
- const weights = {
211
- outputQuality: 0.3,
212
- contextRetention: 0.25,
213
- taskRelevance: 0.25,
214
- repetitionPenalty: 0.1,
215
- // penalty for repetition
216
- divergencePenalty: 0.1
217
- // penalty for divergence
218
- };
219
- const baseScore = metrics.outputQuality * weights.outputQuality + metrics.contextRetention * weights.contextRetention + metrics.taskRelevance * weights.taskRelevance;
220
- const penalties = metrics.repetitionRate * weights.repetitionPenalty + metrics.divergenceRate * weights.divergencePenalty;
221
- return Math.max(0, baseScore - penalties);
222
- }
223
- /**
224
- * Intervene in a session to restore coherence
225
- */
226
- async interventeInSession(session, reason, currentCoherence) {
227
- logger.warn("Intervening in session due to coherence degradation", {
228
- sessionId: session.id,
229
- reason,
230
- currentCoherence,
231
- interventionCount: session.state.interventionCount
232
- });
233
- const intervention = {
234
- timestamp: Date.now(),
235
- type: session.config.refreshStrategy,
236
- reason,
237
- effectiveness: 0
238
- // will be calculated later
239
- };
240
- switch (session.config.refreshStrategy) {
241
- case "checkpoint":
242
- await this.checkpointSession(session);
243
- break;
244
- case "context_refresh":
245
- await this.refreshSessionContext(session);
246
- break;
247
- case "full_restart":
248
- await this.restartSession(session);
249
- break;
250
- default:
251
- await this.provideGuidance(session, reason);
252
- intervention.type = "guidance";
253
- }
254
- session.interventions.push(intervention);
255
- session.state.interventionCount++;
256
- const _previousStatus = session.state.status;
257
- session.state.status = "degraded";
258
- setTimeout(async () => {
259
- const newMetrics = await this.calculateCoherenceMetrics(session);
260
- const newCoherence = this.calculateOverallCoherence(newMetrics);
261
- intervention.effectiveness = Math.max(0, newCoherence - currentCoherence);
262
- if (newCoherence > session.config.coherenceThreshold) {
263
- session.state.status = "active";
264
- logger.info("Session coherence restored", {
265
- sessionId: session.id,
266
- newCoherence,
267
- effectiveness: intervention.effectiveness
268
- });
269
- }
270
- }, 12e4);
271
- }
272
- /**
273
- * Create a checkpoint of session state
274
- */
275
- async checkpointSession(session) {
276
- const checkpointPath = path.join(
277
- this.baseDir,
278
- session.id,
279
- `checkpoint-${Date.now()}.json`
280
- );
281
- const checkpointData = {
282
- timestamp: Date.now(),
283
- state: session.state,
284
- recentMetrics: session.metrics.slice(-3),
285
- currentPhase: session.state.currentPhase,
286
- completedMilestones: session.state.completedMilestones,
287
- // Include recent agent context
288
- contextSummary: await this.generateContextSummary(session)
289
- };
290
- await fs.writeFile(checkpointPath, JSON.stringify(checkpointData, null, 2));
291
- session.state.lastCheckpoint = Date.now();
292
- logger.info("Session checkpoint created", {
293
- sessionId: session.id,
294
- checkpointPath
295
- });
296
- }
297
- /**
298
- * Refresh session context to restore coherence
299
- */
300
- async refreshSessionContext(session) {
301
- logger.info("Refreshing session context", { sessionId: session.id });
302
- const refreshPrompt = await this.generateContextRefreshPrompt(session);
303
- await this.applyContextRefresh(session, refreshPrompt);
304
- session.state.refreshCount++;
305
- }
306
- /**
307
- * Restart session from last good checkpoint
308
- */
309
- async restartSession(session) {
310
- logger.info("Restarting session from checkpoint", {
311
- sessionId: session.id
312
- });
313
- const checkpoint = await this.loadLatestCheckpoint(session);
314
- if (checkpoint) {
315
- session.state = { ...checkpoint.state };
316
- await this.restartAgentFromCheckpoint(session, checkpoint);
317
- } else {
318
- await this.restartAgentFromBeginning(session);
319
- }
320
- }
321
- /**
322
- * Initialize workspace for a coherence session
323
- */
324
- async initializeSessionWorkspace(session) {
325
- const sessionDir = path.join(this.baseDir, session.id);
326
- await fs.mkdir(sessionDir, { recursive: true });
327
- const manifest = {
328
- sessionId: session.id,
329
- agent: session.agent,
330
- task: session.task,
331
- config: session.config,
332
- createdAt: Date.now()
333
- };
334
- await fs.writeFile(
335
- path.join(sessionDir, "manifest.json"),
336
- JSON.stringify(manifest, null, 2)
337
- );
338
- }
339
- /**
340
- * Launch the actual agent work session
341
- */
342
- async launchAgentSession(session) {
343
- const sessionDir = path.join(this.baseDir, session.id);
344
- const ralph = new RalphStackMemoryBridge({
345
- baseDir: sessionDir,
346
- maxIterations: Math.ceil(session.config.maxDuration / 5),
347
- // ~5 min per iteration
348
- useStackMemory: true
349
- });
350
- await ralph.initialize({
351
- task: this.buildExtendedCoherencePrompt(session),
352
- criteria: session.task.breakpoints.join("\n")
353
- });
354
- ralph.run().catch((error) => {
355
- logger.error("Extended coherence session failed", {
356
- sessionId: session.id,
357
- error: error.message
358
- });
359
- session.state.status = "failed";
360
- });
361
- }
362
- /**
363
- * Build prompt optimized for extended coherence
364
- */
365
- buildExtendedCoherencePrompt(session) {
366
- return `
367
- # EXTENDED COHERENCE WORK SESSION
368
-
369
- ## Your Mission
370
- ${session.task.description}
371
-
372
- ## Session Parameters
373
- - Estimated Duration: ${session.task.estimatedDuration} minutes
374
- - Maximum Duration: ${session.config.maxDuration} minutes
375
- - Coherence Threshold: ${session.config.coherenceThreshold * 100}%
376
-
377
- ## Coherence Guidelines
378
- 1. **Maintain Focus**: Stay on task throughout the entire session
379
- 2. **Track Progress**: Document incremental progress at each step
380
- 3. **Context Awareness**: Reference previous work and maintain consistency
381
- 4. **Quality Control**: Regularly assess your output quality
382
- 5. **Milestone Reporting**: Report when you reach natural breakpoints
383
-
384
- ## Breakpoints & Milestones
385
- ${session.task.breakpoints.map((bp, i) => `${i + 1}. ${bp}`).join("\n")}
386
-
387
- ## Extended Session Strategy
388
- - Take regular checkpoint breaks (every ${session.config.checkpointInterval} minutes)
389
- - Summarize your progress regularly
390
- - Ask for context refresh if you feel you're losing focus
391
- - Maintain awareness of the overall project goal
392
- - Break complex tasks into smaller, manageable chunks
393
-
394
- ## Memory Palace (if enabled)
395
- ${session.config.enableMemoryPalace ? `
396
- Use structured memory organization:
397
- - **Project Context**: Overall goals and requirements
398
- - **Current Status**: What's been completed and what's next
399
- - **Working Memory**: Current task details and immediate context
400
- - **Reference Memory**: Important patterns, decisions, and learnings
401
- ` : ""}
402
-
403
- ## Success Criteria
404
- - Complete the task within the allocated time
405
- - Maintain high output quality throughout
406
- - Document progress and decisions clearly
407
- - Stay coherent and focused for the entire session
408
-
409
- Begin your extended coherence work session now.
410
- `;
411
- }
412
- // Placeholder implementations for helper methods
413
- async getRecentAgentOutputs(_session) {
414
- return [];
415
- }
416
- assessOutputQuality(_outputs) {
417
- return 0.8;
418
- }
419
- assessContextRetention(_outputs, _task) {
420
- return 0.7;
421
- }
422
- assessTaskRelevance(_outputs, _task) {
423
- return 0.9;
424
- }
425
- calculateRepetitionRate(_outputs) {
426
- return 0.1;
427
- }
428
- calculateDivergenceRate(_outputs, _task) {
429
- return 0.05;
430
- }
431
- calculateErrorRate(_outputs) {
432
- return 0.02;
433
- }
434
- calculateProgressRate(_session) {
435
- return 2.5;
436
- }
437
- async getMemoryUsage(_session) {
438
- return 150;
439
- }
440
- async getContextWindowUsage(_session) {
441
- return 65;
442
- }
443
- generateBreakpoints(_taskConfig) {
444
- return [
445
- "Initial analysis complete",
446
- "Core implementation finished",
447
- "Testing phase complete",
448
- "Final review and cleanup done"
449
- ];
450
- }
451
- async generateContextSummary(session) {
452
- return `Session ${session.id} context summary`;
453
- }
454
- async generateContextRefreshPrompt(_session) {
455
- return "Context refresh prompt";
456
- }
457
- async applyContextRefresh(_session, _prompt) {
458
- }
459
- async loadLatestCheckpoint(_session) {
460
- return null;
461
- }
462
- async restartAgentFromCheckpoint(_session, _checkpoint) {
463
- }
464
- async restartAgentFromBeginning(_session) {
465
- }
466
- async provideGuidance(_session, _reason) {
467
- }
468
- /**
469
- * Get extended coherence capabilities
470
- */
471
- getCoherenceCapabilities() {
472
- const activeSessions = Array.from(this.activeSessions.values());
473
- return {
474
- maxSessionDuration: Math.max(
475
- ...activeSessions.map((s) => s.config.maxDuration)
476
- ),
477
- activeSessionCount: activeSessions.filter(
478
- (s) => s.state.status === "active"
479
- ).length,
480
- averageCoherence: activeSessions.reduce((sum, s) => {
481
- const recent = s.metrics.slice(-1)[0];
482
- return sum + (recent ? this.calculateOverallCoherence(recent) : 0);
483
- }, 0) / activeSessions.length,
484
- totalInterventions: activeSessions.reduce(
485
- (sum, s) => sum + s.interventions.length,
486
- 0
487
- )
488
- };
489
- }
490
- }
491
- var extended_coherence_sessions_default = ExtendedCoherenceManager;
492
- export {
493
- ExtendedCoherenceManager,
494
- extended_coherence_sessions_default as default
495
- };