opencode-codex-memory 0.10.0 → 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.10.0" }
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.10.0"]
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)
package/dist/src/llm.js CHANGED
@@ -116,8 +116,8 @@ async function createSession(title) {
116
116
  /**
117
117
  * opencode's config carries the same split codex expresses with provider
118
118
  * model preferences: `small_model` for cheap background work (codex:
119
- * memory_extraction_preferred_model = gpt-5.6-luna) and `model` for capable
120
- * 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
121
121
  * plugin instance — opencode reloads plugins on config change.
122
122
  */
123
123
  let configModels = null;
@@ -145,9 +145,10 @@ async function runVersionPhase2(store, opts) {
145
145
  // the lease instead of leaving the row running until it expires.
146
146
  const interop = opts.codexInterop ? resolveCodexInterop(opts.codexInterop) : null;
147
147
  ensureLayout();
148
- // Preserves an existing baseline (only initializes a missing one): the
149
- // diff below must span last-successful-run -> now so user edits and
150
- // 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
151
152
  // output pruning happens in phase 1, before the rate gate (codex
152
153
  // start.rs ordering).
153
154
  if (!await withHostTimeout(ensureBaseline(), GIT_TIMEOUT_MS, "ensureBaseline")) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-codex-memory",
3
- "version": "0.10.0",
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",