opencode-codex-memory 0.7.7 → 0.8.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.
Files changed (63) hide show
  1. package/README.md +64 -482
  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/claude-import.js +25 -27
  6. package/dist/src/codex-interop.js +5 -0
  7. package/dist/src/db.d.ts +7 -1
  8. package/dist/src/db.js +38 -11
  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 +39 -61
  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/memory-version.d.ts +5 -0
  16. package/dist/src/memory-version.js +16 -0
  17. package/dist/src/migration.d.ts +24 -0
  18. package/dist/src/migration.js +37 -0
  19. package/dist/src/options.d.ts +4 -0
  20. package/dist/src/options.js +2 -0
  21. package/dist/src/paths.d.ts +9 -3
  22. package/dist/src/paths.js +22 -8
  23. package/dist/src/phase1.js +16 -2
  24. package/dist/src/phase2.js +15 -9
  25. package/dist/src/pipeline.d.ts +3 -0
  26. package/dist/src/pipeline.js +74 -0
  27. package/dist/src/ratelimit.js +5 -4
  28. package/dist/src/rollout-input.d.ts +3 -2
  29. package/dist/src/rollout-input.js +26 -17
  30. package/dist/src/session-version.d.ts +9 -0
  31. package/dist/src/session-version.js +27 -0
  32. package/dist/src/source.js +21 -6
  33. package/dist/src/store.d.ts +10 -1
  34. package/dist/src/store.js +76 -24
  35. package/dist/src/templates/consolidation_v2.md +54 -0
  36. package/dist/src/templates/read_path_v2.md +58 -0
  37. package/dist/src/templates/stage_one_input_v2.md +21 -0
  38. package/dist/src/templates/stage_one_system_v2.md +53 -0
  39. package/dist/src/token.d.ts +2 -0
  40. package/dist/src/token.js +16 -0
  41. package/dist/src/v2/agents.d.ts +4 -2
  42. package/dist/src/v2/agents.js +28 -9
  43. package/dist/src/v2/citation-overlay.d.ts +1 -1
  44. package/dist/src/v2/citation-overlay.js +27 -4
  45. package/dist/src/v2/plugin.js +47 -76
  46. package/dist/src/v2/search-sandbox.d.ts +4 -0
  47. package/dist/src/v2/search-sandbox.js +33 -0
  48. package/dist/src/v2/service.d.ts +2 -0
  49. package/dist/src/v2/service.js +43 -4
  50. package/dist/src/v2/shim.d.ts +2 -2
  51. package/dist/src/v2/shim.js +82 -39
  52. package/dist/src/v2/status-rpc.d.ts +70 -1
  53. package/dist/src/v2/status-rpc.js +41 -2
  54. package/dist/src/v2/status.d.ts +1 -1
  55. package/dist/src/v2/status.js +28 -6
  56. package/dist/src/v2/tui.js +57 -2
  57. package/dist/src/workspace.d.ts +8 -6
  58. package/dist/src/workspace.js +31 -11
  59. package/dist/tools/control.d.ts +6 -2
  60. package/dist/tools/control.js +196 -164
  61. package/dist/tools/memory.js +11 -1
  62. package/opencode.json +2 -2
  63. package/package.json +2 -2
@@ -73,8 +73,10 @@ function lstatKind(p) {
73
73
  return "dir";
74
74
  return "other";
75
75
  }
76
- catch {
77
- return "missing";
76
+ catch (err) {
77
+ if (err.code === "ENOENT")
78
+ return "missing";
79
+ throw err;
78
80
  }
79
81
  }
80
82
  /**
@@ -83,13 +85,7 @@ function lstatKind(p) {
83
85
  * cwd that canonicalizes to an existing directory wins.
84
86
  */
85
87
  export function projectCwdFromSessions(projectRoot) {
86
- let entries;
87
- try {
88
- entries = fs.readdirSync(projectRoot, { withFileTypes: true });
89
- }
90
- catch {
91
- return null;
92
- }
88
+ const entries = fs.readdirSync(projectRoot, { withFileTypes: true });
93
89
  const sessions = entries
94
90
  .filter((e) => e.isFile() && e.name.endsWith(".jsonl"))
95
91
  .map((e) => {
@@ -139,13 +135,9 @@ export function projectCwdFromSessions(projectRoot) {
139
135
  return null;
140
136
  }
141
137
  function collectMarkdownFiles(sourceRoot, currentDir, projectKey, projectCwd, out) {
142
- let entries;
143
- try {
144
- entries = fs.readdirSync(currentDir, { withFileTypes: true });
145
- }
146
- catch {
147
- return;
148
- }
138
+ // A partial scan is not a deletion signal. Codex propagates discovery errors
139
+ // before replacing/pruning any imported project.
140
+ const entries = fs.readdirSync(currentDir, { withFileTypes: true });
149
141
  entries.sort((a, b) => a.name.localeCompare(b.name));
150
142
  for (const entry of entries) {
151
143
  const full = path.join(currentDir, entry.name);
@@ -179,13 +171,7 @@ export function discoverExternalMemoryFiles(claudeHome) {
179
171
  if (lstatKind(projectsRoot) !== "dir")
180
172
  return [];
181
173
  const files = [];
182
- let projectEntries;
183
- try {
184
- projectEntries = fs.readdirSync(projectsRoot, { withFileTypes: true });
185
- }
186
- catch {
187
- return [];
188
- }
174
+ const projectEntries = fs.readdirSync(projectsRoot, { withFileTypes: true });
189
175
  projectEntries.sort((a, b) => a.name.localeCompare(b.name));
190
176
  for (const entry of projectEntries) {
191
177
  if (!entry.isDirectory() || entry.isSymbolicLink())
@@ -317,6 +303,14 @@ function removeProjectResources(projectKey) {
317
303
  fs.rmSync(targetRoot, { recursive: true, force: true });
318
304
  return true;
319
305
  }
306
+ /** Codex project_has_unscoped_target: keep valid scoped imports when cwd is unavailable. */
307
+ function projectHasUnscopedTarget(projectKey) {
308
+ const target = path.join(memoryRoot(), "extensions", EXTENSION_NAME, "resources", projectKey);
309
+ const kind = lstatKind(target);
310
+ if (kind === "missing")
311
+ return false;
312
+ return kind !== "dir" || lstatKind(path.join(target, PROJECT_SCOPE_FILE)) !== "file";
313
+ }
320
314
  function replaceProjectResources(projectKey, projectCwd, projectFiles) {
321
315
  // Read all sources first so a mid-copy failure never leaves a half-empty dir
322
316
  // after we deleted the previous resources (codex replace_project_resources).
@@ -372,8 +366,13 @@ export function syncClaudeImport(opts) {
372
366
  if (!opts.enabled)
373
367
  return empty;
374
368
  const claudeHome = resolveClaudeHome(opts);
375
- if (lstatKind(claudeHome) !== "dir")
376
- return empty;
369
+ try {
370
+ if (lstatKind(claudeHome) !== "dir")
371
+ return empty;
372
+ }
373
+ catch {
374
+ return empty; // Unreachable home is the documented quiet no-op.
375
+ }
377
376
  const allFiles = discoverExternalMemoryFiles(claudeHome);
378
377
  const byProject = groupByProject(allFiles);
379
378
  const sourceKeys = new Set(byProject.keys());
@@ -417,8 +416,7 @@ export function syncClaudeImport(opts) {
417
416
  skippedNoCwd.push(projectKey);
418
417
  // Unscoped leftovers under this key → remove (codex project_has_unscoped_target).
419
418
  try {
420
- const target = path.join(memoryRoot(), "extensions", EXTENSION_NAME, "resources", projectKey);
421
- if (lstatKind(target) !== "missing") {
419
+ if (projectHasUnscopedTarget(projectKey)) {
422
420
  if (removeProjectResources(projectKey)) {
423
421
  changed = true;
424
422
  synchronizedProjects.push(projectKey);
@@ -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;