Skip to content

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

feat(codex): support upstream marketplace install (#2879)

LinQiang3918708debe1016
diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json
new file mode 100644
index 000000000..32af29206
--- /dev/null
+++ b/.agents/plugins/marketplace.json
@@ -0,0 +1,21 @@
+{
+ "name": "openviking",
+ "description": "OpenViking plugins for OpenAI Codex.",
+ "interface": {
+ "displayName": "OpenViking"
+ },
+ "plugins": [
+ {
+ "name": "openviking-memory",
+ "source": {
+ "source": "local",
+ "path": "./examples/codex-memory-plugin"
+ },
+ "policy": {
+ "installation": "AVAILABLE",
+ "authentication": "ON_USE"
+ },
+ "category": "Productivity"
+ }
+ ]
+}
diff --git a/docs/en/agent-integrations/04-codex.md b/docs/en/agent-integrations/04-codex.md
index d1d144df7..67713d6ca 100644
--- a/docs/en/agent-integrations/04-codex.md
+++ b/docs/en/agent-integrations/04-codex.md
@@ -6,6 +6,20 @@ Source: [examples/codex-memory-plugin](https://github.com/volcengine/OpenViking/
## Install
+### Codex marketplace
+
+Use Codex's native marketplace commands for local or self-hosted OpenViking:
+
+```bash
+codex plugin marketplace add volcengine/OpenViking
+codex plugin add openviking-memory@openviking
+```
+
+When adding from the Codex App UI, leave the sparse path empty. The marketplace
+catalog lives at the repository root in `.agents/plugins/marketplace.json`.
+
+### One-line installer
+
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/codex-memory-plugin/setup-helper/install.sh)
```
@@ -38,6 +52,53 @@ Prerequisites: Node.js >= 22, Codex >= 0.130.0, and the `codex_hooks` feature en
3. **Placeholder rendering** — The provided `.mcp.json` and `hooks.json` files contain placeholders that must be substituted when copied to Codex's plugin cache. The automated installer handles this for you.
+ Codex App keeps the installed copy in its plugin cache:
+
+ - macOS/Linux: `~/.codex/plugins/cache/openviking/openviking-memory/<version>/`
+ - Windows: `%USERPROFILE%\.codex\plugins\cache\openviking\openviking-memory\<version>\`
+
+ If you installed from the Codex marketplace and later changed
+ `~/.openviking/ovcli.conf`, re-render the cached MCP config. On Windows:
+
+ ```powershell
+ $PluginCache = Get-ChildItem "$env:USERPROFILE\.codex\plugins\cache\openviking\openviking-memory" -Directory |
+ Sort-Object LastWriteTime -Descending |
+ Select-Object -First 1
+ node "$($PluginCache.FullName)\scripts\ov-credentials.mjs" sync-mcp "$($PluginCache.FullName)\.mcp.json"
+ Get-Content -Raw "$($PluginCache.FullName)\.mcp.json"
+ ```
+
+ The rendered `.mcp.json` should point at `/mcp` and use
+ `bearer_token_env_var` instead of storing the secret:
+
+ ```json
+ {
+ "mcpServers": {
+ "openviking-memory": {
+ "url": "http://localhost:1933/mcp",
+ "bearer_token_env_var": "OPENVIKING_API_KEY",
+ "env_http_headers": {
+ "X-OpenViking-Account": "OPENVIKING_ACCOUNT",
+ "X-OpenViking-User": "OPENVIKING_USER"
+ }
+ }
+ }
+ }
+ ```
+
+ Restart Codex after editing `.mcp.json` or changing environment variables.
+
+ Copy this prompt into Codex if you want the agent to repair the installed
+ cache for you:
+
+ ```text
+ Fix my installed OpenViking Memory Codex plugin MCP config.
+ Locate the newest openviking-memory plugin cache under CODEX_HOME, or ~/.codex if unset
+ (Windows: %CODEX_HOME%, or %USERPROFILE%\.codex if unset). Use ~/.openviking/ovcli.conf
+ to run scripts/ov-credentials.mjs sync-mcp against the cached .mcp.json. Do not write
+ the API key value into .mcp.json; show the redacted result and remind me to restart Codex.
+ ```
+
</details>
## Verify
diff --git a/docs/images/agents/en/codex.md b/docs/images/agents/en/codex.md
index 49e6177b8..dcf5d09f3 100644
--- a/docs/images/agents/en/codex.md
+++ b/docs/images/agents/en/codex.md
@@ -4,6 +4,20 @@ Source: [examples/codex-memory-plugin](https://github.com/volcengine/OpenViking/
## Step 1: Install
+### Codex marketplace
+
+Use Codex's native marketplace commands for local or self-hosted OpenViking:
+
+```bash
+codex plugin marketplace add volcengine/OpenViking
+codex plugin add openviking-memory@openviking
+```
+
+When adding from the Codex App UI, leave the sparse path empty. The marketplace
+catalog lives at the repository root in `.agents/plugins/marketplace.json`.
+
+### One-line installer
+
```bash
bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/codex-memory-plugin/tos-install.sh)
```
@@ -30,6 +44,32 @@ Prerequisites: Node.js >= 22, Codex >= 0.130.0, and the `codex_hooks` feature en
3. **Render placeholders** - Placeholders in `.mcp.json` and `hooks.json` must be replaced with absolute paths or values when copied into the Codex cache. The automated installer handles this for you.
+ Codex App stores the installed plugin under:
+
+ - macOS/Linux: `~/.codex/plugins/cache/openviking/openviking-memory/<version>/`
+ - Windows: `%USERPROFILE%\.codex\plugins\cache\openviking\openviking-memory\<version>\`
+
+ After changing `~/.openviking/ovcli.conf`, re-render the cached MCP config.
+ On Windows:
+
+ ```powershell
+ $PluginCache = Get-ChildItem "$env:USERPROFILE\.codex\plugins\cache\openviking\openviking-memory" -Directory |
+ Sort-Object LastWriteTime -Descending |
+ Select-Object -First 1
+ node "$($PluginCache.FullName)\scripts\ov-credentials.mjs" sync-mcp "$($PluginCache.FullName)\.mcp.json"
+ Get-Content -Raw "$($PluginCache.FullName)\.mcp.json"
+ ```
+
+ You can ask Codex to do it with this prompt:
+
+ ```text
+ Fix my installed OpenViking Memory Codex plugin MCP config.
+ Locate the newest openviking-memory plugin cache under CODEX_HOME, or ~/.codex if unset
+ (Windows: %CODEX_HOME%, or %USERPROFILE%\.codex if unset). Use ~/.openviking/ovcli.conf
+ to run scripts/ov-credentials.mjs sync-mcp against the cached .mcp.json. Do not write
+ the API key value into .mcp.json; show the redacted result and remind me to restart Codex.
+ ```
+
</details>
## Step 2: Verify
diff --git a/examples/codex-memory-plugin/.codex-plugin/plugin.json b/examples/codex-memory-plugin/.codex-plugin/plugin.json
index 7fcb9ecdd..4c869a5e5 100644
--- a/examples/codex-memory-plugin/.codex-plugin/plugin.json
+++ b/examples/codex-memory-plugin/.codex-plugin/plugin.json
@@ -21,14 +21,16 @@
"interface": {
"displayName": "OpenViking Memory",
"shortDescription": "Long-term semantic memory for Codex",
- "longDescription": "Hooks Codex's lifecycle to keep an external semantic memory: recall relevant memories on each UserPromptSubmit; on every Stop (turn end) append the new user/assistant turns to a long-lived OpenViking session keyed by codex session_id; on PreCompact commit that session so OV's extractor produces durable memories before context is summarized; on SessionStart(source=clear) commit any orphaned prior session before /clear discards it. Also exposes explicit MCP tools (openviking_recall, openviking_store, openviking_forget, openviking_health) for manual use.",
+ "longDescription": "Hooks Codex's lifecycle to keep an external semantic memory: recall relevant memories on each UserPromptSubmit; on every Stop (turn end) append the new user/assistant turns to a long-lived OpenViking session keyed by codex session_id; on PreCompact commit that session so OV's extractor produces durable memories before context is summarized; on SessionStart(source=clear) commit any orphaned prior session before /clear discards it. Also exposes explicit MCP tools (search, store, read, list, grep, glob, forget, add_resource, health) over OpenViking's native streamable-HTTP /mcp endpoint for manual use.",
"developerName": "OpenViking",
"category": "Productivity",
"capabilities": [
- "Memory recall",
- "Auto memory capture",
- "Manual memory storage",
- "Manual memory deletion"
+ "Automatic memory recall on each prompt",
+ "Incremental conversation capture per turn",
+ "Pre-compaction memory extraction",
+ "Session archive search and original-text read-back",
+ "Resource ingestion for RAG (add_resource)",
+ "Explicit MCP tools: search, store, read, list, grep, glob, forget, add_resource, health"
],
"websiteURL": "https://github.com/volcengine/OpenViking"
}
diff --git a/examples/codex-memory-plugin/.mcp.json b/examples/codex-memory-plugin/.mcp.json
index 99e3bc9c5..fb7ad4686 100644
--- a/examples/codex-memory-plugin/.mcp.json
+++ b/examples/codex-memory-plugin/.mcp.json
@@ -1,13 +1,7 @@
{
"mcpServers": {
"openviking-memory": {
- "url": "__OPENVIKING_MCP_URL__",
- "bearer_token_env_var": "OPENVIKING_API_KEY",
- "env_http_headers": {
- "X-OpenViking-Account": "OPENVIKING_ACCOUNT",
- "X-OpenViking-User": "OPENVIKING_USER",
- "X-OpenViking-Actor-Peer": "OPENVIKING_PEER_ID"
- }
+ "url": "http://127.0.0.1:1933/mcp"
}
}
}
diff --git a/examples/codex-memory-plugin/README.md b/examples/codex-memory-plugin/README.md
index 38e0090a3..dc88f3286 100644
--- a/examples/codex-memory-plugin/README.md
+++ b/examples/codex-memory-plugin/README.md
@@ -13,7 +13,48 @@ It also wires Codex up to OpenViking's native `/mcp` endpoint (streamable HTTP,
## Quick Start
-### One-line installer (recommended)
+There are two install paths. **Pick one — don't mix them** (both surface the same `openviking-memory` plugin; enabling it from both would run the hooks twice).
+
+### A. Codex marketplace install (recommended for local / self-hosted)
+
+The repo ships a Codex marketplace catalog at `.agents/plugins/marketplace.json`, so you can install with Codex's native commands — no `curl | bash`, no shell-rc wrapper:
+
+```bash
+# 1. add the OpenViking marketplace (use volcengine/OpenViking once merged
+# upstream, or <your-fork>/OpenViking while testing a fork)
+codex plugin marketplace add volcengine/OpenViking
+
+# 2. install the plugin from that marketplace
+# (older Codex builds spell this `codex plugin install`)
+codex plugin add openviking-memory@openviking
+```
+
+Then enable plugin hooks (if your Codex build doesn't already) by adding to `~/.codex/config.toml`:
+
+```toml
+[features]
+plugin_hooks = true
+```
+
+Finally start Codex and trust the plugin hooks once:
+
+```bash
+codex # then run /hooks inside Codex to review & approve the hooks
+```
+
+> **Requirements & notes**
+>
+> - **Codex version**: this path relies on Codex injecting and inline-substituting `${PLUGIN_ROOT}` in plugin hook commands (current Codex does both). On an older Codex that doesn't substitute `${PLUGIN_ROOT}`, the hook script paths won't resolve — use path **B**, whose installer renders `${PLUGIN_ROOT}` to absolute paths for old Codex.
+> - **Catalog source**: the catalog entry (`.agents/plugins/marketplace.json`) uses a relative source (`./examples/codex-memory-plugin`). `codex plugin add` therefore installs the plugin from the same marketplace snapshot/ref that you added. This keeps fork, branch, tag, and upstream-main installs reproducible and testable without rewriting the catalog.
+
+This path works **out of the box against an unauthenticated local OpenViking** at `http://127.0.0.1:1933`: the shipped `.mcp.json` defaults to that `/mcp` URL and the hooks reference Codex's native `${PLUGIN_ROOT}` token (Codex injects it into the hook env and substitutes it inline), so the model gets the `/mcp` tools and all four lifecycle hooks with **zero rendering**.
+
+For an **authenticated or remote/cloud** server on this path:
+
+- **Hooks** (the REST calls) read `~/.openviking/ovcli.conf` (or `OPENVIKING_*` env) directly — set `url` / `api_key` / `account` / `user` there.
+- **MCP auth**: Codex reads the bearer token from an env var, so export `OPENVIKING_API_KEY` in the shell that launches Codex *and* add `"bearer_token_env_var": "OPENVIKING_API_KEY"` to the installed plugin's cached `.mcp.json`. It's omitted by default because Codex **hard-fails** MCP startup when a `bearer_token_env_var` points at an unset/empty variable. Also note Codex doesn't let user config override a plugin's MCP `url`, so cloud users who want everything wired automatically should prefer path **B**.
+
+### B. One-line installer — `curl | bash` (recommended for Volcengine Cloud / managed credentials)
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/codex-memory-plugin/setup-helper/install.sh)
@@ -24,8 +65,8 @@ The installer:
1. Checks `codex`, `git`, and Node.js 22+
2. Clones or refreshes `~/.openviking/openviking-repo`
3. Registers a local `openviking-plugins-local` marketplace, enables `openviking-memory@openviking-plugins-local`, sets `features.plugin_hooks = true`
-4. Renders the cached `.mcp.json` URL using the shared credential resolver
-5. Renders the cached `hooks.json` with absolute script paths (Codex 0.130 doesn't inject `CODEX_PLUGIN_ROOT` into hook env)
+4. Renders the cached `.mcp.json` URL **and** bearer/identity headers from your active `ovcli.conf`
+5. Renders the cached `hooks.json` `${PLUGIN_ROOT}` token to absolute script paths (so even older Codex builds that don't substitute `${PLUGIN_ROOT}` work)
6. Appends a `codex()` shell function to your rc that resolves the active OpenViking CLI config at invocation, injects the matching env for Codex/MCP, and strips stale inherited credential env vars
After install:
@@ -48,7 +89,56 @@ If you don't want the installer touching your rc, do these three things yourself
2. **Add the plugin** via a local marketplace pointing at this directory. See `setup-helper/install.sh` for the exact `codex plugin marketplace add` invocation.
-3. **Render the `__OPENVIKING_MCP_URL__` placeholder** in `.mcp.json` and the `__OPENVIKING_PLUGIN_ROOT__` placeholders in `hooks/hooks.json` to absolute values. The installer does this automatically when copying the plugin into Codex's cache; for manual setup you do it once with `sed`.
+3. **Point the cached `.mcp.json` at your server.** The checked-in `.mcp.json` defaults to `http://127.0.0.1:1933/mcp` with no bearer. For a remote/authenticated server, set the `url` and add `"bearer_token_env_var": "OPENVIKING_API_KEY"` — `node scripts/ov-credentials.mjs sync-mcp <path-to-cached .mcp.json>` does both from your active `ovcli.conf`. `hooks/hooks.json` needs **no** rendering on modern Codex: it uses the native `${PLUGIN_ROOT}` token, which Codex injects into the hook env and substitutes inline. Only older Codex builds that don't substitute `${PLUGIN_ROOT}` require replacing it with an absolute path (the installer does this for its cache copy).
+
+ Codex App stores the installed plugin under its cache, not in this source
+ tree. Common cache locations are:
+
+ - macOS/Linux: `~/.codex/plugins/cache/openviking/openviking-memory/<version>/`
+ - Windows: `%USERPROFILE%\.codex\plugins\cache\openviking\openviking-memory\<version>\`
+
+ To re-render the installed MCP config on Windows after changing
+ `~/.openviking/ovcli.conf`:
+
+ ```powershell
+ $PluginCache = Get-ChildItem "$env:USERPROFILE\.codex\plugins\cache\openviking\openviking-memory" -Directory |
+ Sort-Object LastWriteTime -Descending |
+ Select-Object -First 1
+ node "$($PluginCache.FullName)\scripts\ov-credentials.mjs" sync-mcp "$($PluginCache.FullName)\.mcp.json"
+ Get-Content -Raw "$($PluginCache.FullName)\.mcp.json"
+ ```
+
+ A rendered authenticated config looks like:
+
+ ```json
+ {
+ "mcpServers": {
+ "openviking-memory": {
+ "url": "http://localhost:1933/mcp",
+ "bearer_token_env_var": "OPENVIKING_API_KEY",
+ "env_http_headers": {
+ "X-OpenViking-Account": "OPENVIKING_ACCOUNT",
+ "X-OpenViking-User": "OPENVIKING_USER"
+ }
+ }
+ }
+ }
+ ```
+
+ Keep the API key in `ovcli.conf` or the environment; do not write the
+ secret value directly into `.mcp.json`. Restart Codex after changing MCP
+ config or environment variables.
+
+ You can also ask Codex to repair this on the user's machine with this
+ prompt:
+
+ ```text
+ Fix my installed OpenViking Memory Codex plugin MCP config.
+ Locate the newest openviking-memory plugin cache under CODEX_HOME, or ~/.codex if unset
+ (Windows: %CODEX_HOME%, or %USERPROFILE%\.codex if unset). Use ~/.openviking/ovcli.conf
+ to run scripts/ov-credentials.mjs sync-mcp against the cached .mcp.json. Do not write
+ the API key value into .mcp.json; show the redacted result and remind me to restart Codex.
+ ```
## Configuration
@@ -124,7 +214,7 @@ Earlier plugin versions configured tuning fields under a `codex` block in `~/.op
OPENVIKING_API_KEY) add_resource, health)
```
-The plugin no longer bundles a local stdio MCP server. Codex talks to OpenViking's built-in `/mcp` endpoint directly via streamable HTTP, with `bearer_token_env_var: "OPENVIKING_API_KEY"` in `.mcp.json` so the key stays in `ovcli.conf` and the shell function — never on disk in `.mcp.json` itself.
+The plugin no longer bundles a local stdio MCP server. Codex talks to OpenViking's built-in `/mcp` endpoint directly via streamable HTTP. The checked-in `.mcp.json` ships only the local-default `url` (no `bearer_token_env_var`), so a `codex plugin marketplace add` install connects to an unauthenticated local OV out of the box. For an authenticated server, the installer/wrapper adds `bearer_token_env_var: "OPENVIKING_API_KEY"` to the cached copy when an API key is configured (and `codex plugin add` users add it by hand) — the key itself stays in `ovcli.conf` / the env, never on disk in `.mcp.json`.
For details on OpenViking's MCP endpoint, tools, and protocol, see the [MCP Integration Guide](../../docs/en/guides/06-mcp-integration.md). The tools list and per-tool semantics are documented there once, not duplicated here.
@@ -218,8 +308,8 @@ codex-memory-plugin/
│ └── plugin.json # Plugin manifest (hooks + mcp wiring)
├── hooks/
│ └── hooks.json # SessionStart + UserPromptSubmit + Stop + PreCompact
-│ (uses __OPENVIKING_PLUGIN_ROOT__ placeholder;
-│ installer renders to absolute paths)
+│ (uses Codex's native ${PLUGIN_ROOT} token; no
+│ rendering needed on modern Codex)
├── scripts/
│ ├── config.mjs # Shared config loader (ovcli.conf + env)
│ ├── capture-utils.mjs # Transcript text extraction, filtering, tool compression
@@ -232,7 +322,7 @@ codex-memory-plugin/
│ └── pre-compact-capture.mjs # PreCompact hook
├── setup-helper/
│ └── install.sh # One-line installer
-├── .mcp.json # Streamable-HTTP MCP wiring (renders __OPENVIKING_MCP_URL__)
+├── .mcp.json # Streamable-HTTP MCP wiring (local-default url; installer adds auth)
├── DESIGN.md
├── VERIFICATION.md
└── README.md
@@ -240,11 +330,13 @@ codex-memory-plugin/
No `src/`, `servers/`, `node_modules/`, or `package.json`: there is no local MCP server to build or run. All hook scripts are zero-dep `.mjs` running on Codex's bundled Node 22.
+The Codex marketplace catalog that exposes this plugin for `codex plugin marketplace add` lives at the **repo root** in `.agents/plugins/marketplace.json` (Codex resolves a marketplace manifest from the source root, not from this subdirectory). The catalog points at `./examples/codex-memory-plugin` using a relative source, so the installed plugin follows the same marketplace snapshot/ref that the user added.
+
## Differences from the Claude Code Plugin
| Aspect | Claude Code Plugin | Codex Plugin |
|--------|--------------------|--------------|
-| Plugin root env var | `CLAUDE_PLUGIN_ROOT` (expanded by CC) | `CODEX_PLUGIN_ROOT` (NOT expanded by Codex 0.130; installer renders absolute paths into the cached copies) |
+| Plugin root env var | `CLAUDE_PLUGIN_ROOT` (expanded by CC) | `${PLUGIN_ROOT}` (injected into hook env + substituted inline by modern Codex; installer also renders it to absolute paths for older Codex) |
| `UserPromptSubmit` injection | `decision: "approve"` + `hookSpecificOutput.additionalContext` | `hookSpecificOutput.additionalContext` only — `approve` is not a Codex output |
| `Stop` decision | `decision: "approve"` no-op | `{}` no-op — only `block` is a valid Codex `decision` |
| Compaction hook | n/a (Claude Code does not expose one) | `PreCompact` — full-transcript commit before context loss |
diff --git a/examples/codex-memory-plugin/hooks/hooks.json b/examples/codex-memory-plugin/hooks/hooks.json
index 076f7d11b..4ac2caaf6 100644
--- a/examples/codex-memory-plugin/hooks/hooks.json
+++ b/examples/codex-memory-plugin/hooks/hooks.json
@@ -6,7 +6,7 @@
"hooks": [
{
"type": "command",
- "command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/session-start-commit.mjs",
+ "command": "node ${PLUGIN_ROOT}/scripts/session-start-commit.mjs",
"timeout": 70
}
]
@@ -18,7 +18,7 @@
"hooks": [
{
"type": "command",
- "command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/auto-recall.mjs",
+ "command": "node ${PLUGIN_ROOT}/scripts/auto-recall.mjs",
"timeout": 130
}
]
@@ -30,7 +30,7 @@
"hooks": [
{
"type": "command",
- "command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/auto-capture.mjs",
+ "command": "node ${PLUGIN_ROOT}/scripts/auto-capture.mjs",
"timeout": 30
}
]
@@ -42,7 +42,7 @@
"hooks": [
{
"type": "command",
- "command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/pre-compact-capture.mjs",
+ "command": "node ${PLUGIN_ROOT}/scripts/pre-compact-capture.mjs",
"timeout": 60
}
]
diff --git a/examples/codex-memory-plugin/scripts/auto-recall.mjs b/examples/codex-memory-plugin/scripts/auto-recall.mjs
index 922eb3346..8d251ec4f 100644
--- a/examples/codex-memory-plugin/scripts/auto-recall.mjs
+++ b/examples/codex-memory-plugin/scripts/auto-recall.mjs
@@ -214,8 +214,6 @@ function postProcess(items, limit, threshold) {
}
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 };
if (sessionId) body.session_id = sessionId;
const result = await fetchJSON("/api/v1/search/search", {
@@ -225,10 +223,46 @@ async function searchScope(query, targetUri, limit, bucket = "memories", session
return result?.[bucket] || [];
}
+// Candidate target URIs for a bucket, most-specific first. In trusted mode a
+// user's memories live under viking://user/<user>/<bucket>; in api_key mode the
+// server canonicalizes the generic viking://user/<bucket> to the authenticated
+// user. Trying the user-scoped path first with the generic path as a fallback
+// recalls correctly in both modes. De-duped so a missing/blank user never
+// doubles the request count.
+function userScopedTargets(kind) {
+ const suffix = kind.replace(/^\/+/, "");
+ const targets = [`viking://user/${suffix}`];
+ if (cfg.user) {
+ targets.unshift(`viking://user/${cfg.user}/${suffix}`);
+ }
+ return [...new Set(targets)];
+}
+
+// Two-phase, short-circuiting search over the candidate targets:
+// 1) a session-scoped pass (uses OpenViking's session-aware planner);
+// 2) only if the entire session pass is empty, a single session-independent
+// pass (the planner can legitimately decide that no extra context is
+// needed for this session, but auto-recall still needs a memory lookup).
+// Each phase stops at the first non-empty target, so a warm user costs one
+// request and the worst case is bounded by (targets x 2) — instead of running
+// a per-target session+fallback for every target.
+async function searchBucket(query, targetUris, limit, bucket, sessionId = null) {
+ for (const targetUri of targetUris) {
+ const items = await searchScope(query, targetUri, limit, bucket, sessionId);
+ if (items.length > 0) return items;
+ }
+ if (!sessionId) return [];
+ for (const targetUri of targetUris) {
+ const items = await searchScope(query, targetUri, limit, bucket, null);
+ if (items.length > 0) return items;
+ }
+ return [];
+}
+
async function searchAll(query, limit, sessionId = null) {
const [userMems, userSkills] = await Promise.all([
- searchScope(query, "viking://user/memories", limit, "memories", sessionId),
- searchScope(query, "viking://user/skills", limit, "skills", sessionId),
+ searchBucket(query, userScopedTargets("memories"), limit, "memories", sessionId),
+ searchBucket(query, userScopedTargets("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) });
diff --git a/examples/codex-memory-plugin/scripts/auto-recall.test.mjs b/examples/codex-memory-plugin/scripts/auto-recall.test.mjs
index ac8584042..a04529c9d 100644
--- a/examples/codex-memory-plugin/scripts/auto-recall.test.mjs
+++ b/examples/codex-memory-plugin/scripts/auto-recall.test.mjs
@@ -48,8 +48,12 @@ async function withMockOpenViking(handler, fn) {
function runAutoRecall(input, env) {
return new Promise((resolve, reject) => {
+ const cleanEnv = { ...process.env };
+ for (const key of Object.keys(cleanEnv)) {
+ if (key.startsWith("OPENVIKING_")) delete cleanEnv[key];
+ }
const child = spawn(process.execPath, [join(SCRIPT_DIR, "auto-recall.mjs")], {
- env: { ...process.env, ...env },
+ env: { ...cleanEnv, ...env },
stdio: ["pipe", "pipe", "pipe"],
});
let stdout = "";
@@ -133,12 +137,161 @@ test("auto-recall uses context-aware search with the derived OpenViking session
);
});
- assert.equal(requests.length, 2);
+ assert.equal(requests.length, 3);
assert.deepEqual(
- requests.map((request) => request.body.target_uri).sort(),
- ["viking://user/memories", "viking://user/skills"],
+ requests.map((request) => [request.body.target_uri, Boolean(request.body.session_id)]).sort(),
+ [
+ ["viking://user/memories", true],
+ ["viking://user/skills", false],
+ ["viking://user/skills", true],
+ ],
);
- assert.ok(requests.every((request) => request.body.session_id === "cx-codex_123"));
+ } finally {
+ await rm(stateDir, { recursive: true, force: true });
+ }
+});
+
+test("auto-recall expands configured user in memory search target", async () => {
+ const stateDir = await mkdtemp(join(tmpdir(), "ov-auto-recall-user-target-"));
+ 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/zeus/memories") {
+ writeJson(res, {
+ status: "ok",
+ result: {
+ memories: [{
+ uri: "viking://user/zeus/memories/entities/project/example.md",
+ level: 2,
+ score: 0.9,
+ category: "entities",
+ abstract: "configured user 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: "configured user 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 configured user memory", session_id: "codex:456" },
+ {
+ 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_USER: "zeus",
+ 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,
+ /configured user recalled detail/,
+ );
+ });
+
+ assert.equal(requests[0].body.target_uri, "viking://user/zeus/memories");
+ assert.equal(requests[0].body.session_id, "cx-codex_456");
+ } finally {
+ await rm(stateDir, { recursive: true, force: true });
+ }
+});
+
+test("auto-recall preserves explicit default user memory target", async () => {
+ const stateDir = await mkdtemp(join(tmpdir(), "ov-auto-recall-default-user-"));
+ 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/default/memories") {
+ writeJson(res, {
+ status: "ok",
+ result: {
+ memories: [{
+ uri: "viking://user/default/memories/preferences/default-food.md",
+ level: 2,
+ score: 0.9,
+ category: "preferences",
+ abstract: "explicit default user 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: "explicit default user 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 default user memory", session_id: "codex:789" },
+ {
+ 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_USER: "default",
+ 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,
+ /explicit default user recalled detail/,
+ );
+ });
+
+ assert.equal(requests[0].body.target_uri, "viking://user/default/memories");
+ assert.equal(requests[0].body.session_id, "cx-codex_789");
} finally {
await rm(stateDir, { recursive: true, force: true });
}
diff --git a/examples/codex-memory-plugin/scripts/marketplace.test.mjs b/examples/codex-memory-plugin/scripts/marketplace.test.mjs
new file mode 100644
index 000000000..0cf676327
--- /dev/null
+++ b/examples/codex-memory-plugin/scripts/marketplace.test.mjs
@@ -0,0 +1,142 @@
+/**
+ * Contract test for the repo-root Codex marketplace catalog
+ * (.agents/plugins/marketplace.json) and its coherence with this plugin.
+ *
+ * These checks guard the `codex plugin marketplace add <owner>/OpenViking`
+ * install path: the catalog must exist, be valid JSON, point at this plugin,
+ * and the plugin's manifest / hooks / mcp wiring must stay consistent with the
+ * marketplace-install assumptions (native ${PLUGIN_ROOT}, local-default url,
+ * no stale tool names).
+ */
+
+import test from "node:test";
+import assert from "node:assert/strict";
+import { existsSync, readFileSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const scriptsDir = dirname(fileURLToPath(import.meta.url));
+const pluginDir = resolve(scriptsDir, "..");
+const repoRoot = resolve(scriptsDir, "..", "..", "..");
+const catalogPath = join(repoRoot, ".agents", "plugins", "marketplace.json");
+const manifestPath = join(pluginDir, ".codex-plugin", "plugin.json");
+
+const PLUGIN_NAME = "openviking-memory";
+const REAL_MCP_TOOLS = ["search", "store", "read", "list", "grep", "glob", "forget", "add_resource", "health"];
+const LEGACY_TOOL_NAMES = ["openviking_recall", "openviking_store", "openviking_forget", "openviking_health"];
+
+function readJson(path) {
+ return JSON.parse(readFileSync(path, "utf-8"));
+}
+
+// Accept both the string form ("./examples/...") and local object forms
+// ({source:"local",path}); return the ./-stripped path.
+function sourcePath(source) {
+ const raw = typeof source === "string" ? source : (source && typeof source === "object" ? source.path : "");
+ return String(raw || "").replace(/^\.\//, "");
+}
+
+test("repo-root marketplace catalog exists and is valid JSON", () => {
+ assert.ok(existsSync(catalogPath), `missing catalog at ${catalogPath}`);
+ const catalog = readJson(catalogPath);
+ assert.ok(typeof catalog.name === "string" && catalog.name.length > 0, "catalog.name must be a non-empty string");
+ assert.ok(Array.isArray(catalog.plugins) && catalog.plugins.length > 0, "catalog.plugins must be a non-empty array");
+});
+
+test("catalog lists openviking-memory and its source points at this plugin dir", () => {
+ const catalog = readJson(catalogPath);
+ const entry = catalog.plugins.find((p) => p && p.name === PLUGIN_NAME);
+ assert.ok(entry, `catalog must contain a plugin named "${PLUGIN_NAME}"`);
+
+ const rel = sourcePath(entry.source);
+ assert.ok(rel.endsWith("examples/codex-memory-plugin"), `source path must point at examples/codex-memory-plugin, got "${rel}"`);
+ assert.equal(resolve(repoRoot, rel), pluginDir, "catalog source must resolve to this plugin directory");
+});
+
+test("catalog plugin name matches plugin.json name", () => {
+ const catalog = readJson(catalogPath);
+ const entry = catalog.plugins.find((p) => p && p.name === PLUGIN_NAME);
+ const manifest = readJson(manifestPath);
+ assert.equal(entry.name, manifest.name, "marketplace plugin name must equal plugin.json name");
+});
+
+test("catalog policy uses valid Codex install/auth enums", () => {
+ const catalog = readJson(catalogPath);
+ const entry = catalog.plugins.find((p) => p && p.name === PLUGIN_NAME);
+ assert.ok(entry.policy, "plugin entry must declare a policy (Codex needs it to render install controls)");
+ assert.ok(
+ ["NOT_AVAILABLE", "AVAILABLE", "INSTALLED_BY_DEFAULT"].includes(entry.policy.installation),
+ `invalid policy.installation: ${entry.policy.installation}`,
+ );
+ assert.ok(
+ ["ON_INSTALL", "ON_USE"].includes(entry.policy.authentication),
+ `invalid policy.authentication: ${entry.policy.authentication}`,
+ );
+});
+
+test("catalog source is local to the marketplace snapshot", () => {
+ const catalog = readJson(catalogPath);
+ const entry = catalog.plugins.find((p) => p && p.name === PLUGIN_NAME);
+ const src = entry.source;
+ assert.ok(src, "catalog entry must declare a source");
+ if (typeof src === "string") {
+ assert.ok(src.startsWith("./"), `string source must be relative to the marketplace root, got "${src}"`);
+ } else if (typeof src === "object") {
+ assert.equal(src.source, "local", `object source must be a local source, got "${src.source}"`);
+ for (const remote of ["url", "ref", "branch", "tag", "rev", "commit"]) {
+ assert.ok(!(remote in src), `catalog source must not fetch a different Git repo/ref (found "${remote}")`);
+ }
+ assert.ok(typeof src.path === "string" && src.path.startsWith("./"), `object source path must be relative, got "${src.path}"`);
+ } else {
+ assert.fail(`unsupported catalog source type: ${typeof src}`);
+ }
+});
+
+test("required plugin files are present", () => {
+ for (const rel of [".codex-plugin/plugin.json", ".mcp.json", "hooks/hooks.json"]) {
+ assert.ok(existsSync(join(pluginDir, rel)), `missing required plugin file: ${rel}`);
+ }
+});
+
+test("plugin.json describes the real MCP tools, not the legacy names", () => {
+ const manifest = readJson(manifestPath);
+ const longDesc = manifest.interface?.longDescription || "";
+ for (const legacy of LEGACY_TOOL_NAMES) {
+ assert.ok(!longDesc.includes(legacy), `longDescription must not reference legacy tool name "${legacy}"`);
+ }
+ for (const tool of ["search", "add_resource", "health"]) {
+ assert.ok(longDesc.includes(tool), `longDescription should mention real tool "${tool}"`);
+ }
+});
+
+test("hooks.json uses Codex's native ${PLUGIN_ROOT}, not the legacy placeholder", () => {
+ const hooks = readFileSync(join(pluginDir, "hooks", "hooks.json"), "utf-8");
+ assert.ok(hooks.includes("${PLUGIN_ROOT}"), "hooks.json should reference ${PLUGIN_ROOT}");
+ assert.ok(!hooks.includes("__OPENVIKING_PLUGIN_ROOT__"), "hooks.json should not keep the legacy __OPENVIKING_PLUGIN_ROOT__ placeholder");
+ // every hook command should be rooted at ${PLUGIN_ROOT}
+ const parsed = JSON.parse(hooks);
+ const commands = Object.values(parsed.hooks || {})
+ .flat()
+ .flatMap((group) => group.hooks || [])
+ .map((h) => h.command || "");
+ assert.ok(commands.length >= 4, "expected at least 4 hook commands (SessionStart/UserPromptSubmit/Stop/PreCompact)");
+ for (const cmd of commands) {
+ assert.ok(cmd.includes("${PLUGIN_ROOT}/scripts/"), `hook command must be rooted at \${PLUGIN_ROOT}: ${cmd}`);
+ }
+});
+
+test(".mcp.json ships a concrete local-default url and omits bearer by default", () => {
+ const mcp = readJson(join(pluginDir, ".mcp.json"));
+ const server = mcp.mcpServers?.[PLUGIN_NAME];
+ assert.ok(server, `.mcp.json must define mcpServers["${PLUGIN_NAME}"]`);
+ assert.ok(/^https?:\/\//.test(server.url || ""), `.mcp.json url must be a concrete http(s) endpoint, got "${server.url}"`);
+ assert.ok(!String(server.url).includes("__OPENVIKING_MCP_URL__"), ".mcp.json must not keep the legacy url placeholder");
+ // Codex hard-fails MCP startup if bearer_token_env_var points at an unset var,
+ // so the checked-in (marketplace-default, unauthenticated) file must omit it.
+ assert.ok(!("bearer_token_env_var" in server), "checked-in .mcp.json should omit bearer_token_env_var for the local-default install");
+});
+
+test("plugin.json keeps the canonical tool list available for reference", () => {
+ // Sanity: the documented tool set is the one we assert against above.
+ assert.equal(REAL_MCP_TOOLS.length, 9);
+});
diff --git a/examples/codex-memory-plugin/setup-helper/install.sh b/examples/codex-memory-plugin/setup-helper/install.sh
index 5239ea728..8fe361a9f 100755
--- a/examples/codex-memory-plugin/setup-helper/install.sh
+++ b/examples/codex-memory-plugin/setup-helper/install.sh
@@ -365,24 +365,29 @@ render_plugin_cache() {
rm -rf "$CACHE_DIR"
cp -R "$PLUGIN_DIR" "$CACHE_DIR"
- # Codex 0.130 does not inject CODEX_PLUGIN_ROOT into hook subprocess env and
- # does not let hooks.json declare a cwd, so relative paths in hooks.json
- # resolve against the user's cwd (typically ~). Render the placeholder
- # __OPENVIKING_PLUGIN_ROOT__ into the cache copy's absolute path. The repo's
- # checked-in hooks.json keeps the placeholder; only the cached copy is
- # rewritten at install time.
+ # The repo's checked-in hooks.json uses Codex's native ${PLUGIN_ROOT} token,
+ # which modern Codex injects into hook env AND substitutes inline in hook
+ # command strings (so a plain `codex plugin marketplace add` install works
+ # with no rendering). Older Codex (<=0.130) neither injects CODEX_PLUGIN_ROOT
+ # nor substitutes ${PLUGIN_ROOT}, so for this installer-managed cache copy we
+ # still render ${PLUGIN_ROOT} to an absolute path — harmless on modern Codex
+ # (no token left to substitute) and required on old Codex.
local hooks_json="$CACHE_DIR/hooks/hooks.json"
if [ -f "$hooks_json" ]; then
local cache_esc
cache_esc="$(printf '%s' "$CACHE_DIR" | sed -e 's/[\\/&]/\\&/g')"
- sed -i.bak -e "s/__OPENVIKING_PLUGIN_ROOT__/$cache_esc/g" "$hooks_json"
+ sed -i.bak -e "s/\${PLUGIN_ROOT}/$cache_esc/g" "$hooks_json"
rm -f "${hooks_json}.bak"
fi
- # Render the OpenViking /mcp URL into the cached .mcp.json (and drop the
- # bearer_token_env_var line in no-auth mode). The repo's checked-in
- # .mcp.json keeps the placeholder + always-present bearer field; the cache
- # copy is what Codex actually loads.
+ # Render the OpenViking /mcp URL into the cached .mcp.json (and add the
+ # bearer_token_env_var line when an API key is configured). The repo's
+ # checked-in .mcp.json ships a local-default url with NO bearer field, so a
+ # plain `codex plugin marketplace add` install connects to unauthenticated
+ # local OV out of the box (Codex hard-fails MCP startup if
+ # bearer_token_env_var points at an unset/empty var). For this installer
+ # path, sync-mcp overwrites the url and adds bearer/identity headers based on
+ # the active ovcli.conf; the cache copy is what Codex actually loads.
local mcp_json="$CACHE_DIR/.mcp.json"
if [ -f "$mcp_json" ]; then
OPENVIKING_CLI_CONFIG_FILE="$OVCLI_CONF" OPENVIKING_MCP_URL="$MCP_URL" \
@@ -607,7 +612,7 @@ validate_plugin_install() {
if [ ! -f "$hooks_json" ]; then
issues+=("cached hooks.json missing")
else
- grep -q "__OPENVIKING_PLUGIN_ROOT__" "$hooks_json" && issues+=("cached hooks.json still contains __OPENVIKING_PLUGIN_ROOT__")
+ grep -qF '${PLUGIN_ROOT}' "$hooks_json" && issues+=("cached hooks.json still contains unrendered \${PLUGIN_ROOT}")
grep -q "$CACHE_DIR/scripts/session-start-commit.mjs" "$hooks_json" || issues+=("SessionStart hook path is not rendered to cache dir")
grep -q '"matcher": "clear|startup|resume"' "$hooks_json" || issues+=("SessionStart matcher is not clear|startup|resume")
grep -q '"timeout": 70' "$hooks_json" || issues+=("SessionStart timeout is not 70s")
@@ -616,7 +621,7 @@ validate_plugin_install() {
if [ ! -f "$mcp_json" ]; then
issues+=("cached .mcp.json missing")
else
- grep -q "__OPENVIKING_MCP_URL__" "$mcp_json" && issues+=("cached .mcp.json still contains __OPENVIKING_MCP_URL__")
+ grep -q '"url"[[:space:]]*:[[:space:]]*"http' "$mcp_json" || issues+=("cached .mcp.json is missing a concrete http(s) url")
if [ "$HAS_API_KEY" != "1" ] && grep -q "bearer_token_env_var" "$mcp_json"; then
issues+=("cached .mcp.json keeps bearer_token_env_var without configured API key")
fi