opencode-codex-memory 0.12.1 → 0.13.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.
package/dist/src/retry.js CHANGED
@@ -3,6 +3,7 @@ import { isPluginShuttingDown } from "./lifecycle.js";
3
3
  import { pluginOptions } from "./options.js";
4
4
  import { recordDiagnostic } from "./diagnostics.js";
5
5
  import { existingMemoryStores } from "./store.js";
6
+ import { writeMemoryVersions } from "./memory-version.js";
6
7
  const capacity = {
7
8
  state: "blocked",
8
9
  message: "A background model is still rate-limited. Wait for the limit to clear. Backup models can help on future runs.",
@@ -11,47 +12,66 @@ const running = {
11
12
  state: "blocked",
12
13
  message: "Memory work is already running. Try again when it finishes.",
13
14
  };
14
- async function retryExtraction(excludeSession) {
15
- const passes = await retryFailedExtractions(excludeSession);
15
+ function retryExtraction(passes, planned, targetCount) {
16
16
  const completed = passes.filter((pass) => pass.status === "completed");
17
17
  const saved = completed.reduce((total, pass) => total + pass.saved, 0);
18
18
  const noOutput = completed.reduce((total, pass) => total + pass.noOutput, 0);
19
19
  const failed = completed.reduce((total, pass) => total + pass.failed, 0);
20
20
  const interrupted = completed.some((pass) => pass.skipped > 0) || passes.some((pass) => pass.status === "shutting_down");
21
21
  const passFailed = passes.some((pass) => pass.status === "failed");
22
+ const unsuccessful = new Set(completed.flatMap((pass) => pass.retryFailures));
23
+ const processed = new Set(completed.flatMap((pass) => pass.retried).filter((id) => !unsuccessful.has(id))).size;
24
+ const skipped = (targetCount ?? 0) - processed - unsuccessful.size;
25
+ const counts = {
26
+ ...(processed > 0 ? { conversationsProcessed: processed } : {}),
27
+ ...(planned && unsuccessful.size > 0 ? { conversationsFailed: unsuccessful.size } : {}),
28
+ ...(skipped > 0 ? { conversationsSkipped: skipped } : {}),
29
+ };
22
30
  const savedMessage = saved ? `Saved ${saved} ${saved === 1 ? "recap" : "recaps"} for consolidation. ` : "";
31
+ if (passes.some((pass) => pass.status === "generation_disabled"))
32
+ return { ...counts, state: "blocked", message: savedMessage + "Stopped because learning was paused." };
33
+ if (passes.some((pass) => pass.status === "provider_capacity"))
34
+ return { ...counts, state: "blocked", message: savedMessage + capacity.message };
23
35
  if (failed || passFailed) {
24
36
  return {
25
37
  state: "failed",
26
- message: `${savedMessage}Some attempts still failed. Check the latest diagnostics in the panel or memory_inspect.`,
38
+ ...counts,
39
+ message: `${savedMessage}${counts.conversationsFailed ? "" : "Some attempts still failed. "}See the latest diagnostics in the panel or memory_inspect.`,
27
40
  };
28
41
  }
29
42
  if (passes.some((pass) => pass.status === "discovery_failed"))
30
43
  return {
31
44
  state: "blocked",
45
+ ...counts,
32
46
  message: savedMessage + "Couldn’t list conversations. Check the OpenCode service, then retry.",
33
47
  };
34
- if (passes.some((pass) => pass.status === "provider_capacity"))
35
- return { state: "blocked", message: savedMessage + capacity.message };
36
48
  if (passes.some((pass) => pass.status === "already_running"))
37
- return { state: "blocked", message: savedMessage + running.message };
49
+ return { ...counts, state: "blocked", message: savedMessage + running.message };
38
50
  if (interrupted)
39
- return { state: "blocked", message: savedMessage + "The retry was interrupted. Try again when OpenCode is ready." };
51
+ return {
52
+ ...counts,
53
+ state: "blocked",
54
+ message: savedMessage + "The retry was interrupted. Try again when OpenCode is ready.",
55
+ };
40
56
  if (saved || noOutput) {
41
57
  return {
42
58
  state: "completed",
59
+ ...counts,
43
60
  message: saved
44
61
  ? `${savedMessage}Memory will update on the next eligible consolidation.`
45
62
  : "Extraction finished. There was no new memory to save.",
46
63
  };
47
64
  }
48
65
  return {
66
+ ...counts,
49
67
  state: "blocked",
50
- message: "No failed sessions were eligible. Check learning preferences, idle and age limits, and provider backoff.",
68
+ message: planned
69
+ ? "No failed conversations are ready to retry."
70
+ : "No failed sessions were eligible. Check learning preferences, idle and age limits, and provider backoff.",
51
71
  };
52
72
  }
53
- async function retryConsolidation() {
54
- const results = await runMemoryConsolidation(true);
73
+ async function retryConsolidation(canStart) {
74
+ const results = await runMemoryConsolidation(true, canStart);
55
75
  const succeeded = results.some((status) => status === "succeeded" || status === "no_workspace_changes");
56
76
  const remains = results.filter((status) => !["succeeded", "no_workspace_changes", "skipped_no_failure"].includes(status));
57
77
  if (!remains.length)
@@ -75,12 +95,49 @@ async function retryConsolidation() {
75
95
  message: prefix + "Consolidation still failed. Check the latest error before retrying again.",
76
96
  };
77
97
  }
98
+ async function updateMemory(run) {
99
+ const outcomes = await run();
100
+ const updated = outcomes.includes("succeeded");
101
+ const skipped = outcomes.filter((result) => result !== "succeeded" && result !== "no_workspace_changes");
102
+ if (!skipped.length)
103
+ return { state: "completed", message: updated ? "Memory updated." : "No changes to consolidate." };
104
+ const prefix = updated ? "One memory version was updated. " : "";
105
+ if (skipped.every((result) => result === "generation_disabled"))
106
+ return { state: "blocked", message: prefix + "Stopped because learning was paused." };
107
+ if (skipped.every((result) => result === "skipped_retry_unavailable")) {
108
+ const writers = writeMemoryVersions();
109
+ const times = existingMemoryStores().flatMap((store) => {
110
+ if (outcomes[writers.indexOf(store.version)] !== "skipped_retry_unavailable")
111
+ return [];
112
+ const retryAt = store.phase2JobSnapshot()?.retry_at;
113
+ return retryAt == null ? [] : [retryAt * 1000];
114
+ });
115
+ const until = times.length ? ` until ${new Date(Math.min(...times)).toLocaleString()}` : "";
116
+ return {
117
+ state: "blocked",
118
+ message: prefix + `An earlier update is waiting to retry${until}. Use Retry consolidation to try now if offered.`,
119
+ };
120
+ }
121
+ if (skipped.every((result) => result === "skipped_rate_limit"))
122
+ return { state: "blocked", message: prefix + "Consolidation is waiting for the provider rate limit to clear." };
123
+ if (skipped.every((result) => result === "skipped_running" || result === "already_running"))
124
+ return { state: "blocked", message: prefix + running.message };
125
+ if (skipped.every((result) => result === "shutting_down"))
126
+ return { state: "blocked", message: prefix + "The update was interrupted because OpenCode is stopping." };
127
+ return {
128
+ state: "failed",
129
+ message: prefix + "Memory did not finish updating. See the consolidation status for details.",
130
+ };
131
+ }
78
132
  const listeners = new Set();
79
133
  let activeRetry;
80
134
  let latestRetry = null;
81
135
  let finishedAt;
82
136
  export function memoryRetryStatus(maxAgeMs = Infinity) {
83
- if (!latestRetry || (finishedAt !== undefined && Date.now() - finishedAt >= maxAgeMs))
137
+ if (!latestRetry)
138
+ return null;
139
+ const completedExtraction = latestRetry.phase === "extraction" && latestRetry.state === "completed";
140
+ if (!completedExtraction && finishedAt !== undefined && Date.now() - finishedAt >= maxAgeMs)
84
141
  return null;
85
142
  return { ...latestRetry };
86
143
  }
@@ -116,25 +173,47 @@ export async function waitForMemoryRetry() {
116
173
  await activeRetry;
117
174
  }
118
175
  /** Same process-wide retry for panel actions and tools. Callers may await the outcome or read status. */
119
- export function requestMemoryRetry(phase, excludeSession) {
176
+ export function requestMemoryRetry(phase, excludeSession, options) {
177
+ const message = phase === "consolidation"
178
+ ? "Retrying the failed memory update with the current background models."
179
+ : options?.all
180
+ ? "Checking all failed conversations for retry eligibility."
181
+ : "Retrying a batch of failed sessions with the current background models.";
182
+ return requestMemoryWork(phase, message, async (progress) => {
183
+ if (phase === "consolidation")
184
+ return retryConsolidation(options?.canStart);
185
+ if (!options?.extraction)
186
+ return retryExtraction(await retryFailedExtractions(excludeSession), false);
187
+ const { passes, targetCount } = await options.extraction(progress);
188
+ return retryExtraction(passes, true, targetCount);
189
+ });
190
+ }
191
+ export function requestMemoryUpdate(run) {
192
+ return requestMemoryWork("consolidation", "Processing eligible conversations and consolidating memory.", () => updateMemory(run), "update");
193
+ }
194
+ function requestMemoryWork(phase, initialMessage, run, action) {
120
195
  const message = memoryRetryBlockedReason();
121
196
  if (message)
122
197
  return { ok: false, message };
123
- latestRetry = {
198
+ const operation = {
199
+ ...(action ? { action } : {}),
124
200
  phase,
125
- state: "running",
126
- message: phase === "extraction"
127
- ? "Retrying a batch of failed sessions with the current background models."
128
- : "Retrying the failed memory update with the current background models.",
129
201
  };
202
+ latestRetry = { ...operation, state: "running", message: initialMessage };
130
203
  finishedAt = undefined;
131
- const completion = (phase === "extraction" ? retryExtraction(excludeSession) : retryConsolidation())
204
+ const completion = run((message) => {
205
+ latestRetry = { ...operation, state: "running", message };
206
+ notify();
207
+ })
132
208
  .catch((error) => {
133
209
  recordDiagnostic("error", "manual-retry", String(error));
134
- return { state: "failed", message: "The retry could not finish. Check memory_inspect for details." };
210
+ return {
211
+ state: "failed",
212
+ message: `The ${action ?? "retry"} could not finish. Check memory_inspect for details.`,
213
+ };
135
214
  })
136
215
  .then((outcome) => {
137
- const result = { phase, ...outcome };
216
+ const result = { ...operation, ...outcome };
138
217
  latestRetry = result;
139
218
  finishedAt = Date.now();
140
219
  activeRetry = undefined;
@@ -43,6 +43,10 @@ export type Phase2ClaimResult = {
43
43
  type: "skipped_no_failure";
44
44
  };
45
45
  export declare const SHUTDOWN_JOB_ERROR = "plugin shutting down";
46
+ export declare function stage1ProviderBackoff(row: {
47
+ last_error: string;
48
+ retry_at: number | null;
49
+ }, now: number): boolean;
46
50
  /** Wipe jobs/outputs in every versioned DB. Leaves memory_session_meta on memory.db. */
47
51
  export declare function clearAllVersionMemoryData(wipeWorkspace: () => void): void;
48
52
  /** Include inactive existing stores for deletion, reset guards and diagnostics. */
@@ -70,6 +74,11 @@ export declare class MemoryStore {
70
74
  * context calls, and either observation may happen after a process restart.
71
75
  */
72
76
  recordUsageOnce(sessionId: string, assistantMessageId: string, citedSessionIds: string[]): string[];
77
+ stage1RetryJobs(): {
78
+ job_key: string;
79
+ last_error: string;
80
+ retry_at: number | null;
81
+ }[];
73
82
  claimStage1Jobs(sessions: ClaimableSession[], excludeSession?: string, maxClaimed?: number, retryFailed?: boolean): Stage1Claim[];
74
83
  markStage1Succeeded(sessionId: string, ownershipToken: string, out: Omit<Stage1Output, "usage_count" | "last_usage">): boolean;
75
84
  /** Extraction succeeded but produced nothing worth keeping: finish the job and drop any stale output. */
@@ -191,8 +200,9 @@ export declare class MemoryStore {
191
200
  * (typically now − max_rollout_age_days) are counted in `stale_exhausted`
192
201
  * and omitted from `recent_errors` so leftover rows from old plugin
193
202
  * versions do not bury live due/backoff failures.
203
+ * `includeExhausted` scopes the actionable backlog without hiding diagnostics.
194
204
  */
195
- stage1JobSnapshot(staleBeforeSec?: number): {
205
+ stage1JobSnapshot(staleBeforeSec?: number, includeExhausted?: (sessionID: string) => boolean): {
196
206
  by_status: Record<string, number>;
197
207
  by_failure_class: {
198
208
  backoff: number;
@@ -203,6 +213,8 @@ export declare class MemoryStore {
203
213
  stale_exhausted: number;
204
214
  recent_errors: Stage1RecentError[];
205
215
  latest_exhausted: Stage1RecentError | null;
216
+ exhausted_session_ids: string[];
217
+ latest_success_at: number | null;
206
218
  next_retry_at: number | null;
207
219
  active_claims: number;
208
220
  };
@@ -212,6 +224,7 @@ export interface Stage1RecentError {
212
224
  session_id: string;
213
225
  last_error: string;
214
226
  retry_at: number | null;
227
+ finished_at: number | null;
215
228
  status: string;
216
229
  retry_remaining: number;
217
230
  failure_class: Stage1FailureClass | null;
package/dist/src/store.js CHANGED
@@ -14,6 +14,11 @@ export const STAGE1_CONCURRENCY = 8;
14
14
  export const SCAN_LIMIT = 5000;
15
15
  export const PRUNE_BATCH_SIZE = 200;
16
16
  export const SHUTDOWN_JOB_ERROR = "plugin shutting down";
17
+ const STAGE1_RETRY_JOBS = `SELECT job_key, last_error, retry_at FROM memory_jobs
18
+ WHERE kind='memory_stage1' AND status IN ('failed', 'pending') AND last_error IS NOT NULL AND last_error != ?`;
19
+ export function stage1ProviderBackoff(row, now) {
20
+ return row.retry_at != null && row.retry_at > now && isProviderCapacityError(row.last_error);
21
+ }
17
22
  function clearJobTables(db) {
18
23
  db.transaction(() => {
19
24
  db.run("DELETE FROM memory_stage1_outputs");
@@ -210,6 +215,11 @@ export class MemoryStore {
210
215
  .immediate();
211
216
  return fresh;
212
217
  }
218
+ stage1RetryJobs() {
219
+ return this.db
220
+ .query(STAGE1_RETRY_JOBS)
221
+ .all(SHUTDOWN_JOB_ERROR);
222
+ }
213
223
  claimStage1Jobs(sessions, excludeSession, maxClaimed, retryFailed = false) {
214
224
  const workerId = newId();
215
225
  // Cap per-pass claims at codex's max_rollouts_per_startup (max_claimed,
@@ -219,22 +229,15 @@ export class MemoryStore {
219
229
  const claimCap = Math.max(1, maxClaimed ?? 2);
220
230
  const manual = retryFailed ? 1 : 0;
221
231
  const claimed = [];
222
- const failedJobs = `SELECT job_key, last_error, retry_at FROM memory_jobs
223
- WHERE kind='memory_stage1' AND status IN ('failed', 'pending') AND last_error IS NOT NULL AND last_error != ?`;
224
232
  const failure = retryFailed
225
- ? this.db.query(`${failedJobs} AND job_key = ?`)
226
- : null;
227
- const failedIDs = retryFailed
228
- ? new Set(this.db
229
- .query(failedJobs)
230
- .all(SHUTDOWN_JOB_ERROR)
231
- .map((row) => row.job_key))
233
+ ? this.db.query(`${STAGE1_RETRY_JOBS} AND job_key = ?`)
232
234
  : null;
235
+ const failedIDs = retryFailed ? new Set(this.stage1RetryJobs().map((row) => row.job_key)) : null;
233
236
  const claimOne = this.db.transaction((s, ownershipToken, lease) => {
234
237
  const startedAt = nowSec();
235
238
  if (failure) {
236
239
  const row = failure.get(SHUTDOWN_JOB_ERROR, s.id);
237
- if (!row || (row.retry_at != null && row.retry_at > startedAt && isProviderCapacityError(row.last_error)))
240
+ if (!row || stage1ProviderBackoff(row, startedAt))
238
241
  return false;
239
242
  if (this.getMemoryMode(s.id) === "disabled" || this.isPolluted(s.id))
240
243
  return false;
@@ -796,11 +799,13 @@ export class MemoryStore {
796
799
  * (typically now − max_rollout_age_days) are counted in `stale_exhausted`
797
800
  * and omitted from `recent_errors` so leftover rows from old plugin
798
801
  * versions do not bury live due/backoff failures.
802
+ * `includeExhausted` scopes the actionable backlog without hiding diagnostics.
799
803
  */
800
- stage1JobSnapshot(staleBeforeSec) {
804
+ stage1JobSnapshot(staleBeforeSec, includeExhausted) {
801
805
  const tNow = nowSec();
802
806
  const rows = this.db
803
- .prepare(`SELECT status, COUNT(*) AS c, COUNT(CASE WHEN lease_until IS NULL OR lease_until > ? THEN 1 END) AS active
807
+ .prepare(`SELECT status, COUNT(*) AS c, MAX(finished_at) AS latest_finished_at,
808
+ COUNT(CASE WHEN lease_until IS NULL OR lease_until > ? THEN 1 END) AS active
804
809
  FROM memory_jobs WHERE kind='memory_stage1' GROUP BY status`)
805
810
  .all(tNow);
806
811
  const by_status = {};
@@ -823,6 +828,7 @@ export class MemoryStore {
823
828
  session_id: row.session_id,
824
829
  last_error: row.last_error,
825
830
  retry_at: row.retry_at,
831
+ finished_at: row.finished_at,
826
832
  status: row.status,
827
833
  retry_remaining: row.retry_remaining,
828
834
  failure_class,
@@ -840,6 +846,7 @@ export class MemoryStore {
840
846
  live.push(entry);
841
847
  }
842
848
  live.sort((a, b) => liveErrorRank(a.failure_class) - liveErrorRank(b.failure_class));
849
+ const exhausted = live.filter((error) => error.failure_class === "other_exhausted" && (includeExhausted?.(error.session_id) ?? true));
843
850
  return {
844
851
  by_status,
845
852
  active_claims: rows.find((row) => row.status === "running")?.active ?? 0,
@@ -847,7 +854,9 @@ export class MemoryStore {
847
854
  stale_exhausted,
848
855
  recent_errors: live.slice(0, 5),
849
856
  // Due jobs can fill recent_errors; the panel still needs an affected session.
850
- latest_exhausted: live.find((error) => error.failure_class === "other_exhausted") ?? null,
857
+ latest_exhausted: exhausted[0] ?? null,
858
+ exhausted_session_ids: exhausted.map((error) => error.session_id),
859
+ latest_success_at: rows.find((row) => row.status === "done")?.latest_finished_at ?? null,
851
860
  next_retry_at: nextRetryAt,
852
861
  };
853
862
  }
@@ -0,0 +1,8 @@
1
+ import type { ExtractionQueue, MemoryRetryPhase } from "../recovery-info.js";
2
+ export declare function pauseMemoryLearning(): void;
3
+ export declare function memoryLearningPermit(): () => boolean;
4
+ export declare function clearRetryQueue(): void;
5
+ export declare function inspectExtractionQueue(excludeSession?: string): Promise<ExtractionQueue>;
6
+ export declare function requestV2MemoryRetry(phase: MemoryRetryPhase, excludeSession?: string, all?: boolean): import("../recovery-info.js").MemoryRetryRequest;
7
+ /** Status stays responsive while an uncached host session list is being fetched. */
8
+ export declare function extractionQueue(onChange: () => void): ExtractionQueue;
@@ -0,0 +1,174 @@
1
+ import { cachedRecentSessions, filterEligibleSessions, listRecentSessions } from "../capture.js";
2
+ import { getDiscoveryStatus } from "../diagnostics.js";
3
+ import { isPluginShuttingDown } from "../lifecycle.js";
4
+ import { writeMemoryVersions } from "../memory-version.js";
5
+ import { pluginOptions } from "../options.js";
6
+ import { retryFailedExtractions } from "../pipeline.js";
7
+ import { isProviderCapacityBlocked } from "../ratelimit.js";
8
+ import { requestMemoryRetry } from "../retry.js";
9
+ import { existingMemoryStores, SCAN_LIMIT, stage1ProviderBackoff } from "../store.js";
10
+ let learningEpoch = 0;
11
+ const retryOrder = new Map();
12
+ let order = 0;
13
+ let preview;
14
+ let previewFailedAt = -Infinity;
15
+ export function pauseMemoryLearning() {
16
+ learningEpoch++;
17
+ }
18
+ export function memoryLearningPermit() {
19
+ const epoch = learningEpoch;
20
+ return () => epoch === learningEpoch && pluginOptions.generate_memories;
21
+ }
22
+ export function clearRetryQueue() {
23
+ retryOrder.clear();
24
+ order = 0;
25
+ previewFailedAt = -Infinity;
26
+ }
27
+ function planExtraction(rows, excludeSession) {
28
+ const now = Date.now();
29
+ const rowsByID = new Map(rows.map((row) => [row.id, row]));
30
+ const candidates = {};
31
+ const ready = new Set();
32
+ const waitingForIdle = new Set();
33
+ const failed = new Set();
34
+ const writers = writeMemoryVersions();
35
+ const capacityBlocked = isProviderCapacityBlocked("phase1", pluginOptions.extract_model, now);
36
+ for (const store of existingMemoryStores()) {
37
+ if (!writers.includes(store.version))
38
+ continue;
39
+ const candidateRows = [];
40
+ for (const job of store.stage1RetryJobs()) {
41
+ const id = job.job_key;
42
+ if (id === excludeSession || store.getMemoryMode(id) === "disabled" || store.isPolluted(id))
43
+ continue;
44
+ failed.add(id);
45
+ const row = rowsByID.get(id);
46
+ if (!row || capacityBlocked || stage1ProviderBackoff(job, Math.floor(now / 1000)))
47
+ continue;
48
+ candidateRows.push(row);
49
+ }
50
+ const eligibility = {
51
+ maxAgeDays: pluginOptions.max_rollout_age_days,
52
+ minIdleHours: pluginOptions.min_rollout_idle_hours,
53
+ };
54
+ const inWindow = filterEligibleSessions(candidateRows, store, { ...eligibility, minIdleHours: 0 }, now);
55
+ const available = filterEligibleSessions(inWindow, store, eligibility, now);
56
+ const availableIDs = new Set(available.map(({ id }) => id));
57
+ for (const { id } of available)
58
+ ready.add(id);
59
+ for (const { id } of inWindow)
60
+ if (!availableIDs.has(id))
61
+ waitingForIdle.add(id);
62
+ candidates[store.version] = available.sort((a, b) => b.updated_at - a.updated_at);
63
+ }
64
+ for (const id of ready)
65
+ waitingForIdle.delete(id);
66
+ return {
67
+ candidates,
68
+ counts: {
69
+ ready: ready.size,
70
+ waitingForIdle: waitingForIdle.size,
71
+ unavailable: failed.size - ready.size - waitingForIdle.size,
72
+ multipleBatches: writers.some((version) => (candidates[version]?.length ?? 0) > pluginOptions.max_rollouts_per_startup),
73
+ },
74
+ };
75
+ }
76
+ export async function inspectExtractionQueue(excludeSession) {
77
+ const rows = await listRecentSessions(SCAN_LIMIT, true);
78
+ return getDiscoveryStatus()?.ok === false
79
+ ? { ready: null, waitingForIdle: 0, unavailable: 0 }
80
+ : planExtraction(rows, excludeSession).counts;
81
+ }
82
+ export function requestV2MemoryRetry(phase, excludeSession, all = false) {
83
+ const canStart = memoryLearningPermit();
84
+ return requestMemoryRetry(phase, excludeSession, {
85
+ canStart,
86
+ all,
87
+ extraction: (progress) => runExtractionRetries(all, canStart, progress, excludeSession),
88
+ });
89
+ }
90
+ /** Status stays responsive while an uncached host session list is being fetched. */
91
+ export function extractionQueue(onChange) {
92
+ const rows = cachedRecentSessions();
93
+ if (rows)
94
+ return planExtraction(rows).counts;
95
+ if (!preview && Date.now() - previewFailedAt >= 30_000) {
96
+ preview = listRecentSessions()
97
+ .then(() => {
98
+ if (!cachedRecentSessions())
99
+ previewFailedAt = Date.now();
100
+ })
101
+ .finally(() => {
102
+ preview = undefined;
103
+ onChange();
104
+ });
105
+ }
106
+ return { ready: null, waitingForIdle: 0, unavailable: 0, checking: !!preview };
107
+ }
108
+ async function runExtractionRetries(all, canStart, progress, excludeSession) {
109
+ const passes = [];
110
+ const remaining = new Set();
111
+ const attempted = new Set();
112
+ const writers = writeMemoryVersions();
113
+ let total;
114
+ const finish = (status) => {
115
+ if (status)
116
+ passes.push({ status });
117
+ return { passes, targetCount: all ? total : undefined };
118
+ };
119
+ while (true) {
120
+ if (isPluginShuttingDown())
121
+ return finish("shutting_down");
122
+ if (!canStart())
123
+ return finish("generation_disabled");
124
+ if (isProviderCapacityBlocked("phase1", pluginOptions.extract_model))
125
+ return finish("provider_capacity");
126
+ const rows = await listRecentSessions(SCAN_LIMIT, true);
127
+ if (getDiscoveryStatus()?.ok === false)
128
+ return finish("discovery_failed");
129
+ if (!canStart())
130
+ return finish("generation_disabled");
131
+ const { candidates, counts } = planExtraction(rows, excludeSession);
132
+ if (total === undefined) {
133
+ total = counts.ready;
134
+ for (const version of writers)
135
+ for (const row of candidates[version] ?? [])
136
+ remaining.add(`${version}:${row.id}`);
137
+ if (all && total > 0)
138
+ progress(`Retrying ${total} eligible conversations in batches.`);
139
+ }
140
+ const selected = {};
141
+ for (const version of writers) {
142
+ const key = (row) => `${version}:${row.id}`;
143
+ const rank = (row) => retryOrder.get(key(row)) ?? 0;
144
+ const batch = (candidates[version] ?? [])
145
+ .filter((row) => remaining.has(key(row)))
146
+ .sort((a, b) => rank(a) - rank(b))
147
+ .slice(0, pluginOptions.max_rollouts_per_startup);
148
+ for (const row of batch) {
149
+ remaining.delete(key(row));
150
+ retryOrder.delete(key(row));
151
+ retryOrder.set(key(row), ++order);
152
+ }
153
+ selected[version] = batch;
154
+ }
155
+ while (retryOrder.size > 2 * SCAN_LIMIT)
156
+ retryOrder.delete(retryOrder.keys().next().value);
157
+ if (!writers.some((version) => selected[version]?.length))
158
+ break;
159
+ const batchResults = await retryFailedExtractions(excludeSession, selected, canStart);
160
+ passes.push(...batchResults);
161
+ for (const result of batchResults) {
162
+ if (result.status !== "completed")
163
+ continue;
164
+ for (const id of [...result.retried, ...result.retryFailures])
165
+ attempted.add(id);
166
+ }
167
+ if (!all || batchResults.some((result) => result.status === "already_running"))
168
+ break;
169
+ progress(`${attempted.size} of ${total} conversations attempted. Rechecking the remaining batch.`);
170
+ if (remaining.size === 0)
171
+ break;
172
+ }
173
+ return finish();
174
+ }
@@ -1,4 +1,5 @@
1
- import { type MemoryNotice, type MemoryRetryPhase, type MemoryStatus } from "./status-rpc.js";
1
+ export { retryResultText } from "../recovery-info.js";
2
+ import { type MemoryNotice, type MemoryRetry, type MemoryRetryPhase, type MemoryStatus } from "./status-rpc.js";
2
3
  export declare const memoryHelp: {
3
4
  readonly models: {
4
5
  readonly label: "Background model setup";
@@ -40,6 +41,11 @@ export declare const retryLabels: {
40
41
  result: string;
41
42
  };
42
43
  };
44
+ export declare function retryActionLabel(phase: MemoryRetryPhase, status?: MemoryStatus | null): string;
45
+ export declare function retryResultLabel(retry: MemoryRetry): string;
46
+ export declare function retryAllLabel(status?: MemoryStatus | null): string | undefined;
47
+ export declare function extractionRetryUnavailable(status?: MemoryStatus | null): boolean;
48
+ export declare function noticeDetail(notice: MemoryNotice): string;
43
49
  export interface MemoryMessage {
44
50
  title: string;
45
51
  description: string;
@@ -1,6 +1,7 @@
1
1
  import { activeMemoryWork, hasConsolidationLease, remaining } from "./panel-status.js";
2
- import { modelRecoveryGuidance } from "../recovery-info.js";
3
- import { MEMORY_NOTICE_KINDS } from "./status-rpc.js";
2
+ import { extractionQueueText, modelRecoveryGuidance } from "../recovery-info.js";
3
+ export { retryResultText } from "../recovery-info.js";
4
+ import { MEMORY_NOTICE_KINDS, } from "./status-rpc.js";
4
5
  export const memoryHelp = {
5
6
  models: { label: "Background model setup", path: "configuration.md#choose-background-models" },
6
7
  providers: { label: "Open provider settings", path: null },
@@ -18,6 +19,28 @@ export const retryLabels = {
18
19
  extraction: { action: "Retry extraction", result: "Extraction retry" },
19
20
  consolidation: { action: "Retry consolidation", result: "Consolidation retry" },
20
21
  };
22
+ export function retryActionLabel(phase, status) {
23
+ return phase === "extraction" && status?.extractionBacklog?.historical
24
+ ? "Retry next batch"
25
+ : retryLabels[phase].action;
26
+ }
27
+ export function retryResultLabel(retry) {
28
+ return retry.action === "update" ? "Memory update" : retryLabels[retry.phase].result;
29
+ }
30
+ export function retryAllLabel(status) {
31
+ const queue = status?.extractionQueue;
32
+ if (queue?.multipleBatches && queue.ready)
33
+ return `Retry all eligible (${queue.ready})`;
34
+ }
35
+ export function extractionRetryUnavailable(status) {
36
+ const queue = status?.extractionQueue;
37
+ return !!queue && !queue.ready;
38
+ }
39
+ export function noticeDetail(notice) {
40
+ const version = notice.version ? `${notice.version.toUpperCase()}: ` : "";
41
+ const date = notice.failedAt === undefined ? "" : `${new Date(notice.failedAt).toLocaleString()} · `;
42
+ return `${version}${date}${notice.detail ?? ""}`;
43
+ }
21
44
  const retryWaitMessages = {
22
45
  retry: "A memory retry is already running. Wait for it to finish.",
23
46
  consolidation: "A background memory update is running. You can retry when it finishes.",
@@ -28,19 +51,32 @@ function retryDescription(times, now) {
28
51
  ? `Automatic retry can run ${remaining(Math.min(...times), now)}, when there’s OpenCode activity.`
29
52
  : "Automatic retry can run on the next OpenCode activity.";
30
53
  }
31
- function noticeMessage(kind, details, now, offersRetry, retryBlockedReason, supportsRetry, sessionID) {
54
+ function noticeMessage(kind, details, now, offersRetry, retryBlockedReason, status, sessionID) {
32
55
  const canRetry = offersRetry && !retryBlockedReason;
33
56
  switch (kind) {
34
57
  case "extraction_exhausted": {
35
58
  const current = sessionID ? details.find((notice) => notice.sessionID === sessionID) : undefined;
36
59
  const affected = current ?? details[0];
60
+ const backlog = status.extractionBacklog;
61
+ if (backlog?.historical) {
62
+ const count = backlog.count;
63
+ const remaining = count === 1
64
+ ? "1 conversation still has an earlier failure."
65
+ : `${count} conversations still have earlier failures.`;
66
+ return {
67
+ title: "Earlier extraction failures",
68
+ description: `${remaining} Memory has processed other conversations since then.${canRetry ? " You can retry in batches." : ""}`,
69
+ affectedSessionID: current ? undefined : affected?.sessionID,
70
+ details,
71
+ };
72
+ }
37
73
  const recovery = modelRecoveryGuidance(details.filter((notice) => notice.sessionID === affected?.sessionID).map((notice) => notice.detail ?? ""), "extraction");
38
74
  const conversation = current ? "this conversation" : "an affected conversation";
39
75
  const nextStep = canRetry
40
76
  ? "Retry a batch with the current background models. No new message is needed."
41
77
  : offersRetry
42
78
  ? undefined
43
- : supportsRetry
79
+ : status.manualRetry !== undefined
44
80
  ? "Wait for the provider limit to clear before retrying."
45
81
  : `After fixing the issue, send a new message in ${conversation} and let it go idle.`;
46
82
  return {
@@ -130,6 +166,13 @@ export function memoryMessages(status, now, sessionID) {
130
166
  if (status.activity === "stopping")
131
167
  return [{ title: "Memory is stopping", description: "Wait for OpenCode to reconnect." }];
132
168
  const work = activeMemoryWork(status, now);
169
+ if (!status.generateMemories && work)
170
+ return [
171
+ {
172
+ title: "Pausing learning",
173
+ description: "Current memory work is finishing. No new batches or consolidation will start.",
174
+ },
175
+ ];
133
176
  const retryBlockedReason = !status.generateMemories
134
177
  ? "Turn on Learn from sessions to retry."
135
178
  : work
@@ -150,16 +193,26 @@ export function memoryMessages(status, now, sessionID) {
150
193
  }
151
194
  }
152
195
  const offersRetry = retryPhases.length > 0;
196
+ const queue = retryPhases.includes("extraction") ? status.extractionQueue : undefined;
197
+ const blocked = retryBlockedReason ?? (queue && !queue.ready ? extractionQueueText(queue) : undefined);
198
+ const message = noticeMessage(kind, notices, now, offersRetry, blocked, status, sessionID);
153
199
  return [
154
200
  {
155
- ...noticeMessage(kind, notices, now, offersRetry, retryBlockedReason, status.manualRetry !== undefined, sessionID),
201
+ ...message,
202
+ description: queue?.ready ? `${message.description} ${extractionQueueText(queue)}` : message.description,
156
203
  retryPhases,
157
- retryBlockedReason: offersRetry ? retryBlockedReason : undefined,
204
+ retryBlockedReason: offersRetry ? blocked : undefined,
158
205
  },
159
206
  ];
160
207
  });
161
208
  if (status.manualRetry?.state === "running")
162
- return [{ title: `Retrying ${status.manualRetry.phase}…`, description: status.manualRetry.message }, ...messages];
209
+ return [
210
+ {
211
+ title: status.manualRetry.action === "update" ? "Updating memory…" : `Retrying ${status.manualRetry.phase}…`,
212
+ description: status.manualRetry.message,
213
+ },
214
+ ...messages,
215
+ ];
163
216
  if (status.generateMemories) {
164
217
  const active = status.pipelines.filter((pipeline) => status.dualWrite || pipeline.version === status.version);
165
218
  if (status.activity === "consolidating") {