opencode-codex-memory 0.7.6 → 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 (60) 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/diagnostics.js +5 -1
  9. package/dist/src/host-client.d.ts +5 -0
  10. package/dist/src/index.d.ts +12 -4
  11. package/dist/src/index.js +71 -66
  12. package/dist/src/lifecycle.js +14 -9
  13. package/dist/src/llm.d.ts +3 -2
  14. package/dist/src/llm.js +47 -11
  15. package/dist/src/local-session-times.d.ts +6 -0
  16. package/dist/src/local-session-times.js +59 -0
  17. package/dist/src/memory-version.d.ts +5 -0
  18. package/dist/src/memory-version.js +16 -0
  19. package/dist/src/migration.d.ts +24 -0
  20. package/dist/src/migration.js +37 -0
  21. package/dist/src/options.d.ts +10 -0
  22. package/dist/src/options.js +3 -0
  23. package/dist/src/paths.d.ts +9 -3
  24. package/dist/src/paths.js +22 -8
  25. package/dist/src/phase1.js +16 -2
  26. package/dist/src/phase2.js +15 -9
  27. package/dist/src/pipeline.d.ts +3 -0
  28. package/dist/src/pipeline.js +74 -0
  29. package/dist/src/ratelimit.js +9 -4
  30. package/dist/src/rollout-input.d.ts +3 -2
  31. package/dist/src/rollout-input.js +26 -17
  32. package/dist/src/session-version.d.ts +9 -0
  33. package/dist/src/session-version.js +27 -0
  34. package/dist/src/source.js +21 -6
  35. package/dist/src/store.d.ts +19 -3
  36. package/dist/src/store.js +121 -38
  37. package/dist/src/templates/consolidation_v2.md +54 -0
  38. package/dist/src/templates/read_path_v2.md +58 -0
  39. package/dist/src/templates/stage_one_input_v2.md +21 -0
  40. package/dist/src/templates/stage_one_system_v2.md +53 -0
  41. package/dist/src/token.d.ts +2 -0
  42. package/dist/src/token.js +16 -0
  43. package/dist/src/v2/agents.d.ts +4 -2
  44. package/dist/src/v2/agents.js +15 -7
  45. package/dist/src/v2/citation-overlay.d.ts +1 -1
  46. package/dist/src/v2/citation-overlay.js +27 -4
  47. package/dist/src/v2/plugin.js +27 -74
  48. package/dist/src/v2/shim.js +20 -9
  49. package/dist/src/v2/status-rpc.d.ts +70 -1
  50. package/dist/src/v2/status-rpc.js +41 -2
  51. package/dist/src/v2/status.d.ts +1 -1
  52. package/dist/src/v2/status.js +35 -9
  53. package/dist/src/v2/tui.js +57 -2
  54. package/dist/src/workspace.d.ts +8 -6
  55. package/dist/src/workspace.js +31 -11
  56. package/dist/tools/control.d.ts +6 -2
  57. package/dist/tools/control.js +209 -155
  58. package/dist/tools/memory.js +11 -1
  59. package/opencode.json +2 -2
  60. package/package.json +1 -1
@@ -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();
@@ -278,19 +225,21 @@ export async function setup(ctx) {
278
225
  resetAgentHealth();
279
226
  mcpStatusInFlight = null;
280
227
  clearConfigWarnings();
281
- if (ctx.options)
282
- applyPluginOptions(ctx.options);
228
+ const rawOptions = ctx.options;
229
+ if (rawOptions && Object.keys(rawOptions).length > 0)
230
+ applyPluginOptions(rawOptions);
283
231
  else {
284
- const previousDb = memoryDbPath();
232
+ const previousDb = dataRoot();
285
233
  resetPluginOptions();
286
- if (memoryDbPath() !== previousDb)
234
+ if (dataRoot() !== previousDb)
287
235
  closeDb();
288
236
  }
289
237
  await ensureV2Agents(ctx);
290
238
  const statusRegistration = await ctx.rpc.register(MemoryStatusRpc, {
291
239
  status: async (input) => {
292
240
  const sessionID = input?.sessionID;
293
- return readMemoryStatus(typeof sessionID === "string" ? sessionID : null);
241
+ const minimum = input?.minConsolidatedThreads;
242
+ return readMemoryStatus(typeof sessionID === "string" ? sessionID : null, minimum);
294
243
  },
295
244
  setOption: async (input) => {
296
245
  const { key, value } = (input ?? {});
@@ -361,11 +310,13 @@ export async function setup(ctx) {
361
310
  }
362
311
  if (!inject || !pluginOptions.use_memories)
363
312
  return;
364
- ensureMemoryLayout();
365
- const memoryPrompt = buildMemorySystemPrompt(pluginOptions.dedicated_tools);
313
+ const memoryPrompt = withSessionMemoryVersion(sid, () => {
314
+ ensureMemoryLayout();
315
+ return buildMemorySystemPrompt(pluginOptions.dedicated_tools);
316
+ });
366
317
  if (!memoryPrompt)
367
318
  return;
368
- const text = overlayV2CitationInstructions(memoryPrompt);
319
+ const text = overlayV2CitationInstructions(memoryPrompt, sessionMemoryVersion(sid));
369
320
  if (!Array.isArray(ev.system))
370
321
  ev.system = [];
371
322
  ev.system.push({ type: "text", text });
@@ -411,8 +362,10 @@ export async function setup(ctx) {
411
362
  // Bounded reseed before the event loop can see leftover helpers as user sessions.
412
363
  await cleanupOldSubSessions();
413
364
  try {
414
- if (getStore().releaseOrphanedPhase2Job()) {
415
- 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
+ }
416
369
  }
417
370
  }
418
371
  catch (err) {
@@ -451,7 +404,7 @@ export async function setup(ctx) {
451
404
  const sid = sessionIdFromV2Event(data);
452
405
  if (sid) {
453
406
  try {
454
- handleSessionDeleted(sid, getStore(), () => {
407
+ handleSessionDeleted(sid, undefined, () => {
455
408
  if (pluginOptions.generate_memories)
456
409
  trackBackgroundTask(triggerPhase2().then(() => { }));
457
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) {
@@ -288,16 +289,15 @@ async function v2promptWithWait(sessionID, body, signal) {
288
289
  if (body.format) {
289
290
  const prompt = body.system ? `${body.system}\n\n---\n\n${text}` : text;
290
291
  const parsed = body.model ? parseModelRef(`${body.model.providerID}/${body.model.modelID}`) : null;
292
+ // Model.Ref requires providerID + id. A variant is valid only alongside
293
+ // that complete reference; never emit a variant-only model object.
291
294
  const payload = {
292
295
  prompt,
293
- ...(parsed || body.variant
294
- ? {
295
- model: {
296
- ...(parsed ? { providerID: parsed.providerID, id: parsed.modelID } : {}),
297
- ...(body.variant ? { variant: body.variant } : {}),
298
- },
299
- }
300
- : {}),
296
+ ...(parsed ? { model: {
297
+ providerID: parsed.providerID,
298
+ id: parsed.modelID,
299
+ ...(body.variant ? { variant: body.variant } : {}),
300
+ } } : {}),
301
301
  };
302
302
  if (signal?.aborted)
303
303
  throw new Error("sub-agent prompt cancelled");
@@ -440,6 +440,9 @@ export function buildV1ClientShim() {
440
440
  const res = await ctx().session.create({
441
441
  ...(opts?.body?.title ? { title: opts.body.title } : {}),
442
442
  ...(opts?.body?.metadata ? { metadata: opts.body.metadata } : {}),
443
+ ...(opts?.body?.title === "codex-memory-consolidate"
444
+ ? { permissions: consolidationPermissions(memoryRoot()) }
445
+ : {}),
443
446
  location: { directory: opts?.query?.directory ?? memoryRoot() },
444
447
  });
445
448
  return { data: { id: und(res)?.id } };
@@ -453,7 +456,7 @@ export function buildV1ClientShim() {
453
456
  return await v2promptWithWait(opts.path.id, opts.body, opts.signal);
454
457
  }
455
458
  catch (e) {
456
- return { error: e };
459
+ return { error: e instanceof Error ? { message: e.message } : e };
457
460
  }
458
461
  },
459
462
  messages: async (opts) => {
@@ -490,6 +493,12 @@ export function buildV1ClientShim() {
490
493
  }
491
494
  },
492
495
  delete: async (opts) => {
496
+ // generate.text never creates a host session. Its synthetic handle is
497
+ // released locally; passing it to session APIs fails the ^ses schema.
498
+ if (opts.path.id === EXTRACT_STUB_SESSION_ID) {
499
+ markReleased(opts.path.id);
500
+ return {};
501
+ }
493
502
  let shutdownError;
494
503
  try {
495
504
  const client = await serviceOrThrow();
@@ -573,6 +582,8 @@ export function buildV1ClientShim() {
573
582
  }
574
583
  },
575
584
  abort: async (opts) => {
585
+ if (opts.path.id === EXTRACT_STUB_SESSION_ID)
586
+ return {};
576
587
  try {
577
588
  const client = await serviceOrThrow();
578
589
  if (typeof client.session.interrupt !== "function")
@@ -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,13 +7,26 @@ 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();
13
- const phase1 = store.stage1JobSnapshot();
14
- const phase2 = store.phase2JobSnapshot();
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));
15
25
  const options = pluginOptions;
16
26
  const now = Date.now();
27
+ const staleBeforeSec = Math.floor(now / 1000) - options.max_rollout_age_days * 86_400;
28
+ const phase1 = store.stage1JobSnapshot(staleBeforeSec);
29
+ const phase2 = store.phase2JobSnapshot();
17
30
  const session = sessionInjection(sessionID);
18
31
  const total = injectionTotals();
19
32
  const retryTimes = [
@@ -30,12 +43,20 @@ export function readMemoryStatus(sessionID) {
30
43
  }
31
44
  if (phase2?.last_error)
32
45
  warnings.push("Consolidation failed; see memory_inspect for details.");
33
- if (phase1.by_failure_class.other_exhausted > 0)
46
+ for (const pipeline of active) {
47
+ if (pipeline.version !== sessionVersion && pipeline.lastError)
48
+ warnings.push(`${pipeline.version}: consolidation failed; see memory_inspect.`);
49
+ }
50
+ if (phase1.by_failure_class.due > 0)
51
+ warnings.push("Some extraction jobs are due to retry.");
52
+ if (phase1.by_failure_class.other_exhausted > phase1.stale_exhausted) {
34
53
  warnings.push("Some extraction jobs exhausted their retries.");
54
+ }
35
55
  if (phase1.by_failure_class.provider_capacity > 0)
36
56
  warnings.push("Some extraction jobs hit provider capacity limits.");
37
- const codexImport = options.codex_interop.import && resolveCodexInterop(options.codex_interop) !== null;
38
- 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)
39
60
  warnings.push("Codex import is misconfigured.");
40
61
  // A `running` row this process does not own is either another opencode
41
62
  // instance's live job or an orphaned lease (e.g. a server restart killed the
@@ -52,7 +73,7 @@ export function readMemoryStatus(sessionID) {
52
73
  activity = "stopping";
53
74
  else if (isPhase2InFlight())
54
75
  activity = "consolidating";
55
- else if ((phase1.by_status.running ?? 0) > 0)
76
+ else if (active.some((pipeline) => pipeline.extracting > 0))
56
77
  activity = "extracting";
57
78
  else if (!options.generate_memories)
58
79
  activity = options.use_memories ? "read_only" : "disabled";
@@ -62,6 +83,11 @@ export function readMemoryStatus(sessionID) {
62
83
  activity = "error";
63
84
  return {
64
85
  activity,
86
+ version: options.version,
87
+ sessionVersion,
88
+ pipelines,
89
+ dualWrite: options.dual_write,
90
+ ...readMigrationStatus(minConsolidatedThreads),
65
91
  useMemories: options.use_memories,
66
92
  generateMemories: options.generate_memories,
67
93
  extractModel: options.extract_model ?? null,
@@ -72,7 +98,7 @@ export function readMemoryStatus(sessionID) {
72
98
  retryAt,
73
99
  warnings,
74
100
  sessionMode: sessionID ? store.getMemoryMode(sessionID) : null,
75
- memoryRoot: memoryRoot(),
101
+ memoryRoot: memoryRoot(sessionVersion),
76
102
  injected: {
77
103
  sessionTokens: session.tokens,
78
104
  sessionRequests: session.requests,
@@ -39,14 +39,38 @@ var MemoryStatusRpc = {
39
39
  status: {
40
40
  input: {
41
41
  type: "object",
42
- properties: { sessionID: { type: "string" } },
42
+ properties: {
43
+ sessionID: { type: "string" },
44
+ minConsolidatedThreads: { type: "integer", minimum: 1, maximum: 4096 }
45
+ },
43
46
  additionalProperties: false
44
47
  },
45
48
  output: {
46
49
  type: "object",
47
50
  properties: {
48
51
  activity: { type: "string", enum: [...MEMORY_STATUS_ACTIVITIES] },
52
+ version: { type: "string", enum: ["v1", "v2"] },
53
+ sessionVersion: { type: "string", enum: ["v1", "v2"] },
54
+ dualWrite: { type: "boolean" },
55
+ v2ConsolidatedThreads: { type: "integer", minimum: 0 },
56
+ v2Ready: { type: "boolean" },
57
+ minConsolidatedThreads: { type: "integer", minimum: 1, maximum: 4096 },
49
58
  useMemories: { type: "boolean" },
59
+ pipelines: {
60
+ type: "array",
61
+ items: {
62
+ type: "object",
63
+ properties: {
64
+ version: { type: "string", enum: ["v1", "v2"] },
65
+ stage1Count: { type: "integer", minimum: 0 },
66
+ extracting: { type: "integer", minimum: 0 },
67
+ phase2Status: { type: ["string", "null"] },
68
+ lastError: { type: ["string", "null"] }
69
+ },
70
+ required: ["version", "stage1Count", "extracting", "phase2Status", "lastError"],
71
+ additionalProperties: false
72
+ }
73
+ },
50
74
  generateMemories: { type: "boolean" },
51
75
  extractModel: { type: ["string", "null"] },
52
76
  consolidationModel: { type: ["string", "null"] },
@@ -60,6 +84,13 @@ var MemoryStatusRpc = {
60
84
  },
61
85
  required: [
62
86
  "activity",
87
+ "version",
88
+ "sessionVersion",
89
+ "dualWrite",
90
+ "v2ConsolidatedThreads",
91
+ "v2Ready",
92
+ "minConsolidatedThreads",
93
+ "pipelines",
63
94
  "useMemories",
64
95
  "generateMemories",
65
96
  "extractModel",
@@ -122,10 +153,20 @@ function isMemoryStatus(value) {
122
153
  if (typeof value.activity !== "string" || !MEMORY_STATUS_ACTIVITIES.includes(value.activity)) {
123
154
  return false;
124
155
  }
125
- for (const key of ["useMemories", "generateMemories", "codexImport"]) {
156
+ for (const key of ["useMemories", "generateMemories", "codexImport", "dualWrite", "v2Ready"]) {
126
157
  if (typeof value[key] !== "boolean")
127
158
  return false;
128
159
  }
160
+ for (const key of ["version", "sessionVersion"]) {
161
+ if (value[key] !== "v1" && value[key] !== "v2")
162
+ return false;
163
+ }
164
+ if (!Number.isInteger(value.v2ConsolidatedThreads) || value.v2ConsolidatedThreads < 0)
165
+ return false;
166
+ if (!Number.isInteger(value.minConsolidatedThreads) || value.minConsolidatedThreads < 1 || value.minConsolidatedThreads > 4096)
167
+ return false;
168
+ if (!Array.isArray(value.pipelines) || !value.pipelines.every((pipeline) => isRecord(pipeline) && (pipeline.version === "v1" || pipeline.version === "v2") && Number.isInteger(pipeline.stage1Count) && pipeline.stage1Count >= 0 && Number.isInteger(pipeline.extracting) && pipeline.extracting >= 0 && (pipeline.phase2Status === null || typeof pipeline.phase2Status === "string") && (pipeline.lastError === null || typeof pipeline.lastError === "string")))
169
+ return false;
129
170
  for (const key of ["extractModel", "consolidationModel", "lastSuccessAt", "retryAt"]) {
130
171
  const v = value[key];
131
172
  if (v !== null && typeof v !== (key === "extractModel" || key === "consolidationModel" ? "string" : "number")) {
@@ -235,6 +276,20 @@ function statusRows(s, now) {
235
276
  label: "Activity",
236
277
  value: labels[s.activity]
237
278
  }, {
279
+ label: "Memory version",
280
+ value: `${s.sessionVersion} (default ${s.version})`
281
+ }, {
282
+ label: "Learning pipelines",
283
+ value: s.dualWrite ? "v1 + v2" : s.version
284
+ }, {
285
+ label: "V2 readiness",
286
+ value: `${s.v2Ready ? "Ready" : "Warming"} \xB7 ${s.v2ConsolidatedThreads}/${s.minConsolidatedThreads} sessions`,
287
+ tone: s.v2Ready ? "ok" : "muted"
288
+ }, ...s.pipelines.map((pipeline) => ({
289
+ label: `${pipeline.version.toUpperCase()} pipeline`,
290
+ value: `${pipeline.stage1Count} recaps \xB7 ${pipeline.extracting ? "extracting" : pipeline.phase2Status ?? "idle"}`,
291
+ tone: pipeline.lastError ? "warn" : "muted"
292
+ })), {
238
293
  label: "Read memories",
239
294
  value: s.useMemories ? "On" : "Off",
240
295
  tone: s.useMemories ? "ok" : "muted"