@myrialabs/clopen 0.4.26 → 0.4.28

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 (98) 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/claude/message-converter.ts +5 -24
  15. package/backend/engine/adapters/copilot/stream.ts +37 -1
  16. package/backend/engine/adapters/pi/models.ts +19 -7
  17. package/backend/engine/adapters/pi/stream.ts +2 -1
  18. package/backend/engine/docs/adapter-contract.md +25 -8
  19. package/backend/engine/docs/adding-an-engine.md +40 -4
  20. package/backend/engine/docs/frontend-and-chat.md +66 -1
  21. package/backend/engine/docs/lessons-learned.md +165 -6
  22. package/backend/engine/docs/quick-reference.md +10 -0
  23. package/backend/engine/docs/stack.md +10 -0
  24. package/backend/engine/docs/websocket-routes.md +15 -1
  25. package/backend/engine/engine-setup.ts +1 -1
  26. package/backend/engine/index.test.ts +186 -0
  27. package/backend/engine/index.ts +117 -71
  28. package/backend/engine/install-recipes.test.ts +105 -0
  29. package/backend/engine/install-recipes.ts +4 -1
  30. package/backend/index.ts +9 -0
  31. package/backend/mcp/internal/config.ts +6 -0
  32. package/backend/mcp/internal/servers/index.ts +2 -0
  33. package/backend/mcp/internal/servers/memory-graph/description.ts +33 -0
  34. package/backend/mcp/internal/servers/memory-graph/format.ts +45 -0
  35. package/backend/mcp/internal/servers/memory-graph/index.ts +52 -0
  36. package/backend/mcp/internal/servers/memory-graph/runner.ts +342 -0
  37. package/backend/mcp/internal/servers/memory-graph/schema.ts +140 -0
  38. package/backend/memory/README.md +432 -0
  39. package/backend/memory/bootstrap.ts +101 -0
  40. package/backend/memory/compose.test.ts +198 -0
  41. package/backend/memory/compose.ts +343 -0
  42. package/backend/memory/config.ts +100 -0
  43. package/backend/memory/consolidate.ts +280 -0
  44. package/backend/memory/context.test.ts +321 -0
  45. package/backend/memory/context.ts +451 -0
  46. package/backend/memory/embedding/embedder.test.ts +141 -0
  47. package/backend/memory/embedding/embedder.ts +269 -0
  48. package/backend/memory/embedding/index.ts +17 -0
  49. package/backend/memory/embedding/install.ts +254 -0
  50. package/backend/memory/embedding/paths.ts +101 -0
  51. package/backend/memory/embedding/vector-cache.ts +270 -0
  52. package/backend/memory/extract/episodic.ts +725 -0
  53. package/backend/memory/extract/index.ts +133 -0
  54. package/backend/memory/extract/languages.ts +176 -0
  55. package/backend/memory/extract/scheduler.test.ts +352 -0
  56. package/backend/memory/extract/scheduler.ts +406 -0
  57. package/backend/memory/extract/structural.test.ts +215 -0
  58. package/backend/memory/extract/structural.ts +364 -0
  59. package/backend/memory/index.ts +37 -0
  60. package/backend/memory/indexer.ts +150 -0
  61. package/backend/memory/invalidate.ts +134 -0
  62. package/backend/memory/judge.ts +285 -0
  63. package/backend/memory/maintenance.ts +132 -0
  64. package/backend/memory/model.ts +91 -0
  65. package/backend/memory/notify.ts +102 -0
  66. package/backend/memory/readiness.ts +74 -0
  67. package/backend/memory/redact.test.ts +101 -0
  68. package/backend/memory/redact.ts +133 -0
  69. package/backend/memory/retention.ts +139 -0
  70. package/backend/memory/retrieval.eval.test.ts +301 -0
  71. package/backend/memory/retrieval.test.ts +1023 -0
  72. package/backend/memory/retrieval.ts +707 -0
  73. package/backend/memory/revise.test.ts +693 -0
  74. package/backend/memory/revise.ts +400 -0
  75. package/backend/memory/time.ts +31 -0
  76. package/backend/memory/view.ts +164 -0
  77. package/backend/shipped-runtime-imports.test.ts +228 -0
  78. package/backend/ws/engine/claude/accounts.ts +4 -12
  79. package/backend/ws/engine/codex/accounts.ts +4 -13
  80. package/backend/ws/engine/pty-output.test.ts +37 -0
  81. package/backend/ws/engine/pty-output.ts +43 -0
  82. package/backend/ws/index.ts +5 -1
  83. package/backend/ws/memory/crud.ts +631 -0
  84. package/backend/ws/memory/index.ts +41 -0
  85. package/backend/ws/sessions/crud.ts +10 -0
  86. package/backend/ws/snapshot/restore.ts +38 -4
  87. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +1 -0
  88. package/dist/assets/{index-DYa-GDsb.js → index-BujQYGBm.js} +1 -1
  89. package/dist/assets/{index-B6QGUN03.js → index-DRMOgS9y.js} +1 -1
  90. package/dist/assets/{main-Dznkfxsd.js → main-BrYtWn-4.js} +832 -423
  91. package/dist/assets/main-BrqMMMRX.css +1 -0
  92. package/dist/index.html +2 -2
  93. package/package.json +8 -2
  94. package/shared/types/database/connection.ts +9 -0
  95. package/shared/types/memory.ts +519 -0
  96. package/shared/utils/logger.ts +1 -0
  97. package/dist/assets/main-Dh-MTGNR.css +0 -1
  98. package/shared/utils/anonymous-user.ts +0 -168
@@ -0,0 +1,270 @@
1
+ /**
2
+ * The vector index, resident.
3
+ *
4
+ * Retrieval brute-forces cosine over every candidate vector, and that part is
5
+ * genuinely cheap: 256 int8 multiply-adds is nothing, and even a hundred
6
+ * thousand of them is a few milliseconds. What is NOT cheap is getting the
7
+ * vectors out of SQLite. Reading twenty thousand rows of BLOB per query means
8
+ * five megabytes copied out of the page cache, allocated as Uint8Arrays and
9
+ * handed to the GC — on EVERY turn, because injection retrieves on every turn.
10
+ * At a hundred thousand memories that read dominates the query by an order of
11
+ * magnitude over the arithmetic it feeds.
12
+ *
13
+ * So the vectors live here instead, in one contiguous buffer with a fixed
14
+ * stride, and SQLite is asked only for CANDIDATE IDS — an index-covered scan
15
+ * over columns, no blobs. The database stays the source of truth for which nodes
16
+ * exist and which filters they pass; this is only the arithmetic surface.
17
+ *
18
+ * ── what happens when it is wrong ──
19
+ * A cache of derived data is a correctness risk exactly in proportion to how
20
+ * hard it is to notice it drifting, so this one is built so that drift cannot
21
+ * produce a wrong answer:
22
+ *
23
+ * - A node the cache has never heard of is scored from the database instead
24
+ * (`scoreMissing`), so a cold or partial cache degrades in latency, never in
25
+ * results.
26
+ * - A node the cache still holds after its row is gone is never ASKED about,
27
+ * because candidate ids come from SQL. It wastes a slot until the next
28
+ * rebuild; it cannot be returned.
29
+ * - `reset()` is called by every path that removes rows in bulk.
30
+ *
31
+ * ── when it declines ──
32
+ * Above `MAX_CACHED` vectors the resident cost stops being obviously worth it
33
+ * (65 MB at 250k × 260 bytes), so the cache refuses to load and retrieval falls
34
+ * back to streaming from SQLite. That is a slower query on a graph far larger
35
+ * than anything this feature is expected to reach, rather than an instance that
36
+ * runs out of memory in the background.
37
+ */
38
+
39
+ import { getDatabase } from '$backend/database';
40
+ import { debug } from '$shared/utils/logger';
41
+ import { cosineToPacked } from './embedder';
42
+ import { EMBEDDING_VERSION } from './paths';
43
+
44
+ /**
45
+ * Ceiling on resident vectors. 250k × 260 bytes ≈ 65 MB — past the point where a
46
+ * background index should be quietly holding memory on a small VPS.
47
+ */
48
+ const MAX_CACHED = 250_000;
49
+
50
+ /** Vectors read per statement when scoring ids the cache does not hold. */
51
+ const MISSING_BATCH = 500;
52
+
53
+ class VectorCache {
54
+ private data: Uint8Array | null = null;
55
+ private slots = new Map<string, number>();
56
+ private free: number[] = [];
57
+ private used = 0;
58
+ private stride = 0;
59
+ private loaded = false;
60
+ private refused = false;
61
+
62
+ get ready(): boolean {
63
+ return this.loaded && this.data !== null;
64
+ }
65
+
66
+ get size(): number {
67
+ return this.slots.size;
68
+ }
69
+
70
+ /**
71
+ * Load every vector for the current artifact version, once.
72
+ *
73
+ * Returns false when there is nothing to cache or the corpus is past the
74
+ * ceiling — callers treat that as "score from the database" rather than as an
75
+ * error.
76
+ */
77
+ ensure(): boolean {
78
+ if (this.loaded) return this.data !== null;
79
+ if (this.refused) return false;
80
+
81
+ try {
82
+ const db = getDatabase();
83
+ const count = (
84
+ db.prepare(`SELECT COUNT(*) AS c FROM graph_vectors WHERE model = ?`).get(EMBEDDING_VERSION) as {
85
+ c: number;
86
+ }
87
+ ).c;
88
+ if (count === 0) {
89
+ // Nothing to hold yet. Not marked loaded, so the first indexed vector
90
+ // brings the cache up on the next query.
91
+ return false;
92
+ }
93
+ if (count > MAX_CACHED) {
94
+ this.refused = true;
95
+ debug.log('memory', `Vector cache declined: ${count} vectors exceeds the ${MAX_CACHED} ceiling`);
96
+ return false;
97
+ }
98
+
99
+ const rows = db
100
+ .prepare(`SELECT node_id AS id, vec FROM graph_vectors WHERE model = ?`)
101
+ .all(EMBEDDING_VERSION) as { id: string; vec: Uint8Array }[];
102
+ if (rows.length === 0) return false;
103
+
104
+ // Headroom so a growing graph does not reallocate on every write.
105
+ this.stride = rows[0].vec.length;
106
+ const capacity = Math.min(MAX_CACHED, Math.max(rows.length * 2, 1024));
107
+ this.data = new Uint8Array(capacity * this.stride);
108
+ this.slots.clear();
109
+ this.free = [];
110
+ this.used = 0;
111
+
112
+ for (const row of rows) {
113
+ if (row.vec.length !== this.stride) continue;
114
+ this.write(row.id, row.vec);
115
+ }
116
+
117
+ this.loaded = true;
118
+ debug.log(
119
+ 'memory',
120
+ `Vector cache resident: ${this.slots.size} vector(s), ${((this.slots.size * this.stride) / 1e6).toFixed(1)} MB`
121
+ );
122
+ return true;
123
+ } catch (error) {
124
+ debug.warn('memory', 'Vector cache load failed; scoring from the database', error);
125
+ this.data = null;
126
+ this.loaded = false;
127
+ return false;
128
+ }
129
+ }
130
+
131
+ /** Store or replace one node's vector. Silently ignored before the cache loads. */
132
+ set(nodeId: string, packed: Uint8Array): void {
133
+ if (!this.loaded || !this.data) return;
134
+ if (this.stride === 0) this.stride = packed.length;
135
+ if (packed.length !== this.stride) return;
136
+ this.write(nodeId, packed);
137
+ }
138
+
139
+ /** Forget specific nodes — an edit dropped their vector, or they were deleted. */
140
+ drop(nodeIds: string[]): void {
141
+ if (!this.loaded) return;
142
+ for (const id of nodeIds) {
143
+ const slot = this.slots.get(id);
144
+ if (slot === undefined) continue;
145
+ this.slots.delete(id);
146
+ this.free.push(slot);
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Throw the whole thing away.
152
+ *
153
+ * Called by every bulk removal — purge, batch delete, a model change that
154
+ * invalidates the index. Rebuilding is one sequential read; reconciling would
155
+ * be a second implementation of the same truth.
156
+ */
157
+ reset(): void {
158
+ this.data = null;
159
+ this.slots.clear();
160
+ this.free = [];
161
+ this.used = 0;
162
+ this.loaded = false;
163
+ this.refused = false;
164
+ }
165
+
166
+ /**
167
+ * Score `ids` against `query`, best first.
168
+ *
169
+ * Ids the cache does not hold are scored from the database in batches, so a
170
+ * result set is never silently short. `minScore` filters during the scan
171
+ * rather than after it — at a hundred thousand candidates the array the caller
172
+ * would otherwise sort is most of the corpus.
173
+ */
174
+ score(query: Float32Array, ids: string[], minScore = 0): { id: string; score: number }[] {
175
+ const scored: { id: string; score: number }[] = [];
176
+ const missing: string[] = [];
177
+
178
+ if (this.loaded && this.data) {
179
+ for (const id of ids) {
180
+ const slot = this.slots.get(id);
181
+ if (slot === undefined) {
182
+ missing.push(id);
183
+ continue;
184
+ }
185
+ const offset = slot * this.stride;
186
+ const packed = this.data.subarray(offset, offset + this.stride);
187
+ const score = cosineToPacked(query, packed);
188
+ if (score > minScore) scored.push({ id, score });
189
+ }
190
+ } else {
191
+ missing.push(...ids);
192
+ }
193
+
194
+ if (missing.length > 0) scored.push(...this.scoreMissing(query, missing, minScore));
195
+
196
+ scored.sort((a, b) => b.score - a.score);
197
+ return scored;
198
+ }
199
+
200
+ /** One node's packed vector, from wherever it is. */
201
+ get(nodeId: string): Uint8Array | null {
202
+ if (this.loaded && this.data) {
203
+ const slot = this.slots.get(nodeId);
204
+ if (slot !== undefined) {
205
+ const offset = slot * this.stride;
206
+ return this.data.subarray(offset, offset + this.stride);
207
+ }
208
+ }
209
+ try {
210
+ const row = getDatabase()
211
+ .prepare(`SELECT vec FROM graph_vectors WHERE node_id = ? AND model = ?`)
212
+ .get(nodeId, EMBEDDING_VERSION) as { vec: Uint8Array } | null;
213
+ return row?.vec ?? null;
214
+ } catch {
215
+ return null;
216
+ }
217
+ }
218
+
219
+ private scoreMissing(query: Float32Array, ids: string[], minScore: number): { id: string; score: number }[] {
220
+ const out: { id: string; score: number }[] = [];
221
+ try {
222
+ const db = getDatabase();
223
+ for (let i = 0; i < ids.length; i += MISSING_BATCH) {
224
+ const chunk = ids.slice(i, i + MISSING_BATCH);
225
+ const placeholders = chunk.map(() => '?').join(',');
226
+ const rows = db
227
+ .prepare(
228
+ `SELECT node_id AS id, vec FROM graph_vectors
229
+ WHERE model = ? AND node_id IN (${placeholders})`
230
+ )
231
+ .all(EMBEDDING_VERSION, ...chunk) as { id: string; vec: Uint8Array }[];
232
+ for (const row of rows) {
233
+ const score = cosineToPacked(query, row.vec);
234
+ if (score > minScore) out.push({ id: row.id, score });
235
+ }
236
+ }
237
+ } catch (error) {
238
+ debug.warn('memory', 'Vector fallback scoring failed', error);
239
+ }
240
+ return out;
241
+ }
242
+
243
+ private write(nodeId: string, packed: Uint8Array): void {
244
+ if (!this.data) return;
245
+
246
+ let slot = this.slots.get(nodeId);
247
+ if (slot === undefined) {
248
+ slot = this.free.pop();
249
+ if (slot === undefined) {
250
+ const capacity = this.data.length / this.stride;
251
+ if (this.used >= capacity) {
252
+ if (capacity * 2 > MAX_CACHED) {
253
+ // Past the ceiling mid-flight. Drop the cache rather than growing
254
+ // past what it promised to hold; the next query rebuilds or declines.
255
+ this.reset();
256
+ return;
257
+ }
258
+ const grown = new Uint8Array(this.data.length * 2);
259
+ grown.set(this.data);
260
+ this.data = grown;
261
+ }
262
+ slot = this.used++;
263
+ }
264
+ this.slots.set(nodeId, slot);
265
+ }
266
+ this.data.set(packed, slot * this.stride);
267
+ }
268
+ }
269
+
270
+ export const vectorCache = new VectorCache();