@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
@@ -0,0 +1,269 @@
1
+ /**
2
+ * Local text embedder for the Memory Graph.
3
+ *
4
+ * The model is a *static* embedding table (Model2Vec), so embedding a string is
5
+ * tokenize → look each token's row up → mean-pool → L2-normalize. There is no
6
+ * forward pass, which is why this runs in plain TypeScript on Bun with no ONNX
7
+ * runtime, no WASM and no native binary. A query costs ~0.05 ms.
8
+ *
9
+ * The table is int8-quantized with a per-row scale (see
10
+ * `scripts/build-embedding-artifact.ts`). Rows are dequantized while pooling
11
+ * rather than up front, so only ~39 MB stays resident instead of ~154 MB.
12
+ *
13
+ * Vectors are persisted quantized too — 260 bytes per node instead of 1 KB —
14
+ * because retrieval brute-forces the candidate set and wants it to fit in cache.
15
+ */
16
+
17
+ import { join } from 'node:path';
18
+ import { Tokenizer } from '@huggingface/tokenizers';
19
+ import { debug } from '$shared/utils/logger';
20
+ import {
21
+ EMBEDDING_VERSION,
22
+ getEmbeddingModelDir,
23
+ isEmbeddingArtifactInstalled,
24
+ type EmbeddingManifest
25
+ } from './paths';
26
+
27
+ const MAGIC = 'CLPEMB\0';
28
+ const HEADER_BYTES = 16;
29
+
30
+ /** Longest input we embed. Static models have no context limit, but pooling a
31
+ * whole file into one 256-dim vector stops being meaningful long before this. */
32
+ const MAX_CHARS = 8_000;
33
+
34
+ interface LoadedModel {
35
+ tokenizer: Tokenizer;
36
+ quant: Int8Array;
37
+ scales: Float32Array;
38
+ rows: number;
39
+ dim: number;
40
+ unkId: number;
41
+ }
42
+
43
+ export interface EmbedderStatus {
44
+ ready: boolean;
45
+ installed: boolean;
46
+ version: string | null;
47
+ dim: number | null;
48
+ rows: number | null;
49
+ error: string | null;
50
+ }
51
+
52
+ class Embedder {
53
+ private model: LoadedModel | null = null;
54
+ private loading: Promise<LoadedModel | null> | null = null;
55
+ private lastError: string | null = null;
56
+
57
+ /** Dimensionality of emitted vectors, or null before the model has loaded. */
58
+ get dim(): number | null {
59
+ return this.model?.dim ?? null;
60
+ }
61
+
62
+ get ready(): boolean {
63
+ return this.model !== null;
64
+ }
65
+
66
+ status(): EmbedderStatus {
67
+ return {
68
+ ready: this.ready,
69
+ installed: isEmbeddingArtifactInstalled(),
70
+ version: isEmbeddingArtifactInstalled() ? EMBEDDING_VERSION : null,
71
+ dim: this.model?.dim ?? null,
72
+ rows: this.model?.rows ?? null,
73
+ error: this.lastError
74
+ };
75
+ }
76
+
77
+ /**
78
+ * Load the artifact if it is installed. Concurrent callers share one load.
79
+ * Returns null when the artifact is absent or unreadable — callers treat
80
+ * that as "no vector half this time" rather than an error, so the graph
81
+ * stays usable while the download is still in flight.
82
+ */
83
+ async load(): Promise<boolean> {
84
+ if (this.model) return true;
85
+ if (!this.loading) {
86
+ this.loading = this.doLoad().finally(() => {
87
+ this.loading = null;
88
+ });
89
+ }
90
+ return (await this.loading) !== null;
91
+ }
92
+
93
+ private async doLoad(): Promise<LoadedModel | null> {
94
+ if (!isEmbeddingArtifactInstalled()) {
95
+ this.lastError = 'embedding artifact is not installed';
96
+ return null;
97
+ }
98
+
99
+ const dir = getEmbeddingModelDir();
100
+ try {
101
+ const started = performance.now();
102
+
103
+ const manifest = JSON.parse(await Bun.file(join(dir, 'manifest.json')).text()) as EmbeddingManifest;
104
+ const tokenizerJson = JSON.parse(await Bun.file(join(dir, 'tokenizer.json')).text()) as {
105
+ model: { unk_id?: number };
106
+ };
107
+ const tokenizerConfig = JSON.parse(await Bun.file(join(dir, 'tokenizer_config.json')).text()) as Record<
108
+ string,
109
+ unknown
110
+ >;
111
+ const tokenizer = new Tokenizer(tokenizerJson, tokenizerConfig);
112
+
113
+ const buf = await Bun.file(join(dir, 'model.bin')).arrayBuffer();
114
+ const magic = new TextDecoder().decode(new Uint8Array(buf, 0, MAGIC.length));
115
+ if (magic !== MAGIC) throw new Error(`bad magic in model.bin: ${JSON.stringify(magic)}`);
116
+
117
+ const view = new DataView(buf);
118
+ const rows = view.getUint32(8, true);
119
+ const dim = view.getUint32(12, true);
120
+ if (rows !== manifest.rows || dim !== manifest.dim) {
121
+ throw new Error(`model.bin (${rows}×${dim}) disagrees with manifest (${manifest.rows}×${manifest.dim})`);
122
+ }
123
+
124
+ const scalesEnd = HEADER_BYTES + rows * 4;
125
+ const expected = scalesEnd + rows * dim;
126
+ if (buf.byteLength !== expected) {
127
+ throw new Error(`model.bin is ${buf.byteLength} bytes, expected ${expected}`);
128
+ }
129
+
130
+ const model: LoadedModel = {
131
+ tokenizer,
132
+ scales: new Float32Array(buf.slice(HEADER_BYTES, scalesEnd)),
133
+ quant: new Int8Array(buf, scalesEnd),
134
+ rows,
135
+ dim,
136
+ unkId: tokenizerJson.model.unk_id ?? 1
137
+ };
138
+
139
+ this.model = model;
140
+ this.lastError = null;
141
+ debug.log(
142
+ 'memory',
143
+ `Embedder ready: ${rows.toLocaleString()}×${dim} int8 (${(buf.byteLength / 1e6).toFixed(1)} MB) ` +
144
+ `in ${(performance.now() - started).toFixed(0)} ms`
145
+ );
146
+ return model;
147
+ } catch (error) {
148
+ this.lastError = error instanceof Error ? error.message : String(error);
149
+ debug.error('memory', 'Failed to load embedding artifact', error);
150
+ return null;
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Embed one string. Returns null when the model is not loaded, when the text
156
+ * has no in-vocabulary tokens, or when it has fewer than `minTokens` of them.
157
+ *
158
+ * `minTokens` exists because mean pooling over very few tokens produces an
159
+ * unstable centroid: measured on this artifact, a two-token label like a bare
160
+ * package name scores 0.2+ against unrelated sentences, which is higher than
161
+ * many genuinely correct matches. Such vectors do not encode meaning, they
162
+ * encode noise, and they outrank real answers. Callers that index short
163
+ * labels should set a floor and let BM25 handle them — a filename is exactly
164
+ * what lexical search is best at anyway.
165
+ */
166
+ embed(text: string, options?: { minTokens?: number }): Float32Array | null {
167
+ const model = this.model;
168
+ if (!model) return null;
169
+
170
+ const trimmed = text.trim();
171
+ if (!trimmed) return null;
172
+
173
+ // No special tokens: the model pools raw content vectors, and [PAD]/[UNK]
174
+ // would drag every embedding toward a shared centroid.
175
+ const encoded = model.tokenizer.encode(
176
+ trimmed.length > MAX_CHARS ? trimmed.slice(0, MAX_CHARS) : trimmed,
177
+ { add_special_tokens: false }
178
+ );
179
+ const ids = encoded.ids as ArrayLike<number>;
180
+
181
+ const { quant, scales, dim, unkId, rows } = model;
182
+ const out = new Float32Array(dim);
183
+ let used = 0;
184
+
185
+ for (let i = 0; i < ids.length; i++) {
186
+ const id = ids[i];
187
+ // Unknown tokens carry no signal, and an out-of-range id would read
188
+ // past the table — both are dropped rather than pooled as zeros.
189
+ if (id === unkId || id < 0 || id >= rows) continue;
190
+ const off = id * dim;
191
+ const scale = scales[id];
192
+ for (let d = 0; d < dim; d++) out[d] += quant[off + d] * scale;
193
+ used++;
194
+ }
195
+
196
+ if (used === 0 || used < (options?.minTokens ?? 1)) return null;
197
+
198
+ let norm = 0;
199
+ for (let d = 0; d < dim; d++) {
200
+ out[d] /= used;
201
+ norm += out[d] * out[d];
202
+ }
203
+ norm = Math.sqrt(norm);
204
+ if (norm === 0) return null;
205
+ for (let d = 0; d < dim; d++) out[d] /= norm;
206
+
207
+ return out;
208
+ }
209
+
210
+ /** Embed many strings, preserving positions (null where embedding failed). */
211
+ embedMany(texts: string[]): (Float32Array | null)[] {
212
+ return texts.map(t => this.embed(t));
213
+ }
214
+
215
+ /** Drop the loaded table (used after an artifact update). */
216
+ unload(): void {
217
+ this.model = null;
218
+ this.lastError = null;
219
+ }
220
+ }
221
+
222
+ export const embedder = new Embedder();
223
+
224
+ // ─────────────────────────────────────────────────────────────────────────────
225
+ // Persistence helpers
226
+ // ─────────────────────────────────────────────────────────────────────────────
227
+
228
+ /**
229
+ * Pack a normalized vector into a compact BLOB: float32 scale followed by int8
230
+ * components. 260 bytes for a 256-dim vector versus 1 KB as float32, which
231
+ * matters because retrieval loads every candidate vector to score it.
232
+ */
233
+ export function packVector(vec: Float32Array): Uint8Array {
234
+ let max = 0;
235
+ for (let i = 0; i < vec.length; i++) {
236
+ const v = Math.abs(vec[i]);
237
+ if (v > max) max = v;
238
+ }
239
+ const scale = max / 127 || 1;
240
+
241
+ const out = new Uint8Array(4 + vec.length);
242
+ new DataView(out.buffer).setFloat32(0, scale, true);
243
+ const q = new Int8Array(out.buffer, 4);
244
+ for (let i = 0; i < vec.length; i++) q[i] = Math.round(vec[i] / scale);
245
+ return out;
246
+ }
247
+
248
+ /** Inverse of `packVector`. */
249
+ export function unpackVector(blob: Uint8Array): Float32Array {
250
+ const scale = new DataView(blob.buffer, blob.byteOffset, blob.byteLength).getFloat32(0, true);
251
+ const q = new Int8Array(blob.buffer, blob.byteOffset + 4, blob.byteLength - 4);
252
+ const out = new Float32Array(q.length);
253
+ for (let i = 0; i < q.length; i++) out[i] = q[i] * scale;
254
+ return out;
255
+ }
256
+
257
+ /**
258
+ * Cosine similarity between a query vector and a packed one. Both sides are
259
+ * L2-normalized at creation, so the dot product *is* the cosine and no
260
+ * per-comparison normalization is needed.
261
+ */
262
+ export function cosineToPacked(query: Float32Array, blob: Uint8Array): number {
263
+ const scale = new DataView(blob.buffer, blob.byteOffset, blob.byteLength).getFloat32(0, true);
264
+ const q = new Int8Array(blob.buffer, blob.byteOffset + 4, blob.byteLength - 4);
265
+ const n = Math.min(query.length, q.length);
266
+ let dot = 0;
267
+ for (let i = 0; i < n; i++) dot += query[i] * q[i];
268
+ return dot * scale;
269
+ }
@@ -0,0 +1,17 @@
1
+ export { embedder, packVector, unpackVector, cosineToPacked, type EmbedderStatus } from './embedder';
2
+ export {
3
+ ensureEmbeddingArtifact,
4
+ getEmbeddingInstallStatus,
5
+ onEmbeddingInstallChange,
6
+ type EmbeddingInstallStatus,
7
+ type EmbeddingFailureKind
8
+ } from './install';
9
+ export { vectorCache } from './vector-cache';
10
+ export {
11
+ EMBEDDING_VERSION,
12
+ getStackEmbeddingDir,
13
+ getEmbeddingModelDir,
14
+ isEmbeddingArtifactInstalled,
15
+ readEmbeddingManifest,
16
+ type EmbeddingManifest
17
+ } from './paths';
@@ -0,0 +1,254 @@
1
+ /**
2
+ * On-demand fetch of the embedding artifact.
3
+ *
4
+ * The artifact is REQUIRED, not an enhancement. Retrieval fuses BM25 with vector
5
+ * similarity, and the lexical half alone cannot answer a question phrased
6
+ * differently from the memory that holds the answer — asking in Indonesian about
7
+ * a memory written in English shares no terms at all, so BM25 returns nothing and
8
+ * the feature looks broken rather than degraded. Memory therefore reports itself
9
+ * NOT READY until this lands, and recall stays off until it does.
10
+ *
11
+ * Recording is deliberately exempt from that gate (see `readiness.ts`): the turns
12
+ * a user has while the download runs are usually the ones that set up a project,
13
+ * and losing them to a progress bar would be the worse failure. Extraction keeps
14
+ * writing, the indexer backfills vectors the moment the artifact arrives, and
15
+ * nothing recorded in the meantime is lost.
16
+ *
17
+ * Every file is checksum-verified before it is put in place, and the whole set is
18
+ * written to a temporary directory that is only renamed once complete. A partial
19
+ * or corrupted table would not crash anything; it would quietly return wrong
20
+ * neighbours forever, which is far harder to notice than a failed download.
21
+ */
22
+
23
+ import { mkdir, rename, rm, writeFile } from 'node:fs/promises';
24
+ import { join } from 'node:path';
25
+ import { debug } from '$shared/utils/logger';
26
+ import { embedder } from './embedder';
27
+ import {
28
+ EMBEDDING_ASSETS,
29
+ EMBEDDING_VERSION,
30
+ assetUrl,
31
+ getEmbeddingModelDir,
32
+ getStackEmbeddingDir,
33
+ hasPinnedChecksums,
34
+ isEmbeddingArtifactInstalled
35
+ } from './paths';
36
+
37
+ /**
38
+ * Why a download did not produce a usable artifact.
39
+ *
40
+ * The distinction that matters is whether WAITING can fix it. A network error
41
+ * can; a checksum mismatch cannot, and retrying one forever would hammer the
42
+ * release endpoint while telling the user nothing. `unpublished` is the same
43
+ * kind of dead end from the other direction — no release exists for this version
44
+ * yet, so there is nothing to retry against until the build is upgraded.
45
+ */
46
+ export type EmbeddingFailureKind = 'network' | 'corrupt' | 'unpublished';
47
+
48
+ export interface EmbeddingInstallStatus {
49
+ phase: 'idle' | 'downloading' | 'installed' | 'waiting' | 'failed';
50
+ attempts: number;
51
+ error: string | null;
52
+ failure: EmbeddingFailureKind | null;
53
+ /** True when no further automatic attempt is scheduled. */
54
+ permanent: boolean;
55
+ /** ISO time of the next automatic attempt, when one is scheduled. */
56
+ nextAttemptAt: string | null;
57
+ receivedBytes: number;
58
+ totalBytes: number;
59
+ }
60
+
61
+ /** Total payload, known up front from the pinned sizes. */
62
+ const TOTAL_BYTES = EMBEDDING_ASSETS.reduce((sum, asset) => sum + asset.bytes, 0);
63
+
64
+ /**
65
+ * Backoff for a retryable failure: 15s, 45s, 2m, 6m, then every 15 minutes.
66
+ *
67
+ * The tail is deliberately not unbounded. The common cause is a laptop that is
68
+ * offline or on a captive portal, and that resolves on a timescale of minutes —
69
+ * a schedule that backs off to hours would leave memory unready long after the
70
+ * network came back, with no signal to the user that anything was still waiting.
71
+ */
72
+ const BACKOFF_MS = [15_000, 45_000, 120_000, 360_000];
73
+ const MAX_BACKOFF_MS = 900_000;
74
+
75
+ let status: EmbeddingInstallStatus = {
76
+ phase: 'idle',
77
+ attempts: 0,
78
+ error: null,
79
+ failure: null,
80
+ permanent: false,
81
+ nextAttemptAt: null,
82
+ receivedBytes: 0,
83
+ totalBytes: TOTAL_BYTES
84
+ };
85
+
86
+ let inFlight: Promise<boolean> | null = null;
87
+ let retryTimer: ReturnType<typeof setTimeout> | null = null;
88
+ let onChange: (() => void) | null = null;
89
+
90
+ /** Notified whenever the status changes, so the UI can follow a live download. */
91
+ export function onEmbeddingInstallChange(listener: (() => void) | null): void {
92
+ onChange = listener;
93
+ }
94
+
95
+ export function getEmbeddingInstallStatus(): EmbeddingInstallStatus {
96
+ return { ...status };
97
+ }
98
+
99
+ function setStatus(patch: Partial<EmbeddingInstallStatus>): void {
100
+ status = { ...status, ...patch };
101
+ onChange?.();
102
+ }
103
+
104
+ /**
105
+ * Ensure the artifact is present and loaded. Resolves to whether the embedder
106
+ * ended up ready. Idempotent and safe to call at every startup.
107
+ *
108
+ * `force` restarts a schedule that has given up, which is what the Settings
109
+ * button and a fresh startup both need — otherwise a permanent failure would
110
+ * stay permanent for the life of the process even after the user fixed it.
111
+ */
112
+ export function ensureEmbeddingArtifact(force = false): Promise<boolean> {
113
+ if (inFlight) return inFlight;
114
+ if (force) {
115
+ clearRetry();
116
+ setStatus({ attempts: 0, permanent: false, nextAttemptAt: null });
117
+ }
118
+ inFlight = run().finally(() => {
119
+ inFlight = null;
120
+ });
121
+ return inFlight;
122
+ }
123
+
124
+ function clearRetry(): void {
125
+ if (retryTimer) {
126
+ clearTimeout(retryTimer);
127
+ retryTimer = null;
128
+ }
129
+ }
130
+
131
+ /** Schedule the next attempt, or stop and say why. */
132
+ function scheduleRetry(kind: EmbeddingFailureKind, message: string): void {
133
+ // Neither of these can be fixed by trying again: the bytes at the far end are
134
+ // wrong, or there are no bytes at the far end at all.
135
+ if (kind === 'corrupt' || kind === 'unpublished') {
136
+ setStatus({ phase: 'failed', error: message, failure: kind, permanent: true, nextAttemptAt: null });
137
+ return;
138
+ }
139
+
140
+ const delay = BACKOFF_MS[Math.min(status.attempts - 1, BACKOFF_MS.length - 1)] ?? MAX_BACKOFF_MS;
141
+ const wait = Math.min(delay, MAX_BACKOFF_MS);
142
+ setStatus({
143
+ phase: 'waiting',
144
+ error: message,
145
+ failure: kind,
146
+ permanent: false,
147
+ nextAttemptAt: new Date(Date.now() + wait).toISOString()
148
+ });
149
+
150
+ clearRetry();
151
+ retryTimer = setTimeout(() => {
152
+ retryTimer = null;
153
+ void ensureEmbeddingArtifact();
154
+ }, wait);
155
+ // A pending retry must never hold the process open on its own.
156
+ retryTimer.unref?.();
157
+ }
158
+
159
+ async function run(): Promise<boolean> {
160
+ if (isEmbeddingArtifactInstalled()) {
161
+ const loaded = await embedder.load();
162
+ if (loaded) {
163
+ clearRetry();
164
+ setStatus({
165
+ phase: 'installed',
166
+ error: null,
167
+ failure: null,
168
+ permanent: false,
169
+ nextAttemptAt: null,
170
+ receivedBytes: TOTAL_BYTES
171
+ });
172
+ }
173
+ return loaded;
174
+ }
175
+
176
+ if (!hasPinnedChecksums()) {
177
+ // No release has been cut for this version yet. Downloading without a
178
+ // checksum to compare against would be verification theatre, so it is
179
+ // skipped and said plainly.
180
+ const message = `No published embedding artifact for v${EMBEDDING_VERSION}`;
181
+ debug.log(
182
+ 'memory',
183
+ `${message} — build one locally with: bun scripts/build-embedding-artifact.ts --install`
184
+ );
185
+ scheduleRetry('unpublished', message);
186
+ return false;
187
+ }
188
+
189
+ const target = getEmbeddingModelDir();
190
+ const staging = `${target}.partial`;
191
+
192
+ setStatus({ phase: 'downloading', attempts: status.attempts + 1, error: null, receivedBytes: 0 });
193
+
194
+ try {
195
+ await rm(staging, { recursive: true, force: true });
196
+ await mkdir(staging, { recursive: true });
197
+
198
+ let downloaded = 0;
199
+ for (const asset of EMBEDDING_ASSETS) {
200
+ const url = assetUrl(asset.file);
201
+ const response = await fetch(url);
202
+ if (!response.ok) throw new Error(`GET ${url} → ${response.status} ${response.statusText}`);
203
+
204
+ const bytes = new Uint8Array(await response.arrayBuffer());
205
+ const digest = Bun.SHA256.hash(bytes, 'hex');
206
+ if (digest !== asset.sha256) {
207
+ // Thrown apart from the network errors below, because no amount of
208
+ // retrying turns the wrong bytes into the right ones.
209
+ throw new CorruptAssetError(
210
+ `checksum mismatch for ${asset.file}: expected ${asset.sha256}, got ${digest}`
211
+ );
212
+ }
213
+
214
+ await writeFile(join(staging, asset.file), bytes);
215
+ downloaded += bytes.byteLength;
216
+ setStatus({ receivedBytes: downloaded });
217
+ }
218
+
219
+ await mkdir(getStackEmbeddingDir(), { recursive: true });
220
+ await rm(target, { recursive: true, force: true });
221
+ await rename(staging, target);
222
+
223
+ debug.log('memory', `Embedding artifact v${EMBEDDING_VERSION} installed (${(downloaded / 1e6).toFixed(1)} MB)`);
224
+ } catch (error) {
225
+ await rm(staging, { recursive: true, force: true }).catch(() => {});
226
+ const message = error instanceof Error ? error.message : String(error);
227
+ const kind: EmbeddingFailureKind = error instanceof CorruptAssetError ? 'corrupt' : 'network';
228
+ debug.warn('memory', `Embedding artifact download failed (${kind})`, error);
229
+ scheduleRetry(kind, message);
230
+ return false;
231
+ }
232
+
233
+ embedder.unload();
234
+ const loaded = await embedder.load();
235
+ if (loaded) {
236
+ clearRetry();
237
+ setStatus({
238
+ phase: 'installed',
239
+ error: null,
240
+ failure: null,
241
+ permanent: false,
242
+ nextAttemptAt: null,
243
+ receivedBytes: TOTAL_BYTES
244
+ });
245
+ } else {
246
+ // The files verified but the table would not parse — the artifact on the
247
+ // release is not what this build expects, which waiting cannot fix.
248
+ scheduleRetry('corrupt', embedder.status().error ?? 'artifact failed to load');
249
+ }
250
+ return loaded;
251
+ }
252
+
253
+ /** Marker so the catch can tell a bad payload from a bad connection. */
254
+ class CorruptAssetError extends Error {}
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Where the on-demand embedding artifact lives, and what it is made of.
3
+ *
4
+ * The weights are DATA, not code, so they are fetched from a GitHub release
5
+ * asset rather than installed as an npm package. npm would have meant publishing
6
+ * a package this repository is itself the source of, and a 44 MB payload whose
7
+ * only consumer resolves it by path anyway.
8
+ *
9
+ * Files land in `~/.clopen/stack/embedding/<version>/`, alongside the engine
10
+ * SDKs — a clopen-managed directory, so a globally installed clopen never
11
+ * touches the user's global store or their projects. Versioning the directory
12
+ * means a new artifact is a fresh download rather than an in-place overwrite,
13
+ * so a half-finished fetch can never leave a mixed set of files behind.
14
+ */
15
+
16
+ import { join } from 'node:path';
17
+ import { existsSync, readFileSync } from 'node:fs';
18
+ import { getClopenDir } from '$backend/utils/paths';
19
+
20
+ /**
21
+ * Artifact version. Also the release tag: `embedding-v<version>`.
22
+ *
23
+ * Bump this together with the checksums below whenever the artifact is rebuilt —
24
+ * they are what makes a download verifiable, so a mismatched pair is worse than
25
+ * no pin at all.
26
+ */
27
+ export const EMBEDDING_VERSION = '0.0.1';
28
+
29
+ /** GitHub repository the release assets are published from. */
30
+ const RELEASE_REPO = 'myrialabs/clopen';
31
+
32
+ export interface EmbeddingAsset {
33
+ file: string;
34
+ /** SHA-256 of the file, hex. Emitted by `scripts/build-embedding-artifact.ts`. */
35
+ sha256: string;
36
+ bytes: number;
37
+ }
38
+
39
+ /**
40
+ * The four files that make up the artifact, with the checksums the build script
41
+ * emitted. Downloads are verified against these before anything is written into
42
+ * place: the payload is executed as weights, not code, but a corrupted table
43
+ * would silently poison every similarity score rather than fail loudly.
44
+ *
45
+ * `hasPinnedChecksums()` reports whether they are real, so the installer refuses
46
+ * to download rather than pretending to verify against an empty hash.
47
+ */
48
+ export const EMBEDDING_ASSETS: EmbeddingAsset[] = [
49
+ { file: 'model.bin', sha256: '777801e24cd154ee1c87fe62b9e6a2a7afecf1c695bb0e29d0a0ee4d7fd76f87', bytes: 39000016 },
50
+ { file: 'tokenizer.json', sha256: 'fe59f0916aab8a9b73daadb1b9b3ed9a38b81f46de4848c3fdbe10123b97f828', bytes: 5411414 },
51
+ { file: 'tokenizer_config.json', sha256: 'bd0e8c3a56aeac5078a6445e6b04425cd17b41bcc8d382ae925b5dbca287f8eb', bytes: 1898 },
52
+ { file: 'manifest.json', sha256: '584e9e64e7baa33bbb244e281791736238144d68b226dc09c3fc9a7b27a21ce7', bytes: 214 }
53
+ ];
54
+
55
+ /** True once real checksums have been pinned for the current version. */
56
+ export function hasPinnedChecksums(): boolean {
57
+ return EMBEDDING_ASSETS.every(asset => asset.sha256.length === 64);
58
+ }
59
+
60
+ /** Download URL for one asset of the current version. */
61
+ export function assetUrl(file: string): string {
62
+ return `https://github.com/${RELEASE_REPO}/releases/download/embedding-v${EMBEDDING_VERSION}/${file}`;
63
+ }
64
+
65
+ /** Managed directory holding every installed artifact version. */
66
+ export function getStackEmbeddingDir(): string {
67
+ return join(getClopenDir(), 'stack', 'embedding');
68
+ }
69
+
70
+ /** Directory holding the current version's `model.bin`, tokenizer and manifest. */
71
+ export function getEmbeddingModelDir(): string {
72
+ return join(getStackEmbeddingDir(), EMBEDDING_VERSION);
73
+ }
74
+
75
+ export interface EmbeddingManifest {
76
+ source: string;
77
+ sourceLicense: string;
78
+ rows: number;
79
+ dim: number;
80
+ quantization: string;
81
+ vocabLimit: number;
82
+ }
83
+
84
+ /**
85
+ * Whether a usable artifact is present. Checks every payload file rather than
86
+ * just the directory, so a half-finished install reads as missing instead of
87
+ * failing later during load.
88
+ */
89
+ export function isEmbeddingArtifactInstalled(): boolean {
90
+ const dir = getEmbeddingModelDir();
91
+ return EMBEDDING_ASSETS.every(asset => existsSync(join(dir, asset.file)));
92
+ }
93
+
94
+ /** Parsed manifest of the installed artifact, or null when unavailable. */
95
+ export function readEmbeddingManifest(): EmbeddingManifest | null {
96
+ try {
97
+ return JSON.parse(readFileSync(join(getEmbeddingModelDir(), 'manifest.json'), 'utf8')) as EmbeddingManifest;
98
+ } catch {
99
+ return null;
100
+ }
101
+ }