@myrialabs/clopen 0.4.26 → 0.4.27

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 (93) hide show
  1. package/backend/auth/permissions.ts +21 -0
  2. package/backend/bootstrap.ts +18 -1
  3. package/backend/chat/engine-handoff.test.ts +229 -0
  4. package/backend/chat/engine-handoff.ts +439 -0
  5. package/backend/chat/stream-manager.ts +200 -16
  6. package/backend/database/migrations/066_create_memory_graph.ts +369 -0
  7. package/backend/database/migrations/index.ts +7 -0
  8. package/backend/database/queries/audit-log-queries.test.ts +10 -1
  9. package/backend/database/queries/graph-queries.ts +1764 -0
  10. package/backend/database/queries/index.ts +2 -0
  11. package/backend/database/queries/memory-queue-queries.ts +381 -0
  12. package/backend/database/queries/snapshot-queries.ts +20 -0
  13. package/backend/engine/README.md +45 -2
  14. package/backend/engine/adapters/copilot/stream.ts +37 -1
  15. package/backend/engine/adapters/pi/models.ts +19 -7
  16. package/backend/engine/adapters/pi/stream.ts +2 -1
  17. package/backend/engine/docs/adapter-contract.md +25 -8
  18. package/backend/engine/docs/adding-an-engine.md +40 -4
  19. package/backend/engine/docs/frontend-and-chat.md +66 -1
  20. package/backend/engine/docs/lessons-learned.md +165 -6
  21. package/backend/engine/docs/quick-reference.md +10 -0
  22. package/backend/engine/docs/stack.md +10 -0
  23. package/backend/engine/docs/websocket-routes.md +15 -1
  24. package/backend/engine/engine-setup.ts +1 -1
  25. package/backend/engine/index.test.ts +186 -0
  26. package/backend/engine/index.ts +117 -71
  27. package/backend/engine/install-recipes.test.ts +105 -0
  28. package/backend/engine/install-recipes.ts +4 -1
  29. package/backend/index.ts +9 -0
  30. package/backend/mcp/internal/config.ts +6 -0
  31. package/backend/mcp/internal/servers/index.ts +2 -0
  32. package/backend/mcp/internal/servers/memory-graph/description.ts +33 -0
  33. package/backend/mcp/internal/servers/memory-graph/format.ts +45 -0
  34. package/backend/mcp/internal/servers/memory-graph/index.ts +52 -0
  35. package/backend/mcp/internal/servers/memory-graph/runner.ts +342 -0
  36. package/backend/mcp/internal/servers/memory-graph/schema.ts +140 -0
  37. package/backend/memory/README.md +432 -0
  38. package/backend/memory/bootstrap.ts +101 -0
  39. package/backend/memory/compose.test.ts +198 -0
  40. package/backend/memory/compose.ts +343 -0
  41. package/backend/memory/config.ts +100 -0
  42. package/backend/memory/consolidate.ts +280 -0
  43. package/backend/memory/context.test.ts +321 -0
  44. package/backend/memory/context.ts +451 -0
  45. package/backend/memory/embedding/embedder.test.ts +141 -0
  46. package/backend/memory/embedding/embedder.ts +269 -0
  47. package/backend/memory/embedding/index.ts +17 -0
  48. package/backend/memory/embedding/install.ts +254 -0
  49. package/backend/memory/embedding/paths.ts +101 -0
  50. package/backend/memory/embedding/vector-cache.ts +270 -0
  51. package/backend/memory/extract/episodic.ts +725 -0
  52. package/backend/memory/extract/index.ts +133 -0
  53. package/backend/memory/extract/languages.ts +176 -0
  54. package/backend/memory/extract/scheduler.test.ts +352 -0
  55. package/backend/memory/extract/scheduler.ts +406 -0
  56. package/backend/memory/extract/structural.test.ts +215 -0
  57. package/backend/memory/extract/structural.ts +364 -0
  58. package/backend/memory/index.ts +37 -0
  59. package/backend/memory/indexer.ts +150 -0
  60. package/backend/memory/invalidate.ts +134 -0
  61. package/backend/memory/judge.ts +285 -0
  62. package/backend/memory/maintenance.ts +132 -0
  63. package/backend/memory/model.ts +91 -0
  64. package/backend/memory/notify.ts +102 -0
  65. package/backend/memory/readiness.ts +74 -0
  66. package/backend/memory/redact.test.ts +101 -0
  67. package/backend/memory/redact.ts +133 -0
  68. package/backend/memory/retention.ts +139 -0
  69. package/backend/memory/retrieval.eval.test.ts +301 -0
  70. package/backend/memory/retrieval.test.ts +1023 -0
  71. package/backend/memory/retrieval.ts +707 -0
  72. package/backend/memory/revise.test.ts +693 -0
  73. package/backend/memory/revise.ts +400 -0
  74. package/backend/memory/time.ts +31 -0
  75. package/backend/memory/view.ts +164 -0
  76. package/backend/shipped-runtime-imports.test.ts +228 -0
  77. package/backend/ws/index.ts +5 -1
  78. package/backend/ws/memory/crud.ts +631 -0
  79. package/backend/ws/memory/index.ts +41 -0
  80. package/backend/ws/sessions/crud.ts +10 -0
  81. package/backend/ws/snapshot/restore.ts +38 -4
  82. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +1 -0
  83. package/dist/assets/{index-B6QGUN03.js → index-BCv5HlPk.js} +1 -1
  84. package/dist/assets/{index-DYa-GDsb.js → index-BTGcf_Vy.js} +1 -1
  85. package/dist/assets/main-BrqMMMRX.css +1 -0
  86. package/dist/assets/{main-Dznkfxsd.js → main-CgmAFpU3.js} +835 -426
  87. package/dist/index.html +2 -2
  88. package/package.json +8 -2
  89. package/shared/types/database/connection.ts +9 -0
  90. package/shared/types/memory.ts +519 -0
  91. package/shared/utils/logger.ts +1 -0
  92. package/dist/assets/main-Dh-MTGNR.css +0 -1
  93. package/shared/utils/anonymous-user.ts +0 -168
@@ -12,73 +12,109 @@
12
12
  * Each project gets its own engine instance so abort controllers,
13
13
  * active queries, and session IDs are fully isolated.
14
14
  * Cancelling Project A's stream never affects Project B.
15
+ *
16
+ * Adapters are loaded on first use, never at boot. This registry used to import
17
+ * all eight statically, which coupled every user's startup to every adapter: one
18
+ * adapter failing to load — an SDK that isn't installed, a bad module-level
19
+ * expression — took down the whole backend, including for someone who only ever
20
+ * uses Claude. Loading per engine keeps that failure where it belongs, on the
21
+ * engine being asked for, and the existing pre-stream readiness check
22
+ * (`checkEngineSetup`) turns it into an actionable chat error.
23
+ *
24
+ * A load failure is deliberately NOT caught here. There is exactly one place
25
+ * that decides what an unusable engine means to the user, and adding a second
26
+ * one would let a broken engine masquerade as a working one.
15
27
  */
16
28
 
17
29
  import type { AIEngine, EngineType } from './types';
18
- import { ClaudeCodeEngine } from './adapters/claude';
19
- import { OpenCodeEngine, disposeOpenCodeClient } from './adapters/opencode';
20
- import { CopilotEngine } from './adapters/copilot';
21
- import { CodexEngine } from './adapters/codex';
22
- import { QwenEngine } from './adapters/qwen';
23
- import { PiEngine } from './adapters/pi';
24
- import { ClineEngine } from './adapters/cline';
25
- import { CursorEngine } from './adapters/cursor';
30
+ // The one exception to lazy loading: the OpenCode server module holds a
31
+ // process-wide client singleton that shutdown must release. It is imported
32
+ // directly (not via the adapter barrel) so it does not drag in the engine class.
33
+ import { disposeOpenCodeClient } from './adapters/opencode/server';
26
34
  import { debug } from '$shared/utils/logger';
27
35
 
28
36
  // ============================================================================
29
- // Helpers
37
+ // Adapter loading
30
38
  // ============================================================================
31
39
 
32
- function createEngine(type: EngineType): AIEngine {
33
- switch (type) {
34
- case 'claude-code':
35
- return new ClaudeCodeEngine();
36
- case 'opencode':
37
- return new OpenCodeEngine();
38
- case 'copilot':
39
- return new CopilotEngine();
40
- case 'codex':
41
- return new CodexEngine();
42
- case 'qwen':
43
- return new QwenEngine();
44
- case 'pi':
45
- return new PiEngine();
46
- case 'cline':
47
- return new ClineEngine();
48
- case 'cursor':
49
- return new CursorEngine();
50
- default:
51
- throw new Error(`Unknown engine type: ${type}`);
52
- }
40
+ /**
41
+ * The only reference to an adapter module anywhere in this registry. Being a
42
+ * total `Record<EngineType, …>`, adding an engine will not type-check until its
43
+ * loader is registered here — the exhaustiveness the old `switch` needed a
44
+ * runtime `default` branch to approximate.
45
+ */
46
+ const ENGINE_LOADERS: Record<EngineType, () => Promise<AIEngine>> = {
47
+ 'claude-code': async () => new (await import('./adapters/claude')).ClaudeCodeEngine(),
48
+ opencode: async () => new (await import('./adapters/opencode')).OpenCodeEngine(),
49
+ copilot: async () => new (await import('./adapters/copilot')).CopilotEngine(),
50
+ codex: async () => new (await import('./adapters/codex')).CodexEngine(),
51
+ qwen: async () => new (await import('./adapters/qwen')).QwenEngine(),
52
+ pi: async () => new (await import('./adapters/pi')).PiEngine(),
53
+ cline: async () => new (await import('./adapters/cline')).ClineEngine(),
54
+ cursor: async () => new (await import('./adapters/cursor')).CursorEngine(),
55
+ };
56
+
57
+ /**
58
+ * A cache entry. `pending` is what callers await — sharing it means concurrent
59
+ * callers get one instance rather than racing to build two. `instance` is the
60
+ * settled value, for callers that must read an engine without creating one.
61
+ */
62
+ interface EngineSlot {
63
+ pending: Promise<AIEngine>;
64
+ instance: AIEngine | null;
65
+ }
66
+
67
+ /**
68
+ * Get (or start) the cached creation of an engine in the given cache.
69
+ *
70
+ * A failed creation is evicted rather than cached: the usual cause is an engine
71
+ * the user has not installed yet, and they must be able to install it in
72
+ * Settings → Stack and retry without restarting the server.
73
+ */
74
+ function slotFor(type: EngineType, cache: Map<EngineType, EngineSlot>): EngineSlot {
75
+ const cached = cache.get(type);
76
+ if (cached) return cached;
77
+
78
+ const load = ENGINE_LOADERS[type];
79
+ // Engine types reach us from stored settings, so an unknown one is possible
80
+ // even though the type system rules it out at every call site.
81
+ if (!load) throw new Error(`Unknown engine type: ${type}`);
82
+
83
+ const slot: EngineSlot = {
84
+ instance: null,
85
+ pending: load().then(
86
+ engine => { slot.instance = engine; return engine; },
87
+ error => { cache.delete(type); throw error; }
88
+ ),
89
+ };
90
+ cache.set(type, slot);
91
+ return slot;
53
92
  }
54
93
 
55
94
  // ============================================================================
56
95
  // Global Singletons — for non-streaming operations (models, settings, etc.)
57
96
  // ============================================================================
58
97
 
59
- const engines = new Map<EngineType, AIEngine>();
98
+ const engines = new Map<EngineType, EngineSlot>();
60
99
 
61
100
  /**
62
101
  * Get (or create) a global singleton engine instance by type.
63
102
  * Use for non-streaming operations only (e.g. models:list).
64
103
  */
65
- export function getEngine(type: EngineType): AIEngine {
66
- let engine = engines.get(type);
67
-
68
- if (!engine) {
69
- engine = createEngine(type);
70
- engines.set(type, engine);
71
- debug.log('engine', `Global engine instance created: ${type}`);
72
- }
104
+ export async function getEngine(type: EngineType): Promise<AIEngine> {
105
+ const cached = engines.get(type);
106
+ if (cached) return cached.pending;
73
107
 
74
- return engine;
108
+ const slot = slotFor(type, engines);
109
+ debug.log('engine', `Global engine instance created: ${type}`);
110
+ return slot.pending;
75
111
  }
76
112
 
77
113
  /**
78
114
  * Initialize a global engine (call this before streaming if you want eager init).
79
115
  */
80
116
  export async function initializeEngine(type: EngineType): Promise<AIEngine> {
81
- const engine = getEngine(type);
117
+ const engine = await getEngine(type);
82
118
  if (!engine.isInitialized) {
83
119
  await engine.initialize();
84
120
  }
@@ -89,10 +125,10 @@ export async function initializeEngine(type: EngineType): Promise<AIEngine> {
89
125
  * Dispose a specific global engine and release its resources.
90
126
  */
91
127
  export async function disposeEngine(type: EngineType): Promise<void> {
92
- const engine = engines.get(type);
93
- if (engine) {
94
- await engine.dispose();
128
+ const slot = engines.get(type);
129
+ if (slot) {
95
130
  engines.delete(type);
131
+ if (slot.instance) await slot.instance.dispose();
96
132
  debug.log('engine', `Global engine disposed: ${type}`);
97
133
  }
98
134
  }
@@ -101,9 +137,9 @@ export async function disposeEngine(type: EngineType): Promise<void> {
101
137
  * Dispose all global engines (used on server shutdown).
102
138
  */
103
139
  export async function disposeAllEngines(): Promise<void> {
104
- for (const [type, engine] of engines) {
140
+ for (const [type, slot] of engines) {
105
141
  try {
106
- await engine.dispose();
142
+ if (slot.instance) await slot.instance.dispose();
107
143
  debug.log('engine', `Global engine disposed: ${type}`);
108
144
  } catch (error) {
109
145
  debug.error('engine', `Error disposing global engine ${type}:`, error);
@@ -119,36 +155,46 @@ export async function disposeAllEngines(): Promise<void> {
119
155
  // Per-Project Instances — for streaming (fully isolated per project)
120
156
  // ============================================================================
121
157
 
122
- /** projectId → (engineType → AIEngine) */
123
- const projectEngines = new Map<string, Map<EngineType, AIEngine>>();
158
+ /** projectId → (engineType → EngineSlot) */
159
+ const projectEngines = new Map<string, Map<EngineType, EngineSlot>>();
124
160
 
125
161
  /**
126
162
  * Get (or create) an engine instance scoped to a specific project.
127
163
  * Each project gets its own engine with independent state (abort controllers,
128
164
  * active queries, session IDs), ensuring complete stream isolation.
129
165
  */
130
- export function getProjectEngine(projectId: string, type: EngineType): AIEngine {
131
- if (!projectEngines.has(projectId)) {
132
- projectEngines.set(projectId, new Map());
166
+ export async function getProjectEngine(projectId: string, type: EngineType): Promise<AIEngine> {
167
+ let engines = projectEngines.get(projectId);
168
+ if (!engines) {
169
+ engines = new Map();
170
+ projectEngines.set(projectId, engines);
133
171
  }
134
172
 
135
- const engines = projectEngines.get(projectId)!;
136
- let engine = engines.get(type);
173
+ const cached = engines.get(type);
174
+ if (cached) return cached.pending;
137
175
 
138
- if (!engine) {
139
- engine = createEngine(type);
140
- engines.set(type, engine);
141
- debug.log('engine', `Project engine created: ${type} for project ${projectId.slice(0, 8)}`);
142
- }
176
+ const slot = slotFor(type, engines);
177
+ debug.log('engine', `Project engine created: ${type} for project ${projectId.slice(0, 8)}`);
178
+ return slot.pending;
179
+ }
143
180
 
144
- return engine;
181
+ /**
182
+ * The engine already created for a project, or undefined.
183
+ *
184
+ * For callers acting on a stream that is already running — cancelling it,
185
+ * routing an answer back into it. Those must never create an engine: a fresh
186
+ * instance has nothing to cancel and no pending question, so building one would
187
+ * only hide the fact that the real engine went missing.
188
+ */
189
+ export function findProjectEngine(projectId: string, type: EngineType): AIEngine | undefined {
190
+ return projectEngines.get(projectId)?.get(type)?.instance ?? undefined;
145
191
  }
146
192
 
147
193
  /**
148
194
  * Initialize a project-scoped engine.
149
195
  */
150
196
  export async function initializeProjectEngine(projectId: string, type: EngineType): Promise<AIEngine> {
151
- const engine = getProjectEngine(projectId, type);
197
+ const engine = await getProjectEngine(projectId, type);
152
198
  if (!engine.isInitialized) {
153
199
  await engine.initialize();
154
200
  }
@@ -161,10 +207,10 @@ export async function initializeProjectEngine(projectId: string, type: EngineTyp
161
207
  export async function disposeProjectEngine(projectId: string, type: EngineType): Promise<void> {
162
208
  const engines = projectEngines.get(projectId);
163
209
  if (engines) {
164
- const engine = engines.get(type);
165
- if (engine) {
166
- await engine.dispose();
210
+ const slot = engines.get(type);
211
+ if (slot) {
167
212
  engines.delete(type);
213
+ if (slot.instance) await slot.instance.dispose();
168
214
  debug.log('engine', `Project engine disposed: ${type} for project ${projectId.slice(0, 8)}`);
169
215
  }
170
216
  if (engines.size === 0) {
@@ -179,9 +225,9 @@ export async function disposeProjectEngine(projectId: string, type: EngineType):
179
225
  export async function disposeProjectEngines(projectId: string): Promise<void> {
180
226
  const engines = projectEngines.get(projectId);
181
227
  if (engines) {
182
- for (const [type, engine] of engines) {
228
+ for (const [type, slot] of engines) {
183
229
  try {
184
- await engine.dispose();
230
+ if (slot.instance) await slot.instance.dispose();
185
231
  debug.log('engine', `Project engine disposed: ${type} for project ${projectId.slice(0, 8)}`);
186
232
  } catch (error) {
187
233
  debug.error('engine', `Error disposing project engine ${type}:`, error);
@@ -198,15 +244,15 @@ export async function disposeProjectEngines(projectId: string): Promise<void> {
198
244
  */
199
245
  export async function disposeAllProjectEnginesByType(type: EngineType): Promise<void> {
200
246
  for (const [projectId, engines] of projectEngines) {
201
- const engine = engines.get(type);
202
- if (engine) {
247
+ const slot = engines.get(type);
248
+ if (slot) {
249
+ engines.delete(type);
203
250
  try {
204
- await engine.dispose();
251
+ if (slot.instance) await slot.instance.dispose();
205
252
  debug.log('engine', `Project engine disposed: ${type} for project ${projectId.slice(0, 8)}`);
206
253
  } catch (error) {
207
254
  debug.error('engine', `Error disposing project engine ${type} for ${projectId.slice(0, 8)}:`, error);
208
255
  }
209
- engines.delete(type);
210
256
  }
211
257
  if (engines.size === 0) {
212
258
  projectEngines.delete(projectId);
@@ -222,9 +268,9 @@ export async function disposeAllProjectEnginesByType(type: EngineType): Promise<
222
268
  */
223
269
  async function disposeAllProjectEngines(): Promise<void> {
224
270
  for (const [projectId, engines] of projectEngines) {
225
- for (const [type, engine] of engines) {
271
+ for (const [type, slot] of engines) {
226
272
  try {
227
- await engine.dispose();
273
+ if (slot.instance) await slot.instance.dispose();
228
274
  } catch (error) {
229
275
  debug.error('engine', `Error disposing project engine ${type} for ${projectId.slice(0, 8)}:`, error);
230
276
  }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * On-demand engine install integrity
3
+ *
4
+ * Engine SDKs are not bundled. `resolveEngineRecipe` builds a `bun add` for the
5
+ * managed stack dir and pins each package to the version `getRequiredSdkVersion`
6
+ * reads out of package.json — the single source of truth.
7
+ *
8
+ * That pinning is silent when it fails. A package listed in ENGINE_PACKAGES but
9
+ * missing from package.json yields `null`, and `engineInstallArgs` falls back to
10
+ * the bare name, so the user installs `@latest` instead of the version clopen
11
+ * was tested against. Nothing errors; the engine just installs something else.
12
+ * Clopen has already been bitten by a floated version this way (typebox, #362),
13
+ * and the blast radius grows with every engine added.
14
+ *
15
+ * `readEngineSdkVersion` compounds it: `loadEngineSdk` only enforces a version
16
+ * match when a required version exists, so an unpinned package also loses the
17
+ * "needs update" check that would otherwise surface the drift in Settings → Stack.
18
+ */
19
+
20
+ import { describe, expect, test } from 'bun:test';
21
+ import { readFileSync } from 'node:fs';
22
+ import { join } from 'node:path';
23
+ import type { EngineType } from '$shared/types/unified';
24
+ import { ENGINE_PACKAGES, type ToolId } from './install-recipes';
25
+ import { ENGINE_SDK } from './engine-setup';
26
+ import { getRequiredSdkVersion } from './sdk-loader';
27
+
28
+ const pkg = JSON.parse(
29
+ readFileSync(join(import.meta.dir, '..', '..', 'package.json'), 'utf8')
30
+ ) as { dependencies?: Record<string, string>; devDependencies?: Record<string, string> };
31
+
32
+ const declared = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };
33
+
34
+ /** Every (engine, package) pair clopen installs on demand. */
35
+ const enginePackages = Object.entries(ENGINE_PACKAGES).flatMap(([engine, packages]) =>
36
+ (packages ?? []).map(name => ({ engine, name }))
37
+ );
38
+
39
+ describe('on-demand engine SDKs', () => {
40
+ test('the registry is non-empty', () => {
41
+ // Without this, an emptied registry would make the checks below vacuous.
42
+ expect(enginePackages.length).toBeGreaterThan(0);
43
+ });
44
+
45
+ test('every engine package is declared in package.json', () => {
46
+ const undeclared = enginePackages
47
+ .filter(({ name }) => declared[name] === undefined)
48
+ .map(({ engine, name }) => `${engine}: "${name}" would install as @latest`);
49
+
50
+ expect(undeclared).toEqual([]);
51
+ });
52
+
53
+ test('every engine package is pinned to an exact version', () => {
54
+ // A range (^1.2.3) reintroduces the same drift the pin exists to prevent:
55
+ // the published package.json is the only resolution source on a global
56
+ // install, so bun.lock cannot hold the version down for the user.
57
+ const floated = enginePackages
58
+ .filter(({ name }) => !/^\d+\.\d+\.\d+/.test(declared[name] ?? ''))
59
+ .map(({ engine, name }) => `${engine}: "${name}" is "${declared[name]}", not an exact version`);
60
+
61
+ expect(floated).toEqual([]);
62
+ });
63
+
64
+ test('the readiness check and the installer name the same package', () => {
65
+ // Three registries describe the same fact in different namespaces:
66
+ // ENGINE_SDK (EngineType → the package `checkEngineSetup` probes),
67
+ // ENGINE_PACKAGES (ToolId → what `bun add` installs, first entry being the
68
+ // one clopen imports), and this mapping between the two id spaces.
69
+ //
70
+ // Drift here makes readiness lie rather than fail: the pre-stream check
71
+ // would probe a package nobody installs — reporting an installed engine as
72
+ // missing, or worse, waving through one that cannot load. TypeScript only
73
+ // forces the keys to exist; the values have to be checked.
74
+ const TOOL_FOR_ENGINE: Record<EngineType, ToolId> = {
75
+ 'claude-code': 'claude',
76
+ opencode: 'opencode',
77
+ copilot: 'copilot',
78
+ codex: 'codex',
79
+ qwen: 'qwen',
80
+ pi: 'pi',
81
+ cline: 'cline',
82
+ cursor: 'cursor',
83
+ };
84
+
85
+ const drift = Object.entries(TOOL_FOR_ENGINE).flatMap(([engine, tool]) => {
86
+ const probed = ENGINE_SDK[engine as EngineType];
87
+ const installed = ENGINE_PACKAGES[tool]?.[0];
88
+ if (installed === undefined) return [`${engine}: no install recipe for tool "${tool}"`];
89
+ return probed === installed
90
+ ? []
91
+ : [`${engine}: readiness probes "${probed}" but the recipe installs "${installed}"`];
92
+ });
93
+
94
+ expect(drift).toEqual([]);
95
+ });
96
+
97
+ test('the resolver agrees with package.json', () => {
98
+ // Guards the seam the recipe actually uses — if getRequiredSdkVersion ever
99
+ // stops reading package.json, the checks above would pass while installs
100
+ // silently floated again.
101
+ for (const { name } of enginePackages) {
102
+ expect(getRequiredSdkVersion(name)).toBe(declared[name]!);
103
+ }
104
+ });
105
+ });
@@ -87,8 +87,11 @@ export interface ToolStatus {
87
87
  * any extras pin a transitive CLI the SDK would otherwise float (e.g. copilot).
88
88
  * Versions are read from package.json (the single source of truth), so an
89
89
  * on-demand install always matches the exact version clopen was tested against.
90
+ * Every package listed here must therefore be declared in package.json —
91
+ * `install-recipes.test.ts` enforces that, since an undeclared one would
92
+ * silently install as `@latest`.
90
93
  */
91
- const ENGINE_PACKAGES: Partial<Record<ToolId, string[]>> = {
94
+ export const ENGINE_PACKAGES: Partial<Record<ToolId, string[]>> = {
92
95
  claude: ['@anthropic-ai/claude-agent-sdk'],
93
96
  opencode: ['@opencode-ai/sdk'],
94
97
  copilot: ['@github/copilot-sdk', '@github/copilot'],
package/backend/index.ts CHANGED
@@ -57,6 +57,8 @@ import { sessionCleanupScheduler } from './auth/session-cleanup';
57
57
  import { uploadTempCleanup } from './http/upload-temp-cleanup';
58
58
  import { ws as wsServer } from './utils/ws';
59
59
  import { messageRateLimiter } from './ws/message-rate-limiter';
60
+ import { flushEpisodicIngest, stopExtractionRunner } from './memory/extract';
61
+ import { stopMemoryMaintenance } from './memory/maintenance';
60
62
 
61
63
  /** How often (ms) the auth gate re-confirms a connection's session against the DB. */
62
64
  const SESSION_REVALIDATE_MS = 15_000;
@@ -303,6 +305,13 @@ async function gracefulShutdown() {
303
305
  await closeMcpServer();
304
306
  // Cleanup browser preview sessions
305
307
  await browserPreviewServiceManager.cleanup();
308
+ // Write out any memory extraction still in flight or held back by a live
309
+ // stream. Bounded, because each entry is a model call with no timeout of its
310
+ // own — and the queue is a table, so whatever is left is picked up on the next
311
+ // start rather than lost.
312
+ stopMemoryMaintenance();
313
+ stopExtractionRunner();
314
+ await flushEpisodicIngest();
306
315
  // Dispose all AI engines
307
316
  await disposeAllEngines();
308
317
  // Close database connection
@@ -36,6 +36,12 @@ export const mcpServersConfig: Record<ServerName, ServerConfig> = {
36
36
  // One tool. Every browser capability is an action inside `actions`, so a
37
37
  // whole interaction is one call and the agent decides what to batch.
38
38
  tools: ["actions"]
39
+ },
40
+ "memory-graph": {
41
+ enabled: true,
42
+ // Same shape: every graph capability is an operation inside `memory`, so
43
+ // recalling a memory and then walking its neighbours is a single call.
44
+ tools: ["memory"]
39
45
  }
40
46
  };
41
47
 
@@ -11,6 +11,7 @@
11
11
  */
12
12
 
13
13
  import browserAutomation from './browser-automation/index';
14
+ import memoryGraph from './memory-graph/index';
14
15
  import { buildServerRegistries } from './helper';
15
16
 
16
17
  // Re-export types and remote server factory
@@ -25,6 +26,7 @@ export { createRemoteMcpServer } from './helper';
25
26
  */
26
27
  export const allServers = [
27
28
  browserAutomation,
29
+ memoryGraph,
28
30
  // Add more servers here...
29
31
  ] as const;
30
32
 
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Tool description. The agent reads this once per session, so it has to explain
3
+ * not just the actions but WHEN reaching for the graph beats guessing — and, just
4
+ * as importantly, that it does not have to write anything.
5
+ */
6
+
7
+ export const memoryToolDescription = `Query and curate Clopen's Memory Graph — a persistent store of what has been decided, tried and learned across past sessions of this workspace, plus a map of the codebase those memories attach to. It is shared by every AI engine and survives session switches, so a memory written months ago by a different model is still here.
8
+
9
+ YOU DO NOT NEED TO RECORD ANYTHING. Memories are written automatically from each finished conversation turn, including anything the user asks you to remember — saying "remember that I prefer X" is enough on its own, and there is deliberately no action here that stores a new memory. That is one write path rather than two, so what ends up in the graph is predictable. This tool is for reading it and for correcting what is already there.
10
+
11
+ Reach for it when:
12
+ - you are about to make an architectural choice, and an earlier session may already have made it (and rejected alternatives you are about to re-propose)
13
+ - something is failing in a way that feels like it has failed before
14
+ - you need to know why code looks the way it does, when the code itself does not say
15
+ - the user refers to a past discussion, decision or preference
16
+ - you want to know what a file or module is connected to before changing it
17
+ - a memory you were shown is wrong, out of date, or filed under the wrong kind
18
+
19
+ Relevant memories are already prepended to each turn automatically, so this tool is for going DEEPER than that: following up on something you have just discovered, asking about another project, or walking the graph. It is not a substitute for reading what you were given.
20
+
21
+ Actions:
22
+ - recall — natural-language search across memories and code entities. Runs keyword and semantic search together and expands into the graph, so it finds paraphrases as well as exact names. Use scope "all" to search every project, which is how you find that a problem was already solved in another repository.
23
+ - neighbours — walk outward from a node returned by recall. This is where the graph earns its keep: the memory you need is often adjacent to your match rather than being it.
24
+ - timeline — recent memories in order, for "what have we been doing here".
25
+ - update — correct a memory in place. Prefer this whenever an existing memory is nearly right: it keeps the node's connections and its history, where retiring it and letting a new one be written loses both.
26
+ - link — connect two nodes. Use "supersedes" when a memory replaces an older one and "contradicts" when two disagree and you cannot tell which is right.
27
+ - forget — archive a memory that was never true. It is retired from search, not deleted, so the reasoning trail survives and the user can restore it.
28
+ - restore — bring an archived memory back, when it was retired in error.
29
+ - stats — size and composition of the graph.
30
+
31
+ Forgetting and superseding are different claims and worth getting right. "forget" says a memory was WRONG. "supersedes" says it was true and has since been REPLACED — the old one stops being recalled but stays one hop from the new one, so the history of a decision remains answerable. Reach for supersedes whenever something changed rather than was mistaken.
32
+
33
+ Batch independent operations into one call. Each memory returned carries an id, its kind, how it was found, and how confident the writer was — treat low confidence as a lead, not a fact, and trust the current code over any memory that disagrees with it.`;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Rendering the run report.
3
+ *
4
+ * The report is the agent's only view of the graph, so it leads with the count
5
+ * that matters, keeps each operation's outcome separate, and says plainly when
6
+ * the graph was queried without project context — otherwise an empty result
7
+ * looks like "nothing was ever decided" when it actually means "you asked
8
+ * outside any project".
9
+ */
10
+
11
+ import type { RunReport } from './runner';
12
+
13
+ export function formatReport(report: RunReport): {
14
+ content: Array<{ type: 'text'; text: string }>;
15
+ isError?: boolean;
16
+ } {
17
+ const total = report.operations.length;
18
+ const ok = report.operations.filter(o => o.ok).length;
19
+
20
+ const lines: string[] = [`Memory Graph — ${ok}/${total} operation(s) succeeded`];
21
+
22
+ if (!report.projectScoped) {
23
+ lines.push('No project context for this call, so project-scoped memories were not searched.');
24
+ }
25
+
26
+ for (const [index, operation] of report.operations.entries()) {
27
+ lines.push('', `[${index + 1}] ${operation.action}${operation.ok ? '' : ' FAILED'}`);
28
+ lines.push(indent(operation.text));
29
+ }
30
+
31
+ return {
32
+ content: [{ type: 'text', text: lines.join('\n') }],
33
+ // Only a batch where nothing worked counts as an error: a partially useful
34
+ // result is still useful, and flagging it would push the agent to retry work
35
+ // that already landed.
36
+ ...(ok === 0 && total > 0 && { isError: true })
37
+ };
38
+ }
39
+
40
+ function indent(text: string): string {
41
+ return text
42
+ .split('\n')
43
+ .map(line => (line ? ` ${line}` : line))
44
+ .join('\n');
45
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Memory Graph — internal MCP server.
3
+ *
4
+ * One tool. Every capability is an operation inside it, so recalling a memory and
5
+ * then walking its neighbours can be one call instead of a round trip each, and
6
+ * the whole surface fits in a single description the agent reads once.
7
+ *
8
+ * Exposed through the existing Streamable HTTP endpoint
9
+ * (`backend/mcp/internal/remote-server.ts`), which is what makes the graph
10
+ * agent-agnostic for free: every engine that can consume an MCP URL reaches the
11
+ * same store, with no per-engine work.
12
+ */
13
+
14
+ import { defineServer } from '../helper';
15
+ import { memoryToolDescription } from './description';
16
+ import { memoryToolSchema } from './schema';
17
+ import { runMemoryOperations } from './runner';
18
+ import { formatReport } from './format';
19
+
20
+ export default defineServer({
21
+ name: 'memory-graph',
22
+ title: 'Memory Graph',
23
+ description:
24
+ 'Persistent memory shared by every engine — past decisions, patterns and failures, plus the code they attach to, searchable across every project.',
25
+ version: '1.0.0',
26
+ tools: {
27
+ memory: {
28
+ description: memoryToolDescription,
29
+ schema: memoryToolSchema,
30
+ handler: async (args) => {
31
+ try {
32
+ const report = await runMemoryOperations(args as Parameters<typeof runMemoryOperations>[0]);
33
+ return formatReport(report);
34
+ } catch (error) {
35
+ // Nothing ran: the batch never started, so there is no partial report
36
+ // to render.
37
+ return {
38
+ content: [
39
+ {
40
+ type: 'text' as const,
41
+ text: `Memory Graph call failed before starting: ${
42
+ error instanceof Error ? error.message : 'Unknown error'
43
+ }`
44
+ }
45
+ ],
46
+ isError: true
47
+ };
48
+ }
49
+ }
50
+ }
51
+ }
52
+ });