opencode-codex-memory 0.7.6 → 0.8.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.
Files changed (60) hide show
  1. package/README.md +51 -8
  2. package/dist/opencode.json +2 -2
  3. package/dist/src/capture.d.ts +5 -0
  4. package/dist/src/capture.js +8 -0
  5. package/dist/src/codex-interop.js +5 -0
  6. package/dist/src/db.d.ts +7 -1
  7. package/dist/src/db.js +38 -11
  8. package/dist/src/diagnostics.js +5 -1
  9. package/dist/src/host-client.d.ts +5 -0
  10. package/dist/src/index.d.ts +12 -4
  11. package/dist/src/index.js +71 -66
  12. package/dist/src/lifecycle.js +14 -9
  13. package/dist/src/llm.d.ts +3 -2
  14. package/dist/src/llm.js +47 -11
  15. package/dist/src/local-session-times.d.ts +6 -0
  16. package/dist/src/local-session-times.js +59 -0
  17. package/dist/src/memory-version.d.ts +5 -0
  18. package/dist/src/memory-version.js +16 -0
  19. package/dist/src/migration.d.ts +24 -0
  20. package/dist/src/migration.js +37 -0
  21. package/dist/src/options.d.ts +10 -0
  22. package/dist/src/options.js +3 -0
  23. package/dist/src/paths.d.ts +9 -3
  24. package/dist/src/paths.js +22 -8
  25. package/dist/src/phase1.js +16 -2
  26. package/dist/src/phase2.js +15 -9
  27. package/dist/src/pipeline.d.ts +3 -0
  28. package/dist/src/pipeline.js +74 -0
  29. package/dist/src/ratelimit.js +9 -4
  30. package/dist/src/rollout-input.d.ts +3 -2
  31. package/dist/src/rollout-input.js +26 -17
  32. package/dist/src/session-version.d.ts +9 -0
  33. package/dist/src/session-version.js +27 -0
  34. package/dist/src/source.js +21 -6
  35. package/dist/src/store.d.ts +19 -3
  36. package/dist/src/store.js +121 -38
  37. package/dist/src/templates/consolidation_v2.md +54 -0
  38. package/dist/src/templates/read_path_v2.md +58 -0
  39. package/dist/src/templates/stage_one_input_v2.md +21 -0
  40. package/dist/src/templates/stage_one_system_v2.md +53 -0
  41. package/dist/src/token.d.ts +2 -0
  42. package/dist/src/token.js +16 -0
  43. package/dist/src/v2/agents.d.ts +4 -2
  44. package/dist/src/v2/agents.js +15 -7
  45. package/dist/src/v2/citation-overlay.d.ts +1 -1
  46. package/dist/src/v2/citation-overlay.js +27 -4
  47. package/dist/src/v2/plugin.js +27 -74
  48. package/dist/src/v2/shim.js +20 -9
  49. package/dist/src/v2/status-rpc.d.ts +70 -1
  50. package/dist/src/v2/status-rpc.js +41 -2
  51. package/dist/src/v2/status.d.ts +1 -1
  52. package/dist/src/v2/status.js +35 -9
  53. package/dist/src/v2/tui.js +57 -2
  54. package/dist/src/workspace.d.ts +8 -6
  55. package/dist/src/workspace.js +31 -11
  56. package/dist/tools/control.d.ts +6 -2
  57. package/dist/tools/control.js +209 -155
  58. package/dist/tools/memory.js +11 -1
  59. package/opencode.json +2 -2
  60. package/package.json +1 -1
package/README.md CHANGED
@@ -53,7 +53,7 @@ If you want the mental model — learning, remembering, forgetting — see
53
53
 
54
54
  ```json
55
55
  {
56
- "plugin": ["opencode-codex-memory@0.7.6"]
56
+ "plugin": ["opencode-codex-memory@0.8.0"]
57
57
  }
58
58
  ```
59
59
 
@@ -73,7 +73,7 @@ V2 plugin syntax:
73
73
 
74
74
  ```jsonc
75
75
  {
76
- "plugins": [{ "package": "opencode-codex-memory@0.7.6" }],
76
+ "plugins": [{ "package": "opencode-codex-memory@0.8.0" }],
77
77
  }
78
78
  ```
79
79
 
@@ -189,6 +189,8 @@ Codex's `[memories]` config so the two stay easy to compare:
189
189
  | Option | Default | Meaning |
190
190
  |---|---|---|
191
191
  | `generate_memories` | `true` | Turn the background learning pipeline on/off |
192
+ | `version` | `"v1"` | Read version for new sessions, and the sole writer when dual-write is off. `"v2"` is summary-only, with recaps in isolated `memories_v2/` and no `MEMORY.md`. |
193
+ | `dual_write` | `false` | Run both learning pipelines independently while reading the selected version. Enables V2 warmup before an explicit cutover. |
192
194
  | `use_memories` | `true` | Inject the memory summary into the system prompt |
193
195
  | `dedicated_tools` | `true` | Expose the `memory_read`/`memory_search`/`memory_list`/`memory_add_note` tools |
194
196
  | `disable_on_external_context` | `false` | Exclude sessions that used web/MCP tools from memory |
@@ -208,7 +210,7 @@ To set options, turn the plugin entry into a `[name, options]` pair:
208
210
  ```json
209
211
  {
210
212
  "plugin": [
211
- ["opencode-codex-memory@0.7.6", { "disable_on_external_context": true, "min_rollout_idle_hours": 2 }]
213
+ ["opencode-codex-memory@0.8.0", { "disable_on_external_context": true, "min_rollout_idle_hours": 2 }]
212
214
  ]
213
215
  }
214
216
  ```
@@ -263,6 +265,47 @@ nearest OpenCode variant on `none < minimal < low < medium < high < xhigh < max`
263
265
  > maintenance tools (`memory_reset`, `memory_inspect`, `memory_mode`) stay
264
266
  > available either way.
265
267
 
268
+ ### Migrating from memory V1 to V2
269
+
270
+ Memory versions are independent of OpenCode host versions: both work on
271
+ OpenCode 1.x and 2.x. V1 remains the default. See the
272
+ [conceptual comparison](docs/how-ai-memory-works.md#two-versions-v1-and-v2)
273
+ for the different learning contracts.
274
+
275
+ 1. Set these **plugin options** and restart OpenCode's server:
276
+
277
+ ```json
278
+ { "version": "v1", "dual_write": true }
279
+ ```
280
+
281
+ V1 continues serving memory. Both pipelines independently extract eligible
282
+ conversations and consolidate into their own workspaces. This adds model
283
+ calls for the second pipeline; it does not copy or convert V1 artifacts.
284
+
285
+ 2. Check `memory_inspect`, or `/memory` on OpenCode 2. `v2_ready` becomes true
286
+ when V2 has a valid summary and one successful consolidation has consumed
287
+ at least **20 distinct sessions**. The count is a high-water mark, not a
288
+ lifetime sum, so repeated consolidation of one session cannot make V2 ready.
289
+ `min_consolidated_threads` on inspect (RPC: `minConsolidatedThreads`) can
290
+ override the reporting threshold from 1 to 4096; it does not change config
291
+ or switch versions. Readiness is a warmup signal, not a quality guarantee.
292
+
293
+ 3. When ready, set `version: "v2"` and restart the server. New sessions use V2.
294
+ Existing sessions keep the version selected on their first memory use,
295
+ including retrieval tools, explicit notes, and citation accounting across
296
+ server restarts. Start a new session to try the new read path.
297
+
298
+ 4. Keep `dual_write: true` while evaluating V2, then set it to `false` when you
299
+ want only V2 learning. To roll back, select `version: "v1"` and start a new
300
+ session. If dual-write was off, V1 will not contain the intervening learning.
301
+
302
+ There is no automatic cutover. An explicit "remember this" note goes to the
303
+ requesting session's selected workspace; the other writer learns from eligible
304
+ conversation history. Disabled/polluted session flags are shared. Session
305
+ deletion removes extracted rows from both stores and queues forgetting;
306
+ `memory_reset` clears both stores and workspaces, preserving session modes and
307
+ read-version stamps. Inactive stores resume queued consolidation when enabled.
308
+
266
309
  ### Relocating memory (sandbox mounts)
267
310
 
268
311
  First match wins:
@@ -280,7 +323,7 @@ dedicated directory:
280
323
  ```json
281
324
  {
282
325
  "plugin": [
283
- ["opencode-codex-memory@0.7.6", { "home": "/path/to/opencode-memory" }]
326
+ ["opencode-codex-memory@0.8.0", { "home": "/path/to/opencode-memory" }]
284
327
  ]
285
328
  }
286
329
  ```
@@ -290,7 +333,7 @@ OpenCode 2:
290
333
  ```jsonc
291
334
  {
292
335
  "plugins": [
293
- { "package": "opencode-codex-memory@0.7.6", "options": { "home": "/path/to/opencode-memory" } }
336
+ { "package": "opencode-codex-memory@0.8.0", "options": { "home": "/path/to/opencode-memory" } }
294
337
  ]
295
338
  }
296
339
  ```
@@ -325,7 +368,7 @@ Off by default; no changes to Codex's own config are required.
325
368
  {
326
369
  "plugin": [
327
370
  [
328
- "opencode-codex-memory@0.7.6",
371
+ "opencode-codex-memory@0.8.0",
329
372
  { "codex_interop": { "import": true, "export": true } }
330
373
  ]
331
374
  ]
@@ -382,7 +425,7 @@ from the project memories Claude already keeps on your machine. **One-way only**
382
425
  ```json
383
426
  {
384
427
  "plugin": [
385
- ["opencode-codex-memory@0.7.6", { "claude_import": { "enabled": true } }]
428
+ ["opencode-codex-memory@0.8.0", { "claude_import": { "enabled": true } }]
386
429
  ]
387
430
  }
388
431
  ```
@@ -409,7 +452,7 @@ Claude names each project with an opaque id (a folder under
409
452
  {
410
453
  "plugin": [
411
454
  [
412
- "opencode-codex-memory@0.7.6",
455
+ "opencode-codex-memory@0.8.0",
413
456
  {
414
457
  "claude_import": {
415
458
  "enabled": true,
@@ -3,7 +3,7 @@
3
3
  "agent": {
4
4
  "memorize": {
5
5
  "mode": "subagent",
6
- "prompt": "You are a memory consolidation agent. Read the workspace diff file and update MEMORY.md, memory_summary.md, and skills/ under the memory workspace only. Do not read or edit project source files outside that memory root. Keep memory_summary.md under 10000 chars (2500 tokens). Prune stale entries. Do not access the network.",
6
+ "prompt": "You are a memory consolidation agent. Follow the supplied version-specific consolidation contract and update only its requested artifacts under the supplied memory workspace. Do not read or edit project source files or a different memory workspace. Keep memory_summary.md under 10000 bytes. Prune stale entries. Do not access the network.",
7
7
  "permission": {
8
8
  "*": "deny",
9
9
  "bash": "deny",
@@ -20,7 +20,7 @@
20
20
  },
21
21
  "memorize-extract": {
22
22
  "mode": "subagent",
23
- "prompt": "You are a memory extraction agent. The session transcript is provided inline in the prompt. Extract raw_memory, rollout_summary, and rollout_slug as JSON. Exclude AGENTS.md/instruction content. Redact secrets.",
23
+ "prompt": "You are a memory extraction agent. The session transcript is provided inline in the prompt. Follow the supplied version-specific JSON schema. Exclude AGENTS.md/instruction content. Redact secrets.",
24
24
  "permission": {
25
25
  "*": "deny",
26
26
  "bash": "deny",
@@ -11,6 +11,11 @@ export interface TranscriptMessage {
11
11
  type: string;
12
12
  role?: string;
13
13
  text?: string;
14
+ /** Native question-tool replies are human evidence, paired with the question. */
15
+ userReply?: {
16
+ question: string;
17
+ answer: string;
18
+ };
14
19
  }
15
20
  /**
16
21
  * Transcript loading uses the official API — the same surface opencode's own
@@ -97,10 +97,18 @@ export async function loadTranscript(sessionId) {
97
97
  for (const row of rows) {
98
98
  const role = row?.info?.role;
99
99
  for (const part of row?.parts ?? []) {
100
+ const question = part;
101
+ const answer = question?.state?.output;
102
+ const userReply = question?.tool === "question" && question.ignored !== true
103
+ && typeof answer === "string" && answer.startsWith("User has answered your questions:")
104
+ && /"="(?!Unanswered")[^"]+"/.test(answer)
105
+ ? { question: JSON.stringify(question.state?.input ?? {}), answer }
106
+ : undefined;
100
107
  out.push({
101
108
  type: hostPartType(part),
102
109
  role,
103
110
  text: extractText(part),
111
+ ...(userReply ? { userReply } : {}),
104
112
  });
105
113
  }
106
114
  }
@@ -1,6 +1,7 @@
1
1
  import fs from "fs";
2
2
  import path from "path";
3
3
  import os from "os";
4
+ import { currentMemoryVersion } from "./memory-version.js";
4
5
  import { memoryRoot } from "./paths.js";
5
6
  import { readRegularFileNoFollow, safeResolveUnderRoot, writeRegularFileNoFollow } from "./path-guard.js";
6
7
  /**
@@ -189,6 +190,10 @@ function overlaps(a, b) {
189
190
  export function resolveCodexInterop(opts) {
190
191
  if (!opts.import && !opts.export)
191
192
  return null;
193
+ if (currentMemoryVersion() === "v2") {
194
+ console.warn("[opencode-codex-memory] codex_interop disabled: handbook exchange is v1-only while version=v2");
195
+ return null;
196
+ }
192
197
  // codex find_codex_home ignores an EMPTY env var (home-dir/src/lib.rs);
193
198
  // without the filter "" would resolve to a cwd-relative "memories" path.
194
199
  const envHome = process.env[CODEX_HOME_ENV];
package/dist/src/db.d.ts CHANGED
@@ -1,3 +1,9 @@
1
1
  import { Database } from "bun:sqlite";
2
- export declare function openDb(): Database;
2
+ import type { MemoryVersion } from "./options.js";
3
+ /** Both versioned handles stay open while their pipelines run concurrently. */
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
+ /** Always memory.db — shared session_meta catalog across versions. */
8
+ export declare function openSessionMetaDb(): Database;
3
9
  export declare function closeDb(): void;
package/dist/src/db.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Database } from "bun:sqlite";
2
2
  import fs from "fs";
3
3
  import path from "path";
4
- import { memoryDbPath } from "./paths.js";
4
+ import { memoryDbPath, sessionMetaDbPath } from "./paths.js";
5
5
  const SCHEMA_V1 = [
6
6
  `CREATE TABLE IF NOT EXISTS memory_stage1_outputs (
7
7
  session_id TEXT PRIMARY KEY,
@@ -43,11 +43,8 @@ const SCHEMA_V1 = [
43
43
  updated_at INTEGER NOT NULL
44
44
  )`,
45
45
  ];
46
- let dbInstance = null;
47
- export function openDb() {
48
- if (dbInstance)
49
- return dbInstance;
50
- const dbPath = memoryDbPath();
46
+ const connections = new Map();
47
+ function openSqlite(dbPath) {
51
48
  fs.mkdirSync(path.dirname(dbPath), { recursive: true });
52
49
  const db = new Database(dbPath, { create: true, readwrite: true, strict: false });
53
50
  try {
@@ -58,7 +55,6 @@ export function openDb() {
58
55
  db.run("PRAGMA busy_timeout=5000");
59
56
  db.run("PRAGMA auto_vacuum=INCREMENTAL");
60
57
  runMigrations(db);
61
- dbInstance = db;
62
58
  return db;
63
59
  }
64
60
  catch (err) {
@@ -66,6 +62,26 @@ export function openDb() {
66
62
  throw err;
67
63
  }
68
64
  }
65
+ function connection(dbPath) {
66
+ let db = connections.get(dbPath);
67
+ if (!db) {
68
+ db = openSqlite(dbPath);
69
+ connections.set(dbPath, db);
70
+ }
71
+ return db;
72
+ }
73
+ /** Both versioned handles stay open while their pipelines run concurrently. */
74
+ export function openDb(version) {
75
+ return connection(memoryDbPath(version));
76
+ }
77
+ /** One-shot connection for reset across versioned files. Caller must close. */
78
+ export function openTransientDb(dbPath) {
79
+ return openSqlite(dbPath);
80
+ }
81
+ /** Always memory.db — shared session_meta catalog across versions. */
82
+ export function openSessionMetaDb() {
83
+ return connection(sessionMetaDbPath());
84
+ }
69
85
  function runMigrations(db) {
70
86
  db.run(`CREATE TABLE IF NOT EXISTS schema_version (
71
87
  version INTEGER NOT NULL,
@@ -91,11 +107,22 @@ function runMigrations(db) {
91
107
  )`);
92
108
  db.prepare("INSERT INTO schema_version (version, applied_at) VALUES (?, ?)").run(2, Date.now());
93
109
  }
110
+ if (currentVersion < 3) {
111
+ db.run(`CREATE TABLE consolidation_progress (
112
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
113
+ max_thread_count INTEGER NOT NULL DEFAULT 0
114
+ )`);
115
+ db.run("INSERT INTO consolidation_progress (singleton, max_thread_count) VALUES (1, 0)");
116
+ db.run(`CREATE TABLE memory_session_versions (
117
+ session_id TEXT PRIMARY KEY,
118
+ version TEXT NOT NULL CHECK (version IN ('v1', 'v2'))
119
+ )`);
120
+ db.prepare("INSERT INTO schema_version (version, applied_at) VALUES (?, ?)").run(3, Date.now());
121
+ }
94
122
  }).immediate();
95
123
  }
96
124
  export function closeDb() {
97
- if (dbInstance) {
98
- dbInstance.close();
99
- dbInstance = null;
100
- }
125
+ for (const db of connections.values())
126
+ db.close();
127
+ connections.clear();
101
128
  }
@@ -13,11 +13,15 @@ export function recordDiagnostic(level, kind, message) {
13
13
  events.shift();
14
14
  }
15
15
  export function recordDiscoveryStatus(status) {
16
+ const prev = discovery;
16
17
  discovery = { ...status, at: Date.now() };
17
18
  if (!status.ok) {
18
19
  recordDiagnostic("warn", "discovery", status.error ?? "session discovery failed");
20
+ return;
19
21
  }
20
- else {
22
+ // Same count every 30s cache hit is not a pipeline event — only log
23
+ // changes (or the first success) so inspect is not 12× "listed 1".
24
+ if (!prev || !prev.ok || prev.count !== status.count) {
21
25
  recordDiagnostic("info", "discovery", `listed ${status.count} session(s)`);
22
26
  }
23
27
  }
@@ -45,6 +45,11 @@ export declare function withHostTimeout<T>(promise: Promise<T>, ms: number, labe
45
45
  export interface SessionCreateBody {
46
46
  title?: string;
47
47
  metadata?: Record<string, unknown>;
48
+ permission?: {
49
+ permission: string;
50
+ pattern: string;
51
+ action: "allow" | "deny";
52
+ }[];
48
53
  }
49
54
  /** GET /provider. V1 SDK types omit model.variants; parse the payload loosely. */
50
55
  export declare function hostProviderList(client: PluginInput["client"] | null | undefined, opts?: {
@@ -101,8 +101,12 @@ declare const _default: {
101
101
  };
102
102
  memory_inspect: {
103
103
  description: string;
104
- args: {};
105
- execute(args: Record<string, never>, context: import("@opencode-ai/plugin").ToolContext): Promise<import("@opencode-ai/plugin").ToolResult>;
104
+ args: {
105
+ min_consolidated_threads: import("zod").ZodOptional<import("zod").ZodNumber>;
106
+ };
107
+ execute(args: {
108
+ min_consolidated_threads?: number | undefined;
109
+ }, context: import("@opencode-ai/plugin").ToolContext): Promise<import("@opencode-ai/plugin").ToolResult>;
106
110
  };
107
111
  memory_mode: {
108
112
  description: string;
@@ -131,8 +135,12 @@ declare const _default: {
131
135
  };
132
136
  memory_inspect: {
133
137
  description: string;
134
- args: {};
135
- execute(args: Record<string, never>, context: import("@opencode-ai/plugin").ToolContext): Promise<import("@opencode-ai/plugin").ToolResult>;
138
+ args: {
139
+ min_consolidated_threads: import("zod").ZodOptional<import("zod").ZodNumber>;
140
+ };
141
+ execute(args: {
142
+ min_consolidated_threads?: number | undefined;
143
+ }, context: import("@opencode-ai/plugin").ToolContext): Promise<import("@opencode-ai/plugin").ToolResult>;
136
144
  };
137
145
  memory_mode: {
138
146
  description: string;
package/dist/src/index.js CHANGED
@@ -1,20 +1,20 @@
1
1
  import { ensureMemoryLayout, buildMemorySystemPrompt, invalidateCache } from "./source.js";
2
- import { memoryRoot, memoryDbPath, setConfiguredHome, resolveHomePath } from "./paths.js";
2
+ import { memoryRoot, dataRoot, setConfiguredHome, resolveHomePath } from "./paths.js";
3
3
  import { closeDb } from "./db.js";
4
4
  import { stripCitations, extractCitedSessionIds, hasCitationMarkup } from "./citation.js";
5
5
  import { memory_read, memory_search, memory_list, memory_add_note } from "../tools/memory.js";
6
6
  import { memory_reset, memory_inspect, memory_mode } from "../tools/control.js";
7
7
  import { MemoryStore } from "./store.js";
8
- import { runPhase1 } from "./phase1.js";
9
- import { runPhase2 } from "./phase2.js";
8
+ import { runMemoryPipeline, runMemoryConsolidation } from "./pipeline.js";
9
+ import { writeMemoryVersions } from "./memory-version.js";
10
+ import { sessionMemoryVersion, withSessionMemoryVersion } from "./session-version.js";
11
+ import { existingMemoryStores } from "./store.js";
10
12
  import { setPluginInput, cleanupOldSubSessions, isMemorySubSession, abortActiveSubSessions } from "./llm.js";
11
13
  import { pluginOptions, recordConfigWarning, clearConfigWarnings, resetPluginOptions } from "./options.js";
12
- import { beginPluginShutdown, isPluginShuttingDown, resetPluginLifecycle } from "./lifecycle.js";
14
+ import { beginPluginShutdown, resetPluginLifecycle } from "./lifecycle.js";
13
15
  import { hostMcpStatus } from "./host-client.js";
14
- import { recordDiagnostic } from "./diagnostics.js";
15
16
  import { loadBundledAgentDefinitions, recordAgentConfig, resetAgentHealth } from "./agent-health.js";
16
17
  import path from "path";
17
- let phase1InFlight = false;
18
18
  let pluginClient = null;
19
19
  const backgroundTasks = new Set();
20
20
  function trackBackgroundTask(task) {
@@ -110,14 +110,18 @@ export function shouldHandleIdle(sessionId, now = Date.now()) {
110
110
  lruSet(recentIdle, sessionId, deduped ? last : now, MAX_TRACKED_IDLE);
111
111
  return !deduped;
112
112
  }
113
- export function handleSessionDeleted(sessionId, store = getStore(),
113
+ export function handleSessionDeleted(sessionId, store,
114
114
  // With generation off the memorize agent is not injected, so a consolidation
115
115
  // attempt could only fail; the row deletion above still happens, and the
116
116
  // enqueued job runs when generation is re-enabled (codex: delete only
117
117
  // enqueues; the pipeline itself is gated elsewhere).
118
118
  schedulePhase2 = () => { if (pluginOptions.generate_memories)
119
119
  trackBackgroundTask(triggerPhase2()); }) {
120
- if (store.deleteSessionMemory(sessionId))
120
+ const stores = store ? [store] : existingMemoryStores();
121
+ let changed = false;
122
+ for (const target of stores)
123
+ changed = target.deleteSessionMemory(sessionId) || changed;
124
+ if (changed)
121
125
  schedulePhase2();
122
126
  }
123
127
  export default {
@@ -139,17 +143,19 @@ export default {
139
143
  if (opts)
140
144
  applyPluginOptions(opts);
141
145
  else {
142
- const previousDb = memoryDbPath();
146
+ const previousDb = dataRoot();
143
147
  resetPluginOptions();
144
- if (memoryDbPath() !== previousDb)
148
+ if (dataRoot() !== previousDb)
145
149
  closeDb();
146
150
  }
147
151
  // Finish bounded reseeding before hooks can see a surviving memory
148
152
  // sub-session after a plugin reload.
149
153
  await cleanupOldSubSessions();
150
154
  try {
151
- if (getStore().releaseOrphanedPhase2Job()) {
152
- console.warn("[opencode-codex-memory] released a consolidation lease orphaned by a dead process");
155
+ for (const store of existingMemoryStores()) {
156
+ if (store.releaseOrphanedPhase2Job()) {
157
+ console.warn(`[opencode-codex-memory] released orphaned ${store.version} consolidation lease`);
158
+ }
153
159
  }
154
160
  }
155
161
  catch (err) {
@@ -163,6 +169,8 @@ const KNOWN_OPTION_KEYS = new Set([
163
169
  "use_memories",
164
170
  "dedicated_tools",
165
171
  "disable_on_external_context",
172
+ "version",
173
+ "dual_write",
166
174
  "extract_model",
167
175
  "consolidation_model",
168
176
  "max_raw_memories_for_consolidation",
@@ -170,6 +178,7 @@ const KNOWN_OPTION_KEYS = new Set([
170
178
  "max_rollout_age_days",
171
179
  "max_rollouts_per_startup",
172
180
  "min_rollout_idle_hours",
181
+ "test",
173
182
  "home",
174
183
  "codex_interop",
175
184
  "claude_import",
@@ -186,10 +195,18 @@ function clampInt(key, value, min, max, fallback) {
186
195
  }
187
196
  return Math.min(max, Math.max(min, Math.floor(value)));
188
197
  }
198
+ /** Finite number, no Codex range clamp. Used only when options.test is true. */
199
+ function finiteNumber(key, value, fallback) {
200
+ if (typeof value !== "number" || !Number.isFinite(value)) {
201
+ recordConfigWarning(`${key} must be a finite number; using default ${fallback}`);
202
+ return fallback;
203
+ }
204
+ return value;
205
+ }
189
206
  export function applyPluginOptions(opts) {
190
207
  // Fresh pass per apply so memory_inspect never shows warnings for keys the
191
208
  // caller has since fixed. server() clears too, for boots without options.
192
- const previousDb = memoryDbPath();
209
+ const previousDb = dataRoot();
193
210
  clearConfigWarnings();
194
211
  resetPluginOptions();
195
212
  const raw = opts;
@@ -201,7 +218,7 @@ export function applyPluginOptions(opts) {
201
218
  recordConfigWarning(`unknown/unsupported option '${key}' ignored`);
202
219
  }
203
220
  }
204
- for (const key of ["generate_memories", "use_memories", "dedicated_tools", "disable_on_external_context"]) {
221
+ for (const key of ["generate_memories", "use_memories", "dedicated_tools", "disable_on_external_context", "dual_write"]) {
205
222
  if (!(key in raw))
206
223
  continue;
207
224
  if (typeof raw[key] === "boolean")
@@ -209,6 +226,13 @@ export function applyPluginOptions(opts) {
209
226
  else
210
227
  recordConfigWarning(`${key} must be a boolean; using default ${pluginOptions[key]}`);
211
228
  }
229
+ // options.test: live-harness only. Skips MemoriesToml numeric clamps.
230
+ if ("test" in raw) {
231
+ if (typeof raw.test === "boolean")
232
+ pluginOptions.test = raw.test;
233
+ else
234
+ recordConfigWarning("test must be a boolean; using default false");
235
+ }
212
236
  for (const key of ["extract_model", "consolidation_model"]) {
213
237
  if (!(key in raw))
214
238
  continue;
@@ -217,16 +241,33 @@ export function applyPluginOptions(opts) {
217
241
  else
218
242
  recordConfigWarning(`${key} must be a string; using the opencode model default`);
219
243
  }
244
+ const testing = pluginOptions.test;
245
+ if ("version" in raw) {
246
+ if (raw.version === "v1" || raw.version === "v2")
247
+ pluginOptions.version = raw.version;
248
+ else
249
+ recordConfigWarning('version must be "v1" or "v2"; using default v1');
250
+ }
220
251
  if ("max_raw_memories_for_consolidation" in opts)
221
- pluginOptions.max_raw_memories_for_consolidation = clampInt("max_raw_memories_for_consolidation", opts.max_raw_memories_for_consolidation, 1, 4096, 256);
252
+ pluginOptions.max_raw_memories_for_consolidation = testing
253
+ ? finiteNumber("max_raw_memories_for_consolidation", opts.max_raw_memories_for_consolidation, 256)
254
+ : clampInt("max_raw_memories_for_consolidation", opts.max_raw_memories_for_consolidation, 1, 4096, 256);
222
255
  if ("max_unused_days" in opts)
223
- pluginOptions.max_unused_days = clampInt("max_unused_days", opts.max_unused_days, 0, 365, 30);
256
+ pluginOptions.max_unused_days = testing
257
+ ? finiteNumber("max_unused_days", opts.max_unused_days, 30)
258
+ : clampInt("max_unused_days", opts.max_unused_days, 0, 365, 30);
224
259
  if ("max_rollout_age_days" in opts)
225
- pluginOptions.max_rollout_age_days = clampInt("max_rollout_age_days", opts.max_rollout_age_days, 0, 90, 10);
260
+ pluginOptions.max_rollout_age_days = testing
261
+ ? finiteNumber("max_rollout_age_days", opts.max_rollout_age_days, 10)
262
+ : clampInt("max_rollout_age_days", opts.max_rollout_age_days, 0, 90, 10);
226
263
  if ("max_rollouts_per_startup" in opts)
227
- pluginOptions.max_rollouts_per_startup = clampInt("max_rollouts_per_startup", opts.max_rollouts_per_startup, 1, 128, 2);
264
+ pluginOptions.max_rollouts_per_startup = testing
265
+ ? finiteNumber("max_rollouts_per_startup", opts.max_rollouts_per_startup, 2)
266
+ : clampInt("max_rollouts_per_startup", opts.max_rollouts_per_startup, 1, 128, 2);
228
267
  if ("min_rollout_idle_hours" in opts)
229
- pluginOptions.min_rollout_idle_hours = clampInt("min_rollout_idle_hours", opts.min_rollout_idle_hours, 1, 48, 6);
268
+ pluginOptions.min_rollout_idle_hours = testing
269
+ ? finiteNumber("min_rollout_idle_hours", opts.min_rollout_idle_hours, 6)
270
+ : clampInt("min_rollout_idle_hours", opts.min_rollout_idle_hours, 1, 48, 6);
230
271
  if ("home" in raw) {
231
272
  if (typeof raw.home !== "string") {
232
273
  recordConfigWarning("home must be a string; using the OpenCode data dir");
@@ -311,7 +352,7 @@ export function applyPluginOptions(opts) {
311
352
  recordConfigWarning("claude_import must be an object like { enabled, claude_home, projects }; ignored");
312
353
  }
313
354
  }
314
- if (memoryDbPath() !== previousDb)
355
+ if (dataRoot() !== previousDb)
315
356
  closeDb();
316
357
  }
317
358
  /**
@@ -410,7 +451,7 @@ export function injectAgentDefinitions(config) {
410
451
  // belt-and-suspenders (path is home/env-dependent; out-ranks `"*": deny`).
411
452
  const memorize = defs["memorize"];
412
453
  if (memorize?.permission && !("external_directory" in memorize.permission)) {
413
- memorize.permission["external_directory"] = { [path.join(memoryRoot(), "*")]: "allow" };
454
+ memorize.permission["external_directory"] = Object.fromEntries(writeMemoryVersions().map((version) => [path.join(memoryRoot(version), "*"), "allow"]));
414
455
  }
415
456
  config.agent ??= {};
416
457
  for (const [name, def] of Object.entries(defs)) {
@@ -452,8 +493,10 @@ function buildHooks() {
452
493
  return;
453
494
  if (isTitleGenerationPrompt(output.system))
454
495
  return;
455
- ensureMemoryLayout();
456
- const memoryPrompt = buildMemorySystemPrompt(pluginOptions.dedicated_tools);
496
+ const memoryPrompt = withSessionMemoryVersion(input.sessionID, () => {
497
+ ensureMemoryLayout();
498
+ return buildMemorySystemPrompt(pluginOptions.dedicated_tools);
499
+ });
457
500
  if (memoryPrompt) {
458
501
  output.system.push(memoryPrompt);
459
502
  }
@@ -483,7 +526,7 @@ function buildHooks() {
483
526
  // records them; the other becomes a no-op.
484
527
  const fresh = takeNewCitations(`${input.sessionID}:${input.partID}`, ids);
485
528
  if (fresh.length > 0)
486
- getStore().recordUsage(fresh);
529
+ withSessionMemoryVersion(input.sessionID, () => getStore().recordUsage(fresh));
487
530
  }
488
531
  catch (e) {
489
532
  console.error("[opencode-codex-memory] citation recording failed:", e);
@@ -532,6 +575,7 @@ function buildHooks() {
532
575
  const sid = input?.sessionID;
533
576
  if (!sid || isMemorySubSession(sid))
534
577
  return;
578
+ sessionMemoryVersion(sid);
535
579
  if (!markTurnSeen(sid))
536
580
  return;
537
581
  try {
@@ -597,7 +641,7 @@ function buildHooks() {
597
641
  const fresh = takeNewCitations(`${part.sessionID ?? ""}:${part.id ?? ""}`, ids);
598
642
  if (fresh.length > 0) {
599
643
  try {
600
- getStore().recordUsage(fresh);
644
+ withSessionMemoryVersion(part.sessionID, () => getStore().recordUsage(fresh));
601
645
  }
602
646
  catch (e) {
603
647
  console.error("[opencode-codex-memory] recordUsage failed:", e);
@@ -692,47 +736,8 @@ function buildHooks() {
692
736
  return { ...base, tool };
693
737
  }
694
738
  async function triggerPhase1(currentSessionId) {
695
- if (phase1InFlight || !pluginOptions.generate_memories || isPluginShuttingDown())
696
- return;
697
- phase1InFlight = true;
698
- try {
699
- await runPhase1(getStore(), {
700
- maxAgeDays: pluginOptions.max_rollout_age_days,
701
- minIdleHours: pluginOptions.min_rollout_idle_hours,
702
- maxClaimed: pluginOptions.max_rollouts_per_startup,
703
- maxUnusedDays: pluginOptions.max_unused_days,
704
- excludeSession: currentSessionId,
705
- extractModel: pluginOptions.extract_model,
706
- });
707
- }
708
- catch (err) {
709
- console.error("[opencode-codex-memory] phase1 error:", err);
710
- recordDiagnostic("error", "phase1", err instanceof Error ? err.message : String(err));
711
- }
712
- finally {
713
- phase1InFlight = false;
714
- }
715
- trackBackgroundTask(triggerPhase2());
739
+ await runMemoryPipeline(currentSessionId);
716
740
  }
717
741
  async function triggerPhase2() {
718
- if (isPluginShuttingDown())
719
- return;
720
- try {
721
- // runPhase2 has its own in-flight guard
722
- const result = await runPhase2(getStore(), {
723
- maxRaw: pluginOptions.max_raw_memories_for_consolidation,
724
- maxUnusedDays: pluginOptions.max_unused_days,
725
- extensionRetentionDays: 7,
726
- consolidationModel: pluginOptions.consolidation_model,
727
- codexInterop: pluginOptions.codex_interop,
728
- claudeImport: pluginOptions.claude_import,
729
- });
730
- if (result.status !== "already_running" && result.status !== "skipped_cooldown" && result.status !== "skipped_running") {
731
- recordDiagnostic(result.status === "succeeded" || result.status === "no_workspace_changes" ? "info" : "warn", "phase2", result.status);
732
- }
733
- }
734
- catch (err) {
735
- console.error("[opencode-codex-memory] phase2 error:", err);
736
- recordDiagnostic("error", "phase2", err instanceof Error ? err.message : String(err));
737
- }
742
+ await runMemoryConsolidation();
738
743
  }