opencode-codex-memory 0.9.12 → 0.10.1

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/README.md CHANGED
@@ -35,7 +35,7 @@ to your existing global `~/.config/opencode/opencode.jsonc` or `opencode.json`
35
35
  {
36
36
  "$schema": "https://opencode.ai/config.json",
37
37
  "plugins": [
38
- { "package": "opencode-codex-memory@0.9.12" }
38
+ { "package": "opencode-codex-memory@0.10.1" }
39
39
  ]
40
40
  }
41
41
  ```
@@ -45,7 +45,7 @@ to your existing global `~/.config/opencode/opencode.jsonc` or `opencode.json`
45
45
  ```json
46
46
  {
47
47
  "$schema": "https://opencode.ai/config.json",
48
- "plugin": ["opencode-codex-memory@0.9.12"]
48
+ "plugin": ["opencode-codex-memory@0.10.1"]
49
49
  }
50
50
  ```
51
51
 
@@ -382,14 +382,31 @@ function describeVersion(value) {
382
382
  return typeof value;
383
383
  }
384
384
  /**
385
- * Selected Codex read version from `$CODEX_HOME/config.toml` only.
385
+ * Codex's runtime default when `memories.version` is unset (a390571745, #56211,
386
+ * 2026-10-22): a fresh profile (no `memories/` directory) uses v2 unless
387
+ * `dual_write = false`. Exchange mirrors the same observable signal instead of
388
+ * assuming v1. Explicit versions always win; profile, project, and session
389
+ * layers are still not merged. `memories_v2/` alone is enough evidence for v2
390
+ * when `memories/` is absent.
391
+ */
392
+ function resolveUnsetCodexVersion(codexHome, dualWrite) {
393
+ if (dualWrite === false)
394
+ return "v1";
395
+ if (fs.existsSync(path.join(codexHome, CODEX_MEMORY_DIR.v1)))
396
+ return "v1";
397
+ if (fs.existsSync(path.join(codexHome, CODEX_MEMORY_DIR.v2)))
398
+ return "v2";
399
+ return "v1";
400
+ }
401
+ /**
402
+ * Selected Codex read version from `$CODEX_HOME/config.toml` plus the same
403
+ * directory signal Codex uses for fresh profiles.
386
404
  *
387
- * Unset, missing file, or a `[memories]` table with no `version` → v1, matching
388
- * Codex's default. Profile, project, and session layers are not merged: those
389
- * overrides are not on disk in a form this plugin can resolve. `dual_write`
390
- * does not change the root — the injected store is `version`. An unreadable
391
- * file, a parse failure, or a value other than "v1"/"v2" fails closed so a
392
- * leftover `memories/` handbook is not imported by guess.
405
+ * Explicit `memories.version` wins. Unset, missing file, or a `[memories]`
406
+ * table with no `version` → `memories/` exists ? v1 : `memories_v2/` exists ?
407
+ * v2 : v1. `memories.dual_write = false` keeps v1 (Codex's transition opt-out).
408
+ * An unreadable file, a parse failure, or a value other than "v1"/"v2" fails
409
+ * closed so a leftover `memories/` handbook is not imported by guess.
393
410
  */
394
411
  function readCodexMemoryVersion(codexHome) {
395
412
  const file = path.join(codexHome, CODEX_CONFIG_FILE);
@@ -398,8 +415,9 @@ function readCodexMemoryVersion(codexHome) {
398
415
  text = fs.readFileSync(file, "utf8");
399
416
  }
400
417
  catch (err) {
401
- if (err.code === "ENOENT")
402
- return { ok: true, version: "v1" };
418
+ if (err.code === "ENOENT") {
419
+ return { ok: true, version: resolveUnsetCodexVersion(codexHome, undefined) };
420
+ }
403
421
  return { ok: false, reason: `could not read ${file}` };
404
422
  }
405
423
  let parsed;
@@ -414,13 +432,14 @@ function readCodexMemoryVersion(codexHome) {
414
432
  }
415
433
  const memories = parsed.memories;
416
434
  if (memories == null)
417
- return { ok: true, version: "v1" };
435
+ return { ok: true, version: resolveUnsetCodexVersion(codexHome, undefined) };
418
436
  if (typeof memories !== "object" || Array.isArray(memories)) {
419
437
  return { ok: false, reason: `${file} memories.version is not "v1" or "v2"` };
420
438
  }
421
- const version = memories.version;
439
+ const table = memories;
440
+ const version = table.version;
422
441
  if (version == null)
423
- return { ok: true, version: "v1" };
442
+ return { ok: true, version: resolveUnsetCodexVersion(codexHome, table.dual_write) };
424
443
  if (version === "v1" || version === "v2")
425
444
  return { ok: true, version };
426
445
  return { ok: false, reason: `${file} memories.version ${describeVersion(version)} is not "v1" or "v2"` };
@@ -14,11 +14,12 @@ export interface WorkspaceDiff {
14
14
  extensionSnapshot?: ReadonlyMap<string, string>;
15
15
  }
16
16
  /**
17
- * Mirrors codex prepare_memory_workspace: an existing baseline is preserved
18
- * untouched so the phase-2 diff spans last-successful-run -> now — including
19
- * manual user edits and newly added ad-hoc notes. Committing here would
20
- * swallow those changes and consolidation would never see them. Only a root
21
- * without any commit gets a fresh baseline.
17
+ * Mirrors codex prepare_memory_workspace: a current-version baseline is
18
+ * preserved untouched so the phase-2 diff spans last-successful-run -> now —
19
+ * including manual user edits and newly added ad-hoc notes. Committing here
20
+ * would swallow those changes and consolidation would never see them. Missing,
21
+ * outdated, or unusable metadata gets an empty baseline (codex keeps existing
22
+ * memory files visible as additions).
22
23
  */
23
24
  export declare function ensureBaseline(): Promise<boolean>;
24
25
  export declare function captureWorkspaceDiff(): Promise<WorkspaceDiff>;
@@ -10,6 +10,11 @@ const AUTHOR = { name: "opencode-codex-memory", email: "memory@opencode.local" }
10
10
  // commits (mirrors codex's remove_workspace_diff) so it never enters the
11
11
  // baseline history or shows up as memory content.
12
12
  export const DIFF_ARTIFACT = "phase2_workspace_diff.md";
13
+ // codex baseline.rs: a baseline is derived data, so snapshots skip files above
14
+ // the automatic ghost-snapshot limit instead of reading unbounded content.
15
+ const MAX_BASELINE_FILE_BYTES = 10 * 1024 * 1024;
16
+ const BASELINE_VERSION_FILE = "codex-baseline-version";
17
+ const BASELINE_VERSION = "1\n";
13
18
  /**
14
19
  * Hidden path components are invisible to tools/path-guard (`not found`).
15
20
  * Codex's gix walker includes them and reads bytes directly; isomorphic-git
@@ -22,7 +27,10 @@ function isHiddenBaselinePath(filepath) {
22
27
  const EXTENSIONS_PREFIX = "extensions/";
23
28
  function workdirHash(dir, filepath) {
24
29
  try {
25
- const content = readRegularFileNoFollow(safeResolveUnderRoot(dir, filepath)).content;
30
+ const file = safeResolveUnderRoot(dir, filepath);
31
+ if (fs.lstatSync(file).size > MAX_BASELINE_FILE_BYTES)
32
+ return null;
33
+ const content = readRegularFileNoFollow(file).content;
26
34
  return createHash("sha1").update(content).digest("hex");
27
35
  }
28
36
  catch {
@@ -36,39 +44,73 @@ function removeDiffArtifact(dir) {
36
44
  catch {
37
45
  }
38
46
  }
39
- async function ensureInit(dir) {
40
- const gitDir = path.join(dir, ".git");
41
- let recreate = false;
42
- try {
43
- recreate = gitMetadataUnusable(gitDir);
44
- }
45
- catch (err) {
46
- if (err.code !== "ENOENT")
47
- throw err;
48
- }
49
- if (recreate)
50
- fs.rmSync(gitDir, { recursive: true, force: true });
51
- if (!fs.existsSync(gitDir)) {
52
- await isogit.init({ fs, dir });
53
- }
47
+ function baselineVersionPath(dir) {
48
+ return path.join(dir, ".git", BASELINE_VERSION_FILE);
54
49
  }
55
50
  /**
56
51
  * Only the `.git` entry itself. A recursive walk of git objects hangs on
57
52
  * Windows junctions / symlink cycles and is not needed: we only refuse a
58
- * `.git` that is a symlink or a non-directory.
53
+ * `.git` that is a symlink, a non-directory (gitfile), or a linked worktree.
59
54
  */
60
55
  function gitMetadataUnusable(gitDir) {
61
56
  const st = fs.lstatSync(gitDir);
62
- return st.isSymbolicLink() || !st.isDirectory();
57
+ if (st.isSymbolicLink() || !st.isDirectory())
58
+ return true;
59
+ // codex requires common_dir == git_dir; a commondir file marks a linked worktree.
60
+ return fs.existsSync(path.join(gitDir, "commondir"));
61
+ }
62
+ function isOversizedFile(dir, filepath) {
63
+ try {
64
+ const st = fs.lstatSync(path.join(dir, filepath));
65
+ return st.isFile() && st.size > MAX_BASELINE_FILE_BYTES;
66
+ }
67
+ catch {
68
+ return false;
69
+ }
70
+ }
71
+ function statusMatrix(dir) {
72
+ return isogit.statusMatrix({
73
+ fs,
74
+ dir,
75
+ filter: (filepath) => !isHiddenBaselinePath(filepath) && !isOversizedFile(dir, filepath),
76
+ });
77
+ }
78
+ async function hasVersionedBaseline(dir) {
79
+ try {
80
+ if (gitMetadataUnusable(path.join(dir, ".git")))
81
+ return false;
82
+ if (fs.readFileSync(baselineVersionPath(dir), "utf8") !== BASELINE_VERSION)
83
+ return false;
84
+ await isogit.resolveRef({ fs, dir, ref: "HEAD" });
85
+ return true;
86
+ }
87
+ catch {
88
+ return false;
89
+ }
90
+ }
91
+ /**
92
+ * codex ensure_git_baseline_repository: missing, outdated, or unusable
93
+ * metadata is replaced with an EMPTY baseline, so every eligible working file
94
+ * stays visible to the next consolidation as an addition. The version marker
95
+ * is written last; an interrupted reset therefore never looks trusted.
96
+ */
97
+ async function initEmptyBaseline(dir) {
98
+ fs.rmSync(path.join(dir, ".git"), { recursive: true, force: true });
99
+ await isogit.init({ fs, dir });
100
+ const tree = await isogit.writeTree({ fs, dir, tree: [] });
101
+ await isogit.commit({ fs, dir, message: "memory baseline", author: AUTHOR, tree, parent: [] });
102
+ fs.writeFileSync(baselineVersionPath(dir), BASELINE_VERSION);
103
+ }
104
+ async function ensureVersionedBaseline(dir) {
105
+ if (!(await hasVersionedBaseline(dir)))
106
+ await initEmptyBaseline(dir);
63
107
  }
64
108
  // statusMatrix rows are [filepath, head, workdir, stage]; head !== workdir
65
109
  // means the working tree differs from HEAD (added, modified, or deleted).
66
110
  async function stageAll(dir, skip) {
67
- const matrix = await isogit.statusMatrix({ fs, dir });
111
+ const matrix = await statusMatrix(dir);
68
112
  let changes = 0;
69
113
  for (const [filepath, head, workdir, stage] of matrix) {
70
- if (isHiddenBaselinePath(filepath))
71
- continue;
72
114
  if (head === 1 && workdir === 1 && stage === 1)
73
115
  continue;
74
116
  if (workdir !== 0 && skip?.(filepath))
@@ -85,45 +127,34 @@ async function stageAll(dir, skip) {
85
127
  }
86
128
  return changes;
87
129
  }
88
- async function hasHeadCommit(dir) {
89
- try {
90
- await isogit.resolveRef({ fs, dir, ref: "HEAD" });
91
- return true;
92
- }
93
- catch {
94
- return false;
95
- }
96
- }
97
130
  async function commitBaseline(dir, skip) {
98
131
  await stageAll(dir, skip);
99
- return isogit.commit({ fs, dir, message: "memory baseline", author: AUTHOR });
132
+ const oid = await isogit.commit({ fs, dir, message: "memory baseline", author: AUTHOR });
133
+ fs.writeFileSync(baselineVersionPath(dir), BASELINE_VERSION);
134
+ return oid;
100
135
  }
101
136
  /**
102
- * Mirrors codex prepare_memory_workspace: an existing baseline is preserved
103
- * untouched so the phase-2 diff spans last-successful-run -> now — including
104
- * manual user edits and newly added ad-hoc notes. Committing here would
105
- * swallow those changes and consolidation would never see them. Only a root
106
- * without any commit gets a fresh baseline.
137
+ * Mirrors codex prepare_memory_workspace: a current-version baseline is
138
+ * preserved untouched so the phase-2 diff spans last-successful-run -> now —
139
+ * including manual user edits and newly added ad-hoc notes. Committing here
140
+ * would swallow those changes and consolidation would never see them. Missing,
141
+ * outdated, or unusable metadata gets an empty baseline (codex keeps existing
142
+ * memory files visible as additions).
107
143
  */
108
144
  export async function ensureBaseline() {
109
145
  const dir = memoryRoot();
110
146
  try {
111
147
  removeDiffArtifact(dir);
112
- await ensureInit(dir);
113
- if (!(await hasHeadCommit(dir))) {
114
- await commitBaseline(dir);
115
- }
148
+ await ensureVersionedBaseline(dir);
116
149
  return true;
117
150
  }
118
151
  catch (err) {
119
152
  // codex ensure_git_baseline_repository: unusable/corrupt git metadata is
120
- // recovered by a destructive fresh re-init (reset_git_repository_sync)
121
- // instead of failing the job forever.
153
+ // recovered by a destructive fresh empty re-init instead of failing the
154
+ // job forever.
122
155
  console.error("[opencode-codex-memory] ensureBaseline error, re-initializing baseline:", err);
123
156
  try {
124
- fs.rmSync(path.join(dir, ".git"), { recursive: true, force: true });
125
- await isogit.init({ fs, dir });
126
- await commitBaseline(dir);
157
+ await initEmptyBaseline(dir);
127
158
  return true;
128
159
  }
129
160
  catch (err2) {
@@ -143,17 +174,78 @@ async function readBaselineText(dir, headOid, filepath) {
143
174
  }
144
175
  function readWorkdirText(dir, filepath) {
145
176
  const file = safeResolveUnderRoot(dir, filepath);
177
+ if (fs.lstatSync(file).size > MAX_BASELINE_FILE_BYTES) {
178
+ throw new Error(`file grew beyond the snapshot file limit during diff: ${filepath}`);
179
+ }
146
180
  return readRegularFileNoFollow(file).content.toString("utf8");
147
181
  }
182
+ /**
183
+ * Every non-hidden regular file above the snapshot limit. Used to invalidate a
184
+ * baseline whose tracked inputs grew after preparation (codex
185
+ * diff_since_latest_init).
186
+ */
187
+ function collectOversizedPaths(dir) {
188
+ const out = [];
189
+ const walk = (current, prefix) => {
190
+ let entries;
191
+ try {
192
+ entries = fs.readdirSync(current, { withFileTypes: true });
193
+ }
194
+ catch {
195
+ return;
196
+ }
197
+ for (const entry of entries) {
198
+ if (entry.name === ".git")
199
+ continue;
200
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
201
+ if (isHiddenBaselinePath(rel))
202
+ continue;
203
+ const full = path.join(current, entry.name);
204
+ if (entry.isDirectory()) {
205
+ walk(full, rel);
206
+ }
207
+ else if (entry.isFile()) {
208
+ try {
209
+ if (fs.lstatSync(full).size > MAX_BASELINE_FILE_BYTES)
210
+ out.push(rel);
211
+ }
212
+ catch {
213
+ }
214
+ }
215
+ }
216
+ };
217
+ walk(dir, "");
218
+ return out;
219
+ }
220
+ async function hasTrackedOversizedFile(dir) {
221
+ const oversized = collectOversizedPaths(dir);
222
+ if (oversized.length === 0)
223
+ return false;
224
+ let tracked;
225
+ try {
226
+ tracked = await isogit.listFiles({ fs, dir, ref: "HEAD" });
227
+ }
228
+ catch {
229
+ return false;
230
+ }
231
+ const trackedSet = new Set(tracked);
232
+ return oversized.some((filepath) => trackedSet.has(filepath));
233
+ }
148
234
  // Throws on failure: codex fails the phase-2 job on workspace-status errors
149
235
  // (failed_workspace_status). Swallowing the error here would make an errored
150
236
  // diff indistinguishable from "no changes" and falsely mark the job succeeded.
151
237
  export async function captureWorkspaceDiff() {
152
238
  const dir = memoryRoot();
153
- await ensureInit(dir);
239
+ await ensureVersionedBaseline(dir);
154
240
  removeDiffArtifact(dir);
155
- const matrix = await isogit.statusMatrix({ fs, dir });
156
- const changedRows = matrix.filter(([filepath, head, workdir]) => head !== workdir && filepath !== DIFF_ARTIFACT && !isHiddenBaselinePath(filepath));
241
+ let matrix = await statusMatrix(dir);
242
+ // Inputs may grow during synchronization, after the initial baseline was
243
+ // prepared. Rebuild empty so the remaining files stay visible as additions.
244
+ if (await hasTrackedOversizedFile(dir)) {
245
+ await initEmptyBaseline(dir);
246
+ matrix = await statusMatrix(dir);
247
+ }
248
+ const changedRows = matrix.filter(([filepath, head, workdir]) => head !== workdir && filepath !== DIFF_ARTIFACT);
157
249
  const changes = changedRows.map(([filepath, head, workdir]) => {
158
250
  if (head === 0)
159
251
  return { status: "A", path: filepath };
@@ -172,13 +264,14 @@ export async function captureWorkspaceDiff() {
172
264
  for (const [filepath, head, workdir] of changedRows) {
173
265
  const oldText = head === 1 && headOid ? await readBaselineText(dir, headOid, filepath) : "";
174
266
  const newText = workdir === 0 ? "" : readWorkdirText(dir, filepath);
175
- // No per-file cap: codex renders every file's patch in full and relies
176
- // on the global 4 MiB truncation in writeWorkspaceDiff.
267
+ // Per-file patches render in full; only the global 4 MiB truncation in
268
+ // writeWorkspaceDiff caps the rendered diff. Files above the baseline
269
+ // snapshot limit never reach this loop.
177
270
  patches.push(createPatch(filepath, oldText, newText));
178
271
  }
179
272
  const extensionSnapshot = new Map();
180
273
  for (const [filepath, , workdir] of matrix) {
181
- if (workdir === 0 || !filepath.startsWith(EXTENSIONS_PREFIX) || isHiddenBaselinePath(filepath))
274
+ if (workdir === 0 || !filepath.startsWith(EXTENSIONS_PREFIX))
182
275
  continue;
183
276
  const hash = workdirHash(dir, filepath);
184
277
  if (hash)
@@ -242,7 +242,14 @@ declare const _default: {
242
242
  }>;
243
243
  };
244
244
  export default _default;
245
- export declare function applyPluginOptions(opts: PluginOptions): void;
245
+ /**
246
+ * `modelFallback`: keep comma-separated model chains (OpenCode 2 only).
247
+ * OpenCode 1.x retries quota errors for about 70s per attempt before the
248
+ * plugin sees them, so V1 uses only the first model.
249
+ */
250
+ export declare function applyPluginOptions(opts: PluginOptions, { modelFallback }?: {
251
+ modelFallback?: boolean | undefined;
252
+ }): void;
246
253
  /**
247
254
  * Registers the memorize / memorize-extract sub-agents through the config
248
255
  * hook so installing the plugin requires no manual agent setup. Definitions
package/dist/src/index.js CHANGED
@@ -10,7 +10,7 @@ import { writeMemoryVersions } from "./memory-version.js";
10
10
  import { sessionMemoryVersion, withSessionMemoryVersion } from "./session-version.js";
11
11
  import { existingMemoryStores } from "./store.js";
12
12
  import { setPluginInput, cleanupOldSubSessions, isMemorySubSession, abortActiveSubSessions } from "./llm.js";
13
- import { pluginOptions, recordConfigWarning, clearConfigWarnings, resetPluginOptions } from "./options.js";
13
+ import { pluginOptions, recordConfigWarning, clearConfigWarnings, resetPluginOptions, modelList } from "./options.js";
14
14
  import { beginPluginShutdown, resetPluginLifecycle } from "./lifecycle.js";
15
15
  import { hostMcpStatus } from "./host-client.js";
16
16
  import { loadBundledAgentDefinitions, recordAgentConfig, resetAgentHealth } from "./agent-health.js";
@@ -203,7 +203,12 @@ function finiteNumber(key, value, fallback) {
203
203
  }
204
204
  return value;
205
205
  }
206
- export function applyPluginOptions(opts) {
206
+ /**
207
+ * `modelFallback`: keep comma-separated model chains (OpenCode 2 only).
208
+ * OpenCode 1.x retries quota errors for about 70s per attempt before the
209
+ * plugin sees them, so V1 uses only the first model.
210
+ */
211
+ export function applyPluginOptions(opts, { modelFallback = false } = {}) {
207
212
  // Fresh pass per apply so memory_inspect never shows warnings for keys the
208
213
  // caller has since fixed. server() clears too, for boots without options.
209
214
  const previousDb = dataRoot();
@@ -236,10 +241,13 @@ export function applyPluginOptions(opts) {
236
241
  for (const key of ["extract_model", "consolidation_model"]) {
237
242
  if (!(key in raw))
238
243
  continue;
239
- if (typeof raw[key] === "string")
240
- pluginOptions[key] = raw[key];
241
- else
242
- recordConfigWarning(`${key} must be a string; using the opencode model default`);
244
+ const models = typeof raw[key] === "string" ? modelList(raw[key]) : [];
245
+ if (models.length === 0) {
246
+ recordConfigWarning(`${key} must be a "provider/model" string or comma-separated list; using the opencode model default`);
247
+ continue;
248
+ }
249
+ // A shared V1/V2 config is valid: V1 quietly runs the first model only.
250
+ pluginOptions[key] = modelFallback ? models.join(", ") : models[0];
243
251
  }
244
252
  const testing = pluginOptions.test;
245
253
  if ("version" in raw) {
package/dist/src/llm.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { PluginInput } from "@opencode-ai/plugin";
2
- import type { MemoryVersion } from "./options.js";
2
+ import { type MemoryVersion } from "./options.js";
3
3
  export interface ExtractionResult {
4
4
  raw_memory: string;
5
5
  rollout_summary: string;
@@ -46,8 +46,9 @@ export declare class SubagentShutdownError extends Error {
46
46
  }
47
47
  export interface ExtractOptions {
48
48
  cwd?: string;
49
+ /** "provider/model", or a comma-separated fallback chain tried in order. */
49
50
  model?: string;
50
- /** Override the default 1h extract timeout (tests / advanced). */
51
+ /** Override the default 1h extract budget, shared by fallbacks (tests / advanced). */
51
52
  timeoutMs?: number;
52
53
  /**
53
54
  * Cancel in-flight extract. Defaults to pluginShutdownSignal() so dispose
@@ -64,6 +65,7 @@ export interface ExtractOptions {
64
65
  * write tools (D2) so a lingering server turn cannot dual-write the memory root.
65
66
  */
66
67
  export declare function extractViaSubagent(sessionId: string, transcript: string, opts?: ExtractOptions): Promise<ExtractionResult | null>;
68
+ /** `model`: "provider/model", or a comma-separated fallback chain tried in order. */
67
69
  export declare function consolidateViaSubagent(memoryRoot: string, diffFileName: string, model?: string, signal?: AbortSignal): Promise<void>;
68
70
  export declare function cleanupOldSubSessions(maxAgeMinutes?: number, timeoutMs?: number): Promise<void>;
69
71
  /** Best-effort abort of every memory sub-session (plugin dispose / reload). */
package/dist/src/llm.js CHANGED
@@ -4,9 +4,11 @@ import { memoryRoot } from "./paths.js";
4
4
  import { hostListSessionsGlobal, hostProviderList, hostSessionCreate, hostSessionDeletionConfirmed, hostSessionPrompt, hostStructuredOutput, ignoreLateRejection, pluginHttpGet, withHostTimeout, } from "./host-client.js";
5
5
  import { catalogVariantKeys, nearestReasoningVariant } from "./reasoning-variant.js";
6
6
  import { isPluginShuttingDown, pluginShutdownSignal } from "./lifecycle.js";
7
+ import { modelList } from "./options.js";
7
8
  import { currentMemoryVersion } from "./memory-version.js";
8
9
  import { SCAN_LIMIT, STAGE1_LEASE_SECONDS } from "./store.js";
9
- import { isProviderCapacityError, ProviderCapacityError } from "./ratelimit.js";
10
+ import { isProviderCapacityBlocked, isProviderCapacityError, noteProviderCapacityExhausted, ProviderCapacityError, providerCapacityMessage, } from "./ratelimit.js";
11
+ import { recordDiagnostic } from "./diagnostics.js";
10
12
  const EXTRACTION_TIMEOUT_MS = (STAGE1_LEASE_SECONDS - 600) * 1000;
11
13
  let inputRef = null;
12
14
  let inputGeneration = 0;
@@ -114,8 +116,8 @@ async function createSession(title) {
114
116
  /**
115
117
  * opencode's config carries the same split codex expresses with provider
116
118
  * model preferences: `small_model` for cheap background work (codex:
117
- * memory_extraction_preferred_model = gpt-5.6-luna) and `model` for capable
118
- * work (codex: memory_consolidation_preferred_model = gpt-5.6-terra). Cached per
119
+ * memory_extraction_preferred_model = gpt-6-luna) and `model` for capable
120
+ * work (codex: memory_consolidation_preferred_model = gpt-6.1-terra). Cached per
119
121
  * plugin instance — opencode reloads plugins on config change.
120
122
  */
121
123
  let configModels = null;
@@ -371,6 +373,58 @@ function extractAssistantText(body) {
371
373
  return body.output;
372
374
  return JSON.stringify(body);
373
375
  }
376
+ const FALLBACK_DIAGNOSTIC_CHARS = 300;
377
+ /**
378
+ * Plugin-only (codex takes one model per phase): tries each model of a
379
+ * comma-separated chain in order until one succeeds. Models in quota backoff
380
+ * are skipped, and a quota failure starts that model's backoff. Fallbacks
381
+ * share one deadline. Cancellation, timeout, and a failed helper shutdown end
382
+ * the chain; the last means a writer may still be alive. The thrown error is
383
+ * the first non-quota failure, so the job keeps its quota classification
384
+ * (no retry burned) only when every attempted model ran out of quota.
385
+ */
386
+ async function withModelFallback(phase, configured, deadline, signal, attempt) {
387
+ const chain = modelList(configured);
388
+ if (chain.length === 0)
389
+ chain.push(undefined);
390
+ const available = (model) => !isProviderCapacityBlocked(phase, model);
391
+ const job = phase === "phase1" ? "extraction" : "consolidation";
392
+ let failure;
393
+ let capacityFailure;
394
+ for (let i = 0; i < chain.length; i++) {
395
+ const model = chain[i];
396
+ if (!available(model))
397
+ continue;
398
+ const remaining = deadline - Date.now();
399
+ if (remaining <= 0 && (failure || capacityFailure))
400
+ break;
401
+ try {
402
+ return await attempt(model, Math.max(1, remaining));
403
+ }
404
+ catch (err) {
405
+ if (err instanceof SubagentCancelledError ||
406
+ err instanceof SubagentTimeoutError ||
407
+ err instanceof SubagentShutdownError ||
408
+ signal?.aborted ||
409
+ isPluginShuttingDown())
410
+ throw err;
411
+ const capacity = isProviderCapacityError(err);
412
+ if (capacity) {
413
+ noteProviderCapacityExhausted(phase, model);
414
+ capacityFailure = err;
415
+ }
416
+ else {
417
+ failure ??= err;
418
+ }
419
+ const next = chain.slice(i + 1).find(available);
420
+ if (next) {
421
+ recordDiagnostic("warn", phase, `${job} model ${model} failed${capacity ? " (quota/rate limit)" : ""}: ` +
422
+ `${providerCapacityMessage(err).slice(0, FALLBACK_DIAGNOSTIC_CHARS)}; falling back to ${next}`);
423
+ }
424
+ }
425
+ }
426
+ throw failure ?? capacityFailure ?? new ProviderCapacityError("provider capacity exhausted");
427
+ }
374
428
  // JSON Schema for structured stage-1 output. Mirrors the deliverables in
375
429
  // stage_one_system.md (three required string fields; all-empty = no-op) and is
376
430
  // opencode's equivalent of codex's output_schema + output_schema_strict.
@@ -403,22 +457,28 @@ const EXTRACTION_SCHEMA_V2 = {
403
457
  * write tools (D2) so a lingering server turn cannot dual-write the memory root.
404
458
  */
405
459
  export async function extractViaSubagent(sessionId, transcript, opts = {}) {
460
+ // Bounded by the stage-1 job lease (1h), minus headroom for transcript
461
+ // load, session creation, and model lookups before the prompt starts.
462
+ // Codex has no per-request timeout; a timeout past the lease lets another
463
+ // process reclaim the job and silently drop this paid result.
464
+ const deadline = Date.now() + (opts.timeoutMs ?? EXTRACTION_TIMEOUT_MS);
465
+ const signal = opts.signal ?? pluginShutdownSignal();
466
+ return withModelFallback("phase1", opts.model, deadline, signal, (model, timeoutMs) => extractOnce(sessionId, transcript, opts.cwd, model, timeoutMs, signal));
467
+ }
468
+ async function extractOnce(sessionId, transcript, cwd, configuredModel, timeoutMs, signal) {
406
469
  const agent = "memorize-extract";
470
+ // Fresh helper per attempt: a fallback must not inherit the failed turn.
407
471
  const subId = await createSession(`codex-memory-extract-${sessionId}`);
408
472
  try {
409
473
  const version = currentMemoryVersion();
410
- const prompt = buildExtractionInput(sessionId, opts.cwd ?? "unknown", transcript, version);
411
- // extract_model option > opencode small_model > session default.
412
- const model = await resolveExtractionModel(opts.model);
474
+ const prompt = buildExtractionInput(sessionId, cwd ?? "unknown", transcript, version);
475
+ // extract_model chain entry > opencode small_model > session default.
476
+ const model = await resolveExtractionModel(configuredModel);
413
477
  const data = await runPrompt(subId, prompt, agent, {
414
- // Bounded by the stage-1 job lease (1h), minus headroom for transcript
415
- // load, session creation, and model lookups before the prompt starts.
416
- // Codex has no per-request timeout; a timeout past the lease lets
417
- // another process reclaim the job and silently drop this paid result.
418
- timeoutMs: opts.timeoutMs ?? EXTRACTION_TIMEOUT_MS,
478
+ timeoutMs,
419
479
  system: readTemplate(version === "v2" ? "stage_one_system_v2.md" : "stage_one_system.md"),
420
480
  model,
421
- signal: opts.signal ?? pluginShutdownSignal(),
481
+ signal,
422
482
  // opencode enforces json_schema output via a forced StructuredOutput tool
423
483
  // call (toolChoice: required) — which is why memorize-extract must allow
424
484
  // that one otherwise-denied tool.
@@ -447,19 +507,25 @@ export async function extractViaSubagent(sessionId, transcript, opts = {}) {
447
507
  // codex runs the consolidation agent under a 1h job lease with heartbeats;
448
508
  // its INIT pass is explicitly allowed to run long ("do not be lazy"). A short
449
509
  // timeout here would fail the job after the workspace was already synced.
510
+ // Fallback models share this budget.
450
511
  const CONSOLIDATION_TIMEOUT_MS = 3600_000;
512
+ /** `model`: "provider/model", or a comma-separated fallback chain tried in order. */
451
513
  export async function consolidateViaSubagent(memoryRoot, diffFileName, model, signal) {
514
+ const deadline = Date.now() + CONSOLIDATION_TIMEOUT_MS;
515
+ return withModelFallback("phase2", model, deadline, signal, (configured, timeoutMs) => consolidateOnce(memoryRoot, diffFileName, configured, timeoutMs, signal));
516
+ }
517
+ async function consolidateOnce(memoryRoot, diffFileName, configuredModel, timeoutMs, signal) {
452
518
  const agent = "memorize";
453
519
  const subId = await createSession("codex-memory-consolidate");
454
520
  let promptError;
455
521
  let promptFailed = false;
456
522
  try {
457
523
  const prompt = buildConsolidationPrompt(memoryRoot, diffFileName);
458
- // consolidation_model option > opencode model (main) > session default.
459
- const resolved = await resolveConsolidationModel(model);
524
+ // consolidation_model chain entry > opencode model (main) > session default.
525
+ const resolved = await resolveConsolidationModel(configuredModel);
460
526
  await promptSession(subId, prompt, agent, {
461
527
  model: resolved,
462
- timeoutMs: CONSOLIDATION_TIMEOUT_MS,
528
+ timeoutMs,
463
529
  signal,
464
530
  // Codex consolidation ReasoningEffort::Medium. Nearest listed effort if missing.
465
531
  variant: await resolveReasoningVariant(CONSOLIDATE_VARIANT, resolved),
@@ -20,7 +20,9 @@ export interface PluginOptionsState {
20
20
  disable_on_external_context: boolean;
21
21
  version: MemoryVersion;
22
22
  dual_write: boolean;
23
+ /** "provider/model", or a comma-separated fallback chain tried in order. */
23
24
  extract_model?: string;
25
+ /** Same format as extract_model. */
24
26
  consolidation_model?: string;
25
27
  /** Resolved absolute plugin home (parent of memory.db + memories/). Unset = default. */
26
28
  home?: string;
@@ -39,6 +41,8 @@ export interface PluginOptionsState {
39
41
  claude_import: ClaudeImportOptions;
40
42
  }
41
43
  export declare const pluginOptions: PluginOptionsState;
44
+ /** Splits an extract_model / consolidation_model value into its fallback chain. */
45
+ export declare function modelList(value?: string): string[];
42
46
  export declare function resetPluginOptions(): void;
43
47
  export declare function recordConfigWarning(message: string): void;
44
48
  export declare function getConfigWarnings(): readonly string[];
@@ -20,6 +20,10 @@ export const pluginOptions = {
20
20
  codex_interop: { ...DEFAULT_PLUGIN_OPTIONS.codex_interop },
21
21
  claude_import: { ...DEFAULT_PLUGIN_OPTIONS.claude_import },
22
22
  };
23
+ /** Splits an extract_model / consolidation_model value into its fallback chain. */
24
+ export function modelList(value) {
25
+ return [...new Set((value ?? "").split(",").map((model) => model.trim()).filter(Boolean))];
26
+ }
23
27
  export function resetPluginOptions() {
24
28
  delete pluginOptions.extract_model;
25
29
  delete pluginOptions.consolidation_model;
@@ -4,7 +4,7 @@ import { serializeTieredInput } from "./rollout-input.js";
4
4
  import { redact, isMemoryExcludedFragment } from "./redact.js";
5
5
  import { stripCitations } from "./citation.js";
6
6
  import { extractViaSubagent, SubagentCancelledError } from "./llm.js";
7
- import { checkRateLimit, isProviderCapacityBlocked, isProviderCapacityError, markRateLimitUsed, noteProviderCapacityExhausted, ProviderCapacityError, } from "./ratelimit.js";
7
+ import { checkRateLimit, isProviderCapacityBlocked, markRateLimitUsed, ProviderCapacityError, } from "./ratelimit.js";
8
8
  import { isPluginShuttingDown } from "./lifecycle.js";
9
9
  import { recordDiagnostic } from "./diagnostics.js";
10
10
  import { currentMemoryVersion, withMemoryVersion } from "./memory-version.js";
@@ -68,7 +68,8 @@ async function runVersionPhase1(store, opts, rateLimitCheck) {
68
68
  store.releaseStage1OnShutdown(sid, claim.ownershipToken);
69
69
  return;
70
70
  }
71
- // Sibling jobs in this pass: do not call the model after quota was observed.
71
+ // Sibling jobs in this pass: do not call a model after quota was observed
72
+ // for every model in the chain.
72
73
  if (isProviderCapacityBlocked("phase1", extractModel)) {
73
74
  store.markStage1Failed(sid, claim.ownershipToken, new ProviderCapacityError("provider capacity exhausted"));
74
75
  return;
@@ -121,12 +122,11 @@ async function runVersionPhase1(store, opts, rateLimitCheck) {
121
122
  catch (err) {
122
123
  // Aborted mid-extract on dispose (shutdown signal / flag): release for
123
124
  // immediate reclaim, do not burn a retry or impose the 1h failure backoff.
125
+ // Quota backoff is per model, noted by the extraction fallback chain.
124
126
  if (err instanceof SubagentCancelledError || isPluginShuttingDown()) {
125
127
  store.releaseStage1OnShutdown(sid, claim.ownershipToken);
126
128
  }
127
129
  else {
128
- if (isProviderCapacityError(err))
129
- noteProviderCapacityExhausted("phase1", extractModel);
130
130
  store.markStage1Failed(sid, claim.ownershipToken, err);
131
131
  }
132
132
  }
@@ -1,5 +1,5 @@
1
1
  import { PHASE2_HEARTBEAT_SECONDS } from "./store.js";
2
- import { checkRateLimit, isProviderCapacityError, noteProviderCapacityExhausted } from "./ratelimit.js";
2
+ import { checkRateLimit } from "./ratelimit.js";
3
3
  import { ensureLayout, rebuildRawMemories, writeRolloutSummaries, pruneExtensionResources, EXTENSION_RESOURCE_RETENTION_DAYS, writeWorkspaceDiff, validateConsolidationArtifactsForVersion, removeMemorySymlinks, } from "./workspace.js";
4
4
  import { ensureBaseline, captureWorkspaceDiff, resetBaseline, DIFF_ARTIFACT } from "./git-baseline.js";
5
5
  import { consolidateViaSubagent, getPluginInput, SubagentCancelledError, SubagentShutdownError, } from "./llm.js";
@@ -113,7 +113,8 @@ async function runVersionPhase2(store, opts) {
113
113
  phase2InFlight.add(root);
114
114
  try {
115
115
  // No 30s process gate: codex serializes phase 2 only via the DB claim.
116
- // An observed quota stamp still skips both phases (Codex start.rs).
116
+ // An observed quota stamp on every chain model still skips both phases
117
+ // (Codex start.rs).
117
118
  const consolidationModel = opts.consolidationModel;
118
119
  const rl = await checkRateLimit("phase2", consolidationModel);
119
120
  if (!rl.ok)
@@ -144,9 +145,10 @@ async function runVersionPhase2(store, opts) {
144
145
  // the lease instead of leaving the row running until it expires.
145
146
  const interop = opts.codexInterop ? resolveCodexInterop(opts.codexInterop) : null;
146
147
  ensureLayout();
147
- // Preserves an existing baseline (only initializes a missing one): the
148
- // diff below must span last-successful-run -> now so user edits and
149
- // ad-hoc notes added since then reach consolidation. Stale stage-1
148
+ // Preserves a current-version baseline; missing/outdated/unusable
149
+ // metadata becomes an empty baseline (codex ensure_git_baseline_repository),
150
+ // so the diff below spans last-successful-run -> now and existing memory
151
+ // files stay visible as additions. Stale stage-1
150
152
  // output pruning happens in phase 1, before the rate gate (codex
151
153
  // start.rs ordering).
152
154
  if (!await withHostTimeout(ensureBaseline(), GIT_TIMEOUT_MS, "ensureBaseline")) {
@@ -305,8 +307,7 @@ async function runVersionPhase2(store, opts) {
305
307
  store.releasePhase2OnShutdown(claim.ownershipToken);
306
308
  return { status: "shutting_down" };
307
309
  }
308
- if (isProviderCapacityError(err))
309
- noteProviderCapacityExhausted("phase2", consolidationModel);
310
+ // Quota backoff is per model, noted by the consolidation fallback chain.
310
311
  sweepMemorySymlinksBestEffort();
311
312
  store.markPhase2Failed(claim.ownershipToken, err);
312
313
  return { status: "failed" };
@@ -15,6 +15,7 @@ export declare const PROVIDER_CAPACITY_BACKOFF_MS = 3600000;
15
15
  export declare function providerCapacityMessage(error: unknown): string;
16
16
  export declare function isProviderCapacityError(error: unknown): boolean;
17
17
  export declare function activeProviderCapacityBackoffs(now?: number): ProviderCapacityBackoff[];
18
+ /** True when every model in the (comma-separated) chain is in quota backoff. */
18
19
  export declare function isProviderCapacityBlocked(phase: MemoryPhase, model?: string, now?: number): boolean;
19
20
  /** Call after a quota/rate-limit failure so later passes skip claiming. */
20
21
  export declare function noteProviderCapacityExhausted(phase: MemoryPhase, model?: string, now?: number): void;
@@ -1,4 +1,4 @@
1
- import { pluginOptions } from "./options.js";
1
+ import { modelList, pluginOptions } from "./options.js";
2
2
  import { memoryDbPath } from "./paths.js";
3
3
  export class ProviderCapacityError extends Error {
4
4
  statusCode;
@@ -32,7 +32,7 @@ const lastPhase1Work = new Map();
32
32
  const providerCapacityUntil = new Map();
33
33
  const MIN_PHASE1_INTERVAL_MS = 30_000;
34
34
  export const PROVIDER_CAPACITY_BACKOFF_MS = 3_600_000;
35
- const PROVIDER_CAPACITY_RE = /usage limit|free usage exceeded|provider capacity exhausted|rate[\s_-]?limit|quota\s+(?:exceeded|exhausted|reached)|exceeded (?:your|the) (?:current )?quota|too many requests|\b429\b|resource_exhausted|insufficient_quota|billing.?hard.?limit/i;
35
+ const PROVIDER_CAPACITY_RE = /usage limit|free usage exceeded|provider capacity exhausted|rate[\s_-]?limit|quota\s+(?:exceeded|exhausted|reached)|exceeded (?:your|the) (?:[\w-]+ )?quota|too many requests|\b429\b|resource_exhausted|insufficient_quota|billing.?hard.?limit/i;
36
36
  // A single request larger than the per-minute budget (OpenAI "Request too
37
37
  // large … tokens per min", sent as 429) never succeeds on retry; treating it
38
38
  // as capacity would keep that session pending forever and trip the breaker
@@ -78,8 +78,10 @@ export function isProviderCapacityError(error) {
78
78
  return true;
79
79
  return PROVIDER_CAPACITY_RE.test(message);
80
80
  }
81
- function providerCapacityScope(phase, model) {
82
- return model ? `model:${model}` : `phase:${phase}:default`;
81
+ // One scope per model in a fallback chain; an unset model shares the phase default.
82
+ function providerCapacityScopes(phase, model) {
83
+ const models = modelList(model);
84
+ return models.length > 0 ? models.map((m) => `model:${m}`) : [`phase:${phase}:default`];
83
85
  }
84
86
  export function activeProviderCapacityBackoffs(now = Date.now()) {
85
87
  const active = [];
@@ -92,19 +94,24 @@ export function activeProviderCapacityBackoffs(now = Date.now()) {
92
94
  }
93
95
  return active.sort((a, b) => a.scope.localeCompare(b.scope));
94
96
  }
97
+ /** True when every model in the (comma-separated) chain is in quota backoff. */
95
98
  export function isProviderCapacityBlocked(phase, model, now = Date.now()) {
96
- const until = providerCapacityUntil.get(providerCapacityScope(phase, model));
97
- return until !== undefined && until > now;
99
+ return providerCapacityScopes(phase, model).every((scope) => {
100
+ const until = providerCapacityUntil.get(scope);
101
+ return until !== undefined && until > now;
102
+ });
98
103
  }
99
104
  /** Call after a quota/rate-limit failure so later passes skip claiming. */
100
105
  export function noteProviderCapacityExhausted(phase, model, now = Date.now()) {
101
- providerCapacityUntil.set(providerCapacityScope(phase, model), now + PROVIDER_CAPACITY_BACKOFF_MS);
106
+ for (const scope of providerCapacityScopes(phase, model)) {
107
+ providerCapacityUntil.set(scope, now + PROVIDER_CAPACITY_BACKOFF_MS);
108
+ }
102
109
  }
103
110
  export async function checkRateLimit(kind = "phase1", model) {
104
111
  if (isProviderCapacityBlocked(kind, model)) {
105
112
  return {
106
113
  ok: false,
107
- reason: `provider capacity exhausted for ${providerCapacityScope(kind, model)} (observed quota/rate-limit)`,
114
+ reason: `provider capacity exhausted for ${providerCapacityScopes(kind, model).join(", ")} (observed quota/rate-limit)`,
108
115
  };
109
116
  }
110
117
  // Phase 2: no 30s gate (codex relies on DB claim/cooldown only).
@@ -289,7 +289,7 @@ export async function setup(ctx) {
289
289
  clearConfigWarnings();
290
290
  const rawOptions = ctx.options;
291
291
  if (rawOptions && Object.keys(rawOptions).length > 0)
292
- applyPluginOptions(rawOptions);
292
+ applyPluginOptions(rawOptions, { modelFallback: true });
293
293
  else {
294
294
  const previousDb = dataRoot();
295
295
  resetPluginOptions();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-codex-memory",
3
- "version": "0.9.12",
3
+ "version": "0.10.1",
4
4
  "description": "Persistent memory plugin for opencode — ports codex's two-phase memory system (extraction → consolidation → injection → citation feedback)",
5
5
  "type": "module",
6
6
  "main": "./dist/src/index.js",