@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,557 +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 { ConflictDetector } from "./conflict-detector.js";
7
- import { StackDiffVisualizer } from "./stack-diff.js";
8
- import { logger } from "../monitoring/logger.js";
9
- class ResolutionEngine {
10
- conflictDetector;
11
- diffVisualizer;
12
- resolutionHistory = /* @__PURE__ */ new Map();
13
- constructor() {
14
- this.conflictDetector = new ConflictDetector();
15
- this.diffVisualizer = new StackDiffVisualizer();
16
- }
17
- /**
18
- * Resolve conflicts using the specified strategy
19
- */
20
- async resolveConflicts(stack1, stack2, strategy, context) {
21
- const conflicts = this.conflictDetector.detectConflicts(stack1, stack2);
22
- logger.info(
23
- `Resolving ${conflicts.length} conflicts using ${strategy} strategy`,
24
- {
25
- userId: context.userId,
26
- userRole: context.userRole
27
- }
28
- );
29
- let resolution;
30
- switch (strategy) {
31
- case "keep_both":
32
- resolution = await this.keepBothStrategy(
33
- conflicts,
34
- stack1,
35
- stack2,
36
- context
37
- );
38
- break;
39
- case "team_vote":
40
- resolution = await this.teamVoteStrategy(
41
- conflicts,
42
- stack1,
43
- stack2,
44
- context
45
- );
46
- break;
47
- case "senior_override":
48
- resolution = await this.seniorOverrideStrategy(
49
- conflicts,
50
- stack1,
51
- stack2,
52
- context
53
- );
54
- break;
55
- case "ai_suggest":
56
- resolution = await this.aiSuggestStrategy(
57
- conflicts,
58
- stack1,
59
- stack2,
60
- context
61
- );
62
- break;
63
- case "hybrid":
64
- resolution = await this.hybridStrategy(
65
- conflicts,
66
- stack1,
67
- stack2,
68
- context
69
- );
70
- break;
71
- default:
72
- throw new Error(`Unknown resolution strategy: ${strategy}`);
73
- }
74
- const mergeResult = await this.executeMerge(
75
- stack1,
76
- stack2,
77
- conflicts,
78
- resolution
79
- );
80
- this.storeResolution(mergeResult.mergedFrameId || "", resolution);
81
- return mergeResult;
82
- }
83
- /**
84
- * Strategy: Keep Both Solutions
85
- * Creates a merged frame that includes both approaches
86
- */
87
- async keepBothStrategy(conflicts, stack1, stack2, context) {
88
- logger.info("Applying keep_both strategy");
89
- const strategy = {
90
- type: "keep_both",
91
- confidence: 0.8,
92
- reasoning: "Preserving both solutions to maintain all work and allow future evaluation"
93
- };
94
- for (const conflict of conflicts) {
95
- conflict.resolution = {
96
- strategy,
97
- resolvedBy: context.userId,
98
- resolvedAt: Date.now(),
99
- notes: "Both solutions preserved in merged frame"
100
- };
101
- }
102
- return {
103
- strategy,
104
- resolvedBy: context.userId,
105
- resolvedAt: Date.now(),
106
- notes: `Kept all ${stack1.frames.length + stack2.frames.length} frames from both stacks`
107
- };
108
- }
109
- /**
110
- * Strategy: Team Vote
111
- * Uses democratic voting to choose between options
112
- */
113
- async teamVoteStrategy(conflicts, stack1, stack2, context) {
114
- logger.info("Applying team_vote strategy");
115
- if (!context.teamVotes || context.teamVotes.length === 0) {
116
- throw new Error("Team vote strategy requires votes from team members");
117
- }
118
- const voteResults = this.countVotes(context.teamVotes);
119
- const strategy = {
120
- type: "team_vote",
121
- confidence: this.calculateVoteConfidence(voteResults),
122
- reasoning: `Team consensus from ${context.teamVotes.length} votes`,
123
- votes: context.teamVotes
124
- };
125
- for (const conflict of conflicts) {
126
- conflict.resolution = {
127
- strategy,
128
- resolvedBy: "team_consensus",
129
- resolvedAt: Date.now(),
130
- notes: `Resolved by ${voteResults.consensus}% consensus`
131
- };
132
- }
133
- return {
134
- strategy,
135
- resolvedBy: "team_consensus",
136
- resolvedAt: Date.now(),
137
- notes: `Democratic resolution with ${voteResults.consensus}% agreement`
138
- };
139
- }
140
- /**
141
- * Strategy: Senior Override
142
- * Senior developer's choice takes precedence
143
- */
144
- async seniorOverrideStrategy(conflicts, stack1, stack2, context) {
145
- logger.info("Applying senior_override strategy");
146
- if (context.userRole !== "senior" && context.userRole !== "lead") {
147
- throw new Error("Senior override requires senior or lead role");
148
- }
149
- this.determinePreferredStack(stack1, stack2, context);
150
- const strategy = {
151
- type: "senior_override",
152
- confidence: 0.95,
153
- reasoning: `Senior developer (${context.userId}) selected based on experience and architectural knowledge`
154
- };
155
- for (const conflict of conflicts) {
156
- conflict.resolution = {
157
- strategy,
158
- resolvedBy: context.userId,
159
- resolvedAt: Date.now(),
160
- notes: `Overridden by ${context.userRole} authority`
161
- };
162
- }
163
- return {
164
- strategy,
165
- resolvedBy: context.userId,
166
- resolvedAt: Date.now(),
167
- notes: `Senior override applied to all ${conflicts.length} conflicts`
168
- };
169
- }
170
- /**
171
- * Strategy: AI Suggest
172
- * Uses AI analysis to recommend best resolution
173
- */
174
- async aiSuggestStrategy(conflicts, stack1, stack2, context) {
175
- logger.info("Applying ai_suggest strategy");
176
- const analysis = await this.analyzeFrameQuality(stack1, stack2);
177
- const strategy = {
178
- type: "ai_suggest",
179
- confidence: context.aiConfidence || 0.85,
180
- reasoning: this.generateAIReasoning(analysis)
181
- };
182
- for (const conflict of conflicts) {
183
- const recommendation = this.getAIRecommendation(conflict, analysis);
184
- conflict.resolution = {
185
- strategy,
186
- resolvedBy: "ai_system",
187
- resolvedAt: Date.now(),
188
- notes: recommendation
189
- };
190
- }
191
- return {
192
- strategy,
193
- resolvedBy: "ai_system",
194
- resolvedAt: Date.now(),
195
- notes: `AI analysis with ${strategy.confidence * 100}% confidence`
196
- };
197
- }
198
- /**
199
- * Strategy: Hybrid
200
- * Combines multiple strategies based on conflict type
201
- */
202
- async hybridStrategy(conflicts, stack1, stack2, context) {
203
- logger.info("Applying hybrid strategy");
204
- const strategy = {
205
- type: "hybrid",
206
- confidence: 0.9,
207
- reasoning: "Using optimal strategy for each conflict type"
208
- };
209
- for (const conflict of conflicts) {
210
- let subStrategy;
211
- switch (conflict.type) {
212
- case "parallel_solution":
213
- subStrategy = "keep_both";
214
- break;
215
- case "conflicting_decision":
216
- subStrategy = "ai_suggest";
217
- break;
218
- case "structural_divergence":
219
- subStrategy = context.userRole === "senior" || context.userRole === "lead" ? "senior_override" : "team_vote";
220
- break;
221
- default:
222
- subStrategy = "ai_suggest";
223
- }
224
- conflict.resolution = {
225
- strategy: {
226
- ...strategy,
227
- reasoning: `${subStrategy} for ${conflict.type}`
228
- },
229
- resolvedBy: context.userId,
230
- resolvedAt: Date.now(),
231
- notes: `Hybrid resolution using ${subStrategy}`
232
- };
233
- }
234
- return {
235
- strategy,
236
- resolvedBy: context.userId,
237
- resolvedAt: Date.now(),
238
- notes: `Hybrid strategy optimized for each conflict type`
239
- };
240
- }
241
- /**
242
- * Execute the merge based on resolution
243
- */
244
- async executeMerge(stack1, stack2, conflicts, resolution) {
245
- const mergedFrameId = uuidv4();
246
- const rollbackPoint = this.createRollbackPoint(stack1, stack2);
247
- const notifications = [];
248
- try {
249
- const mergedFrames = this.mergeFrames(
250
- stack1,
251
- stack2,
252
- conflicts,
253
- resolution
254
- );
255
- const isValid = this.validateMerge(mergedFrames, conflicts);
256
- if (!isValid) {
257
- throw new Error("Merge validation failed");
258
- }
259
- const notifyResults = await this.sendNotifications(conflicts, resolution);
260
- notifications.push(...notifyResults);
261
- logger.info("Merge executed successfully", {
262
- mergedFrameId,
263
- frameCount: mergedFrames.length,
264
- strategy: resolution.strategy.type
265
- });
266
- return {
267
- success: true,
268
- mergedFrameId,
269
- conflicts,
270
- resolution,
271
- rollbackPoint,
272
- notifications
273
- };
274
- } catch (error) {
275
- logger.error("Merge execution failed", error);
276
- return {
277
- success: false,
278
- conflicts,
279
- resolution,
280
- rollbackPoint,
281
- notifications
282
- };
283
- }
284
- }
285
- /**
286
- * Count votes from team members
287
- */
288
- countVotes(votes) {
289
- const counts = {
290
- frame1: 0,
291
- frame2: 0,
292
- both: 0,
293
- neither: 0,
294
- total: votes.length,
295
- consensus: 0
296
- };
297
- for (const vote of votes) {
298
- counts[vote.choice]++;
299
- }
300
- const maxVotes = Math.max(
301
- counts.frame1,
302
- counts.frame2,
303
- counts.both,
304
- counts.neither
305
- );
306
- counts.consensus = Math.round(maxVotes / counts.total * 100);
307
- return counts;
308
- }
309
- /**
310
- * Calculate confidence based on vote distribution
311
- */
312
- calculateVoteConfidence(voteResults) {
313
- if (voteResults.consensus >= 80) return 0.95;
314
- if (voteResults.consensus >= 60) return 0.75;
315
- if (voteResults.consensus >= 40) return 0.5;
316
- return 0.3;
317
- }
318
- /**
319
- * Determine winner from vote results
320
- */
321
- determineVoteWinner(conflict, voteResults) {
322
- if (voteResults.frame1 > voteResults.frame2) return conflict.frameId1;
323
- if (voteResults.frame2 > voteResults.frame1) return conflict.frameId2;
324
- if (voteResults.both > voteResults.neither) return "both";
325
- return "neither";
326
- }
327
- /**
328
- * Determine preferred stack for senior override
329
- */
330
- determinePreferredStack(stack1, stack2, context) {
331
- if (stack1.owner === context.userId) return stack1;
332
- if (stack2.owner === context.userId) return stack2;
333
- if (stack1.lastModified > stack2.lastModified) return stack1;
334
- if (stack2.frames.filter((f) => f.state === "closed").length > stack1.frames.filter((f) => f.state === "closed").length) {
335
- return stack2;
336
- }
337
- return stack1;
338
- }
339
- /**
340
- * Analyze frame quality for AI suggestions
341
- */
342
- async analyzeFrameQuality(stack1, stack2) {
343
- const analysis = {
344
- stack1: {
345
- completeness: this.calculateCompleteness(stack1),
346
- efficiency: this.calculateEfficiency(stack1),
347
- quality: this.calculateQuality(stack1)
348
- },
349
- stack2: {
350
- completeness: this.calculateCompleteness(stack2),
351
- efficiency: this.calculateEfficiency(stack2),
352
- quality: this.calculateQuality(stack2)
353
- }
354
- };
355
- return analysis;
356
- }
357
- /**
358
- * Calculate stack completeness
359
- */
360
- calculateCompleteness(stack) {
361
- const closedFrames = stack.frames.filter(
362
- (f) => f.state === "closed"
363
- ).length;
364
- return closedFrames / stack.frames.length;
365
- }
366
- /**
367
- * Calculate stack efficiency
368
- */
369
- calculateEfficiency(stack) {
370
- let totalDuration = 0;
371
- let completedFrames = 0;
372
- for (const frame of stack.frames) {
373
- if (frame.closed_at && frame.created_at) {
374
- totalDuration += frame.closed_at - frame.created_at;
375
- completedFrames++;
376
- }
377
- }
378
- if (completedFrames === 0) return 0;
379
- const avgDuration = totalDuration / completedFrames;
380
- return Math.max(0, Math.min(1, 3e5 / avgDuration));
381
- }
382
- /**
383
- * Calculate stack quality
384
- */
385
- calculateQuality(stack) {
386
- let qualityScore = 0;
387
- for (const frame of stack.frames) {
388
- if (frame.outputs && Object.keys(frame.outputs).length > 0)
389
- qualityScore += 0.3;
390
- if (frame.digest_text) qualityScore += 0.3;
391
- if (frame.state === "closed") qualityScore += 0.4;
392
- }
393
- return Math.min(1, qualityScore / stack.frames.length);
394
- }
395
- /**
396
- * Generate AI reasoning for resolution
397
- */
398
- generateAIReasoning(analysis) {
399
- const stack1Score = analysis.stack1.completeness * 0.3 + analysis.stack1.efficiency * 0.3 + analysis.stack1.quality * 0.4;
400
- const stack2Score = analysis.stack2.completeness * 0.3 + analysis.stack2.efficiency * 0.3 + analysis.stack2.quality * 0.4;
401
- if (stack1Score > stack2Score) {
402
- return `Stack 1 shows higher overall quality (${(stack1Score * 100).toFixed(1)}% vs ${(stack2Score * 100).toFixed(1)}%)`;
403
- } else {
404
- return `Stack 2 shows higher overall quality (${(stack2Score * 100).toFixed(1)}% vs ${(stack1Score * 100).toFixed(1)}%)`;
405
- }
406
- }
407
- /**
408
- * Get AI recommendation for specific conflict
409
- */
410
- getAIRecommendation(conflict) {
411
- switch (conflict.type) {
412
- case "parallel_solution":
413
- return "Recommend keeping both solutions for A/B testing";
414
- case "conflicting_decision":
415
- return "Recommend the decision with higher quality score";
416
- case "structural_divergence":
417
- return "Recommend restructuring to accommodate both approaches";
418
- default:
419
- return "Recommend manual review for this conflict";
420
- }
421
- }
422
- /**
423
- * Create rollback point before merge
424
- */
425
- createRollbackPoint(_stack1, _stack2) {
426
- const rollbackId = uuidv4();
427
- logger.info("Created rollback point", { rollbackId });
428
- return rollbackId;
429
- }
430
- /**
431
- * Merge frames based on resolution
432
- */
433
- mergeFrames(stack1, stack2, conflicts, resolution) {
434
- const mergedFrames = [];
435
- const processedIds = /* @__PURE__ */ new Set();
436
- switch (resolution.strategy.type) {
437
- case "keep_both":
438
- mergedFrames.push(...stack1.frames, ...stack2.frames);
439
- break;
440
- case "team_vote":
441
- case "senior_override":
442
- case "ai_suggest":
443
- for (const frame of stack1.frames) {
444
- const conflict = conflicts.find((c) => c.frameId1 === frame.frame_id);
445
- if (!conflict || conflict.resolution?.strategy.type === "keep_both") {
446
- mergedFrames.push(frame);
447
- processedIds.add(frame.frame_id);
448
- }
449
- }
450
- for (const frame of stack2.frames) {
451
- if (!processedIds.has(frame.frame_id)) {
452
- const conflict = conflicts.find(
453
- (c) => c.frameId2 === frame.frame_id
454
- );
455
- if (!conflict || conflict.resolution?.strategy.type === "keep_both") {
456
- mergedFrames.push(frame);
457
- }
458
- }
459
- }
460
- break;
461
- case "hybrid":
462
- this.hybridMerge(stack1, stack2, conflicts, mergedFrames);
463
- break;
464
- }
465
- return mergedFrames;
466
- }
467
- /**
468
- * Hybrid merge implementation
469
- */
470
- hybridMerge(stack1, stack2, conflicts, mergedFrames) {
471
- const conflictMap = /* @__PURE__ */ new Map();
472
- for (const conflict of conflicts) {
473
- conflictMap.set(conflict.frameId1, conflict);
474
- conflictMap.set(conflict.frameId2, conflict);
475
- }
476
- for (const frame of [...stack1.frames, ...stack2.frames]) {
477
- const conflict = conflictMap.get(frame.frame_id);
478
- if (!conflict) {
479
- if (!mergedFrames.find((f) => f.frame_id === frame.frame_id)) {
480
- mergedFrames.push(frame);
481
- }
482
- } else if (conflict.type === "parallel_solution") {
483
- if (!mergedFrames.find((f) => f.frame_id === frame.frame_id)) {
484
- mergedFrames.push(frame);
485
- }
486
- }
487
- }
488
- }
489
- /**
490
- * Validate merge integrity
491
- */
492
- validateMerge(mergedFrames, conflicts) {
493
- const ids = /* @__PURE__ */ new Set();
494
- for (const frame of mergedFrames) {
495
- if (ids.has(frame.frame_id)) {
496
- logger.error("Duplicate frame ID in merge", {
497
- frameId: frame.frame_id
498
- });
499
- return false;
500
- }
501
- ids.add(frame.frame_id);
502
- }
503
- for (const frame of mergedFrames) {
504
- if (frame.parent_frame_id) {
505
- const parent = mergedFrames.find(
506
- (f) => f.frame_id === frame.parent_frame_id
507
- );
508
- if (!parent) {
509
- logger.warn("Orphaned frame in merge", { frameId: frame.frame_id });
510
- }
511
- }
512
- }
513
- for (const conflict of conflicts) {
514
- if (!conflict.resolution) {
515
- logger.error("Unresolved conflict in merge", {
516
- conflictId: conflict.id
517
- });
518
- return false;
519
- }
520
- }
521
- return true;
522
- }
523
- /**
524
- * Send notifications about merge
525
- */
526
- async sendNotifications(conflicts, resolution) {
527
- const notifications = [];
528
- const notification = {
529
- userId: resolution.resolvedBy || "team",
530
- type: "in-app",
531
- sent: true,
532
- timestamp: Date.now()
533
- };
534
- notifications.push(notification);
535
- logger.info("Notifications sent", { count: notifications.length });
536
- return notifications;
537
- }
538
- /**
539
- * Store resolution in history
540
- */
541
- storeResolution(mergeId, resolution) {
542
- this.resolutionHistory.set(mergeId, resolution);
543
- logger.info("Resolution stored in history", {
544
- mergeId,
545
- strategy: resolution.strategy.type
546
- });
547
- }
548
- /**
549
- * Get resolution history for analysis
550
- */
551
- getResolutionHistory() {
552
- return this.resolutionHistory;
553
- }
554
- }
555
- export {
556
- ResolutionEngine
557
- };