@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.
@@ -0,0 +1,112 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { mkdir, readFile, rename, rm } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { liveHolder } from "../lock.js";
5
+ import { MemoryGraph } from "./graph.js";
6
+ import { isMemory, LEGACY_GRAPH_FILE, MEMORY_DB, MEMORY_VERSION, MemoryStore, } from "./store.js";
7
+ import { MemoryError } from "./types.js";
8
+ // ---------------------------------------------------------------------------
9
+ // From the version 1 layout to the database
10
+ //
11
+ // Version 1 kept a memory as `graph.json`, `vectors.f32`, `vectors.json` and a
12
+ // `manifest.json` written last. The conversion reads all of it, writes the
13
+ // database in one transaction, and moves the old files into `v1/` rather than
14
+ // deleting them, so a migration that turns out wrong is undone by moving four
15
+ // files back. `files/` is shared by both layouts and does not move.
16
+ // ---------------------------------------------------------------------------
17
+ /** Where the version 1 files are kept once converted. */
18
+ export const LEGACY_DIR = 'v1';
19
+ const LEGACY_FILES = [LEGACY_GRAPH_FILE, 'vectors.f32', 'vectors.json', 'manifest.json', '.lock'];
20
+ export async function migrateMemory(dir) {
21
+ if (isMemory(dir)) {
22
+ throw new MemoryError(`${dir} is already a version ${MEMORY_VERSION} memory`);
23
+ }
24
+ if (!existsSync(join(dir, LEGACY_GRAPH_FILE))) {
25
+ throw new MemoryError(`${dir} is not a version 1 memory`, `no ${LEGACY_GRAPH_FILE} in it`);
26
+ }
27
+ const held = liveHolder(join(dir, '.lock'));
28
+ if (held) {
29
+ throw new MemoryError(`this memory is in use (pid ${held.pid}, since ${held.startedAt})`, 'wait for that run to finish');
30
+ }
31
+ const manifest = await readJson(join(dir, 'manifest.json'));
32
+ if (manifest?.version !== undefined && manifest.version !== 1) {
33
+ throw new MemoryError(`${dir} is version ${manifest.version}, not version 1`);
34
+ }
35
+ const graph = MemoryGraph.from(JSON.parse(await readFile(join(dir, LEGACY_GRAPH_FILE), 'utf8')));
36
+ const embedding = manifest?.embedding;
37
+ const vectors = embedding
38
+ ? await readVectors(dir, embedding.dimensions)
39
+ : new Map();
40
+ const legacy = join(dir, LEGACY_DIR);
41
+ await mkdir(legacy, { recursive: true });
42
+ const moved = [];
43
+ for (const name of LEGACY_FILES) {
44
+ if (existsSync(join(dir, name))) {
45
+ await rename(join(dir, name), join(legacy, name));
46
+ moved.push(name);
47
+ }
48
+ }
49
+ try {
50
+ const store = await MemoryStore.open(dir, embedding ? { embedding } : {});
51
+ try {
52
+ for (const node of graph.nodes()) {
53
+ store.graph.adopt(node);
54
+ }
55
+ for (const link of graph.links()) {
56
+ store.graph.adoptEdge(link.source, link.target, link.attrs);
57
+ }
58
+ for (const [id, vector] of vectors) {
59
+ if (graph.has(id)) {
60
+ store.vectors?.set(id, vector);
61
+ }
62
+ }
63
+ await store.commit();
64
+ }
65
+ finally {
66
+ store.release();
67
+ }
68
+ }
69
+ catch (err) {
70
+ for (const suffix of ['', '-wal', '-shm']) {
71
+ await rm(join(dir, MEMORY_DB + suffix), { force: true });
72
+ }
73
+ for (const name of moved) {
74
+ await rename(join(legacy, name), join(dir, name));
75
+ }
76
+ throw err;
77
+ }
78
+ return {
79
+ dir,
80
+ nodes: graph.order,
81
+ edges: graph.size,
82
+ vectors: [...vectors.keys()].filter((id) => graph.has(id)).length,
83
+ ...(embedding ? { embedding } : {}),
84
+ legacy,
85
+ };
86
+ }
87
+ async function readJson(path) {
88
+ try {
89
+ return JSON.parse(await readFile(path, 'utf8'));
90
+ }
91
+ catch {
92
+ return undefined;
93
+ }
94
+ }
95
+ /** Vectors of a width that no longer matches the manifest are dropped, as version 1 did. */
96
+ async function readVectors(dir, dimensions) {
97
+ const out = new Map();
98
+ const meta = await readJson(join(dir, 'vectors.json'));
99
+ if (!meta || meta.dims !== dimensions) {
100
+ return out;
101
+ }
102
+ const raw = await readFile(join(dir, 'vectors.f32'));
103
+ const data = new Float32Array(Math.floor(raw.byteLength / 4));
104
+ new Uint8Array(data.buffer).set(raw.subarray(0, data.length * 4));
105
+ meta.ids.forEach((id, row) => {
106
+ if ((row + 1) * dimensions <= data.length) {
107
+ out.set(id, data.slice(row * dimensions, (row + 1) * dimensions));
108
+ }
109
+ });
110
+ return out;
111
+ }
112
+ //# sourceMappingURL=migrate.js.map
@@ -1,44 +1,34 @@
1
- import { type Lock } from '../lock.ts';
2
1
  import { MemoryGraph } from './graph.ts';
3
2
  import { VectorBlock } from './vectors.ts';
4
- export declare const MEMORY_VERSION = 1;
5
- export declare const GRAPH_FILE = "graph.json";
6
- export declare const VECTORS_FILE = "vectors.f32";
7
- export declare const VECTOR_IDS_FILE = "vectors.json";
8
- export declare const MANIFEST_FILE = "manifest.json";
3
+ export declare const MEMORY_VERSION = 2;
4
+ export declare const MEMORY_DB = "memory.db";
9
5
  export declare const FILES_DIR = "files";
10
- export declare const LOCK_FILE = ".lock";
6
+ /** The version 1 graph; present without a database, it means the memory needs migrating. */
7
+ export declare const LEGACY_GRAPH_FILE = "graph.json";
8
+ /** How long a write waits for another to finish before giving up. */
9
+ export declare const BUSY_TIMEOUT_MS = 5000;
11
10
  export interface MemoryEmbedding {
12
11
  model: string;
13
12
  dimensions: number;
14
13
  }
15
- export interface MemoryManifest {
16
- version: number;
17
- /** absent when the project configured no embedder and ranks lexically */
18
- embedding?: MemoryEmbedding;
19
- nodes: number;
20
- edges: number;
21
- updatedAt: string;
22
- }
23
14
  export interface OpenOptions {
24
- /** the embedder the caller intends to use; a mismatch with the manifest is fatal */
15
+ /** the embedder the caller intends to use; a mismatch with the memory is fatal */
25
16
  embedding?: MemoryEmbedding;
26
- /** take the directory lock; off for read-only inspection (`zen memory ls`) */
27
- lock?: boolean;
28
17
  /**
29
- * Recall, and nothing else. Writing is refused rather than dropped, the
30
- * directory is never created, and no lock is taken — so any number of runs
31
- * may share one graph at once, which is the whole point of it.
18
+ * Recall, and nothing else. Writing is refused rather than dropped, and the
19
+ * directory is never created, so pointing at a mistyped path fails here.
32
20
  */
33
21
  readOnly?: boolean;
22
+ /** how long a write waits on another; `BUSY_TIMEOUT_MS` by default */
23
+ busyTimeoutMs?: number;
34
24
  }
35
25
  export declare class MemoryStore {
36
26
  #private;
37
27
  readonly dir: string;
38
- readonly graph: MemoryGraph;
39
28
  readonly readOnly: boolean;
40
29
  private constructor();
41
30
  static open(dir: string, opts?: OpenOptions): Promise<MemoryStore>;
31
+ get graph(): MemoryGraph;
42
32
  get embedding(): MemoryEmbedding | undefined;
43
33
  /**
44
34
  * Records the vectoriser actually in use. A width is only knowable from a
@@ -50,14 +40,33 @@ export declare class MemoryStore {
50
40
  /** Absent when no embedder is configured; recall then falls back to term overlap. */
51
41
  get vectors(): VectorBlock | undefined;
52
42
  filePath(name: string): string;
53
- /** Manifest last: a torn commit reads as no memory, never as a partial one. */
43
+ /**
44
+ * Catches up with what other connections committed. Cheap when nothing
45
+ * did: one pragma, answered from shared memory without touching the file.
46
+ */
47
+ refresh(): void;
48
+ /**
49
+ * One transaction: catch up, let `fn` change the graph, persist what it
50
+ * changed. Whatever `fn` throws rolls the whole thing back, on disk and in
51
+ * the cache.
52
+ */
53
+ write<T>(fn: () => T): T;
54
+ /** Persists whatever the graph changed outside `write` — a merge folding in memory. */
54
55
  commit(): Promise<void>;
56
+ /** Folds the log into the database file and closes, so a committed `.db` is complete. */
55
57
  release(): void;
56
58
  }
59
+ /** Whether a directory holds a memory anything has written to. */
60
+ export declare function isMemory(dir: string): boolean;
61
+ /**
62
+ * The database as of one moment, written to `file`, whatever other runs are
63
+ * doing to it meanwhile.
64
+ */
65
+ export declare function snapshotMemory(from: string, file: string): void;
57
66
  /**
58
- * Who is writing a memory right now, if anyone. Read-only on purpose: it never
59
- * claims the lock and never clears a stale one, so it is safe to ask about a
60
- * directory this process has no intention of opening for writing.
67
+ * A consistent copy of a memory another run may be writing to: the database
68
+ * as of one moment, then the files. Files written after that moment come
69
+ * along as well, which costs a few unreferenced bytes and nothing else.
61
70
  */
62
- export declare function lockHolder(dir: string): Lock | undefined;
71
+ export declare function copyMemory(from: string, to: string): Promise<void>;
63
72
  //# sourceMappingURL=store.d.ts.map