opencode-codex-memory 0.7.7 → 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 (57) 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/host-client.d.ts +5 -0
  9. package/dist/src/index.d.ts +12 -4
  10. package/dist/src/index.js +39 -61
  11. package/dist/src/lifecycle.js +14 -9
  12. package/dist/src/llm.d.ts +3 -2
  13. package/dist/src/llm.js +47 -11
  14. package/dist/src/memory-version.d.ts +5 -0
  15. package/dist/src/memory-version.js +16 -0
  16. package/dist/src/migration.d.ts +24 -0
  17. package/dist/src/migration.js +37 -0
  18. package/dist/src/options.d.ts +4 -0
  19. package/dist/src/options.js +2 -0
  20. package/dist/src/paths.d.ts +9 -3
  21. package/dist/src/paths.js +22 -8
  22. package/dist/src/phase1.js +16 -2
  23. package/dist/src/phase2.js +15 -9
  24. package/dist/src/pipeline.d.ts +3 -0
  25. package/dist/src/pipeline.js +74 -0
  26. package/dist/src/ratelimit.js +5 -4
  27. package/dist/src/rollout-input.d.ts +3 -2
  28. package/dist/src/rollout-input.js +26 -17
  29. package/dist/src/session-version.d.ts +9 -0
  30. package/dist/src/session-version.js +27 -0
  31. package/dist/src/source.js +21 -6
  32. package/dist/src/store.d.ts +10 -1
  33. package/dist/src/store.js +76 -24
  34. package/dist/src/templates/consolidation_v2.md +54 -0
  35. package/dist/src/templates/read_path_v2.md +58 -0
  36. package/dist/src/templates/stage_one_input_v2.md +21 -0
  37. package/dist/src/templates/stage_one_system_v2.md +53 -0
  38. package/dist/src/token.d.ts +2 -0
  39. package/dist/src/token.js +16 -0
  40. package/dist/src/v2/agents.d.ts +4 -2
  41. package/dist/src/v2/agents.js +15 -7
  42. package/dist/src/v2/citation-overlay.d.ts +1 -1
  43. package/dist/src/v2/citation-overlay.js +27 -4
  44. package/dist/src/v2/plugin.js +24 -72
  45. package/dist/src/v2/shim.js +5 -1
  46. package/dist/src/v2/status-rpc.d.ts +70 -1
  47. package/dist/src/v2/status-rpc.js +41 -2
  48. package/dist/src/v2/status.d.ts +1 -1
  49. package/dist/src/v2/status.js +28 -6
  50. package/dist/src/v2/tui.js +57 -2
  51. package/dist/src/workspace.d.ts +8 -6
  52. package/dist/src/workspace.js +31 -11
  53. package/dist/tools/control.d.ts +6 -2
  54. package/dist/tools/control.js +196 -164
  55. package/dist/tools/memory.js +11 -1
  56. package/opencode.json +2 -2
  57. 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.7"]
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.7" }],
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.7", { "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.7", { "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.7", "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.7",
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.7", { "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.7",
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
  }
@@ -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",
@@ -198,7 +206,7 @@ function finiteNumber(key, value, fallback) {
198
206
  export function applyPluginOptions(opts) {
199
207
  // Fresh pass per apply so memory_inspect never shows warnings for keys the
200
208
  // caller has since fixed. server() clears too, for boots without options.
201
- const previousDb = memoryDbPath();
209
+ const previousDb = dataRoot();
202
210
  clearConfigWarnings();
203
211
  resetPluginOptions();
204
212
  const raw = opts;
@@ -210,7 +218,7 @@ export function applyPluginOptions(opts) {
210
218
  recordConfigWarning(`unknown/unsupported option '${key}' ignored`);
211
219
  }
212
220
  }
213
- 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"]) {
214
222
  if (!(key in raw))
215
223
  continue;
216
224
  if (typeof raw[key] === "boolean")
@@ -234,6 +242,12 @@ export function applyPluginOptions(opts) {
234
242
  recordConfigWarning(`${key} must be a string; using the opencode model default`);
235
243
  }
236
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
+ }
237
251
  if ("max_raw_memories_for_consolidation" in opts)
238
252
  pluginOptions.max_raw_memories_for_consolidation = testing
239
253
  ? finiteNumber("max_raw_memories_for_consolidation", opts.max_raw_memories_for_consolidation, 256)
@@ -338,7 +352,7 @@ export function applyPluginOptions(opts) {
338
352
  recordConfigWarning("claude_import must be an object like { enabled, claude_home, projects }; ignored");
339
353
  }
340
354
  }
341
- if (memoryDbPath() !== previousDb)
355
+ if (dataRoot() !== previousDb)
342
356
  closeDb();
343
357
  }
344
358
  /**
@@ -437,7 +451,7 @@ export function injectAgentDefinitions(config) {
437
451
  // belt-and-suspenders (path is home/env-dependent; out-ranks `"*": deny`).
438
452
  const memorize = defs["memorize"];
439
453
  if (memorize?.permission && !("external_directory" in memorize.permission)) {
440
- memorize.permission["external_directory"] = { [path.join(memoryRoot(), "*")]: "allow" };
454
+ memorize.permission["external_directory"] = Object.fromEntries(writeMemoryVersions().map((version) => [path.join(memoryRoot(version), "*"), "allow"]));
441
455
  }
442
456
  config.agent ??= {};
443
457
  for (const [name, def] of Object.entries(defs)) {
@@ -479,8 +493,10 @@ function buildHooks() {
479
493
  return;
480
494
  if (isTitleGenerationPrompt(output.system))
481
495
  return;
482
- ensureMemoryLayout();
483
- const memoryPrompt = buildMemorySystemPrompt(pluginOptions.dedicated_tools);
496
+ const memoryPrompt = withSessionMemoryVersion(input.sessionID, () => {
497
+ ensureMemoryLayout();
498
+ return buildMemorySystemPrompt(pluginOptions.dedicated_tools);
499
+ });
484
500
  if (memoryPrompt) {
485
501
  output.system.push(memoryPrompt);
486
502
  }
@@ -510,7 +526,7 @@ function buildHooks() {
510
526
  // records them; the other becomes a no-op.
511
527
  const fresh = takeNewCitations(`${input.sessionID}:${input.partID}`, ids);
512
528
  if (fresh.length > 0)
513
- getStore().recordUsage(fresh);
529
+ withSessionMemoryVersion(input.sessionID, () => getStore().recordUsage(fresh));
514
530
  }
515
531
  catch (e) {
516
532
  console.error("[opencode-codex-memory] citation recording failed:", e);
@@ -559,6 +575,7 @@ function buildHooks() {
559
575
  const sid = input?.sessionID;
560
576
  if (!sid || isMemorySubSession(sid))
561
577
  return;
578
+ sessionMemoryVersion(sid);
562
579
  if (!markTurnSeen(sid))
563
580
  return;
564
581
  try {
@@ -624,7 +641,7 @@ function buildHooks() {
624
641
  const fresh = takeNewCitations(`${part.sessionID ?? ""}:${part.id ?? ""}`, ids);
625
642
  if (fresh.length > 0) {
626
643
  try {
627
- getStore().recordUsage(fresh);
644
+ withSessionMemoryVersion(part.sessionID, () => getStore().recordUsage(fresh));
628
645
  }
629
646
  catch (e) {
630
647
  console.error("[opencode-codex-memory] recordUsage failed:", e);
@@ -719,47 +736,8 @@ function buildHooks() {
719
736
  return { ...base, tool };
720
737
  }
721
738
  async function triggerPhase1(currentSessionId) {
722
- if (phase1InFlight || !pluginOptions.generate_memories || isPluginShuttingDown())
723
- return;
724
- phase1InFlight = true;
725
- try {
726
- await runPhase1(getStore(), {
727
- maxAgeDays: pluginOptions.max_rollout_age_days,
728
- minIdleHours: pluginOptions.min_rollout_idle_hours,
729
- maxClaimed: pluginOptions.max_rollouts_per_startup,
730
- maxUnusedDays: pluginOptions.max_unused_days,
731
- excludeSession: currentSessionId,
732
- extractModel: pluginOptions.extract_model,
733
- });
734
- }
735
- catch (err) {
736
- console.error("[opencode-codex-memory] phase1 error:", err);
737
- recordDiagnostic("error", "phase1", err instanceof Error ? err.message : String(err));
738
- }
739
- finally {
740
- phase1InFlight = false;
741
- }
742
- trackBackgroundTask(triggerPhase2());
739
+ await runMemoryPipeline(currentSessionId);
743
740
  }
744
741
  async function triggerPhase2() {
745
- if (isPluginShuttingDown())
746
- return;
747
- try {
748
- // runPhase2 has its own in-flight guard
749
- const result = await runPhase2(getStore(), {
750
- maxRaw: pluginOptions.max_raw_memories_for_consolidation,
751
- maxUnusedDays: pluginOptions.max_unused_days,
752
- extensionRetentionDays: 7,
753
- consolidationModel: pluginOptions.consolidation_model,
754
- codexInterop: pluginOptions.codex_interop,
755
- claudeImport: pluginOptions.claude_import,
756
- });
757
- if (result.status !== "already_running" && result.status !== "skipped_cooldown" && result.status !== "skipped_running") {
758
- recordDiagnostic(result.status === "succeeded" || result.status === "no_workspace_changes" ? "info" : "warn", "phase2", result.status);
759
- }
760
- }
761
- catch (err) {
762
- console.error("[opencode-codex-memory] phase2 error:", err);
763
- recordDiagnostic("error", "phase2", err instanceof Error ? err.message : String(err));
764
- }
742
+ await runMemoryConsolidation();
765
743
  }
@@ -11,8 +11,9 @@
11
11
  * Phase-2 keeps its own scope so heartbeat loss can cancel the consolidator
12
12
  * without marking the whole plugin as shutting down.
13
13
  */
14
+ import { memoryRoot } from "./paths.js";
14
15
  let shuttingDown = false;
15
- let phase2Abort = null;
16
+ const phase2Aborts = new Map();
16
17
  /** Fresh each boot; aborted on dispose. Extract (and others) subscribe here. */
17
18
  let shutdownAbort = new AbortController();
18
19
  export function isPluginShuttingDown() {
@@ -27,7 +28,8 @@ export function beginPluginShutdown() {
27
28
  shuttingDown = true;
28
29
  if (!shutdownAbort.signal.aborted)
29
30
  shutdownAbort.abort();
30
- phase2Abort?.abort();
31
+ for (const controller of phase2Aborts.values())
32
+ controller.abort();
31
33
  }
32
34
  /**
33
35
  * Test / re-boot seam: a fresh server() call clears the previous dispose.
@@ -35,8 +37,9 @@ export function beginPluginShutdown() {
35
37
  * glitched boot order cannot orphan a still-running phase-2 prompt.
36
38
  */
37
39
  export function resetPluginLifecycle() {
38
- phase2Abort?.abort();
39
- phase2Abort = null;
40
+ for (const controller of phase2Aborts.values())
41
+ controller.abort();
42
+ phase2Aborts.clear();
40
43
  shutdownAbort = new AbortController();
41
44
  shuttingDown = false;
42
45
  }
@@ -45,14 +48,16 @@ export function resetPluginLifecycle() {
45
48
  * is claimed; aborted on heartbeat loss, dispose, or run end.
46
49
  */
47
50
  export function beginPhase2AbortScope() {
48
- phase2Abort?.abort();
49
- phase2Abort = new AbortController();
50
- return phase2Abort.signal;
51
+ const root = memoryRoot();
52
+ phase2Aborts.get(root)?.abort();
53
+ const controller = new AbortController();
54
+ phase2Aborts.set(root, controller);
55
+ return controller.signal;
51
56
  }
52
57
  export function endPhase2AbortScope() {
53
- phase2Abort = null;
58
+ phase2Aborts.delete(memoryRoot());
54
59
  }
55
60
  /** Abort the current consolidator from outside phase2 (dispose). */
56
61
  export function abortPhase2Consolidation() {
57
- phase2Abort?.abort();
62
+ phase2Aborts.get(memoryRoot())?.abort();
58
63
  }
package/dist/src/llm.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { PluginInput } from "@opencode-ai/plugin";
2
+ import type { MemoryVersion } from "./options.js";
2
3
  export interface ExtractionResult {
3
4
  raw_memory: string;
4
5
  rollout_summary: string;
@@ -74,9 +75,9 @@ export declare function buildConsolidationPrompt(memoryRoot: string, diffFileNam
74
75
  * all-empty no-op. Shared by the structured-output path (AssistantMessage.
75
76
  * structured) and the text parser below.
76
77
  */
77
- export declare function validateExtraction(obj: Partial<ExtractionResult>): ExtractionResult | null;
78
+ export declare function validateExtraction(obj: Partial<ExtractionResult>, version?: MemoryVersion): ExtractionResult | null;
78
79
  /**
79
80
  * Parses stage-1 JSON from assistant text. Fallback for when structured output
80
81
  * is unavailable; the primary path reads AssistantMessage.structured directly.
81
82
  */
82
- export declare function parseExtraction(raw: string): ExtractionResult | null;
83
+ export declare function parseExtraction(raw: string, version?: MemoryVersion): ExtractionResult | null;