opencode-codex-memory 0.8.3 → 0.9.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.
@@ -27,7 +27,8 @@ interface V2ToolDefinition {
27
27
  /**
28
28
  * Same gating as the V1 entry: the read/search/list/add-note tools require
29
29
  * BOTH use_memories and dedicated_tools (codex MemoriesExtension); the
30
- * control tools are always available.
30
+ * control tools are always available. memory_reset needs user approval,
31
+ * which V2 plugin tools cannot request: reset lives in the memory panel.
31
32
  */
32
33
  export declare function buildV2Tools(): V2ToolDefinition[];
33
34
  export {};
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import { z } from "zod";
13
13
  import { memory_read, memory_search, memory_list, memory_add_note } from "../../tools/memory.js";
14
- import { memory_reset, memory_inspect, memory_mode } from "../../tools/control.js";
14
+ import { memory_inspect, memory_mode } from "../../tools/control.js";
15
15
  import { pluginOptions } from "../options.js";
16
16
  import { getV2DiscoveryStatus } from "./shim.js";
17
17
  function adaptTool(name, v1) {
@@ -28,7 +28,10 @@ function adaptTool(name, v1) {
28
28
  worktree: "",
29
29
  abort: tctx.abort instanceof AbortSignal ? tctx.abort : new AbortController().signal,
30
30
  metadata: () => { },
31
- ask: async () => { },
31
+ // OpenCode 2 gives plugin tools no approval request; fail closed.
32
+ ask: async () => {
33
+ throw new Error("User approval is unavailable to plugin tools on OpenCode 2. Use /memory-inspect → Controls instead.");
34
+ },
32
35
  };
33
36
  const res = await v1.execute(input, v1ctx);
34
37
  if (typeof res === "string")
@@ -54,15 +57,15 @@ const ALL_MEMORY_TOOLS = [
54
57
  ["memory_search", memory_search],
55
58
  ["memory_list", memory_list],
56
59
  ["memory_add_note", memory_add_note],
57
- ["memory_reset", memory_reset],
58
60
  ["memory_inspect", memory_inspect],
59
61
  ["memory_mode", memory_mode],
60
62
  ];
61
- const CONTROL_ONLY = new Set(["memory_reset", "memory_inspect", "memory_mode"]);
63
+ const CONTROL_ONLY = new Set(["memory_inspect", "memory_mode"]);
62
64
  /**
63
65
  * Same gating as the V1 entry: the read/search/list/add-note tools require
64
66
  * BOTH use_memories and dedicated_tools (codex MemoriesExtension); the
65
- * control tools are always available.
67
+ * control tools are always available. memory_reset needs user approval,
68
+ * which V2 plugin tools cannot request: reset lives in the memory panel.
66
69
  */
67
70
  export function buildV2Tools() {
68
71
  const full = pluginOptions.use_memories && pluginOptions.dedicated_tools;
@@ -67,7 +67,10 @@ var MemoryStatusRpc = {
67
67
  stage1Count: { type: "integer", minimum: 0 },
68
68
  extracting: { type: "integer", minimum: 0 },
69
69
  phase2Status: { type: ["string", "null"] },
70
- lastError: { type: ["string", "null"] }
70
+ lastError: { type: ["string", "null"] },
71
+ phase2CooldownUntil: { type: ["number", "null"] },
72
+ phase1RetryAt: { type: ["number", "null"] },
73
+ phase2RetryAt: { type: ["number", "null"] }
71
74
  },
72
75
  required: ["version", "stage1Count", "extracting", "phase2Status", "lastError"],
73
76
  additionalProperties: false
@@ -140,6 +143,20 @@ var MemoryStatusRpc = {
140
143
  required: ["status"],
141
144
  additionalProperties: false
142
145
  }
146
+ },
147
+ resetMemory: {
148
+ input: {
149
+ type: "object",
150
+ properties: { confirm: { type: "boolean" } },
151
+ required: ["confirm"],
152
+ additionalProperties: false
153
+ },
154
+ output: {
155
+ type: "object",
156
+ properties: { ok: { type: "boolean" }, message: { type: "string" } },
157
+ required: ["ok", "message"],
158
+ additionalProperties: false
159
+ }
143
160
  }
144
161
  },
145
162
  events: {
@@ -167,7 +184,7 @@ function isMemoryStatus(value) {
167
184
  return false;
168
185
  if (!Number.isInteger(value.minConsolidatedThreads) || value.minConsolidatedThreads < 1 || value.minConsolidatedThreads > 4096)
169
186
  return false;
170
- if (!Array.isArray(value.pipelines) || !value.pipelines.every((pipeline) => isRecord(pipeline) && (pipeline.version === "v1" || pipeline.version === "v2") && Number.isInteger(pipeline.stage1Count) && pipeline.stage1Count >= 0 && Number.isInteger(pipeline.extracting) && pipeline.extracting >= 0 && (pipeline.phase2Status === null || typeof pipeline.phase2Status === "string") && (pipeline.lastError === null || typeof pipeline.lastError === "string")))
187
+ if (!Array.isArray(value.pipelines) || !value.pipelines.every((pipeline) => isRecord(pipeline) && (pipeline.version === "v1" || pipeline.version === "v2") && Number.isInteger(pipeline.stage1Count) && pipeline.stage1Count >= 0 && Number.isInteger(pipeline.extracting) && pipeline.extracting >= 0 && (pipeline.phase2Status === null || typeof pipeline.phase2Status === "string") && (pipeline.lastError === null || typeof pipeline.lastError === "string") && ["phase2CooldownUntil", "phase1RetryAt", "phase2RetryAt"].every((key) => pipeline[key] === undefined || pipeline[key] === null || typeof pipeline[key] === "number" && Number.isFinite(pipeline[key]))))
171
188
  return false;
172
189
  for (const key of ["extractModel", "consolidationModel", "lastSuccessAt", "retryAt"]) {
173
190
  const v = value[key];
@@ -341,6 +358,29 @@ function watchStatus(rpc, context, sessionID) {
341
358
  signal: lifetime.signal
342
359
  };
343
360
  }
361
+ function pipelineRows(s, now) {
362
+ return s.pipelines.flatMap((pipeline) => {
363
+ const version = pipeline.version.toUpperCase();
364
+ const paused = !s.generateMemories || !s.dualWrite && pipeline.version !== s.version;
365
+ const extractionRetry = pipeline.phase1RetryAt != null && pipeline.phase1RetryAt > now;
366
+ const consolidationRetry = pipeline.phase2RetryAt != null && pipeline.phase2RetryAt > now;
367
+ const cooldown = pipeline.phase2CooldownUntil != null && pipeline.phase2CooldownUntil > now;
368
+ const consolidation = pipeline.phase2Status === "pending" ? "Queued" : pipeline.phase2Status === "failed" ? "Retry due" : "Idle";
369
+ return [{
370
+ label: `${version} recaps`,
371
+ value: `${pipeline.stage1Count} stored`,
372
+ tone: "muted"
373
+ }, {
374
+ label: `${version} extraction`,
375
+ value: pipeline.extracting ? `Running (${pipeline.extracting})` : paused ? "Paused" : extractionRetry ? `Retry ${remaining(pipeline.phase1RetryAt, now)}` : "Idle",
376
+ tone: extractionRetry && !paused ? "warn" : "muted"
377
+ }, {
378
+ label: `${version} consolidation`,
379
+ value: pipeline.phase2Status === "running" ? "Running" : paused ? "Paused" : consolidationRetry ? `Retry ${remaining(pipeline.phase2RetryAt, now)}` : cooldown ? `${consolidation} \xB7 cooldown ends ${remaining(pipeline.phase2CooldownUntil, now)}` : pipeline.phase2Status === "pending" ? "Queued \xB7 next activity" : consolidation,
380
+ tone: pipeline.lastError ? "warn" : "muted"
381
+ }];
382
+ });
383
+ }
344
384
  function statusRows(s, now) {
345
385
  return [{
346
386
  label: "Activity",
@@ -355,11 +395,7 @@ function statusRows(s, now) {
355
395
  label: "V2 readiness",
356
396
  value: `${s.v2Ready ? "Ready" : "Warming"} \xB7 ${s.v2ConsolidatedThreads}/${s.minConsolidatedThreads} sessions`,
357
397
  tone: s.v2Ready ? "ok" : "muted"
358
- }, ...s.pipelines.map((pipeline) => ({
359
- label: `${pipeline.version.toUpperCase()} pipeline`,
360
- value: `${pipeline.stage1Count} recaps \xB7 ${pipeline.extracting ? "extracting" : pipeline.phase2Status ?? "idle"}`,
361
- tone: pipeline.lastError ? "warn" : "muted"
362
- })), {
398
+ }, ...pipelineRows(s, now), {
363
399
  label: "Use memories",
364
400
  value: s.useMemories ? "On" : "Off",
365
401
  tone: s.useMemories ? "ok" : "muted"
@@ -427,6 +463,7 @@ function MemoryDialog(context, sessionID) {
427
463
  const [cursor, setCursor] = createSignal(0);
428
464
  const [notice, setNotice] = createSignal(null);
429
465
  const [busy, setBusy] = createSignal(null);
466
+ const [armed, setArmed] = createSignal(false);
430
467
  let scroll;
431
468
  const call = async (id, method, input, done) => {
432
469
  if (busy() || unavailable())
@@ -442,7 +479,7 @@ function MemoryDialog(context, sessionID) {
442
479
  return;
443
480
  const reply = result;
444
481
  if (method === "consolidateNow" ? reply?.status !== "started" : reply?.ok !== true) {
445
- throw new Error("The server did not apply the request. Refresh and try again.");
482
+ throw new Error(reply?.message ?? "The server did not apply the request. Refresh and try again.");
446
483
  }
447
484
  setNotice({
448
485
  message: done,
@@ -509,6 +546,26 @@ function MemoryDialog(context, sessionID) {
509
546
  enabled: s.generateMemories && !running && s.activity !== "stopping",
510
547
  run: () => void call("now", "consolidateNow", {}, "Background run requested. See Overview for progress.")
511
548
  });
549
+ list.push({
550
+ id: "reset",
551
+ title: armed() ? "Reset memory \u2014 press again to confirm" : "Reset memory",
552
+ hint: armed() ? "Erases all learned memories, notes, and history. This cannot be undone. Moving the selection cancels." : running ? "Wait for the running extraction or consolidation to finish." : "Erase all learned memories and notes for every project. Session preferences are kept.",
553
+ enabled: !running,
554
+ run: () => {
555
+ if (!armed()) {
556
+ setArmed(true);
557
+ setNotice({
558
+ message: "Press Enter again to erase all memory.",
559
+ tone: "warn"
560
+ });
561
+ return;
562
+ }
563
+ setArmed(false);
564
+ call("reset", "resetMemory", {
565
+ confirm: true
566
+ }, "Memory reset complete.");
567
+ }
568
+ });
512
569
  return list;
513
570
  };
514
571
  const activate = (i) => {
@@ -531,6 +588,8 @@ function MemoryDialog(context, sessionID) {
531
588
  });
532
589
  };
533
590
  const select = (i) => {
591
+ if (i !== cursor())
592
+ setArmed(false);
534
593
  setCursor(i);
535
594
  const control = controls()[i];
536
595
  if (!control || !scroll)
@@ -553,6 +612,7 @@ function MemoryDialog(context, sessionID) {
553
612
  select((cursor() + d + n) % n);
554
613
  };
555
614
  const switchTab = (next) => {
615
+ setArmed(false);
556
616
  setTab(next);
557
617
  setCursor(0);
558
618
  scroll?.scrollTo(0);
@@ -845,7 +905,7 @@ function MemoryDialog(context, sessionID) {
845
905
  const selected = () => cursor() === i();
846
906
  const disabled = () => !c.enabled || unavailable() || busy() !== null;
847
907
  const fg = () => selected() ? color.selectedText : disabled() ? color.muted : color.text;
848
- const state = () => busy() === c.id ? c.id === "now" ? "Starting\u2026" : "Saving\u2026" : c.on === undefined ? c.enabled ? "Run" : "Unavailable" : c.on ? "On" : "Off";
908
+ const state = () => busy() === c.id ? c.id === "now" ? "Starting\u2026" : c.id === "reset" ? "Resetting\u2026" : "Saving\u2026" : c.id === "reset" && armed() ? "Confirm" : c.on === undefined ? c.enabled ? "Run" : "Unavailable" : c.on ? "On" : "Off";
849
909
  return (() => {
850
910
  var _el$34 = _$createElement("box"), _el$35 = _$createElement("box"), _el$36 = _$createElement("text"), _el$37 = _$createElement("text"), _el$38 = _$createElement("text"), _el$39 = _$createElement("box"), _el$40 = _$createElement("text");
851
911
  _$insertNode(_el$34, _el$35);
@@ -938,7 +998,7 @@ function MemoryDialog(context, sessionID) {
938
998
  _$insert(_el$19, () => tab() === "Controls" ? "select" : "scroll", null);
939
999
  _$insert(_el$21, () => tab() === "Controls" ? "Enter/Space change" : "PgUp/PgDn page \xB7 Home/End ends");
940
1000
  _$effect((_p$) => {
941
- var _v$5 = Math.min(tab() === "Overview" ? 34 : sessionID ? 22 : 19, Math.max(8, dimensions().height - 2)), _v$6 = color.text, _v$7 = color.muted, _v$8 = click(() => {
1001
+ var _v$5 = Math.min(tab() === "Overview" ? 34 : sessionID ? 25 : 22, Math.max(8, dimensions().height - 2)), _v$6 = color.text, _v$7 = color.muted, _v$8 = click(() => {
942
1002
  refresh();
943
1003
  }), _v$9 = color.muted, _v$0 = click(() => context.ui.dialog.clear()), _v$1 = color.muted, _v$10 = color.muted;
944
1004
  _v$5 !== _p$.e && (_p$.e = _$setProp(_el$9, "height", _v$5, _p$.e));
@@ -170,7 +170,8 @@ export function rolloutSummaryFileStem(o) {
170
170
  return slug ? `${prefix}-${slug}` : prefix;
171
171
  }
172
172
  export function rebuildRawMemories(outputs) {
173
- const sorted = [...outputs].sort((a, b) => a.session_id.localeCompare(b.session_id));
173
+ // codex: selected.sort_by_key(thread_id) — byte order, not locale order.
174
+ const sorted = [...outputs].sort((a, b) => (a.session_id < b.session_id ? -1 : a.session_id > b.session_id ? 1 : 0));
174
175
  let content = "# Raw Memories\n\n";
175
176
  if (sorted.length === 0) {
176
177
  content += "No raw memories yet.\n";
@@ -1,3 +1,11 @@
1
+ /**
2
+ * Shared by the memory_reset tool (after user approval) and the OpenCode 2
3
+ * memory panel (whose confirmation is the approval).
4
+ */
5
+ export declare function performMemoryReset(): {
6
+ ok: boolean;
7
+ message: string;
8
+ };
1
9
  export declare const memory_reset: {
2
10
  description: string;
3
11
  args: {
@@ -181,41 +181,58 @@ function renderAgentHealth() {
181
181
  }
182
182
  return lines;
183
183
  }
184
+ function resetBlockedReason() {
185
+ if (isSymlinkedRoot())
186
+ return "Reset refused: memory root is a symlink. Remove it manually to be safe.";
187
+ // A consolidation running in THIS process would recreate files right
188
+ // after the wipe (the sub-agent edits live artifacts and resets the git
189
+ // baseline). Refuse instead of racing it. clearMemoryData also leaves a
190
+ // phase-2 cooldown marker so the next idle/chat hook cannot first-run-claim
191
+ // phase 2 and re-seed the root via ensureLayout. Cross-process consolidators
192
+ // already in flight remain ownership-guarded (their final mark becomes a
193
+ // no-op once the row is replaced) but may leave stray files — same window
194
+ // codex has between CLI clear and a running daemon.
195
+ if (isPhase2InFlight())
196
+ return "Reset refused: memory consolidation is currently running. Try again in a few minutes.";
197
+ return null;
198
+ }
199
+ /**
200
+ * Shared by the memory_reset tool (after user approval) and the OpenCode 2
201
+ * memory panel (whose confirmation is the approval).
202
+ */
203
+ export function performMemoryReset() {
204
+ const blocked = resetBlockedReason();
205
+ if (blocked)
206
+ return { ok: false, message: blocked };
207
+ try {
208
+ clearAllVersionMemoryData();
209
+ wipeMemoriesDir();
210
+ // codex keeps its state DB pool open across resets (clear_memory_roots_contents
211
+ // only wipes directories); closing here would strand cached handles elsewhere.
212
+ invalidateCache();
213
+ return { ok: true, message: "Memory reset complete. Extracted memories and jobs cleared, memories directory (incl. git history) wiped, cache invalidated. Per-session memory modes were preserved." };
214
+ }
215
+ catch (err) {
216
+ return { ok: false, message: `memory_reset error: ${err.message}` };
217
+ }
218
+ }
184
219
  export const memory_reset = tool({
185
220
  description: "Reset all persistent memory. Wipes the plugin's extracted memories and jobs tables and the entire " +
186
221
  "contents of the memories and memories_v2 directories (including git history). Per-session memory modes are preserved, " +
187
- "so disabled/polluted sessions stay excluded. Refuses to run if a memory root is a symlink.",
222
+ "so disabled/polluted sessions stay excluded. Asks the user for approval first. Refuses to run if a memory root is a symlink.",
188
223
  args: {
189
224
  confirm: tool.schema.boolean().describe("Must be true to perform the reset."),
190
225
  },
191
- async execute(args) {
226
+ async execute(args, ctx) {
192
227
  if (!args.confirm)
193
228
  return { output: "Reset aborted: confirm=false." };
194
- if (isSymlinkedRoot()) {
195
- return { output: "Reset refused: memory root is a symlink. Remove it manually to be safe." };
196
- }
197
- // A consolidation running in THIS process would recreate files right
198
- // after the wipe (the sub-agent edits live artifacts and resets the git
199
- // baseline). Refuse instead of racing it. clearMemoryData also leaves a
200
- // phase-2 cooldown marker so the next idle/chat hook cannot first-run-claim
201
- // phase 2 and re-seed the root via ensureLayout. Cross-process consolidators
202
- // already in flight remain ownership-guarded (their final mark becomes a
203
- // no-op once the row is replaced) but may leave stray files — same window
204
- // codex has between CLI clear and a running daemon.
205
- if (isPhase2InFlight()) {
206
- return { output: "Reset refused: memory consolidation is currently running. Try again in a few minutes." };
207
- }
208
- try {
209
- clearAllVersionMemoryData();
210
- wipeMemoriesDir();
211
- // codex keeps its state DB pool open across resets (clear_memory_roots_contents
212
- // only wipes directories); closing here would strand cached handles elsewhere.
213
- invalidateCache();
214
- return { output: "Memory reset complete. Extracted memories and jobs cleared, memories directory (incl. git history) wiped, cache invalidated. Per-session memory modes were preserved." };
215
- }
216
- catch (err) {
217
- return { output: `memory_reset error: ${err.message}` };
218
- }
229
+ const blocked = resetBlockedReason();
230
+ if (blocked)
231
+ return { output: blocked };
232
+ // `confirm` is model-chosen; injected content could set it. Irreversible,
233
+ // so the user approves (a rejection propagates to the host as usual).
234
+ await ctx.ask({ permission: "memory_reset", patterns: ["*"], always: [], metadata: { roots: allMemoryRoots() } });
235
+ return { output: performMemoryReset().message };
219
236
  },
220
237
  });
221
238
  function fmtUnixSec(sec) {
@@ -435,9 +452,23 @@ export const memory_mode = tool({
435
452
  sessionId: tool.schema.string().optional().describe("Session ID. Defaults to the current session."),
436
453
  },
437
454
  async execute(args, ctx) {
455
+ const sid = args.sessionId ?? ctx.sessionID;
456
+ let store;
457
+ let polluted;
458
+ try {
459
+ store = new MemoryStore();
460
+ polluted = store.getMemoryMode(sid) === "polluted";
461
+ }
462
+ catch (err) {
463
+ return { output: `memory_mode error: ${err.message}` };
464
+ }
465
+ // Pollution guards against external content steering memory; the model
466
+ // that read that content must not lift it on its own. A rejection
467
+ // propagates to the host as usual.
468
+ if (args.mode === "enabled" && polluted) {
469
+ await ctx.ask({ permission: "memory_mode", patterns: [sid], always: [], metadata: { sessionId: sid, from: "polluted", to: "enabled" } });
470
+ }
438
471
  try {
439
- const store = new MemoryStore();
440
- const sid = args.sessionId ?? ctx.sessionID;
441
472
  store.setMemoryMode(sid, args.mode);
442
473
  return { output: `Memory mode for session ${sid} set to '${args.mode}'.`, metadata: { sessionId: sid, mode: args.mode } };
443
474
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-codex-memory",
3
- "version": "0.8.3",
3
+ "version": "0.9.0",
4
4
  "description": "Persistent memory plugin for opencode — ports codex's two-phase memory system (extraction → consolidation → injection → citation feedback)",
5
5
  "type": "module",
6
6
  "main": "./dist/src/index.js",
@@ -41,7 +41,7 @@
41
41
  },
42
42
  "scripts": {
43
43
  "dev": "bun --watch src/index.ts",
44
- "build": "tsc && bun scripts/build-tui.ts && rm -rf dist/src/templates && cp -R src/templates dist/src/templates && cp opencode.json dist/opencode.json",
44
+ "build": "rm -rf dist && tsc && bun scripts/build-tui.ts && cp -R src/templates dist/src/templates && cp opencode.json dist/opencode.json",
45
45
  "smoke": "bun scripts/smoke.ts",
46
46
  "contract": "bun scripts/check-opencode-contract.ts",
47
47
  "contract:v2": "bun scripts/check-opencode2-contract.ts",
@@ -1,6 +0,0 @@
1
- export declare function localSessionUpdatedAt(): Map<string, number>;
2
- export declare function overlaySqliteSessionTimes(rows: unknown[]): unknown[];
3
- export declare function overlaySqliteUpdatedAt<T extends {
4
- id: string;
5
- updated_at: number;
6
- }>(rows: T[]): T[];
@@ -1,59 +0,0 @@
1
- /**
2
- * Sandbox/live-test helper: read session watermarks from the isolated
3
- * OpenCode db. Only looks at OPENCODE_CODEX_MEMORY_TEST_ROOT (never the
4
- * host ~/.local/share/opencode db).
5
- */
6
- import { existsSync } from "fs";
7
- import { join } from "path";
8
- import { Database } from "bun:sqlite";
9
- export function localSessionUpdatedAt() {
10
- const out = new Map();
11
- const testRoot = process.env.OPENCODE_CODEX_MEMORY_TEST_ROOT?.trim();
12
- if (!testRoot)
13
- return out;
14
- const dbPath = join(testRoot, "opencode.db");
15
- if (!existsSync(dbPath))
16
- return out;
17
- try {
18
- const db = new Database(dbPath, { readonly: true, strict: false });
19
- try {
20
- const names = new Set(db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all().map((r) => r.name));
21
- const table = names.has("session_v2") ? "session_v2" : names.has("session") ? "session" : null;
22
- if (!table)
23
- return out;
24
- const rows = db.prepare(`SELECT id, time_updated FROM "${table}"`).all();
25
- for (const row of rows) {
26
- if (!row.id || typeof row.time_updated !== "number")
27
- continue;
28
- out.set(row.id, row.time_updated);
29
- }
30
- }
31
- finally {
32
- db.close();
33
- }
34
- }
35
- catch {
36
- // Isolated serve without a readable db: keep host list as-is.
37
- }
38
- return out;
39
- }
40
- export function overlaySqliteSessionTimes(rows) {
41
- const times = localSessionUpdatedAt();
42
- if (times.size === 0)
43
- return rows;
44
- return rows.map((row) => {
45
- if (!row || typeof row !== "object")
46
- return row;
47
- const rec = row;
48
- if (typeof rec.id !== "string" || !times.has(rec.id))
49
- return row;
50
- const updated = times.get(rec.id);
51
- return { ...rec, time: { ...(typeof rec.time === "object" && rec.time ? rec.time : {}), updated } };
52
- });
53
- }
54
- export function overlaySqliteUpdatedAt(rows) {
55
- const times = localSessionUpdatedAt();
56
- if (times.size === 0)
57
- return rows;
58
- return rows.map((row) => (times.has(row.id) ? { ...row, updated_at: times.get(row.id) } : row));
59
- }