opencode-codex-memory 0.8.3 → 0.9.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.
@@ -34,6 +34,7 @@ import { applyPluginOptions, handleSessionDeleted } from "../index.js";
34
34
  import { setV2Context, buildV1ClientShim, rememberV2Session, } from "./shim.js";
35
35
  import { ensureV2Agents } from "./agents.js";
36
36
  import { buildV2Tools } from "./tools.js";
37
+ import { performMemoryReset } from "../../tools/control.js";
37
38
  import { guardMemorySearchTools } from "./search-sandbox.js";
38
39
  import { MemoryStatusRpc } from "./status-rpc.js";
39
40
  import { readMemoryStatus } from "./status.js";
@@ -43,9 +44,41 @@ import { estimateTokens } from "../token.js";
43
44
  let shimClient = null;
44
45
  const backgroundTasks = new Set();
45
46
  const statusListeners = new Set();
47
+ /**
48
+ * The V2 host runs one plugin instance per location in the same process and
49
+ * evicts idle locations independently. Process-wide state (lifecycle, shim
50
+ * context, panel toggles) belongs to the set of live instances, not to
51
+ * whichever location booted or disposed last.
52
+ */
53
+ const liveInstances = [];
54
+ /** Panel toggles; survive later location setups until the last instance disposes. */
55
+ const runtimeOverrides = {};
56
+ const eventLoops = new Set();
57
+ function abortableSleep(ms, signal) {
58
+ return new Promise((resolve) => {
59
+ if (signal.aborted)
60
+ return resolve();
61
+ const timer = setTimeout(done, ms);
62
+ function done() {
63
+ clearTimeout(timer);
64
+ signal.removeEventListener("abort", done);
65
+ resolve();
66
+ }
67
+ signal.addEventListener("abort", done, { once: true });
68
+ });
69
+ }
70
+ // Context hooks fire on every LLM step; each emit makes every open panel
71
+ // re-read status. Coalesce bursts.
72
+ let statusNotifyTimer = null;
46
73
  function notifyStatusChanged() {
47
- for (const notify of statusListeners)
48
- notify();
74
+ if (statusNotifyTimer)
75
+ return;
76
+ statusNotifyTimer = setTimeout(() => {
77
+ statusNotifyTimer = null;
78
+ for (const notify of statusListeners)
79
+ notify();
80
+ }, 250);
81
+ statusNotifyTimer.unref?.();
49
82
  }
50
83
  function trackBackgroundTask(task) {
51
84
  const tracked = task.catch((err) => {
@@ -63,9 +96,18 @@ export async function waitForV2BackgroundTasks() {
63
96
  /** Test seam: reset module state between tests. */
64
97
  export function resetV2ModuleStateForTest() {
65
98
  statusListeners.clear();
99
+ if (statusNotifyTimer)
100
+ clearTimeout(statusNotifyTimer);
101
+ statusNotifyTimer = null;
66
102
  backgroundTasks.clear();
67
103
  seenTurnSessions.clear();
68
104
  mcpStatusInFlight = null;
105
+ liveInstances.length = 0;
106
+ for (const loop of eventLoops)
107
+ loop.abort();
108
+ eventLoops.clear();
109
+ for (const key of Object.keys(runtimeOverrides))
110
+ delete runtimeOverrides[key];
69
111
  }
70
112
  function getStore() {
71
113
  return new MemoryStore();
@@ -82,6 +124,7 @@ function stripAndReconcileCitations(sessionId, messages) {
82
124
  // Model-bound LLM.Message uses role; persisted/legacy rows use type.
83
125
  if ((msg?.role ?? msg?.type) !== "assistant" || !Array.isArray(msg.content))
84
126
  continue;
127
+ let emptied = false;
85
128
  for (const part of msg.content) {
86
129
  if (part?.type !== "text" || typeof part.text !== "string")
87
130
  continue;
@@ -97,6 +140,15 @@ function stripAndReconcileCitations(sessionId, messages) {
97
140
  console.error("[opencode-codex-memory] citation recording failed:", e);
98
141
  }
99
142
  part.text = stripCitations(part.text);
143
+ if (part.text === "")
144
+ emptied = true;
145
+ }
146
+ // The host drops empty text parts before this hook; some providers reject them.
147
+ if (emptied && msg.content.some((part) => part?.type !== "text" || part.text !== "")) {
148
+ for (let i = msg.content.length - 1; i >= 0; i--) {
149
+ if (msg.content[i]?.type === "text" && msg.content[i].text === "")
150
+ msg.content.splice(i, 1);
151
+ }
100
152
  }
101
153
  }
102
154
  }
@@ -221,13 +273,18 @@ async function consolidateNow() {
221
273
  }
222
274
  }
223
275
  export async function setup(ctx) {
224
- resetPluginLifecycle();
225
- resetInjectionStats();
276
+ // Later locations join a running process: resetting the lifecycle would
277
+ // abort the live consolidator, and resetting stats/health would erase state
278
+ // the other locations still report.
279
+ if (liveInstances.length === 0) {
280
+ resetPluginLifecycle();
281
+ resetInjectionStats();
282
+ resetAgentHealth();
283
+ }
226
284
  setV2Context(ctx);
227
285
  shimClient = buildV1ClientShim();
228
286
  setPluginInput({ client: shimClient });
229
287
  setSubSessionDirectory(ctx.location.directory);
230
- resetAgentHealth();
231
288
  mcpStatusInFlight = null;
232
289
  clearConfigWarnings();
233
290
  const rawOptions = ctx.options;
@@ -239,6 +296,7 @@ export async function setup(ctx) {
239
296
  if (dataRoot() !== previousDb)
240
297
  closeDb();
241
298
  }
299
+ Object.assign(pluginOptions, runtimeOverrides);
242
300
  await ensureV2Agents(ctx);
243
301
  const statusRegistration = await ctx.rpc.register(MemoryStatusRpc, {
244
302
  status: async (input) => {
@@ -250,10 +308,12 @@ export async function setup(ctx) {
250
308
  const { key, value } = (input ?? {});
251
309
  if ((key !== "use_memories" && key !== "generate_memories") || typeof value !== "boolean")
252
310
  return { ok: false };
311
+ const instances = liveInstances.includes(ctx) ? [...liveInstances] : [ctx];
253
312
  if (key === "generate_memories" && value && !pluginOptions.generate_memories) {
254
313
  pluginOptions.generate_memories = true;
255
314
  try {
256
- await ensureV2Agents(ctx);
315
+ for (const instance of instances)
316
+ await ensureV2Agents(instance);
257
317
  }
258
318
  catch (error) {
259
319
  pluginOptions.generate_memories = false;
@@ -264,17 +324,25 @@ export async function setup(ctx) {
264
324
  const previous = pluginOptions[key];
265
325
  pluginOptions[key] = value;
266
326
  if (key === "use_memories" && value !== previous) {
327
+ // Transforms capture options but the host only replays them after an
328
+ // explicit registry invalidation. Affect future tool snapshots now,
329
+ // in every location.
330
+ const reloaded = [];
267
331
  try {
268
- // Transforms capture options but the host only replays them after an
269
- // explicit registry invalidation. Affect future tool snapshots now.
270
- await ctx.tool.reload();
332
+ for (const instance of instances) {
333
+ await instance.tool.reload();
334
+ reloaded.push(instance);
335
+ }
271
336
  }
272
337
  catch (error) {
273
338
  pluginOptions[key] = previous;
339
+ for (const instance of reloaded)
340
+ await instance.tool.reload().catch(() => { });
274
341
  console.error("[opencode-codex-memory] failed to reload V2 memory tools:", error);
275
342
  return { ok: false };
276
343
  }
277
344
  }
345
+ runtimeOverrides[key] = value;
278
346
  invalidateCache();
279
347
  notifyStatusChanged();
280
348
  return { ok: true };
@@ -293,6 +361,13 @@ export async function setup(ctx) {
293
361
  trackBackgroundTask(run.then(() => { }));
294
362
  return { status: "started" };
295
363
  },
364
+ resetMemory: async (input) => {
365
+ if (input?.confirm !== true)
366
+ return { ok: false, message: "Reset not confirmed." };
367
+ const result = performMemoryReset();
368
+ notifyStatusChanged();
369
+ return result;
370
+ },
296
371
  });
297
372
  const publishStatus = () => {
298
373
  void statusRegistration.events.emit("changed", {}).catch((err) => {
@@ -366,6 +441,15 @@ export async function setup(ctx) {
366
441
  console.error("[opencode-codex-memory] v2 generate hook error:", err);
367
442
  }
368
443
  });
444
+ // Title requests replay history too; citation markup is noise there.
445
+ await ctx.session.hook("title", (ev) => {
446
+ try {
447
+ handleModelBoundSession(ev, false);
448
+ }
449
+ catch (err) {
450
+ console.error("[opencode-codex-memory] v2 title hook error:", err);
451
+ }
452
+ });
369
453
  await ctx.tool.hook("execute.before", async (ev) => {
370
454
  try {
371
455
  if (!pluginOptions.disable_on_external_context || !ev?.sessionID)
@@ -438,19 +522,39 @@ export async function setup(ctx) {
438
522
  console.error("[opencode-codex-memory] v2 event handling error:", err);
439
523
  }
440
524
  }
441
- break;
525
+ // A stream that ends without dispose (host restart of the bus) must
526
+ // not silently stop phase-1 pumps and citation accounting.
527
+ if (eventAbort.signal.aborted || isPluginShuttingDown())
528
+ break;
442
529
  }
443
530
  catch (err) {
444
531
  if (eventAbort.signal.aborted || isPluginShuttingDown())
445
532
  break;
446
533
  console.error("[opencode-codex-memory] v2 event subscription error:", err);
447
- await new Promise((r) => setTimeout(r, 5000));
448
534
  }
535
+ await abortableSleep(5000, eventAbort.signal);
449
536
  }
450
- })().catch((err) => console.error("[opencode-codex-memory] v2 event loop error:", err));
537
+ })().catch((err) => console.error("[opencode-codex-memory] v2 event loop error:", err))
538
+ .finally(() => eventLoops.delete(eventAbort));
539
+ eventLoops.add(eventAbort);
540
+ liveInstances.push(ctx);
451
541
  return () => {
452
542
  statusListeners.delete(publishStatus);
453
543
  eventAbort.abort();
544
+ const index = liveInstances.indexOf(ctx);
545
+ if (index >= 0)
546
+ liveInstances.splice(index, 1);
547
+ const survivor = liveInstances.at(-1);
548
+ if (survivor) {
549
+ // Only the newest location owns the shim; re-point when it leaves.
550
+ if (index === liveInstances.length) {
551
+ setV2Context(survivor);
552
+ setSubSessionDirectory(survivor.location.directory);
553
+ }
554
+ return;
555
+ }
556
+ for (const key of Object.keys(runtimeOverrides))
557
+ delete runtimeOverrides[key];
454
558
  beginPluginShutdown();
455
559
  setSubSessionDirectory();
456
560
  setV2Context(null);
@@ -198,7 +198,8 @@ async function probeEndpoint(deps, endpoint, client, signal) {
198
198
  export function isLoopbackEndpointUrl(url) {
199
199
  try {
200
200
  const hostname = new URL(url).hostname;
201
- return hostname === "127.0.0.1" || hostname === "localhost" || hostname === "::1";
201
+ // WHATWG URL keeps IPv6 brackets in hostname.
202
+ return hostname === "127.0.0.1" || hostname === "localhost" || hostname === "[::1]" || hostname === "::1";
202
203
  }
203
204
  catch {
204
205
  return false;
@@ -295,11 +295,17 @@ async function loadV2Messages(sessionID, context, signal) {
295
295
  cursor = next;
296
296
  }
297
297
  }
298
+ // session.context is the model context from the latest completed compaction
299
+ // on, not the full transcript: the originals before it are gone here, so
300
+ // the compaction summary is the only record of them. (message.list above
301
+ // keeps the originals; there the summary would duplicate them.)
298
302
  const raw = await (context ?? ctx()).session.context({ sessionID });
299
303
  const rows = responseRows(raw);
300
304
  if (!rows)
301
305
  throw new Error("session context returned an invalid message list");
302
- return rows;
306
+ return rows.map((m) => m?.type === "compaction" && typeof m.summary === "string" && typeof m.text !== "string"
307
+ ? { ...m, text: `[Summary of earlier conversation]\n${m.summary}` }
308
+ : m);
303
309
  }
304
310
  function completedPromptResponse(rows, promptID) {
305
311
  const boundary = typeof promptID === "string" ? rows.findIndex((m) => m?.id === promptID && m.type === "user") : -1;
@@ -342,6 +348,21 @@ function adaptV2SessionRow(row) {
342
348
  // ---------------------------------------------------------------------------
343
349
  // The façade: V1-shaped client over the V2 context
344
350
  // ---------------------------------------------------------------------------
351
+ /** Race a promise against a (possibly long-lived) signal without leaking listeners. */
352
+ function raceAbort(promise, signal) {
353
+ let onAbort;
354
+ const aborted = new Promise((_, reject) => {
355
+ onAbort = () => reject(new Error("sub-agent prompt cancelled"));
356
+ if (signal.aborted)
357
+ onAbort();
358
+ else
359
+ signal.addEventListener("abort", onAbort, { once: true });
360
+ });
361
+ return Promise.race([promise, aborted]).finally(() => {
362
+ if (onAbort)
363
+ signal.removeEventListener("abort", onAbort);
364
+ });
365
+ }
345
366
  async function v2promptWithWait(sessionID, body, signal) {
346
367
  const c = ctx();
347
368
  const text = body.parts.map((p) => p.text ?? "").join("\n");
@@ -381,14 +402,7 @@ async function v2promptWithWait(sessionID, body, signal) {
381
402
  }
382
403
  // ctx.generate.text ignores request-option signals. Race AbortSignal.
383
404
  const genP = c.generate.text(payload);
384
- const gen = signal
385
- ? await Promise.race([
386
- genP,
387
- new Promise((_, reject) => {
388
- signal.addEventListener("abort", () => reject(new Error("sub-agent prompt cancelled")), { once: true });
389
- }),
390
- ])
391
- : await genP;
405
+ const gen = signal ? await raceAbort(genP, signal) : await genP;
392
406
  const outText = typeof gen?.text === "string" ? gen.text : JSON.stringify(gen);
393
407
  return { data: { parts: [{ type: "text", text: outText }] } };
394
408
  }
@@ -416,12 +430,7 @@ async function v2promptWithWait(sessionID, body, signal) {
416
430
  await waitP.catch(() => { });
417
431
  throw new Error("sub-agent prompt cancelled");
418
432
  }
419
- await Promise.race([
420
- waitP,
421
- new Promise((_, reject) => {
422
- signal.addEventListener("abort", () => reject(new Error("sub-agent prompt cancelled")), { once: true });
423
- }),
424
- ]).catch(async (e) => {
433
+ await raceAbort(waitP, signal).catch(async (e) => {
425
434
  await c.session.interrupt({ sessionID }).catch(() => { });
426
435
  await waitP.catch(() => { });
427
436
  throw e;
@@ -538,7 +547,13 @@ export function buildV1ClientShim() {
538
547
  return await v2promptWithWait(opts.path.id, opts.body, opts.signal);
539
548
  }
540
549
  catch (e) {
541
- return { error: e instanceof Error ? { message: e.message } : e };
550
+ // Keep the HTTP status: an undeclared 429 surfaces as ClientError
551
+ // "UnexpectedStatus" whose message alone misses the capacity breaker.
552
+ if (!(e instanceof Error))
553
+ return { error: e };
554
+ const status = e.status
555
+ ?? e.cause?.status;
556
+ return { error: { message: e.message, ...(typeof status === "number" ? { statusCode: status } : {}) } };
542
557
  }
543
558
  },
544
559
  messages: async (opts) => {
@@ -558,61 +573,52 @@ export function buildV1ClientShim() {
558
573
  markReleased(opts.path.id);
559
574
  return {};
560
575
  }
561
- let shutdownError;
562
- try {
563
- const client = await serviceOrThrow();
564
- if (typeof client.session.remove !== "function")
565
- throw new Error("registered service does not support session.remove");
566
- const result = await serviceRequest(client, () => client.session.remove({ sessionID: opts.path.id }, opts.signal ? { signal: opts.signal } : undefined));
567
- if (result?.error)
568
- throw result.error;
569
- if (await sessionGoneOnService(client, opts.path.id)) {
570
- markReleased(opts.path.id);
571
- return {};
572
- }
573
- throw new Error("session still exists after remove");
574
- }
575
- catch (error) {
576
- shutdownError = error;
577
- }
576
+ const id = opts.path.id;
577
+ // Interrupt where the helper runs first. With a loopback PID mismatch the
578
+ // service is another process: removing the row there alone would leave
579
+ // this process's consolidator editing after the lease is released.
580
+ let interruptError;
578
581
  try {
579
582
  const session = ctx().session;
580
- const interrupt = await session.interrupt({ sessionID: opts.path.id });
583
+ const interrupt = await session.interrupt({ sessionID: id });
581
584
  if (interrupt?.error)
582
585
  throw interrupt.error;
583
586
  if (typeof session.wait === "function")
584
- await session.wait({ sessionID: opts.path.id });
587
+ await session.wait({ sessionID: id });
585
588
  }
586
- catch (interruptError) {
587
- return { error: shutdownError ?? interruptError };
589
+ catch (error) {
590
+ interruptError = error ?? new Error("session interrupt failed");
588
591
  }
592
+ let client = null;
593
+ let removeError;
589
594
  try {
590
- const client = await ownServiceClient();
591
- if (client?.session?.get) {
592
- const info = await serviceRequest(client, () => client.session.get({ sessionID: opts.path.id }));
593
- if (info?.error && isNotFoundError(info.error)) {
594
- markReleased(opts.path.id);
595
- return {};
596
- }
597
- const data = und(info);
598
- if (data && typeof data === "object") {
599
- return { error: shutdownError ?? new Error("session still exists after interrupt") };
600
- }
601
- return { error: shutdownError ?? new Error("session still exists after interrupt") };
595
+ client = await ownServiceClient();
596
+ if (client) {
597
+ if (typeof client.session.remove !== "function")
598
+ throw new Error("registered service does not support session.remove");
599
+ const service = client;
600
+ const result = await serviceRequest(service, () => service.session.remove({ sessionID: id }, opts.signal ? { signal: opts.signal } : undefined));
601
+ if (result?.error)
602
+ throw result.error;
602
603
  }
603
- // Isolated serve: no session.remove on plugin ctx. interrupt+wait already
604
- // finished, so the helper is idle. Holding the phase-2 lease until it
605
- // expires would block consolidation for an hour.
606
- markReleased(opts.path.id);
607
- return {};
608
604
  }
609
- catch (e) {
610
- if (isNotFoundError(e)) {
611
- markReleased(opts.path.id);
605
+ catch (error) {
606
+ removeError = error;
607
+ }
608
+ if (client && typeof client.session.get === "function") {
609
+ if (await sessionGoneOnService(client, id)) {
610
+ markReleased(id);
612
611
  return {};
613
612
  }
614
- return { error: shutdownError ?? e };
613
+ return { error: removeError ?? interruptError ?? new Error("session still exists after remove") };
615
614
  }
615
+ if (interruptError !== undefined)
616
+ return { error: removeError ?? interruptError };
617
+ // Isolated serve: no session.remove on plugin ctx. interrupt+wait already
618
+ // finished, so the helper is idle. Holding the phase-2 lease until it
619
+ // expires would block consolidation for an hour.
620
+ markReleased(id);
621
+ return {};
616
622
  },
617
623
  get: async (opts) => {
618
624
  try {
@@ -643,19 +649,20 @@ export function buildV1ClientShim() {
643
649
  abort: async (opts) => {
644
650
  if (opts.path.id === EXTRACT_STUB_SESSION_ID)
645
651
  return {};
652
+ // Local first: the helper runs in this process (see delete above).
646
653
  try {
647
- const client = await serviceOrThrow();
648
- if (typeof client.session.interrupt !== "function")
649
- throw new Error("registered service does not support session.interrupt");
650
- const result = await serviceRequest(client, () => client.session.interrupt({ sessionID: opts.path.id }));
654
+ const result = await ctx().session.interrupt({ sessionID: opts.path.id });
651
655
  if (!result?.error)
652
656
  return {};
653
657
  }
654
658
  catch {
655
- // Fall through to the context-local interrupt below.
659
+ // Fall through to the registered service.
656
660
  }
657
661
  try {
658
- await ctx().session.interrupt({ sessionID: opts.path.id });
662
+ const client = await ownServiceClient();
663
+ if (client && typeof client.session.interrupt === "function") {
664
+ await serviceRequest(client, () => client.session.interrupt({ sessionID: opts.path.id }));
665
+ }
659
666
  }
660
667
  catch {
661
668
  // Best-effort, mirrors V1.
@@ -22,6 +22,10 @@ export interface MemoryStatus {
22
22
  extracting: number;
23
23
  phase2Status: string | null;
24
24
  lastError: string | null;
25
+ /** Unix milliseconds; optional for older servers. Cooldown is not a retry. */
26
+ phase2CooldownUntil?: number | null;
27
+ phase1RetryAt?: number | null;
28
+ phase2RetryAt?: number | null;
25
29
  }[];
26
30
  useMemories: boolean;
27
31
  generateMemories: boolean;
@@ -117,6 +121,15 @@ export declare const MemoryStatusRpc: {
117
121
  readonly lastError: {
118
122
  readonly type: readonly ["string", "null"];
119
123
  };
124
+ readonly phase2CooldownUntil: {
125
+ readonly type: readonly ["number", "null"];
126
+ };
127
+ readonly phase1RetryAt: {
128
+ readonly type: readonly ["number", "null"];
129
+ };
130
+ readonly phase2RetryAt: {
131
+ readonly type: readonly ["number", "null"];
132
+ };
120
133
  };
121
134
  readonly required: readonly ["version", "stage1Count", "extracting", "phase2Status", "lastError"];
122
135
  readonly additionalProperties: false;
@@ -249,6 +262,32 @@ export declare const MemoryStatusRpc: {
249
262
  readonly additionalProperties: false;
250
263
  };
251
264
  };
265
+ /** Same wipe as the V1 memory_reset tool; the panel's confirm step is the approval. */
266
+ readonly resetMemory: {
267
+ readonly input: {
268
+ readonly type: "object";
269
+ readonly properties: {
270
+ readonly confirm: {
271
+ readonly type: "boolean";
272
+ };
273
+ };
274
+ readonly required: readonly ["confirm"];
275
+ readonly additionalProperties: false;
276
+ };
277
+ readonly output: {
278
+ readonly type: "object";
279
+ readonly properties: {
280
+ readonly ok: {
281
+ readonly type: "boolean";
282
+ };
283
+ readonly message: {
284
+ readonly type: "string";
285
+ };
286
+ };
287
+ readonly required: readonly ["ok", "message"];
288
+ readonly additionalProperties: false;
289
+ };
290
+ };
252
291
  };
253
292
  readonly events: {
254
293
  readonly changed: {
@@ -60,6 +60,9 @@ export const MemoryStatusRpc = {
60
60
  extracting: { type: "integer", minimum: 0 },
61
61
  phase2Status: { type: ["string", "null"] },
62
62
  lastError: { type: ["string", "null"] },
63
+ phase2CooldownUntil: { type: ["number", "null"] },
64
+ phase1RetryAt: { type: ["number", "null"] },
65
+ phase2RetryAt: { type: ["number", "null"] },
63
66
  },
64
67
  required: ["version", "stage1Count", "extracting", "phase2Status", "lastError"],
65
68
  additionalProperties: false,
@@ -130,6 +133,21 @@ export const MemoryStatusRpc = {
130
133
  additionalProperties: false,
131
134
  },
132
135
  },
136
+ /** Same wipe as the V1 memory_reset tool; the panel's confirm step is the approval. */
137
+ resetMemory: {
138
+ input: {
139
+ type: "object",
140
+ properties: { confirm: { type: "boolean" } },
141
+ required: ["confirm"],
142
+ additionalProperties: false,
143
+ },
144
+ output: {
145
+ type: "object",
146
+ properties: { ok: { type: "boolean" }, message: { type: "string" } },
147
+ required: ["ok", "message"],
148
+ additionalProperties: false,
149
+ },
150
+ },
133
151
  },
134
152
  events: {
135
153
  changed: { schema: { type: "object", properties: {}, additionalProperties: false } },
@@ -162,7 +180,8 @@ export function isMemoryStatus(value) {
162
180
  && Number.isInteger(pipeline.stage1Count) && pipeline.stage1Count >= 0
163
181
  && Number.isInteger(pipeline.extracting) && pipeline.extracting >= 0
164
182
  && (pipeline.phase2Status === null || typeof pipeline.phase2Status === "string")
165
- && (pipeline.lastError === null || typeof pipeline.lastError === "string")))
183
+ && (pipeline.lastError === null || typeof pipeline.lastError === "string")
184
+ && ["phase2CooldownUntil", "phase1RetryAt", "phase2RetryAt"].every((key) => pipeline[key] === undefined || pipeline[key] === null || (typeof pipeline[key] === "number" && Number.isFinite(pipeline[key])))))
166
185
  return false;
167
186
  for (const key of ["extractModel", "consolidationModel", "lastSuccessAt", "retryAt"]) {
168
187
  const v = value[key];
@@ -1,4 +1,4 @@
1
- import { MemoryStore } from "../store.js";
1
+ import { MemoryStore, existingMemoryStores, PHASE2_COOLDOWN_MS } from "../store.js";
2
2
  import { pluginOptions, getConfigWarnings } from "../options.js";
3
3
  import { getAgentHealth } from "../agent-health.js";
4
4
  import { isPhase2InFlight } from "../phase2.js";
@@ -7,7 +7,7 @@ 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";
10
+ import { readMigrationStatus } from "../migration.js";
11
11
  import { peekSessionMemoryVersion } from "../session-version.js";
12
12
  import { withMemoryVersion, writeMemoryVersions } from "../memory-version.js";
13
13
  import { getV2DiscoveryStatus } from "./shim.js";
@@ -15,27 +15,44 @@ import { getV2DiscoveryStatus } from "./shim.js";
15
15
  export function readMemoryStatus(sessionID, minConsolidatedThreads) {
16
16
  const sessionVersion = peekSessionMemoryVersion(sessionID);
17
17
  const store = withMemoryVersion(sessionVersion, () => new MemoryStore());
18
- const pipelines = memoryPipelineSnapshots().map((pipeline) => ({
19
- version: pipeline.version,
20
- stage1Count: pipeline.stage1Count,
21
- extracting: pipeline.stage1Jobs.running ?? 0,
22
- phase2Status: pipeline.phase2?.status ?? null,
23
- lastError: pipeline.phase2?.last_error ?? null,
24
- }));
25
- const active = pipelines.filter((pipeline) => writeMemoryVersions().includes(pipeline.version));
26
18
  const options = pluginOptions;
27
19
  const now = Date.now();
28
20
  const staleBeforeSec = Math.floor(now / 1000) - options.max_rollout_age_days * 86_400;
29
- const phase1 = store.stage1JobSnapshot(staleBeforeSec);
21
+ const snapshots = existingMemoryStores().map((pipelineStore) => ({
22
+ version: pipelineStore.version,
23
+ stage1Count: pipelineStore.stage1OutputCount(),
24
+ phase1: pipelineStore.stage1JobSnapshot(staleBeforeSec),
25
+ phase2: pipelineStore.phase2JobSnapshot(),
26
+ }));
27
+ const nextRetry = (times) => {
28
+ const future = times.filter((time) => time != null && time * 1000 > now);
29
+ return future.length ? Math.min(...future) * 1000 : null;
30
+ };
31
+ const pipelines = snapshots.map((pipeline) => {
32
+ const cooldown = pipeline.phase2?.success_finished_at == null
33
+ ? null : pipeline.phase2.success_finished_at * 1000 + PHASE2_COOLDOWN_MS;
34
+ return {
35
+ version: pipeline.version,
36
+ stage1Count: pipeline.stage1Count,
37
+ extracting: pipeline.phase1.by_status.running ?? 0,
38
+ phase2Status: pipeline.phase2?.status ?? null,
39
+ lastError: pipeline.phase2?.last_error ?? null,
40
+ phase2CooldownUntil: cooldown !== null && cooldown > now ? cooldown : null,
41
+ phase1RetryAt: nextRetry(pipeline.phase1.recent_errors
42
+ .filter((error) => error.failure_class === "backoff" || error.failure_class === "provider_capacity")
43
+ .map((error) => error.retry_at)),
44
+ phase2RetryAt: nextRetry([pipeline.phase2?.retry_at]),
45
+ };
46
+ });
47
+ const active = pipelines.filter((pipeline) => writeMemoryVersions().includes(pipeline.version));
30
48
  const phase2 = store.phase2JobSnapshot();
31
49
  const session = sessionInjection(sessionID);
32
50
  const total = injectionTotals();
33
- const retryTimes = [
51
+ const retryAt = nextRetry([
34
52
  ...activeProviderCapacityBackoffs().map((backoff) => backoff.retry_at),
35
- ...phase1.recent_errors.map((error) => error.retry_at),
36
- phase2?.retry_at,
37
- ].filter((time) => time != null && time * 1000 > now);
38
- const retryAt = retryTimes.length ? Math.min(...retryTimes) * 1000 : null;
53
+ ...active.flatMap((pipeline) => [pipeline.phase1RetryAt, pipeline.phase2RetryAt]
54
+ .map((time) => time === null ? null : time / 1000)),
55
+ ]);
39
56
  const warnings = [...getConfigWarnings()];
40
57
  const discoveryWarning = getV2DiscoveryStatus()?.warning;
41
58
  if (options.generate_memories && discoveryWarning)
@@ -51,13 +68,22 @@ export function readMemoryStatus(sessionID, minConsolidatedThreads) {
51
68
  if (pipeline.version !== sessionVersion && pipeline.lastError)
52
69
  warnings.push(`${pipeline.version}: consolidation failed; see memory_inspect.`);
53
70
  }
54
- if (phase1.by_failure_class.due > 0)
55
- warnings.push("Some extraction jobs are due to retry.");
56
- if (phase1.by_failure_class.other_exhausted > phase1.stale_exhausted) {
57
- warnings.push("Some extraction jobs exhausted their retries.");
71
+ for (const pipeline of snapshots.filter((pipeline) => writeMemoryVersions().includes(pipeline.version))) {
72
+ const phase1 = pipeline.phase1;
73
+ const prefix = `${pipeline.version}: `;
74
+ if (phase1.by_failure_class.backoff > 0) {
75
+ const error = phase1.recent_errors.find((error) => error.failure_class === "backoff");
76
+ const count = phase1.by_failure_class.backoff;
77
+ warnings.push(`${prefix}Extraction retry (${count} ${count === 1 ? "job" : "jobs"})${error ? `: ${error.last_error.slice(0, 200)}` : "."}`);
78
+ }
79
+ if (phase1.by_failure_class.due > 0)
80
+ warnings.push(`${prefix}Some extraction jobs are due to retry.`);
81
+ if (phase1.by_failure_class.other_exhausted > phase1.stale_exhausted) {
82
+ warnings.push(`${prefix}Some extraction jobs exhausted their retries.`);
83
+ }
84
+ if (phase1.by_failure_class.provider_capacity > 0)
85
+ warnings.push(`${prefix}Some extraction jobs hit provider capacity limits.`);
58
86
  }
59
- if (phase1.by_failure_class.provider_capacity > 0)
60
- warnings.push("Some extraction jobs hit provider capacity limits.");
61
87
  const importsV1 = options.codex_interop.import && writeMemoryVersions().includes("v1");
62
88
  const codexImport = importsV1 && withMemoryVersion("v1", () => resolveCodexInterop(options.codex_interop)) !== null;
63
89
  if (importsV1 && !codexImport)