@zenera/cli 1.1.54 → 1.1.56

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 (32) hide show
  1. package/dist/archive.js +3 -1
  2. package/dist/batch.d.ts +7 -7
  3. package/dist/batch.js +18 -27
  4. package/dist/commands/export.js +82 -62
  5. package/dist/commands/inspect.js +6 -6
  6. package/dist/commands/memory.js +80 -39
  7. package/dist/commands/sandbox.js +1 -17
  8. package/dist/meta/finetune/memories.d.ts +1 -1
  9. package/dist/meta/finetune/memories.js +25 -8
  10. package/dist/sandbox.js +1 -1
  11. package/dist/validate.js +6 -8
  12. package/package.json +4 -4
  13. package/templates/editor/.github/copilot-instructions.md +17 -30
  14. package/templates/editor/.github/skills/zen-analyze-run/SKILL.md +2 -1
  15. package/templates/editor/.github/skills/zen-cli/SKILL.md +1 -1
  16. package/templates/editor/.github/skills/zen-cli/references/export.md +7 -6
  17. package/templates/editor/.github/skills/zen-cli/references/memory.md +14 -13
  18. package/templates/editor/.github/skills/zen-cli/references/run.md +5 -5
  19. package/templates/editor/.github/skills/zen-finetune/SKILL.md +1 -1
  20. package/templates/editor/.github/skills/zen-finetune/scripts/memory.mjs +21 -7
  21. package/templates/editor/.github/skills/zen-finetune/scripts/report.mjs +2 -2
  22. package/templates/editor/.github/skills/zen-instructions/SKILL.md +3 -2
  23. package/templates/editor/.github/skills/zen-memory/SKILL.md +38 -38
  24. package/templates/editor/.github/skills/zen-memory-warmup/SKILL.md +2 -2
  25. package/templates/editor/.github/skills/zen-review/SKILL.md +3 -3
  26. package/templates/editor/.github/skills/zen-review/scripts/check-paths.sh +3 -3
  27. package/templates/editor/.github/skills/zen-sandbox/SKILL.md +5 -16
  28. package/templates/editor/.vscode/agents.schema.json +3 -2
  29. package/templates/project/agents/files-instructions.md +3 -2
  30. package/templates/project/agents/memory-instructions.md +8 -6
  31. package/templates/project/gitignore +6 -4
  32. package/templates/project/sandbox/Dockerfile.tmpl +28 -2
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
@@ -44,9 +44,9 @@ export interface BatchOptions {
44
44
  export type MemoryMode = 'read-only' | 'copied' | 'none';
45
45
  export declare function runBatch(opts: BatchOptions): Promise<void>;
46
46
  /**
47
- * The most containers one item can start: one shared by the agents on the
48
- * project's sandbox block, one more for each agent with a block of its own.
49
- * A project that does not load is each item's to report, so it counts none.
47
+ * The containers one item can start: one, shared by every agent, when any
48
+ * agent can reach a shell, and none otherwise. A project that does not load
49
+ * is each item's to report, so it counts none.
50
50
  */
51
51
  export declare function containersPerItem(dir: string): number;
52
52
  /**
@@ -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.
@@ -176,9 +170,9 @@ export async function runBatch(opts) {
176
170
  // One item
177
171
  // ---------------------------------------------------------------------------
178
172
  /**
179
- * The most containers one item can start: one shared by the agents on the
180
- * project's sandbox block, one more for each agent with a block of its own.
181
- * A project that does not load is each item's to report, so it counts none.
173
+ * The containers one item can start: one, shared by every agent, when any
174
+ * agent can reach a shell, and none otherwise. A project that does not load
175
+ * is each item's to report, so it counts none.
182
176
  */
183
177
  export function containersPerItem(dir) {
184
178
  let read;
@@ -189,7 +183,7 @@ export function containersPerItem(dir) {
189
183
  return 0;
190
184
  }
191
185
  const tools = availableTools(read.root, read.config);
192
- const shells = read.config.agents.filter((a) => {
186
+ const shell = read.config.agents.some((a) => {
193
187
  try {
194
188
  return selectTools(tools, [...(a.tools ?? [])], { where: a.name }).some((t) => t.group === SANDBOX_GROUP);
195
189
  }
@@ -197,8 +191,7 @@ export function containersPerItem(dir) {
197
191
  return false;
198
192
  }
199
193
  });
200
- const own = shells.filter((a) => a.sandbox).length;
201
- return own + (shells.length > own ? 1 : 0);
194
+ return shell ? 1 : 0;
202
195
  }
203
196
  /**
204
197
  * A failure is data. One item that asks something the model cannot answer must
@@ -335,8 +328,8 @@ export function concurrency(value) {
335
328
  * Each item's memory, made before any of them runs.
336
329
  *
337
330
  * 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
331
+ * sixteen runs at once are sixteen private histories rather than one shared
332
+ * one. A source that is not there yet is not an error: a project declares its
340
333
  * memory directory and the first run makes it, so warming a cold project means
341
334
  * copying from nothing, and nothing is what each item starts with.
342
335
  */
@@ -347,7 +340,7 @@ export async function prepareMemories(items, at) {
347
340
  if (at.mode === 'copied' && at.source) {
348
341
  const mine = join(at.dir, item.id, 'memory');
349
342
  if (at.seeded) {
350
- await cp(at.source, mine, { recursive: true, filter: notLock });
343
+ await copyMemory(at.source, mine);
351
344
  }
352
345
  prepared.set(item.id, mine);
353
346
  }
@@ -360,15 +353,15 @@ export async function prepareMemories(items, at) {
360
353
  /**
361
354
  * Drops the memories nothing was committed to, and counts the ones left.
362
355
  *
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
356
+ * A memory is its database; a directory without one is not a memory and
357
+ * `merge` refuses it by name. Leaving those behind
365
358
  * would mean the `merge` line this command prints is advice that fails, so an
366
359
  * item that learned nothing leaves nothing.
367
360
  */
368
361
  export async function keepWritten(prepared) {
369
362
  let kept = 0;
370
363
  for (const at of prepared.values()) {
371
- if (existsSync(join(at, MEMORY_MANIFEST))) {
364
+ if (isMemory(at)) {
372
365
  kept += 1;
373
366
  }
374
367
  else {
@@ -387,8 +380,6 @@ function memorySource(projectDir, override) {
387
380
  return override;
388
381
  }
389
382
  }
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
383
  /**
393
384
  * The question, for the index — text whole, media named rather than repeated.
394
385
  * 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, WORKSPACE_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";
@@ -654,7 +654,7 @@ async function rebuild(session, run, store) {
654
654
  title: run.id,
655
655
  memory: store,
656
656
  // The run never recorded a `workdir:`, so the default name is the guess.
657
- mounts: workspace ? [{ at: SANDBOX_MOUNT, href: pathToFileURL(workspace).href }] : [],
657
+ mounts: workspace ? [{ at: WORKSPACE_MOUNT, href: pathToFileURL(workspace).href }] : [],
658
658
  });
659
659
  await writeFile(run.report, renderReportHtml(report), 'utf8');
660
660
  }
@@ -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) {
@@ -942,7 +983,7 @@ function textLast(rows, texts) {
942
983
  : Infinity;
943
984
  return table(rows.map((r, i) => [...r, clip(texts[i] ?? '', room)]));
944
985
  }
945
- /** The stored `/memory/<id>.<ext>` is the agent's mount path; a terminal needs the host one. */
986
+ /** The stored `/memory/<id>.<ext>` names the file, not where it is; a terminal needs the host path. */
946
987
  function onHost(o, n) {
947
988
  return n.file ? { ...n, file: { ...n.file, path: hostPath(o.dir, n.file) } } : n;
948
989
  }
@@ -122,7 +122,7 @@ async function projectSandbox(cwd, values) {
122
122
  name: found.name,
123
123
  image: build?.tag ?? config.sandbox?.image,
124
124
  build,
125
- limits: widest(config),
125
+ limits: sandboxLimits(config.sandbox),
126
126
  };
127
127
  }
128
128
  catch {
@@ -237,22 +237,6 @@ const PAINT = {
237
237
  function ansi(line) {
238
238
  return line.map((s) => PAINT[s.tone ?? 'plain'](s.text)).join('');
239
239
  }
240
- /**
241
- * The hungriest container this project can start. An agent may override the
242
- * project's `sandbox:` block, and it is the largest of them that decides
243
- * whether a batch fits — reporting the project's own figure would understate
244
- * the machine by however much an agent asked for on top.
245
- *
246
- * The overrides are merged onto the project's block rather than read alone,
247
- * because that is what `SandboxPool.for` does when it builds the container: an
248
- * agent that names only `memory:` still runs with the project's `cpus:`.
249
- */
250
- function widest(config) {
251
- const base = config.sandbox ?? {};
252
- return config.agents
253
- .map((a) => sandboxLimits(a.sandbox ? { ...base, ...a.sandbox } : base))
254
- .reduce((most, one) => (one.memory > most.memory ? one : most), sandboxLimits(base));
255
- }
256
240
  /**
257
241
  * How many containers of this size the engine could hold at once.
258
242
  *
@@ -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;