@zenera/neo 1.1.54 → 1.1.55

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.
@@ -1,83 +1,117 @@
1
- import { unlinkSync } from 'node:fs';
2
- import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
1
+ import { existsSync } from 'node:fs';
2
+ import { cp, mkdir } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
- import { claimLock, liveHolder, ownLock } from "../lock.js";
4
+ import { DatabaseSync } from 'node:sqlite';
5
5
  import { MemoryGraph } from "./graph.js";
6
6
  import { MemoryError } from "./types.js";
7
7
  import { VectorBlock } from "./vectors.js";
8
8
  // ---------------------------------------------------------------------------
9
9
  // What a memory is, on disk
10
10
  //
11
- // A directory, and the order it is written in is the whole crash story: the
12
- // manifest goes last, so a half-written memory has no manifest and reads as
13
- // empty rather than as a graph that quietly lost its vectors. Every file lands
14
- // through a temporary name and a rename, which on a local filesystem is atomic,
15
- // so a reader never sees half a graph.
11
+ // One SQLite database beside a `files/` directory. SQLite is what makes a
12
+ // memory safe to share: in WAL mode any number of connections read while one
13
+ // writes, every write is a transaction that lands whole or not at all, and a
14
+ // process killed mid-write leaves the last committed state behind rather than
15
+ // half a graph. It is built into Node, so this costs `@zenera/neo` no
16
+ // dependency and ships no binary of its own.
16
17
  //
17
- // The lock is advisory and per directory. Memory is project-scoped, and two
18
- // runs of the same project writing the same graph would interleave commits and
19
- // lose edges — but a lock whose process is gone is stale by definition and gets
20
- // taken, because a crashed run must not make a project permanently unusable.
18
+ // The graph is still read whole and held in memory — recall, grep and merge
19
+ // all walk it — so the database is the record and `MemoryGraph` a cache of it.
20
+ // Every row carries the sequence number of the write that last touched it, and
21
+ // a forgotten node leaves a tombstone, so catching up with what other runs
22
+ // committed is a read of the rows newer than the last one seen, not a reload.
21
23
  //
22
- // Vectors live beside the graph rather than inside it. `graph.json` is parsed
23
- // whole on open and a few thousand embeddings inflate to megabytes of JSON
24
- // numbers; the same data as raw little-endian float32 is a quarter the size and
25
- // needs no parsing at all.
24
+ // A write is `write(fn)`: take the write lock, catch up, let `fn` change the
25
+ // graph, persist exactly what it changed, commit. `fn` runs against the graph
26
+ // as it stands on disk at that moment, which is what lets two runs change the
27
+ // same memory without one silently undoing the other. It must be synchronous:
28
+ // `DatabaseSync` waits for the lock by blocking the thread, so a transaction
29
+ // held across an `await` would leave every other connection in this process
30
+ // waiting on a lock nothing can release.
26
31
  // ---------------------------------------------------------------------------
27
- export const MEMORY_VERSION = 1;
28
- export const GRAPH_FILE = 'graph.json';
29
- export const VECTORS_FILE = 'vectors.f32';
30
- export const VECTOR_IDS_FILE = 'vectors.json';
31
- export const MANIFEST_FILE = 'manifest.json';
32
+ export const MEMORY_VERSION = 2;
33
+ export const MEMORY_DB = 'memory.db';
32
34
  export const FILES_DIR = 'files';
33
- export const LOCK_FILE = '.lock';
35
+ /** The version 1 graph; present without a database, it means the memory needs migrating. */
36
+ export const LEGACY_GRAPH_FILE = 'graph.json';
37
+ /** How long a write waits for another to finish before giving up. */
38
+ export const BUSY_TIMEOUT_MS = 5000;
39
+ /** Tombstones kept for readers catching up; one further behind reloads in full. */
40
+ const TOMBSTONES = 1000;
41
+ const SCHEMA = `
42
+ CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
43
+ CREATE TABLE IF NOT EXISTS nodes (
44
+ id TEXT PRIMARY KEY,
45
+ body TEXT NOT NULL,
46
+ seq INTEGER NOT NULL
47
+ );
48
+ CREATE INDEX IF NOT EXISTS nodes_seq ON nodes (seq);
49
+ CREATE TABLE IF NOT EXISTS edges (
50
+ source TEXT NOT NULL REFERENCES nodes (id) ON DELETE CASCADE,
51
+ relation TEXT NOT NULL,
52
+ target TEXT NOT NULL REFERENCES nodes (id) ON DELETE CASCADE,
53
+ attrs TEXT NOT NULL,
54
+ seq INTEGER NOT NULL,
55
+ PRIMARY KEY (source, relation, target)
56
+ );
57
+ CREATE INDEX IF NOT EXISTS edges_target ON edges (target);
58
+ CREATE INDEX IF NOT EXISTS edges_seq ON edges (seq);
59
+ CREATE TABLE IF NOT EXISTS vectors (
60
+ id TEXT PRIMARY KEY REFERENCES nodes (id) ON DELETE CASCADE,
61
+ data BLOB NOT NULL,
62
+ seq INTEGER NOT NULL
63
+ );
64
+ CREATE INDEX IF NOT EXISTS vectors_seq ON vectors (seq);
65
+ CREATE TABLE IF NOT EXISTS forgotten (id TEXT NOT NULL, seq INTEGER NOT NULL);
66
+ CREATE INDEX IF NOT EXISTS forgotten_seq ON forgotten (seq);
67
+ `;
34
68
  export class MemoryStore {
35
69
  dir;
36
- graph;
37
70
  readOnly;
71
+ #graph = new MemoryGraph();
38
72
  #embedding;
39
73
  #vectors;
40
- #locked = false;
41
- constructor(dir, graph, vectors, embedding, readOnly) {
74
+ #db;
75
+ #statements = new Map();
76
+ #busyMs;
77
+ /** the last write this cache has caught up with */
78
+ #seq = 0;
79
+ /** `PRAGMA data_version` when last caught up; it moves only when another connection commits */
80
+ #version = -1;
81
+ constructor(dir, readOnly, busyMs) {
42
82
  this.dir = dir;
43
- this.graph = graph;
44
- this.#vectors = vectors;
45
- this.#embedding = embedding;
46
83
  this.readOnly = readOnly;
84
+ this.#busyMs = busyMs;
47
85
  }
48
86
  static async open(dir, opts = {}) {
49
87
  const readOnly = opts.readOnly === true;
50
- if (!readOnly) {
51
- await mkdir(join(dir, FILES_DIR), { recursive: true });
88
+ const path = join(dir, MEMORY_DB);
89
+ if (!existsSync(path) && existsSync(join(dir, LEGACY_GRAPH_FILE))) {
90
+ throw new MemoryError(`${dir} holds a version 1 memory`, `convert it once with \`zen memory migrate --dir ${dir}\``);
52
91
  }
53
- const manifest = await readManifest(dir);
54
92
  // Opening for writing brings a memory into existence; opening one to
55
93
  // read from has to find it, or a mistyped path is an empty graph that
56
94
  // answers every question with silence and reports no error.
57
- if (readOnly && !manifest) {
58
- throw new MemoryError(`${dir} is not a memory`, `no ${MANIFEST_FILE} in it, and a read-only open cannot create one`);
59
- }
60
- if (manifest?.embedding && opts.embedding) {
61
- const a = manifest.embedding;
62
- const b = opts.embedding;
63
- if (a.model !== b.model || a.dimensions !== b.dimensions) {
64
- throw new MemoryError(`this memory was embedded with ${a.model} (${a.dimensions}d), ` +
65
- `but ${b.model} (${b.dimensions}d) is configured`, 'restore the original model, or start a new memory');
66
- }
67
- }
68
- const graph = manifest
69
- ? MemoryGraph.from(JSON.parse(await readFile(join(dir, GRAPH_FILE), 'utf8')))
70
- : new MemoryGraph();
71
- const embedding = opts.embedding ?? manifest?.embedding;
72
- const vectors = manifest && embedding ? await readVectors(dir, embedding) : undefined;
73
- const store = new MemoryStore(dir, graph, vectors, embedding, readOnly);
74
- // A reader that claimed the lock would only be refusing itself, and the
75
- // readers of one graph are meant to be able to refuse each other least.
76
- if (!readOnly && opts.lock !== false) {
77
- store.#claim();
95
+ if (readOnly && !existsSync(path)) {
96
+ throw new MemoryError(`${dir} is not a memory`, `no ${MEMORY_DB} in it, and a read-only open cannot create one`);
97
+ }
98
+ if (!readOnly) {
99
+ await mkdir(join(dir, FILES_DIR), { recursive: true });
100
+ }
101
+ const store = new MemoryStore(dir, readOnly, opts.busyTimeoutMs ?? BUSY_TIMEOUT_MS);
102
+ store.#embedding = opts.embedding;
103
+ if (store.#connect(false)) {
104
+ const held = store.#read(() => store.#meta('embedding'));
105
+ if (held && opts.embedding) {
106
+ assertSame(held, opts.embedding);
107
+ }
108
+ store.#reload();
78
109
  }
79
110
  return store;
80
111
  }
112
+ get graph() {
113
+ return this.#graph;
114
+ }
81
115
  get embedding() {
82
116
  return this.#embedding;
83
117
  }
@@ -90,10 +124,7 @@ export class MemoryStore {
90
124
  adopt(embedding) {
91
125
  const held = this.#embedding;
92
126
  if (held) {
93
- if (held.model !== embedding.model || held.dimensions !== embedding.dimensions) {
94
- throw new MemoryError(`this memory was embedded with ${held.model} (${held.dimensions}d), ` +
95
- `but ${embedding.model} (${embedding.dimensions}d) is configured`, 'restore the original model, or start a new memory');
96
- }
127
+ assertSame(held, embedding);
97
128
  return;
98
129
  }
99
130
  this.#embedding = embedding;
@@ -108,100 +139,352 @@ export class MemoryStore {
108
139
  filePath(name) {
109
140
  return join(this.dir, FILES_DIR, name);
110
141
  }
111
- /** Manifest last: a torn commit reads as no memory, never as a partial one. */
112
- async commit() {
113
- // Loudly, not quietly. A write that is silently dropped is a run that
114
- // believes it remembered something and did not.
142
+ /**
143
+ * Catches up with what other connections committed. Cheap when nothing
144
+ * did: one pragma, answered from shared memory without touching the file.
145
+ */
146
+ refresh() {
147
+ if (!this.#db && !this.#connect(false)) {
148
+ return;
149
+ }
150
+ const version = this.#dataVersion();
151
+ if (version === this.#version) {
152
+ return;
153
+ }
154
+ this.#read(() => this.#pull());
155
+ this.#version = version;
156
+ }
157
+ /**
158
+ * One transaction: catch up, let `fn` change the graph, persist what it
159
+ * changed. Whatever `fn` throws rolls the whole thing back, on disk and in
160
+ * the cache.
161
+ */
162
+ write(fn) {
115
163
  if (this.readOnly) {
164
+ // Loudly, not quietly. A write that is silently dropped is a run
165
+ // that believes it remembered something and did not.
116
166
  throw new MemoryError('this memory is open read-only', 'nothing this run learns can be kept — point it at a memory of its own');
117
167
  }
118
- // Indented so a committed memory diffs per node rather than as one line.
119
- await atomic(join(this.dir, GRAPH_FILE), `${JSON.stringify(this.graph.export(), null, 2)}\n`);
120
- const vectors = this.#vectors;
121
- if (vectors) {
122
- const raw = vectors.bytes();
123
- await atomic(join(this.dir, VECTORS_FILE), new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength));
124
- await atomic(join(this.dir, VECTOR_IDS_FILE), `${JSON.stringify({ dims: vectors.dims, ids: vectors.ids }, null, 2)}\n`);
125
- }
126
- const manifest = {
127
- version: MEMORY_VERSION,
128
- ...(this.#embedding ? { embedding: this.#embedding } : {}),
129
- nodes: this.graph.order,
130
- edges: this.graph.size,
131
- updatedAt: new Date().toISOString(),
132
- };
133
- await atomic(join(this.dir, MANIFEST_FILE), `${JSON.stringify(manifest, null, 4)}\n`);
168
+ this.#connect(true);
169
+ const db = this.#db;
170
+ try {
171
+ db.exec('BEGIN IMMEDIATE');
172
+ }
173
+ catch (err) {
174
+ throw busy(this.dir, err);
175
+ }
176
+ try {
177
+ this.#pull();
178
+ const out = fn();
179
+ if (out instanceof Promise) {
180
+ throw new Error('MemoryStore.write takes a synchronous function');
181
+ }
182
+ this.#flush();
183
+ db.exec('COMMIT');
184
+ this.#graph.settle();
185
+ return out;
186
+ }
187
+ catch (err) {
188
+ if (db.isTransaction) {
189
+ db.exec('ROLLBACK');
190
+ }
191
+ if (this.#graph.dirty) {
192
+ this.#reload();
193
+ }
194
+ throw err;
195
+ }
134
196
  }
197
+ /** Persists whatever the graph changed outside `write` — a merge folding in memory. */
198
+ async commit() {
199
+ this.write(() => undefined);
200
+ }
201
+ /** Folds the log into the database file and closes, so a committed `.db` is complete. */
135
202
  release() {
136
- if (!this.#locked) {
203
+ const db = this.#db;
204
+ if (!db) {
137
205
  return;
138
206
  }
139
- this.#locked = false;
207
+ this.#db = undefined;
208
+ this.#statements.clear();
209
+ try {
210
+ if (!this.readOnly) {
211
+ db.exec('PRAGMA wal_checkpoint(TRUNCATE)');
212
+ }
213
+ }
214
+ catch {
215
+ // Another connection is still reading; the last one to close folds it in.
216
+ }
140
217
  try {
141
- unlinkSync(join(this.dir, LOCK_FILE));
218
+ db.close();
142
219
  }
143
220
  catch {
144
- // Already gone, or taken over as stale: neither is worth failing a run for.
221
+ // already closed
222
+ }
223
+ }
224
+ // --- the connection ---
225
+ #connect(create) {
226
+ if (this.#db) {
227
+ return true;
228
+ }
229
+ const path = join(this.dir, MEMORY_DB);
230
+ if (!create && !existsSync(path)) {
231
+ return false;
232
+ }
233
+ let db;
234
+ try {
235
+ db = new DatabaseSync(path, { readOnly: this.readOnly, timeout: this.#busyMs });
236
+ }
237
+ catch (err) {
238
+ throw new MemoryError(`cannot open ${path}: ${err.message}`);
239
+ }
240
+ try {
241
+ const version = Number(db.prepare('PRAGMA user_version').get().user_version);
242
+ if (version !== MEMORY_VERSION && !(version === 0 && !this.readOnly)) {
243
+ throw new MemoryError(`this memory is version ${version}, but this build reads version ${MEMORY_VERSION}`, 'open it with the build that wrote it, or start a new memory');
244
+ }
245
+ if (!this.readOnly) {
246
+ db.exec('PRAGMA journal_mode = WAL');
247
+ db.exec('PRAGMA synchronous = NORMAL');
248
+ db.exec('PRAGMA foreign_keys = ON');
249
+ if (version === 0) {
250
+ db.exec('BEGIN IMMEDIATE');
251
+ db.exec(SCHEMA);
252
+ db.exec(`PRAGMA user_version = ${MEMORY_VERSION}`);
253
+ db.exec('COMMIT');
254
+ }
255
+ }
256
+ }
257
+ catch (err) {
258
+ db.close();
259
+ if (err instanceof MemoryError) {
260
+ throw err;
261
+ }
262
+ throw busy(this.dir, err);
145
263
  }
264
+ this.#db = db;
265
+ return true;
146
266
  }
147
- #claim() {
148
- claimLock(join(this.dir, LOCK_FILE), ownLock(), (held) => new MemoryError(`this memory is in use (pid ${held.pid}, since ${held.startedAt})`, 'wait for that run to finish, or remove .lock if it crashed'));
149
- this.#locked = true;
267
+ #sql(text) {
268
+ let statement = this.#statements.get(text);
269
+ if (!statement) {
270
+ statement = this.#db.prepare(text);
271
+ this.#statements.set(text, statement);
272
+ }
273
+ return statement;
150
274
  }
151
- }
152
- async function readManifest(dir) {
153
- try {
154
- const manifest = JSON.parse(await readFile(join(dir, MANIFEST_FILE), 'utf8'));
155
- if (manifest.version !== MEMORY_VERSION) {
156
- throw new MemoryError(`this memory is version ${manifest.version}, but this build reads version ${MEMORY_VERSION}`, 'export it with the older build, or start a new memory');
275
+ #dataVersion() {
276
+ return Number(this.#sql('PRAGMA data_version').get().data_version);
277
+ }
278
+ /** Several reads that must see one snapshot. */
279
+ #read(fn) {
280
+ const db = this.#db;
281
+ if (db.isTransaction) {
282
+ return fn();
283
+ }
284
+ db.exec('BEGIN');
285
+ try {
286
+ return fn();
287
+ }
288
+ finally {
289
+ db.exec('COMMIT');
157
290
  }
158
- return manifest;
159
291
  }
160
- catch (err) {
161
- if (err instanceof MemoryError) {
162
- throw err;
292
+ #meta(key) {
293
+ const row = this.#sql('SELECT value FROM meta WHERE key = ?').get(key);
294
+ return row ? JSON.parse(row.value) : undefined;
295
+ }
296
+ #setMeta(key, value) {
297
+ this.#sql('INSERT INTO meta (key, value) VALUES (?, ?) ' +
298
+ 'ON CONFLICT (key) DO UPDATE SET value = excluded.value').run(key, JSON.stringify(value));
299
+ }
300
+ // --- reading ---
301
+ /** The whole memory, from scratch. Discards anything not yet persisted. */
302
+ #reload() {
303
+ const db = this.#db;
304
+ if (!db) {
305
+ this.#graph = new MemoryGraph();
306
+ this.#vectors = undefined;
307
+ this.#seq = 0;
308
+ return;
309
+ }
310
+ this.#read(() => {
311
+ this.#adoptEmbedding();
312
+ const graph = new MemoryGraph();
313
+ for (const row of this.#sql('SELECT body FROM nodes').all()) {
314
+ graph.adopt(JSON.parse(row.body));
315
+ }
316
+ for (const row of this.#sql('SELECT source, target, attrs FROM edges').all()) {
317
+ graph.adoptEdge(row.source, row.target, JSON.parse(row.attrs));
318
+ }
319
+ graph.settle();
320
+ this.#graph = graph;
321
+ this.#vectors = this.#embedding
322
+ ? new VectorBlock(this.#embedding.dimensions)
323
+ : undefined;
324
+ for (const row of this.#sql('SELECT id, data FROM vectors').all()) {
325
+ this.#setVector(row);
326
+ }
327
+ this.#seq = this.#meta('seq') ?? 0;
328
+ });
329
+ this.#version = this.#dataVersion();
330
+ }
331
+ /** What other connections committed since this cache last looked. Inside a transaction. */
332
+ #pull() {
333
+ const seq = this.#meta('seq') ?? 0;
334
+ if (seq === this.#seq) {
335
+ return;
336
+ }
337
+ if (this.#seq < (this.#meta('floor') ?? 0) && !this.#graph.dirty) {
338
+ this.#reload();
339
+ return;
340
+ }
341
+ this.#adoptEmbedding();
342
+ const since = this.#seq;
343
+ const graph = this.#graph;
344
+ graph.untracked(() => {
345
+ const gone = this.#sql('SELECT id FROM forgotten WHERE seq > ?').all(since);
346
+ const alive = this.#sql('SELECT 1 FROM nodes WHERE id = ?');
347
+ for (const { id } of gone) {
348
+ // A row still there means the id came back after it was forgotten.
349
+ if (!graph.isDirty(id) && !alive.get(id)) {
350
+ graph.forget(id);
351
+ this.#vectors?.remove(id);
352
+ }
353
+ }
354
+ const nodes = this.#sql('SELECT body FROM nodes WHERE seq > ?').all(since);
355
+ for (const row of nodes) {
356
+ const node = JSON.parse(row.body);
357
+ if (!graph.isDirty(node.id)) {
358
+ graph.adopt(node);
359
+ }
360
+ }
361
+ const edges = this.#sql('SELECT source, target, attrs FROM edges WHERE seq > ?').all(since);
362
+ for (const row of edges) {
363
+ if (graph.has(row.source) && graph.has(row.target)) {
364
+ graph.adoptEdge(row.source, row.target, JSON.parse(row.attrs));
365
+ }
366
+ }
367
+ });
368
+ const vectors = this.#sql('SELECT id, data FROM vectors WHERE seq > ?').all(since);
369
+ for (const row of vectors) {
370
+ if (!graph.isDirty(row.id)) {
371
+ this.#setVector(row);
372
+ }
163
373
  }
164
- return undefined;
374
+ this.#seq = seq;
375
+ }
376
+ /** A memory first embedded by another run tells this one what it was embedded with. */
377
+ #adoptEmbedding() {
378
+ const held = this.#meta('embedding');
379
+ if (held && !this.#embedding) {
380
+ this.#embedding = held;
381
+ }
382
+ }
383
+ #setVector(row) {
384
+ const block = this.vectors;
385
+ const data = new Float32Array(row.data.byteLength / 4);
386
+ new Uint8Array(data.buffer).set(row.data);
387
+ if (block && data.length === block.dims) {
388
+ block.set(row.id, data);
389
+ }
390
+ }
391
+ // --- writing ---
392
+ /** Inside the write transaction: exactly what the graph says changed. */
393
+ #flush() {
394
+ const seq = this.#seq + 1;
395
+ const changes = this.#graph.changes();
396
+ const vectors = this.#vectors;
397
+ if (this.#embedding) {
398
+ const held = this.#meta('embedding');
399
+ if (held) {
400
+ assertSame(held, this.#embedding);
401
+ }
402
+ else {
403
+ this.#setMeta('embedding', this.#embedding);
404
+ }
405
+ }
406
+ const drop = this.#sql('DELETE FROM nodes WHERE id = ?');
407
+ const tombstone = this.#sql('INSERT INTO forgotten (id, seq) VALUES (?, ?)');
408
+ for (const id of changes.dropped) {
409
+ drop.run(id);
410
+ tombstone.run(id, seq);
411
+ }
412
+ const node = this.#sql('INSERT INTO nodes (id, body, seq) VALUES (?, ?, ?) ' +
413
+ 'ON CONFLICT (id) DO UPDATE SET body = excluded.body, seq = excluded.seq');
414
+ const vector = this.#sql('INSERT INTO vectors (id, data, seq) VALUES (?, ?, ?) ' +
415
+ 'ON CONFLICT (id) DO UPDATE SET data = excluded.data, seq = excluded.seq');
416
+ for (const id of changes.nodes) {
417
+ const current = this.#graph.get(id);
418
+ if (!current) {
419
+ continue;
420
+ }
421
+ node.run(id, JSON.stringify(current), seq);
422
+ const v = vectors?.get(id);
423
+ if (v) {
424
+ vector.run(id, new Uint8Array(v.buffer, v.byteOffset, v.byteLength), seq);
425
+ }
426
+ }
427
+ const edge = this.#sql('INSERT INTO edges (source, relation, target, attrs, seq) VALUES (?, ?, ?, ?, ?) ' +
428
+ 'ON CONFLICT (source, relation, target) DO UPDATE SET attrs = excluded.attrs, seq = excluded.seq');
429
+ for (const key of changes.edges) {
430
+ const e = this.#graph.edge(key);
431
+ if (e) {
432
+ edge.run(e.source, e.attrs.relation, e.target, JSON.stringify(e.attrs), seq);
433
+ }
434
+ }
435
+ this.#setMeta('seq', seq);
436
+ if (seq % 100 === 0 && seq > TOMBSTONES) {
437
+ const floor = seq - TOMBSTONES;
438
+ this.#sql('DELETE FROM forgotten WHERE seq <= ?').run(floor);
439
+ this.#setMeta('floor', floor);
440
+ }
441
+ this.#seq = seq;
165
442
  }
166
443
  }
167
- async function readVectors(dir, embedding) {
168
- let ids;
169
- let dims;
170
- try {
171
- const meta = JSON.parse(await readFile(join(dir, VECTOR_IDS_FILE), 'utf8'));
172
- ids = meta.ids;
173
- dims = meta.dims;
174
- }
175
- catch {
176
- return new VectorBlock(embedding.dimensions);
177
- }
178
- if (dims !== embedding.dimensions) {
179
- return new VectorBlock(embedding.dimensions);
180
- }
181
- const raw = await readFile(join(dir, VECTORS_FILE));
182
- // Copied rather than viewed: a Buffer from the pool is not guaranteed to sit
183
- // on a 4-byte boundary, and Float32Array over an unaligned buffer throws.
184
- const data = new Float32Array(Math.floor(raw.byteLength / 4));
185
- Buffer.from(data.buffer, data.byteOffset, data.byteLength).set(raw);
186
- return VectorBlock.load(dims, ids, data);
444
+ function assertSame(held, wanted) {
445
+ if (held.model !== wanted.model || held.dimensions !== wanted.dimensions) {
446
+ throw new MemoryError(`this memory was embedded with ${held.model} (${held.dimensions}d), ` +
447
+ `but ${wanted.model} (${wanted.dimensions}d) is configured`, 'restore the original model, or start a new memory');
448
+ }
187
449
  }
188
- async function atomic(path, body) {
189
- const tmp = `${path}.tmp`;
190
- await writeFile(tmp, body);
450
+ function busy(dir, err) {
451
+ const message = err.message ?? String(err);
452
+ return /locked|busy/i.test(message)
453
+ ? new MemoryError(`the memory in ${dir} is busy`, 'another run held it past the wait; try again when it finishes')
454
+ : new MemoryError(`the memory in ${dir} cannot be written: ${message}`);
455
+ }
456
+ /** Whether a directory holds a memory anything has written to. */
457
+ export function isMemory(dir) {
458
+ return existsSync(join(dir, MEMORY_DB));
459
+ }
460
+ /**
461
+ * The database as of one moment, written to `file`, whatever other runs are
462
+ * doing to it meanwhile.
463
+ */
464
+ export function snapshotMemory(from, file) {
465
+ const db = new DatabaseSync(join(from, MEMORY_DB), {
466
+ readOnly: true,
467
+ timeout: BUSY_TIMEOUT_MS,
468
+ });
191
469
  try {
192
- await rename(tmp, path);
470
+ db.prepare('VACUUM INTO ?').run(file);
193
471
  }
194
- catch (err) {
195
- await rm(tmp, { force: true });
196
- throw err;
472
+ finally {
473
+ db.close();
197
474
  }
198
475
  }
199
476
  /**
200
- * Who is writing a memory right now, if anyone. Read-only on purpose: it never
201
- * claims the lock and never clears a stale one, so it is safe to ask about a
202
- * directory this process has no intention of opening for writing.
477
+ * A consistent copy of a memory another run may be writing to: the database
478
+ * as of one moment, then the files. Files written after that moment come
479
+ * along as well, which costs a few unreferenced bytes and nothing else.
203
480
  */
204
- export function lockHolder(dir) {
205
- return liveHolder(join(dir, LOCK_FILE));
481
+ export async function copyMemory(from, to) {
482
+ await mkdir(to, { recursive: true });
483
+ if (isMemory(from)) {
484
+ snapshotMemory(from, join(to, MEMORY_DB));
485
+ }
486
+ if (existsSync(join(from, FILES_DIR))) {
487
+ await cp(join(from, FILES_DIR), join(to, FILES_DIR), { recursive: true });
488
+ }
206
489
  }
207
490
  //# sourceMappingURL=store.js.map
@@ -16,6 +16,7 @@
16
16
  */
17
17
  import { hash } from "../payload.js";
18
18
  import { MEMORY_COMMIT_TOOL, MEMORY_FORGET_TOOL, MEMORY_GREP_TOOL, MEMORY_LOAD_TOOL, MEMORY_SEARCH_TOOL, tool, withEffects, } from "../types.js";
19
+ import { RevisionMismatch } from "./graph.js";
19
20
  import { GREP_FIELDS, grepMemory } from "./grep.js";
20
21
  import { renderRecollection } from "./render.js";
21
22
  import { canForget, canWrite, KIND_HELP, MemoryError, RELATION_HELP, } from "./types.js";
@@ -408,6 +409,7 @@ export function memoryTools(opts) {
408
409
  },
409
410
  execute: async (args, tc) => {
410
411
  const opId = memoryOpId(tc.state.runId, tc.callId);
412
+ index.refresh();
411
413
  const before = args.ids.flatMap((id) => {
412
414
  const node = index.graph.get(id);
413
415
  return node ? [{ id, kind: node.kind, revision: node.revision }] : [];
@@ -446,6 +448,12 @@ function refusal(err) {
446
448
  if (err instanceof MemoryError) {
447
449
  return { error: err.message, hint: err.hint };
448
450
  }
451
+ if (err instanceof RevisionMismatch) {
452
+ return {
453
+ error: err.message,
454
+ hint: `another run changed it; ${MEMORY_LOAD_TOOL} it again and commit against the new revision`,
455
+ };
456
+ }
449
457
  throw err;
450
458
  }
451
459
  function extractFilePath(raw) {