opencode-codex-memory 0.7.7 → 0.8.0

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 (57) hide show
  1. package/README.md +51 -8
  2. package/dist/opencode.json +2 -2
  3. package/dist/src/capture.d.ts +5 -0
  4. package/dist/src/capture.js +8 -0
  5. package/dist/src/codex-interop.js +5 -0
  6. package/dist/src/db.d.ts +7 -1
  7. package/dist/src/db.js +38 -11
  8. package/dist/src/host-client.d.ts +5 -0
  9. package/dist/src/index.d.ts +12 -4
  10. package/dist/src/index.js +39 -61
  11. package/dist/src/lifecycle.js +14 -9
  12. package/dist/src/llm.d.ts +3 -2
  13. package/dist/src/llm.js +47 -11
  14. package/dist/src/memory-version.d.ts +5 -0
  15. package/dist/src/memory-version.js +16 -0
  16. package/dist/src/migration.d.ts +24 -0
  17. package/dist/src/migration.js +37 -0
  18. package/dist/src/options.d.ts +4 -0
  19. package/dist/src/options.js +2 -0
  20. package/dist/src/paths.d.ts +9 -3
  21. package/dist/src/paths.js +22 -8
  22. package/dist/src/phase1.js +16 -2
  23. package/dist/src/phase2.js +15 -9
  24. package/dist/src/pipeline.d.ts +3 -0
  25. package/dist/src/pipeline.js +74 -0
  26. package/dist/src/ratelimit.js +5 -4
  27. package/dist/src/rollout-input.d.ts +3 -2
  28. package/dist/src/rollout-input.js +26 -17
  29. package/dist/src/session-version.d.ts +9 -0
  30. package/dist/src/session-version.js +27 -0
  31. package/dist/src/source.js +21 -6
  32. package/dist/src/store.d.ts +10 -1
  33. package/dist/src/store.js +76 -24
  34. package/dist/src/templates/consolidation_v2.md +54 -0
  35. package/dist/src/templates/read_path_v2.md +58 -0
  36. package/dist/src/templates/stage_one_input_v2.md +21 -0
  37. package/dist/src/templates/stage_one_system_v2.md +53 -0
  38. package/dist/src/token.d.ts +2 -0
  39. package/dist/src/token.js +16 -0
  40. package/dist/src/v2/agents.d.ts +4 -2
  41. package/dist/src/v2/agents.js +15 -7
  42. package/dist/src/v2/citation-overlay.d.ts +1 -1
  43. package/dist/src/v2/citation-overlay.js +27 -4
  44. package/dist/src/v2/plugin.js +24 -72
  45. package/dist/src/v2/shim.js +5 -1
  46. package/dist/src/v2/status-rpc.d.ts +70 -1
  47. package/dist/src/v2/status-rpc.js +41 -2
  48. package/dist/src/v2/status.d.ts +1 -1
  49. package/dist/src/v2/status.js +28 -6
  50. package/dist/src/v2/tui.js +57 -2
  51. package/dist/src/workspace.d.ts +8 -6
  52. package/dist/src/workspace.js +31 -11
  53. package/dist/tools/control.d.ts +6 -2
  54. package/dist/tools/control.js +196 -164
  55. package/dist/tools/memory.js +11 -1
  56. package/opencode.json +2 -2
  57. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  export declare const MEMORIZE_AGENT_ID = "memorize";
2
2
  export declare const MEMORIZE_EXTRACT_AGENT_ID = "memorize-extract";
3
- export declare const MEMORIZE_SYSTEM = "You are a memory consolidation agent. Read the workspace diff file and update MEMORY.md, memory_summary.md, and skills/ under the memory workspace only. Do not read or edit project source files outside that memory root. Keep memory_summary.md under 10000 chars (2500 tokens). Prune stale entries. Do not access the network.";
4
- export declare const MEMORIZE_EXTRACT_SYSTEM = "You are a memory extraction agent. The session transcript is provided inline in the prompt. Extract raw_memory, rollout_summary, and rollout_slug as JSON. Exclude AGENTS.md/instruction content. Redact secrets.";
3
+ export declare const MEMORIZE_SYSTEM = "You are a memory consolidation agent. Follow the supplied version-specific consolidation contract and update only its requested artifacts under the supplied memory workspace. Do not read or edit project source files or a different memory workspace. Keep memory_summary.md under 10000 bytes. Prune stale entries. Do not access the network.";
4
+ export declare const MEMORIZE_EXTRACT_SYSTEM = "You are a memory extraction agent. The session transcript is provided inline in the prompt. Follow the supplied version-specific JSON schema. Exclude AGENTS.md/instruction content. Redact secrets.";
5
5
  export declare const MEMORIZE_DESCRIPTION = "Memory consolidation agent (opencode-codex-memory)";
6
6
  export declare const MEMORIZE_EXTRACT_DESCRIPTION = "Memory extraction agent (opencode-codex-memory)";
7
7
  export interface V2AgentDefinition {
@@ -17,6 +17,8 @@ export interface V2AgentDefinition {
17
17
  }
18
18
  /** V2-native memorize definition (V2 action names: edit covers write/patch). */
19
19
  export declare function buildMemorizeAgent(): V2AgentDefinition;
20
+ /** Session rules run after agent rules: a concurrent helper gets one root only. */
21
+ export declare function consolidationPermissions(root: string): V2AgentDefinition["permissions"];
20
22
  /**
21
23
  * Hidden extraction definition. Unused at runtime (extraction goes through
22
24
  * generate.text), kept for parity with the V1 bundle and the health
@@ -16,11 +16,12 @@
16
16
  import path from "path";
17
17
  import { memoryRoot } from "../paths.js";
18
18
  import { pluginOptions } from "../options.js";
19
+ import { writeMemoryVersions } from "../memory-version.js";
19
20
  import { recordAgentConfig } from "../agent-health.js";
20
21
  export const MEMORIZE_AGENT_ID = "memorize";
21
22
  export const MEMORIZE_EXTRACT_AGENT_ID = "memorize-extract";
22
- export const MEMORIZE_SYSTEM = "You are a memory consolidation agent. Read the workspace diff file and update MEMORY.md, memory_summary.md, and skills/ under the memory workspace only. Do not read or edit project source files outside that memory root. Keep memory_summary.md under 10000 chars (2500 tokens). Prune stale entries. Do not access the network.";
23
- export const MEMORIZE_EXTRACT_SYSTEM = "You are a memory extraction agent. The session transcript is provided inline in the prompt. Extract raw_memory, rollout_summary, and rollout_slug as JSON. Exclude AGENTS.md/instruction content. Redact secrets.";
23
+ export const MEMORIZE_SYSTEM = "You are a memory consolidation agent. Follow the supplied version-specific consolidation contract and update only its requested artifacts under the supplied memory workspace. Do not read or edit project source files or a different memory workspace. Keep memory_summary.md under 10000 bytes. Prune stale entries. Do not access the network.";
24
+ export const MEMORIZE_EXTRACT_SYSTEM = "You are a memory extraction agent. The session transcript is provided inline in the prompt. Follow the supplied version-specific JSON schema. Exclude AGENTS.md/instruction content. Redact secrets.";
24
25
  export const MEMORIZE_DESCRIPTION = "Memory consolidation agent (opencode-codex-memory)";
25
26
  export const MEMORIZE_EXTRACT_DESCRIPTION = "Memory extraction agent (opencode-codex-memory)";
26
27
  /** V2-native memorize definition (V2 action names: edit covers write/patch). */
@@ -31,17 +32,24 @@ export function buildMemorizeAgent() {
31
32
  system: MEMORIZE_SYSTEM,
32
33
  permissions: [
33
34
  { action: "*", resource: "*", effect: "deny" },
34
- { action: "read", resource: path.join(memoryRoot(), "*"), effect: "allow" },
35
- { action: "edit", resource: path.join(memoryRoot(), "*"), effect: "allow" },
36
- { action: "glob", resource: path.join(memoryRoot(), "*"), effect: "allow" },
37
- { action: "grep", resource: path.join(memoryRoot(), "*"), effect: "allow" },
38
35
  // Memories live outside every project: without this grant the wildcard
39
36
  // deny blocks consolidation from touching the memory workspace (same
40
37
  // role as external_directory in the V1 definition).
41
- { action: "external_directory", resource: path.join(memoryRoot(), "*"), effect: "allow" },
38
+ ...writeMemoryVersions().flatMap((version) => ["read", "edit", "glob", "grep", "external_directory"].map((action) => ({
39
+ action, resource: path.join(memoryRoot(version), "*"), effect: "allow",
40
+ }))),
42
41
  ],
43
42
  };
44
43
  }
44
+ /** Session rules run after agent rules: a concurrent helper gets one root only. */
45
+ export function consolidationPermissions(root) {
46
+ return [
47
+ { action: "*", resource: "*", effect: "deny" },
48
+ ...["read", "edit", "glob", "grep", "external_directory"].map((action) => ({
49
+ action, resource: path.join(root, "*"), effect: "allow",
50
+ })),
51
+ ];
52
+ }
45
53
  /**
46
54
  * Hidden extraction definition. Unused at runtime (extraction goes through
47
55
  * generate.text), kept for parity with the V1 bundle and the health
@@ -4,4 +4,4 @@
4
4
  * overlays this section onto the shared inject prompt.
5
5
  */
6
6
  export declare const V2_CITATION_INSTRUCTIONS = "Memory citation requirements:\n\n- If ANY relevant memory files were used: append exactly one fenced code\n block with the language tag `memory-citation` as the VERY LAST content of\n the final reply. Answer first, then a blank line, then the block. The\n opening fence must be on its own line at column 0 \u2014 never glue it to the\n last sentence, or markdown clients treat the block as paragraph text and\n collapse its newlines. The host renders this block natively.\n- Use this exact structure for programmatic parsing (blank line before the\n fence is required):\n````\nanswer text ends here.\n\n```memory-citation\nMEMORY.md:234-236|note=build command for the api service\nrollout_summaries/2026-02-17T21-23-02-ln3m-example.md:10-12|note=weekly report format\nsessions: ses_abc123 ses_def456\n```\n````\n- Do not wrap it in `<memory-citation>` XML tags; the fenced form replaces\n that older format.\n- Citation entry lines are for rendering:\n - one citation entry per line\n - format: `<file>:<line_start>-<line_end>|note=<how memory was used>`\n - use file paths relative to the memory base path (for example, `MEMORY.md`,\n `rollout_summaries/...`, `skills/...`)\n - only cite files actually used under the memory base path (do not cite\n workspace files as memory citations)\n - if you used `MEMORY.md` and then a rollout summary/skill file, cite both\n - list entries in order of importance (most important first)\n - `note` should be short, single-line, and use simple characters only (avoid\n unusual symbols, no newlines)\n- The final `sessions:` line is for us to track which past sessions you find\n useful:\n - one line, space-separated session ids after `sessions:`\n - session ids look like `ses_...` and appear in rollout summary files and\n MEMORY.md as `session_id:`\n - include unique ids only; do not repeat ids\n - omit the `sessions:` line if no session ids are available\n - do not include file paths or notes on this line\n - for every citation entry, try to find and cite the corresponding session id\n- Never include memory citations inside pull-request messages.\n- Never cite blank lines; double-check ranges.\n\n";
7
- export declare function overlayV2CitationInstructions(prompt: string): string;
7
+ export declare function overlayV2CitationInstructions(prompt: string, version?: "v1" | "v2"): string;
@@ -48,10 +48,33 @@ sessions: ses_abc123 ses_def456
48
48
  - Never cite blank lines; double-check ranges.
49
49
 
50
50
  `;
51
- export function overlayV2CitationInstructions(prompt) {
52
- const start = prompt.indexOf("Memory citation requirements:");
51
+ const SUMMARY_ONLY_CITATIONS = `Memory citation requirements:
52
+
53
+ - When a read rollout summary informs the answer, append exactly one fenced
54
+ \`memory-citation\` block as the VERY LAST content of the final reply.
55
+ Answer first, then a blank line, then the opening fence at column 0.
56
+ - Cite only memory files actually read and used. Do not cite memory_summary.md.
57
+ Do not reread files solely to construct citations. Never cite in pull requests.
58
+ - Use relative paths and nonblank line ranges. Notes must be short and single-line.
59
+ - Include unique session ids already available; omit the sessions line if none.
60
+ - Use this exact structure (never XML tags):
61
+ \`\`\`\`
62
+ answer text ends here.
63
+
64
+ \`\`\`memory-citation
65
+ rollout_summaries/2026-02-17T21-23-02-ln3m-example.md:10-12|note=weekly report format
66
+ sessions: ses_abc123 ses_def456
67
+ \`\`\`
68
+ \`\`\`\`
69
+
70
+ `;
71
+ export function overlayV2CitationInstructions(prompt, version = "v1") {
72
+ let start = prompt.indexOf("Memory citation requirements:");
73
+ if (start === -1)
74
+ start = prompt.indexOf("Memory citations:");
53
75
  const end = prompt.indexOf("Updating memories:");
76
+ const instructions = version === "v2" ? SUMMARY_ONLY_CITATIONS : V2_CITATION_INSTRUCTIONS;
54
77
  if (start === -1 || end === -1 || end <= start)
55
- return `${prompt.trimEnd()}\n\n${V2_CITATION_INSTRUCTIONS}`;
56
- return prompt.slice(0, start) + V2_CITATION_INSTRUCTIONS + prompt.slice(end);
78
+ return `${prompt.trimEnd()}\n\n${instructions}`;
79
+ return prompt.slice(0, start) + instructions + prompt.slice(end);
57
80
  }
@@ -20,16 +20,15 @@
20
20
  */
21
21
  import { ensureMemoryLayout, buildMemorySystemPrompt, invalidateCache } from "../source.js";
22
22
  import { stripCitations, extractCitedSessionIds, hasCitationMarkup } from "../citation.js";
23
- import { MemoryStore } from "../store.js";
24
- import { runPhase1 } from "../phase1.js";
25
- import { runPhase2 } from "../phase2.js";
23
+ import { MemoryStore, existingMemoryStores } from "../store.js";
24
+ import { runMemoryPipeline, runMemoryConsolidation } from "../pipeline.js";
25
+ import { sessionMemoryVersion, withSessionMemoryVersion } from "../session-version.js";
26
26
  import { setPluginInput, setSubSessionDirectory, cleanupOldSubSessions, isMemorySubSession, abortActiveSubSessions, } from "../llm.js";
27
27
  import { pluginOptions, clearConfigWarnings, resetPluginOptions } from "../options.js";
28
- import { memoryDbPath } from "../paths.js";
28
+ import { dataRoot } from "../paths.js";
29
29
  import { closeDb } from "../db.js";
30
30
  import { beginPluginShutdown, isPluginShuttingDown, resetPluginLifecycle } from "../lifecycle.js";
31
31
  import { hostMcpStatus } from "../host-client.js";
32
- import { recordDiagnostic } from "../diagnostics.js";
33
32
  import { resetAgentHealth } from "../agent-health.js";
34
33
  import { applyPluginOptions, handleSessionDeleted } from "../index.js";
35
34
  import { setV2Context, buildV1ClientShim, rememberV2Session, } from "./shim.js";
@@ -40,7 +39,6 @@ import { readMemoryStatus } from "./status.js";
40
39
  import { recordInjection, resetInjectionStats } from "./injection.js";
41
40
  import { overlayV2CitationInstructions } from "./citation-overlay.js";
42
41
  import { estimateTokens } from "../token.js";
43
- let phase1InFlight = false;
44
42
  let shimClient = null;
45
43
  const backgroundTasks = new Set();
46
44
  const statusListeners = new Set();
@@ -63,7 +61,6 @@ export async function waitForV2BackgroundTasks() {
63
61
  }
64
62
  /** Test seam: reset module state between tests. */
65
63
  export function resetV2ModuleStateForTest() {
66
- phase1InFlight = false;
67
64
  statusListeners.clear();
68
65
  backgroundTasks.clear();
69
66
  seenTurnSessions.clear();
@@ -77,7 +74,7 @@ function recordV2Citations(sessionId, assistantMessageId, text) {
77
74
  return;
78
75
  const ids = extractCitedSessionIds(text);
79
76
  if (ids.length > 0)
80
- getStore().recordUsageOnce(sessionId, assistantMessageId, ids);
77
+ withSessionMemoryVersion(sessionId, () => getStore().recordUsageOnce(sessionId, assistantMessageId, ids));
81
78
  }
82
79
  function stripAndReconcileCitations(sessionId, messages) {
83
80
  for (const [i, msg] of (messages ?? []).entries()) {
@@ -183,6 +180,7 @@ async function classifyExternalContextTool(toolName) {
183
180
  function stampAndPump(sid, directory) {
184
181
  rememberV2Session(sid, directory ?? null);
185
182
  try {
183
+ sessionMemoryVersion(sid);
186
184
  getStore().stampMemoryModeIfAbsent(sid, pluginOptions.generate_memories ? "enabled" : "disabled");
187
185
  }
188
186
  catch (e) {
@@ -191,52 +189,17 @@ function stampAndPump(sid, directory) {
191
189
  trackBackgroundTask(triggerPhase1(sid));
192
190
  }
193
191
  async function triggerPhase1(currentSessionId) {
194
- if (phase1InFlight || !pluginOptions.generate_memories || isPluginShuttingDown())
195
- return;
196
- phase1InFlight = true;
197
192
  notifyStatusChanged();
198
193
  try {
199
- await runPhase1(getStore(), {
200
- maxAgeDays: pluginOptions.max_rollout_age_days,
201
- minIdleHours: pluginOptions.min_rollout_idle_hours,
202
- maxClaimed: pluginOptions.max_rollouts_per_startup,
203
- maxUnusedDays: pluginOptions.max_unused_days,
204
- excludeSession: currentSessionId,
205
- extractModel: pluginOptions.extract_model,
206
- });
207
- }
208
- catch (err) {
209
- console.error("[opencode-codex-memory] phase1 error:", err);
210
- recordDiagnostic("error", "phase1", err instanceof Error ? err.message : String(err));
194
+ await runMemoryPipeline(currentSessionId);
211
195
  }
212
196
  finally {
213
- phase1InFlight = false;
214
197
  notifyStatusChanged();
215
198
  }
216
- trackBackgroundTask(triggerPhase2().then(() => { }));
217
199
  }
218
- async function triggerPhase2(bypassCooldown = false) {
219
- if (isPluginShuttingDown())
220
- return "shutting_down";
200
+ async function triggerPhase2() {
221
201
  try {
222
- const result = await runPhase2(getStore(), {
223
- maxRaw: pluginOptions.max_raw_memories_for_consolidation,
224
- maxUnusedDays: pluginOptions.max_unused_days,
225
- extensionRetentionDays: 7,
226
- consolidationModel: pluginOptions.consolidation_model,
227
- codexInterop: pluginOptions.codex_interop,
228
- claudeImport: pluginOptions.claude_import,
229
- bypassCooldown,
230
- });
231
- if (result.status !== "already_running" && result.status !== "skipped_cooldown" && result.status !== "skipped_running") {
232
- recordDiagnostic(result.status === "succeeded" || result.status === "no_workspace_changes" ? "info" : "warn", "phase2", result.status);
233
- }
234
- return result.status;
235
- }
236
- catch (err) {
237
- console.error("[opencode-codex-memory] phase2 error:", err);
238
- recordDiagnostic("error", "phase2", err instanceof Error ? err.message : String(err));
239
- return "failed";
202
+ return (await runMemoryConsolidation()).join(", ");
240
203
  }
241
204
  finally {
242
205
  notifyStatusChanged();
@@ -244,29 +207,13 @@ async function triggerPhase2(bypassCooldown = false) {
244
207
  }
245
208
  /** /memory "Consolidate now": one phase-1 pass over idle sessions, then phase 2 without cooldown. */
246
209
  async function consolidateNow() {
247
- if (phase1InFlight)
248
- return "already_running";
249
- if (!pluginOptions.generate_memories)
250
- return "generation_disabled";
251
- phase1InFlight = true;
252
210
  notifyStatusChanged();
253
211
  try {
254
- await runPhase1(getStore(), {
255
- maxAgeDays: pluginOptions.max_rollout_age_days,
256
- minIdleHours: pluginOptions.min_rollout_idle_hours,
257
- maxClaimed: pluginOptions.max_rollouts_per_startup,
258
- maxUnusedDays: pluginOptions.max_unused_days,
259
- extractModel: pluginOptions.extract_model,
260
- });
261
- }
262
- catch (err) {
263
- recordDiagnostic("error", "phase1", err instanceof Error ? err.message : String(err));
212
+ return (await runMemoryPipeline(undefined, true)).join(", ");
264
213
  }
265
214
  finally {
266
- phase1InFlight = false;
267
215
  notifyStatusChanged();
268
216
  }
269
- return triggerPhase2(true);
270
217
  }
271
218
  export async function setup(ctx) {
272
219
  resetPluginLifecycle();
@@ -282,16 +229,17 @@ export async function setup(ctx) {
282
229
  if (rawOptions && Object.keys(rawOptions).length > 0)
283
230
  applyPluginOptions(rawOptions);
284
231
  else {
285
- const previousDb = memoryDbPath();
232
+ const previousDb = dataRoot();
286
233
  resetPluginOptions();
287
- if (memoryDbPath() !== previousDb)
234
+ if (dataRoot() !== previousDb)
288
235
  closeDb();
289
236
  }
290
237
  await ensureV2Agents(ctx);
291
238
  const statusRegistration = await ctx.rpc.register(MemoryStatusRpc, {
292
239
  status: async (input) => {
293
240
  const sessionID = input?.sessionID;
294
- return readMemoryStatus(typeof sessionID === "string" ? sessionID : null);
241
+ const minimum = input?.minConsolidatedThreads;
242
+ return readMemoryStatus(typeof sessionID === "string" ? sessionID : null, minimum);
295
243
  },
296
244
  setOption: async (input) => {
297
245
  const { key, value } = (input ?? {});
@@ -362,11 +310,13 @@ export async function setup(ctx) {
362
310
  }
363
311
  if (!inject || !pluginOptions.use_memories)
364
312
  return;
365
- ensureMemoryLayout();
366
- const memoryPrompt = buildMemorySystemPrompt(pluginOptions.dedicated_tools);
313
+ const memoryPrompt = withSessionMemoryVersion(sid, () => {
314
+ ensureMemoryLayout();
315
+ return buildMemorySystemPrompt(pluginOptions.dedicated_tools);
316
+ });
367
317
  if (!memoryPrompt)
368
318
  return;
369
- const text = overlayV2CitationInstructions(memoryPrompt);
319
+ const text = overlayV2CitationInstructions(memoryPrompt, sessionMemoryVersion(sid));
370
320
  if (!Array.isArray(ev.system))
371
321
  ev.system = [];
372
322
  ev.system.push({ type: "text", text });
@@ -412,8 +362,10 @@ export async function setup(ctx) {
412
362
  // Bounded reseed before the event loop can see leftover helpers as user sessions.
413
363
  await cleanupOldSubSessions();
414
364
  try {
415
- if (getStore().releaseOrphanedPhase2Job()) {
416
- console.warn("[opencode-codex-memory] released a consolidation lease orphaned by a dead process");
365
+ for (const store of existingMemoryStores()) {
366
+ if (store.releaseOrphanedPhase2Job()) {
367
+ console.warn(`[opencode-codex-memory] released orphaned ${store.version} consolidation lease`);
368
+ }
417
369
  }
418
370
  }
419
371
  catch (err) {
@@ -452,7 +404,7 @@ export async function setup(ctx) {
452
404
  const sid = sessionIdFromV2Event(data);
453
405
  if (sid) {
454
406
  try {
455
- handleSessionDeleted(sid, getStore(), () => {
407
+ handleSessionDeleted(sid, undefined, () => {
456
408
  if (pluginOptions.generate_memories)
457
409
  trackBackgroundTask(triggerPhase2().then(() => { }));
458
410
  });
@@ -1,4 +1,5 @@
1
1
  import { memoryRoot } from "../paths.js";
2
+ import { consolidationPermissions } from "./agents.js";
2
3
  import { invalidateOwnService, lastServiceFailure, ownServiceClient } from "./service.js";
3
4
  let v2ctx = null;
4
5
  export function setV2Context(ctx) {
@@ -439,6 +440,9 @@ export function buildV1ClientShim() {
439
440
  const res = await ctx().session.create({
440
441
  ...(opts?.body?.title ? { title: opts.body.title } : {}),
441
442
  ...(opts?.body?.metadata ? { metadata: opts.body.metadata } : {}),
443
+ ...(opts?.body?.title === "codex-memory-consolidate"
444
+ ? { permissions: consolidationPermissions(memoryRoot()) }
445
+ : {}),
442
446
  location: { directory: opts?.query?.directory ?? memoryRoot() },
443
447
  });
444
448
  return { data: { id: und(res)?.id } };
@@ -452,7 +456,7 @@ export function buildV1ClientShim() {
452
456
  return await v2promptWithWait(opts.path.id, opts.body, opts.signal);
453
457
  }
454
458
  catch (e) {
455
- return { error: e };
459
+ return { error: e instanceof Error ? { message: e.message } : e };
456
460
  }
457
461
  },
458
462
  messages: async (opts) => {
@@ -10,6 +10,19 @@ export declare const MEMORY_STATUS_ACTIVITIES: readonly ["idle", "extracting", "
10
10
  export type MemoryStatusActivity = (typeof MEMORY_STATUS_ACTIVITIES)[number];
11
11
  export interface MemoryStatus {
12
12
  activity: MemoryStatusActivity;
13
+ version: "v1" | "v2";
14
+ sessionVersion: "v1" | "v2";
15
+ dualWrite: boolean;
16
+ v2ConsolidatedThreads: number;
17
+ v2Ready: boolean;
18
+ minConsolidatedThreads: number;
19
+ pipelines: {
20
+ version: "v1" | "v2";
21
+ stage1Count: number;
22
+ extracting: number;
23
+ phase2Status: string | null;
24
+ lastError: string | null;
25
+ }[];
13
26
  useMemories: boolean;
14
27
  generateMemories: boolean;
15
28
  extractModel: string | null;
@@ -40,6 +53,11 @@ export declare const MemoryStatusRpc: {
40
53
  readonly sessionID: {
41
54
  readonly type: "string";
42
55
  };
56
+ readonly minConsolidatedThreads: {
57
+ readonly type: "integer";
58
+ readonly minimum: 1;
59
+ readonly maximum: 4096;
60
+ };
43
61
  };
44
62
  readonly additionalProperties: false;
45
63
  };
@@ -50,9 +68,60 @@ export declare const MemoryStatusRpc: {
50
68
  readonly type: "string";
51
69
  readonly enum: readonly ["idle", "extracting", "consolidating", "retrying", "error", "read_only", "disabled", "stopping"];
52
70
  };
71
+ readonly version: {
72
+ readonly type: "string";
73
+ readonly enum: readonly ["v1", "v2"];
74
+ };
75
+ readonly sessionVersion: {
76
+ readonly type: "string";
77
+ readonly enum: readonly ["v1", "v2"];
78
+ };
79
+ readonly dualWrite: {
80
+ readonly type: "boolean";
81
+ };
82
+ readonly v2ConsolidatedThreads: {
83
+ readonly type: "integer";
84
+ readonly minimum: 0;
85
+ };
86
+ readonly v2Ready: {
87
+ readonly type: "boolean";
88
+ };
89
+ readonly minConsolidatedThreads: {
90
+ readonly type: "integer";
91
+ readonly minimum: 1;
92
+ readonly maximum: 4096;
93
+ };
53
94
  readonly useMemories: {
54
95
  readonly type: "boolean";
55
96
  };
97
+ readonly pipelines: {
98
+ readonly type: "array";
99
+ readonly items: {
100
+ readonly type: "object";
101
+ readonly properties: {
102
+ readonly version: {
103
+ readonly type: "string";
104
+ readonly enum: readonly ["v1", "v2"];
105
+ };
106
+ readonly stage1Count: {
107
+ readonly type: "integer";
108
+ readonly minimum: 0;
109
+ };
110
+ readonly extracting: {
111
+ readonly type: "integer";
112
+ readonly minimum: 0;
113
+ };
114
+ readonly phase2Status: {
115
+ readonly type: readonly ["string", "null"];
116
+ };
117
+ readonly lastError: {
118
+ readonly type: readonly ["string", "null"];
119
+ };
120
+ };
121
+ readonly required: readonly ["version", "stage1Count", "extracting", "phase2Status", "lastError"];
122
+ readonly additionalProperties: false;
123
+ };
124
+ };
56
125
  readonly generateMemories: {
57
126
  readonly type: "boolean";
58
127
  };
@@ -104,7 +173,7 @@ export declare const MemoryStatusRpc: {
104
173
  readonly additionalProperties: false;
105
174
  };
106
175
  };
107
- readonly required: readonly ["activity", "useMemories", "generateMemories", "extractModel", "consolidationModel", "codexImport", "lastSuccessAt", "retryAt", "warnings", "sessionMode", "memoryRoot", "injected"];
176
+ readonly required: readonly ["activity", "version", "sessionVersion", "dualWrite", "v2ConsolidatedThreads", "v2Ready", "minConsolidatedThreads", "pipelines", "useMemories", "generateMemories", "extractModel", "consolidationModel", "codexImport", "lastSuccessAt", "retryAt", "warnings", "sessionMode", "memoryRoot", "injected"];
108
177
  readonly additionalProperties: false;
109
178
  };
110
179
  };
@@ -33,14 +33,38 @@ export const MemoryStatusRpc = {
33
33
  status: {
34
34
  input: {
35
35
  type: "object",
36
- properties: { sessionID: { type: "string" } },
36
+ properties: {
37
+ sessionID: { type: "string" },
38
+ minConsolidatedThreads: { type: "integer", minimum: 1, maximum: 4096 },
39
+ },
37
40
  additionalProperties: false,
38
41
  },
39
42
  output: {
40
43
  type: "object",
41
44
  properties: {
42
45
  activity: { type: "string", enum: [...MEMORY_STATUS_ACTIVITIES] },
46
+ version: { type: "string", enum: ["v1", "v2"] },
47
+ sessionVersion: { type: "string", enum: ["v1", "v2"] },
48
+ dualWrite: { type: "boolean" },
49
+ v2ConsolidatedThreads: { type: "integer", minimum: 0 },
50
+ v2Ready: { type: "boolean" },
51
+ minConsolidatedThreads: { type: "integer", minimum: 1, maximum: 4096 },
43
52
  useMemories: { type: "boolean" },
53
+ pipelines: {
54
+ type: "array",
55
+ items: {
56
+ type: "object",
57
+ properties: {
58
+ version: { type: "string", enum: ["v1", "v2"] },
59
+ stage1Count: { type: "integer", minimum: 0 },
60
+ extracting: { type: "integer", minimum: 0 },
61
+ phase2Status: { type: ["string", "null"] },
62
+ lastError: { type: ["string", "null"] },
63
+ },
64
+ required: ["version", "stage1Count", "extracting", "phase2Status", "lastError"],
65
+ additionalProperties: false,
66
+ },
67
+ },
44
68
  generateMemories: { type: "boolean" },
45
69
  extractModel: { type: ["string", "null"] },
46
70
  consolidationModel: { type: ["string", "null"] },
@@ -54,6 +78,7 @@ export const MemoryStatusRpc = {
54
78
  },
55
79
  required: [
56
80
  "activity",
81
+ "version", "sessionVersion", "dualWrite", "v2ConsolidatedThreads", "v2Ready", "minConsolidatedThreads", "pipelines",
57
82
  "useMemories",
58
83
  "generateMemories",
59
84
  "extractModel",
@@ -121,10 +146,24 @@ export function isMemoryStatus(value) {
121
146
  !MEMORY_STATUS_ACTIVITIES.includes(value.activity)) {
122
147
  return false;
123
148
  }
124
- for (const key of ["useMemories", "generateMemories", "codexImport"]) {
149
+ for (const key of ["useMemories", "generateMemories", "codexImport", "dualWrite", "v2Ready"]) {
125
150
  if (typeof value[key] !== "boolean")
126
151
  return false;
127
152
  }
153
+ for (const key of ["version", "sessionVersion"]) {
154
+ if (value[key] !== "v1" && value[key] !== "v2")
155
+ return false;
156
+ }
157
+ if (!Number.isInteger(value.v2ConsolidatedThreads) || value.v2ConsolidatedThreads < 0)
158
+ return false;
159
+ if (!Number.isInteger(value.minConsolidatedThreads) || value.minConsolidatedThreads < 1 || value.minConsolidatedThreads > 4096)
160
+ return false;
161
+ if (!Array.isArray(value.pipelines) || !value.pipelines.every((pipeline) => isRecord(pipeline) && (pipeline.version === "v1" || pipeline.version === "v2")
162
+ && Number.isInteger(pipeline.stage1Count) && pipeline.stage1Count >= 0
163
+ && Number.isInteger(pipeline.extracting) && pipeline.extracting >= 0
164
+ && (pipeline.phase2Status === null || typeof pipeline.phase2Status === "string")
165
+ && (pipeline.lastError === null || typeof pipeline.lastError === "string")))
166
+ return false;
128
167
  for (const key of ["extractModel", "consolidationModel", "lastSuccessAt", "retryAt"]) {
129
168
  const v = value[key];
130
169
  if (v !== null && typeof v !== (key === "extractModel" || key === "consolidationModel" ? "string" : "number")) {
@@ -1,3 +1,3 @@
1
1
  import type { MemoryStatus } from "./status-rpc.js";
2
2
  /** Read the same snapshots as memory_inspect; never claim or advance a job. */
3
- export declare function readMemoryStatus(sessionID?: string | null): MemoryStatus;
3
+ export declare function readMemoryStatus(sessionID?: string | null, minConsolidatedThreads?: number): MemoryStatus;
@@ -7,9 +7,21 @@ import { activeProviderCapacityBackoffs } from "../ratelimit.js";
7
7
  import { resolveCodexInterop } from "../codex-interop.js";
8
8
  import { injectionTotals, sessionInjection } from "./injection.js";
9
9
  import { memoryRoot } from "../paths.js";
10
+ import { readMigrationStatus, memoryPipelineSnapshots } from "../migration.js";
11
+ import { peekSessionMemoryVersion } from "../session-version.js";
12
+ import { withMemoryVersion, writeMemoryVersions } from "../memory-version.js";
10
13
  /** Read the same snapshots as memory_inspect; never claim or advance a job. */
11
- export function readMemoryStatus(sessionID) {
12
- const store = new MemoryStore();
14
+ export function readMemoryStatus(sessionID, minConsolidatedThreads) {
15
+ const sessionVersion = peekSessionMemoryVersion(sessionID);
16
+ const store = withMemoryVersion(sessionVersion, () => new MemoryStore());
17
+ const pipelines = memoryPipelineSnapshots().map((pipeline) => ({
18
+ version: pipeline.version,
19
+ stage1Count: pipeline.stage1Count,
20
+ extracting: pipeline.stage1Jobs.running ?? 0,
21
+ phase2Status: pipeline.phase2?.status ?? null,
22
+ lastError: pipeline.phase2?.last_error ?? null,
23
+ }));
24
+ const active = pipelines.filter((pipeline) => writeMemoryVersions().includes(pipeline.version));
13
25
  const options = pluginOptions;
14
26
  const now = Date.now();
15
27
  const staleBeforeSec = Math.floor(now / 1000) - options.max_rollout_age_days * 86_400;
@@ -31,6 +43,10 @@ export function readMemoryStatus(sessionID) {
31
43
  }
32
44
  if (phase2?.last_error)
33
45
  warnings.push("Consolidation failed; see memory_inspect for details.");
46
+ for (const pipeline of active) {
47
+ if (pipeline.version !== sessionVersion && pipeline.lastError)
48
+ warnings.push(`${pipeline.version}: consolidation failed; see memory_inspect.`);
49
+ }
34
50
  if (phase1.by_failure_class.due > 0)
35
51
  warnings.push("Some extraction jobs are due to retry.");
36
52
  if (phase1.by_failure_class.other_exhausted > phase1.stale_exhausted) {
@@ -38,8 +54,9 @@ export function readMemoryStatus(sessionID) {
38
54
  }
39
55
  if (phase1.by_failure_class.provider_capacity > 0)
40
56
  warnings.push("Some extraction jobs hit provider capacity limits.");
41
- const codexImport = options.codex_interop.import && resolveCodexInterop(options.codex_interop) !== null;
42
- if (options.codex_interop.import && !codexImport)
57
+ const importsV1 = options.codex_interop.import && writeMemoryVersions().includes("v1");
58
+ const codexImport = importsV1 && withMemoryVersion("v1", () => resolveCodexInterop(options.codex_interop)) !== null;
59
+ if (importsV1 && !codexImport)
43
60
  warnings.push("Codex import is misconfigured.");
44
61
  // A `running` row this process does not own is either another opencode
45
62
  // instance's live job or an orphaned lease (e.g. a server restart killed the
@@ -56,7 +73,7 @@ export function readMemoryStatus(sessionID) {
56
73
  activity = "stopping";
57
74
  else if (isPhase2InFlight())
58
75
  activity = "consolidating";
59
- else if ((phase1.by_status.running ?? 0) > 0)
76
+ else if (active.some((pipeline) => pipeline.extracting > 0))
60
77
  activity = "extracting";
61
78
  else if (!options.generate_memories)
62
79
  activity = options.use_memories ? "read_only" : "disabled";
@@ -66,6 +83,11 @@ export function readMemoryStatus(sessionID) {
66
83
  activity = "error";
67
84
  return {
68
85
  activity,
86
+ version: options.version,
87
+ sessionVersion,
88
+ pipelines,
89
+ dualWrite: options.dual_write,
90
+ ...readMigrationStatus(minConsolidatedThreads),
69
91
  useMemories: options.use_memories,
70
92
  generateMemories: options.generate_memories,
71
93
  extractModel: options.extract_model ?? null,
@@ -76,7 +98,7 @@ export function readMemoryStatus(sessionID) {
76
98
  retryAt,
77
99
  warnings,
78
100
  sessionMode: sessionID ? store.getMemoryMode(sessionID) : null,
79
- memoryRoot: memoryRoot(),
101
+ memoryRoot: memoryRoot(sessionVersion),
80
102
  injected: {
81
103
  sessionTokens: session.tokens,
82
104
  sessionRequests: session.requests,