opencode-codex-memory 0.9.7 → 0.9.9

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.
package/README.md CHANGED
@@ -35,7 +35,7 @@ to your existing global `~/.config/opencode/opencode.jsonc` or `opencode.json`
35
35
  {
36
36
  "$schema": "https://opencode.ai/config.json",
37
37
  "plugins": [
38
- { "package": "opencode-codex-memory@0.9.7" }
38
+ { "package": "opencode-codex-memory@0.9.9" }
39
39
  ]
40
40
  }
41
41
  ```
@@ -45,7 +45,7 @@ to your existing global `~/.config/opencode/opencode.jsonc` or `opencode.json`
45
45
  ```json
46
46
  {
47
47
  "$schema": "https://opencode.ai/config.json",
48
- "plugin": ["opencode-codex-memory@0.9.7"]
48
+ "plugin": ["opencode-codex-memory@0.9.9"]
49
49
  }
50
50
  ```
51
51
 
@@ -1,6 +1,7 @@
1
1
  import fs from "fs";
2
2
  import path from "path";
3
3
  import { memoryRoot } from "./paths.js";
4
+ import { writeMemoryVersions } from "./memory-version.js";
4
5
  const AGENT_NAMES = ["memorize", "memorize-extract"];
5
6
  const REQUIRED_ALLOWS = {
6
7
  memorize: ["read", "edit", "write", "glob", "grep"],
@@ -69,13 +70,16 @@ function permissionIssues(name, definition) {
69
70
  }
70
71
  if (name === "memorize") {
71
72
  const external = asRecord(permission.external_directory);
72
- const expectedPath = path.join(memoryRoot(), "*");
73
- if (external?.[expectedPath] !== "allow") {
74
- issues.push(`consolidator must allow external_directory '${expectedPath}'`);
73
+ // Agent grants cover all writers; helper-session rules narrow each job to one root.
74
+ const expectedPaths = new Set(writeMemoryVersions().map((version) => path.join(memoryRoot(version), "*")));
75
+ for (const expectedPath of expectedPaths) {
76
+ if (external?.[expectedPath] !== "allow") {
77
+ issues.push(`consolidator must allow external_directory '${expectedPath}'`);
78
+ }
75
79
  }
76
80
  if (external) {
77
81
  for (const [grantedPath, action] of Object.entries(external)) {
78
- if (grantedPath === expectedPath)
82
+ if (expectedPaths.has(grantedPath))
79
83
  continue;
80
84
  if (hasNonDenyAction(action)) {
81
85
  issues.push(`consolidator must deny extra external_directory '${grantedPath}'`);
@@ -3,6 +3,9 @@ export declare const DEFAULT_MIN_CONSOLIDATED_THREADS = 20;
3
3
  export declare function readMigrationStatus(minConsolidatedThreads?: number): {
4
4
  v2ConsolidatedThreads: number;
5
5
  v2Ready: boolean;
6
+ v2NotReadyReason: string | null;
7
+ v2SummaryBytes: number | null;
8
+ v2InjectedSummaryBytes: number | null;
6
9
  minConsolidatedThreads: number;
7
10
  };
8
11
  export declare function memoryPipelineSnapshots(): {
@@ -2,8 +2,9 @@ import fs from "node:fs";
2
2
  import { memoryDbPath, memoryRoot } from "./paths.js";
3
3
  import { MemoryStore, existingMemoryStores } from "./store.js";
4
4
  import { withMemoryVersion } from "./memory-version.js";
5
- import { isValidV2Summary } from "./workspace.js";
5
+ import { validateV2Summary } from "./workspace.js";
6
6
  import { safeResolveUnderRoot, readRegularFileNoFollow } from "./path-guard.js";
7
+ import { MEMORY_V2_SUMMARY_MAX_BYTES, truncateToBytes } from "./token.js";
7
8
  export const DEFAULT_MIN_CONSOLIDATED_THREADS = 20;
8
9
  /** Codex memory/status: high-water progress AND a currently valid V2 summary. */
9
10
  export function readMigrationStatus(minConsolidatedThreads = DEFAULT_MIN_CONSOLIDATED_THREADS) {
@@ -14,14 +15,32 @@ export function readMigrationStatus(minConsolidatedThreads = DEFAULT_MIN_CONSOLI
14
15
  ? withMemoryVersion("v2", () => new MemoryStore().maxConsolidatedThreadCount())
15
16
  : 0;
16
17
  let valid = false;
18
+ let v2SummaryBytes = null;
19
+ let v2InjectedSummaryBytes = null;
20
+ let v2NotReadyReason = null;
17
21
  try {
18
22
  const file = safeResolveUnderRoot(memoryRoot("v2"), "memory_summary.md");
19
- valid = isValidV2Summary(readRegularFileNoFollow(file).content.toString("utf8"));
23
+ const summary = readRegularFileNoFollow(file).content.toString("utf8");
24
+ const validation = validateV2Summary(summary);
25
+ valid = validation.ok;
26
+ v2SummaryBytes = validation.bytes;
27
+ v2InjectedSummaryBytes = Buffer.byteLength(truncateToBytes(summary.trim(), MEMORY_V2_SUMMARY_MAX_BYTES), "utf8");
28
+ v2NotReadyReason = validation.reason;
29
+ }
30
+ catch (error) {
31
+ const code = error?.code;
32
+ const message = error instanceof Error ? error.message : String(error);
33
+ v2NotReadyReason = `cannot read V2 memory summary${typeof code === "string" ? ` (${code})` : ""}: ${message}`;
34
+ }
35
+ if (valid && v2ConsolidatedThreads < minConsolidatedThreads) {
36
+ v2NotReadyReason = `insufficient consolidated threads: ${v2ConsolidatedThreads} < ${minConsolidatedThreads}`;
20
37
  }
21
- catch { /* Missing or unsafe summary is not ready. */ }
22
38
  return {
23
39
  v2ConsolidatedThreads,
24
40
  v2Ready: valid && v2ConsolidatedThreads >= minConsolidatedThreads,
41
+ v2NotReadyReason,
42
+ v2SummaryBytes,
43
+ v2InjectedSummaryBytes,
25
44
  minConsolidatedThreads,
26
45
  };
27
46
  }
@@ -3,7 +3,7 @@ import path from "path";
3
3
  import { currentMemoryVersion } from "./memory-version.js";
4
4
  import { memoryRoot } from "./paths.js";
5
5
  import { assertMemoryRootSafe, safeResolveMemoryPath, withRegularFileNoFollow } from "./path-guard.js";
6
- import { truncateToTokens } from "./token.js";
6
+ import { MEMORY_V2_SUMMARY_MAX_BYTES, truncateToBytes, truncateToTokens } from "./token.js";
7
7
  import { fillTemplate } from "./llm.js";
8
8
  const MEMORY_SUMMARY_TOKEN_LIMIT = 2500;
9
9
  const READ_PATH_TEMPLATE = "read_path.md";
@@ -61,7 +61,9 @@ function readMemorySummary() {
61
61
  const raw = fs.readFileSync(fd, "utf8").trim();
62
62
  if (!raw)
63
63
  return null;
64
- const truncated = truncateToTokens(raw, MEMORY_SUMMARY_TOKEN_LIMIT);
64
+ const truncated = currentMemoryVersion() === "v2"
65
+ ? truncateToBytes(raw, MEMORY_V2_SUMMARY_MAX_BYTES)
66
+ : truncateToTokens(raw, MEMORY_SUMMARY_TOKEN_LIMIT);
65
67
  cache.set(summaryPath, { content: truncated, identity });
66
68
  return truncated;
67
69
  });
@@ -23,7 +23,8 @@ decisions, or provenance; redact secrets and access-bearing URL values as
23
23
 
24
24
  Begin with `v1`, followed by `## User Profile`, `## User preferences`,
25
25
  `## General Tips`, and `## What's in Memory`; keep the complete result
26
- comfortably under 10,000 UTF-8 bytes. Use judgment to preserve substantive older
26
+ comfortably under 10,000 UTF-8 bytes, aiming for at most 9,000 bytes to leave
27
+ headroom. Use judgment to preserve substantive older
27
28
  context and give recent, consequential work richer direct routes without
28
29
  obscuring actionable preferences or status.
29
30
 
@@ -1,4 +1,5 @@
1
1
  export declare const TOKEN_ESTIMATE_CHARS_PER_TOKEN = 4;
2
+ export declare const MEMORY_V2_SUMMARY_MAX_BYTES = 9999;
2
3
  export declare function estimateTokens(input: string): number;
3
4
  /**
4
5
  * Middle truncation, like codex truncate_with_head_and_tail: keep the head
package/dist/src/token.js CHANGED
@@ -1,4 +1,6 @@
1
1
  export const TOKEN_ESTIMATE_CHARS_PER_TOKEN = 4;
2
+ // V2's injected summary stays strictly below Codex's 10,000-byte artifact target.
3
+ export const MEMORY_V2_SUMMARY_MAX_BYTES = 9_999;
2
4
  export function estimateTokens(input) {
3
5
  return Math.max(0, Math.round(input.length / TOKEN_ESTIMATE_CHARS_PER_TOKEN));
4
6
  }
@@ -15,6 +15,11 @@ export interface MemoryStatus {
15
15
  dualWrite: boolean;
16
16
  v2ConsolidatedThreads: number;
17
17
  v2Ready: boolean;
18
+ /** Readiness diagnostics; optional for older servers. Null reason means ready. */
19
+ v2NotReadyReason?: string | null;
20
+ v2SummaryBytes?: number | null;
21
+ /** Bounded summary payload, excluding read-path instructions; optional for older servers. */
22
+ v2InjectedSummaryBytes?: number | null;
18
23
  minConsolidatedThreads: number;
19
24
  pipelines: {
20
25
  version: "v1" | "v2";
@@ -90,6 +95,18 @@ export declare const MemoryStatusRpc: {
90
95
  readonly v2Ready: {
91
96
  readonly type: "boolean";
92
97
  };
98
+ readonly v2NotReadyReason: {
99
+ readonly type: readonly ["string", "null"];
100
+ };
101
+ readonly v2SummaryBytes: {
102
+ readonly type: readonly ["integer", "null"];
103
+ readonly minimum: 0;
104
+ };
105
+ readonly v2InjectedSummaryBytes: {
106
+ readonly type: readonly ["integer", "null"];
107
+ readonly minimum: 0;
108
+ readonly maximum: 9999;
109
+ };
93
110
  readonly minConsolidatedThreads: {
94
111
  readonly type: "integer";
95
112
  readonly minimum: 1;
@@ -48,6 +48,9 @@ export const MemoryStatusRpc = {
48
48
  dualWrite: { type: "boolean" },
49
49
  v2ConsolidatedThreads: { type: "integer", minimum: 0 },
50
50
  v2Ready: { type: "boolean" },
51
+ v2NotReadyReason: { type: ["string", "null"] },
52
+ v2SummaryBytes: { type: ["integer", "null"], minimum: 0 },
53
+ v2InjectedSummaryBytes: { type: ["integer", "null"], minimum: 0, maximum: 9999 },
51
54
  minConsolidatedThreads: { type: "integer", minimum: 1, maximum: 4096 },
52
55
  useMemories: { type: "boolean" },
53
56
  pipelines: {
@@ -174,6 +177,15 @@ export function isMemoryStatus(value) {
174
177
  }
175
178
  if (!Number.isInteger(value.v2ConsolidatedThreads) || value.v2ConsolidatedThreads < 0)
176
179
  return false;
180
+ if (value.v2NotReadyReason !== undefined && value.v2NotReadyReason !== null && typeof value.v2NotReadyReason !== "string")
181
+ return false;
182
+ for (const key of ["v2SummaryBytes", "v2InjectedSummaryBytes"]) {
183
+ if (value[key] !== undefined && value[key] !== null &&
184
+ (!Number.isInteger(value[key]) || value[key] < 0))
185
+ return false;
186
+ }
187
+ if (typeof value.v2InjectedSummaryBytes === "number" && value.v2InjectedSummaryBytes > 9999)
188
+ return false;
177
189
  if (!Number.isInteger(value.minConsolidatedThreads) || value.minConsolidatedThreads < 1 || value.minConsolidatedThreads > 4096)
178
190
  return false;
179
191
  if (!Array.isArray(value.pipelines) || !value.pipelines.every((pipeline) => isRecord(pipeline) && (pipeline.version === "v1" || pipeline.version === "v2")
@@ -56,6 +56,9 @@ var MemoryStatusRpc = {
56
56
  dualWrite: { type: "boolean" },
57
57
  v2ConsolidatedThreads: { type: "integer", minimum: 0 },
58
58
  v2Ready: { type: "boolean" },
59
+ v2NotReadyReason: { type: ["string", "null"] },
60
+ v2SummaryBytes: { type: ["integer", "null"], minimum: 0 },
61
+ v2InjectedSummaryBytes: { type: ["integer", "null"], minimum: 0, maximum: 9999 },
59
62
  minConsolidatedThreads: { type: "integer", minimum: 1, maximum: 4096 },
60
63
  useMemories: { type: "boolean" },
61
64
  pipelines: {
@@ -182,6 +185,14 @@ function isMemoryStatus(value) {
182
185
  }
183
186
  if (!Number.isInteger(value.v2ConsolidatedThreads) || value.v2ConsolidatedThreads < 0)
184
187
  return false;
188
+ if (value.v2NotReadyReason !== undefined && value.v2NotReadyReason !== null && typeof value.v2NotReadyReason !== "string")
189
+ return false;
190
+ for (const key of ["v2SummaryBytes", "v2InjectedSummaryBytes"]) {
191
+ if (value[key] !== undefined && value[key] !== null && (!Number.isInteger(value[key]) || value[key] < 0))
192
+ return false;
193
+ }
194
+ if (typeof value.v2InjectedSummaryBytes === "number" && value.v2InjectedSummaryBytes > 9999)
195
+ return false;
185
196
  if (!Number.isInteger(value.minConsolidatedThreads) || value.minConsolidatedThreads < 1 || value.minConsolidatedThreads > 4096)
186
197
  return false;
187
198
  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]))))
@@ -378,7 +389,11 @@ function pipelineRows(s, now) {
378
389
  label: `${version} consolidation`,
379
390
  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
391
  tone: pipeline.lastError ? "warn" : "muted"
381
- }];
392
+ }, ...pipeline.lastError ? [{
393
+ label: `${version} last error`,
394
+ value: pipeline.lastError,
395
+ tone: "warn"
396
+ }] : []];
382
397
  });
383
398
  }
384
399
  function statusRows(s, now) {
@@ -393,9 +408,17 @@ function statusRows(s, now) {
393
408
  value: s.dualWrite ? "v1 + v2" : s.version
394
409
  }, {
395
410
  label: "V2 readiness",
396
- value: `${s.v2Ready ? "Ready" : "Warming"} \xB7 ${s.v2ConsolidatedThreads}/${s.minConsolidatedThreads} sessions`,
411
+ value: `${s.v2Ready ? "Ready" : "Not ready"} \xB7 ${s.v2ConsolidatedThreads}/${s.minConsolidatedThreads} sessions`,
397
412
  tone: s.v2Ready ? "ok" : "muted"
398
- }, ...pipelineRows(s, now), {
413
+ }, ...s.v2NotReadyReason ? [{
414
+ label: "V2 not ready",
415
+ value: s.v2NotReadyReason,
416
+ tone: "muted"
417
+ }] : [], ...s.v2SummaryBytes !== undefined ? [{
418
+ label: "V2 summary",
419
+ value: s.v2SummaryBytes === null ? "Unreadable" : s.v2InjectedSummaryBytes != null ? `${s.v2SummaryBytes} bytes on disk \xB7 ${s.v2InjectedSummaryBytes} injected${s.v2SummaryBytes >= 1e4 ? " (capped)" : ""}` : `${s.v2SummaryBytes} UTF-8 bytes`,
420
+ tone: "muted"
421
+ }] : [], ...pipelineRows(s, now), {
399
422
  label: "Use memories",
400
423
  value: s.useMemories ? "On" : "Off",
401
424
  tone: s.useMemories ? "ok" : "muted"
@@ -4,6 +4,12 @@ import { type WorkspaceDiff } from "./git-baseline.js";
4
4
  /** Mirrors codex `remove_memory_symlinks` (workspace.rs): unlink every symlink in the tree, never follow. */
5
5
  export declare function removeMemorySymlinks(root?: string): number;
6
6
  export declare function ensureLayout(): void;
7
+ /** Codex format checks with content-free diagnostics; V2 size is bounded at injection. */
8
+ export declare function validateV2Summary(summary: string): {
9
+ ok: boolean;
10
+ bytes: number;
11
+ reason: string | null;
12
+ };
7
13
  export declare function isValidV2Summary(summary: string): boolean;
8
14
  export declare function validateConsolidationArtifacts(root?: string): {
9
15
  ok: true;
@@ -93,13 +93,21 @@ export function ensureLayout() {
93
93
  * Invalid artifacts force a consolidator re-run and block baseline reset.
94
94
  */
95
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;
96
+ /** Codex format checks with content-free diagnostics; V2 size is bounded at injection. */
97
+ export function validateV2Summary(summary) {
98
+ const bytes = Buffer.byteLength(summary, "utf8");
99
+ if (summary.split(/\r?\n/, 1)[0] !== "v1") {
100
+ const hint = summary.startsWith("\uFEFF") ? " (UTF-8 BOM detected)" : "";
101
+ return { ok: false, bytes, reason: `summary must start with the exact line 'v1'${hint}` };
102
+ }
101
103
  const lines = summary.split(/\r?\n/).map((line) => line.trim());
102
- return V2_SUMMARY_HEADINGS.every((heading) => lines.includes(heading));
104
+ const missing = V2_SUMMARY_HEADINGS.filter((heading) => !lines.includes(heading));
105
+ return missing.length
106
+ ? { ok: false, bytes, reason: `missing required headings: ${missing.join(", ")}` }
107
+ : { ok: true, bytes, reason: null };
108
+ }
109
+ export function isValidV2Summary(summary) {
110
+ return validateV2Summary(summary).ok;
103
111
  }
104
112
  export function validateConsolidationArtifacts(root = memoryRoot()) {
105
113
  return validateConsolidationArtifactsForVersion(root, "v1");
@@ -141,8 +149,10 @@ export function validateConsolidationArtifactsForVersion(root = memoryRoot(), ve
141
149
  if (first !== "v1") {
142
150
  return { ok: false, reason: `memory summary artifact does not start with v1: ${summaryPath}` };
143
151
  }
144
- if (version === "v2" && !isValidV2Summary(summary)) {
145
- return { ok: false, reason: "invalid v2 memory summary" };
152
+ if (version === "v2") {
153
+ const validation = validateV2Summary(summary);
154
+ if (!validation.ok)
155
+ return { ok: false, reason: `invalid v2 memory summary: ${validation.reason}` };
146
156
  }
147
157
  return { ok: true };
148
158
  }
@@ -272,7 +272,7 @@ function phase2NoteLines(phase2) {
272
272
  export const memory_inspect = tool({
273
273
  description: "Inspect the current memory state. Returns: stage1_outputs count, stage-1 job status " +
274
274
  "breakdown, failure classes (backoff / provider_capacity / other_exhausted), recent errors, " +
275
- "Phase 2 job status (including last error / retry time), " +
275
+ "Phase 2 job status (including per-writer last error / retry time), V2 readiness failure reason and UTF-8 summary bytes, " +
276
276
  "last discovery outcome, pipeline diagnostics, memory_summary token estimate " +
277
277
  "(on-disk; injection caps at ~2500), a listing of the memories directory, the " +
278
278
  "effective plugin options, and any configuration warnings. Use it to verify " +
@@ -379,8 +379,15 @@ function inspect(args, ctx) {
379
379
  `read_version: ${peekSessionMemoryVersion(ctx?.sessionID)}`,
380
380
  `dual_write: ${pluginOptions.dual_write}`,
381
381
  `v2_ready: ${migration.v2Ready}`,
382
+ `v2_not_ready_reason: ${migration.v2NotReadyReason ?? "none"}`,
383
+ `v2_summary_bytes: ${migration.v2SummaryBytes ?? "unknown"} (UTF-8 on disk)`,
384
+ `v2_injected_summary_bytes: ${migration.v2InjectedSummaryBytes ?? "unknown"} (UTF-8; capped under 10000, including truncation marker)`,
382
385
  `v2_consolidated_threads: ${migration.v2ConsolidatedThreads} (minimum ${migration.minConsolidatedThreads})`,
383
- ...pipelines.map((p) => `pipeline_${p.version}: outputs=${p.stage1Count}, phase2=${p.phase2?.status ?? "none"}, root=${p.root}`),
386
+ ...pipelines.flatMap((p) => [
387
+ `pipeline_${p.version}: outputs=${p.stage1Count}, phase2=${p.phase2?.status ?? "none"}, root=${p.root}`,
388
+ ` pipeline_${p.version}_phase2_last_error: ${p.phase2?.last_error ?? "none"}`,
389
+ ` pipeline_${p.version}_phase2_retry_at: ${fmtUnixSec(p.phase2?.retry_at ?? null)}`,
390
+ ]),
384
391
  ...stage1Lines,
385
392
  ...phase2Lines,
386
393
  discoveryLine,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-codex-memory",
3
- "version": "0.9.7",
3
+ "version": "0.9.9",
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",