@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
@@ -137,6 +137,27 @@ export const ADMIN_ONLY_ROUTES = new Set([
137
137
  'mcp:tools',
138
138
  'mcp:set-tool-overrides',
139
139
  'mcp:call-tool',
140
+ // Memory Graph — the graph is instance-global and is injected into every
141
+ // future turn on every engine, so editing it changes what every agent is told.
142
+ // Mutations only: the read surface (memory:graph / :node / :search / :stats /
143
+ // :config) stays open so any member can see what the project has learned.
144
+ 'memory:save-node',
145
+ 'memory:archive-node',
146
+ 'memory:restore-nodes',
147
+ 'memory:save-config',
148
+ // Writing a memory by hand. `draft-node` is gated too even though it stores
149
+ // nothing: it spends a model call, and a member who cannot save the result has
150
+ // no reason to be able to generate one.
151
+ 'memory:draft-node',
152
+ 'memory:create-node',
153
+ // Hard deletes. `delete-nodes` is reached only from the forgotten list, but
154
+ // `purge` empties a project — or the entire instance — in one call, which is
155
+ // the most destructive action the memory surface has.
156
+ 'memory:delete-nodes',
157
+ 'memory:purge',
158
+ // Re-running failed extractions costs model calls, so it is an admin action —
159
+ // reading the queue's status is not.
160
+ 'memory:retry-failed',
140
161
  // Agent Skills — creating/importing/installing skills writes to the shared
141
162
  // canonical store and applies to every engine, so the whole surface is
142
163
  // admin-only, mirroring MCP and Stack.
@@ -16,6 +16,8 @@
16
16
 
17
17
  import { syncInternalServers } from './mcp';
18
18
  import { ensureDefaultEngineInstalled } from './engine/bootstrap-default-engine';
19
+ import { bootstrapMemoryGraph } from './memory/bootstrap';
20
+ import { ensureMemoryModel } from './memory/model';
19
21
  import { debug } from '$shared/utils/logger';
20
22
 
21
23
  /**
@@ -33,7 +35,22 @@ export function bootstrapAfterDbInit(): void {
33
35
 
34
36
  // Fresh/emptied install: (re)install a usable engine in the background.
35
37
  // No-ops once any engine is already present. Fire-and-forget.
36
- void ensureDefaultEngineInstalled();
38
+ //
39
+ // Memory's extraction model is picked from that engine's catalog, so it is
40
+ // chosen again once the install settles. `bootstrapMemoryGraph` already tries
41
+ // on its own, but on a fresh or just-cleared install the engine is usually not
42
+ // ready yet and the catalog comes back empty — which left memory with no model
43
+ // until someone found the settings page, and is the state a data wipe used to
44
+ // land in. `ensureMemoryModel` is idempotent and never overwrites an explicit
45
+ // choice, so running it twice costs nothing.
46
+ void ensureDefaultEngineInstalled()
47
+ .then(() => ensureMemoryModel())
48
+ .catch(error => debug.warn('server', 'Default engine / memory model bootstrap failed', error));
49
+
50
+ // Fetch the embedding artifact and backfill memory vectors in the background.
51
+ // Recall is gated on the artifact, but recording is not, so nothing here
52
+ // blocks startup.
53
+ bootstrapMemoryGraph();
37
54
 
38
55
  debug.log('server', '✅ Post-DB bootstrap complete');
39
56
  }
@@ -0,0 +1,229 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+
3
+ import { renderHandoff, withHandoff } from './engine-handoff';
4
+ import type {
5
+ AssistantMessage,
6
+ MessageEngine,
7
+ ReasoningMessage,
8
+ UnifiedMessage,
9
+ UserMessage,
10
+ } from '$shared/types/unified';
11
+
12
+ // The handoff is the only thing standing between "switch engine" and "the new
13
+ // engine has no idea what we were doing", and it runs invisibly — a user never
14
+ // sees the transcript, so a regression here is silent. Each case below is a
15
+ // property the design depends on rather than an incidental detail of the
16
+ // current wording.
17
+
18
+ const ALL: { image: boolean; document: boolean } = { image: true, document: true };
19
+ const TEXT_ONLY: { image: boolean; document: boolean } = { image: false, document: false };
20
+
21
+ function engine(type: MessageEngine['type'] = 'claude-code'): MessageEngine {
22
+ return { type, provider: 'anthropic', model: { id: 'm', name: 'M' }, account: { id: 0, name: '' } };
23
+ }
24
+
25
+ function base(id: string) {
26
+ return {
27
+ createdAt: '2026-01-01T00:00:00.000Z',
28
+ messageId: id,
29
+ sessionId: 'sdk-1',
30
+ parent: { messageId: null, sessionId: null, toolUseId: null },
31
+ engine: engine(),
32
+ };
33
+ }
34
+
35
+ function user(id: string, text: string, extra: Partial<UserMessage> = {}): UserMessage {
36
+ return {
37
+ ...base(id),
38
+ type: 'user',
39
+ sender: { id: 'u', name: 'U' },
40
+ content: [{ type: 'text', text }],
41
+ synthetic: false,
42
+ ...extra,
43
+ };
44
+ }
45
+
46
+ function assistant(id: string, text: string, extra: Partial<AssistantMessage> = {}): AssistantMessage {
47
+ return {
48
+ ...base(id),
49
+ type: 'assistant',
50
+ content: [{ type: 'text', text }],
51
+ stopReason: null,
52
+ usage: null,
53
+ ...extra,
54
+ };
55
+ }
56
+
57
+ function toolCall(id: string, toolUseId: string, name: string, input: unknown): AssistantMessage {
58
+ return {
59
+ ...base(id),
60
+ type: 'assistant',
61
+ content: [{
62
+ type: 'tool_use',
63
+ id: toolUseId,
64
+ name,
65
+ input,
66
+ result: null,
67
+ subActivities: [],
68
+ skillPrompt: null,
69
+ interrupted: false,
70
+ } as AssistantMessage['content'][number]],
71
+ stopReason: 'tool_use',
72
+ usage: null,
73
+ };
74
+ }
75
+
76
+ function toolResult(id: string, toolUseId: string, content: string): UserMessage {
77
+ return {
78
+ ...base(id),
79
+ type: 'user',
80
+ sender: { id: '', name: '' },
81
+ content: [{ type: 'tool_result', toolUseId, content, isError: false }],
82
+ synthetic: true,
83
+ };
84
+ }
85
+
86
+ /** The single text block of a handoff result. */
87
+ function transcriptOf(messages: UnifiedMessage[], support = ALL, previous: MessageEngine['type'] | null = 'claude-code') {
88
+ const result = renderHandoff(messages, support, previous);
89
+ expect(result).not.toBeNull();
90
+ const first = result!.blocks[0];
91
+ expect(first.type).toBe('text');
92
+ return { text: (first as { type: 'text'; text: string }).text, result: result! };
93
+ }
94
+
95
+ describe('renderHandoff', () => {
96
+ test('returns null when there is nothing to replay', () => {
97
+ expect(renderHandoff([], ALL, null)).toBeNull();
98
+ });
99
+
100
+ test('replays the conversation in order and names the previous engine', () => {
101
+ const { text } = transcriptOf([
102
+ user('1', 'add a login page'),
103
+ assistant('2', 'done, added Login.svelte'),
104
+ ]);
105
+
106
+ expect(text).toContain('claude-code');
107
+ expect(text.indexOf('add a login page')).toBeLessThan(text.indexOf('done, added Login.svelte'));
108
+ });
109
+
110
+ test('carries tool calls with their inputs and results verbatim under the trigger', () => {
111
+ const { text, result } = transcriptOf([
112
+ user('1', 'what is in config.ts?'),
113
+ toolCall('2', 't1', 'Read', { filePath: '/app/config.ts' }),
114
+ toolResult('3', 't1', 'export const PORT = 3000'),
115
+ ]);
116
+
117
+ expect(text).toContain('Read');
118
+ expect(text).toContain('/app/config.ts');
119
+ expect(text).toContain('export const PORT = 3000');
120
+ expect(result.stats.clearedToolResults).toBe(0);
121
+ });
122
+
123
+ test('keeps reasoning blocks', () => {
124
+ const reasoning: ReasoningMessage = { ...base('2'), type: 'reasoning', text: 'the user wants X' };
125
+ const { text } = transcriptOf([user('1', 'hi'), reasoning]);
126
+ expect(text).toContain('the user wants X');
127
+ });
128
+
129
+ // Sub-agent traffic is already summarised by its parent tool result; replaying
130
+ // it would duplicate the same work far more verbosely.
131
+ test('drops sub-agent messages but keeps root-level ones', () => {
132
+ const nested = assistant('2', 'inner sub-agent chatter');
133
+ nested.parent = { messageId: null, sessionId: null, toolUseId: 't1' };
134
+
135
+ const { text } = transcriptOf([user('1', 'root question'), nested, assistant('3', 'root answer')]);
136
+
137
+ expect(text).toContain('root question');
138
+ expect(text).toContain('root answer');
139
+ expect(text).not.toContain('inner sub-agent chatter');
140
+ });
141
+
142
+ // The compaction summary is the previous engine's own compression of
143
+ // everything before it — the single most valuable message to carry over.
144
+ test('keeps the synthetic post-compaction summary', () => {
145
+ const summary = user('2', 'Summary: we refactored the auth module', { synthetic: true });
146
+ const { text } = transcriptOf([user('1', 'start'), summary]);
147
+ expect(text).toContain('we refactored the auth module');
148
+ });
149
+
150
+ describe('tool-result clearing past the trigger', () => {
151
+ // >100k estimated tokens means >400k characters at 4 chars/token.
152
+ const HUGE = 'x'.repeat(120_000);
153
+
154
+ const longRun: UnifiedMessage[] = [
155
+ user('1', 'go'),
156
+ toolCall('2', 't1', 'Read', { filePath: '/a' }),
157
+ toolResult('3', 't1', `oldest ${HUGE}`),
158
+ toolCall('4', 't2', 'Read', { filePath: '/b' }),
159
+ toolResult('5', 't2', `second ${HUGE}`),
160
+ toolCall('6', 't3', 'Read', { filePath: '/c' }),
161
+ toolResult('7', 't3', `third ${HUGE}`),
162
+ toolCall('8', 't4', 'Read', { filePath: '/d' }),
163
+ toolResult('9', 't4', `fourth ${HUGE}`),
164
+ toolCall('10', 't5', 'Read', { filePath: '/e' }),
165
+ toolResult('11', 't5', `newest ${HUGE}`),
166
+ ];
167
+
168
+ test('clears the oldest results and keeps the last three', () => {
169
+ const { text, result } = transcriptOf(longRun);
170
+
171
+ // 5 tool uses, keep 3 → the 2 oldest results are cleared.
172
+ expect(result.stats.clearedToolResults).toBe(2);
173
+ expect(text).not.toContain('oldest x');
174
+ expect(text).not.toContain('second x');
175
+ expect(text).toContain('third x');
176
+ expect(text).toContain('fourth x');
177
+ expect(text).toContain('newest x');
178
+ });
179
+
180
+ test('keeps every tool input even when its result is cleared', () => {
181
+ const { text } = transcriptOf(longRun);
182
+ for (const path of ['/a', '/b', '/c', '/d', '/e']) {
183
+ expect(text).toContain(path);
184
+ }
185
+ });
186
+
187
+ test('marks cleared results so the engine knows to re-derive them', () => {
188
+ const { text } = transcriptOf(longRun);
189
+ expect(text).toContain('cleared');
190
+ });
191
+ });
192
+
193
+ describe('attachments', () => {
194
+ const withImage = user('1', 'look at this', {
195
+ content: [
196
+ { type: 'text', text: 'look at this' },
197
+ { type: 'image', mediaType: 'image/png', data: 'BASE64DATA' },
198
+ ],
199
+ });
200
+
201
+ test('re-attaches images when the target supports them', () => {
202
+ const result = renderHandoff([withImage], ALL, 'codex')!;
203
+ const image = result.blocks.find(b => b.type === 'image');
204
+ expect(image).toBeDefined();
205
+ expect((image as { data: string }).data).toBe('BASE64DATA');
206
+ expect(result.stats.droppedAttachments).toBe(0);
207
+ });
208
+
209
+ test('degrades to a placeholder when the target cannot take them', () => {
210
+ const result = renderHandoff([withImage], TEXT_ONLY, 'codex')!;
211
+ expect(result.blocks.some(b => b.type === 'image')).toBe(false);
212
+ expect(result.stats.droppedAttachments).toBe(1);
213
+ expect((result.blocks[0] as { text: string }).text).toContain('not supported');
214
+ });
215
+ });
216
+ });
217
+
218
+ describe('withHandoff', () => {
219
+ test('prepends the blocks without mutating the original message', () => {
220
+ const prompt = user('1', 'the real question');
221
+ const merged = withHandoff(prompt, [{ type: 'text', text: 'CARRIED CONTEXT' }]);
222
+
223
+ // The original is what gets persisted and rendered — it must stay clean.
224
+ expect(prompt.content).toHaveLength(1);
225
+ expect(merged.content).toHaveLength(2);
226
+ expect((merged.content[0] as { text: string }).text).toBe('CARRIED CONTEXT');
227
+ expect((merged.content[1] as { text: string }).text).toBe('the real question');
228
+ });
229
+ });