opencode-codex-memory 0.10.0 → 0.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +10 -12
  2. package/dist/src/agent-health.js +10 -7
  3. package/dist/src/capture.js +7 -7
  4. package/dist/src/citation.js +12 -3
  5. package/dist/src/claude-import.js +1 -3
  6. package/dist/src/codex-interop.js +51 -17
  7. package/dist/src/db.d.ts +0 -2
  8. package/dist/src/db.js +0 -4
  9. package/dist/src/git-baseline.d.ts +10 -11
  10. package/dist/src/git-baseline.js +167 -97
  11. package/dist/src/host-client.d.ts +5 -0
  12. package/dist/src/host-client.js +24 -0
  13. package/dist/src/index.d.ts +1 -1
  14. package/dist/src/index.js +56 -99
  15. package/dist/src/llm.d.ts +4 -1
  16. package/dist/src/llm.js +43 -15
  17. package/dist/src/options.d.ts +7 -0
  18. package/dist/src/options.js +20 -2
  19. package/dist/src/paths.d.ts +1 -0
  20. package/dist/src/paths.js +5 -2
  21. package/dist/src/phase1.js +12 -21
  22. package/dist/src/phase2.js +7 -6
  23. package/dist/src/reasoning-variant.d.ts +7 -0
  24. package/dist/src/reasoning-variant.js +11 -2
  25. package/dist/src/rollout-input.js +3 -5
  26. package/dist/src/session-version.js +4 -5
  27. package/dist/src/source.js +6 -2
  28. package/dist/src/store.d.ts +3 -2
  29. package/dist/src/store.js +72 -47
  30. package/dist/src/v2/agents.js +11 -14
  31. package/dist/src/v2/model-readiness.js +3 -1
  32. package/dist/src/v2/plugin.js +81 -109
  33. package/dist/src/v2/search-sandbox.js +1 -1
  34. package/dist/src/v2/service.js +5 -0
  35. package/dist/src/v2/shim.d.ts +3 -0
  36. package/dist/src/v2/shim.js +144 -90
  37. package/dist/src/v2/status-rpc.js +40 -14
  38. package/dist/src/v2/status.js +4 -7
  39. package/dist/src/v2/tools.d.ts +15 -9
  40. package/dist/src/v2/tools.js +9 -9
  41. package/dist/src/v2/tui.js +14 -4
  42. package/dist/src/workspace.js +13 -4
  43. package/dist/tools/control.js +29 -28
  44. package/dist/tools/memory.js +163 -89
  45. package/package.json +22 -9
package/README.md CHANGED
@@ -34,9 +34,7 @@ to your existing global `~/.config/opencode/opencode.jsonc` or `opencode.json`
34
34
  ```jsonc
35
35
  {
36
36
  "$schema": "https://opencode.ai/config.json",
37
- "plugins": [
38
- { "package": "opencode-codex-memory@0.10.0" }
39
- ]
37
+ "plugins": [{ "package": "opencode-codex-memory@0.10.2" }],
40
38
  }
41
39
  ```
42
40
 
@@ -45,7 +43,7 @@ to your existing global `~/.config/opencode/opencode.jsonc` or `opencode.json`
45
43
  ```json
46
44
  {
47
45
  "$schema": "https://opencode.ai/config.json",
48
- "plugin": ["opencode-codex-memory@0.10.0"]
46
+ "plugin": ["opencode-codex-memory@0.10.2"]
49
47
  }
50
48
  ```
51
49
 
@@ -93,14 +91,14 @@ privacy, backups, and relocation.
93
91
 
94
92
  ## Start here
95
93
 
96
- | I want to… | Read |
97
- |---|---|
98
- | Recall past work, save a note, or pause learning | [Using memory](./docs/usage.md) |
99
- | Choose or switch memory behavior | [Memory V1 and Memory V2](./docs/memory-versions.md) |
100
- | Set models, learning frequency, or other options | [Configuration](./docs/configuration.md) |
101
- | Find, back up, move, or reset my data | [Storage and privacy](./docs/storage-and-privacy.md) |
102
- | Share with Codex CLI or import Claude Code memories | [Integrations](./docs/integrations.md) |
103
- | Fix missing memory or check an update | [Troubleshooting](./docs/troubleshooting.md) |
94
+ | I want to… | Read |
95
+ | --------------------------------------------------- | ---------------------------------------------------- |
96
+ | Recall past work, save a note, or pause learning | [Using memory](./docs/usage.md) |
97
+ | Choose or switch memory behavior | [Memory V1 and Memory V2](./docs/memory-versions.md) |
98
+ | Set models, learning frequency, or other options | [Configuration](./docs/configuration.md) |
99
+ | Find, back up, move, or reset my data | [Storage and privacy](./docs/storage-and-privacy.md) |
100
+ | Share with Codex CLI or import Claude Code memories | [Integrations](./docs/integrations.md) |
101
+ | Fix missing memory or check an update | [Troubleshooting](./docs/troubleshooting.md) |
104
102
 
105
103
  ## Learn more and contribute
106
104
 
@@ -11,7 +11,11 @@ const SAFE_ALLOWS = {
11
11
  memorize: new Set(["read", "edit", "write", "glob", "grep", "external_directory"]),
12
12
  "memorize-extract": new Set(["StructuredOutput"]),
13
13
  };
14
- const initialEntry = () => ({ source: "missing", healthy: false, issues: ["config hook has not run"] });
14
+ const initialEntry = () => ({
15
+ source: "missing",
16
+ healthy: false,
17
+ issues: ["config hook has not run"],
18
+ });
15
19
  let snapshot = {
16
20
  observed: false,
17
21
  generationEnabled: null,
@@ -102,11 +106,7 @@ export function recordAgentConfig(config, generationEnabled, shipped) {
102
106
  const agents = {};
103
107
  for (const name of AGENT_NAMES) {
104
108
  const definition = configured?.[name];
105
- const source = definition === undefined
106
- ? "missing"
107
- : definitionsEqual(shipped[name], definition)
108
- ? "shipped"
109
- : "user_override";
109
+ const source = definition === undefined ? "missing" : definitionsEqual(shipped[name], definition) ? "shipped" : "user_override";
110
110
  agents[name] = inspectAgent(name, definition, source);
111
111
  if (!generationEnabled && definition === undefined) {
112
112
  agents[name] = { source: "missing", healthy: true, issues: ["generation disabled; agent not injected"] };
@@ -120,7 +120,10 @@ export function getAgentHealth() {
120
120
  generationEnabled: snapshot.generationEnabled,
121
121
  agents: {
122
122
  memorize: { ...snapshot.agents.memorize, issues: [...snapshot.agents.memorize.issues] },
123
- "memorize-extract": { ...snapshot.agents["memorize-extract"], issues: [...snapshot.agents["memorize-extract"].issues] },
123
+ "memorize-extract": {
124
+ ...snapshot.agents["memorize-extract"],
125
+ issues: [...snapshot.agents["memorize-extract"].issues],
126
+ },
124
127
  },
125
128
  };
126
129
  }
@@ -1,7 +1,7 @@
1
1
  import { SCAN_LIMIT } from "./store.js";
2
2
  import { getPluginInput } from "./llm.js";
3
3
  import { recordDiscoveryStatus } from "./diagnostics.js";
4
- import { hostListSessionsGlobal, hostPartType, hostSessionMessages, pluginHttpGet, withHostTimeout } from "./host-client.js";
4
+ import { hostListSessionsGlobal, hostPartType, hostSessionMessages, pluginHttpGet, withHostTimeout, } from "./host-client.js";
5
5
  const API_TIMEOUT_MS = 60_000;
6
6
  /**
7
7
  * Global session discovery through the official API:
@@ -22,9 +22,7 @@ export function resetDiscoveryCacheForTest() {
22
22
  }
23
23
  export async function listRecentSessions(limit = SCAN_LIMIT) {
24
24
  const now = Date.now();
25
- if (discoveryCache &&
26
- discoveryCache.limit >= limit &&
27
- now - discoveryCache.at < DISCOVERY_CACHE_MS) {
25
+ if (discoveryCache && discoveryCache.limit >= limit && now - discoveryCache.at < DISCOVERY_CACHE_MS) {
28
26
  return discoveryCache.rows.slice(0, limit);
29
27
  }
30
28
  const client = getPluginInput()?.client;
@@ -103,9 +101,11 @@ export async function loadTranscript(sessionId) {
103
101
  for (const part of row?.parts ?? []) {
104
102
  const question = part;
105
103
  const answer = question?.state?.output;
106
- const userReply = question?.tool === "question" && question.ignored !== true
107
- && typeof answer === "string" && answer.startsWith("User has answered your questions:")
108
- && /"="(?!Unanswered")[^"]+"/.test(answer)
104
+ const userReply = question?.tool === "question" &&
105
+ question.ignored !== true &&
106
+ typeof answer === "string" &&
107
+ answer.startsWith("User has answered your questions:") &&
108
+ /"="(?!Unanswered")[^"]+"/.test(answer)
109
109
  ? { question: JSON.stringify(question.state?.input ?? {}), answer }
110
110
  : undefined;
111
111
  out.push({
@@ -21,7 +21,10 @@ export function parseCitationBody(body) {
21
21
  continue;
22
22
  const sessions = trimmed.match(SESSIONS_LINE_RE);
23
23
  if (sessions) {
24
- for (const id of sessions[1].split(/[\s,]+/).map((s) => s.trim()).filter(Boolean)) {
24
+ for (const id of sessions[1]
25
+ .split(/[\s,]+/)
26
+ .map((s) => s.trim())
27
+ .filter(Boolean)) {
25
28
  if (!seen.has(id)) {
26
29
  seen.add(id);
27
30
  sessionIds.push(id);
@@ -108,7 +111,10 @@ export function parseCitations(text) {
108
111
  }
109
112
  else if (entriesBlock && entries.length === 0) {
110
113
  // Legacy format: <citation_entries> held a comma-separated session-id list.
111
- for (const id of entriesBlock.split(",").map((s) => s.trim()).filter(Boolean)) {
114
+ for (const id of entriesBlock
115
+ .split(",")
116
+ .map((s) => s.trim())
117
+ .filter(Boolean)) {
112
118
  if (!seen.has(id)) {
113
119
  seen.add(id);
114
120
  sessionIds.push(id);
@@ -134,5 +140,8 @@ export function extractCitedSessionIds(text) {
134
140
  return Array.from(seen);
135
141
  }
136
142
  export function stripCitations(text) {
137
- return text.replace(CITATION_BLOCK_RE, "").replace(/[ \t]*\n{3,}/g, "\n\n").trimEnd();
143
+ return text
144
+ .replace(CITATION_BLOCK_RE, "")
145
+ .replace(/[ \t]*\n{3,}/g, "\n\n")
146
+ .trimEnd();
138
147
  }
@@ -402,9 +402,7 @@ export function syncClaudeImport(opts) {
402
402
  const allFiles = discoverExternalMemoryFiles(claudeHome);
403
403
  const byProject = groupByProject(allFiles);
404
404
  const sourceKeys = new Set(byProject.keys());
405
- const allowlist = opts.projects && opts.projects.length > 0
406
- ? new Set(opts.projects.filter(isSafeProjectKey))
407
- : null;
405
+ const allowlist = opts.projects && opts.projects.length > 0 ? new Set(opts.projects.filter(isSafeProjectKey)) : null;
408
406
  // Desired set: allowlist, or every source project (cwd checked per project).
409
407
  const desired = new Set();
410
408
  if (allowlist) {
@@ -2,6 +2,7 @@ import fs from "fs";
2
2
  import path from "path";
3
3
  import os from "os";
4
4
  import { currentMemoryVersion } from "./memory-version.js";
5
+ import { pluginOptions } from "./options.js";
5
6
  import { memoryRoot } from "./paths.js";
6
7
  import { isValidV2Summary } from "./workspace.js";
7
8
  import { readRegularFileNoFollow, safeResolveUnderRoot, writeRegularFileNoFollow } from "./path-guard.js";
@@ -382,14 +383,31 @@ function describeVersion(value) {
382
383
  return typeof value;
383
384
  }
384
385
  /**
385
- * Selected Codex read version from `$CODEX_HOME/config.toml` only.
386
+ * Codex's runtime default when `memories.version` is unset (a390571745, #56211,
387
+ * 2026-10-22): a fresh profile (no `memories/` directory) uses v2 unless
388
+ * `dual_write = false`. Exchange mirrors the same observable signal instead of
389
+ * assuming v1. Explicit versions always win; profile, project, and session
390
+ * layers are still not merged. `memories_v2/` alone is enough evidence for v2
391
+ * when `memories/` is absent.
392
+ */
393
+ function resolveUnsetCodexVersion(codexHome, dualWrite) {
394
+ if (dualWrite === false)
395
+ return "v1";
396
+ if (fs.existsSync(path.join(codexHome, CODEX_MEMORY_DIR.v1)))
397
+ return "v1";
398
+ if (fs.existsSync(path.join(codexHome, CODEX_MEMORY_DIR.v2)))
399
+ return "v2";
400
+ return "v1";
401
+ }
402
+ /**
403
+ * Selected Codex read version from `$CODEX_HOME/config.toml` plus the same
404
+ * directory signal Codex uses for fresh profiles.
386
405
  *
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.
406
+ * Explicit `memories.version` wins. Unset, missing file, or a `[memories]`
407
+ * table with no `version` → `memories/` exists ? v1 : `memories_v2/` exists ?
408
+ * v2 : v1. `memories.dual_write = false` keeps v1 (Codex's transition opt-out).
409
+ * An unreadable file, a parse failure, or a value other than "v1"/"v2" fails
410
+ * closed so a leftover `memories/` handbook is not imported by guess.
393
411
  */
394
412
  function readCodexMemoryVersion(codexHome) {
395
413
  const file = path.join(codexHome, CODEX_CONFIG_FILE);
@@ -398,8 +416,9 @@ function readCodexMemoryVersion(codexHome) {
398
416
  text = fs.readFileSync(file, "utf8");
399
417
  }
400
418
  catch (err) {
401
- if (err.code === "ENOENT")
402
- return { ok: true, version: "v1" };
419
+ if (err.code === "ENOENT") {
420
+ return { ok: true, version: resolveUnsetCodexVersion(codexHome, undefined) };
421
+ }
403
422
  return { ok: false, reason: `could not read ${file}` };
404
423
  }
405
424
  let parsed;
@@ -414,13 +433,14 @@ function readCodexMemoryVersion(codexHome) {
414
433
  }
415
434
  const memories = parsed.memories;
416
435
  if (memories == null)
417
- return { ok: true, version: "v1" };
436
+ return { ok: true, version: resolveUnsetCodexVersion(codexHome, undefined) };
418
437
  if (typeof memories !== "object" || Array.isArray(memories)) {
419
438
  return { ok: false, reason: `${file} memories.version is not "v1" or "v2"` };
420
439
  }
421
- const version = memories.version;
440
+ const table = memories;
441
+ const version = table.version;
422
442
  if (version == null)
423
- return { ok: true, version: "v1" };
443
+ return { ok: true, version: resolveUnsetCodexVersion(codexHome, table.dual_write) };
424
444
  if (version === "v1" || version === "v2")
425
445
  return { ok: true, version };
426
446
  return { ok: false, reason: `${file} memories.version ${describeVersion(version)} is not "v1" or "v2"` };
@@ -451,7 +471,7 @@ function classifyCodexInterop(opts, warn) {
451
471
  codexMemoryRoot,
452
472
  codexVersion: version.version,
453
473
  importEnabled: opts.import,
454
- exportEnabled: opts.export,
474
+ exportEnabled: opts.export && currentMemoryVersion() === pluginOptions.version,
455
475
  },
456
476
  };
457
477
  }
@@ -480,6 +500,17 @@ function readIfFile(file) {
480
500
  return null;
481
501
  }
482
502
  }
503
+ /** Only a confirmed missing artifact authorizes forgetting its previous copy. */
504
+ function readSource(file) {
505
+ try {
506
+ return readRegularFileNoFollow(file).content;
507
+ }
508
+ catch (error) {
509
+ if (error.code === "ENOENT")
510
+ return null;
511
+ throw error;
512
+ }
513
+ }
483
514
  /** Writes only when content differs (codex byte-equality sync). Returns true when written. */
484
515
  function writeIfChanged(file, content) {
485
516
  const next = typeof content === "string" ? Buffer.from(content, "utf8") : content;
@@ -528,8 +559,10 @@ function syncExtension(sourceRoot, targetRoot, extension, subdir, instructions,
528
559
  return false;
529
560
  const extensionDir = safeResolveUnderRoot(targetRoot, path.join("extensions", extension));
530
561
  const resDir = safeResolveUnderRoot(targetRoot, path.join("extensions", extension, "resources", subdir));
531
- const sourceAvailable = artifacts.some((name) => readIfFile(path.join(sourceRoot, name)) !== null);
532
- if (!sourceAvailable) {
562
+ const sources = artifacts.map((name) => [name, readSource(path.join(sourceRoot, name))]);
563
+ if (!fs.statSync(sourceRoot).isDirectory())
564
+ return false;
565
+ if (sources.every(([, content]) => content === null)) {
533
566
  // Root exists but the artifacts for this store are gone (e.g. codex memory
534
567
  // cleared, or a v2 root with no summary). Drop our copies so the workspace
535
568
  // diff carries the deletion signal. Keep instructions.md — prune and
@@ -543,8 +576,7 @@ function syncExtension(sourceRoot, targetRoot, extension, subdir, instructions,
543
576
  if (writeIfChanged(path.join(extensionDir, "instructions.md"), instructions))
544
577
  changed = true;
545
578
  const active = new Set(artifacts);
546
- for (const name of artifacts) {
547
- const source = readIfFile(path.join(sourceRoot, name));
579
+ for (const [name, source] of sources) {
548
580
  const target = path.join(resDir, name);
549
581
  if (source === null) {
550
582
  if (removeIfPresent(target))
@@ -612,6 +644,8 @@ function exportPlan(codexVersion) {
612
644
  };
613
645
  }
614
646
  export function exportToCodexMemory(codexMemoryRoot, version) {
647
+ if (currentMemoryVersion() !== pluginOptions.version)
648
+ return false;
615
649
  let rootStat;
616
650
  try {
617
651
  rootStat = fs.statSync(codexMemoryRoot);
package/dist/src/db.d.ts CHANGED
@@ -2,8 +2,6 @@ import { Database } from "bun:sqlite";
2
2
  import type { MemoryVersion } from "./options.js";
3
3
  /** Both versioned handles stay open while their pipelines run concurrently. */
4
4
  export declare function openDb(version?: MemoryVersion): Database;
5
- /** One-shot connection for reset across versioned files. Caller must close. */
6
- export declare function openTransientDb(dbPath: string): Database;
7
5
  /** Always memory.db — shared session_meta catalog across versions. */
8
6
  export declare function openSessionMetaDb(): Database;
9
7
  export declare function closeDb(): void;
package/dist/src/db.js CHANGED
@@ -74,10 +74,6 @@ function connection(dbPath) {
74
74
  export function openDb(version) {
75
75
  return connection(memoryDbPath(version));
76
76
  }
77
- /** One-shot connection for reset across versioned files. Caller must close. */
78
- export function openTransientDb(dbPath) {
79
- return openSqlite(dbPath);
80
- }
81
77
  /** Always memory.db — shared session_meta catalog across versions. */
82
78
  export function openSessionMetaDb() {
83
79
  return connection(sessionMetaDbPath());
@@ -7,18 +7,18 @@ export interface WorkspaceDiff {
7
7
  changes: WorkspaceChange[];
8
8
  unifiedDiff: string;
9
9
  /**
10
- * Content hash of every `extensions/` file at capture time. Notes written
11
- * while the consolidator runs are not in this diff; resetBaseline keeps
12
- * them out of the new baseline so the next run still sees them.
10
+ * Git blob for each extension input seen by the consolidator. The new
11
+ * baseline stages these exact bytes even if a file has since disappeared.
13
12
  */
14
13
  extensionSnapshot?: ReadonlyMap<string, string>;
15
14
  }
16
15
  /**
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.
16
+ * Mirrors codex prepare_memory_workspace: a current-version baseline is
17
+ * preserved untouched so the phase-2 diff spans last-successful-run -> now —
18
+ * including manual user edits and newly added ad-hoc notes. Committing here
19
+ * would swallow those changes and consolidation would never see them. Missing,
20
+ * outdated, or unusable metadata gets an empty baseline (codex keeps existing
21
+ * memory files visible as additions).
22
22
  */
23
23
  export declare function ensureBaseline(): Promise<boolean>;
24
24
  export declare function captureWorkspaceDiff(): Promise<WorkspaceDiff>;
@@ -27,8 +27,7 @@ export declare function captureWorkspaceDiff(): Promise<WorkspaceDiff>;
27
27
  * single-commit baseline so deleted/redacted memory content is not retained
28
28
  * in unreachable git objects (history is intentionally dropped).
29
29
  *
30
- * Divergence: `extensions/` files added or edited after `captured` (e.g. a
31
- * memory_add_note during the consolidator turn) stay out of the baseline, so
32
- * they appear as added in the next diff instead of never being consolidated.
30
+ * Stage captured extension blobs alongside live consolidator outputs. This
31
+ * preserves concurrent additions, edits AND deletions for the next diff.
33
32
  */
34
33
  export declare function resetBaseline(captured?: ReadonlyMap<string, string>): Promise<boolean>;