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
@@ -1,7 +1,7 @@
1
1
  export declare const MEMORIZE_AGENT_ID = "memorize";
2
2
  export declare const MEMORIZE_EXTRACT_AGENT_ID = "memorize-extract";
3
- export declare const MEMORIZE_SYSTEM = "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.";
4
- export declare const MEMORIZE_EXTRACT_SYSTEM = "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.";
3
+ export declare const MEMORIZE_SYSTEM = "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.";
4
+ export declare const MEMORIZE_EXTRACT_SYSTEM = "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.";
5
5
  export declare const MEMORIZE_DESCRIPTION = "Memory consolidation agent (opencode-codex-memory)";
6
6
  export declare const MEMORIZE_EXTRACT_DESCRIPTION = "Memory extraction agent (opencode-codex-memory)";
7
7
  export interface V2AgentDefinition {
@@ -17,6 +17,8 @@ export interface V2AgentDefinition {
17
17
  }
18
18
  /** V2-native memorize definition (V2 action names: edit covers write/patch). */
19
19
  export declare function buildMemorizeAgent(): V2AgentDefinition;
20
+ /** Session rules run after agent rules: a concurrent helper gets one root only. */
21
+ export declare function consolidationPermissions(root: string): V2AgentDefinition["permissions"];
20
22
  /**
21
23
  * Hidden extraction definition. Unused at runtime (extraction goes through
22
24
  * generate.text), kept for parity with the V1 bundle and the health
@@ -14,13 +14,14 @@
14
14
  * hidden definition preserves the health snapshot both agents report into.
15
15
  */
16
16
  import path from "path";
17
- import { memoryRoot } from "../paths.js";
17
+ import { allMemoryRoots, memoryRoot } from "../paths.js";
18
18
  import { pluginOptions } from "../options.js";
19
+ import { writeMemoryVersions } from "../memory-version.js";
19
20
  import { recordAgentConfig } from "../agent-health.js";
20
21
  export const MEMORIZE_AGENT_ID = "memorize";
21
22
  export const MEMORIZE_EXTRACT_AGENT_ID = "memorize-extract";
22
- export const MEMORIZE_SYSTEM = "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.";
23
- export const MEMORIZE_EXTRACT_SYSTEM = "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
+ export const MEMORIZE_SYSTEM = "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.";
24
+ export const MEMORIZE_EXTRACT_SYSTEM = "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
25
  export const MEMORIZE_DESCRIPTION = "Memory consolidation agent (opencode-codex-memory)";
25
26
  export const MEMORIZE_EXTRACT_DESCRIPTION = "Memory extraction agent (opencode-codex-memory)";
26
27
  /** V2-native memorize definition (V2 action names: edit covers write/patch). */
@@ -31,17 +32,30 @@ export function buildMemorizeAgent() {
31
32
  system: MEMORIZE_SYSTEM,
32
33
  permissions: [
33
34
  { action: "*", resource: "*", effect: "deny" },
34
- { action: "read", resource: path.join(memoryRoot(), "*"), effect: "allow" },
35
- { action: "edit", resource: path.join(memoryRoot(), "*"), effect: "allow" },
36
- { action: "glob", resource: path.join(memoryRoot(), "*"), effect: "allow" },
37
- { action: "grep", resource: path.join(memoryRoot(), "*"), effect: "allow" },
38
35
  // Memories live outside every project: without this grant the wildcard
39
36
  // deny blocks consolidation from touching the memory workspace (same
40
37
  // role as external_directory in the V1 definition).
41
- { action: "external_directory", resource: path.join(memoryRoot(), "*"), effect: "allow" },
38
+ ...writeMemoryVersions().flatMap((version) => workspacePermissions(memoryRoot(version))),
42
39
  ],
43
40
  };
44
41
  }
42
+ /** Session rules run after agent rules: a concurrent helper gets one root only. */
43
+ export function consolidationPermissions(root) {
44
+ return [
45
+ { action: "*", resource: "*", effect: "deny" },
46
+ ...workspacePermissions(root),
47
+ ];
48
+ }
49
+ function workspacePermissions(root) {
50
+ return [
51
+ ...["read", "edit", "external_directory"].flatMap((action) => [root, path.join(root, "*")].map((resource) => ({
52
+ action, resource, effect: "allow",
53
+ }))),
54
+ // These actions check the search pattern, not a path. search-sandbox.ts
55
+ // wraps the built-in executors to enforce this helper's single root.
56
+ ...["glob", "grep"].map((action) => ({ action, resource: "*", effect: "allow" })),
57
+ ];
58
+ }
45
59
  /**
46
60
  * Hidden extraction definition. Unused at runtime (extraction goes through
47
61
  * generate.text), kept for parity with the V1 bundle and the health
@@ -69,6 +83,9 @@ export function toV1AgentDefinition(def, agentId) {
69
83
  continue;
70
84
  }
71
85
  if (rule.action === "external_directory") {
86
+ // V1 health expects only root/*; its V1 sandbox already includes root.
87
+ if (allMemoryRoots().includes(rule.resource))
88
+ continue;
72
89
  const cur = (permission.external_directory ?? {});
73
90
  cur[rule.resource] = rule.effect;
74
91
  permission.external_directory = cur;
@@ -173,7 +190,7 @@ function isShippedIncomplete(id, existing, shipped) {
173
190
  const perms = existing.permissions;
174
191
  if (!Array.isArray(perms))
175
192
  return true;
176
- return !perms.some((rule) => rule && typeof rule === "object" && rule.action === "external_directory");
193
+ return shipped.permissions.some((expected) => !perms.some((rule) => rule?.action === expected.action && rule?.resource === expected.resource && rule?.effect === expected.effect));
177
194
  }
178
195
  function v2PermissionsToV1Map(permissions) {
179
196
  const out = {};
@@ -187,6 +204,8 @@ function v2PermissionsToV1Map(permissions) {
187
204
  continue;
188
205
  }
189
206
  if (rule.action === "external_directory" && typeof rule.resource === "string") {
207
+ if (allMemoryRoots().includes(rule.resource))
208
+ continue;
190
209
  const cur = (out.external_directory ?? {});
191
210
  cur[rule.resource] = rule.effect;
192
211
  out.external_directory = cur;
@@ -4,4 +4,4 @@
4
4
  * overlays this section onto the shared inject prompt.
5
5
  */
6
6
  export declare const V2_CITATION_INSTRUCTIONS = "Memory citation requirements:\n\n- If ANY relevant memory files were used: append exactly one fenced code\n block with the language tag `memory-citation` as the VERY LAST content of\n the final reply. Answer first, then a blank line, then the block. The\n opening fence must be on its own line at column 0 \u2014 never glue it to the\n last sentence, or markdown clients treat the block as paragraph text and\n collapse its newlines. The host renders this block natively.\n- Use this exact structure for programmatic parsing (blank line before the\n fence is required):\n````\nanswer text ends here.\n\n```memory-citation\nMEMORY.md:234-236|note=build command for the api service\nrollout_summaries/2026-02-17T21-23-02-ln3m-example.md:10-12|note=weekly report format\nsessions: ses_abc123 ses_def456\n```\n````\n- Do not wrap it in `<memory-citation>` XML tags; the fenced form replaces\n that older format.\n- Citation entry lines are for rendering:\n - one citation entry per line\n - format: `<file>:<line_start>-<line_end>|note=<how memory was used>`\n - use file paths relative to the memory base path (for example, `MEMORY.md`,\n `rollout_summaries/...`, `skills/...`)\n - only cite files actually used under the memory base path (do not cite\n workspace files as memory citations)\n - if you used `MEMORY.md` and then a rollout summary/skill file, cite both\n - list entries in order of importance (most important first)\n - `note` should be short, single-line, and use simple characters only (avoid\n unusual symbols, no newlines)\n- The final `sessions:` line is for us to track which past sessions you find\n useful:\n - one line, space-separated session ids after `sessions:`\n - session ids look like `ses_...` and appear in rollout summary files and\n MEMORY.md as `session_id:`\n - include unique ids only; do not repeat ids\n - omit the `sessions:` line if no session ids are available\n - do not include file paths or notes on this line\n - for every citation entry, try to find and cite the corresponding session id\n- Never include memory citations inside pull-request messages.\n- Never cite blank lines; double-check ranges.\n\n";
7
- export declare function overlayV2CitationInstructions(prompt: string): string;
7
+ export declare function overlayV2CitationInstructions(prompt: string, version?: "v1" | "v2"): string;
@@ -48,10 +48,33 @@ sessions: ses_abc123 ses_def456
48
48
  - Never cite blank lines; double-check ranges.
49
49
 
50
50
  `;
51
- export function overlayV2CitationInstructions(prompt) {
52
- const start = prompt.indexOf("Memory citation requirements:");
51
+ const SUMMARY_ONLY_CITATIONS = `Memory citation requirements:
52
+
53
+ - When a read rollout summary informs the answer, append exactly one fenced
54
+ \`memory-citation\` block as the VERY LAST content of the final reply.
55
+ Answer first, then a blank line, then the opening fence at column 0.
56
+ - Cite only memory files actually read and used. Do not cite memory_summary.md.
57
+ Do not reread files solely to construct citations. Never cite in pull requests.
58
+ - Use relative paths and nonblank line ranges. Notes must be short and single-line.
59
+ - Include unique session ids already available; omit the sessions line if none.
60
+ - Use this exact structure (never XML tags):
61
+ \`\`\`\`
62
+ answer text ends here.
63
+
64
+ \`\`\`memory-citation
65
+ rollout_summaries/2026-02-17T21-23-02-ln3m-example.md:10-12|note=weekly report format
66
+ sessions: ses_abc123 ses_def456
67
+ \`\`\`
68
+ \`\`\`\`
69
+
70
+ `;
71
+ export function overlayV2CitationInstructions(prompt, version = "v1") {
72
+ let start = prompt.indexOf("Memory citation requirements:");
73
+ if (start === -1)
74
+ start = prompt.indexOf("Memory citations:");
53
75
  const end = prompt.indexOf("Updating memories:");
76
+ const instructions = version === "v2" ? SUMMARY_ONLY_CITATIONS : V2_CITATION_INSTRUCTIONS;
54
77
  if (start === -1 || end === -1 || end <= start)
55
- return `${prompt.trimEnd()}\n\n${V2_CITATION_INSTRUCTIONS}`;
56
- return prompt.slice(0, start) + V2_CITATION_INSTRUCTIONS + prompt.slice(end);
78
+ return `${prompt.trimEnd()}\n\n${instructions}`;
79
+ return prompt.slice(0, start) + instructions + prompt.slice(end);
57
80
  }
@@ -13,34 +13,33 @@
13
13
  * - agent.transform → memorize sub-agent provisioning (was config hook)
14
14
  * - tool.transform → memory tool registration (was returned tool map)
15
15
  *
16
- * Known V2 adaptations (see docs/opencode2.md): global session reads use the
16
+ * Known V2 adaptations (see ARCHITECTURE.md): global session reads use the
17
17
  * registered public service; finalized citations are accounted from durable
18
18
  * text events and stripped from model-bound context; config documents are
19
19
  * adapted for the shared model resolver.
20
20
  */
21
21
  import { ensureMemoryLayout, buildMemorySystemPrompt, invalidateCache } from "../source.js";
22
22
  import { stripCitations, extractCitedSessionIds, hasCitationMarkup } from "../citation.js";
23
- import { MemoryStore } from "../store.js";
24
- import { runPhase1 } from "../phase1.js";
25
- import { runPhase2 } from "../phase2.js";
23
+ import { MemoryStore, existingMemoryStores } from "../store.js";
24
+ import { runMemoryPipeline, runMemoryConsolidation } from "../pipeline.js";
25
+ import { sessionMemoryVersion, withSessionMemoryVersion } from "../session-version.js";
26
26
  import { setPluginInput, setSubSessionDirectory, cleanupOldSubSessions, isMemorySubSession, abortActiveSubSessions, } from "../llm.js";
27
27
  import { pluginOptions, clearConfigWarnings, resetPluginOptions } from "../options.js";
28
- import { memoryDbPath } from "../paths.js";
28
+ import { dataRoot } from "../paths.js";
29
29
  import { closeDb } from "../db.js";
30
30
  import { beginPluginShutdown, isPluginShuttingDown, resetPluginLifecycle } from "../lifecycle.js";
31
31
  import { hostMcpStatus } from "../host-client.js";
32
- import { recordDiagnostic } from "../diagnostics.js";
33
32
  import { resetAgentHealth } from "../agent-health.js";
34
33
  import { applyPluginOptions, handleSessionDeleted } from "../index.js";
35
34
  import { setV2Context, buildV1ClientShim, rememberV2Session, } from "./shim.js";
36
35
  import { ensureV2Agents } from "./agents.js";
37
36
  import { buildV2Tools } from "./tools.js";
37
+ import { guardMemorySearchTools } from "./search-sandbox.js";
38
38
  import { MemoryStatusRpc } from "./status-rpc.js";
39
39
  import { readMemoryStatus } from "./status.js";
40
40
  import { recordInjection, resetInjectionStats } from "./injection.js";
41
41
  import { overlayV2CitationInstructions } from "./citation-overlay.js";
42
42
  import { estimateTokens } from "../token.js";
43
- let phase1InFlight = false;
44
43
  let shimClient = null;
45
44
  const backgroundTasks = new Set();
46
45
  const statusListeners = new Set();
@@ -63,7 +62,6 @@ export async function waitForV2BackgroundTasks() {
63
62
  }
64
63
  /** Test seam: reset module state between tests. */
65
64
  export function resetV2ModuleStateForTest() {
66
- phase1InFlight = false;
67
65
  statusListeners.clear();
68
66
  backgroundTasks.clear();
69
67
  seenTurnSessions.clear();
@@ -77,11 +75,12 @@ function recordV2Citations(sessionId, assistantMessageId, text) {
77
75
  return;
78
76
  const ids = extractCitedSessionIds(text);
79
77
  if (ids.length > 0)
80
- getStore().recordUsageOnce(sessionId, assistantMessageId, ids);
78
+ withSessionMemoryVersion(sessionId, () => getStore().recordUsageOnce(sessionId, assistantMessageId, ids));
81
79
  }
82
80
  function stripAndReconcileCitations(sessionId, messages) {
83
- for (const [i, msg] of (messages ?? []).entries()) {
84
- if (msg?.type !== "assistant" || !Array.isArray(msg.content))
81
+ for (const msg of messages ?? []) {
82
+ // Model-bound LLM.Message uses role; persisted/legacy rows use type.
83
+ if ((msg?.role ?? msg?.type) !== "assistant" || !Array.isArray(msg.content))
85
84
  continue;
86
85
  for (const part of msg.content) {
87
86
  if (part?.type !== "text" || typeof part.text !== "string")
@@ -89,7 +88,10 @@ function stripAndReconcileCitations(sessionId, messages) {
89
88
  if (!hasCitationMarkup(part.text))
90
89
  continue;
91
90
  try {
92
- recordV2Citations(sessionId, String(msg.id ?? `context-part-${i}`), part.text);
91
+ // Context fragments may have no durable id. Inventing one would count
92
+ // the same citation again after text.ended (and after compaction).
93
+ if (typeof msg.id === "string")
94
+ recordV2Citations(sessionId, msg.id, part.text);
93
95
  }
94
96
  catch (e) {
95
97
  console.error("[opencode-codex-memory] citation recording failed:", e);
@@ -183,6 +185,7 @@ async function classifyExternalContextTool(toolName) {
183
185
  function stampAndPump(sid, directory) {
184
186
  rememberV2Session(sid, directory ?? null);
185
187
  try {
188
+ sessionMemoryVersion(sid);
186
189
  getStore().stampMemoryModeIfAbsent(sid, pluginOptions.generate_memories ? "enabled" : "disabled");
187
190
  }
188
191
  catch (e) {
@@ -191,52 +194,17 @@ function stampAndPump(sid, directory) {
191
194
  trackBackgroundTask(triggerPhase1(sid));
192
195
  }
193
196
  async function triggerPhase1(currentSessionId) {
194
- if (phase1InFlight || !pluginOptions.generate_memories || isPluginShuttingDown())
195
- return;
196
- phase1InFlight = true;
197
197
  notifyStatusChanged();
198
198
  try {
199
- await runPhase1(getStore(), {
200
- maxAgeDays: pluginOptions.max_rollout_age_days,
201
- minIdleHours: pluginOptions.min_rollout_idle_hours,
202
- maxClaimed: pluginOptions.max_rollouts_per_startup,
203
- maxUnusedDays: pluginOptions.max_unused_days,
204
- excludeSession: currentSessionId,
205
- extractModel: pluginOptions.extract_model,
206
- });
207
- }
208
- catch (err) {
209
- console.error("[opencode-codex-memory] phase1 error:", err);
210
- recordDiagnostic("error", "phase1", err instanceof Error ? err.message : String(err));
199
+ await runMemoryPipeline(currentSessionId);
211
200
  }
212
201
  finally {
213
- phase1InFlight = false;
214
202
  notifyStatusChanged();
215
203
  }
216
- trackBackgroundTask(triggerPhase2().then(() => { }));
217
204
  }
218
- async function triggerPhase2(bypassCooldown = false) {
219
- if (isPluginShuttingDown())
220
- return "shutting_down";
205
+ async function triggerPhase2() {
221
206
  try {
222
- const result = await runPhase2(getStore(), {
223
- maxRaw: pluginOptions.max_raw_memories_for_consolidation,
224
- maxUnusedDays: pluginOptions.max_unused_days,
225
- extensionRetentionDays: 7,
226
- consolidationModel: pluginOptions.consolidation_model,
227
- codexInterop: pluginOptions.codex_interop,
228
- claudeImport: pluginOptions.claude_import,
229
- bypassCooldown,
230
- });
231
- if (result.status !== "already_running" && result.status !== "skipped_cooldown" && result.status !== "skipped_running") {
232
- recordDiagnostic(result.status === "succeeded" || result.status === "no_workspace_changes" ? "info" : "warn", "phase2", result.status);
233
- }
234
- return result.status;
235
- }
236
- catch (err) {
237
- console.error("[opencode-codex-memory] phase2 error:", err);
238
- recordDiagnostic("error", "phase2", err instanceof Error ? err.message : String(err));
239
- return "failed";
207
+ return (await runMemoryConsolidation()).join(", ");
240
208
  }
241
209
  finally {
242
210
  notifyStatusChanged();
@@ -244,29 +212,13 @@ async function triggerPhase2(bypassCooldown = false) {
244
212
  }
245
213
  /** /memory "Consolidate now": one phase-1 pass over idle sessions, then phase 2 without cooldown. */
246
214
  async function consolidateNow() {
247
- if (phase1InFlight)
248
- return "already_running";
249
- if (!pluginOptions.generate_memories)
250
- return "generation_disabled";
251
- phase1InFlight = true;
252
215
  notifyStatusChanged();
253
216
  try {
254
- await runPhase1(getStore(), {
255
- maxAgeDays: pluginOptions.max_rollout_age_days,
256
- minIdleHours: pluginOptions.min_rollout_idle_hours,
257
- maxClaimed: pluginOptions.max_rollouts_per_startup,
258
- maxUnusedDays: pluginOptions.max_unused_days,
259
- extractModel: pluginOptions.extract_model,
260
- });
261
- }
262
- catch (err) {
263
- recordDiagnostic("error", "phase1", err instanceof Error ? err.message : String(err));
217
+ return (await runMemoryPipeline(undefined, true)).join(", ");
264
218
  }
265
219
  finally {
266
- phase1InFlight = false;
267
220
  notifyStatusChanged();
268
221
  }
269
- return triggerPhase2(true);
270
222
  }
271
223
  export async function setup(ctx) {
272
224
  resetPluginLifecycle();
@@ -282,16 +234,17 @@ export async function setup(ctx) {
282
234
  if (rawOptions && Object.keys(rawOptions).length > 0)
283
235
  applyPluginOptions(rawOptions);
284
236
  else {
285
- const previousDb = memoryDbPath();
237
+ const previousDb = dataRoot();
286
238
  resetPluginOptions();
287
- if (memoryDbPath() !== previousDb)
239
+ if (dataRoot() !== previousDb)
288
240
  closeDb();
289
241
  }
290
242
  await ensureV2Agents(ctx);
291
243
  const statusRegistration = await ctx.rpc.register(MemoryStatusRpc, {
292
244
  status: async (input) => {
293
245
  const sessionID = input?.sessionID;
294
- return readMemoryStatus(typeof sessionID === "string" ? sessionID : null);
246
+ const minimum = input?.minConsolidatedThreads;
247
+ return readMemoryStatus(typeof sessionID === "string" ? sessionID : null, minimum);
295
248
  },
296
249
  setOption: async (input) => {
297
250
  const { key, value } = (input ?? {});
@@ -308,7 +261,20 @@ export async function setup(ctx) {
308
261
  return { ok: false };
309
262
  }
310
263
  }
264
+ const previous = pluginOptions[key];
311
265
  pluginOptions[key] = value;
266
+ if (key === "use_memories" && value !== previous) {
267
+ try {
268
+ // Transforms capture options but the host only replays them after an
269
+ // explicit registry invalidation. Affect future tool snapshots now.
270
+ await ctx.tool.reload();
271
+ }
272
+ catch (error) {
273
+ pluginOptions[key] = previous;
274
+ console.error("[opencode-codex-memory] failed to reload V2 memory tools:", error);
275
+ return { ok: false };
276
+ }
277
+ }
312
278
  invalidateCache();
313
279
  notifyStatusChanged();
314
280
  return { ok: true };
@@ -334,6 +300,7 @@ export async function setup(ctx) {
334
300
  });
335
301
  };
336
302
  await ctx.tool.transform((editor) => {
303
+ guardMemorySearchTools(editor, (sessionID) => ctx.session.get({ sessionID }));
337
304
  for (const t of buildV2Tools())
338
305
  editor.add(t);
339
306
  });
@@ -362,11 +329,13 @@ export async function setup(ctx) {
362
329
  }
363
330
  if (!inject || !pluginOptions.use_memories)
364
331
  return;
365
- ensureMemoryLayout();
366
- const memoryPrompt = buildMemorySystemPrompt(pluginOptions.dedicated_tools);
332
+ const memoryPrompt = withSessionMemoryVersion(sid, () => {
333
+ ensureMemoryLayout();
334
+ return buildMemorySystemPrompt(pluginOptions.dedicated_tools);
335
+ });
367
336
  if (!memoryPrompt)
368
337
  return;
369
- const text = overlayV2CitationInstructions(memoryPrompt);
338
+ const text = overlayV2CitationInstructions(memoryPrompt, sessionMemoryVersion(sid));
370
339
  if (!Array.isArray(ev.system))
371
340
  ev.system = [];
372
341
  ev.system.push({ type: "text", text });
@@ -412,8 +381,10 @@ export async function setup(ctx) {
412
381
  // Bounded reseed before the event loop can see leftover helpers as user sessions.
413
382
  await cleanupOldSubSessions();
414
383
  try {
415
- if (getStore().releaseOrphanedPhase2Job()) {
416
- console.warn("[opencode-codex-memory] released a consolidation lease orphaned by a dead process");
384
+ for (const store of existingMemoryStores()) {
385
+ if (store.releaseOrphanedPhase2Job()) {
386
+ console.warn(`[opencode-codex-memory] released orphaned ${store.version} consolidation lease`);
387
+ }
417
388
  }
418
389
  }
419
390
  catch (err) {
@@ -452,7 +423,7 @@ export async function setup(ctx) {
452
423
  const sid = sessionIdFromV2Event(data);
453
424
  if (sid) {
454
425
  try {
455
- handleSessionDeleted(sid, getStore(), () => {
426
+ handleSessionDeleted(sid, undefined, () => {
456
427
  if (pluginOptions.generate_memories)
457
428
  trackBackgroundTask(triggerPhase2().then(() => { }));
458
429
  });
@@ -0,0 +1,4 @@
1
+ /** Pattern permissions cannot constrain paths. Wrap executors, not fail-open hooks. */
2
+ export declare function guardMemorySearchTools(editor: {
3
+ update(id: string, update: (tool: any) => void): void;
4
+ }, getSession: (sessionID: string) => Promise<unknown>): void;
@@ -0,0 +1,33 @@
1
+ import path from "node:path";
2
+ import { allMemoryRoots } from "../paths.js";
3
+ import { safeResolveUnderRoot } from "../path-guard.js";
4
+ import { MEMORIZE_AGENT_ID } from "./agents.js";
5
+ /** Pattern permissions cannot constrain paths. Wrap executors, not fail-open hooks. */
6
+ export function guardMemorySearchTools(editor, getSession) {
7
+ const roots = allMemoryRoots();
8
+ for (const name of ["glob", "grep"]) {
9
+ editor.update(name, (tool) => {
10
+ const execute = tool.execute;
11
+ tool.execute = async (input, context) => {
12
+ if (context.agent !== MEMORIZE_AGENT_ID)
13
+ return execute(input, context);
14
+ const response = await getSession(context.sessionID);
15
+ const session = response?.data ?? response;
16
+ // Helper permissions persist across plugin reloads and select one writer
17
+ // even during dual-write. Never fall back to the active project or version.
18
+ const allowed = roots.filter((root) => session?.permissions?.some((rule) => rule.action === "read" && rule.resource === root && rule.effect === "allow"));
19
+ if (allowed.length !== 1)
20
+ throw new Error("memory search requires one session-scoped memory workspace");
21
+ const root = allowed[0];
22
+ const requested = input.path ?? ".";
23
+ if (typeof requested !== "string")
24
+ throw new Error("invalid memory search path");
25
+ const target = safeResolveUnderRoot(root, path.relative(root, path.resolve(root, requested)));
26
+ if (name === "glob" && (path.isAbsolute(input.pattern) || /(^|[\\/,{])\.\.([\\/},]|$)/.test(input.pattern))) {
27
+ throw new Error("glob pattern escapes memory workspace");
28
+ }
29
+ return execute({ ...input, path: target }, context);
30
+ };
31
+ });
32
+ }
33
+ }
@@ -59,6 +59,8 @@ export declare function setV2ServiceDependenciesForTest(dependencies: V2ServiceD
59
59
  export declare function invalidateOwnService(): void;
60
60
  /** Last discoverOwnService failure, if ownServiceClient returned null. */
61
61
  export declare function lastServiceFailure(): string | null;
62
+ /** Invalidate broken endpoints for the next call. Never replay mutations or generation. */
63
+ export declare function serviceRequest<T>(client: V2ServiceClient, request: () => Promise<T>): Promise<T>;
62
64
  /** Auth headers for the registered local service. */
63
65
  export declare function serviceHeaders(endpoint: V2ServiceEndpoint): Record<string, string> | undefined;
64
66
  export declare function parseReadyStatus(body: unknown): V2ServiceStatus | null;
@@ -15,22 +15,57 @@ import { OpenCode } from "@opencode/client";
15
15
  import { Service } from "@opencode/client/service";
16
16
  let testDependencies = null;
17
17
  let clientPromise = null;
18
+ let cachedClient = null;
18
19
  let lastFailure = null;
19
20
  const SERVICE_REQUEST_TIMEOUT_MS = 3_000;
20
21
  /** Test seam: replace discovery without changing the production connection path. */
21
22
  export function setV2ServiceDependenciesForTest(dependencies) {
22
23
  testDependencies = dependencies;
23
- clientPromise = null;
24
+ invalidateOwnService();
24
25
  }
25
26
  /** Forget a cached endpoint after a service restart or failed request. */
26
27
  export function invalidateOwnService() {
27
28
  clientPromise = null;
29
+ cachedClient = null;
28
30
  lastFailure = null;
29
31
  }
30
32
  /** Last discoverOwnService failure, if ownServiceClient returned null. */
31
33
  export function lastServiceFailure() {
32
34
  return lastFailure;
33
35
  }
36
+ function connectionFailed(error) {
37
+ let failed = false;
38
+ const seen = new Set();
39
+ for (let current = error; current && !seen.has(current); current = current.cause ?? current.error) {
40
+ seen.add(current);
41
+ if (current.name === "AbortError")
42
+ return false;
43
+ const status = current.status ?? current.statusCode ?? current.response?.status;
44
+ if (status === 401 || status === 403 || current.reason === "Transport")
45
+ failed = true;
46
+ if (/ECONNREFUSED|ECONNRESET|EPIPE|ENOTFOUND|ETIMEDOUT|fetch failed|unauthori[sz]ed/i.test([current.code, current.type, current._tag, current.name, current.message].join(" ")))
47
+ failed = true;
48
+ }
49
+ return failed;
50
+ }
51
+ /** Invalidate broken endpoints for the next call. Never replay mutations or generation. */
52
+ export async function serviceRequest(client, request) {
53
+ const invalidate = (error) => {
54
+ if (client === cachedClient && connectionFailed(error)) {
55
+ invalidateOwnService();
56
+ lastFailure = error instanceof Error ? error.message : "registered OpenCode service connection failed";
57
+ }
58
+ };
59
+ try {
60
+ const result = await request();
61
+ invalidate(result?.error);
62
+ return result;
63
+ }
64
+ catch (error) {
65
+ invalidate(error);
66
+ throw error;
67
+ }
68
+ }
34
69
  /** Auth headers for the registered local service. */
35
70
  export function serviceHeaders(endpoint) {
36
71
  return Service.headers(endpoint);
@@ -192,17 +227,21 @@ export async function ownServiceClient() {
192
227
  if (!clientPromise) {
193
228
  const request = discoverOwnService()
194
229
  .then((found) => {
195
- lastFailure = found ? null : "no registered OpenCode 2 service.json";
230
+ if (clientPromise === request) {
231
+ cachedClient = found?.client ?? null;
232
+ lastFailure = found ? null : "no registered OpenCode 2 service.json";
233
+ }
196
234
  return found?.client ?? null;
197
235
  })
198
236
  .catch((err) => {
199
- lastFailure = err instanceof Error ? err.message : String(err);
237
+ if (clientPromise === request)
238
+ lastFailure = err instanceof Error ? err.message : String(err);
200
239
  console.warn("[opencode-codex-memory] registered OpenCode service unavailable:", err);
201
240
  return null;
202
241
  });
203
242
  clientPromise = request;
204
243
  const result = await request;
205
- if (!result)
244
+ if (!result && clientPromise === request)
206
245
  clientPromise = null;
207
246
  return result;
208
247
  }
@@ -18,7 +18,7 @@
18
18
  * the V1 shutdown/liveness logic keeps working across hosts.
19
19
  * - config.get → public service config documents adapted for the V1 resolver;
20
20
  * callers fall back to session defaults if the service is unavailable.
21
- * - provider.list → catalog.model.list adapted to the V1 catalog shape for
21
+ * - provider.list → model.list adapted to the V1 catalog shape for
22
22
  * reasoning-variant mapping.
23
23
  * - mcp.status → mcp.list adapted to the V1 status map.
24
24
  *
@@ -49,7 +49,7 @@ export declare function adaptV2Messages(msgs: unknown): Array<{
49
49
  };
50
50
  parts?: unknown[];
51
51
  }>;
52
- /** V2 catalog.model.list → V1 provider-list shape for catalogVariantKeys. */
52
+ /** V2 model.list (legacy catalog.model.list) → V1 provider-list shape. */
53
53
  export declare function adaptProviderCatalog(v2: unknown): unknown;
54
54
  /** V2 mcp.list → V1 mcp.status map shape. */
55
55
  export declare function adaptMcpStatus(v2: unknown): unknown;