Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat[codex] use session-aware search for recall (#2729)

Zayn Jarvisc0d8622f4433
diff --git a/examples/codex-memory-plugin/DESIGN.md b/examples/codex-memory-plugin/DESIGN.md
index 02d7077de..9a7b0e404 100644
--- a/examples/codex-memory-plugin/DESIGN.md
+++ b/examples/codex-memory-plugin/DESIGN.md
@@ -146,11 +146,17 @@ State is updated:
## Injected context boundary
-`UserPromptSubmit` stdin `prompt` is the user's prompt only. Recalled
-memory is sent back through `hookSpecificOutput.additionalContext`, then
-Codex injects it into the model turn. Transcript capture may later see
-that injected context adjacent to the prompt, so plugin-generated recall
-and resume context are wrapped in a deterministic boundary:
+`UserPromptSubmit` stdin includes the user's `prompt` plus the Codex
+`session_id`. Recall derives the same OpenViking session id used by Stop
+capture (`cx-<safe-session-id>`) directly from the Codex session id and
+calls `/api/v1/search/search` with that `session_id`, so OpenViking can
+use recent session messages and archive overview during query expansion.
+Recall does not read plugin state, so a corrupt or missing state file
+cannot crash the recall hook. Recalled memory is sent back through
+`hookSpecificOutput.additionalContext`, then Codex injects it into the
+model turn. Transcript capture may later see that injected context
+adjacent to the prompt, so plugin-generated recall and resume context are
+wrapped in a deterministic boundary:
```text
<openviking-context source="auto-recall" format="digest">
@@ -211,8 +217,9 @@ OV session id, while commits create additional archives under that session.
```
Legacy state files from earlier plugin versions may still contain a UUID
-`ovSessionId`; the hook preserves that value until the next commit so
-already-captured turns are not orphaned.
+`ovSessionId`; those are now overwritten with the derived `cx-*` id on the
+next resolve. The migration window for preserving old UUID sessions has
+closed.
State files are atomic-write (tmpfile + rename) to survive crash mid-write.
@@ -328,6 +335,16 @@ Configured `off` (`OPENVIKING_RECALL_COMPRESS=0`, model `off`, or thinking
"hook_event_name": "SessionStart"
}
+// UserPromptSubmit input
+{
+ "session_id": "0193af...",
+ "prompt": "user prompt text",
+ "cwd": "/path/to/cwd",
+ "model": "gpt-5.5",
+ "permission_mode": "default",
+ "hook_event_name": "UserPromptSubmit"
+}
+
// Stop input
{
"session_id": "0193af...",
diff --git a/examples/codex-memory-plugin/README.md b/examples/codex-memory-plugin/README.md
index 4de6b9d1b..38e0090a3 100644
--- a/examples/codex-memory-plugin/README.md
+++ b/examples/codex-memory-plugin/README.md
@@ -114,7 +114,7 @@ Earlier plugin versions configured tuning fields under a `codex` block in `~/.op
│ │ │ │
│ ┌───▼────────────────▼───────────────────▼──┐
└────────────►│ OpenViking REST API │
- │ /api/v1/search/find │
+ │ /api/v1/search/search │
│ /api/v1/sessions [+/{id}/{messages,commit}]│
│ /api/v1/content/read │
└─────────────────┬─────────────────────────┘
@@ -152,7 +152,7 @@ On `resume`, the script skips commit/sweep. If local state has no live `ovSessio
### Auto-recall (every UserPromptSubmit)
-`auto-recall.mjs` reads `prompt` from stdin, calls `/api/v1/search/find`, ranks results, reads full content for top-ranked leaves, and emits:
+`auto-recall.mjs` reads `prompt` and `session_id` from stdin, derives the long-lived OpenViking session id (`cx-<safe-session-id>`) directly from the Codex session id (no plugin state read, so a corrupt state file can't crash recall), calls `/api/v1/search/search` with that `session_id`, ranks results, reads full content for top-ranked leaves, and emits:
```json
{ "hookSpecificOutput": { "hookEventName": "UserPromptSubmit", "additionalContext": "<openviking-context source=\"auto-recall\" format=\"digest\">\nOpenViking memory digest:\n- ...\n</openviking-context>" } }
@@ -204,7 +204,7 @@ Codex's hook output schema differs from Claude Code's. Notably:
| Hook | Input field of interest | Output channel for context injection |
|------|------------------------|--------------------------------------|
| `SessionStart` | `source` (`startup`/`resume`/`clear`), `session_id` | `hookSpecificOutput.additionalContext` |
-| `UserPromptSubmit` | `prompt` | `hookSpecificOutput.additionalContext` |
+| `UserPromptSubmit` | `prompt`, `session_id` | `hookSpecificOutput.additionalContext` |
| `Stop` | `last_assistant_message`, `transcript_path`, `session_id` | `systemMessage` (only) |
| `PreCompact` | `trigger` (`manual`/`auto`), `transcript_path`, `session_id` | `systemMessage` (only) |
@@ -226,7 +226,7 @@ codex-memory-plugin/
│ ├── debug-log.mjs # Structured JSONL logger
│ ├── recall-compressor-profile.mjs # Compressor profile detection/cache
│ ├── session-state.mjs # Per-codex-session OV session state
-│ ├── auto-recall.mjs # UserPromptSubmit hook (REST /search/find)
+│ ├── auto-recall.mjs # UserPromptSubmit hook (REST /search/search)
│ ├── auto-capture.mjs # Stop hook (REST /sessions/{id}/messages)
│ ├── session-start-commit.mjs # SessionStart hook (active-window + idle TTL)
│ └── pre-compact-capture.mjs # PreCompact hook
diff --git a/examples/codex-memory-plugin/scripts/auto-recall.mjs b/examples/codex-memory-plugin/scripts/auto-recall.mjs
index 4d722bc0d..922eb3346 100644
--- a/examples/codex-memory-plugin/scripts/auto-recall.mjs
+++ b/examples/codex-memory-plugin/scripts/auto-recall.mjs
@@ -25,6 +25,7 @@ import {
loadCachedRecallCompressorProfile,
markRecallCompressorRuntimeFailed,
} from "./recall-compressor-profile.mjs";
+import { deriveOvSessionId } from "./session-state.mjs";
const cfg = loadConfig();
const { log, logError } = createLogger("auto-recall");
@@ -212,21 +213,22 @@ function postProcess(items, limit, threshold) {
return result;
}
-async function searchScope(query, targetUri, limit, bucket = "memories") {
+async function searchScope(query, targetUri, limit, bucket = "memories", sessionId = null) {
// Keep current-user shorthand here; the server canonicalizes it using the
// authenticated/trusted request context.
const body = { query, target_uri: targetUri, limit, score_threshold: 0 };
- const result = await fetchJSON("/api/v1/search/find", {
+ if (sessionId) body.session_id = sessionId;
+ const result = await fetchJSON("/api/v1/search/search", {
method: "POST",
body: JSON.stringify(body),
});
return result?.[bucket] || [];
}
-async function searchAll(query, limit) {
+async function searchAll(query, limit, sessionId = null) {
const [userMems, userSkills] = await Promise.all([
- searchScope(query, "viking://user/memories", limit),
- searchScope(query, "viking://user/skills", limit, "skills"),
+ searchScope(query, "viking://user/memories", limit, "memories", sessionId),
+ searchScope(query, "viking://user/skills", limit, "skills", sessionId),
]);
log("search_complete", { scope: "user", rawCount: userMems.length, topScores: userMems.slice(0, 3).map((m) => m.score) });
log("search_complete", { scope: "skills", rawCount: userSkills.length, topScores: userSkills.slice(0, 3).map((m) => m.score) });
@@ -239,6 +241,15 @@ async function searchAll(query, limit) {
});
}
+function resolveRecallSessionId(codexSessionId) {
+ if (!codexSessionId) return null;
+ // Derive directly: the OV session id is deterministic (cx-<safe-id>), so
+ // recall does not need to read plugin state. This keeps the recall hook
+ // crash-free even if the state file is corrupt/missing, and stays in sync
+ // with capture, which now also derives cx-* unconditionally.
+ return deriveOvSessionId(codexSessionId);
+}
+
async function readMemoryContent(uri) {
try {
const result = await fetchJSON(`/api/v1/content/read?uri=${encodeURIComponent(uri)}`);
@@ -447,7 +458,11 @@ async function main() {
}
const userPrompt = (input.prompt || "").trim();
+ const codexSessionId = typeof input.session_id === "string" ? input.session_id.trim() : "";
+ const recallSessionId = resolveRecallSessionId(codexSessionId);
log("start", {
+ codexSessionId: codexSessionId || null,
+ recallSessionId,
query: userPrompt.slice(0, 200),
queryLength: userPrompt.length,
config: { recallLimit: cfg.recallLimit, scoreThreshold: cfg.scoreThreshold },
@@ -467,7 +482,7 @@ async function main() {
}
const candidateLimit = Math.max(cfg.recallLimit * 4, 20);
- const allMemories = await searchAll(userPrompt, candidateLimit);
+ const allMemories = await searchAll(userPrompt, candidateLimit, recallSessionId);
if (allMemories.length === 0) {
log("skip", { stage: "search", reason: "no results" });
emit();
diff --git a/examples/codex-memory-plugin/scripts/auto-recall.test.mjs b/examples/codex-memory-plugin/scripts/auto-recall.test.mjs
new file mode 100644
index 000000000..ac8584042
--- /dev/null
+++ b/examples/codex-memory-plugin/scripts/auto-recall.test.mjs
@@ -0,0 +1,145 @@
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { mkdtemp, rm } from "node:fs/promises";
+import http from "node:http";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
+
+function readRequestBody(req) {
+ return new Promise((resolve, reject) => {
+ const chunks = [];
+ req.on("data", (chunk) => chunks.push(chunk));
+ req.on("end", () => {
+ const raw = Buffer.concat(chunks).toString("utf-8");
+ try {
+ resolve(raw ? JSON.parse(raw) : null);
+ } catch (err) {
+ reject(err);
+ }
+ });
+ req.on("error", reject);
+ });
+}
+
+function writeJson(res, value) {
+ res.writeHead(200, { "Content-Type": "application/json" });
+ res.end(JSON.stringify(value));
+}
+
+async function withMockOpenViking(handler, fn) {
+ const server = http.createServer((req, res) => {
+ handler(req, res).catch((err) => {
+ res.writeHead(500, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ status: "error", error: String(err?.stack || err) }));
+ });
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ try {
+ const { port } = server.address();
+ return await fn(`http://127.0.0.1:${port}`);
+ } finally {
+ await new Promise((resolve) => server.close(resolve));
+ }
+}
+
+function runAutoRecall(input, env) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(process.execPath, [join(SCRIPT_DIR, "auto-recall.mjs")], {
+ env: { ...process.env, ...env },
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.on("data", (chunk) => { stdout += chunk.toString(); });
+ child.stderr.on("data", (chunk) => { stderr += chunk.toString(); });
+ child.on("error", reject);
+ child.on("close", (code) => {
+ if (code !== 0) {
+ reject(new Error(`auto-recall exited ${code}: ${stderr}`));
+ return;
+ }
+ resolve({ stdout, stderr });
+ });
+ child.stdin.end(JSON.stringify(input));
+ });
+}
+
+test("auto-recall uses context-aware search with the derived OpenViking session id", async () => {
+ const stateDir = await mkdtemp(join(tmpdir(), "ov-auto-recall-state-"));
+ const requests = [];
+
+ try {
+ await withMockOpenViking(async (req, res) => {
+ const url = new URL(req.url, "http://127.0.0.1");
+ if (req.method === "GET" && url.pathname === "/health") {
+ writeJson(res, { status: "ok", result: { ok: true } });
+ return;
+ }
+ if (req.method === "POST" && url.pathname === "/api/v1/search/search") {
+ const body = await readRequestBody(req);
+ requests.push({ path: url.pathname, body });
+ if (body.target_uri === "viking://user/memories") {
+ writeJson(res, {
+ status: "ok",
+ result: {
+ memories: [{
+ uri: "viking://user/zeus/memories/events/context-search.md",
+ level: 2,
+ score: 0.9,
+ category: "events",
+ abstract: "context search memory",
+ }],
+ skills: [],
+ },
+ });
+ return;
+ }
+ writeJson(res, { status: "ok", result: { memories: [], skills: [] } });
+ return;
+ }
+ if (req.method === "GET" && url.pathname === "/api/v1/content/read") {
+ writeJson(res, { status: "ok", result: "context-aware recalled detail" });
+ return;
+ }
+ res.writeHead(404, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ status: "error", error: "not found" }));
+ }, async (baseUrl) => {
+ const result = await runAutoRecall(
+ { prompt: "please use prior context", session_id: "codex:123" },
+ {
+ OPENVIKING_AUTO_RECALL: "1",
+ OPENVIKING_CODEX_STATE_DIR: stateDir,
+ OPENVIKING_CONFIG_FILE: join(stateDir, "missing-ov.conf"),
+ OPENVIKING_CLI_CONFIG_FILE: join(stateDir, "missing-ovcli.conf"),
+ OPENVIKING_CREDENTIAL_SOURCE: "env",
+ OPENVIKING_RECALL_COMPRESS: "0",
+ OPENVIKING_RECALL_LIMIT: "1",
+ OPENVIKING_RECALL_TIMEOUT_MS: "10000",
+ OPENVIKING_MIN_QUERY_LENGTH: "1",
+ OPENVIKING_SCORE_THRESHOLD: "0",
+ OPENVIKING_TIMEOUT_MS: "5000",
+ OPENVIKING_URL: baseUrl,
+ },
+ );
+
+ const output = JSON.parse(result.stdout.trim());
+ assert.match(
+ output.hookSpecificOutput.additionalContext,
+ /context-aware recalled detail/,
+ );
+ });
+
+ assert.equal(requests.length, 2);
+ assert.deepEqual(
+ requests.map((request) => request.body.target_uri).sort(),
+ ["viking://user/memories", "viking://user/skills"],
+ );
+ assert.ok(requests.every((request) => request.body.session_id === "cx-codex_123"));
+ } finally {
+ await rm(stateDir, { recursive: true, force: true });
+ }
+});
diff --git a/examples/codex-memory-plugin/scripts/session-state.mjs b/examples/codex-memory-plugin/scripts/session-state.mjs
index 58f8d12ca..ef04beb64 100644
--- a/examples/codex-memory-plugin/scripts/session-state.mjs
+++ b/examples/codex-memory-plugin/scripts/session-state.mjs
@@ -29,9 +29,10 @@ export function deriveOvSessionId(codexSessionId) {
}
export function resolveOvSessionId(state) {
- // Keep legacy persisted UUIDs so already-captured turns are not orphaned
- // before their next commit. Fresh or cleared state derives the cx-* id.
- if (state.ovSessionId) return state.ovSessionId;
+ // Always derive the deterministic cx-* id. Legacy persisted UUIDs from
+ // before the cx-* scheme are no longer preserved: the migration window
+ // has closed and keeping them would desync recall (which derives cx-*)
+ // from capture (which used to echo back the legacy value).
state.ovSessionId = deriveOvSessionId(state.codexSessionId);
return state.ovSessionId;
}