opencode-codex-memory 0.8.4 → 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.
@@ -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.4",
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
- }