Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
[codex] tighten memory recall, capture, and resume (#2598)
Zayn Jarvisc6990e4cd6cb
diff --git a/docs/en/agent-integrations/04-codex.md b/docs/en/agent-integrations/04-codex.mdindex 0e2fb463e..d1d144df7 100644--- a/docs/en/agent-integrations/04-codex.md+++ b/docs/en/agent-integrations/04-codex.md@@ -32,7 +32,7 @@ codex # First run: approve hooks once when prompted via /hooksPrerequisites: Node.js >= 22, Codex >= 0.130.0, and the `codex_hooks` feature enabled.-1. **Shell function wrapper** — Append a `codex()` function to your shell profile (e.g., `.bashrc` or `.zshrc`) to inject OpenViking environment variables from `ovcli.conf`. See the [plugin README](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/README.md) for the full function.+1. **Shell function wrapper** — Source the plugin wrapper from your shell profile (e.g., `.bashrc` or `.zshrc`) so Codex receives the active `ovcli.conf` credentials, MCP is re-rendered, and stale inherited credential env vars are stripped. See the [plugin README](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/README.md) for the snippet.2. **Plugin installation** — Register a local marketplace and enable the plugin. See `setup-helper/install.sh` for the exact commands.@@ -46,7 +46,7 @@ Prerequisites: Node.js >= 22, Codex >= 0.130.0, and the `codex_hooks` feature entype codex # Expectation: codex is a shell function```-> If the previous command printed a path instead of `shell function`, the wrapper isn't active yet. Re-source it (or open a new terminal) before launching, otherwise codex starts without `OPENVIKING_API_KEY` and reports `MCP server is not logged in`.+> If the previous command printed a path instead of `shell function`, the wrapper isn't active yet. Re-source it (or open a new terminal) before launching, otherwise Codex may start without the credentials needed by MCP.Once inside Codex, the plugin should seamlessly recall memories on every prompt. Set `OPENVIKING_DEBUG=1` to write events to `~/.openviking/logs/codex-hooks.log`.@@ -59,12 +59,14 @@ The plugin integrates with Codex's lifecycle by hooking into key events. It sear<details><summary><b>Configuration</b></summary>-Configuration priority: Environment variables > `ovcli.conf` > `ov.conf` > Built-in defaults (`http://127.0.0.1:1933`, no authentication).+Credential source: active `ovcli.conf` wins by default (`OPENVIKING_CLI_CONFIG_FILE` or `~/.openviking/ovcli.conf`), so `ov config switch <name>` changes hooks, MCP, and child `ov` commands together on the next launch. Set `OPENVIKING_CREDENTIAL_SOURCE=env` only when you intentionally want env vars to override the CLI config; the wrapper then writes a mode-0600 runtime ovcli config under `~/.openviking/codex-plugin-state/` so child `ov` commands still match. Without an ovcli config, env vars then `ov.conf` then built-in defaults are used.| Env Var | Default | Description ||---------|---------|-------------|| `OPENVIKING_URL` / `OPENVIKING_BASE_URL` | — | Full server URL || `OPENVIKING_API_KEY` | — | API key (sent as `Authorization: Bearer`) |+| `OPENVIKING_CLI_CONFIG_FILE` | `~/.openviking/ovcli.conf` | Active CLI config to use for hooks, MCP, and child `ov` commands |+| `OPENVIKING_CREDENTIAL_SOURCE` | `auto` | Set `env` to force env-var credentials instead of active ovcli config || `OPENVIKING_CODEX_ACTIVE_WINDOW_MS` | `120000` | SessionStart active-window threshold || `OPENVIKING_CODEX_IDLE_TTL_MS` | `1800000` | SessionStart idle-TTL sweep threshold || `OPENVIKING_DEBUG` | `false` | Write logs to `~/.openviking/logs/codex-hooks.log` |@@ -77,13 +79,13 @@ Additional tuning options (e.g., `OPENVIKING_RECALL_LIMIT`, `OPENVIKING_CAPTURE_| Symptom | Cause | Fix ||---------|-------|-----|-| `MCP server is not logged in` | `OPENVIKING_API_KEY` not in env at launch | Ensure the `codex()` shell function is sourced and `ovcli.conf` contains a valid `api_key`. |+| `MCP server is not logged in` | Credentials were not injected at Codex launch, or the active ovcli config has no `api_key` for an authenticated server | Ensure the `codex()` shell function is sourced and `ovcli.conf` contains a valid `api_key`. || `type codex` shows a path instead of a shell function (wrapper inactive) | The rc wasn't `source`d after install, or you launched from a terminal that didn't load it | Run `source ~/.zshrc` (or `~/.bashrc` on bash), or open a new terminal || Launching via an alias (e.g. `cx`) injects no credentials | The alias *name* was listed in `OPENVIKING_CODEX_WRAP_EXTRA` (alias names are skipped), or the alias's target command isn't wrapped | Wrap the command the alias points to, not the alias: `alias cx=codex` needs nothing; for `alias cx=codex-custom`, add `codex-custom` || `4 hooks need review` | Security review on first launch | Run `/hooks` within Codex and approve the hooks. || `hook (failed) exited with code 1` | Stale placeholders in the plugin cache | Re-run the one-line installer. || Recall returns nothing | Server is unreachable or the URL is incorrect | Check the endpoint: `curl "$(jq -r '.url' ~/.openviking/ovcli.conf)/health"` |-| Hook 401 but MCP works (or vice versa) | Mismatch between environment variables and `ovcli.conf` | Hooks re-read `ovcli.conf` on every execution, whereas MCP reads environment variables only at startup. Restart Codex to sync. |+| Hook 401 but MCP works (or vice versa) | Cached MCP config or launch env is stale | Restart Codex through the wrapper. If you intentionally use env credentials, set `OPENVIKING_CREDENTIAL_SOURCE=env`; otherwise use `ov config switch <name>` or `OPENVIKING_CLI_CONFIG_FILE`. |## See alsodiff --git a/docs/zh/agent-integrations/04-codex.md b/docs/zh/agent-integrations/04-codex.mdindex 02791c82f..fe0baf2f6 100644--- a/docs/zh/agent-integrations/04-codex.md+++ b/docs/zh/agent-integrations/04-codex.md@@ -32,7 +32,7 @@ codex # 首次启动需进入 /hooks 完成一次审批前置条件:需安装 Node.js >= 22、Codex >= 0.130.0,并启用 `codex_hooks` 特性。-1. **Shell 函数封装** — 在 shell 的配置文件(如 rc 文件)中追加一个 `codex()` 函数,确保每次调用时都能从 `ovcli.conf` 注入 OpenViking 相关的环境变量。完整的函数代码请参考 [插件 README](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/README.md)。+1. **Shell 函数封装** — 在 shell 的配置文件(如 rc 文件)中 source 插件 wrapper,确保 Codex 使用当前激活的 `ovcli.conf` 凭据,同时刷新 MCP 配置并清掉继承来的过期凭据环境变量。代码片段请参考 [插件 README](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/README.md)。2. **插件安装** — 注册本地 marketplace 并启用插件。具体执行命令请参见 `setup-helper/install.sh`。@@ -46,7 +46,7 @@ codex # 首次启动需进入 /hooks 完成一次审批type codex # 期望输出:codex is a shell function```-> 若上一步输出的是一个路径而非 `shell function`,说明 wrapper 尚未生效,请先 `source` 那行 wrapper(或新开一个终端)再启动;否则 codex 启动时拿不到 `OPENVIKING_API_KEY`,会报 `MCP server is not logged in`。+> 若上一步输出的是一个路径而非 `shell function`,说明 wrapper 尚未生效,请先 `source` 那行 wrapper(或新开一个终端)再启动;否则 Codex 可能拿不到 MCP 所需凭据。进入 Codex 后,插件将在每次用户输入前自动召回记忆。若设置环境变量 `OPENVIKING_DEBUG=1`,则会将相关事件日志写入 `~/.openviking/logs/codex-hooks.log`。@@ -59,12 +59,14 @@ type codex # 期望输出:codex is a shell function<details><summary><b>配置</b></summary>-配置优先级为:环境变量 > `ovcli.conf` > `ov.conf` > 内置默认值(默认 URL 为 `http://127.0.0.1:1933`,无鉴权)。+凭据来源:默认使用当前激活的 `ovcli.conf`(`OPENVIKING_CLI_CONFIG_FILE` 或 `~/.openviking/ovcli.conf`),因此 `ov config switch <name>` 会在下次启动时同时影响 hook、MCP 和 Codex 内部运行的 `ov` 命令。只有明确希望环境变量覆盖 CLI 配置时,才设置 `OPENVIKING_CREDENTIAL_SOURCE=env`;此时 wrapper 会在 `~/.openviking/codex-plugin-state/` 下写入 mode 0600 的运行时 ovcli 配置,让内部 `ov` 命令仍然使用同一套凭据。若没有 ovcli 配置,则依次回退到环境变量、`ov.conf` 和内置默认值。| 环境变量 | 默认值 | 说明 ||---------|--------|------|| `OPENVIKING_URL` / `OPENVIKING_BASE_URL` | — | 完整的服务器 URL || `OPENVIKING_API_KEY` | — | API 密钥(将通过 `Authorization: Bearer` 标头发送) |+| `OPENVIKING_CLI_CONFIG_FILE` | `~/.openviking/ovcli.conf` | hook、MCP 和 Codex 内部 `ov` 命令共同使用的当前 CLI 配置 |+| `OPENVIKING_CREDENTIAL_SOURCE` | `auto` | 设置为 `env` 时强制使用环境变量凭据 || `OPENVIKING_CODEX_ACTIVE_WINDOW_MS` | `120000` | `SessionStart` 活动窗口阈值(毫秒) || `OPENVIKING_CODEX_IDLE_TTL_MS` | `1800000` | `SessionStart` 闲置 TTL 清理阈值(毫秒) || `OPENVIKING_DEBUG` | `false` | 是否将日志写入 `~/.openviking/logs/codex-hooks.log` |@@ -77,13 +79,13 @@ type codex # 期望输出:codex is a shell function| 现象 | 可能原因 | 修复方法 ||------|------|------|-| `MCP server is not logged in` | 启动时环境变量中缺失 `OPENVIKING_API_KEY` | 确认已 source `codex()` 函数,且 `ovcli.conf` 中配置了 `api_key` |+| `MCP server is not logged in` | Codex 启动时未注入凭据,或当前 ovcli 配置没有 authenticated server 所需的 `api_key` | 确认已 source `codex()` 函数,且 `ovcli.conf` 中配置了 `api_key` || `type codex` 显示的是路径而非 shell function(wrapper 未生效) | 安装后未 `source` rc,或在未加载该 rc 的终端里启动 | 执行 `source ~/.zshrc`(bash 用 `~/.bashrc`),或新开一个终端窗口 || 通过别名(如 `cx`)启动,凭据未注入 | 把别名名填进了 `OPENVIKING_CODEX_WRAP_EXTRA`(别名会被跳过),或别名指向的命令未被封装 | 封装别名指向的真实命令而非别名本身:`alias cx=codex` 无需配置;`alias cx=codex-custom` 则把 `codex-custom` 填入 || `4 hooks need review` | 首次启动需要进行安全审批 | 在 Codex 终端内输入 `/hooks` 完成审批 || 审批后仍提示 `hook (failed) exited with code 1` | 缓存文件中的占位符未被正确渲染 | 重新执行一次一键安装脚本 || 召回结果为空 | 服务器不可达或 URL 配置错误 | 执行 `curl "$(jq -r '.url' ~/.openviking/ovcli.conf)/health"` 检查服务器状态 |-| Hook 报 401 但 MCP 正常可用,或反之 | 环境变量与 `ovcli.conf` 的配置不一致 | Hook 每次触发均会重新读取 `ovcli.conf`,而 MCP 仅在启动时读取环境变量。请修改配置并重启 Codex。 |+| Hook 报 401 但 MCP 正常可用,或反之 | MCP 缓存配置或启动环境已过期 | 通过 wrapper 重启 Codex。若确实要使用环境变量凭据,设置 `OPENVIKING_CREDENTIAL_SOURCE=env`;否则使用 `ov config switch <name>` 或 `OPENVIKING_CLI_CONFIG_FILE`。 |## 参见diff --git a/examples/codex-memory-plugin/.mcp.json b/examples/codex-memory-plugin/.mcp.jsonindex f5a0e1719..99e3bc9c5 100644--- a/examples/codex-memory-plugin/.mcp.json+++ b/examples/codex-memory-plugin/.mcp.json@@ -5,7 +5,8 @@"bearer_token_env_var": "OPENVIKING_API_KEY","env_http_headers": {"X-OpenViking-Account": "OPENVIKING_ACCOUNT",- "X-OpenViking-User": "OPENVIKING_USER"+ "X-OpenViking-User": "OPENVIKING_USER",+ "X-OpenViking-Actor-Peer": "OPENVIKING_PEER_ID"}}}diff --git a/examples/codex-memory-plugin/DESIGN.md b/examples/codex-memory-plugin/DESIGN.mdindex 1244ddf7c..02d7077de 100644--- a/examples/codex-memory-plugin/DESIGN.md+++ b/examples/codex-memory-plugin/DESIGN.md@@ -27,7 +27,7 @@ events imply "context for a particular codex `session_id` is gone".| Codex event | Fires when | What we learn ||---|---|---|| `SessionStart` source=`startup` | fresh codex process; `/new`; zouk daemon spawn-without-sessionId; zouk reset | new `session_id` was created |-| `SessionStart` source=`resume` | `/resume`; short reconnect; zouk daemon spawn-with-sessionId | same `session_id` continues |+| `SessionStart` source=`resume` | `/resume`; short reconnect; zouk daemon spawn-with-sessionId | same `session_id` continues; may need archive continuity || `SessionStart` source=`clear` | `/clear` (creates a fresh thread, preserves prior thread on disk as resumable) | new `session_id`; previous one orphaned || `UserPromptSubmit` | every user turn before model | recall context inject || `Stop` | end of every model turn (NOT end of session) | append turns to OV session |@@ -90,12 +90,25 @@ fired and bumped `lastUpdatedAt`; we commit it. The multi-recent caseimplies concurrent codex sessions are active; we can't tell which one (ifany) ended, so we defer to idle TTL to clean up genuinely-dead ones.-### 4. `SessionStart` source=`resume` — never commits+### 4. `SessionStart` source=`resume` — never commits, optional archive injectShort reconnects and `/resume` re-fire `SessionStart` for the same`session_id`. Committing here would seal a still-active session. So`resume` is a no-op for commit purposes.+Resume may still need continuity after `PreCompact` or idle sweep already+committed the live OV session. If local state has `ovSessionId = null`+(or no state file remains), the hook derives `cx-<codex-session-id>`,+calls `GET /api/v1/sessions/{id}/context?token_budget=...`, and injects+`latest_archive_overview` via `hookSpecificOutput.additionalContext` when+present. The injected block includes+`viking://user/sessions/{id}/history/` so the model can use OpenViking MCP+read/search tools for exact prior details.++If local state still has a live `ovSessionId`, resume injection is skipped:+the session is appendable and Codex should already be resuming its own+transcript.+### 5. Idle TTL sweep — fallbackState files whose `lastUpdatedAt` is older than `IDLE_TTL_MS` (default 30@@ -131,6 +144,27 @@ and appends each new user/assistant turn to the OV session for this codexState is updated:`{ovSessionId, capturedTurnCount, lastUpdatedAt: now}`. Never commits.+## 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:++```text+<openviking-context source="auto-recall" format="digest">+OpenViking memory digest:+- ...+</openviking-context>+```++The compressor is still instructed not to generate XML/HTML wrappers. The+wrapper is added by the hook after compression so capture can strip it+mechanically. Legacy `<relevant-memory>` / `<relevant-memories>` blocks and+unwrapped `OpenViking memory digest:` blocks are stripped as backward+compatibility fallbacks.+## Edge cases handled### Post-compact transcript shrink@@ -191,45 +225,87 @@ Env var overrides for tuning without rebuilding:| `OPENVIKING_CODEX_STATE_DIR` | `~/.openviking/codex-plugin-state` | state file dir || `OPENVIKING_CODEX_ACTIVE_WINDOW_MS` | `120000` (2 min) | rule-3 active window || `OPENVIKING_CODEX_IDLE_TTL_MS` | `1800000` (30 min) | idle sweep TTL |+| `OPENVIKING_RECALL_TIMEOUT_MS` | `120000` (2 min) | whole UserPromptSubmit auto-recall deadline |+| `OPENVIKING_RECALL_COMPRESS` | `1` | set `0` / `off` to skip `codex exec` compression |+| `OPENVIKING_RECALL_COMPRESS_MODEL` | unset | custom first-choice compressor model; `off` disables compression |+| `OPENVIKING_RECALL_COMPRESS_THINKING` | unset | custom `model_reasoning_effort`; `default` means omit override; alias `OPENVIKING_RECALL_COMPRESS_REASONING_EFFORT` |+| `OPENVIKING_RECALL_COMPRESS_DETECT_ON_STARTUP` | `1` | recreate/cache compressor profile during every `SessionStart` |+| `OPENVIKING_RECALL_COMPRESS_DETECT_TIMEOUT_MS` | `15000` | per-candidate compressor probe timeout |+| `OPENVIKING_RECALL_COMPRESS_DETECT_TTL_MS` | `604800000` (7 days) | cache TTL used by `UserPromptSubmit` reads |+| `OPENVIKING_RESUME_ARCHIVE_INJECT` | `1` | inject latest archive summary on `source=resume` when no live OV session is open |+| `OPENVIKING_RESUME_ARCHIVE_TOKEN_BUDGET` | `32000` | token budget for `/sessions/{id}/context` on resume |+| `OPENVIKING_RESUME_ARCHIVE_MAX_CHARS` | `6000` | max chars injected from latest archive overview |+| `OPENVIKING_CAPTURE_TOOL_MAX_CHARS` | `2000` | max chars retained per compressed tool call/result || `OPENVIKING_DEBUG` | `0` | enable hook debug log |-## Phase 2: resume context inject (not yet implemented)+## Resume context inject++`SessionStart` `source=resume` runs only the archive-inject path above. It+never commits and never runs idle sweep. This keeps short reconnects cheap+while still restoring continuity after a committed archive. The API shape+is the existing session context endpoint; no archive listing UX is required+for the model.++Injected context is intentionally a summary, not raw history. If exact+commands, file paths, code snippets, config values, or tool outputs matter,+the injected `viking://` URI tells the model to use OpenViking MCP+read/search tools.++## Recall compressor profile++`codex exec` supports `--model` / `-m`, and Codex config overrides such as+`model_reasoning_effort` are passed with `-c`. The recall compressor uses+both:++```bash+codex -m <model> -c 'model_reasoning_effort="low"' exec ...+```++`thinking=default` omits the `model_reasoning_effort` override. This is+important for model families whose default effort is tuned by Codex.++Model availability is re-probed at every `SessionStart`, not in every+`UserPromptSubmit`. Recreating the profile on each session start catches+cross-session env/config changes. The detector writes+`recall-compressor-profile.json` under `OPENVIKING_CODEX_STATE_DIR` and+auto-recall reads that cache. Cache misses in auto-recall use the first+candidate directly and fall back to deterministic digest if `codex exec`+fails.-When `SessionStart` source=`resume` fires for a codex `session_id` whose-state shows `ovSessionId = null` (already committed via idle TTL or-PreCompact), we have no live OV session to resume into. The model loses-continuity unless the most recent committed memories are surfaced.+Fallback order:-Proposed flow:-1. Load state for the resumed `session_id`. If `ovSessionId` is non-null,- no action — the session is still appendable.-2. Otherwise list `viking://user/sessions/cx-<codex-session-id>/history/archive_*/`- on the OV server, take the most recent.-3. Read its abstract (L0) / overview (L1).-4. Emit via `hookSpecificOutput.additionalContext` so codex injects the- summary into the resumed turn.+1. configured model/thinking (`OPENVIKING_RECALL_COMPRESS_MODEL` ++ `OPENVIKING_RECALL_COMPRESS_THINKING`)+2. `gpt-5.3-codex-spark`, thinking `default`+3. `gpt-5.5`, thinking `low`+4. off (deterministic digest, no child `codex exec`)-Deferred because (a) it requires a new OV API call shape, (b) the failure-mode is acceptable in v0.3 (model just lacks continuity for one turn,-recovers via auto-recall), and (c) the core commit logic above must be-proven first.+Configured `off` (`OPENVIKING_RECALL_COMPRESS=0`, model `off`, or thinking+`off`) skips all probing and writes a disabled profile.## What changed vs v0.3.1-- `SessionStart` matcher widened from `"clear"` to `"clear|startup"` so the- active-window heuristic runs on both /clear and /new (and zouk reset).+- `SessionStart` matcher widened from `"clear"` to `"clear|startup|resume"`+ so the active-window heuristic runs on /clear and /new (and zouk reset),+ while `/resume` can inject latest archive context without commit/sweep.- `session-start-commit.mjs` switches commit logic from "all non-current"to active-window heuristic.- Idle TTL sweep brought back, but only at the tail of`session-start-commit.mjs` (not every `Stop`). Default TTL 30 min.- `auto-capture.mjs` Stop hook guards against post-compact transcriptshrink (resets `capturedTurnCount` to 0 if `allTurns.length` < cached).+- Capture parsing shared by Stop and PreCompact now filters obvious hook+ noise, strips deterministic OpenViking context wrappers, and compresses+ tool calls/results instead of dropping them or storing full blobs.+- `auto-recall.mjs` has a whole-hook timeout (default 2 min) in addition+ to per-request timeouts.+- Recall compression model selection is recreated at each SessionStart and+ cached so each user prompt does not probe Codex model availability.- All commit failure paths preserve state instead of clearing.- All state writes go through tmpfile + rename for crash safety.## Open questions / future work-- **Phase 2 resume context inject** (above).- **MCP tool `openviking_commit_pending`**: explicit commit for the modelto call, useful when user knows they're about to exit.- **Subagent hook events**: kimicode has them, codex doesn't yet.diff --git a/examples/codex-memory-plugin/README.md b/examples/codex-memory-plugin/README.mdindex 59f1efda2..4de6b9d1b 100644--- a/examples/codex-memory-plugin/README.md+++ b/examples/codex-memory-plugin/README.md@@ -7,7 +7,7 @@ This is the Codex counterpart to [`claude-code-memory-plugin`](../claude-code-me- **Auto-recall** relevant memories on every `UserPromptSubmit` and inject them via `hookSpecificOutput.additionalContext`- **Incremental capture on `Stop`** (turn end): append the new user/assistant turns to a deterministic OpenViking session id `cx-<codex_session_id>`. No commit per turn.- **Commit on `PreCompact`**: trigger OpenViking's memory extractor on the full pre-compact transcript before Codex summarizes it.-- **Commit on `SessionStart` (source=startup|clear)**: active-window heuristic — if exactly one *other* state file was touched within the last 2 min, commit it (the just-ended session). On `≥2`, defer to idle-TTL sweep at the tail. `source=resume` is a hard no-op (short reconnects re-fire `resume` and we don't want to commit a still-active session). See `DESIGN.md` for the full decision tree.+- **Commit on `SessionStart` (source=startup|clear)**: active-window heuristic — if exactly one *other* state file was touched within the last 2 min, commit it (the just-ended session). On `≥2`, defer to idle-TTL sweep at the tail. `source=resume` never commits or sweeps; if the live OV session was already committed, it may inject the latest archive summary for continuity. See `DESIGN.md` for the full decision tree.It also wires Codex up to OpenViking's native `/mcp` endpoint (streamable HTTP, Bearer auth), so the model has direct access to the `search`, `store`, `read`, `list`, `grep`, `glob`, `forget`, `add_resource`, and `health` tools — no local MCP server process to maintain.@@ -24,9 +24,9 @@ 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 from `ovcli.conf` (or `OPENVIKING_URL`)+4. Renders the cached `.mcp.json` URL using the shared credential resolver5. Renders the cached `hooks.json` with absolute script paths (Codex 0.130 doesn't inject `CODEX_PLUGIN_ROOT` into hook env)-6. Appends a `codex()` shell function to your rc that pulls `OPENVIKING_API_KEY` / `OPENVIKING_ACCOUNT` / `OPENVIKING_USER` from `ovcli.conf` at invocation — keeps the key out of `.mcp.json` on disk+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 varsAfter install:@@ -39,42 +39,11 @@ codex # first run: review /hooks onceIf you don't want the installer touching your rc, do these three things yourself:-1. **Wire a `codex()` shell function** that injects OpenViking creds at invocation time. The installer-emitted version (see `setup-helper/install.sh`) additionally re-renders the cached `.mcp.json` bearer field on each launch — required if you swap `OPENVIKING_CLI_CONFIG_FILE` between configs with and without `api_key`. A simpler equivalent for a fixed config:+1. **Wire the plugin shell wrapper** so Codex gets the same active credentials as the `ov` CLI. The wrapper calls `scripts/ov-credentials.mjs`, re-renders the cached `.mcp.json` bearer field on each launch, and launches Codex with stale credential env vars stripped before the resolved values are added back:```bash- codex() {- local _ov_conf="${OPENVIKING_CLI_CONFIG_FILE:-$HOME/.openviking/ovcli.conf}"- local _ov_url _ov_key _ov_account _ov_user- if [ -f "$_ov_conf" ] && command -v node >/dev/null 2>&1; then- local _ov_env- _ov_env=$(node -e '- try {- const c = JSON.parse(require("node:fs").readFileSync(process.argv[1], "utf8"));- const out = (k, v) => v ? `${k}=${JSON.stringify(String(v))}\n` : "";- process.stdout.write(- out("OV_URL", c.url) +- out("OV_KEY", c.api_key) +- out("OV_ACCOUNT", c.account) +- out("OV_USER", c.user)- );- } catch {}- ' "$_ov_conf" 2>/dev/null)- eval "$_ov_env"- fi- _ov_url="${OPENVIKING_URL:-${OV_URL:-}}"- _ov_key="${OPENVIKING_API_KEY:-${OV_KEY:-}}"- _ov_account="${OPENVIKING_ACCOUNT:-${OV_ACCOUNT:-}}"- _ov_user="${OPENVIKING_USER:-${OV_USER:-}}"- unset OV_URL OV_KEY OV_ACCOUNT OV_USER- # Build env-prefix dynamically so empty values are NOT passed as empty- # strings — Codex hard-fails on empty bearer_token_env_var targets.- local -a _env_args=()- [ -n "$_ov_url" ] && _env_args+=("OPENVIKING_URL=$_ov_url")- [ -n "$_ov_key" ] && _env_args+=("OPENVIKING_API_KEY=$_ov_key")- [ -n "$_ov_account" ] && _env_args+=("OPENVIKING_ACCOUNT=$_ov_account")- [ -n "$_ov_user" ] && _env_args+=("OPENVIKING_USER=$_ov_user")- env "${_env_args[@]}" codex "$@"- }+ [ -f "$HOME/.openviking/openviking-repo/examples/codex-memory-plugin/setup-helper/wrapper.sh" ] \+ && . "$HOME/.openviking/openviking-repo/examples/codex-memory-plugin/setup-helper/wrapper.sh"```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.@@ -83,22 +52,22 @@ If you don't want the installer touching your rc, do these three things yourself## Configuration-Connection / identity resolution order (highest to lowest, applies to both hooks and MCP):+Connection / identity source (applies to hooks, MCP, and `ov` commands run inside Codex):-1. **Environment variables**: `OPENVIKING_URL` / `OPENVIKING_BASE_URL`, `OPENVIKING_API_KEY` / `OPENVIKING_BEARER_TOKEN`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, `OPENVIKING_PEER_ID`-2. **`ovcli.conf`**: `~/.openviking/ovcli.conf` or `OPENVIKING_CLI_CONFIG_FILE`-3. **`ov.conf`**: `~/.openviking/ov.conf` or `OPENVIKING_CONFIG_FILE` (only `server.url` / `server.root_api_key` as connection fallback; tuning fields under a legacy `codex.*` block are honored but deprecated — see [Tuning the plugin](#tuning-the-plugin))-4. **Built-in defaults**: `http://127.0.0.1:1933`, unauthenticated+1. **Default**: active `ovcli.conf` wins when present: `OPENVIKING_CLI_CONFIG_FILE` or `~/.openviking/ovcli.conf`. Use `ov config switch <name>` to change the active credentials for the CLI, hooks, MCP, and child `ov` commands together.+2. **Env-forced**: set `OPENVIKING_CREDENTIAL_SOURCE=env` to force `OPENVIKING_URL` / `OPENVIKING_BASE_URL`, `OPENVIKING_API_KEY` / `OPENVIKING_BEARER_TOKEN`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, and `OPENVIKING_PEER_ID`.+3. **Fallback**: without an ovcli config, env vars are used; then `ov.conf` (`server.url` / `server.root_api_key` plus legacy `codex.*` tuning); then `http://127.0.0.1:1933` unauthenticated.-The shell function wrapper handles step 1 for you by promoting ovcli.conf fields into env vars before exec'ing codex. Hooks then re-resolve the full chain inside Node; the MCP server URL is baked into `.mcp.json` at install time and the API key flows in via `OPENVIKING_API_KEY` (referenced by `bearer_token_env_var` in `.mcp.json`).+The shell wrapper promotes the resolved ovcli credentials into env vars before exec'ing Codex because Codex's MCP runtime can only read auth from env. Hooks call the same resolver directly. The wrapper also exports `OPENVIKING_CLI_CONFIG_FILE`, so an `ov ...` command run inside Codex uses the same active config.+When credentials are forced from env, the wrapper materializes a mode-0600 runtime ovcli config under `~/.openviking/codex-plugin-state/` and points `OPENVIKING_CLI_CONFIG_FILE` at it, so child `ov` commands still use the same credentials as hooks and MCP.Auth is sent as `Authorization: Bearer <api_key>` to both the REST API (used by hooks) and the `/mcp` endpoint (used by the model).-Set `OPENVIKING_PEER_ID` when multiple Codex peers share the same OpenViking user and should keep separate peer memory. Recall passes it as `X-OpenViking-Actor-Peer`; captured session messages store it as `peer_id`. The legacy `codex.peerId` / `codex.peer_id` fields in `ov.conf` are also honored, but env vars are preferred.+Set `actor_peer_id` in `ovcli.conf` (or `OPENVIKING_PEER_ID` with `OPENVIKING_CREDENTIAL_SOURCE=env`) when multiple Codex peers share the same OpenViking user and should keep separate peer memory. Hooks pass it as `peer_id` for captured session messages and as `X-OpenViking-Actor-Peer` for retrieval/filesystem calls; MCP gets the same header mapping. The legacy `codex.peerId` / `codex.peer_id` fields in `ov.conf` still resolve as a fallback.For **unauthenticated local OV** (`ovcli.conf` without `api_key`, or no ovcli.conf at all), `.mcp.json` is rendered *without* `bearer_token_env_var`. Codex 0.130 hard-fails MCP startup with `Environment variable ... is empty` if `bearer_token_env_var` points at an empty/unset env var, so it must be omitted entirely when there's no key.-The `codex()` shell-function wrapper **re-renders this field on every codex launch** based on the currently-active `ovcli.conf` (the one `OPENVIKING_CLI_CONFIG_FILE` points at, falling back to `~/.openviking/ovcli.conf`). That means you can switch between authenticated and unauthenticated OV — e.g. to isolate a benchmark run from production memory — by just changing `OPENVIKING_CLI_CONFIG_FILE` before invoking `codex`, with no re-install needed. The wrapper also omits empty env-var assignments entirely (so `OPENVIKING_API_KEY=` is never passed to codex), keeping `env_http_headers` for identity (`X-OpenViking-Account` / `X-OpenViking-User`) intact.+The `codex()` shell-function wrapper **re-renders this field on every codex launch** based on the currently-active `ovcli.conf` (the one `OPENVIKING_CLI_CONFIG_FILE` points at, falling back to `~/.openviking/ovcli.conf`). That means you can switch between authenticated and unauthenticated OV — e.g. to isolate a benchmark run from production memory — with `ov config switch <name>` or by changing `OPENVIKING_CLI_CONFIG_FILE` before invoking `codex`, with no re-install needed. The wrapper omits empty env-var assignments and strips stale credential env vars first, so `OPENVIKING_API_KEY=` or an inherited key for another user is never accidentally passed to Codex.**Wrapping extra launch commands.** If you start Codex through a different command — a custom wrapper like `codex-custom`, or a multi-word launcher (a base command plus a sub-command) — the installer can wrap those too. Answer its "Extra launch commands" prompt, or pass `OPENVIKING_CODEX_WRAP_EXTRA='codex-custom'` when running it (the env-var form is also what to use when piping the installer through a non-interactive shell). The list is stored in the same rc marker block (read by the wrapper as `$OPENVIKING_CODEX_WRAP_EXTRA`); for a multi-word entry, only invocations whose leading args match the sub-command get the credential injection + `.mcp.json` re-render, so every *other* use of that command passes through untouched. List the *real* launch command, never a shell alias of it: an alias expands to its target before the wrapper runs, so wrap what it points at — `alias cx=codex` already rides the base `codex` wrapper (add nothing), while `alias cx=codex-custom` is covered by listing `codex-custom`. Alias names are skipped if listed.@@ -109,12 +78,16 @@ All plugin behavior is controlled by `OPENVIKING_*` environment variables — se```sh# ~/.zshrc — examplesexport OPENVIKING_RECALL_LIMIT=6+export OPENVIKING_RECALL_COMPRESS=1+export OPENVIKING_RECALL_COMPRESS_MODEL=gpt-5.3-codex-spark+export OPENVIKING_RECALL_COMPRESS_THINKING=default+export OPENVIKING_RECALL_TIMEOUT_MS=120000export OPENVIKING_CAPTURE_ASSISTANT_TURNS=1export OPENVIKING_AUTO_COMMIT_ON_COMPACT=1export OPENVIKING_DEBUG=1```-Full list: see the `Misc env vars` block in `scripts/config.mjs`. Every field has a `OPENVIKING_*` counterpart and env vars always win.+Full list: see the `Misc env vars` block in `scripts/config.mjs`. Tuning fields have `OPENVIKING_*` counterparts and env vars win for those tuning fields.#### Legacy `codex` block in `ov.conf`@@ -128,14 +101,15 @@ Earlier plugin versions configured tuning fields under a `codex` block in `~/.op└──┬─────────────────┬────────────────┬───────────────────┬────┘│ │ │ │SessionStart UserPromptSubmit Stop PreCompact- (startup|clear) │ (per turn) │+ (startup|clear|resume) │ (per turn) ││ │ │ │┌────▼──────────┐ ┌────▼──────┐ ┌──────▼──────┐ ┌──────────▼──────┐│ session-start │ │ auto- │ │ auto- │ │ pre-compact- ││ -commit.mjs │ │ recall.mjs│ │ capture.mjs │ │ capture.mjs │- │ (active-win │ │ (search) │ │ (append + │ │ (commit + reset │- │ heuristic + │ │ │ │ no commit) │ │ ovSessionId) │- │ idle TTL) │ │ │ │ │ │ │+ │ (active-win │ │ (search + │ │ (append + │ │ (commit + reset │+ │ heuristic + │ │ compress) │ │ no commit) │ │ ovSessionId) │+ │ idle TTL + │ │ │ │ │ │ │+ │ resume inject)│ │ │ │ │ │ │└────┬──────────┘ └────┬──────┘ └──────┬──────┘ └──────────┬──────┘│ │ │ ││ ┌───▼────────────────▼───────────────────▼──┐@@ -160,9 +134,9 @@ For details on OpenViking's MCP endpoint, tools, and protocol, see the [MCP Inte### SessionStart commit logic (source=startup|clear, heuristic + idle TTL)-Codex fires `SessionStart` with one of three `source` values: `startup` (fresh process / `/new` / zouk daemon spawn-without-sessionId), `resume` (`/resume` or short reconnect), and `clear` (`/clear` — the previous transcript is orphaned and a new session_id is created). `resume` is the *only* source we treat as a hard no-op; on `startup` and `clear` we run the same active-window heuristic.+Codex fires `SessionStart` with one of three `source` values: `startup` (fresh process / `/new` / zouk daemon spawn-without-sessionId), `resume` (`/resume` or short reconnect), and `clear` (`/clear` — the previous transcript is orphaned and a new session_id is created). `resume` never commits or sweeps; on `startup` and `clear` we run the same active-window heuristic.-`hooks.json` registers `SessionStart` with `matcher: "clear|startup"` so codex's dispatcher invokes the script on both sources. `session-start-commit.mjs` gates internally on `source ∈ {startup, clear}` as defense-in-depth.+`hooks.json` registers `SessionStart` with `matcher: "clear|startup|resume"` so codex's dispatcher invokes the script on all three relevant sources. `session-start-commit.mjs` gates internally so only `startup` and `clear` commit/sweep.On `startup` or `clear`, the script:@@ -174,19 +148,39 @@ On `startup` or `clear`, the script:On any /commit failure (OV unreachable, non-2xx, timeout) we **preserve state** (don't `clearState`) so the next sweep can retry.+On `resume`, the script skips commit/sweep. If local state has no live `ovSessionId`, it reads `/api/v1/sessions/{cx-session-id}/context` and injects the latest committed archive overview. The injected block includes a `viking://user/sessions/{cx-session-id}/history/` URI and tells the model to use the OpenViking MCP `read`/`search` tools for exact prior commands, file paths, tool outputs, or messages. Set `OPENVIKING_RESUME_ARCHIVE_INJECT=0` to disable this.+### 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:```json-{ "hookSpecificOutput": { "hookEventName": "UserPromptSubmit", "additionalContext": "<relevant-memories>...</relevant-memories>" } }+{ "hookSpecificOutput": { "hookEventName": "UserPromptSubmit", "additionalContext": "<openviking-context source=\"auto-recall\" format=\"digest\">\nOpenViking memory digest:\n- ...\n</openviking-context>" } }```-Codex injects `additionalContext` into the model turn, so memories arrive without an extra tool call.+Codex injects `additionalContext` into the model turn, so memories arrive without an extra tool call. By default the hook runs a Codex compression pass over recalled candidates before injection, dropping weakly-related memories and preserving only a short digest. If the compressor returns `NO_RELEVANT_MEMORY`, empty text, or non-digest chatter, the hook emits `{}` and injects nothing. The whole hook has its own `OPENVIKING_RECALL_TIMEOUT_MS` deadline (default 120s); the bundled `hooks.json` gives Codex 130s so the script can return `{}` before Codex kills it. Digests may keep `viking://` source URIs and point the model at the OpenViking MCP `read`/`search` tools for details when the inline bullet is intentionally short. The outer `<openviking-context ...>` wrapper is deterministic, not compressor-generated; capture strips it to distinguish recalled context from the user's prompt. Set `OPENVIKING_RECALL_COMPRESS=0` to fall back to deterministic short formatting.++The compressor profile is recreated on every `SessionStart` and cached under `OPENVIKING_CODEX_STATE_DIR` so cross-session config changes are picked up but each `UserPromptSubmit` does not probe models. Default fallback order:++1. configured `OPENVIKING_RECALL_COMPRESS_MODEL` + `OPENVIKING_RECALL_COMPRESS_THINKING`+2. `gpt-5.3-codex-spark` with thinking `default`+3. `gpt-5.5` with thinking `low`+4. off (deterministic digest, no `codex exec` compression)++Config knobs:++| Env var | Default | Meaning |+|---|---|---|+| `OPENVIKING_RECALL_COMPRESS` | `1` | Set `0` / `off` to disable `codex exec` compression. |+| `OPENVIKING_RECALL_COMPRESS_MODEL` | unset | Custom first-choice compressor model. Set `off` to disable compression. |+| `OPENVIKING_RECALL_COMPRESS_THINKING` | unset | Custom `model_reasoning_effort`; `default` omits the Codex config override. Alias: `OPENVIKING_RECALL_COMPRESS_REASONING_EFFORT`. |+| `OPENVIKING_RECALL_COMPRESS_DETECT_ON_STARTUP` | `1` | Recreate/cache compressor profile in `SessionStart`. |+| `OPENVIKING_RECALL_COMPRESS_DETECT_TIMEOUT_MS` | `15000` | Per-candidate startup probe timeout. |+| `OPENVIKING_RECALL_COMPRESS_DETECT_TTL_MS` | `604800000` | Cache TTL used by `UserPromptSubmit` when reading the latest profile. |### Stop (turn end → `add_message`, NOT `commit`)-`auto-capture.mjs` derives one long-lived OpenViking session id per Codex `session_id` as `cx-<safe-session-id>` and incrementally appends every new user/assistant turn via `/api/v1/sessions/{id}/messages`. The `/messages` endpoint auto-creates the session on first append. Per-codex-session state lives at `~/.openviking/codex-plugin-state/<safe-session-id>.json`. No `/commit` per turn — that would over-fragment memory extraction.+`auto-capture.mjs` derives one long-lived OpenViking session id per Codex `session_id` as `cx-<safe-session-id>` and incrementally appends every new user/assistant turn via `/api/v1/sessions/{id}/messages`. The `/messages` endpoint auto-creates the session on first append. Per-codex-session state lives at `~/.openviking/codex-plugin-state/<safe-session-id>.json`. No `/commit` per turn — that would over-fragment memory extraction. Capture sanitizes obvious hook noise, metadata wrappers, and plugin-injected `<openviking-context ...>` blocks before append; tool calls/results are retained as compact `[tool-call ...]` / `[tool-result ...]` lines capped by `OPENVIKING_CAPTURE_TOOL_MAX_CHARS` (default 2000).### PreCompact (deterministic commit)@@ -228,7 +222,9 @@ codex-memory-plugin/│ installer renders to absolute paths)├── scripts/│ ├── config.mjs # Shared config loader (ovcli.conf + env)+│ ├── capture-utils.mjs # Transcript text extraction, filtering, tool compression│ ├── 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-capture.mjs # Stop hook (REST /sessions/{id}/messages)diff --git a/examples/codex-memory-plugin/VERIFICATION.md b/examples/codex-memory-plugin/VERIFICATION.mdindex 65ed593ad..82d73657a 100644--- a/examples/codex-memory-plugin/VERIFICATION.md+++ b/examples/codex-memory-plugin/VERIFICATION.md@@ -124,7 +124,8 @@ Expect: `appended 2 turn(s) to OpenViking session cx-verify-sess`.## 6. SessionStart — active-window heuristic + idle-TTL sweep`source=startup` and `source=clear` both run the same logic-(matcher = `clear|startup`). `source=resume` is the only hard no-op.+(matcher = `clear|startup|resume`). `source=resume` never commits or sweeps;+it may inject latest archive context if a committed archive exists.See `DESIGN.md` §3 + §5 for the full decision tree.### 6a. `1 active` → commit@@ -205,7 +206,7 @@ If `sess-bbb` was in `≥2 active` from 6c, the heuristic on this call seesjust `sess-bbb` (1 active) and commits it — that's expected and shows theheuristic + sweep working together.-### 6e. `source=resume` → hard no-op (no commit, no sweep)+### 6e. `source=resume` → no commit/sweep; optional archive inject```bashecho '{"session_id":"any","source":"resume","cwd":"/tmp","model":"x","permission_mode":"default","transcript_path":null,"hook_event_name":"SessionStart"}' \@@ -213,7 +214,21 @@ echo '{"session_id":"any","source":"resume","cwd":"/tmp","model":"x","permissionOPENVIKING_CODEX_STATE_DIR=$STATE_DIR/state \CODEX_PLUGIN_ROOT=$PLUGIN \node $PLUGIN/scripts/session-start-commit.mjs-# Expect: {} — resume neither commits nor sweeps; short reconnects fire resume too.+# Expect without an existing archive: {}+# Expect with an existing archive for cx-any: hookSpecificOutput.additionalContext+# containing "OpenViking session archive digest" and a viking://user/sessions/cx-any/history/ URI.+```++### 6f. Compressor profile detect can be disabled for hook smoke tests++```bash+echo '{"session_id":"any","source":"startup","cwd":"/tmp","model":"x","permission_mode":"default","transcript_path":null,"hook_event_name":"SessionStart"}' \+ | OPENVIKING_RECALL_COMPRESS_DETECT_ON_STARTUP=0 \+ OPENVIKING_CONFIG_FILE=$OV_CONF \+ OPENVIKING_CODEX_STATE_DIR=$STATE_DIR/state \+ CODEX_PLUGIN_ROOT=$PLUGIN \+ node $PLUGIN/scripts/session-start-commit.mjs+# Expect: normal SessionStart behavior without spawning `codex exec` for model probing.```## 7. Memory extraction landed in user namespacediff --git a/examples/codex-memory-plugin/hooks/hooks.json b/examples/codex-memory-plugin/hooks/hooks.jsonindex 65284645d..076f7d11b 100644--- a/examples/codex-memory-plugin/hooks/hooks.json+++ b/examples/codex-memory-plugin/hooks/hooks.json@@ -2,12 +2,12 @@"hooks": {"SessionStart": [{- "matcher": "clear|startup",+ "matcher": "clear|startup|resume","hooks": [{"type": "command","command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/session-start-commit.mjs",- "timeout": 30+ "timeout": 70}]}@@ -19,7 +19,7 @@{"type": "command","command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/auto-recall.mjs",- "timeout": 15+ "timeout": 130}]}diff --git a/examples/codex-memory-plugin/scripts/auto-capture.mjs b/examples/codex-memory-plugin/scripts/auto-capture.mjsindex c4988f520..fa7e1c845 100644--- a/examples/codex-memory-plugin/scripts/auto-capture.mjs+++ b/examples/codex-memory-plugin/scripts/auto-capture.mjs@@ -26,6 +26,12 @@*/import { readFile } from "node:fs/promises";+import {+ extractTextFromPayload,+ isAssistantSideCaptureRole,+ normalizeCaptureRole,+ shouldCaptureText,+} from "./capture-utils.mjs";import { loadConfig } from "./config.mjs";import { createLogger } from "./debug-log.mjs";import { loadState, resolveOvSessionId, saveState } from "./session-state.mjs";@@ -52,6 +58,7 @@ async function fetchJSON(path, init = {}) {}if (cfg.account) headers["X-OpenViking-Account"] = cfg.account;if (cfg.user) headers["X-OpenViking-User"] = cfg.user;+ if (cfg.peerId) headers["X-OpenViking-Actor-Peer"] = cfg.peerId;const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });const body = await res.json().catch(() => null);if (!body) return null;@@ -68,18 +75,6 @@ async function fetchJSON(path, init = {}) {// Transcript parsing (JSONL rollout)// ----------------------------------------------------------------------------function extractTextFromContent(content) {- if (!content) return "";- if (typeof content === "string") return content;- if (Array.isArray(content)) {- return content- .filter((b) => b && (b.type === "text" || b.type === "input_text" || b.type === "output_text"))- .map((b) => b.text || "")- .join("\n");- }- return "";-}-function parseTranscript(content) {try {const data = JSON.parse(content);@@ -98,29 +93,16 @@ function extractTurns(rolloutEntries) {for (const entry of rolloutEntries) {if (!entry || typeof entry !== "object") continue;const payload = entry.payload && typeof entry.payload === "object" ? entry.payload : entry;- let role = payload.role;- let text = "";-- if (typeof payload.content === "string") {- text = payload.content;- } else if (Array.isArray(payload.content)) {- text = extractTextFromContent(payload.content);- } else if (payload.message && typeof payload.message === "object") {- role = payload.message.role || role;- text = typeof payload.message.content === "string"- ? payload.message.content- : extractTextFromContent(payload.message.content);- }-- if (role !== "user" && role !== "assistant") continue;- if (role === "assistant" && !cfg.captureAssistantTurns) continue;- const trimmed = text.trim();- if (!trimmed) continue;-- const capped = trimmed.length > cfg.captureMaxLength- ? trimmed.slice(0, cfg.captureMaxLength)- : trimmed;- turns.push({ role, text: capped });+ const message = payload.message && typeof payload.message === "object" ? payload.message : null;+ const rawRole = message?.role || payload.role || payload.type || payload.kind;+ const role = normalizeCaptureRole(rawRole);+ if (!role) continue;+ if (isAssistantSideCaptureRole(rawRole) && !cfg.captureAssistantTurns) continue;++ const rawText = extractTextFromPayload(payload, { toolMaxChars: cfg.captureToolMaxChars });+ const decision = shouldCaptureText(rawText, role, cfg);+ if (!decision.shouldCapture) continue;+ turns.push({ role, text: decision.text });}return turns;}@@ -137,7 +119,16 @@ async function readTranscriptTurns(transcriptPath) {}}-async function appendTurns(ovSessionId, turns) {+function selectStopTurns(state, turns) {+ const limit = cfg.captureMaxTurnsPerStop;+ if (turns.length <= limit) return turns;+ const skipped = turns.length - limit;+ state.capturedTurnCount += skipped;+ log("backlog_trimmed", { newTurns: turns.length, skipped, selected: limit });+ return turns.slice(-limit);+}++async function appendTurns(ovSessionId, turns, state) {let appended = 0;for (const turn of turns) {const body = { role: turn.role, content: turn.text };@@ -148,6 +139,8 @@ async function appendTurns(ovSessionId, turns) {});if (!result) break;appended += 1;+ state.capturedTurnCount += 1;+ await saveState(state);}return appended;}@@ -222,8 +215,9 @@ async function main() {if (!ovSessionId) {logError("resolve_ov_session", "failed to derive OV session id");} else {- added = await appendTurns(ovSessionId, newTurns);- state.capturedTurnCount += added;+ const turnsToAppend = selectStopTurns(state, newTurns);+ await saveState(state);+ added = await appendTurns(ovSessionId, turnsToAppend, state);log("appended", { ovSessionId, added });}}diff --git a/examples/codex-memory-plugin/scripts/auto-recall.mjs b/examples/codex-memory-plugin/scripts/auto-recall.mjsindex 0cf755567..bd06e5953 100644--- a/examples/codex-memory-plugin/scripts/auto-recall.mjs+++ b/examples/codex-memory-plugin/scripts/auto-recall.mjs@@ -13,14 +13,46 @@* is just `{}`.*/+import { spawn } from "node:child_process";+import { mkdtemp, readFile, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";import { loadConfig } from "./config.mjs";import { createLogger } from "./debug-log.mjs";+import {+ buildCodexExecArgs,+ fallbackRecallCompressorProfile,+ loadCachedRecallCompressorProfile,+ markRecallCompressorRuntimeFailed,+} from "./recall-compressor-profile.mjs";const cfg = loadConfig();const { log, logError } = createLogger("auto-recall");-function output(obj) {- process.stdout.write(JSON.stringify(obj) + "\n");+let emitted = false;+let activeCompressor = null;+let recallDeadline = null;++function output(obj, exitAfter = false) {+ if (emitted) return;+ emitted = true;+ if (recallDeadline) clearTimeout(recallDeadline);+ const line = JSON.stringify(obj) + "\n";+ if (exitAfter) {+ process.stdout.write(line, () => process.exit(0));+ return;+ }+ process.stdout.write(line);+}++function wrapRecallContext(additionalContext) {+ const body = sanitizeInjectedText(additionalContext).trim();+ if (!body) return "";+ return [+ '<openviking-context source="auto-recall" format="digest">',+ body,+ "</openviking-context>",+ ].join("\n");}function emit(additionalContext) {@@ -28,14 +60,28 @@ function emit(additionalContext) {output({});return;}+ const wrappedContext = wrapRecallContext(additionalContext);+ if (!wrappedContext) {+ output({});+ return;+ }output({hookSpecificOutput: {hookEventName: "UserPromptSubmit",- additionalContext,+ additionalContext: wrappedContext,},});}+recallDeadline = setTimeout(() => {+ logError("recall_timeout", `timed out after ${cfg.recallTimeoutMs}ms`);+ try {+ activeCompressor?.kill("SIGKILL");+ } catch { /* best effort */ }+ output({}, true);+}, cfg.recallTimeoutMs);+recallDeadline.unref?.();+async function fetchJSON(path, init = {}) {const controller = new AbortController();const timer = setTimeout(() => controller.abort(), cfg.timeoutMs);@@ -250,6 +296,187 @@ async function readMemoryContent(uri) {return null;}+function truncateText(text, maxChars) {+ const value = String(text || "").trim();+ if (value.length <= maxChars) return value;+ return `${value.slice(0, Math.max(0, maxChars - 20)).trimEnd()}\n[truncated]`;+}++function sanitizeInjectedText(text) {+ return String(text || "")+ .replace(/<\/?relevant-memor(?:y|ies)\b[^>]*>/gi, "legacy memory wrapper")+ .replace(/<\/?openviking-context\b[^>]*>/gi, "openviking context marker");+}++function isNoRelevantMemory(text) {+ const value = String(text || "")+ .trim()+ .replace(/^openviking memory digest:\s*/i, "")+ .trim();+ return !value || /^NO_RELEVANT_MEMORY\.?$/i.test(value) || /^no (?:directly )?relevant memor(?:y|ies)\.?$/i.test(value);+}++function hasDigestSignal(text) {+ const body = String(text || "").replace(/^openviking memory digest:\s*/i, "").trim();+ return /(^|\n)\s*[-*]\s+\S/.test(body) || /\bviking:\/\//i.test(body);+}++function appendMcpRetrievalHint(text) {+ const value = String(text || "").trim();+ if (!/\bviking:\/\//i.test(value) || /OpenViking MCP/i.test(value)) return value;+ return `${value}\n\nMore detail: use the OpenViking MCP read/search tools with the cited viking:// URI if needed.`;+}++function fallbackDigest(items) {+ const lines = items.slice(0, cfg.recallCompressMaxBullets).map((item) => {+ const text = sanitizeInjectedText(truncateText(item.text, 260)).replace(/\s+/g, " ");+ return `- [${item.category || "memory"}] ${text} (${item.uri})`;+ });+ return lines.length > 0 ? appendMcpRetrievalHint(`OpenViking memory digest:\n${lines.join("\n")}`) : "";+}++function normalizeCompressedContext(text) {+ let value = String(text || "").trim();+ if (!value) return "";+ value = value.replace(/^```(?:text|markdown)?\s*/i, "").replace(/\s*```$/i, "").trim();+ value = sanitizeInjectedText(value);+ if (isNoRelevantMemory(value)) return "";+ if (!value.toLowerCase().startsWith("openviking memory digest:")) {+ value = `OpenViking memory digest:\n${value}`;+ }+ if (!hasDigestSignal(value)) return "";+ return truncateText(appendMcpRetrievalHint(value), 4000);+}++async function getRecallCompressorProfile() {+ const cached = await loadCachedRecallCompressorProfile(cfg);+ if (cached) return cached;+ const fallback = fallbackRecallCompressorProfile(cfg);+ log("compress_profile_cache_miss", fallback);+ return fallback;+}++async function runCodexCompressor(prompt, profile) {+ const tmp = await mkdtemp(join(tmpdir(), "ov-recall-compress-"));+ const outputPath = join(tmp, "last-message.txt");+ const args = buildCodexExecArgs(profile, outputPath);++ try {+ return await new Promise((resolve) => {+ const env = {+ ...process.env,+ OPENVIKING_AUTO_RECALL: "0",+ OPENVIKING_AUTO_CAPTURE: "0",+ OPENVIKING_RECALL_COMPRESS: "0",+ };+ let done = false;+ let timedOut = false;+ let stderr = "";+ const child = spawn("codex", args, { env, stdio: ["pipe", "ignore", "pipe"] });+ activeCompressor = child;+ const finish = (value, { runtimeFailed = false } = {}) => {+ if (done) return;+ done = true;+ if (activeCompressor === child) activeCompressor = null;+ clearTimeout(timer);+ if (runtimeFailed) {+ // Mark the profile as runtime_failed so subsequent UPS calls in+ // this same codex session skip compress (avoids burning+ // ~recallCompressTimeoutMs per turn on a guaranteed-to-fail+ // spawn). Next SessionStart's cache-first detect treats this+ // marker as a cache miss and re-resolves against the current+ // catalogue, so a transient failure self-recovers across codex+ // restarts. Best-effort write; failure is non-fatal.+ markRecallCompressorRuntimeFailed(cfg, { failedModel: profile.model || "" })+ .catch(() => {});+ }+ resolve(value);+ };+ const timer = setTimeout(() => {+ timedOut = true;+ logError("compress_timeout", `timed out after ${cfg.recallCompressTimeoutMs}ms`);+ try {+ child.kill("SIGKILL");+ } catch { /* best effort */ }+ }, cfg.recallCompressTimeoutMs);++ child.stderr.on("data", (chunk) => {+ stderr += chunk.toString();+ if (stderr.length > 4000) stderr = stderr.slice(-4000);+ });+ child.on("error", (err) => {+ logError("compress_spawn", err);+ finish(null, { runtimeFailed: true });+ });+ child.on("close", async (code) => {+ if (timedOut) {+ finish(null, { runtimeFailed: true });+ return;+ }+ if (code !== 0) {+ logError("compress_exit", {+ profile,+ error: stderr.trim().slice(-1000) || `codex exited ${code}`,+ });+ finish(null, { runtimeFailed: true });+ return;+ }+ try {+ finish(await readFile(outputPath, "utf-8"));+ } catch (err) {+ logError("compress_read", err);+ finish(null, { runtimeFailed: true });+ }+ });+ child.stdin.end(prompt);+ });+ } finally {+ await rm(tmp, { recursive: true, force: true }).catch(() => {});+ }+}++async function compressMemoryContext(userPrompt, items) {+ if (!cfg.recallCompress) return null;+ const profile = await getRecallCompressorProfile();+ if (!profile.enabled) {+ log("compress_skip", { reason: "profile disabled", profile });+ return null;+ }+ const perItemChars = Math.max(500, Math.floor(cfg.recallCompressMaxInputChars / Math.max(1, items.length)));+ const payload = {+ user_prompt: userPrompt,+ max_bullets: cfg.recallCompressMaxBullets,+ memories: items.map((item) => ({+ uri: item.uri,+ category: item.category || "memory",+ score: item.score,+ text: truncateText(item.text, perItemChars),+ })),+ };+ const prompt = `You are a memory relevance compressor for a Codex UserPromptSubmit hook.++Task:+- Keep only memories directly useful for answering the user's current prompt.+- Drop stale, generic, duplicate, merely adjacent, or operationally unrelated memories.+- Compress to at most ${cfg.recallCompressMaxBullets} short bullets.+- Preserve concrete facts, dates, paths, repo names, commands, and user preferences.+- Include the source viking:// URI when the agent may need to inspect more detail.+- If the answer needs detail beyond the bullet, say to use OpenViking MCP read/search with the cited viking:// URI if needed.+- Do not include XML/HTML wrappers.+- Do not mention that you filtered memories.+- Output either "OpenViking memory digest:" followed by useful bullets, or exactly: NO_RELEVANT_MEMORY.+- If no memory is directly useful, output exactly: NO_RELEVANT_MEMORY.++Input JSON:+${JSON.stringify(payload, null, 2)}+`;+ const raw = await runCodexCompressor(prompt, profile);+ if (raw === null) return null;+ const compressed = normalizeCompressedContext(raw);+ log("compressed", { inputCount: items.length, chars: compressed.length, profile });+ return compressed;+}+async function main() {if (!cfg.autoRecall) {log("skip", { stage: "init", reason: "autoRecall disabled" });@@ -324,21 +551,24 @@ async function main() {log("picked", { pickedCount: memories.length, uris: memories.map((m) => m.uri) });- const lines = await Promise.all(+ const memoryItems = await Promise.all(memories.map(async (item) => {+ let text = (item.abstract || item.overview || item.uri).trim();if (item.level === 2) {const content = await readMemoryContent(item.uri);- if (content) return `- [${item.category || "memory"}] ${content}`;+ if (content) text = content;}- return `- [${item.category || "memory"}] ${(item.abstract || item.overview || item.uri).trim()}`;+ return {+ uri: item.uri,+ category: item.category || "memory",+ score: clampScore(item.score),+ text,+ };}),);- const memoryContext =- "<relevant-memories>\n" +- "The following long-term memories from OpenViking may be relevant to this conversation:\n" +- lines.join("\n") + "\n" +- "</relevant-memories>";+ const compressedContext = await compressMemoryContext(userPrompt, memoryItems);+ const memoryContext = compressedContext === null ? fallbackDigest(memoryItems) : compressedContext;emit(memoryContext);}diff --git a/examples/codex-memory-plugin/scripts/capture-utils.mjs b/examples/codex-memory-plugin/scripts/capture-utils.mjsnew file mode 100644index 000000000..005175bad--- /dev/null+++ b/examples/codex-memory-plugin/scripts/capture-utils.mjs@@ -0,0 +1,328 @@+const TEXT_BLOCK_TYPES = new Set(["text", "input_text", "output_text"]);+const TOOL_CALL_TYPES = new Set([+ "tool_call",+ "toolcall",+ "tool_use",+ "tooluse",+ "function_call",+ "functioncall",+]);+const TOOL_RESULT_TYPES = new Set([+ "tool_result",+ "toolresult",+ "tool_output",+ "tooloutput",+ "function_call_output",+ "functioncalloutput",+]);++const ACK_RE = /^(?:ok|okay|k|yes|yep|no|nope|thanks|thank you|thx|done|收到|好的|好|嗯|可以|继续|不用|不需要|没了|好了)[.!?。!?\s]*$/i;+const SLASH_COMMAND_RE = /^\/[a-z0-9_-]{1,64}\b/i;+const METADATA_KEYS = [+ "session_id",+ "sessionid",+ "sessionkey",+ "conversation_id",+ "conversationid",+ "channel",+ "sender",+ "user_id",+ "userid",+ "agent_id",+ "agentid",+ "timestamp",+ "timezone",+ "cwd",+ "model",+ "permission_mode",+];++function normalizeType(value) {+ return String(value || "").toLowerCase().replace(/[-\s]/g, "_");+}++function isToolCallBlock(block) {+ const type = normalizeType(block?.type || block?.kind || block?.role);+ return TOOL_CALL_TYPES.has(type) || Boolean(block?.tool_calls) || Boolean(block?.function?.name);+}++function isToolResultBlock(block) {+ const type = normalizeType(block?.type || block?.kind || block?.role);+ return TOOL_RESULT_TYPES.has(type) || type === "tool" || type === "function";+}++function oneLine(text) {+ return String(text || "").replace(/\s+/g, " ").trim();+}++export function truncateCaptureText(text, maxChars = 2000) {+ const value = String(text || "").trim();+ if (!Number.isFinite(maxChars) || maxChars <= 0 || value.length <= maxChars) return value;+ return `${value.slice(0, Math.max(0, maxChars - 20)).trimEnd()}\n[truncated]`;+}++function stringifyCompact(value, maxChars) {+ if (value == null) return "";+ if (typeof value === "string") return truncateCaptureText(value, maxChars);+ try {+ return truncateCaptureText(JSON.stringify(value), maxChars);+ } catch {+ return truncateCaptureText(String(value), maxChars);+ }+}++function blockText(block) {+ if (!block || typeof block !== "object") return "";+ if (typeof block.text === "string") return block.text;+ if (typeof block.output_text === "string") return block.output_text;+ if (typeof block.input_text === "string") return block.input_text;+ if (typeof block.content === "string") return block.content;+ return "";+}++function toolName(block) {+ return oneLine(+ block?.name ||+ block?.tool_name ||+ block?.toolName ||+ block?.function?.name ||+ block?.call?.name ||+ block?.id ||+ "",+ );+}++function toolPayload(block, kind) {+ if (!block || typeof block !== "object") return "";+ if (kind === "call") {+ return block.input ??+ block.arguments ??+ block.args ??+ block.params ??+ block.function?.arguments ??+ block.command ??+ block.call?.input ??+ block.call?.arguments ??+ "";+ }+ return block.output ??+ block.result ??+ block.error ??+ block.data ??+ block.content ??+ block.text ??+ "";+}++function formatToolBlock(block, kind, maxChars) {+ const name = toolName(block);+ const payload = toolPayload(block, kind);+ const body = oneLine(stringifyCompact(payload, maxChars));+ const label = kind === "call" ? "tool-call" : "tool-result";+ return body+ ? `[${label}${name ? ` ${name}` : ""}] ${body}`+ : `[${label}${name ? ` ${name}` : ""}]`;+}++function blockToText(block, options) {+ if (!block) return "";+ if (typeof block === "string") return block;+ if (Array.isArray(block)) return extractTextFromContent(block, options);+ if (typeof block !== "object") return "";++ if (block.item && typeof block.item === "object") {+ const itemText = blockToText(block.item, options);+ if (itemText) return itemText;+ }++ const type = normalizeType(block.type || block.kind || block.role);+ if (TEXT_BLOCK_TYPES.has(type)) return blockText(block);+ if (isToolCallBlock(block)) return formatToolBlock(block, "call", options.toolMaxChars);+ if (isToolResultBlock(block)) return formatToolBlock(block, "result", options.toolMaxChars);+ if (Array.isArray(block.content)) return extractTextFromContent(block.content, options);+ if (!type) return blockText(block);+ return "";+}++export function extractTextFromContent(content, options = {}) {+ const opts = { toolMaxChars: 2000, ...options };+ if (!content) return "";+ if (typeof content === "string") return content;+ if (Array.isArray(content)) {+ return content+ .map((block) => blockToText(block, opts))+ .filter(Boolean)+ .join("\n\n");+ }+ if (typeof content === "object") {+ return blockToText(content, opts) || stringifyCompact(content, opts.toolMaxChars);+ }+ return "";+}++export function extractTextFromPayload(payload, options = {}) {+ if (!payload || typeof payload !== "object") return "";+ const chunks = [];+ const directType = normalizeType(payload.type || payload.kind || payload.role);+ if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || TOOL_CALL_TYPES.has(directType)) {+ const direct = blockToText(payload, { toolMaxChars: 2000, ...options });+ if (direct) return direct;+ }++ if (payload.message && typeof payload.message === "object") {+ const messageText = extractTextFromPayload(payload.message, options);+ if (messageText) chunks.push(messageText);+ } else if (payload.content !== undefined) {+ const contentText = extractTextFromContent(payload.content, options);+ if (contentText) chunks.push(contentText);+ }++ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {+ const value = payload[key];+ if (!value) continue;+ const toolText = extractTextFromContent(value, options);+ if (toolText) chunks.push(toolText);+ }++ if (chunks.length === 0) {+ const direct = blockToText(payload, { toolMaxChars: 2000, ...options });+ if (direct) chunks.push(direct);+ }++ return chunks.join("\n\n");+}++export function normalizeCaptureRole(role) {+ const value = normalizeType(role);+ if (value === "user") return "user";+ if (value === "assistant") return "assistant";+ if (value === "tool" || value === "tool_result" || value === "function" || value === "function_call_output") {+ return "user";+ }+ if (value === "tool_call" || value === "function_call") return "assistant";+ return null;+}++export function isAssistantSideCaptureRole(role) {+ const value = normalizeType(role);+ return value === "assistant" ||+ value === "tool" ||+ value === "tool_result" ||+ value === "tool_call" ||+ value === "function" ||+ value === "function_call" ||+ value === "function_call_output";+}++function stripMetadataFences(text) {+ return String(text || "").replace(/```(?:json)?\s*([\s\S]*?)```/gi, (match, body) => {+ const lower = body.toLowerCase();+ let hits = 0;+ for (const key of METADATA_KEYS) {+ const re = new RegExp(`["']?${key}["']?\\s*:`, "i");+ if (re.test(lower)) hits += 1;+ }+ return hits >= 3 ? "" : match;+ });+}++function stripInjectedDigestBlocks(text) {+ const lines = String(text || "").split(/\r?\n/);+ const out = [];+ let skipping = false;+ let skipUntilMcpHint = false;++ for (const line of lines) {+ const trimmed = line.trim();+ if (/^OpenViking session archive digest:/i.test(trimmed)) {+ skipping = true;+ skipUntilMcpHint = true;+ continue;+ }+ if (/^OpenViking memory digest:/i.test(trimmed)) {+ skipping = true;+ skipUntilMcpHint = false;+ continue;+ }+ if (skipping) {+ if (skipUntilMcpHint) {+ if (/^More detail: use the OpenViking MCP /i.test(trimmed)) {+ skipping = false;+ skipUntilMcpHint = false;+ }+ continue;+ }+ if (!trimmed) {+ skipping = false;+ continue;+ }+ if (+ /^(?:[-*]\s+|#{1,6}\s+|More detail:|Use OpenViking MCP|Latest committed archive|Resume continuity|viking:\/\/)/i.test(trimmed) ||+ /^\s{2,}\S/.test(line)+ ) {+ continue;+ }+ skipping = false;+ }+ out.push(line);+ }++ return out.join("\n");+}++export function sanitizeCapturedText(text) {+ let value = String(text || "");+ value = value+ .replace(/\u0000/g, "")+ .replace(/<openviking-context\b[^>]*>[\s\S]*?<\/openviking-context>/gi, " ")+ .replace(/<relevant-memor(?:y|ies)\b[^>]*>[\s\S]*?<\/relevant-memor(?:y|ies)>/gi, " ")+ .replace(/^\s*Sender\s*\([^)]+\)\s*```[\s\S]*?```\s*/gim, " ")+ .replace(/^\s*Conversation (?:metadata|info):\s*```[\s\S]*?```\s*/gim, " ")+ .replace(/^\s*\[?\d{4}-\d{2}-\d{2}[T ][^\]\n]{3,80}\]?\s*/gm, "")+ .replace(/^\s*\d{10,13}\s+/gm, "");+ value = stripMetadataFences(value);+ value = stripInjectedDigestBlocks(value);+ value = value.replace(/^\s*More detail: use the OpenViking MCP .*$/gim, " ");+ return value+ .replace(/[ \t]+\n/g, "\n")+ .replace(/\n{3,}/g, "\n\n")+ .trim();+}++function hasEnoughSignal(text) {+ const cjk = text.match(/[\u3400-\u9fff]/g)?.length || 0;+ const alnum = text.match(/[a-z0-9]/gi)?.length || 0;+ return cjk >= 4 || alnum >= 6 || text.length >= 12;+}++function isPunctuationOnly(text) {+ return !/[a-z0-9\u3400-\u9fff]/i.test(text);+}++export function shouldCaptureText(text, role, cfg = {}) {+ const maxLength = cfg.captureMaxLength || 24000;+ const sanitized = sanitizeCapturedText(text);+ if (!sanitized) return { shouldCapture: false, reason: "empty", text: "" };++ const capped = truncateCaptureText(sanitized, maxLength);+ const compact = oneLine(capped);+ const isToolSummary = /^\[tool-(?:call|result)\b/i.test(compact);++ if (!isToolSummary && role === "user" && SLASH_COMMAND_RE.test(compact)) {+ return { shouldCapture: false, reason: "slash_command", text: "" };+ }+ if (!isToolSummary && ACK_RE.test(compact)) {+ return { shouldCapture: false, reason: "ack", text: "" };+ }+ if (!isToolSummary && isPunctuationOnly(compact)) {+ return { shouldCapture: false, reason: "punctuation", text: "" };+ }+ if (!isToolSummary && !hasEnoughSignal(compact)) {+ return { shouldCapture: false, reason: "too_short", text: "" };+ }+ if (/^\[openviking-memory\]/i.test(compact)) {+ return { shouldCapture: false, reason: "plugin_status", text: "" };+ }++ return { shouldCapture: true, reason: "ok", text: capped };+}diff --git a/examples/codex-memory-plugin/scripts/config.mjs b/examples/codex-memory-plugin/scripts/config.mjsindex 85dfd36da..07f03ff3b 100644--- a/examples/codex-memory-plugin/scripts/config.mjs+++ b/examples/codex-memory-plugin/scripts/config.mjs@@ -1,16 +1,18 @@/*** Shared configuration loader for the Codex OpenViking memory plugin.*- * Resolution priority (highest → lowest), per-field:- * 1. Environment variables (OPENVIKING_*)- * 2. ovcli.conf — the CLI client config (carries url/api_key/account/user)- * 3. ov.conf — the server config (server.* + optional codex.* block for tuning)- * 4. Built-in defaults+ * Credential source:+ * - Default: active ovcli.conf wins when present, so `ov config switch`+ * changes hooks, MCP, and in-process `ov` commands together on next launch.+ * - Set OPENVIKING_CREDENTIAL_SOURCE=env to force env-var credentials.+ * - Without ovcli.conf, env vars and then ov.conf/defaults are used.*- * Mirrors examples/claude-code-memory-plugin/scripts/config.mjs so the- * hook surface and the MCP server (src/memory-server.ts imports loadConfig- * from here) resolve identity identically. Aligning the two prevents- * silent identity drift between auto-capture and explicit `remember` calls.+ * Tuning resolution remains env vars > ov.conf codex.* > built-in defaults.+ *+ * Mirrors the credential fields that Codex's streamable-HTTP MCP entry+ * receives from the shell wrapper. Aligning the resolver prevents identity+ * drift between auto-capture/auto-recall hooks, MCP calls, and child `ov`+ * commands launched from inside Codex.** File-path env vars:* OPENVIKING_CLI_CONFIG_FILE alternate ovcli.conf path (preferred)@@ -28,16 +30,15 @@** Misc env vars:* OPENVIKING_TIMEOUT_MS, OPENVIKING_CAPTURE_TIMEOUT_MS+ * OPENVIKING_RECALL_TIMEOUT_MS, OPENVIKING_RECALL_COMPRESS_TIMEOUT_MS+ * OPENVIKING_RECALL_COMPRESS_MODEL, OPENVIKING_RECALL_COMPRESS_THINKING* OPENVIKING_RECALL_LIMIT, OPENVIKING_SCORE_THRESHOLD* OPENVIKING_DEBUG=1, OPENVIKING_DEBUG_LOG*/-import { readFileSync } from "node:fs";import { homedir } from "node:os";-import { join, resolve as resolvePath } from "node:path";--const DEFAULT_OVCLI_CONF_PATH = join(homedir(), ".openviking", "ovcli.conf");-const DEFAULT_OV_CONF_PATH = join(homedir(), ".openviking", "ov.conf");+import { join } from "node:path";+import { resolveOpenVikingCredentials } from "./ov-credentials.mjs";function num(val, fallback) {if (typeof val === "number" && Number.isFinite(val)) return val;@@ -57,127 +58,22 @@ function envBool(name) {const v = process.env[name];if (v == null || v === "") return undefined;const lower = v.trim().toLowerCase();- if (lower === "0" || lower === "false" || lower === "no") return false;+ if (lower === "0" || lower === "false" || lower === "no" || lower === "off") return false;if (lower === "1" || lower === "true" || lower === "yes") return true;return undefined;}-function tryLoadJson(path) {- let raw;- try {- raw = readFileSync(path, "utf-8");- } catch {- return null;- }- try {- return JSON.parse(raw);- } catch {- process.stderr.write(`[openviking-memory] Invalid config file: ${path}\n`);- return null;- }-}--function looksLikeOvcli(obj) {- if (!obj || typeof obj !== "object") return false;- if (obj.server && typeof obj.server === "object") return false;- return typeof obj.url === "string" || typeof obj.api_key === "string";-}--/**- * Returns { cliFile, cliPath, ovFile, ovPath }. Missing files are- * represented as empty objects, so callers can read fields unconditionally.- *- * OPENVIKING_CLI_CONFIG_FILE overrides the ovcli.conf path.- * OPENVIKING_CONFIG_FILE overrides the ov.conf path; if the file looks- * like an ovcli.conf (no `server` section + has `url`/`api_key`), it is- * also used as the cliFile to support the legacy "pass any conf via- * OPENVIKING_CONFIG_FILE" pattern.- */-function loadFiles() {- const cliPathEnv = process.env.OPENVIKING_CLI_CONFIG_FILE- ? resolvePath(process.env.OPENVIKING_CLI_CONFIG_FILE.replace(/^~/, homedir()))- : null;- const ovPathEnv = process.env.OPENVIKING_CONFIG_FILE- ? resolvePath(process.env.OPENVIKING_CONFIG_FILE.replace(/^~/, homedir()))- : null;-- const cliPath = cliPathEnv || DEFAULT_OVCLI_CONF_PATH;- const ovPath = ovPathEnv || DEFAULT_OV_CONF_PATH;-- let cliFile = tryLoadJson(cliPath);- let cliLoadedFrom = cliFile ? cliPath : null;- let ovFile = tryLoadJson(ovPath);- let ovLoadedFrom = ovFile ? ovPath : null;-- // Backward compat: OPENVIKING_CONFIG_FILE pointing at an ovcli-shaped file.- // Earlier plugin versions had a single OPENVIKING_CONFIG_FILE that could- // point at either ov.conf or ovcli.conf; preserve that by promoting.- if (ovPathEnv && !cliPathEnv && looksLikeOvcli(ovFile)) {- cliFile = ovFile;- cliLoadedFrom = ovLoadedFrom;- ovFile = null;- ovLoadedFrom = null;- }-- return {- cliFile: cliFile || {},- cliPath: cliLoadedFrom,- ovFile: ovFile || {},- ovPath: ovLoadedFrom,- };-}--function deriveBaseUrl({ cliFile, ovFile }) {- const envUrl = str(process.env.OPENVIKING_URL, null) || str(process.env.OPENVIKING_BASE_URL, null);- if (envUrl) return envUrl.replace(/\/+$/, "");-- const cliUrl = str(cliFile.url, null);- if (cliUrl) return cliUrl.replace(/\/+$/, "");-- const server = ovFile.server || {};- const ovUrl = str(server.url, null);- if (ovUrl) return ovUrl.replace(/\/+$/, "");-- const host = str(server.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1");- const port = Math.floor(num(server.port, 1933));- return `http://${host}:${port}`;+function hasOwn(obj, key) {+ return Object.prototype.hasOwnProperty.call(obj || {}, key);}export function loadConfig() {- const { cliFile, cliPath, ovFile, ovPath } = loadFiles();+ const creds = resolveOpenVikingCredentials();+ const { cliPath, ovFile, ovPath } = creds;const configPath = cliPath || ovPath || null;- const server = ovFile.server || {};const cx = ovFile.codex || {};- const baseUrl = deriveBaseUrl({ cliFile, ovFile });-- // apiKey: env > cliFile.api_key > codex.apiKey > server.root_api_key- // Accepts OPENVIKING_BEARER_TOKEN or OPENVIKING_API_KEY (sent as Bearer either way).- const apiKey =- str(process.env.OPENVIKING_BEARER_TOKEN, null) ||- str(process.env.OPENVIKING_API_KEY, null) ||- str(cliFile.api_key, null) ||- str(cx.apiKey, null) ||- str(server.root_api_key, "");-- // account: env > cliFile.account > codex.accountId > ""- const account =- str(process.env.OPENVIKING_ACCOUNT, null) ||- str(cliFile.account, null) ||- str(cx.accountId, "");-- // user: env > cliFile.user > codex.userId > ""- const user =- str(process.env.OPENVIKING_USER, null) ||- str(cliFile.user, null) ||- str(cx.userId, "");-- const peerId =- str(process.env.OPENVIKING_PEER_ID, null) ||- str(cx.peerId, null) ||- str(cx.peer_id, "");-const debug = envBool("OPENVIKING_DEBUG") ?? (cx.debug === true);const defaultLogPath = join(homedir(), ".openviking", "logs", "codex-hooks.log");const debugLogPath = str(process.env.OPENVIKING_DEBUG_LOG, defaultLogPath);@@ -190,17 +86,42 @@ export function loadConfig() {process.env.OPENVIKING_CAPTURE_TIMEOUT_MS,num(cx.captureTimeoutMs, Math.max(timeoutMs * 2, 30000)),)));+ const recallTimeoutMs = Math.max(1000, Math.floor(num(+ process.env.OPENVIKING_RECALL_TIMEOUT_MS,+ num(cx.recallTimeoutMs, 120000),+ )));+ const defaultRecallCompressTimeoutMs = Math.max(1000, recallTimeoutMs - 10000);+ const recallCompressTimeoutMs = Math.max(1000, Math.floor(num(+ process.env.OPENVIKING_RECALL_COMPRESS_TIMEOUT_MS,+ num(cx.recallCompressTimeoutMs, defaultRecallCompressTimeoutMs),+ )));+ const recallCompressModel = str(+ process.env.OPENVIKING_RECALL_COMPRESS_MODEL,+ hasOwn(cx, "recallCompressModel") ? str(cx.recallCompressModel, "") : "",+ );+ const cxRecallCompressThinking = hasOwn(cx, "recallCompressThinking")+ ? cx.recallCompressThinking+ : (hasOwn(cx, "recallCompressReasoningEffort") ? cx.recallCompressReasoningEffort : "");+ const recallCompressThinking = str(+ process.env.OPENVIKING_RECALL_COMPRESS_THINKING,+ str(+ process.env.OPENVIKING_RECALL_COMPRESS_REASONING_EFFORT,+ str(cxRecallCompressThinking, ""),+ ),+ );return {configPath,cliConfigPath: cliPath,ovConfigPath: ovPath,- baseUrl,- apiKey,- account,- user,- peerId,+ credentialSource: creds.credentialSource,+ baseUrl: creds.baseUrl,+ apiKey: creds.apiKey,+ account: creds.account,+ user: creds.user,+ peerId: creds.peerId,timeoutMs,+ recallTimeoutMs,autoRecall: envBool("OPENVIKING_AUTO_RECALL") ?? (cx.autoRecall !== false),recallLimit: Math.max(1, Math.floor(num(@@ -216,6 +137,28 @@ export function loadConfig() {num(cx.minQueryLength, 3),))),logRankingDetails: envBool("OPENVIKING_LOG_RANKING_DETAILS") ?? (cx.logRankingDetails === true),+ recallCompress: envBool("OPENVIKING_RECALL_COMPRESS") ?? (cx.recallCompress !== false),+ recallCompressModel,+ recallCompressThinking,+ recallCompressConfigured: Boolean(recallCompressModel || recallCompressThinking),+ recallCompressTimeoutMs,+ recallCompressDetectOnStartup: envBool("OPENVIKING_RECALL_COMPRESS_DETECT_ON_STARTUP") ?? (cx.recallCompressDetectOnStartup !== false),+ recallCompressDetectTimeoutMs: Math.max(1000, Math.floor(num(+ process.env.OPENVIKING_RECALL_COMPRESS_DETECT_TIMEOUT_MS,+ num(cx.recallCompressDetectTimeoutMs, 15000),+ ))),+ recallCompressDetectTtlMs: Math.max(0, Math.floor(num(+ process.env.OPENVIKING_RECALL_COMPRESS_DETECT_TTL_MS,+ num(cx.recallCompressDetectTtlMs, 604800000),+ ))),+ recallCompressMaxInputChars: Math.max(1000, Math.floor(num(+ process.env.OPENVIKING_RECALL_COMPRESS_MAX_INPUT_CHARS,+ num(cx.recallCompressMaxInputChars, 18000),+ ))),+ recallCompressMaxBullets: Math.max(1, Math.floor(num(+ process.env.OPENVIKING_RECALL_COMPRESS_MAX_BULLETS,+ num(cx.recallCompressMaxBullets, 6),+ ))),autoCapture: envBool("OPENVIKING_AUTO_CAPTURE") ?? (cx.autoCapture !== false),captureMode: (str(process.env.OPENVIKING_CAPTURE_MODE, str(cx.captureMode, "semantic")) === "keyword")@@ -225,7 +168,15 @@ export function loadConfig() {process.env.OPENVIKING_CAPTURE_MAX_LENGTH,num(cx.captureMaxLength, 24000),))),+ captureMaxTurnsPerStop: Math.max(1, Math.floor(num(+ process.env.OPENVIKING_CAPTURE_MAX_TURNS_PER_STOP,+ num(cx.captureMaxTurnsPerStop, 8),+ ))),captureTimeoutMs,+ captureToolMaxChars: Math.max(200, Math.floor(num(+ process.env.OPENVIKING_CAPTURE_TOOL_MAX_CHARS,+ num(cx.captureToolMaxChars, 2000),+ ))),// Default true: a "memory plugin" without assistant-side capture only sees half the// conversation, which makes extraction noticeably worse. Mirrors the claude-code plugin// (examples/claude-code-memory-plugin/scripts/config.mjs). Operators who want the old@@ -234,6 +185,15 @@ export function loadConfig() {captureLastAssistantOnStop: envBool("OPENVIKING_CAPTURE_LAST_ASSISTANT_ON_STOP") ?? (cx.captureLastAssistantOnStop !== false),autoCommitOnCompact: envBool("OPENVIKING_AUTO_COMMIT_ON_COMPACT") ?? (cx.autoCommitOnCompact !== false),+ resumeArchiveInject: envBool("OPENVIKING_RESUME_ARCHIVE_INJECT") ?? (cx.resumeArchiveInject !== false),+ resumeArchiveTokenBudget: Math.max(0, Math.floor(num(+ process.env.OPENVIKING_RESUME_ARCHIVE_TOKEN_BUDGET,+ num(cx.resumeArchiveTokenBudget, 32000),+ ))),+ resumeArchiveMaxChars: Math.max(1000, Math.floor(num(+ process.env.OPENVIKING_RESUME_ARCHIVE_MAX_CHARS,+ num(cx.resumeArchiveMaxChars, 6000),+ ))),debug,debugLogPath,diff --git a/examples/codex-memory-plugin/scripts/ov-credentials.mjs b/examples/codex-memory-plugin/scripts/ov-credentials.mjsnew file mode 100644index 000000000..bdc688159--- /dev/null+++ b/examples/codex-memory-plugin/scripts/ov-credentials.mjs@@ -0,0 +1,310 @@+import { createHash } from "node:crypto";+import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { homedir } from "node:os";+import { join, resolve as resolvePath } from "node:path";+import { fileURLToPath } from "node:url";++const DEFAULT_OVCLI_CONF_PATH = join(homedir(), ".openviking", "ovcli.conf");+const DEFAULT_OV_CONF_PATH = join(homedir(), ".openviking", "ov.conf");+const DEFAULT_BASE_URL = "http://127.0.0.1:1933";++function str(val, fallback = "") {+ if (typeof val === "string" && val.trim()) return val.trim();+ return fallback;+}++function normalizePath(value) {+ const raw = str(value, "");+ if (!raw) return "";+ if (raw === "~") return homedir();+ if (raw.startsWith("~/")) return resolvePath(join(homedir(), raw.slice(2)));+ return resolvePath(raw);+}++function tryLoadJson(path) {+ if (!path) return null;+ try {+ return JSON.parse(readFileSync(path, "utf-8"));+ } catch {+ return null;+ }+}++function looksLikeOvcli(obj) {+ if (!obj || typeof obj !== "object") return false;+ if (obj.server && typeof obj.server === "object") return false;+ return Boolean(+ typeof obj.url === "string" ||+ typeof obj.api_key === "string" ||+ typeof obj.account === "string" ||+ typeof obj.account_id === "string" ||+ typeof obj.user === "string" ||+ typeof obj.user_id === "string" ||+ typeof obj.actor_peer_id === "string",+ );+}++function hasCredentialFields(obj) {+ if (!obj || typeof obj !== "object") return false;+ return [+ "url",+ "api_key",+ "account",+ "account_id",+ "user",+ "user_id",+ "actor_peer_id",+ "peer_id",+ ].some((key) => typeof obj[key] === "string");+}++export function loadCredentialFiles(env = process.env) {+ const cliPathCandidate = normalizePath(env.OPENVIKING_CLI_CONFIG_FILE) || DEFAULT_OVCLI_CONF_PATH;+ const ovPathCandidate = normalizePath(env.OPENVIKING_CONFIG_FILE) || DEFAULT_OV_CONF_PATH;+ const cliPathEnv = Boolean(str(env.OPENVIKING_CLI_CONFIG_FILE, ""));+ const ovPathEnv = Boolean(str(env.OPENVIKING_CONFIG_FILE, ""));++ let cliFile = tryLoadJson(cliPathCandidate);+ let cliPath = cliFile ? cliPathCandidate : "";+ let ovFile = tryLoadJson(ovPathCandidate);+ let ovPath = ovFile ? ovPathCandidate : "";++ // Backward compat: older plugin installs used OPENVIKING_CONFIG_FILE for+ // both ov.conf and ovcli.conf. Preserve that when the file is ovcli-shaped.+ if (ovPathEnv && !cliPathEnv && looksLikeOvcli(ovFile)) {+ cliFile = ovFile;+ cliPath = ovPath;+ ovFile = null;+ ovPath = "";+ }++ return {+ cliFile: cliFile || {},+ cliPath,+ cliPathCandidate,+ ovFile: ovFile || {},+ ovPath,+ };+}++function sourceMode(env) {+ const raw = str(env.OPENVIKING_CREDENTIAL_SOURCE, str(env.OPENVIKING_CREDENTIALS_SOURCE, "auto"))+ .toLowerCase();+ if (raw === "env" || raw === "environment") return "env";+ if (raw === "cli" || raw === "ovcli" || raw === "file" || raw === "config") return "cli";+ return "auto";+}++function deriveBaseUrl({ env, cliFile, ovFile, useCli }) {+ const envUrl = str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, ""));+ const cliUrl = str(cliFile.url, "");++ if (useCli && cliUrl) return cliUrl.replace(/\/+$/, "");+ if (!useCli && envUrl) return envUrl.replace(/\/+$/, "");+ if (!useCli && cliUrl) return cliUrl.replace(/\/+$/, "");++ const server = ovFile.server || {};+ const ovUrl = str(server.url, "");+ if (ovUrl) return ovUrl.replace(/\/+$/, "");++ const host = str(server.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1");+ const port = Number.isFinite(Number(server.port)) ? Math.floor(Number(server.port)) : 1933;+ return `http://${host}:${port}`;+}++export function resolveOpenVikingCredentials(env = process.env) {+ const files = loadCredentialFiles(env);+ const mode = sourceMode(env);+ const useCli = mode === "cli" || (mode === "auto" && files.cliPath && hasCredentialFields(files.cliFile));+ const cx = files.ovFile.codex || {};+ const server = files.ovFile.server || {};++ const baseUrl = deriveBaseUrl({ env, ...files, useCli });++ const apiKey = useCli+ ? str(files.cliFile.api_key, "")+ : (+ str(env.OPENVIKING_BEARER_TOKEN, "") ||+ str(env.OPENVIKING_API_KEY, "") ||+ str(files.cliFile.api_key, "") ||+ str(cx.apiKey, "") ||+ str(server.root_api_key, "")+ );++ const account = useCli+ ? str(files.cliFile.account, str(files.cliFile.account_id, ""))+ : (+ str(env.OPENVIKING_ACCOUNT, "") ||+ str(files.cliFile.account, str(files.cliFile.account_id, "")) ||+ str(cx.accountId, "")+ );++ const user = useCli+ ? str(files.cliFile.user, str(files.cliFile.user_id, ""))+ : (+ str(env.OPENVIKING_USER, "") ||+ str(files.cliFile.user, str(files.cliFile.user_id, "")) ||+ str(cx.userId, "")+ );++ const peerId = useCli+ ? str(files.cliFile.actor_peer_id, str(files.cliFile.peer_id, ""))+ : (+ str(env.OPENVIKING_PEER_ID, "") ||+ str(files.cliFile.actor_peer_id, str(files.cliFile.peer_id, "")) ||+ str(cx.peerId, str(cx.peer_id, ""))+ );++ const explicitMcpUrl = str(env.OPENVIKING_MCP_URL, "");+ const mcpUrl = (!useCli && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;++ return {+ ...files,+ credentialSource: useCli ? "ovcli" : (mode === "env" ? "env" : "auto"),+ baseUrl,+ mcpUrl,+ apiKey,+ account,+ user,+ peerId,+ hasApiKey: Boolean(apiKey),+ };+}++function shellQuote(value) {+ return `'${String(value ?? "").replace(/'/g, "'\\''")}'`;+}++function runtimeCliConfigObject(creds) {+ const config = {};+ if (creds.baseUrl) config.url = creds.baseUrl;+ if (creds.apiKey) config.api_key = creds.apiKey;+ if (creds.account) config.account = creds.account;+ if (creds.user) config.user = creds.user;+ if (creds.peerId) config.actor_peer_id = creds.peerId;+ return config;+}++function ensureRuntimeCliConfig(creds) {+ if (creds.credentialSource === "ovcli") {+ return creds.cliPath || creds.cliPathCandidate || "";+ }++ const content = JSON.stringify(runtimeCliConfigObject(creds), null, 2) + "\n";+ const digest = createHash("sha256").update(content).digest("hex").slice(0, 16);+ const dir = join(homedir(), ".openviking", "codex-plugin-state");+ const path = join(dir, `runtime-ovcli.${digest}.conf`);++ mkdirSync(dir, { recursive: true, mode: 0o700 });+ writeFileSync(path, content, { mode: 0o600 });+ try {+ chmodSync(path, 0o600);+ } catch { /* best effort */ }+ return path;+}++function printShellEnv() {+ const creds = resolveOpenVikingCredentials();+ const cliConfigPath = ensureRuntimeCliConfig(creds);+ const assignments = {+ OV_RESOLVED_SOURCE: creds.credentialSource,+ OV_RESOLVED_URL: creds.baseUrl,+ OV_RESOLVED_MCP_URL: creds.mcpUrl,+ OV_RESOLVED_API_KEY: creds.apiKey,+ OV_RESOLVED_ACCOUNT: creds.account,+ OV_RESOLVED_USER: creds.user,+ OV_RESOLVED_PEER_ID: creds.peerId,+ OV_RESOLVED_CLI_CONFIG_FILE: cliConfigPath,+ OV_RESOLVED_HAS_API_KEY: creds.hasApiKey ? "1" : "0",+ };+ for (const [key, value] of Object.entries(assignments)) {+ process.stdout.write(`${key}=${shellQuote(value)}\n`);+ }+}++export function syncMcpConfig(file, env = process.env) {+ const creds = resolveOpenVikingCredentials(env);+ const j = JSON.parse(readFileSync(file, "utf-8"));+ const s = j.mcpServers && j.mcpServers["openviking-memory"];+ if (!s) return false;++ let changed = false;+ if (creds.mcpUrl && s.url !== creds.mcpUrl) {+ s.url = creds.mcpUrl;+ changed = true;+ }++ const curBearer = s.bearer_token_env_var || "";+ if (creds.hasApiKey && curBearer !== "OPENVIKING_API_KEY") {+ s.bearer_token_env_var = "OPENVIKING_API_KEY";+ changed = true;+ } else if (!creds.hasApiKey && curBearer) {+ delete s.bearer_token_env_var;+ changed = true;+ }++ const headers = s.env_http_headers || {};+ const expectedHeaders = {+ "X-OpenViking-Account": "OPENVIKING_ACCOUNT",+ "X-OpenViking-User": "OPENVIKING_USER",+ };+ // Actor-peer is only mapped when a peer is actually configured. Codex's MCP+ // runtime treats unset env vars in env_http_headers as empty-string headers,+ // which the OV side then has to disambiguate from "no peer scope". Match+ // the bearer_token_env_var pattern: present only when there's something to+ // send. The wrapper.sh strips empty OPENVIKING_PEER_ID before exec'ing+ // codex, so without this guard the header would silently flip to "".+ if (creds.peerId) {+ expectedHeaders["X-OpenViking-Actor-Peer"] = "OPENVIKING_PEER_ID";+ } else if (headers["X-OpenViking-Actor-Peer"]) {+ delete headers["X-OpenViking-Actor-Peer"];+ changed = true;+ }+ for (const [header, envName] of Object.entries(expectedHeaders)) {+ if (headers[header] !== envName) {+ headers[header] = envName;+ changed = true;+ }+ }+ if (s.env_http_headers !== headers) {+ s.env_http_headers = headers;+ changed = true;+ }++ if (changed) {+ writeFileSync(file, JSON.stringify(j, null, 2) + "\n");+ }+ return changed;+}++function main() {+ const cmd = process.argv[2] || "";+ if (cmd === "shell-env") {+ printShellEnv();+ return;+ }+ if (cmd === "mcp-url") {+ process.stdout.write(resolveOpenVikingCredentials().mcpUrl);+ return;+ }+ if (cmd === "has-api-key") {+ process.stdout.write(resolveOpenVikingCredentials().hasApiKey ? "1" : "0");+ return;+ }+ if (cmd === "sync-mcp") {+ const file = process.argv[3];+ if (!file) {+ process.stderr.write("usage: ov-credentials.mjs sync-mcp <mcp.json>\n");+ process.exitCode = 2;+ return;+ }+ syncMcpConfig(file);+ return;+ }+ process.stderr.write("usage: ov-credentials.mjs <shell-env|mcp-url|has-api-key|sync-mcp>\n");+ process.exitCode = 2;+}++if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {+ main();+}diff --git a/examples/codex-memory-plugin/scripts/ov-credentials.test.mjs b/examples/codex-memory-plugin/scripts/ov-credentials.test.mjsnew file mode 100644index 000000000..1e78b2c64--- /dev/null+++ b/examples/codex-memory-plugin/scripts/ov-credentials.test.mjs@@ -0,0 +1,198 @@+import assert from "node:assert/strict";+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";+import { resolveOpenVikingCredentials, syncMcpConfig } from "./ov-credentials.mjs";++async function tempJson(prefix, value) {+ const dir = await mkdtemp(join(tmpdir(), prefix));+ const path = join(dir, "ovcli.conf");+ await writeFile(path, JSON.stringify(value, null, 2) + "\n");+ return { dir, path };+}++test("active ovcli config wins over stale credential env by default", async () => {+ const { dir, path } = await tempJson("ov-creds-cli-", {+ url: "https://ov.example.com",+ api_key: "cli-key",+ account: "default",+ user: "zeus",+ actor_peer_id: "peer-a",+ });+ try {+ const creds = resolveOpenVikingCredentials({+ OPENVIKING_CLI_CONFIG_FILE: path,+ OPENVIKING_URL: "https://stale.example.com",+ OPENVIKING_MCP_URL: "https://stale.example.com/mcp",+ OPENVIKING_API_KEY: "stale-key",+ OPENVIKING_ACCOUNT: "stale-account",+ OPENVIKING_USER: "stale-user",+ OPENVIKING_PEER_ID: "stale-peer",+ });++ assert.equal(creds.credentialSource, "ovcli");+ assert.equal(creds.baseUrl, "https://ov.example.com");+ assert.equal(creds.mcpUrl, "https://ov.example.com/mcp");+ assert.equal(creds.apiKey, "cli-key");+ assert.equal(creds.account, "default");+ assert.equal(creds.user, "zeus");+ assert.equal(creds.peerId, "peer-a");+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});++test("env source can be forced explicitly", async () => {+ const { dir, path } = await tempJson("ov-creds-env-", {+ url: "https://ov.example.com",+ api_key: "cli-key",+ user: "zeus",+ });+ try {+ const creds = resolveOpenVikingCredentials({+ OPENVIKING_CREDENTIAL_SOURCE: "env",+ OPENVIKING_CLI_CONFIG_FILE: path,+ OPENVIKING_URL: "https://env.example.com",+ OPENVIKING_MCP_URL: "https://env.example.com/custom-mcp",+ OPENVIKING_API_KEY: "env-key",+ OPENVIKING_ACCOUNT: "env-account",+ OPENVIKING_USER: "env-user",+ OPENVIKING_PEER_ID: "env-peer",+ });++ assert.equal(creds.credentialSource, "env");+ assert.equal(creds.baseUrl, "https://env.example.com");+ assert.equal(creds.mcpUrl, "https://env.example.com/custom-mcp");+ assert.equal(creds.apiKey, "env-key");+ assert.equal(creds.account, "env-account");+ assert.equal(creds.user, "env-user");+ assert.equal(creds.peerId, "env-peer");+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});++test("ovcli config without api_key does not inherit stale env key", async () => {+ const { dir, path } = await tempJson("ov-creds-noauth-", {+ url: "http://127.0.0.1:1933",+ });+ try {+ const creds = resolveOpenVikingCredentials({+ OPENVIKING_CLI_CONFIG_FILE: path,+ OPENVIKING_API_KEY: "stale-key",+ });++ assert.equal(creds.credentialSource, "ovcli");+ assert.equal(creds.baseUrl, "http://127.0.0.1:1933");+ assert.equal(creds.apiKey, "");+ assert.equal(creds.hasApiKey, false);+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});++test("syncMcpConfig with peerId maps actor-peer header", async () => {+ const { dir, path } = await tempJson("ov-creds-mcp-peer-", {+ url: "https://ov.example.com",+ api_key: "cli-key",+ actor_peer_id: "peer-a",+ });+ const mcpPath = join(dir, ".mcp.json");+ await writeFile(mcpPath, JSON.stringify({+ mcpServers: {+ "openviking-memory": {+ url: "__OPENVIKING_MCP_URL__",+ bearer_token_env_var: "STALE_KEY",+ env_http_headers: {},+ },+ },+ }, null, 2) + "\n");++ try {+ syncMcpConfig(mcpPath, { OPENVIKING_CLI_CONFIG_FILE: path });+ const rendered = JSON.parse(await readFile(mcpPath, "utf-8"));+ const server = rendered.mcpServers["openviking-memory"];++ assert.equal(server.url, "https://ov.example.com/mcp");+ assert.equal(server.bearer_token_env_var, "OPENVIKING_API_KEY");+ assert.deepEqual(server.env_http_headers, {+ "X-OpenViking-Account": "OPENVIKING_ACCOUNT",+ "X-OpenViking-User": "OPENVIKING_USER",+ "X-OpenViking-Actor-Peer": "OPENVIKING_PEER_ID",+ });+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});++test("syncMcpConfig without peerId omits actor-peer header (symmetric to bearer)", async () => {+ const { dir, path } = await tempJson("ov-creds-mcp-nopeer-", {+ url: "https://ov.example.com",+ api_key: "cli-key",+ });+ const mcpPath = join(dir, ".mcp.json");+ await writeFile(mcpPath, JSON.stringify({+ mcpServers: {+ "openviking-memory": {+ url: "__OPENVIKING_MCP_URL__",+ bearer_token_env_var: "STALE_KEY",+ env_http_headers: {},+ },+ },+ }, null, 2) + "\n");++ try {+ syncMcpConfig(mcpPath, { OPENVIKING_CLI_CONFIG_FILE: path });+ const rendered = JSON.parse(await readFile(mcpPath, "utf-8"));+ const server = rendered.mcpServers["openviking-memory"];++ assert.equal(server.url, "https://ov.example.com/mcp");+ assert.equal(server.bearer_token_env_var, "OPENVIKING_API_KEY");+ assert.deepEqual(server.env_http_headers, {+ "X-OpenViking-Account": "OPENVIKING_ACCOUNT",+ "X-OpenViking-User": "OPENVIKING_USER",+ });+ assert.equal(+ Object.prototype.hasOwnProperty.call(server.env_http_headers, "X-OpenViking-Actor-Peer"),+ false,+ );+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});++test("syncMcpConfig drops stale actor-peer header when peer is unset", async () => {+ const { dir, path } = await tempJson("ov-creds-mcp-drop-peer-", {+ url: "https://ov.example.com",+ api_key: "cli-key",+ });+ const mcpPath = join(dir, ".mcp.json");+ await writeFile(mcpPath, JSON.stringify({+ mcpServers: {+ "openviking-memory": {+ url: "__OPENVIKING_MCP_URL__",+ bearer_token_env_var: "STALE_KEY",+ env_http_headers: {+ "X-OpenViking-Account": "OPENVIKING_ACCOUNT",+ "X-OpenViking-User": "OPENVIKING_USER",+ "X-OpenViking-Actor-Peer": "OPENVIKING_PEER_ID",+ },+ },+ },+ }, null, 2) + "\n");++ try {+ const changed = syncMcpConfig(mcpPath, { OPENVIKING_CLI_CONFIG_FILE: path });+ assert.equal(changed, true);+ const rendered = JSON.parse(await readFile(mcpPath, "utf-8"));+ const server = rendered.mcpServers["openviking-memory"];++ assert.equal(+ Object.prototype.hasOwnProperty.call(server.env_http_headers, "X-OpenViking-Actor-Peer"),+ false,+ );+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});diff --git a/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs b/examples/codex-memory-plugin/scripts/pre-compact-capture.mjsindex 9c813dcd5..ce25486d6 100644--- a/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs+++ b/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs@@ -21,6 +21,12 @@*/import { readFile } from "node:fs/promises";+import {+ extractTextFromPayload,+ isAssistantSideCaptureRole,+ normalizeCaptureRole,+ shouldCaptureText,+} from "./capture-utils.mjs";import { loadConfig } from "./config.mjs";import { createLogger } from "./debug-log.mjs";import { loadState, resolveOvSessionId, saveState } from "./session-state.mjs";@@ -47,6 +53,7 @@ async function fetchJSON(path, init = {}) {}if (cfg.account) headers["X-OpenViking-Account"] = cfg.account;if (cfg.user) headers["X-OpenViking-User"] = cfg.user;+ if (cfg.peerId) headers["X-OpenViking-Actor-Peer"] = cfg.peerId;const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });const body = await res.json().catch(() => null);if (!body) return null;@@ -59,18 +66,6 @@ async function fetchJSON(path, init = {}) {}}-function extractTextFromContent(content) {- if (!content) return "";- if (typeof content === "string") return content;- if (Array.isArray(content)) {- return content- .filter((b) => b && (b.type === "text" || b.type === "input_text" || b.type === "output_text"))- .map((b) => b.text || "")- .join("\n");- }- return "";-}-function parseTranscript(content) {try {const data = JSON.parse(content);@@ -89,29 +84,16 @@ function extractTurns(entries) {for (const entry of entries) {if (!entry || typeof entry !== "object") continue;const payload = entry.payload && typeof entry.payload === "object" ? entry.payload : entry;- let role = payload.role;- let text = "";-- if (typeof payload.content === "string") {- text = payload.content;- } else if (Array.isArray(payload.content)) {- text = extractTextFromContent(payload.content);- } else if (payload.message && typeof payload.message === "object") {- role = payload.message.role || role;- text = typeof payload.message.content === "string"- ? payload.message.content- : extractTextFromContent(payload.message.content);- }-- if (role !== "user" && role !== "assistant") continue;- if (role === "assistant" && !cfg.captureAssistantTurns) continue;- const trimmed = text.trim();- if (!trimmed) continue;-- const capped = trimmed.length > cfg.captureMaxLength- ? trimmed.slice(0, cfg.captureMaxLength)- : trimmed;- turns.push({ role, text: capped });+ const message = payload.message && typeof payload.message === "object" ? payload.message : null;+ const rawRole = message?.role || payload.role || payload.type || payload.kind;+ const role = normalizeCaptureRole(rawRole);+ if (!role) continue;+ if (isAssistantSideCaptureRole(rawRole) && !cfg.captureAssistantTurns) continue;++ const rawText = extractTextFromPayload(payload, { toolMaxChars: cfg.captureToolMaxChars });+ const decision = shouldCaptureText(rawText, role, cfg);+ if (!decision.shouldCapture) continue;+ turns.push({ role, text: decision.text });}return turns;}diff --git a/examples/codex-memory-plugin/scripts/recall-compressor-profile.mjs b/examples/codex-memory-plugin/scripts/recall-compressor-profile.mjsnew file mode 100644index 000000000..d58b3002b--- /dev/null+++ b/examples/codex-memory-plugin/scripts/recall-compressor-profile.mjs@@ -0,0 +1,272 @@+import { readFile, rm } from "node:fs/promises";+import { homedir } from "node:os";+import { join } from "node:path";+import { mkdir, rename, writeFile } from "node:fs/promises";+import { getStateDir } from "./session-state.mjs";++const DEFAULT_PRIMARY = { model: "gpt-5.3-codex-spark", thinking: "default", source: "default_primary" };+const DEFAULT_FALLBACK = { model: "gpt-5.5", thinking: "low", source: "default_fallback" };+const PROFILE_SCHEMA_VERSION = 2;+const DEFAULT_CODEX_HOME = join(homedir(), ".codex");++function isOff(value) {+ return /^(?:0|false|no|off|none|disabled)$/i.test(String(value || "").trim());+}++function normalizeThinking(value) {+ const thinking = String(value || "").trim().toLowerCase();+ if (!thinking || thinking === "default") return "default";+ return thinking;+}++function normalizeModel(value) {+ return String(value || "").trim();+}++export function recallCompressionExplicitlyOff(cfg) {+ return !cfg.recallCompress || isOff(cfg.recallCompressModel) || isOff(cfg.recallCompressThinking);+}++export function buildCodexExecArgs(profile, outputPath) {+ const args = [];+ if (profile.model) args.push("-m", profile.model);+ if (profile.thinking && profile.thinking !== "default") {+ args.push("-c", `model_reasoning_effort=${JSON.stringify(profile.thinking)}`);+ }+ args.push(+ "--sandbox",+ "read-only",+ "--ask-for-approval",+ "never",+ "exec",+ "--ephemeral",+ "--ignore-user-config",+ "--skip-git-repo-check",+ "--output-last-message",+ outputPath,+ "-",+ );+ return args;+}++export function buildRecallCompressorCandidates(cfg) {+ if (recallCompressionExplicitlyOff(cfg)) return [];++ const candidates = [];+ if (cfg.recallCompressConfigured) {+ const configuredModel = normalizeModel(cfg.recallCompressModel) || DEFAULT_PRIMARY.model;+ candidates.push({+ model: configuredModel,+ thinking: normalizeThinking(cfg.recallCompressThinking),+ source: "configured",+ });+ }++ candidates.push(DEFAULT_PRIMARY, DEFAULT_FALLBACK);++ const seen = new Set();+ return candidates.filter((candidate) => {+ const key = `${candidate.model}\n${candidate.thinking}`;+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+}++function codexHomeDir(env = process.env) {+ const fromEnv = String(env.CODEX_HOME || "").trim();+ return fromEnv || DEFAULT_CODEX_HOME;+}++function modelsCachePath(env = process.env) {+ return join(codexHomeDir(env), "models_cache.json");+}++/**+ * Read codex's local model catalogue. Codex CLI maintains this file using+ * its own etag-backed fetch; reading it is the cheapest way to know which+ * model slugs `codex exec` can actually invoke. Missing or unreadable cache+ * → empty result, callers should treat that as "unknown availability" and+ * fall back to best effort.+ */+export async function loadCodexModelsCache(env = process.env) {+ try {+ const raw = await readFile(modelsCachePath(env), "utf-8");+ const parsed = JSON.parse(raw);+ if (!Array.isArray(parsed?.models)) return { slugs: new Set(), fetchedAt: null, present: false };+ const slugs = new Set();+ for (const entry of parsed.models) {+ if (entry && typeof entry.slug === "string" && entry.slug.trim()) {+ slugs.add(entry.slug.trim());+ }+ }+ return {+ slugs,+ fetchedAt: typeof parsed.fetched_at === "string" ? parsed.fetched_at : null,+ present: true,+ };+ } catch {+ return { slugs: new Set(), fetchedAt: null, present: false };+ }+}++export function fallbackRecallCompressorProfile(cfg) {+ const candidates = buildRecallCompressorCandidates(cfg);+ if (candidates.length === 0) {+ return { enabled: false, source: "off" };+ }+ return { enabled: true, ...candidates[0], detected: false };+}++function configKey(cfg) {+ return JSON.stringify({+ version: PROFILE_SCHEMA_VERSION,+ recallCompress: cfg.recallCompress,+ recallCompressModel: normalizeModel(cfg.recallCompressModel),+ recallCompressThinking: normalizeThinking(cfg.recallCompressThinking),+ recallCompressConfigured: cfg.recallCompressConfigured,+ });+}++function profilePath() {+ return join(getStateDir(), "recall-compressor-profile.json");+}++export async function loadCachedRecallCompressorProfile(cfg) {+ try {+ const raw = await readFile(profilePath(), "utf-8");+ const cached = JSON.parse(raw);+ if (cached?.configKey !== configKey(cfg)) return null;+ if (cfg.recallCompressDetectTtlMs > 0) {+ const age = Date.now() - Number(cached.checkedAt || 0);+ if (!Number.isFinite(age) || age > cfg.recallCompressDetectTtlMs) return null;+ }+ if (!cached.profile || typeof cached.profile !== "object") return null;+ return cached.profile;+ } catch {+ return null;+ }+}++async function saveRecallCompressorProfile(cfg, profile) {+ await mkdir(getStateDir(), { recursive: true });+ const final = profilePath();+ const tmp = `${final}.tmp`;+ await writeFile(tmp, JSON.stringify({+ schemaVersion: PROFILE_SCHEMA_VERSION,+ checkedAt: Date.now(),+ configKey: configKey(cfg),+ profile,+ }));+ await rename(tmp, final);+}++/**+ * Forget the cached compressor profile. Called when the actual `codex exec`+ * compress run fails (exit non-zero, timeout, missing model). Next caller+ * re-resolves from the current models_cache.json.+ */+export async function invalidateRecallCompressorProfileCache() {+ try {+ await rm(profilePath(), { force: true });+ } catch { /* best effort */ }+}++/**+ * Record a runtime compress failure as a disabled profile. UserPromptSubmit+ * reads the cached profile directly, so writing `enabled: false` here makes+ * subsequent UPS calls within the same codex session skip compress (and+ * fall back to deterministic digest) instead of paying ~recallCompressTimeoutMs+ * per turn on a guaranteed-to-fail spawn. The next SessionStart's cache-+ * first detect treats `source === "runtime_failed"` as a cache miss and+ * re-resolves from the current catalogue, so a transient failure does not+ * permanently disable compress across codex restarts.+ */+export async function markRecallCompressorRuntimeFailed(cfg, { failedModel = "" } = {}) {+ try {+ await saveRecallCompressorProfile(cfg, {+ enabled: false,+ source: "runtime_failed",+ failedModel: String(failedModel || ""),+ });+ } catch { /* best effort */ }+}++/**+ * Pick a compressor profile by consulting codex's local model catalogue.+ *+ * No subprocess: we read `~/.codex/models_cache.json` (codex CLI maintains+ * it via its own etag fetch) and pick the first candidate whose slug is+ * present. When the catalogue is absent (codex 0.130 pre-cache, fresh+ * install, etc.) we optimistically pick the first candidate and rely on+ * the runtime compress path to invalidate the cache on failure.+ */+export async function resolveRecallCompressorProfile(cfg, logger = {}, env = process.env) {+ const { log } = logger;++ if (recallCompressionExplicitlyOff(cfg)) {+ const profile = { enabled: false, source: "configured_off" };+ await saveRecallCompressorProfile(cfg, profile);+ log?.("compress_profile_selected", profile);+ return profile;+ }++ const candidates = buildRecallCompressorCandidates(cfg);+ if (candidates.length === 0) {+ const profile = { enabled: false, source: "no_candidates" };+ await saveRecallCompressorProfile(cfg, profile);+ log?.("compress_profile_selected", profile);+ return profile;+ }++ const catalogue = await loadCodexModelsCache(env);+ log?.("compress_profile_catalogue", {+ present: catalogue.present,+ count: catalogue.slugs.size,+ fetchedAt: catalogue.fetchedAt,+ });++ let pick = null;+ if (catalogue.present && catalogue.slugs.size > 0) {+ pick = candidates.find((c) => catalogue.slugs.has(c.model));+ }+ if (!pick) {+ // Catalogue missing or none of our candidates appear in it. Pick the+ // first candidate optimistically; if `codex exec` later fails, the+ // runtime compress path invalidates this cache and re-resolves.+ pick = candidates[0];+ }++ const detected = catalogue.present && catalogue.slugs.has(pick.model);+ const profile = { enabled: true, ...pick, detected };+ await saveRecallCompressorProfile(cfg, profile);+ log?.("compress_profile_selected", profile);+ return profile;+}++/**+ * Cache-first profile lookup used by SessionStart and UserPromptSubmit.+ *+ * SessionStart no longer probes models with a subprocess on every fire.+ * Instead it loads the cached profile and only resolves (a cheap+ * models_cache.json read) when nothing is cached or the cache is stale.+ * The runtime compress path invalidates the cache on failure, which is+ * what triggers the next re-resolve.+ */+export async function detectRecallCompressorProfile(cfg, logger = {}, env = process.env) {+ const { log } = logger;+ const cached = await loadCachedRecallCompressorProfile(cfg);+ if (cached && cached.source !== "runtime_failed") {+ log?.("compress_profile_cache_hit", cached);+ return cached;+ }+ if (cached && cached.source === "runtime_failed") {+ log?.("compress_profile_recover", { failedModel: cached.failedModel || "" });+ }+ if (!cfg.recallCompressDetectOnStartup) {+ log?.("compress_profile_skip", { reason: "detect disabled and no usable cache" });+ return cached || null;+ }+ log?.("compress_profile_resolve", { reason: cached ? "runtime_failed_recover" : "cache_miss" });+ return resolveRecallCompressorProfile(cfg, logger, env);+}diff --git a/examples/codex-memory-plugin/scripts/recall-compressor-profile.test.mjs b/examples/codex-memory-plugin/scripts/recall-compressor-profile.test.mjsnew file mode 100644index 000000000..711cef3d4--- /dev/null+++ b/examples/codex-memory-plugin/scripts/recall-compressor-profile.test.mjs@@ -0,0 +1,275 @@+import assert from "node:assert/strict";+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";++import {+ detectRecallCompressorProfile,+ invalidateRecallCompressorProfileCache,+ loadCachedRecallCompressorProfile,+ loadCodexModelsCache,+ markRecallCompressorRuntimeFailed,+ resolveRecallCompressorProfile,+} from "./recall-compressor-profile.mjs";++function baseCfg(overrides = {}) {+ return {+ recallCompress: true,+ recallCompressModel: "",+ recallCompressThinking: "",+ recallCompressConfigured: false,+ recallCompressDetectOnStartup: true,+ recallCompressDetectTtlMs: 604_800_000,+ ...overrides,+ };+}++async function withTempState(action) {+ const stateDir = await mkdtemp(join(tmpdir(), "ov-compressor-state-"));+ const codexHome = await mkdtemp(join(tmpdir(), "ov-codex-home-"));+ const prevState = process.env.OPENVIKING_CODEX_STATE_DIR;+ process.env.OPENVIKING_CODEX_STATE_DIR = stateDir;+ try {+ await action({ stateDir, codexHome });+ } finally {+ if (prevState === undefined) delete process.env.OPENVIKING_CODEX_STATE_DIR;+ else process.env.OPENVIKING_CODEX_STATE_DIR = prevState;+ await rm(stateDir, { recursive: true, force: true });+ await rm(codexHome, { recursive: true, force: true });+ }+}++async function writeModelsCache(codexHome, slugs) {+ await writeFile(+ join(codexHome, "models_cache.json"),+ JSON.stringify({+ fetched_at: "2026-06-15T00:00:00Z",+ models: slugs.map((slug) => ({ slug })),+ }),+ );+}++test("loadCodexModelsCache returns empty set when cache missing", async () => {+ await withTempState(async ({ codexHome }) => {+ const result = await loadCodexModelsCache({ CODEX_HOME: codexHome });+ assert.equal(result.present, false);+ assert.equal(result.slugs.size, 0);+ });+});++test("loadCodexModelsCache parses available slugs", async () => {+ await withTempState(async ({ codexHome }) => {+ await writeModelsCache(codexHome, ["gpt-5.3-codex-spark", "gpt-5.5", "codex-auto-review"]);+ const result = await loadCodexModelsCache({ CODEX_HOME: codexHome });+ assert.equal(result.present, true);+ assert.equal(result.slugs.size, 3);+ assert.equal(result.slugs.has("gpt-5.3-codex-spark"), true);+ assert.equal(result.slugs.has("gpt-5.5"), true);+ });+});++test("resolveRecallCompressorProfile picks first candidate present in cache", async () => {+ await withTempState(async ({ stateDir, codexHome }) => {+ await writeModelsCache(codexHome, ["gpt-5.5", "codex-auto-review"]);+ const profile = await resolveRecallCompressorProfile(+ baseCfg(),+ {},+ { CODEX_HOME: codexHome },+ );+ assert.equal(profile.enabled, true);+ assert.equal(profile.model, "gpt-5.5");+ assert.equal(profile.detected, true);+ const persisted = JSON.parse(+ await readFile(join(stateDir, "recall-compressor-profile.json"), "utf-8"),+ );+ assert.equal(persisted.profile.model, "gpt-5.5");+ });+});++test("resolveRecallCompressorProfile honors configured candidate first when present", async () => {+ await withTempState(async ({ codexHome }) => {+ await writeModelsCache(codexHome, ["gpt-5.5", "gpt-5.3-codex-spark"]);+ const profile = await resolveRecallCompressorProfile(+ baseCfg({+ recallCompressModel: "gpt-5.5",+ recallCompressThinking: "low",+ recallCompressConfigured: true,+ }),+ {},+ { CODEX_HOME: codexHome },+ );+ assert.equal(profile.enabled, true);+ assert.equal(profile.model, "gpt-5.5");+ assert.equal(profile.thinking, "low");+ assert.equal(profile.source, "configured");+ assert.equal(profile.detected, true);+ });+});++test("resolveRecallCompressorProfile falls back optimistically when cache missing", async () => {+ await withTempState(async ({ codexHome }) => {+ const profile = await resolveRecallCompressorProfile(+ baseCfg(),+ {},+ { CODEX_HOME: codexHome },+ );+ assert.equal(profile.enabled, true);+ assert.equal(profile.model, "gpt-5.3-codex-spark");+ assert.equal(profile.detected, false);+ });+});++test("resolveRecallCompressorProfile disables when compress is configured off", async () => {+ await withTempState(async ({ codexHome }) => {+ await writeModelsCache(codexHome, ["gpt-5.5"]);+ const profile = await resolveRecallCompressorProfile(+ baseCfg({ recallCompress: false }),+ {},+ { CODEX_HOME: codexHome },+ );+ assert.equal(profile.enabled, false);+ assert.equal(profile.source, "configured_off");+ });+});++test("invalidateRecallCompressorProfileCache removes the persisted profile", async () => {+ await withTempState(async ({ stateDir, codexHome }) => {+ await writeModelsCache(codexHome, ["gpt-5.3-codex-spark"]);+ await resolveRecallCompressorProfile(baseCfg(), {}, { CODEX_HOME: codexHome });+ const path = join(stateDir, "recall-compressor-profile.json");+ await readFile(path, "utf-8"); // exists+ await invalidateRecallCompressorProfileCache();+ await assert.rejects(() => readFile(path, "utf-8"), /ENOENT/);+ });+});++test("detectRecallCompressorProfile prefers cached profile (no probe even when cache exists)", async () => {+ await withTempState(async ({ stateDir, codexHome }) => {+ // Seed cache with a different model than what the resolver would pick now.+ await writeModelsCache(codexHome, ["gpt-5.3-codex-spark"]);+ await resolveRecallCompressorProfile(baseCfg(), {}, { CODEX_HOME: codexHome });++ // Change the catalogue so the resolver would pick something else if it+ // ran again; cache-first detect should NOT re-resolve.+ await writeModelsCache(codexHome, ["gpt-5.5"]);++ const profile = await detectRecallCompressorProfile(+ baseCfg(),+ {},+ { CODEX_HOME: codexHome },+ );+ assert.equal(profile.model, "gpt-5.3-codex-spark");+ // Persisted profile is unchanged.+ const persisted = JSON.parse(+ await readFile(join(stateDir, "recall-compressor-profile.json"), "utf-8"),+ );+ assert.equal(persisted.profile.model, "gpt-5.3-codex-spark");+ });+});++test("detectRecallCompressorProfile resolves on cache miss", async () => {+ await withTempState(async ({ codexHome }) => {+ await writeModelsCache(codexHome, ["gpt-5.5"]);+ const profile = await detectRecallCompressorProfile(+ baseCfg(),+ {},+ { CODEX_HOME: codexHome },+ );+ assert.equal(profile.enabled, true);+ assert.equal(profile.model, "gpt-5.5");+ });+});++test("detectRecallCompressorProfile after invalidate re-resolves against current catalogue", async () => {+ await withTempState(async ({ codexHome }) => {+ await writeModelsCache(codexHome, ["gpt-5.3-codex-spark", "gpt-5.5"]);+ const initial = await detectRecallCompressorProfile(+ baseCfg(),+ {},+ { CODEX_HOME: codexHome },+ );+ assert.equal(initial.model, "gpt-5.3-codex-spark");++ // Simulate runtime compress failure → invalidate cache, then drop the+ // failing slug from the catalogue. Next detect should pick the next one.+ await invalidateRecallCompressorProfileCache();+ await writeModelsCache(codexHome, ["gpt-5.5"]);++ const next = await detectRecallCompressorProfile(+ baseCfg(),+ {},+ { CODEX_HOME: codexHome },+ );+ assert.equal(next.model, "gpt-5.5");+ assert.equal(next.detected, true);+ });+});++test("detectRecallCompressorProfile with detect_on_startup=false returns null on cache miss", async () => {+ await withTempState(async ({ codexHome }) => {+ await writeModelsCache(codexHome, ["gpt-5.5"]);+ const profile = await detectRecallCompressorProfile(+ baseCfg({ recallCompressDetectOnStartup: false }),+ {},+ { CODEX_HOME: codexHome },+ );+ assert.equal(profile, null);+ });+});++test("markRecallCompressorRuntimeFailed writes a disabled profile cached for UPS skip", async () => {+ await withTempState(async ({ codexHome }) => {+ await writeModelsCache(codexHome, ["gpt-5.5"]);+ await resolveRecallCompressorProfile(baseCfg(), {}, { CODEX_HOME: codexHome });++ await markRecallCompressorRuntimeFailed(baseCfg(), { failedModel: "gpt-5.3-codex-spark" });+ const cached = await loadCachedRecallCompressorProfile(baseCfg());+ assert.ok(cached, "expected cached profile to exist");+ assert.equal(cached.enabled, false);+ assert.equal(cached.source, "runtime_failed");+ assert.equal(cached.failedModel, "gpt-5.3-codex-spark");+ });+});++test("detectRecallCompressorProfile recovers across SessionStart after runtime_failed marker", async () => {+ await withTempState(async ({ codexHome }) => {+ // Initial healthy resolve.+ await writeModelsCache(codexHome, ["gpt-5.3-codex-spark", "gpt-5.5"]);+ const initial = await detectRecallCompressorProfile(baseCfg(), {}, { CODEX_HOME: codexHome });+ assert.equal(initial.model, "gpt-5.3-codex-spark");++ // Runtime compress failure marks the cache disabled. UPS within the+ // same session would now read this disabled profile and skip compress.+ await markRecallCompressorRuntimeFailed(baseCfg(), { failedModel: "gpt-5.3-codex-spark" });+ const within = await loadCachedRecallCompressorProfile(baseCfg());+ assert.equal(within.enabled, false);++ // Next codex SessionStart: catalogue shrinks (the failed slug went+ // away). Detect should treat runtime_failed as cache miss and+ // re-resolve against the current catalogue, picking gpt-5.5.+ await writeModelsCache(codexHome, ["gpt-5.5"]);+ const recovered = await detectRecallCompressorProfile(baseCfg(), {}, { CODEX_HOME: codexHome });+ assert.equal(recovered.enabled, true);+ assert.equal(recovered.model, "gpt-5.5");+ });+});++test("detectRecallCompressorProfile with detect_on_startup=false honors runtime_failed marker", async () => {+ await withTempState(async ({ codexHome }) => {+ await writeModelsCache(codexHome, ["gpt-5.5"]);+ await resolveRecallCompressorProfile(baseCfg(), {}, { CODEX_HOME: codexHome });+ await markRecallCompressorRuntimeFailed(baseCfg(), { failedModel: "gpt-5.5" });++ const profile = await detectRecallCompressorProfile(+ baseCfg({ recallCompressDetectOnStartup: false }),+ {},+ { CODEX_HOME: codexHome },+ );+ // With detect-on-startup disabled, we respect the marker (don't auto-+ // recover); UPS keeps skipping compress until manual intervention.+ assert.ok(profile);+ assert.equal(profile.enabled, false);+ assert.equal(profile.source, "runtime_failed");+ });+});diff --git a/examples/codex-memory-plugin/scripts/session-start-commit.mjs b/examples/codex-memory-plugin/scripts/session-start-commit.mjsindex e67de64e2..a50172ab9 100644--- a/examples/codex-memory-plugin/scripts/session-start-commit.mjs+++ b/examples/codex-memory-plugin/scripts/session-start-commit.mjs@@ -3,10 +3,11 @@/*** SessionStart hook for Codex.*- * Triggers (matcher = "clear|startup" in hooks.json):+ * Triggers (matcher = "clear|startup|resume" in hooks.json):* - source=startup → fresh codex CLI / `/new` / zouk daemon spawn-without-sessionId* - source=clear → `/clear` (orphans the current process's previous session)- * - source=resume → `/resume` or short reconnect (HARD no-op for commit)+ * - source=resume → `/resume` or short reconnect (no commit/sweep;+ * may inject latest archive summary if the live OV session was already committed)** Behavior (see DESIGN.md §3 — "SessionStart source=startup, heuristic"):* On `startup` or `clear`, run the active-window heuristic over state files@@ -27,12 +28,14 @@* clearState — we keep the state file with ovSessionId still set so the* next sweep retries. A transient OV outage shouldn't lose memory.*- * Output schema accepts {} as a no-op.+ * Output schema accepts {} as a no-op, or hookSpecificOutput.additionalContext+ * for resume archive context injection.*/import { loadConfig } from "./config.mjs";import { createLogger } from "./debug-log.mjs";-import { clearState, listStates } from "./session-state.mjs";+import { detectRecallCompressorProfile } from "./recall-compressor-profile.mjs";+import { clearState, deriveOvSessionId, listStates, loadState } from "./session-state.mjs";const cfg = loadConfig();const { log, logError } = createLogger("session-start");@@ -55,6 +58,24 @@ function noop(message) {output(message ? { systemMessage: message } : {});}+function emitAdditionalContext(additionalContext) {+ if (!additionalContext) {+ noop();+ return;+ }+ const wrappedContext = wrapResumeContext(additionalContext);+ if (!wrappedContext) {+ noop();+ return;+ }+ output({+ hookSpecificOutput: {+ hookEventName: "SessionStart",+ additionalContext: wrappedContext,+ },+ });+}+async function fetchJSON(path, init = {}) {const controller = new AbortController();const timer = setTimeout(() => controller.abort(), cfg.captureTimeoutMs);@@ -66,6 +87,7 @@ async function fetchJSON(path, init = {}) {}if (cfg.account) headers["X-OpenViking-Account"] = cfg.account;if (cfg.user) headers["X-OpenViking-User"] = cfg.user;+ if (cfg.peerId) headers["X-OpenViking-Actor-Peer"] = cfg.peerId;const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });const body = await res.json().catch(() => null);if (!body) return null;@@ -86,6 +108,75 @@ async function commitOvSession(ovSessionId) {);}+function truncateText(text, maxChars) {+ const value = String(text || "").trim();+ if (value.length <= maxChars) return value;+ return `${value.slice(0, Math.max(0, maxChars - 20)).trimEnd()}\n[truncated]`;+}++function buildResumeArchiveContext(ovSessionId, context) {+ const overview = String(context?.latest_archive_overview || "").trim();+ if (!overview) return "";+ const archiveUri = `viking://user/sessions/${ovSessionId}/history/`;+ const body = truncateText(overview, cfg.resumeArchiveMaxChars);+ return [+ "OpenViking session archive digest:",+ `Latest committed archive for resumed Codex session ${ovSessionId}:`,+ body,+ "",+ `More detail: use the OpenViking MCP read/search tools with ${archiveUri} if you need exact prior commands, files, tool outputs, or messages.`,+ ].join("\n");+}++function wrapResumeContext(additionalContext) {+ const body = String(additionalContext || "")+ .replace(/<\/?openviking-context\b[^>]*>/gi, "openviking context marker")+ .trim();+ if (!body) return "";+ return [+ '<openviking-context source="session-resume" format="archive-digest">',+ body,+ "</openviking-context>",+ ].join("\n");+}++async function injectResumeArchive(newSessionId) {+ if (!cfg.resumeArchiveInject) {+ log("skip", { stage: "resume_archive", reason: "disabled" });+ noop();+ return;+ }++ const state = await loadState(newSessionId);+ if (state.ovSessionId) {+ log("skip", {+ stage: "resume_archive",+ reason: "live OV session still open",+ ovSessionId: state.ovSessionId,+ });+ noop();+ return;+ }++ const ovSessionId = deriveOvSessionId(newSessionId);+ const context = await fetchJSON(+ `/api/v1/sessions/${encodeURIComponent(ovSessionId)}/context?token_budget=${cfg.resumeArchiveTokenBudget}`,+ );+ const additionalContext = buildResumeArchiveContext(ovSessionId, context);+ if (!additionalContext) {+ log("skip", { stage: "resume_archive", reason: "no archive overview", ovSessionId });+ noop();+ return;+ }++ log("resume_archive_inject", {+ ovSessionId,+ chars: additionalContext.length,+ tokenBudget: cfg.resumeArchiveTokenBudget,+ });+ emitAdditionalContext(additionalContext);+}+/*** Commit and clear a single state file. On commit failure, preserve state* (don't call clearState) so the next sweep retries.@@ -146,8 +237,20 @@ async function main() {const newSessionId = input.session_id || "unknown";log("start", { source, newSessionId, activeWindowMs: ACTIVE_WINDOW_MS, idleTtlMs: IDLE_TTL_MS });- // resume is a hard no-op — we don't even sweep, because resume re-fires on- // short reconnects and we'd otherwise sweep on every reconnect blip.+ try {+ await detectRecallCompressorProfile(cfg, { log, logError });+ } catch (err) {+ logError("compress_profile_detect_uncaught", err);+ }++ if (source === "resume") {+ await injectResumeArchive(newSessionId);+ return;+ }++ // Other non-startup sources are hard no-ops. We don't sweep there, because+ // reconnect-like sources may fire often and sweep should stay tied to a new+ // session boundary.if (source !== "startup" && source !== "clear") {log("skip", { stage: "source_check", reason: `source=${source} (only startup|clear act)` });noop();diff --git a/examples/codex-memory-plugin/setup-helper/install.sh b/examples/codex-memory-plugin/setup-helper/install.shindex 584bdad7a..e1c55d1cd 100755--- a/examples/codex-memory-plugin/setup-helper/install.sh+++ b/examples/codex-memory-plugin/setup-helper/install.sh@@ -226,6 +226,11 @@ if [ ! -d "$PLUGIN_DIR/.codex-plugin" ]; thenerr "Codex plugin not found at $PLUGIN_DIR"exit 1fi+CREDS_SCRIPT="$PLUGIN_DIR/scripts/ov-credentials.mjs"+if [ ! -f "$CREDS_SCRIPT" ]; then+ err "Credential resolver not found at $CREDS_SCRIPT"+ exit 1+fiPLUGIN_VERSION="$(node -e 'const p=require(process.argv[1]); console.log(p.version || "0.0.0")' "$PLUGIN_DIR/.codex-plugin/plugin.json")"@@ -233,34 +238,11 @@ PLUGIN_VERSION="$(node -e 'const p=require(process.argv[1]); console.log(p.versiheading "4. Plugin install ($PLUGIN_ID, version $PLUGIN_VERSION)"-# Resolve the OpenViking /mcp endpoint at install time. Priority:-# OPENVIKING_MCP_URL (env, full /mcp URL) > OPENVIKING_URL (env, base URL) >-# ovcli.conf .url > default localhost.+# Resolve the OpenViking /mcp endpoint at install time using the same+# credential resolver that hooks and the shell wrapper use. By default the+# active ovcli.conf wins; set OPENVIKING_CREDENTIAL_SOURCE=env to force env.resolve_mcp_url() {- if [ -n "${OPENVIKING_MCP_URL:-}" ]; then- printf '%s' "$OPENVIKING_MCP_URL"- return- fi- if [ -n "${OPENVIKING_URL:-}" ]; then- printf '%s/mcp' "${OPENVIKING_URL%/}"- return- fi- if [ -f "$OVCLI_CONF" ] && command -v node >/dev/null 2>&1; then- local from_conf- from_conf="$(node -e '- try {- const c = JSON.parse(require("node:fs").readFileSync(process.argv[1], "utf8"));- if (typeof c.url === "string" && c.url) {- process.stdout.write(c.url.replace(/\/+$/, "") + "/mcp");- }- } catch {}- ' "$OVCLI_CONF" 2>/dev/null || true)"- if [ -n "$from_conf" ]; then- printf '%s' "$from_conf"- return- fi- fi- printf '%s' "$DEFAULT_MCP_URL"+ OPENVIKING_CLI_CONFIG_FILE="$OVCLI_CONF" node "$CREDS_SCRIPT" mcp-url 2>/dev/null || printf '%s' "$DEFAULT_MCP_URL"}MCP_URL="$(resolve_mcp_url)"@@ -359,22 +341,6 @@ NODEinfo "Enabled plugin + features.plugin_hooks in $CODEX_CONFIG"CACHE_DIR="$HOME/.codex/plugins/cache/$MARKETPLACE_NAME/$PLUGIN_NAME/$PLUGIN_VERSION"-mkdir -p "$(dirname "$CACHE_DIR")"-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.-HOOKS_JSON="$CACHE_DIR/hooks/hooks.json"-if [ -f "$HOOKS_JSON" ]; then- CACHE_ESC="$(printf '%s' "$CACHE_DIR" | sed -e 's/[\\/&]/\\&/g')"- sed -i.bak -e "s/__OPENVIKING_PLUGIN_ROOT__/$CACHE_ESC/g" "$HOOKS_JSON"- rm -f "${HOOKS_JSON}.bak"-fi# Detect whether the user has an OpenViking API key configured anywhere.# When they don't (typical for a local unauth OV), we render .mcp.json@@ -382,48 +348,48 @@ fi# OPENVIKING_API_KEY at MCP launch and trigger its OAuth fallback for# what should be an unauthenticated server.detect_api_key() {- if [ -n "${OPENVIKING_API_KEY:-}" ] || [ -n "${OPENVIKING_BEARER_TOKEN:-}" ]; then- echo "1"- return- fi- if [ -f "$OVCLI_CONF" ]; then- node -e '- try {- const c = JSON.parse(require("node:fs").readFileSync(process.argv[1], "utf8"));- process.stdout.write(c.api_key ? "1" : "0");- } catch { process.stdout.write("0"); }- ' "$OVCLI_CONF" 2>/dev/null || echo "0"- return- fi- echo "0"+ OPENVIKING_CLI_CONFIG_FILE="$OVCLI_CONF" node "$CREDS_SCRIPT" has-api-key 2>/dev/null || echo "0"}HAS_API_KEY="$(detect_api_key)"-# 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.-MCP_JSON="$CACHE_DIR/.mcp.json"-if [ -f "$MCP_JSON" ]; then- node - "$MCP_JSON" "$MCP_URL" "$HAS_API_KEY" <<'NODE'-const fs = require("node:fs");-const [, , file, url, hasKey] = process.argv;-const j = JSON.parse(fs.readFileSync(file, "utf8"));-const s = j.mcpServers["openviking-memory"];-s.url = url;-if (hasKey !== "1") {- delete s.bearer_token_env_var;+render_plugin_cache() {+ mkdir -p "$(dirname "$CACHE_DIR")"+ 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.+ 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"+ 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.+ local mcp_json="$CACHE_DIR/.mcp.json"+ if [ -f "$mcp_json" ]; then+ OPENVIKING_CLI_CONFIG_FILE="$OVCLI_CONF" OPENVIKING_MCP_URL="$MCP_URL" \+ node "$CREDS_SCRIPT" sync-mcp "$mcp_json"+ fi}-fs.writeFileSync(file, JSON.stringify(j, null, 2) + "\n");-NODE-fi++render_plugin_cacheinfo "Plugin cache: $CACHE_DIR"info "MCP auth: $([ "$HAS_API_KEY" = "1" ] && echo "Bearer (OPENVIKING_API_KEY)" || echo "none (unauthenticated)")"# ----- 5. Shell rc wrapper -----## The MCP server reads OPENVIKING_API_KEY (and OPENVIKING_ACCOUNT / _USER /-# _AGENT_ID) from the process env at codex launch. Install a `codex` shell+# _PEER_ID) from the process env at codex launch. Install a `codex` shell# function that pulls these from ovcli.conf at invocation time, so the user# doesn't have to `export` secrets globally.#@@ -449,6 +415,62 @@ case "${SHELL:-}" in;;esac+read_marker_export() {+ local key="$1"+ [ -n "$RC" ] && [ -f "$RC" ] || return 0+ awk -v k="$key" -F"'" '+ $0 ~ "^export " k "=" { print $2; exit }+ $0 ~ "^" k "=" { print $2; exit }+ ' "$RC" 2>/dev/null || true+}++sanitize_marker_value() {+ printf '%s' "$1" | tr -d '\r\n' | sed "s/'//g"+}++RECALL_COMPRESS_SETTING="$(sanitize_marker_value "${OPENVIKING_RECALL_COMPRESS:-$(read_marker_export OPENVIKING_RECALL_COMPRESS)}")"+RECALL_COMPRESS_MODEL_SETTING="$(sanitize_marker_value "${OPENVIKING_RECALL_COMPRESS_MODEL:-$(read_marker_export OPENVIKING_RECALL_COMPRESS_MODEL)}")"+RECALL_COMPRESS_THINKING_SETTING="$(sanitize_marker_value "${OPENVIKING_RECALL_COMPRESS_THINKING:-$(read_marker_export OPENVIKING_RECALL_COMPRESS_THINKING)}")"++if [ -t 0 ]; then+ info 'Recall compressor profile: re-detect at each Codex SessionStart, cached for later UserPromptSubmit hooks.'+ info 'Auto fallback order: configured model/thinking -> gpt-5.3-codex-spark/default -> gpt-5.5/low -> off.'+ if [ -n "$RECALL_COMPRESS_SETTING$RECALL_COMPRESS_MODEL_SETTING$RECALL_COMPRESS_THINKING_SETTING" ]; then+ info "Current recall compressor env: compress=${RECALL_COMPRESS_SETTING:-auto} model=${RECALL_COMPRESS_MODEL_SETTING:-auto} thinking=${RECALL_COMPRESS_THINKING_SETTING:-auto}"+ ask 'Recall compressor [k=keep, a=auto, c=custom, o=off; default k]: '+ read -r RECALL_INPUT || RECALL_INPUT=""+ RECALL_INPUT="${RECALL_INPUT:-k}"+ else+ ask 'Recall compressor [a=auto, c=custom, o=off; default a]: '+ read -r RECALL_INPUT || RECALL_INPUT=""+ RECALL_INPUT="${RECALL_INPUT:-a}"+ fi+ case "$RECALL_INPUT" in+ k|K|keep|KEEP)+ :+ ;;+ o|O|off|OFF)+ RECALL_COMPRESS_SETTING="0"+ RECALL_COMPRESS_MODEL_SETTING=""+ RECALL_COMPRESS_THINKING_SETTING=""+ ;;+ c|C|custom|CUSTOM)+ ask 'Compressor model [gpt-5.3-codex-spark]: '+ read -r RECALL_MODEL_INPUT || RECALL_MODEL_INPUT=""+ ask 'Compressor thinking/reasoning effort [default]: '+ read -r RECALL_THINKING_INPUT || RECALL_THINKING_INPUT=""+ RECALL_COMPRESS_SETTING="1"+ RECALL_COMPRESS_MODEL_SETTING="$(sanitize_marker_value "${RECALL_MODEL_INPUT:-gpt-5.3-codex-spark}")"+ RECALL_COMPRESS_THINKING_SETTING="$(sanitize_marker_value "${RECALL_THINKING_INPUT:-default}")"+ ;;+ *)+ RECALL_COMPRESS_SETTING=""+ RECALL_COMPRESS_MODEL_SETTING=""+ RECALL_COMPRESS_THINKING_SETTING=""+ ;;+ esac+fi+# Extra launch commands to wrap besides `codex` — e.g. a custom wrapper# `codex-custom`, or a multi-word launcher matched on its sub-command.# Persisted in the rc marker block as OPENVIKING_CODEX_WRAP_EXTRA; the wrapper@@ -491,6 +513,20 @@ if [ -n "$WRAP_EXTRA" ]; then[ -n "$WRAP_EXTRA" ] && info "Will wrap: $WRAP_EXTRA"fi+RECALL_ENV_BLOCK=""+if [ -n "$RECALL_COMPRESS_SETTING" ]; then+ RECALL_ENV_BLOCK="${RECALL_ENV_BLOCK}export OPENVIKING_RECALL_COMPRESS='$RECALL_COMPRESS_SETTING'+"+fi+if [ -n "$RECALL_COMPRESS_MODEL_SETTING" ]; then+ RECALL_ENV_BLOCK="${RECALL_ENV_BLOCK}export OPENVIKING_RECALL_COMPRESS_MODEL='$RECALL_COMPRESS_MODEL_SETTING'+"+fi+if [ -n "$RECALL_COMPRESS_THINKING_SETTING" ]; then+ RECALL_ENV_BLOCK="${RECALL_ENV_BLOCK}export OPENVIKING_RECALL_COMPRESS_THINKING='$RECALL_COMPRESS_THINKING_SETTING'+"+fi+# The hook content stays stable across installs (only the absolute path# matters), so the marker-replacement logic only triggers the legacy cleanup# path once when upgrading from a pre-rc-split install that inlined the full@@ -498,12 +534,12 @@ fiSOURCE_HOOK="[ -f \"$WRAPPER_SRC\" ] && . \"$WRAPPER_SRC\""if [ -n "$WRAP_EXTRA" ]; thenSOURCE_BLOCK="$WRAPPER_MARKER_BEGIN-OPENVIKING_CODEX_WRAP_EXTRA='$WRAP_EXTRA'+${RECALL_ENV_BLOCK}OPENVIKING_CODEX_WRAP_EXTRA='$WRAP_EXTRA'$SOURCE_HOOK$WRAPPER_MARKER_END"elseSOURCE_BLOCK="$WRAPPER_MARKER_BEGIN-$SOURCE_HOOK+${RECALL_ENV_BLOCK}$SOURCE_HOOK$WRAPPER_MARKER_END"fi@@ -543,6 +579,100 @@ if [ ! -f "$OVCLI_CONF" ] && [ "$HAS_API_KEY" != "1" ]; thenwarn 'To enable Bearer auth later, create ovcli.conf with an api_key and re-run.'fi+validate_plugin_install() {+ local issues=()+ local marketplace_link="$MARKETPLACE_ROOT/$PLUGIN_NAME"+ local hooks_json="$CACHE_DIR/hooks/hooks.json"+ local mcp_json="$CACHE_DIR/.mcp.json"++ if [ ! -L "$marketplace_link" ] || [ "$(readlink "$marketplace_link" 2>/dev/null || true)" != "$PLUGIN_DIR" ]; then+ issues+=("marketplace symlink does not point at $PLUGIN_DIR")+ fi+ if ! codex plugin list 2>/dev/null | grep -E -q "${PLUGIN_ID}[[:space:]]+installed, enabled"; then+ issues+=("codex plugin list does not show $PLUGIN_ID as installed, enabled")+ fi+ if [ ! -d "$CACHE_DIR" ]; then+ issues+=("plugin cache directory missing: $CACHE_DIR")+ fi+ 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 -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")+ grep -q '"timeout": 130' "$hooks_json" || issues+=("UserPromptSubmit timeout is not 130s")+ fi+ 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__")+ 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+ grep -q '"X-OpenViking-Actor-Peer"' "$mcp_json" || issues+=("cached .mcp.json is missing X-OpenViking-Actor-Peer header mapping")+ fi++ for script in \+ auto-recall.mjs \+ auto-capture.mjs \+ pre-compact-capture.mjs \+ session-start-commit.mjs \+ recall-compressor-profile.mjs \+ config.mjs+ do+ if [ ! -f "$CACHE_DIR/scripts/$script" ]; then+ issues+=("cached script missing: scripts/$script")+ elif ! node --check "$CACHE_DIR/scripts/$script" >/dev/null 2>&1; then+ issues+=("cached script fails node --check: scripts/$script")+ fi+ done++ if [ "${#issues[@]}" -eq 0 ]; then+ return 0+ fi+ for issue in "${issues[@]}"; do+ warn "Install validation: $issue"+ done+ return 1+}++reset_plugin_cache_setup() {+ rm -f "$MARKETPLACE_ROOT/$PLUGIN_NAME"+ ln -s "$PLUGIN_DIR" "$MARKETPLACE_ROOT/$PLUGIN_NAME"+ codex plugin marketplace add "$MARKETPLACE_ROOT" >/dev/null 2>&1 || true+ render_plugin_cache+}++heading '6. Install validation'+if validate_plugin_install; then+ info 'Plugin install looks valid.'+else+ if [ -t 0 ]; then+ ask 'Reset/reinstall plugin symlink/cache and validate again? [Y/n] '+ read -r RESET_REPLY || RESET_REPLY=""+ case "$RESET_REPLY" in+ n|N|no|No|NO)+ err 'Plugin install validation failed. Re-run the installer or reset the plugin cache before using Codex.'+ exit 1+ ;;+ *)+ info 'Resetting plugin symlink/cache.'+ reset_plugin_cache_setup+ if validate_plugin_install; then+ info 'Plugin install looks valid after reset.'+ else+ err 'Plugin install validation still failed after reset. Re-run the installer with a clean plugin setup.'+ exit 1+ fi+ ;;+ esac+ else+ err 'Plugin install validation failed in non-interactive mode. Re-run interactively to reset, or clear the plugin cache and reinstall.'+ exit 1+ fi+fi+# ----- Done -----heading 'Done!'diff --git a/examples/codex-memory-plugin/setup-helper/wrapper.sh b/examples/codex-memory-plugin/setup-helper/wrapper.shindex b915a0517..330fa7f00 100644--- a/examples/codex-memory-plugin/setup-helper/wrapper.sh+++ b/examples/codex-memory-plugin/setup-helper/wrapper.sh@@ -5,12 +5,14 @@# reset --hard` of the plugin checkout — no need to re-run it to refresh.## This wrapper exists because Codex's MCP runtime reads OPENVIKING_API_KEY-# (and OPENVIKING_ACCOUNT / _USER / _AGENT_ID) from the process env at+# (and OPENVIKING_ACCOUNT / _USER / _PEER_ID) from the process env at# codex launch. Rather than asking users to `export` secrets globally, we# wrap `codex` in a shell function that:#-# 1. Reads the user's ovcli.conf (env > $OPENVIKING_CLI_CONFIG_FILE >-# ~/.openviking/ovcli.conf) and resolves URL / API key / identity.+# 1. Resolves credentials through the plugin's shared resolver. By default+# active ovcli.conf wins, so `ov config switch` controls hooks, MCP, and+# in-process `ov` commands together. Set OPENVIKING_CREDENTIAL_SOURCE=env+# to force env-var credentials.## 2. Rewrites the cached .mcp.json's URL and bearer_token_env_var to# match the resolved state. Required because Codex 0.130 hard-fails@@ -20,9 +22,9 @@# configs targeting different OV servers would silently keep hitting# the install-time URL.#-# 3. Exec's the launcher with a dynamically built env prefix that omits-# any OPENVIKING_* whose resolved value is empty (so empty values-# never reach codex as empty strings).+# 3. Exec's the launcher after stripping stale credential env vars and+# adding only the resolved OPENVIKING_* values (so empty values never+# reach codex as empty strings).## Besides `codex`, any extra launch commands listed in# $OPENVIKING_CODEX_WRAP_EXTRA (set by the installer in your shell rc, one@@ -33,6 +35,16 @@## Targets bash and zsh (the only shells that source ~/.bashrc / ~/.zshrc).+_openviking_codex_plugin_dir() {+ local _ov_src+ if [ -n "${BASH_SOURCE[0]-}" ]; then+ _ov_src="${BASH_SOURCE[0]}"+ else+ _ov_src="${(%):-%x}"+ fi+ cd "$(dirname "$_ov_src")/.." >/dev/null 2>&1 && pwd -P+}+# Resolve OpenViking credentials, sync the cached .mcp.json, then exec the# given launch command with an OPENVIKING_* env prefix. $@ is the command to# run (e.g. "codex", or a custom launcher like "codex-custom").@@ -43,29 +55,21 @@ _openviking_codex_exec() {returnfi- # Resolve OV connection settings: existing env > ovcli.conf > nothing.- local _ov_url _ov_key _ov_account _ov_user- if [ -f "$_ov_conf" ]; then- local _ov_env- _ov_env=$(node -e '- try {- const c = JSON.parse(require("node:fs").readFileSync(process.argv[1], "utf8"));- const out = (k, v) => v ? `${k}=${JSON.stringify(String(v))}\n` : "";- process.stdout.write(- out("OV_URL", c.url) +- out("OV_KEY", c.api_key) +- out("OV_ACCOUNT", c.account) +- out("OV_USER", c.user)- );- } catch {}- ' "$_ov_conf" 2>/dev/null)- eval "$_ov_env"+ local _ov_plugin_dir _ov_creds_script+ _ov_plugin_dir="$(_openviking_codex_plugin_dir 2>/dev/null || true)"+ _ov_creds_script="$_ov_plugin_dir/scripts/ov-credentials.mjs"+ if [ ! -f "$_ov_creds_script" ]; then+ command "$@"+ returnfi- _ov_url="${OPENVIKING_URL:-${OV_URL:-}}"- _ov_key="${OPENVIKING_API_KEY:-${OV_KEY:-}}"- _ov_account="${OPENVIKING_ACCOUNT:-${OV_ACCOUNT:-}}"- _ov_user="${OPENVIKING_USER:-${OV_USER:-}}"- unset OV_URL OV_KEY OV_ACCOUNT OV_USER++ local _ov_env+ _ov_env=$(OPENVIKING_CLI_CONFIG_FILE="$_ov_conf" node "$_ov_creds_script" shell-env 2>/dev/null) || _ov_env=""+ if [ -z "$_ov_env" ]; then+ command "$@"+ return+ fi+ eval "$_ov_env"# Sync cache .mcp.json to current OV connection state: rewrite both the# URL (so OPENVIKING_CLI_CONFIG_FILE swaps actually change the target)@@ -73,58 +77,36 @@ _openviking_codex_exec() {# bearer env vars, so the field must be absent in no-auth mode). The# node script writes only when something actually changes — idempotent# fast-path so we don't bump file mtime on every codex launch.- local _has_key _mcp_url_from_conf- if [ -n "$_ov_key" ]; then _has_key=1; else _has_key=0; fi- if [ -n "$_ov_url" ]; then- if [ -n "${OPENVIKING_MCP_URL:-}" ]; then- _mcp_url_from_conf="$OPENVIKING_MCP_URL"- else- _mcp_url_from_conf="${_ov_url%/}/mcp"- fi- else- _mcp_url_from_conf=""+ local _cache_root _cache_mcp+ _cache_root="$HOME/.codex/plugins/cache/openviking-plugins-local/openviking-memory"+ if [ -d "$_cache_root" ]; then+ while IFS= read -r _cache_mcp; do+ [ -f "$_cache_mcp" ] || continue+ OPENVIKING_CLI_CONFIG_FILE="${OV_RESOLVED_CLI_CONFIG_FILE:-$_ov_conf}" \+ node "$_ov_creds_script" sync-mcp "$_cache_mcp" 2>/dev/null || true+ done < <(find "$_cache_root" -mindepth 2 -maxdepth 2 -name .mcp.json -type f 2>/dev/null)fi- local _cache_mcp- for _cache_mcp in "$HOME"/.codex/plugins/cache/openviking-plugins-local/openviking-memory/*/.mcp.json; do- [ -f "$_cache_mcp" ] || continue- node -e '- const fs = require("node:fs");- // node -e: argv is [node, file, hasKey, url] — no [eval] placeholder.- const file = process.argv[1];- const hasKey = process.argv[2];- const url = process.argv[3] || "";- const j = JSON.parse(fs.readFileSync(file, "utf8"));- const s = j.mcpServers && j.mcpServers["openviking-memory"];- if (s) {- let changed = false;- if (url && s.url !== url) {- s.url = url;- changed = true;- }- const cur = s.bearer_token_env_var || "";- if (hasKey === "1" && cur !== "OPENVIKING_API_KEY") {- s.bearer_token_env_var = "OPENVIKING_API_KEY";- changed = true;- } else if (hasKey !== "1" && cur) {- delete s.bearer_token_env_var;- changed = true;- }- if (changed) {- fs.writeFileSync(file, JSON.stringify(j, null, 2) + "\n");- }- }- ' "$_cache_mcp" "$_has_key" "$_mcp_url_from_conf" 2>/dev/null || true- done# Build env-prefix dynamically so empty values are NOT exported as empty# strings — Codex hard-fails on empty bearer_token_env_var targets.local -a _env_args=()- [ -n "$_ov_url" ] && _env_args+=("OPENVIKING_URL=$_ov_url")- [ -n "$_ov_key" ] && _env_args+=("OPENVIKING_API_KEY=$_ov_key")- [ -n "$_ov_account" ] && _env_args+=("OPENVIKING_ACCOUNT=$_ov_account")- [ -n "$_ov_user" ] && _env_args+=("OPENVIKING_USER=$_ov_user")+ [ -n "${OV_RESOLVED_CLI_CONFIG_FILE:-}" ] && _env_args+=("OPENVIKING_CLI_CONFIG_FILE=$OV_RESOLVED_CLI_CONFIG_FILE")+ [ -n "${OV_RESOLVED_URL:-}" ] && _env_args+=("OPENVIKING_URL=$OV_RESOLVED_URL")+ [ -n "${OV_RESOLVED_API_KEY:-}" ] && _env_args+=("OPENVIKING_API_KEY=$OV_RESOLVED_API_KEY")+ [ -n "${OV_RESOLVED_ACCOUNT:-}" ] && _env_args+=("OPENVIKING_ACCOUNT=$OV_RESOLVED_ACCOUNT")+ [ -n "${OV_RESOLVED_USER:-}" ] && _env_args+=("OPENVIKING_USER=$OV_RESOLVED_USER")+ [ -n "${OV_RESOLVED_PEER_ID:-}" ] && _env_args+=("OPENVIKING_PEER_ID=$OV_RESOLVED_PEER_ID")- env "${_env_args[@]}" "$@"+ env \+ -u OPENVIKING_URL \+ -u OPENVIKING_BASE_URL \+ -u OPENVIKING_MCP_URL \+ -u OPENVIKING_API_KEY \+ -u OPENVIKING_BEARER_TOKEN \+ -u OPENVIKING_ACCOUNT \+ -u OPENVIKING_USER \+ -u OPENVIKING_PEER_ID \+ "${_env_args[@]}" "$@"}# Runtime guard for a wrapped command. $1 = exec helper, $2 = command name,