@zenera/cli 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.
package/dist/archive.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { ENV_FILE } from '@zenera/engine';
2
+ import { MEMORY_DB } from '@zenera/neo';
2
3
  import { createWriteStream, lstatSync, mkdirSync, readdirSync, statSync } from 'node:fs';
3
4
  import { mkdir } from 'node:fs/promises';
4
5
  import { dirname, join, relative, resolve, sep } from 'node:path';
@@ -72,7 +73,8 @@ export function excluded(rel, isDir, opts = {}) {
72
73
  if (rel === ENV_FILE || (rel.startsWith(`${ENV_FILE}.`) && rel !== ENV_EXAMPLE)) {
73
74
  return 'env';
74
75
  }
75
- if (name === '.lock') {
76
+ // The memory's write-ahead log: `export` carries a snapshot of the database instead.
77
+ if (name === '.lock' || name === `${MEMORY_DB}-wal` || name === `${MEMORY_DB}-shm`) {
76
78
  return 'locks';
77
79
  }
78
80
  if (name === '.DS_Store') {
package/dist/batch.d.ts CHANGED
@@ -63,8 +63,8 @@ export declare function concurrency(value: string | undefined): number;
63
63
  * Each item's memory, made before any of them runs.
64
64
  *
65
65
  * In the copying mode every item gets its own graph to write into, so that
66
- * sixteen runs at once are sixteen private histories rather than one contended
67
- * lock. A source that is not there yet is not an error: a project declares its
66
+ * sixteen runs at once are sixteen private histories rather than one shared
67
+ * one. A source that is not there yet is not an error: a project declares its
68
68
  * memory directory and the first run makes it, so warming a cold project means
69
69
  * copying from nothing, and nothing is what each item starts with.
70
70
  */
@@ -77,8 +77,8 @@ export declare function prepareMemories(items: readonly BatchItem[], at: {
77
77
  /**
78
78
  * Drops the memories nothing was committed to, and counts the ones left.
79
79
  *
80
- * A memory is its manifest and the two files beside it; a directory without
81
- * one is not a memory and `merge` refuses it by name. Leaving those behind
80
+ * A memory is its database; a directory without one is not a memory and
81
+ * `merge` refuses it by name. Leaving those behind
82
82
  * would mean the `merge` line this command prints is advice that fails, so an
83
83
  * item that learned nothing leaves nothing.
84
84
  */
package/dist/batch.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { display, stamp } from '@zenera/engine';
2
- import { addUsage, lockHolder, MANIFEST_FILE as MEMORY_MANIFEST, memoryDir, MemoryStore, mergeModelUsage, readProjectConfig, SANDBOX_GROUP, selectTools, usageByModel, zeroUsage, } from '@zenera/neo';
2
+ import { addUsage, copyMemory, isMemory, LEGACY_GRAPH_FILE, memoryDir, MemoryStore, mergeModelUsage, readProjectConfig, SANDBOX_GROUP, selectTools, usageByModel, zeroUsage, } from '@zenera/neo';
3
3
  import { existsSync } from 'node:fs';
4
- import { cp, mkdir, rm, writeFile } from 'node:fs/promises';
5
- import { basename, join, resolve } from 'node:path';
4
+ import { mkdir, rm, writeFile } from 'node:fs/promises';
5
+ import { join, resolve } from 'node:path';
6
6
  import * as Engine from "./engine.js";
7
7
  import { duration } from "./narrate.js";
8
8
  import { assertLocks } from "./podman.js";
@@ -35,19 +35,13 @@ export async function runBatch(opts) {
35
35
  // A project declares its memory directory; it is the first run that makes
36
36
  // one. So a batch may legitimately be pointed at a graph that is not there
37
37
  // yet - which is the whole of warming a cold project.
38
- const seeded = source !== undefined && existsSync(source);
38
+ const seeded = source !== undefined && isMemory(source);
39
+ if (source && !seeded && existsSync(join(source, LEGACY_GRAPH_FILE))) {
40
+ throw invalidError(`${source} holds a version 1 memory`, `convert it first: zen memory migrate --dir ${source}`);
41
+ }
39
42
  if (opts.memoryReadOnly && !source) {
40
43
  throw usageError('--memory-read-only, but this project has no memory', 'give one with --memory, or drop the flag');
41
44
  }
42
- if (source && seeded) {
43
- // A graph is three files that only mean anything together. Reading one
44
- // mid-commit is a wrong answer and copying one is a wrong archive, so
45
- // both modes wait rather than race.
46
- const held = lockHolder(source);
47
- if (held) {
48
- throw invalidError(`that memory is in use (pid ${held.pid}, since ${held.startedAt})`, 'wait for that run to finish, or point --memory at another directory');
49
- }
50
- }
51
45
  // Serially, and before anything runs: sixteen recursive copies of the same
52
46
  // tree at once is the one moment a batch is disk-bound, and it would be
53
47
  // spent racing itself.
@@ -335,8 +329,8 @@ export function concurrency(value) {
335
329
  * Each item's memory, made before any of them runs.
336
330
  *
337
331
  * In the copying mode every item gets its own graph to write into, so that
338
- * sixteen runs at once are sixteen private histories rather than one contended
339
- * lock. A source that is not there yet is not an error: a project declares its
332
+ * sixteen runs at once are sixteen private histories rather than one shared
333
+ * one. A source that is not there yet is not an error: a project declares its
340
334
  * memory directory and the first run makes it, so warming a cold project means
341
335
  * copying from nothing, and nothing is what each item starts with.
342
336
  */
@@ -347,7 +341,7 @@ export async function prepareMemories(items, at) {
347
341
  if (at.mode === 'copied' && at.source) {
348
342
  const mine = join(at.dir, item.id, 'memory');
349
343
  if (at.seeded) {
350
- await cp(at.source, mine, { recursive: true, filter: notLock });
344
+ await copyMemory(at.source, mine);
351
345
  }
352
346
  prepared.set(item.id, mine);
353
347
  }
@@ -360,15 +354,15 @@ export async function prepareMemories(items, at) {
360
354
  /**
361
355
  * Drops the memories nothing was committed to, and counts the ones left.
362
356
  *
363
- * A memory is its manifest and the two files beside it; a directory without
364
- * one is not a memory and `merge` refuses it by name. Leaving those behind
357
+ * A memory is its database; a directory without one is not a memory and
358
+ * `merge` refuses it by name. Leaving those behind
365
359
  * would mean the `merge` line this command prints is advice that fails, so an
366
360
  * item that learned nothing leaves nothing.
367
361
  */
368
362
  export async function keepWritten(prepared) {
369
363
  let kept = 0;
370
364
  for (const at of prepared.values()) {
371
- if (existsSync(join(at, MEMORY_MANIFEST))) {
365
+ if (isMemory(at)) {
372
366
  kept += 1;
373
367
  }
374
368
  else {
@@ -387,8 +381,6 @@ function memorySource(projectDir, override) {
387
381
  return override;
388
382
  }
389
383
  }
390
- /** The lock belongs to the run that took it, never to a copy of its memory. */
391
- const notLock = (src) => basename(src) !== '.lock';
392
384
  /**
393
385
  * The question, for the index — text whole, media named rather than repeated.
394
386
  * Every byte is already in the item's own run input file, and a combined file
@@ -1,12 +1,13 @@
1
1
  import { ENV_FILE, isBusy, Registry, sessionIds, sessionsDir, stamp } from '@zenera/engine';
2
- import { lockHolder, memoryDir, readProjectConfig } from '@zenera/neo';
3
- import { existsSync, readFileSync } from 'node:fs';
2
+ import { isMemory, MEMORY_DB, memoryDir, readProjectConfig, snapshotMemory } from '@zenera/neo';
3
+ import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
4
5
  import { isAbsolute, join, resolve } from 'node:path';
5
6
  import { ARCHIVE_FORMAT, collect, ENV_EXAMPLE, envExample, MANIFEST_FILE, safeName, writeArchive, } from "../archive.js";
6
7
  import { one, parse } from "../args.js";
7
8
  import { project as resolveProject } from "../resolve.js";
8
9
  import { ownVersion } from "../scaffold.js";
9
- import { bold, count, cyan, dim, green, bytes as human, invalidError, json, note, progress, table, usageError, warn, writeAll, } from "../term.js";
10
+ import { bold, count, cyan, dim, green, bytes as human, json, note, progress, table, usageError, warn, writeAll, } from "../term.js";
10
11
  import { validateProject } from "../validate.js";
11
12
  const USAGE = 'zen export [project] [--out <file>] [--no-vectors] [--no-memory] [--force]';
12
13
  // ---------------------------------------------------------------------------
@@ -56,8 +57,8 @@ export const pack = {
56
57
  '',
57
58
  'A project that fails `zen check` is still exported, with a warning:',
58
59
  'sending someone a broken project to ask for help is the point.',
59
- 'A memory held by a live run is refused — half a graph is not an',
60
- 'archive — and --force overrides that.',
60
+ 'Memory is copied as of one moment, so a run writing to it meanwhile',
61
+ 'cannot tear the archive.',
61
62
  ],
62
63
  run: async (ctx) => {
63
64
  const { values, positionals } = parse(ctx.args, {
@@ -74,81 +75,100 @@ export const pack = {
74
75
  const force = values.force === true;
75
76
  const vectors = values['no-vectors'] !== true;
76
77
  const memory = values['no-memory'] !== true;
77
- settled(dir, force, memory);
78
+ settled(dir, force);
78
79
  const out = destination(ctx.cwd, found.name, values.out, force);
79
80
  const collected = collect(dir, { vectors, memory });
80
- const extra = new Map();
81
- const env = join(dir, ENV_FILE);
82
- // A project's own `.env.example` is the curated one and travels as is.
83
- if (existsSync(env) && !existsSync(join(dir, ENV_EXAMPLE))) {
84
- extra.set(ENV_EXAMPLE, envExample(readFileSync(env, 'utf8')));
85
- }
86
- const healthy = await sound(dir, found.name, ctx.json);
87
- const manifest = {
88
- format: ARCHIVE_FORMAT,
89
- name: found.name,
90
- root: safeName(found.name) ?? 'project',
91
- exportedAt: new Date().toISOString(),
92
- cli: ownVersion(),
93
- vectors,
94
- memory,
95
- files: collected.files.length + extra.size,
96
- bytes: collected.bytes,
97
- };
98
- const bar = ctx.json ? undefined : progress();
99
- let done = 0;
100
- const size = await writeArchive({
101
- out,
102
- root: manifest.root,
103
- entries: collected.files,
104
- extra,
105
- manifest,
106
- onFile: (rel) => {
107
- done += 1;
108
- bar?.update(`packing ${done}/${collected.files.length} ${dim(rel)}`);
109
- },
110
- });
111
- bar?.done();
112
- if (ctx.json) {
113
- json({
114
- file: out,
115
- bytes: size,
116
- files: manifest.files,
117
- project: found.name,
118
- root: manifest.root,
81
+ const snapshot = memory ? snapshotOf(dir, collected) : undefined;
82
+ try {
83
+ const extra = new Map();
84
+ const env = join(dir, ENV_FILE);
85
+ // A project's own `.env.example` is the curated one and travels as is.
86
+ if (existsSync(env) && !existsSync(join(dir, ENV_EXAMPLE))) {
87
+ extra.set(ENV_EXAMPLE, envExample(readFileSync(env, 'utf8')));
88
+ }
89
+ const healthy = await sound(dir, found.name, ctx.json);
90
+ const manifest = {
91
+ format: ARCHIVE_FORMAT,
92
+ name: found.name,
93
+ root: safeName(found.name) ?? 'project',
94
+ exportedAt: new Date().toISOString(),
95
+ cli: ownVersion(),
119
96
  vectors,
120
97
  memory,
121
- skipped: collected.skipped,
122
- ok: healthy,
98
+ files: collected.files.length + extra.size,
99
+ bytes: collected.bytes,
100
+ };
101
+ const bar = ctx.json ? undefined : progress();
102
+ let done = 0;
103
+ const size = await writeArchive({
104
+ out,
105
+ root: manifest.root,
106
+ entries: collected.files,
107
+ extra,
108
+ manifest,
109
+ onFile: (rel) => {
110
+ done += 1;
111
+ bar?.update(`packing ${done}/${collected.files.length} ${dim(rel)}`);
112
+ },
123
113
  });
124
- return;
114
+ bar?.done();
115
+ if (ctx.json) {
116
+ json({
117
+ file: out,
118
+ bytes: size,
119
+ files: manifest.files,
120
+ project: found.name,
121
+ root: manifest.root,
122
+ vectors,
123
+ memory,
124
+ skipped: collected.skipped,
125
+ ok: healthy,
126
+ });
127
+ return;
128
+ }
129
+ report(out, size, collected, extra.size, vectors, memory);
130
+ }
131
+ finally {
132
+ if (snapshot) {
133
+ rmSync(snapshot, { recursive: true, force: true });
134
+ }
125
135
  }
126
- report(out, size, collected, extra.size, vectors, memory);
127
136
  },
128
137
  };
129
138
  // ---------------------------------------------------------------------------
130
139
  // Refusing at the right moment
131
140
  // ---------------------------------------------------------------------------
132
141
  /**
133
- * Nothing may be written while something is writing to it.
134
- *
135
- * Memory is the hard case: the store is a graph, a manifest and a vector file
136
- * that only mean anything together, and a copy taken mid-write is an archive
137
- * that opens and is wrong — which is worse than one that does not open. A run
138
- * holding a session is milder; the session is not in the archive at all, and
139
- * the only thing it can disturb is an asset the agent is editing.
142
+ * A run holding a session is the one thing worth a word: the session is not
143
+ * in the archive at all, and the only thing it can disturb is an asset the
144
+ * agent is editing.
140
145
  */
141
- function settled(dir, force, memory) {
142
- const at = memory ? memoryAt(dir) : undefined;
143
- const held = at ? lockHolder(at) : undefined;
144
- if (held && !force) {
145
- throw invalidError(`this project's memory is in use (pid ${held.pid}, since ${held.startedAt})`, 'wait for that run to finish, or: zen export --no-memory');
146
- }
146
+ function settled(dir, force) {
147
147
  const busy = sessionIds(dir).filter((id) => isBusy(join(sessionsDir(dir), id)));
148
148
  if (busy.length > 0 && !force) {
149
149
  warn(`${count(busy.length, 'session')} still running — the archive is a snapshot`);
150
150
  }
151
151
  }
152
+ /**
153
+ * Points the memory's database entry at a copy taken as of one moment, so a
154
+ * run committing while the archive is written cannot tear it. Returns the
155
+ * scratch directory holding the copy.
156
+ */
157
+ function snapshotOf(dir, collected) {
158
+ const at = memoryAt(dir);
159
+ const entry = at && collected.files.find((f) => f.abs === join(at, MEMORY_DB));
160
+ if (!at || !entry || !isMemory(at)) {
161
+ return undefined;
162
+ }
163
+ const scratch = mkdtempSync(join(tmpdir(), 'zen-export-'));
164
+ const file = join(scratch, MEMORY_DB);
165
+ snapshotMemory(at, file);
166
+ const bytes = statSync(file).size;
167
+ collected.bytes += bytes - entry.bytes;
168
+ entry.abs = file;
169
+ entry.bytes = bytes;
170
+ return scratch;
171
+ }
152
172
  /**
153
173
  * The configured memory directory, or nothing when the project will not load —
154
174
  * which is a project this command exports anyway, so it cannot be an error here.
@@ -1,9 +1,9 @@
1
1
  import { display, KeyStore, listRuns, listSessions, loadProjectEnv, newestRun, readRunMeta, requireSession, runPaths, runPathsAt, sessionIds, sessionPaths, } from '@zenera/engine';
2
- import { assertState, buildRunReport, FilePayloadStore, memoryDir, MemoryStore, PayloadResolver, projectRegistry, readProjectConfig, renderReportHtml, SANDBOX_MOUNT, text, } from '@zenera/neo';
2
+ import { assertState, buildRunReport, FilePayloadStore, isMemory, memoryDir, MemoryStore, PayloadResolver, projectRegistry, readProjectConfig, renderReportHtml, SANDBOX_MOUNT, text, } from '@zenera/neo';
3
3
  import { spawn } from 'node:child_process';
4
4
  import { existsSync } from 'node:fs';
5
5
  import { readFile, writeFile } from 'node:fs/promises';
6
- import { join, resolve } from 'node:path';
6
+ import { resolve } from 'node:path';
7
7
  import { pathToFileURL } from 'node:url';
8
8
  import { parse } from "../args.js";
9
9
  import { buildDiagnostic, parseRecordedRequest, pickModel } from "../ask.js";
@@ -684,11 +684,11 @@ async function readState(run) {
684
684
  */
685
685
  async function memory(dir, run, override, cwd) {
686
686
  const at = override ? resolve(cwd, override) : memoryPath(dir, await readRunMeta(run));
687
- if (!at || !existsSync(join(at, 'manifest.json'))) {
687
+ if (!at || !isMemory(at)) {
688
688
  return undefined;
689
689
  }
690
690
  try {
691
- return await MemoryStore.open(at, { lock: false });
691
+ return await MemoryStore.open(at, { readOnly: true });
692
692
  }
693
693
  catch {
694
694
  return undefined;
@@ -709,7 +709,7 @@ function memoryPath(dir, meta) {
709
709
  return undefined;
710
710
  }
711
711
  }
712
- return at && existsSync(join(at, 'manifest.json')) ? at : undefined;
712
+ return at && isMemory(at) ? at : undefined;
713
713
  }
714
714
  /**
715
715
  * Handing a URL to the platform opener. `spawn` without a shell, so the path
@@ -1,5 +1,5 @@
1
1
  import { KeyStore, loadProjectEnv } from '@zenera/engine';
2
- import { ALL_AGENTS, buildMemoryReport, createEmbedder, diffMemories, GREP_FIELDS, grepMemory, hostPath, memoryDir, MemoryError, MemoryIndex, MemoryStore, MergeConflicts, mergeMemories, readProjectConfig, renderMemoryHtml, renderRecollection, } from '@zenera/neo';
2
+ import { ALL_AGENTS, buildMemoryReport, createEmbedder, diffMemories, GREP_FIELDS, grepMemory, hostPath, isMemory, LEGACY_GRAPH_FILE, MEMORY_DB, memoryDir, MemoryError, MemoryIndex, MemoryStore, MergeConflicts, mergeMemories, migrateMemory, readProjectConfig, renderMemoryHtml, renderRecollection, } from '@zenera/neo';
3
3
  import { spawn } from 'node:child_process';
4
4
  import { existsSync, readFileSync } from 'node:fs';
5
5
  import { writeFile } from 'node:fs/promises';
@@ -7,8 +7,19 @@ import { basename, isAbsolute, join, resolve } from 'node:path';
7
7
  import { parse } from "../args.js";
8
8
  import { project as resolveProject } from "../resolve.js";
9
9
  import { ago, bold, bytes, CliError, confirm, count, cyan, dim, EXIT, green, isInteractive, json, note, plain, table, usageError, write, writeAll, yellow, } from "../term.js";
10
- const USAGE = 'zen memory [stats|ls|search|grep|show|diff|export|merge|forget] [args] [options]';
11
- const SUBCOMMANDS = ['stats', 'ls', 'search', 'grep', 'show', 'diff', 'export', 'merge', 'forget'];
10
+ const USAGE = 'zen memory [stats|ls|search|grep|show|diff|export|merge|forget|migrate] [args] [options]';
11
+ const SUBCOMMANDS = [
12
+ 'stats',
13
+ 'ls',
14
+ 'search',
15
+ 'grep',
16
+ 'show',
17
+ 'diff',
18
+ 'export',
19
+ 'merge',
20
+ 'forget',
21
+ 'migrate',
22
+ ];
12
23
  /** Enough to see the shape of it; the rest is a number. */
13
24
  const LISTED = 30;
14
25
  // ---------------------------------------------------------------------------
@@ -45,6 +56,7 @@ export const memory = {
45
56
  ' export [file] The whole graph as one HTML page.',
46
57
  ' merge <dir...> Fold other memories into this one.',
47
58
  ' forget <id...> Remove nodes, their vectors and their files.',
59
+ ' migrate Convert a version 1 memory (graph.json) to memory.db.',
48
60
  '',
49
61
  ' --project <name|dir> Which project. Defaults to the one you are in.',
50
62
  ' --dir <dir> Read this memory directory instead of the project’s.',
@@ -95,12 +107,11 @@ export const memory = {
95
107
  '',
96
108
  ' zen memory grep ‘staging.example.com’ --in metadata --in file',
97
109
  '',
98
- 'Nothing that only reads takes the directory lock, so every subcommand',
99
- 'here but `merge` and `forget` works on a memory a run is writing, and on',
100
- 'the read-only /memory mount inside a sandbox.',
110
+ 'Every subcommand reads one consistent snapshot, so all of them work on',
111
+ 'a memory a run is writing to, and runs keep writing while they do.',
101
112
  '',
102
- '`merge` is for warming a memory in parallel. The lock is per directory,',
103
- 'so N runs write N memories; this folds them back into one:',
113
+ '`merge` is for warming a memory in parallel. `zen run batch` gives each',
114
+ 'item its own copy, so N runs write N memories; this folds them back:',
104
115
  '',
105
116
  ' zen memory merge <batch-dir>/*/memory',
106
117
  '',
@@ -142,14 +153,15 @@ export const memory = {
142
153
  throw usageError(`unknown subcommand: ${what}`, USAGE);
143
154
  }
144
155
  const rest = positionals.slice(1);
156
+ if (what === 'migrate') {
157
+ return await migrate(await locate(ctx.cwd, values.project, values.dir), ctx.json);
158
+ }
145
159
  // `merge` is the one subcommand that may write a memory into existence;
146
- // every other one is an inspector and a missing manifest is a mistake.
147
- // And only the two that write take the lock: the moments a reader is
148
- // most wanted are while a run is writing and against the read-only
149
- // /memory mount, in both of which claiming it fails.
160
+ // every other one is an inspector and a missing database is a mistake.
161
+ // Only the two that write open it for writing.
150
162
  const opened = await open(ctx.cwd, values.project, values.dir, {
151
163
  create: what === 'merge',
152
- lock: what === 'merge' || what === 'forget',
164
+ write: what === 'merge' || what === 'forget',
153
165
  });
154
166
  try {
155
167
  switch (what) {
@@ -191,13 +203,28 @@ export const memory = {
191
203
  * `create` drops the requirement that anything be there yet, for `merge`,
192
204
  * which has somewhere to put what it reads even when the destination is a name
193
205
  * nothing has written to.
194
- *
195
- * `lock` is off for a read that must not fail on a busy or read-only memory.
196
- * The lock exists to stop two writers losing each other's edges; a reader that
197
- * took it would only be refusing itself.
198
206
  */
199
207
  async function open(cwd, want, at, opts = {}) {
200
- const { create = false, lock = true } = opts;
208
+ const { create = false, write = false } = opts;
209
+ const found = await locate(cwd, want, at);
210
+ // A version 1 directory gets past this so that opening it says how to convert it.
211
+ if (!create && !isMemory(found.dir) && !existsSync(join(found.dir, LEGACY_GRAPH_FILE))) {
212
+ throw found.at
213
+ ? usageError(`${found.project} has a memory configured but nothing in it yet`, 'it is written the first time an agent commits something')
214
+ : usageError(`${found.dir} is not a memory`, `no ${MEMORY_DB} in it`);
215
+ }
216
+ try {
217
+ return { ...found, store: await MemoryStore.open(found.dir, { readOnly: !write }) };
218
+ }
219
+ catch (err) {
220
+ if (err instanceof MemoryError) {
221
+ throw new CliError(err.message, EXIT.invalid, err.hint);
222
+ }
223
+ throw err;
224
+ }
225
+ }
226
+ /** Which memory directory a command means, without opening it. */
227
+ async function locate(cwd, want, at) {
201
228
  // Standing inside a memory (a merged or batch copy) means that memory, not
202
229
  // the project's own one a few directories up.
203
230
  if (!at && !want && isMemoryDir(cwd)) {
@@ -205,10 +232,7 @@ async function open(cwd, want, at, opts = {}) {
205
232
  }
206
233
  if (at) {
207
234
  const dir = resolve(cwd, at);
208
- if (!create && !existsSync(join(dir, 'manifest.json'))) {
209
- throw usageError(`${dir} is not a memory`, 'no manifest.json in it');
210
- }
211
- return { store: await MemoryStore.open(dir, { lock }), dir, project: basename(dir) };
235
+ return { dir, project: basename(dir) };
212
236
  }
213
237
  const project = await resolveProject({ cwd, project: want });
214
238
  const { config } = readProjectConfig(project.dir);
@@ -216,19 +240,14 @@ async function open(cwd, want, at, opts = {}) {
216
240
  if (!dir) {
217
241
  throw usageError(`${project.name} has no memory`, 'give an agent `memory: true` in agents.yaml, or add a `memory:` block');
218
242
  }
219
- if (!create && !existsSync(join(dir, 'manifest.json'))) {
220
- throw usageError(`${project.name} has a memory configured but nothing in it yet`, 'it is written the first time an agent commits something');
221
- }
222
- return {
223
- store: await MemoryStore.open(dir, { lock }),
224
- dir,
225
- project: project.name,
226
- at: { root: project.dir, config },
227
- };
243
+ return { dir, project: project.name, at: { root: project.dir, config } };
228
244
  }
229
245
  /** A rag index also has a manifest and a graph.json; only a memory's manifest counts nodes and edges. */
230
246
  function isMemoryDir(dir) {
231
- if (!existsSync(join(dir, 'graph.json'))) {
247
+ if (isMemory(dir)) {
248
+ return true;
249
+ }
250
+ if (!existsSync(join(dir, LEGACY_GRAPH_FILE))) {
232
251
  return false;
233
252
  }
234
253
  try {
@@ -690,10 +709,10 @@ async function diff(o, rest, cwd, asJson) {
690
709
  throw usageError('diff takes exactly one base memory', 'zen memory diff <base> [--dir <dir>]');
691
710
  }
692
711
  const at = resolve(cwd, rest[0]);
693
- if (!existsSync(join(at, 'manifest.json'))) {
694
- throw usageError(`${at} is not a memory`, 'no manifest.json in it');
712
+ if (!isMemory(at)) {
713
+ throw usageError(`${at} is not a memory`, `no ${MEMORY_DB} in it`);
695
714
  }
696
- const base = await MemoryStore.open(at, { lock: false });
715
+ const base = await MemoryStore.open(at, { readOnly: true });
697
716
  try {
698
717
  const d = diffMemories(base, o.store);
699
718
  const mine = (n) => onHost(o, n);
@@ -802,9 +821,9 @@ function reveal(target) {
802
821
  // merge
803
822
  // ---------------------------------------------------------------------------
804
823
  /**
805
- * Warming a memory is parallel work, and the lock is per directory, so N runs
806
- * produce N memories rather than one. This is the other half of that: it folds
807
- * them back together, offline and without a model.
824
+ * Warming a memory is parallel work, and a batch gives every item its own
825
+ * copy, so N runs produce N memories rather than one. This is the other half of
826
+ * that: it folds them back together, offline and without a model.
808
827
  *
809
828
  * Divergence refuses rather than guesses. Two copies of the same memory that
810
829
  * disagree are a question about which piece of work was right, and answering
@@ -925,6 +944,28 @@ async function forget(o, ids, flags, asJson) {
925
944
  }
926
945
  }
927
946
  // ---------------------------------------------------------------------------
947
+ // migrate
948
+ // ---------------------------------------------------------------------------
949
+ /** Once per memory: the version 1 files are kept in `v1/`, not deleted. */
950
+ async function migrate(o, asJson) {
951
+ let report;
952
+ try {
953
+ report = await migrateMemory(o.dir);
954
+ }
955
+ catch (err) {
956
+ if (err instanceof MemoryError) {
957
+ throw new CliError(err.message, EXIT.failed, err.hint);
958
+ }
959
+ throw err;
960
+ }
961
+ if (asJson) {
962
+ json(report);
963
+ return;
964
+ }
965
+ note(`${green('migrated')} ${o.dir} ${dim(`· ${count(report.nodes, 'node')}, ${count(report.edges, 'edge')}, ` +
966
+ `${count(report.vectors, 'vector')} · the old files are in ${report.legacy}`)}`);
967
+ }
968
+ // ---------------------------------------------------------------------------
928
969
  // Shared
929
970
  // ---------------------------------------------------------------------------
930
971
  function clip(text, n) {
@@ -1,6 +1,6 @@
1
1
  import type { Case } from './dataset/types.ts';
2
2
  import type { Run } from './train.ts';
3
- import { type Tuning } from './tuning.ts';
3
+ import type { Tuning } from './tuning.ts';
4
4
  export interface Submission {
5
5
  /** `<case>@r<rev>` */
6
6
  key: string;
@@ -1,9 +1,9 @@
1
- import { appendFileSync, cpSync, existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
1
+ import { isMemory, MemoryStore } from '@zenera/neo';
2
+ import { appendFileSync, cpSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
2
3
  import { basename, join } from 'node:path';
3
4
  import { DatasetStore } from "./dataset/store.js";
4
5
  import { errorIn, sizeOf } from "./failure.js";
5
6
  import { writeFeedback } from "./report.js";
6
- import { readJson } from "./tuning.js";
7
7
  function rows(file) {
8
8
  try {
9
9
  return readFileSync(file, 'utf8')
@@ -15,6 +15,24 @@ function rows(file) {
15
15
  return [];
16
16
  }
17
17
  }
18
+ /** How big a memory is, or nothing when there is no memory there to open. */
19
+ async function sizeOfMemory(dir) {
20
+ if (!isMemory(dir)) {
21
+ return undefined;
22
+ }
23
+ try {
24
+ const store = await MemoryStore.open(dir, { readOnly: true });
25
+ try {
26
+ return { nodes: store.graph.order, edges: store.graph.size };
27
+ }
28
+ finally {
29
+ store.release();
30
+ }
31
+ }
32
+ catch {
33
+ return undefined;
34
+ }
35
+ }
18
36
  export class Memories {
19
37
  #t;
20
38
  #chain = Promise.resolve();
@@ -47,7 +65,7 @@ export class Memories {
47
65
  return;
48
66
  }
49
67
  const dir = join(this.dir, 'submitted', key);
50
- const empty = !existsSync(join(run.memory, 'manifest.json'));
68
+ const empty = !isMemory(run.memory);
51
69
  rmSync(dir, { recursive: true, force: true });
52
70
  if (!empty) {
53
71
  cpSync(run.memory, dir, {
@@ -116,7 +134,7 @@ export class Memories {
116
134
  .finally(() => {
117
135
  this.merging = undefined;
118
136
  });
119
- const manifest = readJson(join(target, 'manifest.json'));
137
+ const size = await sizeOfMemory(target);
120
138
  const row = {
121
139
  n,
122
140
  name,
@@ -125,14 +143,13 @@ export class Memories {
125
143
  log,
126
144
  includes: [...(last?.includes ?? []), ...fresh.map((s) => s.key)],
127
145
  added: fresh.map((s) => s.key),
128
- ok: res.code === 0 && manifest !== undefined,
129
- ...(manifest?.nodes !== undefined ? { nodes: manifest.nodes } : {}),
130
- ...(manifest?.edges !== undefined ? { edges: manifest.edges } : {}),
146
+ ok: res.code === 0 && size !== undefined,
147
+ ...(size ? { nodes: size.nodes, edges: size.edges } : {}),
131
148
  };
132
149
  appendFileSync(join(this.dir, 'merges.jsonl'), `${JSON.stringify(row)}\n`);
133
150
  if (!row.ok) {
134
151
  const e = errorIn(log, from);
135
- this.#t.error(`memory ${name}`, e.message ?? 'the merge wrote no manifest', e.log);
152
+ this.#t.error(`memory ${name}`, e.message ?? 'the merge wrote no memory', e.log);
136
153
  }
137
154
  const store = DatasetStore.open(this.#t.root);
138
155
  for (const s of fresh) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zenera/cli",
3
- "version": "1.1.54",
3
+ "version": "1.1.55",
4
4
  "description": "Command-line front end for @zenera/neo: agentic projects you can run, share and commit.",
5
5
  "keywords": [
6
6
  "agents",
@@ -54,9 +54,9 @@
54
54
  "@google/genai": "^2.30.0",
55
55
  "@inkjs/ui": "^2.0.0",
56
56
  "@openrouter/sdk": "^1.4.25",
57
- "@zenera/engine": "^1.1.54",
58
- "@zenera/neo": "^1.1.54",
59
- "@zenera/view": "^1.1.54",
57
+ "@zenera/engine": "^1.1.55",
58
+ "@zenera/neo": "^1.1.55",
59
+ "@zenera/view": "^1.1.55",
60
60
  "google-auth-library": "^10.0.0",
61
61
  "ink": "^7.1.1",
62
62
  "openai": "^6.0.0",
@@ -2089,7 +2089,7 @@ candidates; these are the judgements to make about each one)**
2089
2089
  | Fails only on genuinely hard cases | Promote that agent's tier, or split the hard path out |
2090
2090
  | Shows no reasoning while it works | Turn summaries on for that model - §7.6 |
2091
2091
  | Forgets across conversations | Continue the session rather than starting a new one |
2092
- | Greps `/memory` or reads `graph.json` | `agents/memory-instructions.md` is missing the block - §5.3 |
2092
+ | Greps `/memory` or queries `memory.db` | `agents/memory-instructions.md` is missing the block - §5.3 |
2093
2093
  | Recalls a note it cannot check or continue | Same block: it is what requires provenance on every node - §5.3 |
2094
2094
  | Breaks at load with a named path | Read the message - it names the exact key |
2095
2095
 
@@ -26,7 +26,7 @@ zen key <ls|add|use|check|rm|show|env> [ref] [options]
26
26
  zen models <providers|ls|search|show|test|browse> [ref] [options]
27
27
  zen check [name|dir] [--project <name|dir>] [--no-sandbox] [--no-models] [--strict] [--quiet]
28
28
  zen inspect [report|graph|node|ask] [run] [--dir <run dir>] [--part <name>] [--full] [--open]
29
- zen memory [stats|ls|search|grep|show|export|merge|forget] [args] [options]
29
+ zen memory [stats|ls|search|grep|show|export|merge|forget|migrate] [args] [options]
30
30
  zen export [project] [--out <file>] [--no-vectors] [--no-memory] [--force]
31
31
  zen import <file.zip> [dir] [--name <name>] [--force] [--no-register]
32
32
  zen sandbox [status|up|pull|clean|disk] [options]
@@ -22,7 +22,7 @@ one silently replaced; an `--out` that already exists is a usage error until
22
22
  | `--out <file>` | Where the archive goes |
23
23
  | `--no-vectors` | Leave out `assets/**/lance/` - much smaller, needs a restore |
24
24
  | `--no-memory` | Leave out `memory/` entirely |
25
- | `--force` | Overwrite the target, and export past a held memory lock |
25
+ | `--force` | Overwrite the target |
26
26
 
27
27
  ### What travels
28
28
 
@@ -44,8 +44,10 @@ knows which credentials to supply without being handed any.
44
44
 
45
45
  This is the decision the command is built around. A rag index without its
46
46
  `lance/` tree looks built and cannot search, and memory has no fallback at all:
47
- a graph without `vectors.f32` recalls by term overlap until every node is
48
- written again. So the default archive works when it is opened.
47
+ a memory without its vectors recalls by term overlap until every node is
48
+ written again. So the default archive works when it is opened. The memory
49
+ travels as a snapshot of its database taken at one moment, so a run writing to
50
+ it meanwhile cannot tear the archive.
49
51
 
50
52
  `--no-vectors` makes a much smaller one for someone who will run
51
53
  `zen rag <subject> restore` on arrival. The manifest records the choice and
@@ -53,9 +55,8 @@ written again. So the default archive works when it is opened.
53
55
 
54
56
  ### What it refuses
55
57
 
56
- Only one thing: memory held by a live run, because a graph copied mid-write is
57
- an archive that opens and is wrong. `--force` overrides it, and
58
- `--no-memory` sidesteps it.
58
+ Nothing for being busy: memory is copied as of one moment, so a run writing
59
+ to it meanwhile cannot tear the archive.
59
60
 
60
61
  A project that fails `zen check` is exported anyway, with a warning. Sending
61
62
  someone a broken project to ask for help is a legitimate reason to export one.
@@ -1,7 +1,7 @@
1
1
  # Memory - `zen memory`
2
2
 
3
3
  ```
4
- zen memory [stats|ls|search|grep|show|export|merge|forget] [args] [options]
4
+ zen memory [stats|ls|search|grep|show|export|merge|forget|migrate] [args] [options]
5
5
  ```
6
6
 
7
7
  Alias: `mem`.
@@ -29,9 +29,10 @@ skill.
29
29
  | `zen memory export [f]` | The whole graph as one HTML page |
30
30
  | `zen memory merge <dir…>` | Fold other memories into this one |
31
31
  | `zen memory forget <id…>` | Remove nodes, their vectors and their files |
32
+ | `zen memory migrate` | Convert a version 1 memory (`graph.json`) once |
32
33
 
33
34
  `ls` cuts the text to the terminal's width; piped, or run by an agent, it prints
34
- all of it. Never read `graph.json` directly - `ls --json` is the same nodes in a
35
+ all of it. Never query `memory.db` directly - `ls --json` is the same nodes in a
35
36
  shape that does not change under you.
36
37
 
37
38
  | Flag | Meaning |
@@ -120,22 +121,21 @@ zen memory diff <candidate> --dir <batch-dir>/<id>/memory
120
121
  - **used** - nodes `memory_load` returned, and how often: what the run read.
121
122
  - **removed**, and new `SUPERSEDES` edges.
122
123
 
123
- It reads both sides without the lock, so it works on a memory a run is writing.
124
+ It reads one consistent snapshot of each side, so it works on a memory a run is
125
+ writing.
124
126
 
125
127
  Superseded nodes are left out unless you ask: `--all` includes them marked, and
126
128
  `--stale` narrows to them alone.
127
129
 
128
- Nothing that only reads takes the directory lock, so this and every other
129
- subcommand but `merge` and `forget` works while a run is writing the memory, and
130
- against the read-only `/memory` mount inside a sandbox.
130
+ Every subcommand reads one consistent snapshot, so all of them work while a run
131
+ is writing the memory - and the run keeps writing while they do.
131
132
 
132
133
  ## A graph that is not the project's
133
134
 
134
135
  `--dir` opens a memory directory as it stands, and skips project resolution
135
136
  entirely: there need be no `agents.yaml` anywhere above it. That is what to use
136
- for a graph a run was pointed at with `zen run --memory <dir>`, and for a copy
137
- taken out of a running session - though for reading a live memory, `grep` needs
138
- no copy at all.
137
+ for a graph a run was pointed at with `zen run --memory <dir>`, and for the one
138
+ a running session is writing to - no copy needed.
139
139
 
140
140
  ```
141
141
  zen run --memory .tmp/mem "…" remember into .tmp/mem for this run
@@ -182,8 +182,9 @@ working list and detail view.
182
182
 
183
183
  ## Merging
184
184
 
185
- The lock is per directory, so two runs cannot warm the same memory at once.
186
- They each warm their own, and `merge` puts the results back together:
185
+ Several runs may write one memory at once - each write is a transaction - but a
186
+ warmup should not share one: runs learning together see each other's commits
187
+ mid-round. They each warm their own, and `merge` puts the results back together:
187
188
 
188
189
  ```sh
189
190
  zen memory merge .tmp/warmup-*/batch/*/memory into the project’s
@@ -194,8 +195,8 @@ zen memory merge <batch-dir>/*/memory after `zen run batch`
194
195
  `zen run batch` is the fan-out with the bookkeeping done for you: each item
195
196
  gets its own copy of the memory, the project's is left alone, and the summary
196
197
  prints the `merge` line. A batch that is only asking should say
197
- `--memory-read-only` instead — nobody writes, so nobody needs the lock, and
198
- every item recalls from the one graph.
198
+ `--memory-read-only` instead — nobody writes, so nothing changes under anyone,
199
+ and every item recalls from the one graph.
199
200
 
200
201
  Sources are positional and the target is `--dir`, or the project you are in —
201
202
  the same shape as everywhere else here. The shell expands the glob, so a
@@ -244,10 +244,10 @@ well.
244
244
  A memory is a locked directory, so sixteen runs cannot hold one. Which leaves
245
245
  two honest arrangements, and the flag picks between them:
246
246
 
247
- | Mode | What happens |
248
- | -------------------- | ------------------------------------------------------------------ |
249
- | `--memory-read-only` | Every item recalls from the one graph. Nothing is written, no lock |
250
- | default | Each item gets a copy under `<batch-dir>/<id>/memory` |
247
+ | Mode | What happens |
248
+ | -------------------- | --------------------------------------------------------- |
249
+ | `--memory-read-only` | Every item recalls from the one graph. Nothing is written |
250
+ | default | Each item gets a copy under `<batch-dir>/<id>/memory` |
251
251
 
252
252
  In the copying mode the project's own memory is never touched. Fold what the
253
253
  items learned back in afterwards, having read it:
@@ -265,7 +265,7 @@ source that does not exist yet is not an error in the copying mode: a project
265
265
  declares its memory directory and the first run makes it, so every item simply
266
266
  starts from an empty graph. That is how a cold project is warmed, and pointing
267
267
  `--memory` at a directory that is not there is how you ask for it deliberately.
268
- A batch refuses to start while another run holds that memory's lock.
268
+ Each copy is the source as of one moment, so a run still writing it is fine.
269
269
 
270
270
  `--memory-read-only` works on a single `zen run` too. It is how you ask a
271
271
  question of what the agents know without changing what they know.
@@ -843,7 +843,7 @@ last thing this phase does — read the trajectories before the numbers, or the
843
843
  numbers decide what you look at.
844
844
 
845
845
  **Every question about a run has a command.** Never open `output.json`,
846
- `batch.json`, `state.json` or a memory's `graph.json` with `node -e`,
846
+ `batch.json`, `state.json` or a memory's `memory.db` with `node -e`,
847
847
  `python -c` or `jq` — the formats are the CLI's, and a guess at one costs a
848
848
  probe call to find out it was wrong.
849
849
 
@@ -14,9 +14,9 @@
14
14
  //
15
15
  // When a with-memory run passes, `checkpoint <run>` makes the candidate the last
16
16
  // good memory: it renames the directory and only then repoints
17
- // finetune/memory/last-good.json at it. `zen memory merge` writes its files one
18
- // after another, so a merge killed half-way can leave a graph whose files
19
- // disagree - but only ever a candidate, never the one the pointer names. Stop the
17
+ // finetune/memory/last-good.json at it. A merge killed half-way leaves the
18
+ // candidate it was writing without that merge, and never touches the one the
19
+ // pointer names. Stop the
20
20
  // tuning at any moment and `memory.mjs path` still names a usable graph.
21
21
  //
22
22
  // Needs `zen` on PATH. Run it from anywhere; it finds the project root from its
@@ -34,6 +34,7 @@ import {
34
34
  writeFileSync,
35
35
  } from 'node:fs';
36
36
  import { dirname, join, resolve } from 'node:path';
37
+ import { DatabaseSync } from 'node:sqlite';
37
38
  import { fileURLToPath } from 'node:url';
38
39
 
39
40
  const NAME = 'memory.mjs';
@@ -81,7 +82,17 @@ function writeAtomic(path, value) {
81
82
  }
82
83
 
83
84
  /** @param {string} dir @returns {number} */
84
- const nodesIn = (dir) => Number(json(join(dir, 'manifest.json'))?.nodes) || 0;
85
+ function nodesIn(dir) {
86
+ if (!existsSync(join(dir, 'memory.db'))) {
87
+ return 0;
88
+ }
89
+ const db = new DatabaseSync(join(dir, 'memory.db'), { readOnly: true });
90
+ try {
91
+ return Number(db.prepare('SELECT count(*) AS n FROM nodes').get()?.n) || 0;
92
+ } finally {
93
+ db.close();
94
+ }
95
+ }
85
96
 
86
97
  /** @param {string} run */
87
98
  function passed(run) {
@@ -178,17 +189,20 @@ if (command === 'candidate') {
178
189
  die(`batch ${batch} is already in the last good memory`);
179
190
  }
180
191
 
181
- // Only case memories with a manifest: a case that committed nothing has none.
192
+ // Only case memories with a database: a case that committed nothing has none.
182
193
  const dir = join(RUNS, arg, 'batch');
183
194
  const sources = (existsSync(dir) ? readdirSync(dir, { withFileTypes: true }) : [])
184
- .filter((e) => e.isDirectory() && existsSync(join(dir, e.name, 'memory', 'manifest.json')))
195
+ .filter((e) => e.isDirectory() && existsSync(join(dir, e.name, 'memory', 'memory.db')))
185
196
  .map((e) => join(dir, e.name, 'memory'));
186
197
 
187
198
  const target = join(ROOT, `candidate-batch${pad}`);
188
199
  rmSync(target, { recursive: true, force: true });
189
200
  mkdirSync(ROOT, { recursive: true });
190
201
  if (pointer && existsSync(pointer.dir)) {
191
- cpSync(pointer.dir, target, { recursive: true, filter: (src) => !src.endsWith('/.lock') });
202
+ cpSync(pointer.dir, target, {
203
+ recursive: true,
204
+ filter: (src) => !/\/(\.lock|memory\.db-(wal|shm))$/.test(src),
205
+ });
192
206
  } else {
193
207
  mkdirSync(target, { recursive: true });
194
208
  }
@@ -368,7 +368,7 @@ function memory(dir) {
368
368
  };
369
369
  }
370
370
  if (mode === 'copied') {
371
- return source && existsSync(join(source, 'graph.json'))
371
+ return source && existsSync(join(source, 'memory.db'))
372
372
  ? {
373
373
  kind: 'with memory',
374
374
  line: `WITH MEMORY — each case got its own copy of an existing graph (${source})`,
@@ -593,7 +593,7 @@ if (mode === 'index') {
593
593
  for (const { id } of roster(batch)) {
594
594
  const dir = join(batch, id, 'memory');
595
595
  say('');
596
- if (!existsSync(join(dir, 'manifest.json'))) {
596
+ if (!existsSync(join(dir, 'memory.db'))) {
597
597
  say(`-- ${id} committed nothing`);
598
598
  continue;
599
599
  }
@@ -218,17 +218,17 @@ below.
218
218
 
219
219
  ```
220
220
  <project>/memory/
221
- ├── manifest.json written LAST - a half-written memory reads as empty
222
- ├── graph.json nodes and edges, parsed whole on open
223
- ├── vectors.f32 raw little-endian float32, a quarter the size of JSON
224
- ├── vectors.json the ids those vectors belong to
225
- ├── files/ remembered bytes, one per node that has any
226
- └── .lock held while a run is writing; a dead pid's lock is stale
221
+ ├── memory.db SQLite: nodes, edges and vectors; every write one transaction
222
+ ├── memory.db-wal the write-ahead log while runs have it open; folded in on close
223
+ └── files/ remembered bytes, one per node that has any
227
224
  ```
228
225
 
229
- It is committed with the project - everything but `.lock`, which is runtime
230
- state. The directory is mounted **read-only** at `/memory` in the agent's
231
- namespace.
226
+ Several runs may read and write one memory at once, and a run killed mid-write
227
+ leaves the last commit intact. It is committed with the project - everything
228
+ but `memory.db-wal`/`memory.db-shm`, which are runtime state. Only `files/` is
229
+ mounted, **read-only**, at `/memory` in the agent's namespace. A memory from an
230
+ older `zen` (`graph.json`, `vectors.f32`) is refused until converted once with
231
+ `zen memory migrate`.
232
232
 
233
233
  ## Designing a memory strategy
234
234
 
@@ -653,7 +653,7 @@ can act on.
653
653
  ## Inspecting and repairing it
654
654
 
655
655
  ```
656
- zen memory [stats|ls|search|grep|show|export|merge|forget] [args] [options]
656
+ zen memory [stats|ls|search|grep|show|export|merge|forget|migrate] [args] [options]
657
657
  ```
658
658
 
659
659
  `zen memory export --open` is the one to reach for: one self-contained HTML
@@ -683,22 +683,19 @@ memory that is missing from a memory that is merely ranked sixth.
683
683
  | Fold parallel warmup graphs into one | `zen memory merge <dir...>` |
684
684
  | That should never have been written down | `zen memory forget <id>` |
685
685
 
686
- Never read a memory's `graph.json` or `manifest.json` with code: every question
686
+ Never query a memory's `memory.db` with code: every question
687
687
  above has a command, and `--json` on any of them is the stable shape.
688
688
 
689
689
  The directory is not fixed. `zen run --memory <dir>` sends one run's memory
690
690
  somewhere else - a scratch graph for a trial, one per branch, or a shared one
691
691
  outside the repository - and `zen memory --dir <dir>` reads any such directory
692
- with no project around it. Together they are also how you read a graph while a
693
- run holds its `.lock`: copy the directory, delete the copy's `.lock`, and point
694
- `--dir` at the copy. `grep` needs none of that - it declines the lock, so it
695
- reads a memory a run is writing, and the read-only `/memory` mount as well.
692
+ with no project around it, including one a run is writing to right now.
696
693
 
697
694
  `zen run batch` is where parallel graphs usually come from now. Each item gets
698
695
  its own copy to write into and the summary prints the `merge` line; a batch
699
696
  that is only asking says `--memory-read-only` instead, and then every item
700
- recalls from the one graph, because nothing writes and so nothing needs the
701
- lock.
697
+ recalls from the one graph, because nothing writes and so nothing changes under
698
+ anyone.
702
699
 
703
700
  `zen inspect` answers the other half: a run report shows the recollection block
704
701
  exactly as the model received it, which is how you tell "memory had nothing"
@@ -777,11 +774,11 @@ agents:
777
774
  | Recall finds a memory only when reworded | No embedder. `zen memory stats` says `embedding none` |
778
775
  | A memory is in the graph but never comes back | Ask `zen memory search` for it: a score under `0.15` is dropped as noise, and `--audience <label>` shows whether a mask hid it |
779
776
  | `zen memory search` says `ranked by term overlap` | It could not build the project's embedder - no credential, or the graph holds no vectors. That order is not the one a run gets |
780
- | Recall finds nothing after changing the embedder | Refused rather than mixed - a manifest records the model. Change it back, or start a new memory |
777
+ | Recall finds nothing after changing the embedder | Refused rather than mixed - the memory records the model. Change it back, or start a new memory |
781
778
  | Vectors fewer than nodes | Some nodes were committed with no embedder; they are only reachable by term overlap |
782
779
  | The graph fills with restated requests | The commit rule is not in a prompt or skill. State the "would a later run redo this" test |
783
780
  | Runs do real work and the graph stays empty | The agent is bound `read`, or nothing names the moments: empty recall then work, before an answer, a handoff or a fork's return |
784
- | An agent greps `/memory` or reads `graph.json` | The house-rules block is missing from `agents/memory-instructions.md` - the system prompt never forbids it |
781
+ | An agent greps `/memory` or queries `memory.db` | The house-rules block is missing from `agents/memory-instructions.md` - the system prompt never forbids it |
785
782
  | A recalled fact cannot be checked or continued | Nodes were committed with no provenance. The block's "say where it came from" rule is what prevents it |
786
783
  | Recall returns pointers and the run re-reads it all | Content was committed as `text` alone. A node's text describes and locates; the content belongs in a file |
787
784
  | A wrong memory keeps coming back | It was edited instead of superseded, or superseded in the wrong direction - the **new** node is the source |
@@ -37,8 +37,8 @@ directory of memories comes out, and `zen memory merge` folds them into one.
37
37
 
38
38
  ## What the Command Already Does
39
39
 
40
- Warmup used to be a script's problem: a memory per run because the lock is per
41
- directory, a fresh workspace per run, a bounded number of background jobs, and
40
+ Warmup used to be a script's problem: a memory per run so that no run learns
41
+ from another mid-round, a fresh workspace per run, a bounded number of background jobs, and
42
42
  a merge at the end. `zen run batch` is that fan-out made into a command, so
43
43
  none of it is the script's problem any more.
44
44
 
@@ -5,10 +5,12 @@ sessions/
5
5
  # The same, one level up: a batch's workspaces, memory copies and answers.
6
6
  batches/
7
7
 
8
- # Memory is worth keeping: `graph.json`, `files/` and the vectors are what the
9
- # agents learned. The vectors are binary, but nothing rebuilds them from the
10
- # graph, so a clone without them recalls by term overlap until every node is
11
- # written again. Only the lock is runtime state.
8
+ # Memory is worth keeping: `memory.db` and `files/` are what the agents
9
+ # learned, vectors included, and nothing rebuilds them. The database is folded
10
+ # into that one file whenever the last run using it closes; the write-ahead
11
+ # log beside it is runtime state, as is a version 1 memory's lock.
12
+ memory/memory.db-wal
13
+ memory/memory.db-shm
12
14
  memory/.lock
13
15
 
14
16
  # Scratch, inside the workspace so the sandbox can reach it.