opencode-codex-memory 0.7.6 → 0.8.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.
- package/README.md +51 -8
- package/dist/opencode.json +2 -2
- package/dist/src/capture.d.ts +5 -0
- package/dist/src/capture.js +8 -0
- package/dist/src/codex-interop.js +5 -0
- package/dist/src/db.d.ts +7 -1
- package/dist/src/db.js +38 -11
- package/dist/src/diagnostics.js +5 -1
- package/dist/src/host-client.d.ts +5 -0
- package/dist/src/index.d.ts +12 -4
- package/dist/src/index.js +71 -66
- package/dist/src/lifecycle.js +14 -9
- package/dist/src/llm.d.ts +3 -2
- package/dist/src/llm.js +47 -11
- package/dist/src/local-session-times.d.ts +6 -0
- package/dist/src/local-session-times.js +59 -0
- package/dist/src/memory-version.d.ts +5 -0
- package/dist/src/memory-version.js +16 -0
- package/dist/src/migration.d.ts +24 -0
- package/dist/src/migration.js +37 -0
- package/dist/src/options.d.ts +10 -0
- package/dist/src/options.js +3 -0
- package/dist/src/paths.d.ts +9 -3
- package/dist/src/paths.js +22 -8
- package/dist/src/phase1.js +16 -2
- package/dist/src/phase2.js +15 -9
- package/dist/src/pipeline.d.ts +3 -0
- package/dist/src/pipeline.js +74 -0
- package/dist/src/ratelimit.js +9 -4
- package/dist/src/rollout-input.d.ts +3 -2
- package/dist/src/rollout-input.js +26 -17
- package/dist/src/session-version.d.ts +9 -0
- package/dist/src/session-version.js +27 -0
- package/dist/src/source.js +21 -6
- package/dist/src/store.d.ts +19 -3
- package/dist/src/store.js +121 -38
- package/dist/src/templates/consolidation_v2.md +54 -0
- package/dist/src/templates/read_path_v2.md +58 -0
- package/dist/src/templates/stage_one_input_v2.md +21 -0
- package/dist/src/templates/stage_one_system_v2.md +53 -0
- package/dist/src/token.d.ts +2 -0
- package/dist/src/token.js +16 -0
- package/dist/src/v2/agents.d.ts +4 -2
- package/dist/src/v2/agents.js +15 -7
- package/dist/src/v2/citation-overlay.d.ts +1 -1
- package/dist/src/v2/citation-overlay.js +27 -4
- package/dist/src/v2/plugin.js +27 -74
- package/dist/src/v2/shim.js +20 -9
- package/dist/src/v2/status-rpc.d.ts +70 -1
- package/dist/src/v2/status-rpc.js +41 -2
- package/dist/src/v2/status.d.ts +1 -1
- package/dist/src/v2/status.js +35 -9
- package/dist/src/v2/tui.js +57 -2
- package/dist/src/workspace.d.ts +8 -6
- package/dist/src/workspace.js +31 -11
- package/dist/tools/control.d.ts +6 -2
- package/dist/tools/control.js +209 -155
- package/dist/tools/memory.js +11 -1
- package/opencode.json +2 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -53,7 +53,7 @@ If you want the mental model — learning, remembering, forgetting — see
|
|
|
53
53
|
|
|
54
54
|
```json
|
|
55
55
|
{
|
|
56
|
-
"plugin": ["opencode-codex-memory@0.
|
|
56
|
+
"plugin": ["opencode-codex-memory@0.8.0"]
|
|
57
57
|
}
|
|
58
58
|
```
|
|
59
59
|
|
|
@@ -73,7 +73,7 @@ V2 plugin syntax:
|
|
|
73
73
|
|
|
74
74
|
```jsonc
|
|
75
75
|
{
|
|
76
|
-
"plugins": [{ "package": "opencode-codex-memory@0.
|
|
76
|
+
"plugins": [{ "package": "opencode-codex-memory@0.8.0" }],
|
|
77
77
|
}
|
|
78
78
|
```
|
|
79
79
|
|
|
@@ -189,6 +189,8 @@ Codex's `[memories]` config so the two stay easy to compare:
|
|
|
189
189
|
| Option | Default | Meaning |
|
|
190
190
|
|---|---|---|
|
|
191
191
|
| `generate_memories` | `true` | Turn the background learning pipeline on/off |
|
|
192
|
+
| `version` | `"v1"` | Read version for new sessions, and the sole writer when dual-write is off. `"v2"` is summary-only, with recaps in isolated `memories_v2/` and no `MEMORY.md`. |
|
|
193
|
+
| `dual_write` | `false` | Run both learning pipelines independently while reading the selected version. Enables V2 warmup before an explicit cutover. |
|
|
192
194
|
| `use_memories` | `true` | Inject the memory summary into the system prompt |
|
|
193
195
|
| `dedicated_tools` | `true` | Expose the `memory_read`/`memory_search`/`memory_list`/`memory_add_note` tools |
|
|
194
196
|
| `disable_on_external_context` | `false` | Exclude sessions that used web/MCP tools from memory |
|
|
@@ -208,7 +210,7 @@ To set options, turn the plugin entry into a `[name, options]` pair:
|
|
|
208
210
|
```json
|
|
209
211
|
{
|
|
210
212
|
"plugin": [
|
|
211
|
-
["opencode-codex-memory@0.
|
|
213
|
+
["opencode-codex-memory@0.8.0", { "disable_on_external_context": true, "min_rollout_idle_hours": 2 }]
|
|
212
214
|
]
|
|
213
215
|
}
|
|
214
216
|
```
|
|
@@ -263,6 +265,47 @@ nearest OpenCode variant on `none < minimal < low < medium < high < xhigh < max`
|
|
|
263
265
|
> maintenance tools (`memory_reset`, `memory_inspect`, `memory_mode`) stay
|
|
264
266
|
> available either way.
|
|
265
267
|
|
|
268
|
+
### Migrating from memory V1 to V2
|
|
269
|
+
|
|
270
|
+
Memory versions are independent of OpenCode host versions: both work on
|
|
271
|
+
OpenCode 1.x and 2.x. V1 remains the default. See the
|
|
272
|
+
[conceptual comparison](docs/how-ai-memory-works.md#two-versions-v1-and-v2)
|
|
273
|
+
for the different learning contracts.
|
|
274
|
+
|
|
275
|
+
1. Set these **plugin options** and restart OpenCode's server:
|
|
276
|
+
|
|
277
|
+
```json
|
|
278
|
+
{ "version": "v1", "dual_write": true }
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
V1 continues serving memory. Both pipelines independently extract eligible
|
|
282
|
+
conversations and consolidate into their own workspaces. This adds model
|
|
283
|
+
calls for the second pipeline; it does not copy or convert V1 artifacts.
|
|
284
|
+
|
|
285
|
+
2. Check `memory_inspect`, or `/memory` on OpenCode 2. `v2_ready` becomes true
|
|
286
|
+
when V2 has a valid summary and one successful consolidation has consumed
|
|
287
|
+
at least **20 distinct sessions**. The count is a high-water mark, not a
|
|
288
|
+
lifetime sum, so repeated consolidation of one session cannot make V2 ready.
|
|
289
|
+
`min_consolidated_threads` on inspect (RPC: `minConsolidatedThreads`) can
|
|
290
|
+
override the reporting threshold from 1 to 4096; it does not change config
|
|
291
|
+
or switch versions. Readiness is a warmup signal, not a quality guarantee.
|
|
292
|
+
|
|
293
|
+
3. When ready, set `version: "v2"` and restart the server. New sessions use V2.
|
|
294
|
+
Existing sessions keep the version selected on their first memory use,
|
|
295
|
+
including retrieval tools, explicit notes, and citation accounting across
|
|
296
|
+
server restarts. Start a new session to try the new read path.
|
|
297
|
+
|
|
298
|
+
4. Keep `dual_write: true` while evaluating V2, then set it to `false` when you
|
|
299
|
+
want only V2 learning. To roll back, select `version: "v1"` and start a new
|
|
300
|
+
session. If dual-write was off, V1 will not contain the intervening learning.
|
|
301
|
+
|
|
302
|
+
There is no automatic cutover. An explicit "remember this" note goes to the
|
|
303
|
+
requesting session's selected workspace; the other writer learns from eligible
|
|
304
|
+
conversation history. Disabled/polluted session flags are shared. Session
|
|
305
|
+
deletion removes extracted rows from both stores and queues forgetting;
|
|
306
|
+
`memory_reset` clears both stores and workspaces, preserving session modes and
|
|
307
|
+
read-version stamps. Inactive stores resume queued consolidation when enabled.
|
|
308
|
+
|
|
266
309
|
### Relocating memory (sandbox mounts)
|
|
267
310
|
|
|
268
311
|
First match wins:
|
|
@@ -280,7 +323,7 @@ dedicated directory:
|
|
|
280
323
|
```json
|
|
281
324
|
{
|
|
282
325
|
"plugin": [
|
|
283
|
-
["opencode-codex-memory@0.
|
|
326
|
+
["opencode-codex-memory@0.8.0", { "home": "/path/to/opencode-memory" }]
|
|
284
327
|
]
|
|
285
328
|
}
|
|
286
329
|
```
|
|
@@ -290,7 +333,7 @@ OpenCode 2:
|
|
|
290
333
|
```jsonc
|
|
291
334
|
{
|
|
292
335
|
"plugins": [
|
|
293
|
-
{ "package": "opencode-codex-memory@0.
|
|
336
|
+
{ "package": "opencode-codex-memory@0.8.0", "options": { "home": "/path/to/opencode-memory" } }
|
|
294
337
|
]
|
|
295
338
|
}
|
|
296
339
|
```
|
|
@@ -325,7 +368,7 @@ Off by default; no changes to Codex's own config are required.
|
|
|
325
368
|
{
|
|
326
369
|
"plugin": [
|
|
327
370
|
[
|
|
328
|
-
"opencode-codex-memory@0.
|
|
371
|
+
"opencode-codex-memory@0.8.0",
|
|
329
372
|
{ "codex_interop": { "import": true, "export": true } }
|
|
330
373
|
]
|
|
331
374
|
]
|
|
@@ -382,7 +425,7 @@ from the project memories Claude already keeps on your machine. **One-way only**
|
|
|
382
425
|
```json
|
|
383
426
|
{
|
|
384
427
|
"plugin": [
|
|
385
|
-
["opencode-codex-memory@0.
|
|
428
|
+
["opencode-codex-memory@0.8.0", { "claude_import": { "enabled": true } }]
|
|
386
429
|
]
|
|
387
430
|
}
|
|
388
431
|
```
|
|
@@ -409,7 +452,7 @@ Claude names each project with an opaque id (a folder under
|
|
|
409
452
|
{
|
|
410
453
|
"plugin": [
|
|
411
454
|
[
|
|
412
|
-
"opencode-codex-memory@0.
|
|
455
|
+
"opencode-codex-memory@0.8.0",
|
|
413
456
|
{
|
|
414
457
|
"claude_import": {
|
|
415
458
|
"enabled": true,
|
package/dist/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.
|
|
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.
|
|
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/dist/src/capture.d.ts
CHANGED
|
@@ -11,6 +11,11 @@ export interface TranscriptMessage {
|
|
|
11
11
|
type: string;
|
|
12
12
|
role?: string;
|
|
13
13
|
text?: string;
|
|
14
|
+
/** Native question-tool replies are human evidence, paired with the question. */
|
|
15
|
+
userReply?: {
|
|
16
|
+
question: string;
|
|
17
|
+
answer: string;
|
|
18
|
+
};
|
|
14
19
|
}
|
|
15
20
|
/**
|
|
16
21
|
* Transcript loading uses the official API — the same surface opencode's own
|
package/dist/src/capture.js
CHANGED
|
@@ -97,10 +97,18 @@ export async function loadTranscript(sessionId) {
|
|
|
97
97
|
for (const row of rows) {
|
|
98
98
|
const role = row?.info?.role;
|
|
99
99
|
for (const part of row?.parts ?? []) {
|
|
100
|
+
const question = part;
|
|
101
|
+
const answer = question?.state?.output;
|
|
102
|
+
const userReply = question?.tool === "question" && question.ignored !== true
|
|
103
|
+
&& typeof answer === "string" && answer.startsWith("User has answered your questions:")
|
|
104
|
+
&& /"="(?!Unanswered")[^"]+"/.test(answer)
|
|
105
|
+
? { question: JSON.stringify(question.state?.input ?? {}), answer }
|
|
106
|
+
: undefined;
|
|
100
107
|
out.push({
|
|
101
108
|
type: hostPartType(part),
|
|
102
109
|
role,
|
|
103
110
|
text: extractText(part),
|
|
111
|
+
...(userReply ? { userReply } : {}),
|
|
104
112
|
});
|
|
105
113
|
}
|
|
106
114
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import fs from "fs";
|
|
2
2
|
import path from "path";
|
|
3
3
|
import os from "os";
|
|
4
|
+
import { currentMemoryVersion } from "./memory-version.js";
|
|
4
5
|
import { memoryRoot } from "./paths.js";
|
|
5
6
|
import { readRegularFileNoFollow, safeResolveUnderRoot, writeRegularFileNoFollow } from "./path-guard.js";
|
|
6
7
|
/**
|
|
@@ -189,6 +190,10 @@ function overlaps(a, b) {
|
|
|
189
190
|
export function resolveCodexInterop(opts) {
|
|
190
191
|
if (!opts.import && !opts.export)
|
|
191
192
|
return null;
|
|
193
|
+
if (currentMemoryVersion() === "v2") {
|
|
194
|
+
console.warn("[opencode-codex-memory] codex_interop disabled: handbook exchange is v1-only while version=v2");
|
|
195
|
+
return null;
|
|
196
|
+
}
|
|
192
197
|
// codex find_codex_home ignores an EMPTY env var (home-dir/src/lib.rs);
|
|
193
198
|
// without the filter "" would resolve to a cwd-relative "memories" path.
|
|
194
199
|
const envHome = process.env[CODEX_HOME_ENV];
|
package/dist/src/db.d.ts
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
1
|
import { Database } from "bun:sqlite";
|
|
2
|
-
|
|
2
|
+
import type { MemoryVersion } from "./options.js";
|
|
3
|
+
/** Both versioned handles stay open while their pipelines run concurrently. */
|
|
4
|
+
export declare function openDb(version?: MemoryVersion): Database;
|
|
5
|
+
/** One-shot connection for reset across versioned files. Caller must close. */
|
|
6
|
+
export declare function openTransientDb(dbPath: string): Database;
|
|
7
|
+
/** Always memory.db — shared session_meta catalog across versions. */
|
|
8
|
+
export declare function openSessionMetaDb(): Database;
|
|
3
9
|
export declare function closeDb(): void;
|
package/dist/src/db.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Database } from "bun:sqlite";
|
|
2
2
|
import fs from "fs";
|
|
3
3
|
import path from "path";
|
|
4
|
-
import { memoryDbPath } from "./paths.js";
|
|
4
|
+
import { memoryDbPath, sessionMetaDbPath } from "./paths.js";
|
|
5
5
|
const SCHEMA_V1 = [
|
|
6
6
|
`CREATE TABLE IF NOT EXISTS memory_stage1_outputs (
|
|
7
7
|
session_id TEXT PRIMARY KEY,
|
|
@@ -43,11 +43,8 @@ const SCHEMA_V1 = [
|
|
|
43
43
|
updated_at INTEGER NOT NULL
|
|
44
44
|
)`,
|
|
45
45
|
];
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
if (dbInstance)
|
|
49
|
-
return dbInstance;
|
|
50
|
-
const dbPath = memoryDbPath();
|
|
46
|
+
const connections = new Map();
|
|
47
|
+
function openSqlite(dbPath) {
|
|
51
48
|
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
|
52
49
|
const db = new Database(dbPath, { create: true, readwrite: true, strict: false });
|
|
53
50
|
try {
|
|
@@ -58,7 +55,6 @@ export function openDb() {
|
|
|
58
55
|
db.run("PRAGMA busy_timeout=5000");
|
|
59
56
|
db.run("PRAGMA auto_vacuum=INCREMENTAL");
|
|
60
57
|
runMigrations(db);
|
|
61
|
-
dbInstance = db;
|
|
62
58
|
return db;
|
|
63
59
|
}
|
|
64
60
|
catch (err) {
|
|
@@ -66,6 +62,26 @@ export function openDb() {
|
|
|
66
62
|
throw err;
|
|
67
63
|
}
|
|
68
64
|
}
|
|
65
|
+
function connection(dbPath) {
|
|
66
|
+
let db = connections.get(dbPath);
|
|
67
|
+
if (!db) {
|
|
68
|
+
db = openSqlite(dbPath);
|
|
69
|
+
connections.set(dbPath, db);
|
|
70
|
+
}
|
|
71
|
+
return db;
|
|
72
|
+
}
|
|
73
|
+
/** Both versioned handles stay open while their pipelines run concurrently. */
|
|
74
|
+
export function openDb(version) {
|
|
75
|
+
return connection(memoryDbPath(version));
|
|
76
|
+
}
|
|
77
|
+
/** One-shot connection for reset across versioned files. Caller must close. */
|
|
78
|
+
export function openTransientDb(dbPath) {
|
|
79
|
+
return openSqlite(dbPath);
|
|
80
|
+
}
|
|
81
|
+
/** Always memory.db — shared session_meta catalog across versions. */
|
|
82
|
+
export function openSessionMetaDb() {
|
|
83
|
+
return connection(sessionMetaDbPath());
|
|
84
|
+
}
|
|
69
85
|
function runMigrations(db) {
|
|
70
86
|
db.run(`CREATE TABLE IF NOT EXISTS schema_version (
|
|
71
87
|
version INTEGER NOT NULL,
|
|
@@ -91,11 +107,22 @@ function runMigrations(db) {
|
|
|
91
107
|
)`);
|
|
92
108
|
db.prepare("INSERT INTO schema_version (version, applied_at) VALUES (?, ?)").run(2, Date.now());
|
|
93
109
|
}
|
|
110
|
+
if (currentVersion < 3) {
|
|
111
|
+
db.run(`CREATE TABLE consolidation_progress (
|
|
112
|
+
singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
|
|
113
|
+
max_thread_count INTEGER NOT NULL DEFAULT 0
|
|
114
|
+
)`);
|
|
115
|
+
db.run("INSERT INTO consolidation_progress (singleton, max_thread_count) VALUES (1, 0)");
|
|
116
|
+
db.run(`CREATE TABLE memory_session_versions (
|
|
117
|
+
session_id TEXT PRIMARY KEY,
|
|
118
|
+
version TEXT NOT NULL CHECK (version IN ('v1', 'v2'))
|
|
119
|
+
)`);
|
|
120
|
+
db.prepare("INSERT INTO schema_version (version, applied_at) VALUES (?, ?)").run(3, Date.now());
|
|
121
|
+
}
|
|
94
122
|
}).immediate();
|
|
95
123
|
}
|
|
96
124
|
export function closeDb() {
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
}
|
|
125
|
+
for (const db of connections.values())
|
|
126
|
+
db.close();
|
|
127
|
+
connections.clear();
|
|
101
128
|
}
|
package/dist/src/diagnostics.js
CHANGED
|
@@ -13,11 +13,15 @@ export function recordDiagnostic(level, kind, message) {
|
|
|
13
13
|
events.shift();
|
|
14
14
|
}
|
|
15
15
|
export function recordDiscoveryStatus(status) {
|
|
16
|
+
const prev = discovery;
|
|
16
17
|
discovery = { ...status, at: Date.now() };
|
|
17
18
|
if (!status.ok) {
|
|
18
19
|
recordDiagnostic("warn", "discovery", status.error ?? "session discovery failed");
|
|
20
|
+
return;
|
|
19
21
|
}
|
|
20
|
-
|
|
22
|
+
// Same count every 30s cache hit is not a pipeline event — only log
|
|
23
|
+
// changes (or the first success) so inspect is not 12× "listed 1".
|
|
24
|
+
if (!prev || !prev.ok || prev.count !== status.count) {
|
|
21
25
|
recordDiagnostic("info", "discovery", `listed ${status.count} session(s)`);
|
|
22
26
|
}
|
|
23
27
|
}
|
|
@@ -45,6 +45,11 @@ export declare function withHostTimeout<T>(promise: Promise<T>, ms: number, labe
|
|
|
45
45
|
export interface SessionCreateBody {
|
|
46
46
|
title?: string;
|
|
47
47
|
metadata?: Record<string, unknown>;
|
|
48
|
+
permission?: {
|
|
49
|
+
permission: string;
|
|
50
|
+
pattern: string;
|
|
51
|
+
action: "allow" | "deny";
|
|
52
|
+
}[];
|
|
48
53
|
}
|
|
49
54
|
/** GET /provider. V1 SDK types omit model.variants; parse the payload loosely. */
|
|
50
55
|
export declare function hostProviderList(client: PluginInput["client"] | null | undefined, opts?: {
|
package/dist/src/index.d.ts
CHANGED
|
@@ -101,8 +101,12 @@ declare const _default: {
|
|
|
101
101
|
};
|
|
102
102
|
memory_inspect: {
|
|
103
103
|
description: string;
|
|
104
|
-
args: {
|
|
105
|
-
|
|
104
|
+
args: {
|
|
105
|
+
min_consolidated_threads: import("zod").ZodOptional<import("zod").ZodNumber>;
|
|
106
|
+
};
|
|
107
|
+
execute(args: {
|
|
108
|
+
min_consolidated_threads?: number | undefined;
|
|
109
|
+
}, context: import("@opencode-ai/plugin").ToolContext): Promise<import("@opencode-ai/plugin").ToolResult>;
|
|
106
110
|
};
|
|
107
111
|
memory_mode: {
|
|
108
112
|
description: string;
|
|
@@ -131,8 +135,12 @@ declare const _default: {
|
|
|
131
135
|
};
|
|
132
136
|
memory_inspect: {
|
|
133
137
|
description: string;
|
|
134
|
-
args: {
|
|
135
|
-
|
|
138
|
+
args: {
|
|
139
|
+
min_consolidated_threads: import("zod").ZodOptional<import("zod").ZodNumber>;
|
|
140
|
+
};
|
|
141
|
+
execute(args: {
|
|
142
|
+
min_consolidated_threads?: number | undefined;
|
|
143
|
+
}, context: import("@opencode-ai/plugin").ToolContext): Promise<import("@opencode-ai/plugin").ToolResult>;
|
|
136
144
|
};
|
|
137
145
|
memory_mode: {
|
|
138
146
|
description: string;
|
package/dist/src/index.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
import { ensureMemoryLayout, buildMemorySystemPrompt, invalidateCache } from "./source.js";
|
|
2
|
-
import { memoryRoot,
|
|
2
|
+
import { memoryRoot, dataRoot, setConfiguredHome, resolveHomePath } from "./paths.js";
|
|
3
3
|
import { closeDb } from "./db.js";
|
|
4
4
|
import { stripCitations, extractCitedSessionIds, hasCitationMarkup } from "./citation.js";
|
|
5
5
|
import { memory_read, memory_search, memory_list, memory_add_note } from "../tools/memory.js";
|
|
6
6
|
import { memory_reset, memory_inspect, memory_mode } from "../tools/control.js";
|
|
7
7
|
import { MemoryStore } from "./store.js";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
8
|
+
import { runMemoryPipeline, runMemoryConsolidation } from "./pipeline.js";
|
|
9
|
+
import { writeMemoryVersions } from "./memory-version.js";
|
|
10
|
+
import { sessionMemoryVersion, withSessionMemoryVersion } from "./session-version.js";
|
|
11
|
+
import { existingMemoryStores } from "./store.js";
|
|
10
12
|
import { setPluginInput, cleanupOldSubSessions, isMemorySubSession, abortActiveSubSessions } from "./llm.js";
|
|
11
13
|
import { pluginOptions, recordConfigWarning, clearConfigWarnings, resetPluginOptions } from "./options.js";
|
|
12
|
-
import { beginPluginShutdown,
|
|
14
|
+
import { beginPluginShutdown, resetPluginLifecycle } from "./lifecycle.js";
|
|
13
15
|
import { hostMcpStatus } from "./host-client.js";
|
|
14
|
-
import { recordDiagnostic } from "./diagnostics.js";
|
|
15
16
|
import { loadBundledAgentDefinitions, recordAgentConfig, resetAgentHealth } from "./agent-health.js";
|
|
16
17
|
import path from "path";
|
|
17
|
-
let phase1InFlight = false;
|
|
18
18
|
let pluginClient = null;
|
|
19
19
|
const backgroundTasks = new Set();
|
|
20
20
|
function trackBackgroundTask(task) {
|
|
@@ -110,14 +110,18 @@ export function shouldHandleIdle(sessionId, now = Date.now()) {
|
|
|
110
110
|
lruSet(recentIdle, sessionId, deduped ? last : now, MAX_TRACKED_IDLE);
|
|
111
111
|
return !deduped;
|
|
112
112
|
}
|
|
113
|
-
export function handleSessionDeleted(sessionId, store
|
|
113
|
+
export function handleSessionDeleted(sessionId, store,
|
|
114
114
|
// With generation off the memorize agent is not injected, so a consolidation
|
|
115
115
|
// attempt could only fail; the row deletion above still happens, and the
|
|
116
116
|
// enqueued job runs when generation is re-enabled (codex: delete only
|
|
117
117
|
// enqueues; the pipeline itself is gated elsewhere).
|
|
118
118
|
schedulePhase2 = () => { if (pluginOptions.generate_memories)
|
|
119
119
|
trackBackgroundTask(triggerPhase2()); }) {
|
|
120
|
-
|
|
120
|
+
const stores = store ? [store] : existingMemoryStores();
|
|
121
|
+
let changed = false;
|
|
122
|
+
for (const target of stores)
|
|
123
|
+
changed = target.deleteSessionMemory(sessionId) || changed;
|
|
124
|
+
if (changed)
|
|
121
125
|
schedulePhase2();
|
|
122
126
|
}
|
|
123
127
|
export default {
|
|
@@ -139,17 +143,19 @@ export default {
|
|
|
139
143
|
if (opts)
|
|
140
144
|
applyPluginOptions(opts);
|
|
141
145
|
else {
|
|
142
|
-
const previousDb =
|
|
146
|
+
const previousDb = dataRoot();
|
|
143
147
|
resetPluginOptions();
|
|
144
|
-
if (
|
|
148
|
+
if (dataRoot() !== previousDb)
|
|
145
149
|
closeDb();
|
|
146
150
|
}
|
|
147
151
|
// Finish bounded reseeding before hooks can see a surviving memory
|
|
148
152
|
// sub-session after a plugin reload.
|
|
149
153
|
await cleanupOldSubSessions();
|
|
150
154
|
try {
|
|
151
|
-
|
|
152
|
-
|
|
155
|
+
for (const store of existingMemoryStores()) {
|
|
156
|
+
if (store.releaseOrphanedPhase2Job()) {
|
|
157
|
+
console.warn(`[opencode-codex-memory] released orphaned ${store.version} consolidation lease`);
|
|
158
|
+
}
|
|
153
159
|
}
|
|
154
160
|
}
|
|
155
161
|
catch (err) {
|
|
@@ -163,6 +169,8 @@ const KNOWN_OPTION_KEYS = new Set([
|
|
|
163
169
|
"use_memories",
|
|
164
170
|
"dedicated_tools",
|
|
165
171
|
"disable_on_external_context",
|
|
172
|
+
"version",
|
|
173
|
+
"dual_write",
|
|
166
174
|
"extract_model",
|
|
167
175
|
"consolidation_model",
|
|
168
176
|
"max_raw_memories_for_consolidation",
|
|
@@ -170,6 +178,7 @@ const KNOWN_OPTION_KEYS = new Set([
|
|
|
170
178
|
"max_rollout_age_days",
|
|
171
179
|
"max_rollouts_per_startup",
|
|
172
180
|
"min_rollout_idle_hours",
|
|
181
|
+
"test",
|
|
173
182
|
"home",
|
|
174
183
|
"codex_interop",
|
|
175
184
|
"claude_import",
|
|
@@ -186,10 +195,18 @@ function clampInt(key, value, min, max, fallback) {
|
|
|
186
195
|
}
|
|
187
196
|
return Math.min(max, Math.max(min, Math.floor(value)));
|
|
188
197
|
}
|
|
198
|
+
/** Finite number, no Codex range clamp. Used only when options.test is true. */
|
|
199
|
+
function finiteNumber(key, value, fallback) {
|
|
200
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
201
|
+
recordConfigWarning(`${key} must be a finite number; using default ${fallback}`);
|
|
202
|
+
return fallback;
|
|
203
|
+
}
|
|
204
|
+
return value;
|
|
205
|
+
}
|
|
189
206
|
export function applyPluginOptions(opts) {
|
|
190
207
|
// Fresh pass per apply so memory_inspect never shows warnings for keys the
|
|
191
208
|
// caller has since fixed. server() clears too, for boots without options.
|
|
192
|
-
const previousDb =
|
|
209
|
+
const previousDb = dataRoot();
|
|
193
210
|
clearConfigWarnings();
|
|
194
211
|
resetPluginOptions();
|
|
195
212
|
const raw = opts;
|
|
@@ -201,7 +218,7 @@ export function applyPluginOptions(opts) {
|
|
|
201
218
|
recordConfigWarning(`unknown/unsupported option '${key}' ignored`);
|
|
202
219
|
}
|
|
203
220
|
}
|
|
204
|
-
for (const key of ["generate_memories", "use_memories", "dedicated_tools", "disable_on_external_context"]) {
|
|
221
|
+
for (const key of ["generate_memories", "use_memories", "dedicated_tools", "disable_on_external_context", "dual_write"]) {
|
|
205
222
|
if (!(key in raw))
|
|
206
223
|
continue;
|
|
207
224
|
if (typeof raw[key] === "boolean")
|
|
@@ -209,6 +226,13 @@ export function applyPluginOptions(opts) {
|
|
|
209
226
|
else
|
|
210
227
|
recordConfigWarning(`${key} must be a boolean; using default ${pluginOptions[key]}`);
|
|
211
228
|
}
|
|
229
|
+
// options.test: live-harness only. Skips MemoriesToml numeric clamps.
|
|
230
|
+
if ("test" in raw) {
|
|
231
|
+
if (typeof raw.test === "boolean")
|
|
232
|
+
pluginOptions.test = raw.test;
|
|
233
|
+
else
|
|
234
|
+
recordConfigWarning("test must be a boolean; using default false");
|
|
235
|
+
}
|
|
212
236
|
for (const key of ["extract_model", "consolidation_model"]) {
|
|
213
237
|
if (!(key in raw))
|
|
214
238
|
continue;
|
|
@@ -217,16 +241,33 @@ export function applyPluginOptions(opts) {
|
|
|
217
241
|
else
|
|
218
242
|
recordConfigWarning(`${key} must be a string; using the opencode model default`);
|
|
219
243
|
}
|
|
244
|
+
const testing = pluginOptions.test;
|
|
245
|
+
if ("version" in raw) {
|
|
246
|
+
if (raw.version === "v1" || raw.version === "v2")
|
|
247
|
+
pluginOptions.version = raw.version;
|
|
248
|
+
else
|
|
249
|
+
recordConfigWarning('version must be "v1" or "v2"; using default v1');
|
|
250
|
+
}
|
|
220
251
|
if ("max_raw_memories_for_consolidation" in opts)
|
|
221
|
-
pluginOptions.max_raw_memories_for_consolidation =
|
|
252
|
+
pluginOptions.max_raw_memories_for_consolidation = testing
|
|
253
|
+
? finiteNumber("max_raw_memories_for_consolidation", opts.max_raw_memories_for_consolidation, 256)
|
|
254
|
+
: clampInt("max_raw_memories_for_consolidation", opts.max_raw_memories_for_consolidation, 1, 4096, 256);
|
|
222
255
|
if ("max_unused_days" in opts)
|
|
223
|
-
pluginOptions.max_unused_days =
|
|
256
|
+
pluginOptions.max_unused_days = testing
|
|
257
|
+
? finiteNumber("max_unused_days", opts.max_unused_days, 30)
|
|
258
|
+
: clampInt("max_unused_days", opts.max_unused_days, 0, 365, 30);
|
|
224
259
|
if ("max_rollout_age_days" in opts)
|
|
225
|
-
pluginOptions.max_rollout_age_days =
|
|
260
|
+
pluginOptions.max_rollout_age_days = testing
|
|
261
|
+
? finiteNumber("max_rollout_age_days", opts.max_rollout_age_days, 10)
|
|
262
|
+
: clampInt("max_rollout_age_days", opts.max_rollout_age_days, 0, 90, 10);
|
|
226
263
|
if ("max_rollouts_per_startup" in opts)
|
|
227
|
-
pluginOptions.max_rollouts_per_startup =
|
|
264
|
+
pluginOptions.max_rollouts_per_startup = testing
|
|
265
|
+
? finiteNumber("max_rollouts_per_startup", opts.max_rollouts_per_startup, 2)
|
|
266
|
+
: clampInt("max_rollouts_per_startup", opts.max_rollouts_per_startup, 1, 128, 2);
|
|
228
267
|
if ("min_rollout_idle_hours" in opts)
|
|
229
|
-
pluginOptions.min_rollout_idle_hours =
|
|
268
|
+
pluginOptions.min_rollout_idle_hours = testing
|
|
269
|
+
? finiteNumber("min_rollout_idle_hours", opts.min_rollout_idle_hours, 6)
|
|
270
|
+
: clampInt("min_rollout_idle_hours", opts.min_rollout_idle_hours, 1, 48, 6);
|
|
230
271
|
if ("home" in raw) {
|
|
231
272
|
if (typeof raw.home !== "string") {
|
|
232
273
|
recordConfigWarning("home must be a string; using the OpenCode data dir");
|
|
@@ -311,7 +352,7 @@ export function applyPluginOptions(opts) {
|
|
|
311
352
|
recordConfigWarning("claude_import must be an object like { enabled, claude_home, projects }; ignored");
|
|
312
353
|
}
|
|
313
354
|
}
|
|
314
|
-
if (
|
|
355
|
+
if (dataRoot() !== previousDb)
|
|
315
356
|
closeDb();
|
|
316
357
|
}
|
|
317
358
|
/**
|
|
@@ -410,7 +451,7 @@ export function injectAgentDefinitions(config) {
|
|
|
410
451
|
// belt-and-suspenders (path is home/env-dependent; out-ranks `"*": deny`).
|
|
411
452
|
const memorize = defs["memorize"];
|
|
412
453
|
if (memorize?.permission && !("external_directory" in memorize.permission)) {
|
|
413
|
-
memorize.permission["external_directory"] =
|
|
454
|
+
memorize.permission["external_directory"] = Object.fromEntries(writeMemoryVersions().map((version) => [path.join(memoryRoot(version), "*"), "allow"]));
|
|
414
455
|
}
|
|
415
456
|
config.agent ??= {};
|
|
416
457
|
for (const [name, def] of Object.entries(defs)) {
|
|
@@ -452,8 +493,10 @@ function buildHooks() {
|
|
|
452
493
|
return;
|
|
453
494
|
if (isTitleGenerationPrompt(output.system))
|
|
454
495
|
return;
|
|
455
|
-
|
|
456
|
-
|
|
496
|
+
const memoryPrompt = withSessionMemoryVersion(input.sessionID, () => {
|
|
497
|
+
ensureMemoryLayout();
|
|
498
|
+
return buildMemorySystemPrompt(pluginOptions.dedicated_tools);
|
|
499
|
+
});
|
|
457
500
|
if (memoryPrompt) {
|
|
458
501
|
output.system.push(memoryPrompt);
|
|
459
502
|
}
|
|
@@ -483,7 +526,7 @@ function buildHooks() {
|
|
|
483
526
|
// records them; the other becomes a no-op.
|
|
484
527
|
const fresh = takeNewCitations(`${input.sessionID}:${input.partID}`, ids);
|
|
485
528
|
if (fresh.length > 0)
|
|
486
|
-
getStore().recordUsage(fresh);
|
|
529
|
+
withSessionMemoryVersion(input.sessionID, () => getStore().recordUsage(fresh));
|
|
487
530
|
}
|
|
488
531
|
catch (e) {
|
|
489
532
|
console.error("[opencode-codex-memory] citation recording failed:", e);
|
|
@@ -532,6 +575,7 @@ function buildHooks() {
|
|
|
532
575
|
const sid = input?.sessionID;
|
|
533
576
|
if (!sid || isMemorySubSession(sid))
|
|
534
577
|
return;
|
|
578
|
+
sessionMemoryVersion(sid);
|
|
535
579
|
if (!markTurnSeen(sid))
|
|
536
580
|
return;
|
|
537
581
|
try {
|
|
@@ -597,7 +641,7 @@ function buildHooks() {
|
|
|
597
641
|
const fresh = takeNewCitations(`${part.sessionID ?? ""}:${part.id ?? ""}`, ids);
|
|
598
642
|
if (fresh.length > 0) {
|
|
599
643
|
try {
|
|
600
|
-
getStore().recordUsage(fresh);
|
|
644
|
+
withSessionMemoryVersion(part.sessionID, () => getStore().recordUsage(fresh));
|
|
601
645
|
}
|
|
602
646
|
catch (e) {
|
|
603
647
|
console.error("[opencode-codex-memory] recordUsage failed:", e);
|
|
@@ -692,47 +736,8 @@ function buildHooks() {
|
|
|
692
736
|
return { ...base, tool };
|
|
693
737
|
}
|
|
694
738
|
async function triggerPhase1(currentSessionId) {
|
|
695
|
-
|
|
696
|
-
return;
|
|
697
|
-
phase1InFlight = true;
|
|
698
|
-
try {
|
|
699
|
-
await runPhase1(getStore(), {
|
|
700
|
-
maxAgeDays: pluginOptions.max_rollout_age_days,
|
|
701
|
-
minIdleHours: pluginOptions.min_rollout_idle_hours,
|
|
702
|
-
maxClaimed: pluginOptions.max_rollouts_per_startup,
|
|
703
|
-
maxUnusedDays: pluginOptions.max_unused_days,
|
|
704
|
-
excludeSession: currentSessionId,
|
|
705
|
-
extractModel: pluginOptions.extract_model,
|
|
706
|
-
});
|
|
707
|
-
}
|
|
708
|
-
catch (err) {
|
|
709
|
-
console.error("[opencode-codex-memory] phase1 error:", err);
|
|
710
|
-
recordDiagnostic("error", "phase1", err instanceof Error ? err.message : String(err));
|
|
711
|
-
}
|
|
712
|
-
finally {
|
|
713
|
-
phase1InFlight = false;
|
|
714
|
-
}
|
|
715
|
-
trackBackgroundTask(triggerPhase2());
|
|
739
|
+
await runMemoryPipeline(currentSessionId);
|
|
716
740
|
}
|
|
717
741
|
async function triggerPhase2() {
|
|
718
|
-
|
|
719
|
-
return;
|
|
720
|
-
try {
|
|
721
|
-
// runPhase2 has its own in-flight guard
|
|
722
|
-
const result = await runPhase2(getStore(), {
|
|
723
|
-
maxRaw: pluginOptions.max_raw_memories_for_consolidation,
|
|
724
|
-
maxUnusedDays: pluginOptions.max_unused_days,
|
|
725
|
-
extensionRetentionDays: 7,
|
|
726
|
-
consolidationModel: pluginOptions.consolidation_model,
|
|
727
|
-
codexInterop: pluginOptions.codex_interop,
|
|
728
|
-
claudeImport: pluginOptions.claude_import,
|
|
729
|
-
});
|
|
730
|
-
if (result.status !== "already_running" && result.status !== "skipped_cooldown" && result.status !== "skipped_running") {
|
|
731
|
-
recordDiagnostic(result.status === "succeeded" || result.status === "no_workspace_changes" ? "info" : "warn", "phase2", result.status);
|
|
732
|
-
}
|
|
733
|
-
}
|
|
734
|
-
catch (err) {
|
|
735
|
-
console.error("[opencode-codex-memory] phase2 error:", err);
|
|
736
|
-
recordDiagnostic("error", "phase2", err instanceof Error ? err.message : String(err));
|
|
737
|
-
}
|
|
742
|
+
await runMemoryConsolidation();
|
|
738
743
|
}
|