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,6 +1,7 @@
1
1
  import { createHash } from "crypto";
2
2
  import fs from "fs";
3
3
  import path from "path";
4
+ import { currentMemoryVersion } from "./memory-version.js";
4
5
  import { memoryRoot } from "./paths.js";
5
6
  import { assertMemoryRootSafe, readRegularFileNoFollow, safeResolveMemoryPath, writeRegularFileNoFollow, } from "./path-guard.js";
6
7
  import { DIFF_ARTIFACT } from "./git-baseline.js";
@@ -73,9 +74,11 @@ export function ensureLayout() {
73
74
  for (const dir of [ROLLOUT_DIR, SKILLS_DIR, EXTENSIONS_DIR, ADHOC_NOTES_DIR]) {
74
75
  fs.mkdirSync(safeResolveMemoryPath(dir), { recursive: true });
75
76
  }
76
- const memoryMd = safeResolveMemoryPath("MEMORY.md");
77
- if (!fs.existsSync(memoryMd))
78
- writeRegularFileNoFollow(memoryMd, "# MEMORY.md\n\n_Searchable index of memories._\n");
77
+ if (currentMemoryVersion() === "v1") {
78
+ const memoryMd = safeResolveMemoryPath("MEMORY.md");
79
+ if (!fs.existsSync(memoryMd))
80
+ writeRegularFileNoFollow(memoryMd, "# MEMORY.md\n\n_Searchable index of memories._\n");
81
+ }
79
82
  const summary = safeResolveMemoryPath("memory_summary.md");
80
83
  if (!fs.existsSync(summary))
81
84
  writeRegularFileNoFollow(summary, "");
@@ -89,7 +92,19 @@ export function ensureLayout() {
89
92
  * a regular file and memory_summary.md must start with the exact line `v1`.
90
93
  * Invalid artifacts force a consolidator re-run and block baseline reset.
91
94
  */
95
+ const V2_SUMMARY_HEADINGS = ["## User Profile", "## User preferences", "## General Tips", "## What's in Memory"];
96
+ export function isValidV2Summary(summary) {
97
+ if (summary.split(/\r?\n/, 1)[0] !== "v1")
98
+ return false;
99
+ if (Buffer.byteLength(summary, "utf8") >= 10_000)
100
+ return false;
101
+ const lines = summary.split(/\r?\n/).map((line) => line.trim());
102
+ return V2_SUMMARY_HEADINGS.every((heading) => lines.includes(heading));
103
+ }
92
104
  export function validateConsolidationArtifacts(root = memoryRoot()) {
105
+ return validateConsolidationArtifactsForVersion(root, "v1");
106
+ }
107
+ export function validateConsolidationArtifactsForVersion(root = memoryRoot(), version = currentMemoryVersion()) {
93
108
  let removedSymlinks;
94
109
  try {
95
110
  removedSymlinks = removeMemorySymlinks(root);
@@ -100,14 +115,16 @@ export function validateConsolidationArtifacts(root = memoryRoot()) {
100
115
  if (removedSymlinks !== 0) {
101
116
  return { ok: false, reason: `removed ${removedSymlinks} symbolic links from consolidated memory workspace` };
102
117
  }
103
- const memoryPath = path.join(root, "MEMORY.md");
104
- try {
105
- const st = fs.lstatSync(memoryPath);
106
- if (!st.isFile())
107
- return { ok: false, reason: `consolidated memory artifact is not a file: ${memoryPath}` };
108
- }
109
- catch {
110
- return { ok: false, reason: `missing consolidated memory artifact: ${memoryPath}` };
118
+ if (version === "v1") {
119
+ const memoryPath = path.join(root, "MEMORY.md");
120
+ try {
121
+ const st = fs.lstatSync(memoryPath);
122
+ if (!st.isFile())
123
+ return { ok: false, reason: `consolidated memory artifact is not a file: ${memoryPath}` };
124
+ }
125
+ catch {
126
+ return { ok: false, reason: `missing consolidated memory artifact: ${memoryPath}` };
127
+ }
111
128
  }
112
129
  const summaryPath = path.join(root, "memory_summary.md");
113
130
  let summary;
@@ -124,6 +141,9 @@ export function validateConsolidationArtifacts(root = memoryRoot()) {
124
141
  if (first !== "v1") {
125
142
  return { ok: false, reason: `memory summary artifact does not start with v1: ${summaryPath}` };
126
143
  }
144
+ if (version === "v2" && !isValidV2Summary(summary)) {
145
+ return { ok: false, reason: "invalid v2 memory summary" };
146
+ }
127
147
  return { ok: true };
128
148
  }
129
149
  const RAW_MEMORY_MAX_CHARS = 10_000;
@@ -9,8 +9,12 @@ export declare const memory_reset: {
9
9
  };
10
10
  export declare const memory_inspect: {
11
11
  description: string;
12
- args: {};
13
- execute(args: Record<string, never>, context: import("@opencode-ai/plugin").ToolContext): Promise<import("@opencode-ai/plugin").ToolResult>;
12
+ args: {
13
+ min_consolidated_threads: import("zod").ZodOptional<import("zod").ZodNumber>;
14
+ };
15
+ execute(args: {
16
+ min_consolidated_threads?: number | undefined;
17
+ }, context: import("@opencode-ai/plugin").ToolContext): Promise<import("@opencode-ai/plugin").ToolResult>;
14
18
  };
15
19
  export declare const memory_mode: {
16
20
  description: string;
@@ -1,8 +1,8 @@
1
1
  import fs from "fs";
2
2
  import path from "path";
3
3
  import { tool } from "@opencode-ai/plugin";
4
- import { memoryRoot, memorySummaryPath, dataRoot, memoryHomeSource } from "../src/paths.js";
5
- import { MemoryStore, PHASE2_COOLDOWN_MS } from "../src/store.js";
4
+ import { allMemoryRoots, memoryDbPath, memoryRoot, memorySummaryPath, sessionMetaDbPath, dataRoot, memoryHomeSource } from "../src/paths.js";
5
+ import { clearAllVersionMemoryData, MemoryStore, PHASE2_COOLDOWN_MS } from "../src/store.js";
6
6
  import { invalidateCache } from "../src/source.js";
7
7
  import { estimateTokens } from "../src/token.js";
8
8
  import { assertMemoryRootSafe, readRegularFileNoFollow } from "../src/path-guard.js";
@@ -14,14 +14,20 @@ import { formatDiagnosticLine, getDiscoveryStatus, getRecentDiagnostics, } from
14
14
  import { isPluginShuttingDown } from "../src/lifecycle.js";
15
15
  import { getAgentHealth } from "../src/agent-health.js";
16
16
  import { activeProviderCapacityBackoffs } from "../src/ratelimit.js";
17
+ import { readMigrationStatus, memoryPipelineSnapshots } from "../src/migration.js";
18
+ import { peekSessionMemoryVersion } from "../src/session-version.js";
19
+ import { withMemoryVersion, writeMemoryVersions } from "../src/memory-version.js";
17
20
  function isSymlinkedRoot() {
18
- try {
19
- assertMemoryRootSafe();
20
- return false;
21
- }
22
- catch {
23
- return true;
21
+ for (const root of allMemoryRoots()) {
22
+ try {
23
+ if (fs.lstatSync(root).isSymbolicLink())
24
+ return true;
25
+ }
26
+ catch {
27
+ // Missing root is fine.
28
+ }
24
29
  }
30
+ return false;
25
31
  }
26
32
  // Mirrors codex clear_memory_root_contents: deletes EVERY entry including
27
33
  // .git, so previously deleted/redacted memory content is not recoverable
@@ -29,8 +35,7 @@ function isSymlinkedRoot() {
29
35
  // every remove failure up, and a swallowed error here would report a
30
36
  // successful reset while secrets/memories survive on disk. lstat semantics:
31
37
  // a symlinked entry is unlinked itself, never followed.
32
- function wipeMemoriesDir() {
33
- const root = memoryRoot();
38
+ function wipeMemoryRoot(root) {
34
39
  if (!fs.existsSync(root))
35
40
  return;
36
41
  for (const entry of fs.readdirSync(root)) {
@@ -54,6 +59,10 @@ function homeSourceLabel(source) {
54
59
  return "OpenCode data dir";
55
60
  }
56
61
  }
62
+ function wipeMemoriesDir() {
63
+ for (const root of allMemoryRoots())
64
+ wipeMemoryRoot(root);
65
+ }
57
66
  /**
58
67
  * Renders the effective (post-parse, post-clamp) plugin options plus any
59
68
  * problems recorded while applying them. The plugin never hard-fails on bad
@@ -68,6 +77,11 @@ function renderEffectiveConfig() {
68
77
  "Effective options:",
69
78
  ` generate_memories: ${o.generate_memories}`,
70
79
  ` use_memories: ${o.use_memories}`,
80
+ ` version: ${o.version}`,
81
+ ` dual_write: ${o.dual_write}`,
82
+ ` memory_root: ${memoryRoot()}`,
83
+ ` jobs_db: ${memoryDbPath()}`,
84
+ ` session_meta_db: ${sessionMetaDbPath()}`,
71
85
  ` dedicated_tools: ${o.dedicated_tools}`,
72
86
  ` disable_on_external_context: ${o.disable_on_external_context}`,
73
87
  ` extract_model: ${o.extract_model ?? "(unset — opencode small_model, else agent/provider default)"}`,
@@ -84,15 +98,18 @@ function renderEffectiveConfig() {
84
98
  lines.push(" codex_interop: off");
85
99
  }
86
100
  else {
87
- const resolved = resolveCodexInterop(ci);
88
- if (!resolved) {
101
+ const resolved = withMemoryVersion("v1", () => resolveCodexInterop(ci));
102
+ if (!writeMemoryVersions().includes("v1")) {
103
+ lines.push(" codex_interop: disabled (handbook exchange requires the v1 writer)");
104
+ }
105
+ else if (!resolved) {
89
106
  lines.push(` codex_interop: MISCONFIGURED — the Codex memory root overlaps the plugin memory root (${memoryRoot()}); interop is disabled`);
90
107
  }
91
108
  else {
92
109
  const reachable = fs.existsSync(resolved.codexMemoryRoot);
93
110
  lines.push(` codex_interop: import=${ci.import} export=${ci.export}`, ` codex memories: ${resolved.codexMemoryRoot}${reachable ? "" : " (not found yet — nothing is imported/exported until Codex's memory feature creates it)"}`);
94
111
  if (reachable) {
95
- const mt = codexInteropMtimes(resolved.codexMemoryRoot);
112
+ const mt = withMemoryVersion("v1", () => codexInteropMtimes(resolved.codexMemoryRoot));
96
113
  const fmt = (ms) => (ms == null ? "none" : new Date(ms).toISOString());
97
114
  lines.push(` last import mtimes: MEMORY.md=${fmt(mt.importMemoryMd)} summary=${fmt(mt.importSummary)}`, ` last export mtimes: MEMORY.md=${fmt(mt.exportMemoryMd)} summary=${fmt(mt.exportSummary)}`);
98
115
  }
@@ -166,8 +183,8 @@ function renderAgentHealth() {
166
183
  }
167
184
  export const memory_reset = tool({
168
185
  description: "Reset all persistent memory. Wipes the plugin's extracted memories and jobs tables and the entire " +
169
- "contents of the memories directory (including git history). Per-session memory modes are preserved, " +
170
- "so disabled/polluted sessions stay excluded. Refuses to run if the memory root is a symlink.",
186
+ "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.",
171
188
  args: {
172
189
  confirm: tool.schema.boolean().describe("Must be true to perform the reset."),
173
190
  },
@@ -189,8 +206,7 @@ export const memory_reset = tool({
189
206
  return { output: "Reset refused: memory consolidation is currently running. Try again in a few minutes." };
190
207
  }
191
208
  try {
192
- const store = new MemoryStore();
193
- store.clearMemoryData();
209
+ clearAllVersionMemoryData();
194
210
  wipeMemoriesDir();
195
211
  // codex keeps its state DB pool open across resets (clear_memory_roots_contents
196
212
  // only wipes directories); closing here would strand cached handles elsewhere.
@@ -243,157 +259,173 @@ export const memory_inspect = tool({
243
259
  "(on-disk; injection caps at ~2500), a listing of the memories directory, the " +
244
260
  "effective plugin options, and any configuration warnings. Use it to verify " +
245
261
  "configuration and debug why memory is not building. Read-only.",
246
- args: {},
247
- async execute() {
248
- try {
249
- // Refuse to walk/report through a symlinked root (same rule as reset).
250
- assertMemoryRootSafe();
251
- const store = new MemoryStore();
252
- const outputs = store.stage1Outputs();
253
- const staleBeforeSec = Math.floor(Date.now() / 1000) - pluginOptions.max_rollout_age_days * 86_400;
254
- const stage1Jobs = store.stage1JobSnapshot(staleBeforeSec);
255
- const summaryPath = memorySummaryPath();
256
- let summaryChars = 0;
257
- let summaryTokens = 0;
258
- if (fs.existsSync(summaryPath)) {
259
- const text = readRegularFileNoFollow(summaryPath).content.toString("utf8");
260
- summaryChars = text.length;
261
- summaryTokens = estimateTokens(text);
262
- }
263
- const listing = listMemoriesDir();
264
- const phase2 = store.phase2JobSnapshot();
265
- const phase2Lines = phase2
262
+ args: {
263
+ min_consolidated_threads: tool.schema.number().int().min(1).max(4096).optional()
264
+ .describe("V2 readiness threshold: distinct sessions in a successful consolidation (default 20)."),
265
+ },
266
+ async execute(args, ctx) {
267
+ return withMemoryVersion(peekSessionMemoryVersion(ctx?.sessionID), () => inspect(args, ctx));
268
+ },
269
+ });
270
+ function inspect(args, ctx) {
271
+ try {
272
+ // Refuse to walk/report through a symlinked root (same rule as reset).
273
+ assertMemoryRootSafe();
274
+ const store = new MemoryStore();
275
+ const outputs = store.stage1Outputs();
276
+ const staleBeforeSec = Math.floor(Date.now() / 1000) - pluginOptions.max_rollout_age_days * 86_400;
277
+ const stage1Jobs = store.stage1JobSnapshot(staleBeforeSec);
278
+ const summaryPath = memorySummaryPath();
279
+ let summaryChars = 0;
280
+ let summaryTokens = 0;
281
+ if (fs.existsSync(summaryPath)) {
282
+ const text = readRegularFileNoFollow(summaryPath).content.toString("utf8");
283
+ summaryChars = text.length;
284
+ summaryTokens = estimateTokens(text);
285
+ }
286
+ const listing = listMemoriesDir();
287
+ const phase2 = store.phase2JobSnapshot();
288
+ const phase2Lines = phase2
289
+ ? [
290
+ `phase2_status: ${phase2.status}`,
291
+ `phase2_last_error: ${phase2.last_error ?? "none"}`,
292
+ `phase2_started_at: ${fmtUnixSec(phase2.started_at)}`,
293
+ `phase2_running_for: ${phase2.status === "running" ? fmtElapsedSec(phase2.started_at) : "n/a"}`,
294
+ `phase2_lease_until: ${fmtUnixSec(phase2.lease_until)}`,
295
+ `phase2_retry_at: ${fmtUnixSec(phase2.retry_at)}`,
296
+ `phase2_last_attempt_finished_at: ${fmtUnixSec(phase2.finished_at)}`,
297
+ `phase2_last_success_watermark: ${fmtWatermarkMs(phase2.last_success_watermark)}`,
298
+ // Clean-success finish only — never a failure timestamp.
299
+ `phase2_last_success_finished_at: ${fmtUnixSec(phase2.success_finished_at)}`,
300
+ ...phase2NoteLines(phase2),
301
+ ]
302
+ : [
303
+ "phase2_status: none",
304
+ "phase2_last_error: none",
305
+ "phase2_started_at: none",
306
+ "phase2_running_for: n/a",
307
+ "phase2_lease_until: none",
308
+ "phase2_retry_at: none",
309
+ "phase2_last_attempt_finished_at: none",
310
+ "phase2_last_success_watermark: none",
311
+ "phase2_last_success_finished_at: none",
312
+ ];
313
+ const stage1StatusParts = Object.entries(stage1Jobs.by_status)
314
+ .sort(([a], [b]) => a.localeCompare(b))
315
+ .map(([s, c]) => `${s}=${c}`);
316
+ const fc = stage1Jobs.by_failure_class;
317
+ const failureParts = [
318
+ fc.due > 0 ? `due=${fc.due}` : "",
319
+ fc.backoff > 0 ? `backoff=${fc.backoff}` : "",
320
+ fc.provider_capacity > 0 ? `provider_capacity=${fc.provider_capacity}` : "",
321
+ fc.other_exhausted > 0 ? `other_exhausted=${fc.other_exhausted}` : "",
322
+ ].filter(Boolean);
323
+ const stage1Lines = [
324
+ `stage1_jobs: ${stage1StatusParts.length > 0 ? stage1StatusParts.join(" ") : "none"}`,
325
+ `stage1_failures: ${failureParts.length > 0 ? failureParts.join(" ") : "none"}`,
326
+ ...(stage1Jobs.stale_exhausted > 0
266
327
  ? [
267
- `phase2_status: ${phase2.status}`,
268
- `phase2_last_error: ${phase2.last_error ?? "none"}`,
269
- `phase2_started_at: ${fmtUnixSec(phase2.started_at)}`,
270
- `phase2_running_for: ${phase2.status === "running" ? fmtElapsedSec(phase2.started_at) : "n/a"}`,
271
- `phase2_lease_until: ${fmtUnixSec(phase2.lease_until)}`,
272
- `phase2_retry_at: ${fmtUnixSec(phase2.retry_at)}`,
273
- `phase2_last_attempt_finished_at: ${fmtUnixSec(phase2.finished_at)}`,
274
- `phase2_last_success_watermark: ${fmtWatermarkMs(phase2.last_success_watermark)}`,
275
- // Clean-success finish only — never a failure timestamp.
276
- `phase2_last_success_finished_at: ${fmtUnixSec(phase2.success_finished_at)}`,
277
- ...phase2NoteLines(phase2),
328
+ `stage1_stale_exhausted: ${stage1Jobs.stale_exhausted} (older than max_rollout_age_days, will not retry)`,
278
329
  ]
279
- : [
280
- "phase2_status: none",
281
- "phase2_last_error: none",
282
- "phase2_started_at: none",
283
- "phase2_running_for: n/a",
284
- "phase2_lease_until: none",
285
- "phase2_retry_at: none",
286
- "phase2_last_attempt_finished_at: none",
287
- "phase2_last_success_watermark: none",
288
- "phase2_last_success_finished_at: none",
289
- ];
290
- const stage1StatusParts = Object.entries(stage1Jobs.by_status)
291
- .sort(([a], [b]) => a.localeCompare(b))
292
- .map(([s, c]) => `${s}=${c}`);
293
- const fc = stage1Jobs.by_failure_class;
294
- const failureParts = [
295
- fc.due > 0 ? `due=${fc.due}` : "",
296
- fc.backoff > 0 ? `backoff=${fc.backoff}` : "",
297
- fc.provider_capacity > 0 ? `provider_capacity=${fc.provider_capacity}` : "",
298
- fc.other_exhausted > 0 ? `other_exhausted=${fc.other_exhausted}` : "",
299
- ].filter(Boolean);
300
- const stage1Lines = [
301
- `stage1_jobs: ${stage1StatusParts.length > 0 ? stage1StatusParts.join(" ") : "none"}`,
302
- `stage1_failures: ${failureParts.length > 0 ? failureParts.join(" ") : "none"}`,
303
- ...(stage1Jobs.stale_exhausted > 0
304
- ? [
305
- `stage1_stale_exhausted: ${stage1Jobs.stale_exhausted} (older than max_rollout_age_days, will not retry)`,
306
- ]
307
- : []),
308
- ...stage1Jobs.recent_errors.map((e) => {
309
- const klass = e.failure_class ? `, ${e.failure_class}` : "";
310
- const retry = e.retry_at ? ` retry_at=${fmtUnixSec(e.retry_at)}` : "";
311
- return ` stage1_error ${e.session_id} (${e.status}${klass}): ${e.last_error.slice(0, 200)}${retry}`;
312
- }),
313
- ];
314
- const discovery = getDiscoveryStatus();
315
- const discoveryLine = discovery
316
- ? `discovery: ${discovery.ok ? "ok" : "failed"} count=${discovery.count} at=${new Date(discovery.at).toISOString()}${discovery.error ? ` error=${discovery.error}` : ""} (this process's session list, not total chats)`
317
- : "discovery: never ran (no phase-1 pass yet this process)";
318
- const idleHours = pluginOptions.min_rollout_idle_hours;
319
- const eligibilityHint = `eligibility: sessions must be idle ≥ ${idleHours}h and younger than ${pluginOptions.max_rollout_age_days}d ` +
320
- `(generate_memories=${pluginOptions.generate_memories}). ` +
321
- `For faster local testing, set min_rollout_idle_hours to 1 (clamp floor).`;
322
- const processLines = [
323
- `phase2_in_flight: ${isPhase2InFlight()}`,
324
- `plugin_shutting_down: ${isPluginShuttingDown()}`,
325
- ];
326
- const capacityBackoffs = activeProviderCapacityBackoffs();
327
- const capacityLines = capacityBackoffs.length > 0
328
- ? capacityBackoffs.map((b) => `provider_capacity_backoff ${b.scope}: retry_at=${fmtUnixSec(b.retry_at)}`)
329
- : ["provider_capacity_backoff: none"];
330
- const diagnostics = getRecentDiagnostics(12);
331
- const diagnosticLines = diagnostics.length > 0
332
- ? ["recent_events:", ...diagnostics.map((e) => ` ${formatDiagnosticLine(e)}`)]
333
- : ["recent_events: none"];
334
- const out = [
335
- `stage1_outputs: ${outputs.length}`,
336
- ...stage1Lines,
337
- ...phase2Lines,
338
- discoveryLine,
339
- eligibilityHint,
340
- ...processLines,
341
- ...capacityLines,
342
- `memory_summary_chars: ${summaryChars}`,
343
- `memory_summary_tokens_est: ${summaryTokens} (on disk; injection caps at ~2500)`,
344
- `memories_dir_entries: ${listing.length}`,
345
- "",
346
- ...renderEffectiveConfig(),
347
- "",
348
- ...renderAgentHealth(),
349
- "",
350
- ...diagnosticLines,
351
- "",
352
- "Files:",
353
- listing.length > 0 ? listing.join("\n") : "(empty)",
354
- ].join("\n");
355
- return {
356
- output: out,
357
- metadata: {
358
- stage1_count: outputs.length,
359
- stage1_jobs: stage1Jobs.by_status,
360
- stage1_failures: stage1Jobs.by_failure_class,
361
- stage1_stale_exhausted: stage1Jobs.stale_exhausted,
362
- stage1_recent_errors: stage1Jobs.recent_errors,
363
- phase2_status: phase2?.status ?? null,
364
- phase2_last_error: phase2?.last_error ?? null,
365
- phase2_retry_at: phase2?.retry_at ?? null,
366
- phase2_last_attempt_finished_at: phase2?.finished_at ?? null,
367
- phase2_last_success_watermark: phase2?.last_success_watermark ?? null,
368
- phase2_last_success_finished_at: phase2?.success_finished_at ?? null,
369
- provider_capacity_backoffs: capacityBackoffs,
370
- // Back-compat aliases used by earlier inspect consumers.
371
- phase2_last_finished_at: phase2?.success_finished_at ?? null,
372
- discovery,
373
- summary_chars: summaryChars,
374
- summary_tokens_est: summaryTokens,
375
- files: listing,
376
- effective_options: {
377
- ...pluginOptions,
378
- codex_interop: { ...pluginOptions.codex_interop },
379
- claude_import: {
380
- ...pluginOptions.claude_import,
381
- ...(pluginOptions.claude_import.projects
382
- ? { projects: [...pluginOptions.claude_import.projects] }
383
- : {}),
384
- },
330
+ : []),
331
+ ...stage1Jobs.recent_errors.map((e) => {
332
+ const klass = e.failure_class ? `, ${e.failure_class}` : "";
333
+ const retry = e.retry_at ? ` retry_at=${fmtUnixSec(e.retry_at)}` : "";
334
+ return ` stage1_error ${e.session_id} (${e.status}${klass}): ${e.last_error.slice(0, 200)}${retry}`;
335
+ }),
336
+ ];
337
+ const discovery = getDiscoveryStatus();
338
+ const discoveryLine = discovery
339
+ ? `discovery: ${discovery.ok ? "ok" : "failed"} count=${discovery.count} at=${new Date(discovery.at).toISOString()}${discovery.error ? ` error=${discovery.error}` : ""} (this process's session list, not total chats)`
340
+ : "discovery: never ran (no phase-1 pass yet this process)";
341
+ const idleHours = pluginOptions.min_rollout_idle_hours;
342
+ const eligibilityHint = `eligibility: sessions must be idle ≥ ${idleHours}h and younger than ${pluginOptions.max_rollout_age_days}d ` +
343
+ `(generate_memories=${pluginOptions.generate_memories}). ` +
344
+ `For faster local testing, set min_rollout_idle_hours to 1 (clamp floor).`;
345
+ const processLines = [
346
+ `phase2_in_flight: ${isPhase2InFlight()}`,
347
+ `plugin_shutting_down: ${isPluginShuttingDown()}`,
348
+ ];
349
+ const capacityBackoffs = activeProviderCapacityBackoffs();
350
+ const capacityLines = capacityBackoffs.length > 0
351
+ ? capacityBackoffs.map((b) => `provider_capacity_backoff ${b.scope}: retry_at=${fmtUnixSec(b.retry_at)}`)
352
+ : ["provider_capacity_backoff: none"];
353
+ const diagnostics = getRecentDiagnostics(12);
354
+ const migration = readMigrationStatus(args.min_consolidated_threads);
355
+ const pipelines = memoryPipelineSnapshots();
356
+ const diagnosticLines = diagnostics.length > 0
357
+ ? ["recent_events:", ...diagnostics.map((e) => ` ${formatDiagnosticLine(e)}`)]
358
+ : ["recent_events: none"];
359
+ const out = [
360
+ `stage1_outputs: ${outputs.length}`,
361
+ `read_version: ${peekSessionMemoryVersion(ctx?.sessionID)}`,
362
+ `dual_write: ${pluginOptions.dual_write}`,
363
+ `v2_ready: ${migration.v2Ready}`,
364
+ `v2_consolidated_threads: ${migration.v2ConsolidatedThreads} (minimum ${migration.minConsolidatedThreads})`,
365
+ ...pipelines.map((p) => `pipeline_${p.version}: outputs=${p.stage1Count}, phase2=${p.phase2?.status ?? "none"}, root=${p.root}`),
366
+ ...stage1Lines,
367
+ ...phase2Lines,
368
+ discoveryLine,
369
+ eligibilityHint,
370
+ ...processLines,
371
+ ...capacityLines,
372
+ `memory_summary_chars: ${summaryChars}`,
373
+ `memory_summary_tokens_est: ${summaryTokens} (on disk; injection caps at ~2500)`,
374
+ `memories_dir_entries: ${listing.length}`,
375
+ "",
376
+ ...renderEffectiveConfig(),
377
+ "",
378
+ ...renderAgentHealth(),
379
+ "",
380
+ ...diagnosticLines,
381
+ "",
382
+ "Files:",
383
+ listing.length > 0 ? listing.join("\n") : "(empty)",
384
+ ].join("\n");
385
+ return {
386
+ output: out,
387
+ metadata: {
388
+ stage1_count: outputs.length,
389
+ migration,
390
+ pipelines,
391
+ read_version: peekSessionMemoryVersion(ctx?.sessionID),
392
+ stage1_jobs: stage1Jobs.by_status,
393
+ stage1_failures: stage1Jobs.by_failure_class,
394
+ stage1_stale_exhausted: stage1Jobs.stale_exhausted,
395
+ stage1_recent_errors: stage1Jobs.recent_errors,
396
+ phase2_status: phase2?.status ?? null,
397
+ phase2_last_error: phase2?.last_error ?? null,
398
+ phase2_retry_at: phase2?.retry_at ?? null,
399
+ phase2_last_attempt_finished_at: phase2?.finished_at ?? null,
400
+ phase2_last_success_watermark: phase2?.last_success_watermark ?? null,
401
+ phase2_last_success_finished_at: phase2?.success_finished_at ?? null,
402
+ provider_capacity_backoffs: capacityBackoffs,
403
+ // Back-compat aliases used by earlier inspect consumers.
404
+ phase2_last_finished_at: phase2?.success_finished_at ?? null,
405
+ discovery,
406
+ summary_chars: summaryChars,
407
+ summary_tokens_est: summaryTokens,
408
+ files: listing,
409
+ effective_options: {
410
+ ...pluginOptions,
411
+ codex_interop: { ...pluginOptions.codex_interop },
412
+ claude_import: {
413
+ ...pluginOptions.claude_import,
414
+ ...(pluginOptions.claude_import.projects
415
+ ? { projects: [...pluginOptions.claude_import.projects] }
416
+ : {}),
385
417
  },
386
- config_warnings: [...getConfigWarnings()],
387
- agent_health: getAgentHealth(),
388
- recent_events: diagnostics,
389
418
  },
390
- };
391
- }
392
- catch (err) {
393
- return { output: `memory_inspect error: ${err.message}` };
394
- }
395
- },
396
- });
419
+ config_warnings: [...getConfigWarnings()],
420
+ agent_health: getAgentHealth(),
421
+ recent_events: diagnostics,
422
+ },
423
+ };
424
+ }
425
+ catch (err) {
426
+ return { output: `memory_inspect error: ${err.message}` };
427
+ }
428
+ }
397
429
  export const memory_mode = tool({
398
430
  description: "Set the memory mode for the target session (current session by default). 'enabled' allows Phase 1 extraction. " +
399
431
  "'disabled' excludes this session from extraction. 'polluted' marks it as having external context " +
@@ -1,7 +1,17 @@
1
1
  import fs from "fs";
2
2
  import path from "path";
3
3
  import { safeResolveMemoryPath, assertMemoryRootSafe, readRegularFileNoFollow, writeRegularFileNoFollow, } from "../src/path-guard.js";
4
- import { tool } from "@opencode-ai/plugin";
4
+ import { tool as defineTool } from "@opencode-ai/plugin";
5
+ import { withSessionMemoryVersion } from "../src/session-version.js";
6
+ // Both host adapters call these definitions. Resolve once for the whole tool
7
+ // execution, so relative paths follow the namespace injected into this chat.
8
+ function sessionTool(definition) {
9
+ return defineTool({
10
+ ...definition,
11
+ execute: (args, ctx) => withSessionMemoryVersion(ctx.sessionID, () => definition.execute(args, ctx)),
12
+ });
13
+ }
14
+ const tool = Object.assign(sessionTool, { schema: defineTool.schema });
5
15
  const MAX_READ_BYTES = 256 * 1024;
6
16
  export const memory_read = tool({
7
17
  description: "Read a file from the persistent memory workspace (MEMORY.md, rollout_summaries/*, skills/*, etc.). " +
package/opencode.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "agent": {
4
4
  "memorize": {
5
5
  "mode": "subagent",
6
- "prompt": "You are a memory consolidation agent. Read the workspace diff file and update MEMORY.md, memory_summary.md, and skills/ under the memory workspace only. Do not read or edit project source files outside that memory root. Keep memory_summary.md under 10000 chars (2500 tokens). Prune stale entries. Do not access the network.",
6
+ "prompt": "You are a memory consolidation agent. Follow the supplied version-specific consolidation contract and update only its requested artifacts under the supplied memory workspace. Do not read or edit project source files or a different memory workspace. Keep memory_summary.md under 10000 bytes. Prune stale entries. Do not access the network.",
7
7
  "permission": {
8
8
  "*": "deny",
9
9
  "bash": "deny",
@@ -20,7 +20,7 @@
20
20
  },
21
21
  "memorize-extract": {
22
22
  "mode": "subagent",
23
- "prompt": "You are a memory extraction agent. The session transcript is provided inline in the prompt. Extract raw_memory, rollout_summary, and rollout_slug as JSON. Exclude AGENTS.md/instruction content. Redact secrets.",
23
+ "prompt": "You are a memory extraction agent. The session transcript is provided inline in the prompt. Follow the supplied version-specific JSON schema. Exclude AGENTS.md/instruction content. Redact secrets.",
24
24
  "permission": {
25
25
  "*": "deny",
26
26
  "bash": "deny",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-codex-memory",
3
- "version": "0.7.7",
3
+ "version": "0.8.1",
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",
@@ -49,7 +49,7 @@
49
49
  "live:e2e": "bun scripts/live-e2e.ts",
50
50
  "prepack": "npm run build && npm run smoke",
51
51
  "test": "bun test",
52
- "typecheck": "tsc --noEmit"
52
+ "typecheck": "tsc --noEmit -p tsconfig.typecheck.json"
53
53
  },
54
54
  "keywords": [
55
55
  "opencode",