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
docs: add a cross-integration capability reference page (#4076)
t0saki458e7fae37f7
diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.tsindex a090be344..994d1b947 100644--- a/docs/.vitepress/config.ts+++ b/docs/.vitepress/config.ts@@ -122,6 +122,7 @@ const gettingStartedSidebar = {const agentIntegrationSidebar = {en: {overview: 'Integration Overview',+ topItems: [['16-capability-reference.md', 'Capability Reference']],groups: [{text: 'Developer Tools',@@ -156,6 +157,7 @@ const agentIntegrationSidebar = {},zh: {overview: '集成概览',+ topItems: [['16-capability-reference.md', '集成能力参考']],groups: [{text: '开发工具',@@ -482,6 +484,7 @@ const guidesSidebar = {type StructuredSidebarCopy = {readonly overview: string+ readonly topItems?: ReadonlyArray<readonly [string, string]>readonly groups: ReadonlyArray<{readonly text: stringreadonly items: ReadonlyArray<readonly [string, string]>@@ -540,6 +543,7 @@ function structuredSidebarSection(collapsed,items: [configuredSidebarItem(locale, section, [overviewFile, copy.overview]),+ ...(copy.topItems ?? []).map((item) => configuredSidebarItem(locale, section, item)),...configuredSidebarGroups(locale, section, copy.groups)]}diff --git a/docs/en/agent-integrations/01-overview.md b/docs/en/agent-integrations/01-overview.mdindex 4eb07231a..6656edfff 100644--- a/docs/en/agent-integrations/01-overview.md+++ b/docs/en/agent-integrations/01-overview.md@@ -20,6 +20,10 @@ OpenViking can act as the long-term memory and context backend for many agent ru| **Manus / Claude Desktop / ChatGPT / other MCP clients** | [MCP Clients](./06-mcp-clients.md) — point any MCP-compatible client at the built-in `/mcp` endpoint || **ZCode / AstrBot / …** | [Community Plugins](./08-community-plugins.md) — community-maintained integrations for various runtimes |+## Compare integrations side by side++For the concrete differences between integrations — tool surface, automatic recall, session and commit behaviour, compaction takeover, degradation and fault tolerance — see the [Capability Reference](./16-capability-reference.md), a cross-integration comparison matrix.+## Prerequisite for all integrationsEvery integration on this page connects to a running OpenViking server. If you don't have one yet, follow the [Quickstart Guide](../getting-started/02-quickstart.md). The default endpoint is `http://localhost:1933`; remote use requires an API key (see [Authentication](../guides/04-authentication.md)).diff --git a/docs/en/agent-integrations/02-claude-code.md b/docs/en/agent-integrations/02-claude-code.mdindex c45a4e429..329290bee 100644--- a/docs/en/agent-integrations/02-claude-code.md+++ b/docs/en/agent-integrations/02-claude-code.md@@ -112,6 +112,7 @@ The plugin renders an OpenViking status indicator beneath your Claude Code input## See also+- [Capability Reference](./16-capability-reference.md)- [Blog: OpenViking in Claude Code / Codex](https://blog.openviking.ai/post/openviking-coding-agent/) — Motivation, architecture overview, and demo- [Plugin README](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md) — Full environment variable tables, hook details, and architecture diagrams- [MCP Clients](./06-mcp-clients.md) — Information on MCP tool parameters and other clientsdiff --git a/docs/en/agent-integrations/03-openclaw.md b/docs/en/agent-integrations/03-openclaw.mdindex 4ce682ce9..7566d7cd2 100644--- a/docs/en/agent-integrations/03-openclaw.md+++ b/docs/en/agent-integrations/03-openclaw.md@@ -115,6 +115,7 @@ bash uninstall-openviking.sh## See also+- [Capability Reference](./16-capability-reference.md)- [Full install guide](https://github.com/volcengine/OpenViking/blob/main/examples/openclaw-plugin/INSTALL.md) — every install path and parameter- [Plugin design notes](https://github.com/volcengine/OpenViking/blob/main/examples/openclaw-plugin/README.md) — architecture, identity & routing, hook lifecycle- [Agent operator guide](https://github.com/volcengine/OpenViking/blob/main/examples/openclaw-plugin/INSTALL-AGENT.md) — for agents driving installation on behalf of a userdiff --git a/docs/en/agent-integrations/04-codex.md b/docs/en/agent-integrations/04-codex.mdindex f8aa28ef1..7737e04ec 100644--- a/docs/en/agent-integrations/04-codex.md+++ b/docs/en/agent-integrations/04-codex.md@@ -66,14 +66,14 @@ Tool calls and results are captured as dedicated `tool` parts, and `tool_output`<details><summary><b>Configuration</b></summary>-Credential source: active `ovcli.conf` wins by default (`OPENVIKING_CLI_CONFIG_FILE` or `~/.openviking/ovcli.conf`), so `ov config switch <name>` changes hooks, MCP proxy, 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. Without an ovcli config, env vars then `ov.conf` then built-in defaults are used.+Credential source: env vars win by default — when any `OPENVIKING_*` credential env var (`OPENVIKING_URL`/`OPENVIKING_BASE_URL`, `OPENVIKING_BEARER_TOKEN`/`OPENVIKING_API_KEY`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, `OPENVIKING_PEER_ID`) is set, its value takes precedence over the active `ovcli.conf`. Only when none of them are set does the active `ovcli.conf` (`OPENVIKING_CLI_CONFIG_FILE` or `~/.openviking/ovcli.conf`) drive hooks, MCP proxy, and child `ov` commands together, so `ov config switch <name>` takes effect on the next launch. Set `OPENVIKING_CREDENTIAL_SOURCE=cli` to force the active ovcli config even while credential env vars are present. Fields not covered by either fall back to `ovcli.conf`, then `ov.conf`, then built-in defaults.| 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_CREDENTIAL_SOURCE` | `auto` | `auto` prefers env-var credentials when any are set; `cli` forces the active ovcli config, `env` forces env vars || `OPENVIKING_NO_AUTO_INJECT` | `false` | Disable fixed session-start profile/background injection without disabling per-prompt recall || `OPENVIKING_PROFILE_TOKEN_BUDGET` | `10000` | CJK-aware token budget for `profile.md` plus `preferences/` and `entities/` indexes || `OPENVIKING_CODEX_ACTIVE_WINDOW_MS` | `120000` | SessionStart active-window threshold |@@ -94,10 +94,11 @@ Additional tuning options (e.g., `OPENVIKING_RECALL_LIMIT`, `OPENVIKING_CAPTURE_| MCP tool calls fail with a connection error | Server unreachable or the URL is wrong | Check the endpoint: `curl "$(jq -r '.url' ~/.openviking/ovcli.conf)/health"` || `4 hooks need review` | Security review on first launch | Run `/hooks` within Codex and approve the hooks. || Plugin still targets an old server after `ov config switch` | Codex keeps the proxy process from the previous session | Restart Codex; the proxy resolves credentials at startup. |-| Hooks use one server, MCP another | `OPENVIKING_CREDENTIAL_SOURCE=env` set with stale env vars in one context | Unset it (ovcli.conf then drives both), or make the env vars consistent. |+| Hooks use one server, MCP another | Stale `OPENVIKING_*` credential env vars in one context (env vars override ovcli.conf by default) | Unset the stale env vars (ovcli.conf then drives both), set `OPENVIKING_CREDENTIAL_SOURCE=cli`, or make the env vars consistent. |## See also+- [Capability Reference](./16-capability-reference.md)- [Blog: OpenViking in Claude Code / Codex](https://blog.openviking.ai/post/openviking-coding-agent/) — Motivation, architecture overview, and demo.- [Plugin README](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/README.md) — Full environment variable list and architecture diagram.- [DESIGN.md](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/DESIGN.md) — Commit decision tree.diff --git a/docs/en/agent-integrations/05-hermes.md b/docs/en/agent-integrations/05-hermes.mdindex 75a36894a..c1794816e 100644--- a/docs/en/agent-integrations/05-hermes.md+++ b/docs/en/agent-integrations/05-hermes.md@@ -31,6 +31,7 @@ hermes memory status## See also+- [Capability Reference](./16-capability-reference.md)- [Hermes — OpenViking memory provider docs](https://hermes-agent.nousresearch.com/docs/user-guide/features/memory-providers#openviking) — full setup guide and configuration options- [Deployment Guide](../guides/03-deployment.md) — setting up your OpenViking server- [Authentication](../guides/04-authentication.md) — API key setup for remote accessdiff --git a/docs/en/agent-integrations/06-mcp-clients.md b/docs/en/agent-integrations/06-mcp-clients.mdindex dc625826d..b56199491 100644--- a/docs/en/agent-integrations/06-mcp-clients.md+++ b/docs/en/agent-integrations/06-mcp-clients.md@@ -86,6 +86,7 @@ Once connected, OpenViking exposes retrieval, memory, resource, watch, filesyste## See also+- [Capability Reference](./16-capability-reference.md)- [MCP Integration Guide](../guides/06-mcp-integration.md) — tool parameters, progressive upload, `OPENVIKING_PUBLIC_BASE_URL`- [OAuth 2.1 Guide](../guides/11-oauth.md) — for Claude Desktop, Claude.ai, Cursor- [MCP Specification](https://modelcontextprotocol.io/)diff --git a/docs/en/agent-integrations/07-langchain-langgraph.md b/docs/en/agent-integrations/07-langchain-langgraph.mdindex 165b64381..2fb14082d 100644--- a/docs/en/agent-integrations/07-langchain-langgraph.md+++ b/docs/en/agent-integrations/07-langchain-langgraph.md@@ -319,5 +319,6 @@ For a real OpenViking server and OpenAI-compatible model flow, see the [live Lan## See also+- [Capability Reference](./16-capability-reference.md)- [examples/langchain-langgraph/](https://github.com/volcengine/OpenViking/tree/main/examples/langchain-langgraph) — full source for all examples above- [MCP Clients](./06-mcp-clients.md) — for non-SDK MCP integrationdiff --git a/docs/en/agent-integrations/08-community-plugins.md b/docs/en/agent-integrations/08-community-plugins.mdindex 5dc3934a2..b5b18d11e 100644--- a/docs/en/agent-integrations/08-community-plugins.md+++ b/docs/en/agent-integrations/08-community-plugins.md@@ -76,3 +76,6 @@ A standalone FastAPI server that exposes a curated subset of OpenViking endpointThe [examples/](https://github.com/volcengine/OpenViking/tree/main/examples) directory also contains deployment and integration samples beyond agent plugins — Grafana dashboards, Kubernetes Helm charts, multi-tenant setups, snapshot workflows, and SDK snippets.+## See also++- [Capability Reference](./16-capability-reference.md)diff --git a/docs/en/agent-integrations/09-log-ingestion.md b/docs/en/agent-integrations/09-log-ingestion.mdindex d5905f450..2860d93ca 100644--- a/docs/en/agent-integrations/09-log-ingestion.md+++ b/docs/en/agent-integrations/09-log-ingestion.md@@ -120,5 +120,6 @@ Cursor state persists in `~/.openviking/ingest/state.db`, so both backfill and w## See also+- [Capability Reference](./16-capability-reference.md)- [Overview](./01-overview.md) — the per-harness memory plugins (real-time capture)- [Deployment guide → CLI](../guides/03-deployment.md#cli) — `ov.conf` / credential configurationdiff --git a/docs/en/agent-integrations/10-opencode.md b/docs/en/agent-integrations/10-opencode.mdindex 4d2477681..6ae314978 100644--- a/docs/en/agent-integrations/10-opencode.md+++ b/docs/en/agent-integrations/10-opencode.md@@ -133,11 +133,12 @@ API keys are sent as `Authorization: Bearer ...` by both hooks and the MCP proxy## Verify-Restart OpenCode after installation. In an OpenCode session, the plugin should expose the `openviking` MCP server. OpenCode namespaces MCP tools as `openviking_*`, for example:+Restart OpenCode after installation. In an OpenCode session, the plugin should expose the `openviking` MCP server with the full server MCP tool set (15 tools). OpenCode namespaces MCP tools as `openviking_*`:-- `openviking_search`, `openviking_find` (`openviking_search` with `mode="context"` replaces the former recall tool)-- `openviking_read`, `openviking_list`, `openviking_grep`, `openviking_glob`-- `openviking_remember`, `openviking_add_resource`, `openviking_forget`, `openviking_health`+- `openviking_find`, `openviking_search` (`openviking_search` with `mode="context"` replaces the former recall tool)+- `openviking_read`, `openviking_list`, `openviking_tree`, `openviking_grep`, `openviking_glob`+- `openviking_remember`, `openviking_write`, `openviking_edit`, `openviking_add_resource`+- `openviking_list_watches`, `openviking_cancel_watch`, `openviking_forget`, `openviking_health`Ask OpenCode to search or browse OpenViking memory. Runtime state and errors are written to:@@ -157,3 +158,7 @@ Ask OpenCode to search or browse OpenViking memory. Runtime state and errors are| Local `openviking_add_resource` fails | Pass a file path, not a directory; local directories are not uploaded automatically yet |For all available tools, configuration fields, and runtime file details, see the [plugin README](https://github.com/volcengine/OpenViking/tree/main/examples/opencode-plugin).++## See also++- [Capability Reference](./16-capability-reference.md)diff --git a/docs/en/agent-integrations/11-pi.md b/docs/en/agent-integrations/11-pi.mdindex e65c40558..cdc667aad 100644--- a/docs/en/agent-integrations/11-pi.md+++ b/docs/en/agent-integrations/11-pi.md@@ -44,6 +44,7 @@ git clone https://github.com/volcengine/OpenViking.gitcd OpenVikingmkdir -p ~/.pi/agent/extensionscp -r examples/pi-coding-agent-extension ~/.pi/agent/extensions/openviking+pi install ~/.pi/agent/extensions/openviking```## Configure@@ -94,3 +95,7 @@ Start `pi`. Once connected, the footer shows an `OV ✓` status segment, and `/v| Recall is empty | Confirm the server has indexed memories and the prompt is longer than `minQueryLength` |For the full tool, configuration, and design reference, see the [extension README](https://github.com/volcengine/OpenViking/tree/main/examples/pi-coding-agent-extension).++## See also++- [Capability Reference](./16-capability-reference.md)diff --git a/docs/en/agent-integrations/12-cursor.md b/docs/en/agent-integrations/12-cursor.mdindex dab362a3e..e2270fc88 100644--- a/docs/en/agent-integrations/12-cursor.md+++ b/docs/en/agent-integrations/12-cursor.md@@ -74,5 +74,6 @@ Uninstall removes only OpenViking-managed Cursor Hooks, MCP, Rule, Skill, and ru## See also+- [Capability Reference](./16-capability-reference.md)- [Authentication](../guides/04-authentication.md)- [Cursor Hooks documentation](https://cursor.com/docs/hooks)diff --git a/docs/en/agent-integrations/13-trae.md b/docs/en/agent-integrations/13-trae.mdindex 0af42b8d3..bd83f55f4 100644--- a/docs/en/agent-integrations/13-trae.md+++ b/docs/en/agent-integrations/13-trae.md@@ -45,7 +45,7 @@ Quit and restart the corresponding client after installation.- `UserPromptSubmit` recalls and injects context for the current request.- `PreToolUse` redirects accidental local access to `viking://` paths back to OpenViking MCP tools.- `Stop` captures and immediately commits the completed turn, including short sessions.-- The OpenViking MCP server provides explicit tools such as `search`, `read`, and `remember`; `search` with `mode="context"` returns assembled context.+- The OpenViking MCP server transparently exposes the full server MCP tool set (15 tools): `find`, `search`, `read`, `list`, `tree`, `remember`, `write`, `edit`, `add_resource`, `list_watches`, `cancel_watch`, `grep`, `glob`, `forget`, and `health`. `search` with `mode="context"` returns assembled context.## Verify@@ -89,4 +89,5 @@ Replace `trae-cn` with `trae` for TRAE. For TraeCode CLI 2.0, use `trae-cli plug## See also+- [Capability Reference](./16-capability-reference.md)- [Authentication](../guides/04-authentication.md)diff --git a/docs/en/agent-integrations/14-openviking-helper.md b/docs/en/agent-integrations/14-openviking-helper.mdindex 9e99b7e31..06b4f08d9 100644--- a/docs/en/agent-integrations/14-openviking-helper.md+++ b/docs/en/agent-integrations/14-openviking-helper.md@@ -58,6 +58,7 @@ Helper reads the relevant local agent configuration and data to display integrat## See also+- [Capability Reference](./16-capability-reference.md)- [Agent integrations overview](./01-overview.md)- [Claude Code Memory Plugin](./02-claude-code.md)- [Codex Memory Plugin](./04-codex.md)diff --git a/docs/en/agent-integrations/15-agent-plugins.md b/docs/en/agent-integrations/15-agent-plugins.mdindex 06b1fcde1..a56f20ae1 100644--- a/docs/en/agent-integrations/15-agent-plugins.md+++ b/docs/en/agent-integrations/15-agent-plugins.md@@ -95,3 +95,7 @@ node --test agent-plugins/plugin.test.mjs`plugin.test.mjs` checks manifest schema URLs and matching spec versions, the plugin name rules, the closed manifest root, semver, that every `skills/*` child ships a `SKILL.md` with `name` + `description` frontmatter matching its directory, that `mcp.json` entries reference files that exist and stay inside the plugin root, and that `node --check` passes on every `.mjs` in the package.`servers/shared/*.mjs` are generated copies of `examples/memory-plugin-shared/lib` — edit the shared lib and re-run `node examples/memory-plugin-shared/sync.mjs`; `examples/memory-plugin-shared/sync.test.mjs` fails if they drift. Both test files run in CI.++## See also++- [Capability Reference](./16-capability-reference.md)diff --git a/docs/en/agent-integrations/16-capability-reference.md b/docs/en/agent-integrations/16-capability-reference.mdnew file mode 100644index 000000000..9ef2103dd--- /dev/null+++ b/docs/en/agent-integrations/16-capability-reference.md@@ -0,0 +1,707 @@+# Integration Capability Reference++## Reading guide++| What you want to know | Where to look |+|---|---|+| Which tools an agent can call autonomously per harness | [§1.1](#_1-1-active-tool-surface-agentic-calls) Active tool surface + [§2.1](#_2-1-server-side-mcp-tool-surface) (MCP surface) + the profile cards |+| How memory archiving behaves under different shutdown methods | **[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix) Shutdown path × harness end-state matrix** |+| Whether auto-recall includes `session_id`, and its impact | [§3.2.2](#_3-2-2-decision-matrix) / [§3.2.3](#_3-2-3-profile-opening-injection) |+| How to enable recall digests, and the workload distribution between server and client | [§3.2.5](#_3-2-5-recall-digest) |+| Type boundaries for `forget` and delete operations | [§3.5](#_3-5-type-boundaries-for-writes-and-deletes) |+| Which environment variables apply to specific harnesses | [§3.1.4](#_3-1-4-configuration-layers) Configuration layering + "Config" on each profile card |+| Whether the server provides an automatic commit fallback | [§2.3](#_2-3-server-side-session-and-commit-semantics) |+| The complete `ov` CLI command set | [§5](#_5-ov-cli-command-reference) |+| How to integrate a custom agent with OpenViking | [§6](#_6-custom-agent-integration-guide) |+| Installation, configuration, and troubleshooting for specific integrations | The integration's own page (linked in the first line of each profile card in [§4](#_4-harness-profile-cards)) |++---++# 1. Capability overview++## 1.1 Active tool surface (agentic calls)++- **MCP-based harnesses (claude-code, codex/trae-cli, cursor, trae/trae-cn, zcode, opencode) share an identical active tool surface comprising 15 tools.** The server centrally defines these tools. The plugin reads `~/.openviking/ovcli.conf` via its proxy and establishes a connection to the server-defined MCP tools.++- `trae-cli` means TraeCode CLI 2.0 (2.0 only). It is installed via a `codex` plugin alias and maintains format compatibility with `codex`. Therefore, it is consolidated into the `codex` row in the matrices below.++| harness | tool surface | tools (enabled by default) | search memory | search resource | search skill | write memory | write resource | write skill | delete type boundary |+|---|---|---|---|---|---|---|---|---|---|+| claude-code | MCP passthrough | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | no type distinction² |+| codex / trae-cli | MCP passthrough | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | no type distinction² |+| cursor | MCP passthrough | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | no type distinction² |+| trae / trae-cn | MCP passthrough | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | no type distinction² |+| zcode | MCP passthrough | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | no type distinction² |+| opencode | MCP passthrough (host adds an `openviking_` prefix) | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | no type distinction² |+| dsh | native registration (7 × `viking_*`) | 7 (all on) | ✅ | ✅ | ✅ | ✅ `viking_remember` | ✅ `viking_add_resource` (URL only) | ❌ | no type distinction; delete by query needs score>0.8³ |+| pi | native registration (7 × `viking_*`) | 7 (registration runs preflight checks⁴) | ✅ | ✅ | ✅ | ✅ `viking_remember` | ✅ `viking_add_resource` (URL only) | ❌ | no type distinction; delete by query needs score>0.8³ |+| openclaw | native registration (15 × `memory_*`/`ov_*` and friends) | 15 (14 on by default⁵) | ✅ `memory_recall` | ✅ `ov_search` (both scopes by default) | ✅ `ov_search` | ✅ `memory_store` | off by default⁵ | ✅ `add_skill` | memory-only allowlist + auto-delete only for a single candidate with score≥0.85 |+| hermes | native registration (6 × `viking_*`) | 6 (all on once the provider is active) | ✅ | ✅ | ✅ | ✅ `viking_remember` (writes the file directly, no extraction) | ✅ multi-protocol ingest (HTTP/Git/SSH/local file/directory zip) | ❌ | memory-only + `.md` leaf check |+| ov CLI | CLI commands | ~40 command groups | ✅ `ov find` | ✅ `ov find` | ✅ `ov find` | ✅ `ov add-memory` | ✅ `ov add-resource` | ✅ `ov add-skill` | `ov rm` executes directly (TUI deletion asks for confirmation and blocks root/scope deletes) |++¹ MCP `write` can target `viking://resources`, `viking://user`, or `viking://agent`. Adding skills via MCP is not yet supported; use the openclaw `add_skill` tool, `ov add-skill` CLI, or the REST API instead.+² MCP `forget` does not differentiate between memory, resource, and skill types. However, the storage layer protects namespace roots: deletion requests for bare `viking://`, `viking://user`, and `viking://agent` are rejected. See [§3.5](#_3-5-type-boundaries-for-writes-and-deletes).+³ For `viking_forget` on dsh/pi: the `recursive` flag is strictly set to false (directories are never deleted), and deleting by query requires a match score > 0.8.+⁴ The `pi` harness registers its tools only if the session bypasses `bypassPatterns`, `client.health()` passes, and `ensureSession` succeeds (`index.ts:66-113`). If the health check fails, no tools are registered for that session.+⁵ The `add_resource` tool in openclaw requires a double opt-in before activation.++**Skill addition/deletion boundaries**: Skills can be added via the openclaw `add_skill` tool (enabled by default), the `ov add-skill` CLI command, or the REST API. Deletion operates across four tiers, detailed in [§3.5](#_3-5-type-boundaries-for-writes-and-deletes).++## 1.2 Automatic hook surface (driven by the harness)++| harness | how it plugs in | auto-recall | recall carries session_id | digest (client)* | profile injection | takes over host compaction | offline compensation (pending queue) | statusline |+|---|---|---|---|---|---|---|---|---|+| claude-code | 9 hooks + MCP proxy + slash + statusline + skill | ✅ | ✅ | ✅ local `claude -p` / server-side rewrite (auto by default) | ✅ (10000) | ❌ (PreCompact only commits) | ✅ | ✅ |+| codex / trae-cli | 4 hooks + MCP proxy + skill | ✅ | ✅ | ✅ local `codex exec` (on by default) | ✅ (10000) | ❌ | ❌ no on-disk queue (the cursor stays put and the next turn resends) | ❌ |+| cursor | 7 hooks + MCP proxy + rule + skill | ✅ | ✅ | ❌ | ✅ (6000) | ❌ | ✅ | ❌ |+| trae / trae-cn | 4 hooks + MCP proxy | ✅ | ✅ | ❌ | ✅ (6000) | ❌ | ✅ | ❌ |+| zcode | 4 hooks + MCP proxy | ✅ | ✅ | ❌ | ✅ (6000) | ❌ | ✅ | ❌ |+| opencode | 7 plugin hooks + MCP proxy | ✅ | ✅ | ❌ | ✅ (10000) + repo list into the system prompt | ❌ (commits once before and once after compacting) | ✅ | ❌ (toast instead) |+| dsh | native Cordis plugin (same process) | ✅ | ✅ | ❌ | ✅ (10000, once per session) | ❌ | ✅ | ❌ |+| pi | native extension (8 events) | ✅ | ✅ | ❌ | ✅ (10000, rebuilt into systemPrompt every turn) | ✅ **takeover** (on by default) | ✅ | ✅ |+| openclaw | context-engine plugin (`ownsCompaction:true`) | ✅ | ❌ (goes through `/find`, which has no session_id field) | ❌ | ❌ | ✅ **full ContextEngine takeover** | ❌ failed turns are not replayed | ❌ |+| hermes | native MemoryProvider plugin | ✅ | partial (preferred `search/search` path only; the degraded `/find` path drops it) | ❌ | ❌ (static tool-guidance block) | ❌ | ✅ in-process queue (never written to disk) | ❌ |+| ov CLI | one-shot commands | ❌ (`ov find/search` are explicit commands) | — (`ov search --session-id` is an explicit argument) | ❌ | ❌ | ❌ | ❌ | ❌ |++\* This column indicates whether the client performs its own local compression of recall results. On the server side, the context retrieval API provides digest capabilities equally to all callers via the `rewrite` parameter (see [§3.2.5](#_3-2-5-recall-digest)).++**Current status of `session_id`**: With the exception of openclaw (whose `/find` endpoint lacks this field) and the degraded path in hermes, auto-recall on all harnesses explicitly carries a `session_id`. This behavior is enforced by a cross-plugin regression test (`examples/memory-plugin-shared/recall-session-wiring.test.mjs:16-39`).++## 1.3 Grouping by form++- **Full suite** (hook automation + MCP tool surface + surrounding UX): claude-code and codex (`trae-cli` is installed via an alias and is included here).+- **Thin hook** (sharing `agent-hook-runtime`, meaning core behaviors are essentially identical, with differences limited to host events and thresholds): cursor, trae/trae-cn, and zcode.+- **Plugin event**: opencode (offers the richest host event surface; `dispose` handles shutdown).+- **Native in-process**: dsh (Cordis), pi (extension + compaction takeover), openclaw (full ContextEngine takeover), and hermes (MemoryProvider).+- **Tool**: ov CLI (all operations are explicit calls; no automatic background actions).+- **Non-coding**: Open WebUI (tool server), LangChain (SDK library), the Agent Plugins portable package (an MCP + skill spec bundle), generic direct MCP, log ingestion, and Helper (desktop).++---++# 2. Shared capability core++The individual harness sections (profile cards) focus exclusively on differences and specific implementations. All shared capabilities and universal behaviors are documented once in this section.+## 2.1 Server-side MCP tool surface++These tools are defined on the server side, and future updates will be centrally published there. Harnesses only need to proxy the MCP to obtain the latest `~/.openviking/ovcli.conf`.++| # | Tool | What it does | Key parameters (definition line) |+|---|---|---|---|+| 1 | `find` | Fast semantic search requiring no session context | `query, target_uri="", limit=10, min_score=0.35, level, context_type` (`:259`) |+| 2 | `search` | Deep search, featuring optional `session_id` integration and intent analysis | The session is only loaded if the server has `retrieval.enable_intent` enabled (defaults to true) (`:285`, `:302-304`) |+| 3 | `read` | Read the full text of one or more `viking://` files | Uses a concurrency semaphore of 10; a single failure yields `(nothing found at <uri>)` rather than raising an exception (`:389`) |+| 4 | `list` | List a directory (function name `ls`, explicitly registered as `list`) | `recursive=False` (`:423`) |+| 5 | `tree` | Recursive directory tree | `level_limit=3, node_limit=1000, include_abstract=False` (`:449`) |+| 6 | `remember` | Write long-term memory | Internally creates a one-shot session (`mcp-store-<uuid12>`) and immediately calls `commit_async` (`:504-523`). This is the only commit entry point on the MCP surface, as there is no explicit commit tool. |+| 7 | `write` | Write a `viking://` file | `mode=replace\|append\|create`; `replace` falls back to `create` if not found. New files must use an extension from the allowlist: `.md .txt .json .yaml .yml .toml .py .js .ts`. Writable domains are limited to `resources/user/agent`; directories like `skills/`, `peers/`, `privacy/`, and `sessions/` under the user root are read-only. Derived files (`.abstract.md` / `.overview.md` / `.relations.json`) cannot be written directly (`:529`; `content_write.py:60-81`) |+| 8 | `edit` | Exact string replacement | Supplying an empty `old_string`, finding zero matches, or finding multiple matches without `replace_all` will raise an error and leave the file content unchanged (`:569`) |+| 9 | `add_resource` | Resource ingestion (remote URL / signed upload of a local file / Connector) | `watch_interval` is defined in minutes (0 disables watching). The local-path branch generates a signed upload URL (default TTL of 600s), and ingestion triggers automatically post-upload without requiring a subsequent API call (`:723-947`) |+| 10 | `list_watches` | List watch subscriptions; not yet supported on the commercial edition | Returns an error string if the scheduler is not running (`:958`) |+| 11 | `cancel_watch` | Cancel by `to_uri`; not yet supported on the commercial edition | Deliberately does not expose pause/resume/trigger/update (`:990`) |+| 12 | `grep` | Regex content search | Multiple patterns run concurrently (semaphore of 10), `node_limit=10` (`:1032`) |+| 13 | `glob` | Filename glob | `node_limit=100` (`:1084`) |+| 14 | `forget` | Permanently deletes a URI (unrecoverable) | `recursive=False` by default; type boundaries in [§3.5](#_3-5-type-boundaries-for-writes-and-deletes) (`:1110-1117`) |+| 15 | `health` | Health check | No parameters (`:1123`) |++Supporting mechanisms:++- **Portable schema rewriting** (`:1149-1218`): At module import time, every tool's `anyOf` / `$ref` is flattened into a plain type to ensure compatibility with clients that only support the OpenAPI 3.0 subset (such as Gemini). Runtime validation still relies on the original Python signature (for instance, `read` advertises an array schema but continues to accept a bare string). All MCP clients receive the exact same server-produced schema; there are no client-specific variants.+- **Identity middleware** (`:149-233`): Shares `resolve_identity` with REST endpoints. It reads headers in the following order: `x-api-key`, `authorization`, `x-openviking-account`, `x-openviking-user`, and `x-openviking-actor-peer`. If absent, the account and user fields fall back to `"default"`.++## 2.2 The memory-plugin-shared layer++The `examples/memory-plugin-shared/lib/` directory contains 18 `.mjs` modules and serves as the single source of truth for all JS-based harnesses. These are consumed in two ways:++1. **Vendoring (copying)**: The `sync.mjs` script distributes these modules to 7 targets, prefixing every file with `// GENERATED FROM ... DO NOT EDIT.`. Because of this added line, a vendored copy's line number will be exactly one line greater than the library source (keep this in mind when cross-referencing line numbers). The distribution breakdown is as follows: 16 modules each for claude-code, codex, and opencode (the "HARNESS 13" + `mcp-proxy-core` + `async-writer` + `batch-send`); 13 each for dsh and pi; all 18 for zcode; and 4 for agent-plugins. At the current HEAD, every target has zero drift from the original library source.+2. **Direct import via relative path (no copying)**: Integrations like cursor, trae, and trae-cn directly `import "../../memory-plugin-shared/lib/..."`. To ensure this works, the installer copies the package alongside the shared library into `~/.openviking/agent-integrations/{<client>,memory-plugin-shared}/`, preserving the relative folder layout. At runtime, these harnesses share this directory, meaning reinstalling any one of them will overwrite the shared directory wholesale.++Core modules at a glance (detailed further in the per-dimension sections):++| Module | Responsibility | Consumers |+|---|---|---|+| `recall-core.mjs` | Handles recall request construction, three-tier degradation, and local fallback ranking/injection | All JS-based harnesses |+| `agent-hook-runtime.mjs` | All-in-one "thin hook" runtime handling 19 configuration environment variables, session ID derivation, cross-process locking, fetching, and commits | cursor / trae / trae-cn / zcode |+| `mcp-proxy-core.mjs` | stdio ↔ streamable-HTTP MCP proxy core | All MCP-based integrations + agent-plugins |+| `pending-queue.mjs` | On-disk offline queueing and replay at session start | cc / cursor / trae×2 / zcode / opencode / dsh / pi |+| `batch-send.mjs` | Executes writes in batches of 100, handles per-message degradation on 404/405 errors, and queues the leading contiguous prefix | cc / codex / opencode + the agent-hook family |+| `profile-inject.mjs` | Injects the profile and available-memory index at session start | 9 harnesses (all but openclaw / hermes) |+| `recall-compress-core.mjs` | Manages the recall compression prompt, URI edit-distance repair, and caching | claude-code |+| `capture-utils.mjs` | Handles message normalization, injection back-flow guarding, and capture filtering | codex / opencode / dsh / pi |+| `credentials.mjs` | Credential resolution chain (see [§3.1.3](#_3-1-3-credential-systems)) | All JS-based |+| `session-model.mjs` | Session ID prefix derivation and bypass globbing | All JS-based |+| `async-writer.mjs` | Detaches the write path (drains stdin → spawn → approve → write → unref). Falls back to synchronous writing if spawn fails | cc / codex / zcode |+| `workspace-peer.mjs` | Converts the `cwd` into an actor peer (replacing every non-alphanumeric character with `-`) | All JS-based |+| `uri-guard.mjs` / `agent-uri-guard.mjs` | Intercepts cases where `viking://` is incorrectly treated as a local path | Used in each harness's `PreToolUse` or `tool.execute.before`-style hooks |+| `plugin-config.mjs` | Reads the `plugin` section of `ovcli.conf` | claude-code / codex |+| `setup-wizard.mjs` | Interactively writes to `ovcli.conf` | cc, codex, opencode, and pi expose an entry point for this |+| `retryable.mjs` | Handles retryability checks: allows status codes 0, 408, 429, and ≥500, as well as 409 if `error.details.retryable===true`. Standard 4xx errors (including 401/403) are not retried | All JS-based |++## 2.3 Server-side session and commit semantics++- **Implicit session creation**: Plugins generally do not call `POST /sessions` explicitly (with `dsh` being the only exception, as it sends a creation request carrying only `session_id`). Instead, the server creates the session using `auto_create=True` upon receiving the first `POST /sessions/{id}/messages(/batch)` request. On the recall side, calling `_load_session(auto_create=True)` under `mode="context"` also creates a session, meaning the very first recall action will initialize the session on the server.+- **Two-phase commit**: `POST /sessions/{id}/commit` returns only after Phase 1 (archiving) has completed synchronously. Phase 2 (memory extraction) runs as a background task, returning a `task_id`. The server default for `keep_recent_count` is **0** (meaning it archives everything, leaving no live tail).+- **Server-side auto-commit is disabled by default, and the session creation paths used by plugins never enable it**:+ - `memory.session_auto_commit.default_enabled = false` and `idle_enabled = false` (`memory_config.py:15-16`). Auto-commit is disabled for sessions lacking a storage policy (`session_service.py:637-638`). Furthermore, the idle scanner isn't even instantiated when `idle_enabled=false` (`core.py:440-448`), effectively acting as a double gate.+ - The `auto_create` path triggered by `POST /messages` accepts no policy arguments; only `POST /sessions` (creation) and `PATCH /sessions/{id}/config` can set the `auto_commit_policy`.+ - Currently, no plugin sends an `auto_commit_policy`. Among first-party clients, only the **ov CLI** does this (`ov session new --auto-commit-policy-json` / `--no-auto-commit`, `ov session config set`).+ - When a policy is explicitly enabled, the server defaults are: `pending_token_threshold=10000` (strictly greater than), `message_count_threshold=50`, `idle_timeout_seconds=86400`, `keep_recent_count=2`, and `min_commit_interval_seconds=0`. Note that this set of server defaults operates independently of the plugin clients' configuration (which is typically 20000/10).+- **Consequence**: As it stands, every auto-commit relies on threshold logic implemented individually by each client ([§3.3](#_3-3-session-and-commit-lifecycle)), with no server-side fallback. If a process dies abnormally, any lingering pending messages are only archived and extracted when a subsequent commit is manually triggered in that same session.+- **Externalized tool output**: The server sets `tool_output_externalization.enabled=True` with `threshold_chars=20000` (`server/config.py:257-258`). Clients commonly raise `captureToolMaxChars` to 1000000 purely as a fallback mechanism, since the actual truncation and externalization occur on the server. Externalized results are then referenced via `tool_output_ref` (for context, openclaw provides three dedicated tools specifically for reading these references).+- **Server-side recall timeout fuses**: Configured via `retrieval.recall_intent_timeout_s=5.0` (for query expansion), `recall_rewrite_timeout_s=30.0` (for digests, [§3.2.5](#_3-2-5-recall-digest)), and `enable_intent=true`. Client timeout budgets are derived directly from these two timeout values ([§3.2.4](#_3-2-4-timeout-and-budget-chain)).++---++# 3. Dimensions in detail+## 3.1 Integration forms, installation, and configuration++### 3.1.1 Decision matrix++| Harness | Integration Form | Install Channel | Session ID Prefix/Format | Config Source | Standalone Setup Wizard |+|---|---|---|---|---|---|+| claude-code | CC plugin (marketplace): 9 hooks + MCP proxy + slash + statusline + skill | One-line `install.sh --harness claude` (supports both the modern plugin path and the legacy `claude mcp add` compatibility path) / manual marketplace / TOS mirror | `cc-<CC session_id verbatim>`; subagents use `…__subagent-<agent_id>` | env + ovcli.conf `plugin.claude_code` + ov.conf `claude_code` | ✅ `scripts/setup.mjs` |+| codex | Codex plugin (marketplace): 4 hooks + MCP proxy + skill | One-line `--harness codex` / `codex plugin marketplace add` (the TOS channel uses dumb-HTTP git to ensure remote updates continue working) | `cx-<safeId>` (deterministically derived, without reading state) | env + ovcli.conf `plugin.codex` + ov.conf `codex` | ✅ |+| trae-cli | **Installed as a codex plugin alias** (TraeCode CLI 2.0, 2.0 only; a Codex-family CLI: uses the `traecli` binary and `~/.trae/traecli.toml` config; its capability surface is identical to codex) | One-line `--harness trae-cli` (reuses the codex install flow; marketplace commands run against the targeted binary, e.g., `traecli plugin marketplace add`) | Same derivation rule as codex | Same as codex (env + ovcli.conf `plugin.codex` + ov.conf) | ✅ (same as codex) |+| cursor | Config-driven (writes `~/.cursor/hooks.json`+`mcp.json`) + rule + skill | One-line `--harness cursor` | `cu-<conversation_id>` | env only | ❌ (shares the installer TUI) |+| trae / trae-cn | Config-driven (`~/.trae{,-cn}/hooks.json` + platform-specific mcp.json) | One-line `--harness trae,trae-cn` | `tr-` / `trcn-` | env only | ❌ |+| zcode | Config-driven (merged into `~/.zcode/cli/config.json`, forcing `hooks.enabled=true`) | One-line `--harness zcode` | `zc-<sess_…>` | env only | ❌ |+| opencode | npm plugin `@openviking/opencode-plugin` (its config hook dynamically injects the MCP entry) | One-line `--harness opencode` (uses npm registration with a proxy snapshot fallback) / manual npm / from source | `oc-<id>`; subagents use `oc-<parent>__subagent-<child>` | `openviking-config.json` (searched at 4 levels) + env | ✅ |+| dsh | In-process Cordis plugin (`cordis.patch.yml` plugin group) | Run `dsh plugin add ./examples/dsh-memory-plugin` (the unified installer does not yet support dsh) | `dsh-<session.id as-is>`; each subagent is assigned its own session | cordis patch config + 4 env vars (credentials: patch > env; behavior toggles: env > patch) | ❌ |+| pi | Native pi extension (loaded from a directory, with TypeScript transpiled on the fly via jiti) | One-line `--harness pi` (including `pi install` registration) | `pi-<piSessionId>` | `config.json` (credential fields are resolved via the shared credential chain) + env | ✅ |+| openclaw | context-engine plugin (`ownsCompaction:true`) + 15 tools + 5 slash + 4 hooks + HTTP routes | ClawHub: run `openclaw plugins install clawhub:@openviking/openclaw-plugin` alongside `openclaw openviking setup` / npm installer / TOS offline bundle | A UUID is lowercased as-is, otherwise `sha256(sessionKey)`; `memory_store` temporary sessions use `memory-store-<ts>-<rand>` | `plugins.entries.openviking.config` in `openclaw.json` (strictly validated: unknown keys or invalid values force the plugin into setup-only mode) + a few env vars | ✅ `openclaw openviking setup` (interactive/non-interactive + key role probing + version compatibility check) |+| hermes | Hermes bundled MemoryProvider (ships with Hermes; no plugin installation required) | Run `hermes memory setup openviking` (interactive curses wizard), or manually run `config set memory.provider openviking` + `.env` | Hermes generates `%Y%m%d_%H%M%S_<hex6>`; the plugin uses it verbatim | `.env` (`OPENVIKING_*`) or linked ovcli.conf (`use_ovcli_config` mode clears the 5 corresponding variables from .env) + config.yaml | ✅ (multi-level menu) |+| ov CLI | Native Rust binary | npm `@openviking/cli` / `uv tool install openviking` / cargo / GitHub Releases | Does not manage its own session (`ov chat` defaults to the machine-uid) | `ovcli.conf` (multiple profiles) + a few env vars | ✅ `ov config` (TUI wizard) |++### 3.1.2 Unified installer++The unified install script (`examples/memory-plugin-shared/install.sh`, 3253 lines) supports nine harness IDs: `claude, codex, cursor, trae, trae-cn, trae-cli, zcode, opencode, pi`. (Note that `dsh` and `openclaw` use their own distribution channels, while `trae-cli` reuses the `codex` install flow, as detailed in [§3.1.1](#_3-1-1-decision-matrix)). Key highlights:++- **Interactive prompts:** Two distributions (`--dist github|tos`) and three sources (`--source remote|archive|dev`) are available. When executed via `bash <(curl …)`, it reads input directly from `/dev/tty` to ensure prompts remain interactive.+- **Usage:** In the official documentation, the canonical one-line command omits the `--harness` flag, which launches a TUI multi-select menu. However, the setup-helper forwarding scripts bundled with each plugin append the `--harness` flag automatically.+- **Idempotent merging:** Hooks and MCP entries are identified by the `OPENVIKING_INTEGRATION_ID` marker. This ensures stale entries are pruned and new ones are appended without affecting third-party configurations. Writes are atomic: the script creates a `.bak` backup, writes to a temporary file, and then renames it over the target with `0600` permissions.+- **Credential wizard:** This writes to `~/.openviking/ovcli.conf`. Users can select from three targets (local `http://127.0.0.1:1933` / Volcengine Cloud `https://api.vikingdb.cn-beijing.volces.com/openviking` / custom). If a configuration already exists, the script displays the current values first and asks whether to keep or reconfigure them, masking the API key for security.+- **Uninstallation:** The `--uninstall` flag covers `cursor`, `trae`, `trae-cn`, and `zcode`, and also cleans up any legacy trae-cli hook config. The Codex-format and host-managed plugins (`claude`, `codex`, `trae-cli`, `opencode`, and `pi`) are removed via their respective host's plugin management systems.+- **Post-installation self-check:** This includes grepping the configuration, running `node --check`, and executing a smoke test with `OPENVIKING_MEMORY_ENABLED=0`.+- **Node.js requirement:** The installer enforces a minimum version of Node 18+.++### 3.1.3 Credential systems++Four parallel credential-resolution systems coexist within the codebase, each utilizing its own environment variable names and authentication headers. When troubleshooting, your first step should be identifying which system is currently in use:++| Family | Consumers | URL Env | Key Env | Identity Env | Auth Header |+|---|---|---|---|---|---|+| **A. Shared JS core** (`credentials.mjs`) | claude-code / codex (including trae-cli) / cursor / trae×2 / zcode / opencode / pi / dsh / agent-plugins | `OPENVIKING_URL` → `OPENVIKING_BASE_URL` | `OPENVIKING_BEARER_TOKEN` → `OPENVIKING_API_KEY` | `OPENVIKING_ACCOUNT` / `OPENVIKING_USER` / `OPENVIKING_PEER_ID` | `Authorization: Bearer`. Note: codex's four hook scripts also send an `X-API-Key` compatibility header. |+| **B. openclaw** (its own `config.ts`) | openclaw | `OPENVIKING_BASE_URL` → `OPENVIKING_URL` | `OPENVIKING_API_KEY` (supports SecretRef env/file) | `OPENVIKING_ACCOUNT_ID` / `OPENVIKING_USER_ID` (note the `_ID` suffix here) | `X-API-Key`. (When pointing to OV Cloud, note that it actually authenticates using Bearer). |+| **C. hermes** (Python) | hermes | `OPENVIKING_ENDPOINT` | `OPENVIKING_API_KEY` | `OPENVIKING_ACCOUNT` / `OPENVIKING_USER` / `OPENVIKING_AGENT` (= actor peer) | Sends both `X-API-Key` and `Bearer`. When a key is present, it omits tenant headers by default (if the server rejects the call with a trusted error, it appends them and retries once). |+| **D. ov CLI** (Rust) | ov | Primarily the conf file | conf | `--account/--user/--actor-peer-id` | `X-API-Key`. Toggles between LDAP Basic and OIDC Bearer based on `auth_mode`; an `api_key` containing two or more `.` characters automatically receives a Bearer header as well (JWT fallback). |++Family A resolves credentials in the following order (refer to individual profile cards for other families):++1. The resolution mode is controlled by `OPENVIKING_CREDENTIAL_SOURCE` (aliased as `_CREDENTIALS_SOURCE`), accepting values of `env|cli|auto` (defaults to `auto`).+2. **`auto` prioritizes environment variables**: If any environment credential field is present, the entire resolution process relies on the environment. Only when all environment fields are empty, and an `ovcli.conf` file exists with credential fields, does the system fall back to the configuration file (meaning the key, account, user, and peer are then exclusively sourced from the file).+3. **baseUrl**: Resolves via environment variables → `ovcli` `url` → `ov.conf` `server.url` → `http://{server.host|127.0.0.1}:{server.port|1933}` (where `0.0.0.0` normalizes to `127.0.0.1`), with a final fallback to `http://127.0.0.1:1933`.+4. **apiKey**: Resolves via `BEARER_TOKEN` → `API_KEY` → `ovcli` `api_key` → `ov.conf` `codex.apiKey` → `server.root_api_key`.+5. **mcpUrl**: Resolves via `OPENVIKING_MCP_URL` (when outside CLI mode) → `${baseUrl}/mcp`.+6. **Common request headers**: `Authorization: Bearer` + `X-OpenViking-Account/User/Actor-Peer` + `User-Agent: openviking-memory-<harness>/<version>`.++**Workspace peer** (applies to all of Family A + agent-plugins): If no explicit `peerId` is provided and `OPENVIKING_WORKSPACE_PEER≠0`, the peer is derived from the current working directory (cwd). Every non-alphanumeric character in the path is replaced with a hyphen (`-`) (e.g., `/Users/x/Dev/OpenViking` becomes `-Users-x-Dev-OpenViking`), and this value is sent as the `X-OpenViking-Actor-Peer`. The server validates this header and returns a `400` error if it contains `/` or `\`. For `openclaw`, the peer is derived from `peer_role`/`peer_prefix` (note that if `peer_role=person`, sender information must be available, otherwise tool calls will fail). The `hermes` peer defaults to `OPENVIKING_AGENT` (defaulting to `hermes`).++### 3.1.4 Configuration layers++| Config Layer | Applies To | Notes |+|---|---|---|+| env `OPENVIKING_*` | Per family, see above; behavior knobs are listed on each profile card | The only layer that spans every JS-based integration. |+| ovcli.conf `plugin` section (`plugin.claude_code` / `plugin.codex` / shared scalars) | claude-code / codex | `plugin.<x>` entries named after any other harness are ignored. Note: `ov config add/edit` rewrites the entire file from the Rust Config struct, thereby dropping any `plugin` sections it does not recognize; however, `ov config switch` simply copies bytes and remains unaffected. |+| ov.conf harness sections (`claude_code.*` / `codex.*`) | claude-code / codex (legacy fallback) | |+| The harness's own config file | opencode `openviking-config.json`, pi `config.json`, dsh cordis patch, openclaw `openclaw.json`, hermes `config.yaml`+`.env` | |++**Quick scope reference** (these settings only take effect on the specified harnesses):++- `OPENVIKING_COMMIT_TURN_THRESHOLD`: cursor only (`trae`, `trae-cn`, and `zcode` commit on every Stop and ignore this threshold).+- `OPENVIKING_WRITE_PATH_ASYNC`: claude-code / codex / zcode.+- Recall digest settings (`OPENVIKING_RECALL_COMPRESS`, `OPENVIKING_RECALL_REWRITE`, and their companions): claude-code / codex (note that the server-side `rewrite` parameter is available to all callers, see [§3.2.5](#_3-2-5-recall-digest)).+- `OPENVIKING_RECALL_DEDUP_TURNS`, `OPENVIKING_RECALL_QUERY_EXPANSION`: claude-code / codex.+- ovcli.conf `plugin` section: claude-code / codex.+## 3.2 Automatic recall and injection++### 3.2.1 Mechanism foundation: one shared pipeline, two server-side paths++Recall for the JS-family harnesses is managed through a three-level degradation chain within `recall-core.mjs`:++1. **Context face**: Calls `POST /api/v1/search/search` with `mode:"context"` and `purpose:"coding"`. Its core design principle is "declare intent only, leave the mechanism to the server." Parameters like `quotas`, `max_tokens`, `query_expansion`, and `rewrite_max_bullets` are transmitted only if explicitly configured by the user (indicated by a sentinel field); otherwise, server defaults are applied.+2. **Legacy `/recall`**: If the context face request returns a 400 or 422 error and the response body contains marker fields like `extra`, `mode`, or `unexpected`, the server is identified as an older version. A 6-hour negative cache is then written locally to `~/.openviking/state/context-face.json`. Because this is a machine-wide shared file, once one harness flags it, every JS-family harness on that machine will bypass the context face stage. The call then degrades to the deprecated `/api/v1/search/recall` endpoint. If `peer_scope` is rejected, it retries once without that parameter.+3. **Raw find fallback**: Concurrently requests `viking://user/memories` and `viking://user/skills` by calling `POST /search/find` twice. (Note: resources are deliberately excluded from automatic recall; resource documents are fetched by the model invoking `search` itself). The client then re-ranks the results locally (using weight rules: leaf +0.12, time intent +0.10, preference intent +0.08, and lexical overlap ≤0.2), deduplicates them, and fills up to the client token budget. The `recallTokenBudget`, `recallMaxContentChars`, and `recallPreferAbstract` configurations take effect *only* at this level. Under the context face, the injection budget is dictated by the server's `max_tokens` (which defaults to 1600).++On the server side, `session_id` handling diverges into two distinct execution paths:++- **Path A: `mode="context"`** (utilized by the context face and the `/recall` preset). This path manages query expansion and the cross-turn deduplication ledger. Query expansion requires passing three gates: `retrieval.enable_intent` must be enabled (default is true) → the session must be materialized (meaning the `messages.jsonl` file exists) → and either `latest_archive_overview` or `current_messages` must be non-empty. Following expansion, the original query always ranks first, followed by a maximum of 3 appended planned queries. The ledger (`.recall_log.json`) applies a cooldown to URIs whose bodies have already been sent, lasting for `dedup_turns`. If a turn "sent only the URI and not the body," that record bypasses the cooldown. Similarly, nothing is recorded if the digest determines the memory is `no_relevant`.+- **Path B: `mode="list"`** (the default behavior when the mode is omitted). In this path, `IntentAnalyzer` completely replaces `typed_queries` (meaning the original query is not guaranteed to survive), bypassing both the ledger and the original-query baseline. Callers that land in this path include codex's second-level degradation `searchScope`, hermes's `viking_search(mode="deep")`, and the preferred prefetch path. Although they carry a `session_id`, they do not benefit from the context face's query expansion or deduplication features.++**Three key notes on `dedup_turns`:**+① **Server default:** The server default for the context face is **0**. The familiar default of "5" actually originates from the `recall-core.mjs` client fallback and the `/recall` preset (the latter applying only when a `session_id` is present). Therefore, a third-party application hitting the API directly without the shared library must explicitly send `dedup_turns` to enable cross-turn deduplication, even if a `session_id` is provided.+② **Turn counting:** A "turn" counts individual messages, not full conversation rounds (since `_resolve_turn` relies on `total_message_count`). For a harness that pushes user and assistant messages simultaneously, the default of 5 roughly equals 1-2 actual conversation rounds.+③ **Edge cases with auto-settings:** If `autoCapture=0` and `autoRecall=1`, the message count remains at 0, meaning the ledger clock never advances. As a result, URIs whose bodies were previously sent remain cooled down for the entire session. To disable deduplication entirely (e.g., for claude-code or codex), use `OPENVIKING_RECALL_DEDUP_TURNS=0`.++### 3.2.2 Decision matrix++| harness | trigger | query construction | session_id | server path | injection format / location | digest (client)* |+|---|---|---|---|---|---|---|+| claude-code | every `UserPromptSubmit` | prompt verbatim, trimmed | ✅ `cc-` | A (context face) | `<openviking-context>` → `hookSpecificOutput.additionalContext` | ✅ local/server (default auto, [§3.2.5](#_3-2-5-recall-digest)) |+| codex / trae-cli | every `UserPromptSubmit` (hard 120s deadline for the whole hook) | prompt verbatim | ✅ `cx-` (derived deterministically, no state read) | A; second-level degradation searchScope lands in B | `<openviking-context source="auto-recall" format="digest">` | ✅ local `codex exec` ([§3.2.5](#_3-2-5-recall-digest)) |+| cursor | `beforeSubmitPrompt` | prompt verbatim; deduped by event id and a 500ms window, reusing the cached block for the same promptHash | ✅ `cu-` | A | `additional_context` | ❌ |+| trae / trae-cn | `UserPromptSubmit` | prompt with prior injection blocks stripped (reads `input.prompt` only) | ✅ `tr-`/`trcn-` | A | `additionalContext` | ❌ |+| zcode | `UserPromptSubmit` | three kinds of injection block stripped (including `<system-reminder>`) | ✅ `zc-` | A | `additionalContext` (strict JSON) | ❌ |+| opencode | the user message in every `chat.message` | concatenates non-synthetic text parts; skips recall for the turn if the body already contains `<openviking-context` | ✅ `oc-` | A (timeoutMs=30000) | builds a synthetic part and `unshift`s it to the front of parts | ❌ |+| dsh | `agent/pre-step` waterfall (await next first, then append) | every message in the claimed batch (filtering out its own injected content) | ✅ `dsh-` | A | appended to the end of `decision.messages` via `createUserMessage` (source: plugin/openviking-memory) | ❌ |+| pi | queued during `before_agent_start`; retrieval runs inside the `context` event (this turn's prompt gets this turn's memories) | prompt verbatim | ✅ `pi-` (omitted before the session exists) | A | prepended to the last real user message (idempotency checked via `<openviking-context`) | ❌ |+| openclaw | context-engine transformContext assemble (7 passthrough gates) | plain text of the last user message, cleaned and cut to 4000 characters | ❌ (`/find` has no such field) | `/find` | prepended into the last user message as `<relevant-memories>` + `Source: openviking-auto-recall` | ❌ |+| hermes | `prefetch` runs synchronously before every API call | raw user input, with two layers of skill scaffolding stripped; skipped under 5 characters | partial (only on the preferred `search/search` path, which lands in B; omitted when degrading to `/find`) | B / find | `<memory-context>` fenced block appended to the current user message (request body only, never written back to storage) | ❌ |++\* As in [§1.2](#_1-2-automatic-hook-surface-driven-by-the-harness), "digest" in this column refers to client-side local compression, while the server digest is available to every caller ([§3.2.5](#_3-2-5-recall-digest)). The `ov` CLI has no automatic recall and is not included in this table.++### 3.2.3 Profile / opening injection++- **Implementation**: `profile-inject.mjs` reads the full `viking://user/<space>/memories/profile.md`, alongside a recursive listing of the `preferences/` and `entities/` directories (`abs_limit=512`). The budget estimation logic is CJK-aware: characters ≥U+3000 count as 1.5 tokens per character, while all others are calculated as characters divided by 4. The profile consumes half of the available budget. If the limit is exceeded, the middle section is elided, preserving "the first 8 lines + the tail." If a directory listing exceeds the limit, a `... +N more` note is appended.+- **Who injects, when, and with what budget**:+ - **claude-code**: On `SessionStart` (all sources, 10000 budget).+ - **codex**: On `SessionStart` (startup/clear/resume, 10000 budget).+ - **cursor / trae×2 / zcode**: On `SessionStart` (6000 budget, 2s debounce).+ - **opencode**: Once per session on the first `chat.message` (10000 budget, deduplicated by an in-process `Set`, subagent sessions skipped). Note that opening injection is attempted only once per session and does not retry in-process after a failure.+ - **dsh**: Posts `profileDelivered` once per session (10000 budget; not re-posted after compaction).+ - **pi**: Injected into the `systemPrompt`, re-assembled for every prompt (10000 budget, always resident).+ - *Note:* `openclaw` and `hermes` do not perform profile injection.+- **Archive injection** (pulls the previous archive summary back upon resume):+ - **claude-code**: `source=resume/compact`, `token_budget=32000`, ≤5 `pre_archive_abstracts`.+ - **codex**: On resume, when the local `ovSessionId` has already been cleared (32000 budget / truncated to 6000 characters).+ - **opencode**: Executed as part B of the opening injection (32000 budget).+ - **pi**: Active in non-takeover mode (32000 budget).+- **Repo context injection**: Unique to `opencode`. It inserts the list of indexed repositories into the system prompt via `experimental.chat.system.transform`.++### 3.2.4 Timeout and budget chain++- **Family A client derivation**: With rewrite, the timeout is `max(timeoutMs, 45000)`; with expansion, it is `max(timeoutMs, 15000)`. The corresponding server-side fuses are 5s (expansion) and 30s (rewrite). By design, the client budget accommodates every server stage, ensuring the client never aborts early and loses the entire response.+- **Actual timeout values**:+ - **claude-code (cc)**: 15s (against a 60s hook budget).+ - **codex**: Recall enforces a hard 120s deadline for the entire hook, plus a 110s compression subprocess.+ - **cursor / trae×2 / zcode**: 15s (against a 20s host hook budget).+ - **opencode / dsh / pi**: 15s (`dsh` blocks the pre-step).+ - **openclaw**: Imposes a 5s hard timeout around the entire recall flow (including a 500ms health precheck). Since the default `recallPreferAbstract=false` means every leaf memory costs one extra read, this budget allows at most 1 find + 6 reads + 1 health check.+ - **hermes**: 4s total / 3s per request (configurable).+- **Injection budget**: The server's `max_tokens` defaults to 1600 (Family A harnesses do not send this by default, allowing the server to dictate the limit). Both `openclaw` and `hermes` utilize a 4000-character budget, opting to "skip an entry that does not fit" rather than truncating it.++### 3.2.5 Recall digest++**Server implementation (available to all callers)**: The context retrieval face (covering REST `mode="context"` and legacy `/recall`) accepts a `rewrite` parameter—which can be `false`, `true`, or `"auto"` (defaulting to `false`)—alongside `rewrite_max_bullets` (defaulting to 6, with a range of 1-20). When enabled, the server leverages the `query_planner` model to rewrite recall results into a digest with citations. (If `rewrite=true` but `query_planner` is unconfigured, it falls back to the main `vlm`; `"auto"` only takes effect if `query_planner` is explicitly configured). The digest features an `OpenViking memory digest:` header followed by bullet points (`- `). Each bullet must be ≤500 characters and must cite a valid `viking://` URI from the hit set (bullets with missing or out-of-range citations are dropped). If the model determines there are no relevant memories, it emits a sentinel value and clears the injection block, ensuring that turn is not recorded in the deduplication ledger. This model call is protected by a fuse (`retrieval.recall_rewrite_timeout_s=30s`). On timeout, it falls back to providing the un-rewritten, rendered block (`rewrite.py:78-141`, `pipeline.py:122-130`, `search.py:195-196`).++**Client-side status**:++- **claude-code**: `recallRewrite` supports four states: `off`, `client`, `server`, and `auto` (defaulting to **auto**). It initially probes for a local compressor via `claude --version` (caching the result for 7 days). If available, compression runs in a local subprocess: `claude -p --model sonnet --effort low --strict-mcp-config`. This subprocess has a 30s timeout, skips compression for inputs under 1500 characters, uses per-digest caching, and force-degrades its environment to prevent recursion. Subprocess failures fall back to the uncompressed block. URIs are snapped back to valid URIs using edit distance, and any irreparably broken bullets are dropped. If no local compressor is found, it sends `rewrite:"auto"`, deferring to the server. Notably, this is the *only* harness actively wired to the server-side rewrite.+- **codex**: The boolean `recallCompress` defaults to **true** and relies entirely on local compression (it does not utilize the server rewrite). The model profile is read from `~/.codex/models_cache.json` (candidates range from `gpt-5.3-codex-spark` to `gpt-5.6-luna`, cached for 7 days). The execution command is `codex --sandbox read-only --ask-for-approval never exec --ephemeral --ignore-user-config --skip-git-repo-check --output-last-message <tmp> -`, with a 110s timeout. If a runtime failure occurs, compression is disabled for the remainder of the session and re-probed at the next `SessionStart`. Outputs are normalized and truncated to 4000 characters. When compression is turned off or fails, a deterministic `fallbackDigest` takes over.+- **Other harnesses**: None of the other harnesses send the `rewrite` flag or compress locally; they simply inject the raw recall block returned by the server. Third-party applications directly calling the API can pass `rewrite` themselves to leverage the server digest.++### 3.2.6 Injection backflow protection++To prevent injected content from being captured a second time, the injection process wraps the content in deterministic tags (like `<openviking-context>`), which the capture mechanism then mechanically strips. Specifically, `capture-utils`' `sanitizeCapturedText` function removes injection blocks, digest blocks, metadata fences, and timestamp prefixes.++**Per-harness specifics:**+- **trae / zcode**: Utilize their own cleaning functions (zcode's strips three distinct types of injection blocks).+- **openclaw**: Strips `<relevant-memories>` twice—once when writing data back during `afterTurn`, and again when constructing the query for the next turn.+- **hermes**: Goes a step further by entirely dropping the `tool_call` and `result` of all three recall-type tools from the sync batch (while retaining write-type tools).+## 3.3 Session and commit lifecycle++### 3.3.1 Mechanism foundations++- **Write path**: The JS family routes all writes through `batch-send.mjs` (endpoint `POST /messages/batch`, capped at 100 messages per batch to match the server's `max_length=100` limit; on a 404/405 error, it gracefully degrades to sending one message at a time). Incremental cursors are implemented per integration (e.g., `cc` and `codex` compute a cursor from the transcript turn index; `cursor` uses `sha256(index+role+content)`; `zcode` relies on the rollout `turn_id`; `opencode` uses an event-stream Map; `dsh` uses an event allowlist; `pi` uses the branch entry watermark; and `hermes` slices by the current turn).+- **Commits are client-triggered** (see [§2.3](#_2-3-server-side-session-and-commit-semantics)): The server does not auto-commit by default. Any "threshold/trigger" condition mentioned in the tables below refers strictly to client-side logic.+- **Differences in `keep_recent_count`** (determining how much of a "live tail" a commit leaves for the host): The server default is 0. Here is what each integration passes: `cc`/`codex` pass 10 on threshold commits; `cursor`, `trae×2`, and `zcode` send an empty body `{}`, meaning 0 (every commit acts as a full archive); `opencode` and `dsh` pass 10; `pi` passes 10 outside takeover mode and 3 within it (locally, this means "keep 3 user turns," but the server interprets it as a raw message count, so fewer messages are actually retained); `openclaw` passes 10 on an `afterTurn` threshold trigger and 0 on `compact`/`reset`/`memory_store` operations; `hermes` always passes 0.+- **Write-path detachment** (`async-writer.mjs`, enabled by default for `cc`/`codex`/`zcode` on `Stop`): The execution flow is drain stdin → spawn detached worker → approve → write payload → unref. *(Note: If spawning fails, approval has not yet occurred, ensuring the synchronous fallback executes exactly once).* The detached worker forms its own process group, immunizing it against terminal signals. This is the crucial mechanism that makes `cc` reliable during shutdown and prevents `zcode` from losing writes upon `Ctrl+C`. **Side effect:** Once detachment is active, `Stop` no longer prints the `appended N turn(s)` notice (to restore this, set `OPENVIKING_WRITE_PATH_ASYNC=0`).++### 3.3.2 Regular commit triggers++| harness | turn-level threshold | explicit / boundary trigger | compaction trigger |+|---|---|---|---|+| claude-code | Stop: `pending_tokens ≥ 20000` (reads the server value), keep 10 | SessionEnd: unconditional; SubagentStop: unconditional (no threshold); SessionStart: replays pending | PreCompact: unconditional (runs synchronously, no detach) |+| codex / trae-cli | Stop: same as above, 20000 / keep 10 | SessionStart(startup\|clear): an active-window heuristic (exactly 1 state within 2min → commit; ≥2 → skip) + an idle-TTL sweep (>30min always commits and cleans up) | PreCompact: full commit (sends an empty body `{}`), then sets `ovSessionId=null` |+| cursor | stop: `capturedSinceCommit ≥ 8` (counted in messages, ~4 Q&A turns; purely client-side counting), keep 0 | sessionEnd: registered (but never reached in practice, see [§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)) | preCompact: unconditional |+| trae / trae-cn | Every Stop with content commits (no threshold), keep 0 | — | None (no PreCompact event upstream) |+| zcode | Same as trae (every Stop commits, keep 0; the rollout incremental cursor advances conservatively, so any missed turns are caught up on the next Stop in the same session) | — | None (no PreCompact event upstream) |+| opencode | `session.idle` path: after the flush runs, `pending_tokens ≥ 20000` must hold before it commits, keep 10 | `session.deleted` / `session.error`: forced commit; dispose: forced commit | Fires once before `experimental.session.compacting` and once after `session.compacted` (so one host compaction = two commits) |+| dsh | `turn/end`: `pending_tokens ≥ 20000` (30s timeout), keep 10 | Teardown (see [§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)) | None (does not listen for compaction events) |+| pi (takeover on by default) | `onTurnSynced`: when the locally estimated `pendingTokens ≥ 30000` and `lastSeenUserTurns > 3`, runs commitAndAdvance (keep 3; the overview polls 15 times at 2s intervals, and if it returns empty, the boundary does not advance, but pendingTokens is zeroed and retried once it has accumulated again) | Run `/viking commit` manually | `session_before_compact` (requires a non-empty `firstKeptEntryId`) |+| pi (takeover off) | After syncBranch runs: server-side `pending_tokens ≥ 20000`, keep 10 | `session_shutdown`: unconditional commit; run `/viking commit` manually | `session_before_compact`: unconditional commit |+| openclaw | afterTurn: `pending_tokens ≥ floor(tokenBudget × 0.5)` (ratio defaults to 0.5, tokenBudget defaults to 128000, making the threshold ~64000), wait=false, keep 10 | `before_reset` (running `/new` `/reset`): wait=true, keep 0; the `memory_store` tool: wait=true, keep 0 | `compact()`: wait=true, keep 0 (Phase2 polls for up to 5 minutes) |+| hermes | No threshold commit — every trigger is a session boundary: `on_session_end` (10s drain; if incomplete, this round aborts the commit), `on_session_switch` (covers `/new`, `/resume`, `/branch`, and compaction forks, async drain budget 65s), gateway cache eviction; `/undo` and in-place compaction do not commit. An idempotency set prevents duplicate commits; keep 0 | atexit fallback | Commits at fork-style compaction boundaries; in-place compaction does not commit |+| ov CLI | None | `ov session commit`; `ov add-memory` always commits in step 3 | — |+| ingest | `pending ≥ 6000` or 5s idle, keep 0; backfill runs `commit_if_needed` at the end of every session | Runs `_flush_all()` on exit | — |+| LangChain | `CommitPolicy.mode` defaults to `never`; the `pending_tokens` mode threshold is 8000; the `always` mode triggers on every record | Up to the caller | — |++### 3.3.3 Shutdown method × harness outcome matrix++Legend: **C** = commits; **C\*** = commits, with a precondition (see notes); **—** = does not commit (messages already POSTed stay in the server's live area: the message bodies are not lost, they wait for a later trigger to archive and extract them); **n/a** = not applicable. The server-side behavior is **—** on every row ([§2.3](#_2-3-server-side-session-and-commit-semantics)).++| harness | normal exit | Ctrl+C | SIGTERM | SIGHUP / close terminal / close window·tab | kill -9 / crash | recovery path |+|---|---|---|---|---|---|---|+| claude-code | **C** (SessionEnd → a detached child process commits, so the user does not wait) | **C** | **C** | **C** (the detached worker forms its own process group and is unaffected by SIGHUP) | **—** | Next Stop over the threshold / `/compact` / next SessionEnd |+| codex / trae-cli | **—** (no SessionEnd-style event upstream) | **—** | **—** | **—** | **—** | The heuristic on the next `SessionStart(startup\|clear)` (exactly 1 active state within 2min → commit) or the 30min idle-TTL sweep; with ≥2 concurrent sessions, the heuristic defers to the TTL sweep |+| cursor | **—** (closing a chat or opening a new chat fires no event) | **—** | **—** | **—** (`sessionEnd` is registered and only fires on window_close, but by then the host has destroyed the shell-exec host, causing the hook to abort before spawn) | **—** | A session ending below the 8-message watermark leaves its tail waiting for later messages in the same session to trigger a commit |+| trae / trae-cn | **—** (no session-end-style event) | **—** | **—** | **—** | **—** | Every Stop has already committed, meaning the most data left to archive equals the last in-flight turn |+| zcode | **—** (no session-end-style event) | **C\*** | **—** | **—** | **—** | C\* precondition: The Stop for that turn had already fired when Ctrl+C arrived (the detached worker finishes writing as usual); every Stop has already committed, and missed turns are recovered by the rollout cursor on the next Stop in the same session |+| opencode | **C\*** (≥1.15.11 `dispose` calls `flushAll({commit:true})`, covering all four shutdown paths; <1.15.11 has no such hook → —) | **C\*** | **C\*** | **C\*** | **—** | C\* precondition: The host shutdown budget is 5s, while a single session takes up to 5s for health + 10s for batch + 30s for commit, and multiple sessions process serially. A commit overrunning the budget is cut off, and the pending queue does not cover this (unsettled fetches are never queued); after a restart, `init()` does not proactively flush leftover sessions |+| dsh | **C** (Cordis teardown triggers one 3s-timeout commit per session, no threshold) | **C** (the first one; a second Ctrl+C force-quits → —) | **C** | **—** (no SIGHUP listener) | **—** | The teardown commit and the threshold commit share a serial write chain, meaning it may not fit inside the 5s process grace period if a slow request precedes it; in the web form, closing the browser tab does not trigger a teardown |+| pi (takeover default) | **—** (`session_shutdown` fires on every shutdown path and is awaited, but the handler persists local takeover state and does not commit) | **—** | **—** | **—** | **—** | The next run accumulating 30000, or a manual `/viking commit` |+| pi (takeover off) | **C** (`await sync.commit()`, failures go to the pending queue) | **C** | **C** | **C** | **—** | — |+| openclaw | **—** (upstream sends an awaited `session_end(reason=shutdown\|restart)`; the handler caches agentId and returns without triggering a commit; `gateway_stop` is not registered; no signal handling) | **—** | **—** | **—** | **—** | Explicit `/new` `/reset` and the ~50% threshold; sessions below the threshold rely on these two paths for archiving |+| hermes | **C** (atexit `_run_cleanup` → 10s flush → on_session_end) | **C** (both interactive and non-interactive trigger atexit) | **C** (`_signal_handler`, grace period defaults to 1.5s → clean exit → atexit) | **C** (SIGHUP follows the same path as SIGTERM) | **—** (atexit does not run) | If the drain does not finish, this round aborts the commit (avoiding a half-written commit); an exit watchdog kills slow commits at 30s |+| ov CLI | n/a (one-shot command) | n/a | n/a | n/a | n/a | No pending queue; just re-run a failed command |+| ingest | **C** (`finally _flush_all`) | **C** (SIGINT → stop) | **C** | **—** (no SIGHUP handler) | **—** | The only write path offering crash recovery: `needs_commit` is persisted in the cursor store, and the subsequent run's reconciliation completes the commit |+| LangChain / Open WebUI / Agent Plugins / generic MCP | **—** (no session lifecycle hooks; the `DELETE /mcp` sent by an MCP proxy on exit only releases the protocol session and does not trigger memory commits) | — | — | — | — | LangChain relies on the caller's `close()`; the in-process pending-commit set disappears alongside the process |++**Three reading notes**:++1. Five integrations commit on a normal exit: `claude-code`, `opencode` (≥1.15.11), `dsh`, `pi` (takeover off), and `hermes`. The rest rely on the recovery mechanisms detailed in the "recovery path" column.+2. No integration commits under `kill -9` — messages already submitted remain in the server's live area and are archived the next time the same session triggers a commit. The server offers a per-session idle fallback ([§2.3](#_2-3-server-side-session-and-commit-semantics)), which the current plugins do not utilize by default.+3. `trae×2` and `zcode`, which commit on every turn, offer the simplest shutdown semantics (the maximum data left to archive equals the last round that never reached Stop), at the cost of a full archive and memory extraction on every Stop (keep 0).++### 3.3.4 pending queue / offline compensation comparison++| harness | mechanism | notes |+|---|---|---|+| cc / cursor / trae×2 / zcode / opencode / dsh / pi | On-disk queue `~/.openviking/pending` (0700/0600) | Only retryable failures are queued (4xx errors, including 401/403, are considered non-retryable and are not queued, though they appear in debug logs); replay runs at session start: ≤50 entries per run, ≤3 attempts per entry, TTL 7 days; `.processing` claims entries atomically, with a 10min stale reclaim; an addMessage failure breaks execution immediately to preserve order |+| codex / trae-cli | No on-disk queue | When the server is unreachable, compensation occurs because the `capturedTurnCount` cursor does not advance, prompting the next Stop to resend the same batch. This works provided the process survives and a subsequent turn occurs |+| openclaw | No local queue | An addSessionMessage failure is caught, and that turn's messages are not replayed |+| hermes | In-process daemon-thread queue | The drain operates on a strict budget (10s/65s); nothing is written to disk |+| LangChain | In-process `_pending_commit_sessions` set | A failed commit is retried automatically during the next record; nothing is written to disk. On partial success, it raises an `OpenVikingPartialWriteError` (carrying `messages_written`, `input_messages_consumed`, and `context_attached`, allowing the caller to slice by position and retry the suffix) — making this the only protocol across all integrations that reports partial success |+| ingest | SQLite cursor store + single-instance lock | The intent is persisted before appending. After a crash, a reconciliation process checks the server's message count to determine if the batch landed—making this the only write path with true crash-recovery semantics |++### 3.3.5 subagent session comparison++| harness | handling |+|---|---|+| claude-code | Offers the most complete isolation: SubagentStart derives a separate `cc-<sid>__subagent-<agent_id>` session, and SubagentStop reads the subagent transcript, pushes it, commits unconditionally, and clears the state |+| codex / trae-cli | No separate session: Subagent output (`agent_message` / `sub_agent_activity`) is folded into the main session's assistant/tool components |+| opencode | `oc-<parent>__subagent-<child>` hangs under the parent namespace; the session-start injection skips subagents (though recall does not); ID derivation is sensitive to event order — when `chat.message` arrives before `session.created`, the `__subagent-` suffix is lost |+| dsh | Each subagent operates as a separate `dsh-<id>` session, preserving no parent-child relationship; N subagents = N profile injections + N separate sessions |+| hermes | `delegate_task` passes `skip_memory=True` → the subagent is disconnected from OV (no session, recall, or tool surface); subtask output is not fed back |+| cursor / trae×2 / zcode / pi / openclaw | No specific subagent handling (anything generating its own session ID becomes its own session; otherwise, it mixes into the main session. `openclaw` can mask this behavior using `bypassSessionPatterns`) |+| ingest | The `claude_code` adapter skips `isSidechain` / `isMeta` records, meaning subagent conversations are not ingested |+## 3.4 Compaction takeover++### 3.4.1 Decision matrix++| harness | Stance on host compaction | Before compaction | After compaction |+|---|---|---|---|+| claude-code | No takeover | PreCompact commits synchronously. This is the only write path that does not detach, as CC rewrites the transcript immediately afterward. | A SessionStart with `source="compact"` re-injects OV's `latest_archive_overview` plus ≤5 abstracts. |+| codex / trae-cli | No takeover | PreCompact backfills uncaptured turns → full commit → `ovSessionId=null`. If the backfill is incomplete, no commit occurs and it is left for retry. There is no PostCompact wiring; it relies instead on the transcript shrinkage observed at Stop for defensive correction. | Injects the archive digest upon resume. |+| cursor / trae×2 / zcode | No takeover | Cursor: `preCompact` commits unconditionally (Trae×2/Zcode lack this upstream event). | — |+| opencode | No takeover | Flush and commit prior to compaction. | Flush and commit again once `session.compacted` fires (two commits in total). |+| dsh | Unaware. It does not listen for compaction events; injection rides on a pre-step user message and shrinks alongside the host's compaction. The profile is not re-sent. | — | — |+| pi | **Two-layer takeover** (on by default, [§3.4.2](#_3-4-2-pi-takeover)) | `session_before_compact`: flush → commit → `pollOverview`. On success, it returns a custom compaction summary that overrides Pi's. On failure, it fails open and falls back to Pi's default compaction. | Calls `resetBoundary` upon success. |+| openclaw | **Full takeover**: `ownsCompaction: true`, the host no longer runs its own summary ([§3.4.3](#_3-4-3-openclaw-contextengine)) | `compact()` = `commit(wait=true, keep 0)` → reads the overview back and utilizes it as the summary. | The main `assemble` rebuilds context with `[Session History Summary]`. |+| hermes | No takeover (The `on_pre_compress` interface is reserved but currently plays no role in compaction summaries.) | A fork-style compaction boundary triggers a commit of the old session, whereas in-place compaction does nothing. | — |++### 3.4.2 pi takeover++- The takeover surface involves rewriting the messages of the `context` event; Pi's native history storage remains untouched. The trigger is token pressure (30000 tokens + keep 3 turns) rather than Pi's native compaction event.+- The replacement process: first locate the boundary, then replace every preceding message with a single synthetic user message, `[OpenViking Session Context]`. The overview within this message is truncated at 3000 tokens. Its timestamp is set to the first kept message minus 1, which stabilizes the provider payload to ensure prompt cache hits.+- The data source is `latest_archive_overview` fetched via `GET /sessions/{id}/context` (polled 15 times at 2-second intervals). This state is persisted in Pi's own branch via the custom entry `ov-takeover`.+- Failure stance: fail-open, reverting to the full history. This occurs under three fallback conditions: a fingerprint mismatch, a history shorter than the boundary, or an unavailable overview.+- Relationship to Pi's native compaction: upon success, `session_before_compact` returns `{compaction: {summary, firstKeptEntryId, …, details: {source: "openviking"}}}` to override Pi's summary. If `firstKeptEntryId` is missing, it falls through to Pi's default compaction behavior.++### 3.4.3 openclaw ContextEngine++- Implements the host's `ContextEngine` interface. The `assemble()` function splits into two branches: `transformContext` (handling recall pre-injection only, protected by 5 passthrough guards) and main `assemble` (calls `getSessionContext(tokenBudget)` → replaces the host's live history with the server response using a four-tier budget split, protected by 3 passthrough guards and a provider-message sanitization pipeline).+- `compact()` executes `commit(wait=true, keep 0)` (utilizing 500ms polling, with Phase 2 capped at 5 minutes) → `latest_archive_overview` becomes the summary, and the last segment of `archive_uri` serves as `firstKeptEntryId`. Note that `customInstructions` and `compactionTarget` are reserved interfaces that currently play no role in the compaction output.+- `ingest()` and `ingestBatch()` are deliberate no-ops; all writes are routed through `afterTurn`.+- If an archive exists, a 20-line "Session Context Guide" is injected via `systemPromptAddition`. This instructs the model to re-read the summary before claiming it has "no information" and to attempt at least two different keyword sets using `ov_archive_search`.++### 3.4.4 pi vs. openclaw takeover++| Dimension | pi takeover | openclaw ContextEngine |+|---|---|---|+| Host contract | Rewrites the messages of a single context hook | Registers a `ContextEngine` with `ownsCompaction: true` |+| Source of truth for history | Pi's local branch | OV server-side `getSessionContext` |+| Trigger | Client-side token threshold (30000) + keep 3 turns | Host invocations of `assemble` or `compact` |+| Compaction output | A single synthetic user message (truncated at 3000 tokens) | The fully rebuilt messages array plus a compaction summary |+| Failure stance | Fail-open, reverting to the full history | Passthrough, reverting to the host's live messages |+| Recall and session | The context interface carries `session_id` | `/find` does not (expansion and ledger are excluded) |++## 3.5 Type boundaries for writes and deletes++### 3.5.1 Write boundary++There are three primary guards on MCP `write` and REST `content/write` (`content_write.py`). First, the writable domain is strictly limited to `viking://resources`, `viking://user`, and `viking://agent`. Second, file extensions for new files must match the whitelist (`.md`, `.txt`, `.json`, `.yaml`, `.yml`, `.toml`, `.py`, `.js`, `.ts`). Third, the four managed subtrees (`skills/`, `peers/`, `privacy/`, `sessions/`) under the user root are designated as read-only (`_USER_MANAGED_SUBTREES`). Additionally, derived files (such as `.abstract.md`, `.overview.md`, and `.relations.json`) cannot be written to directly.++### 3.5.2 Delete boundary++**Tier 1: The universal server-side defense (shared by every delete entry point).** The first statement of `VikingFS.rm`, `_ensure_delete_access` (`_access.py:182-229`), enforces five checks: namespace accessibility; ongoing user deletions (returns `FailedPrecondition`); actor-peer hidden views (returns `PermissionDenied`); namespace root protection (bare `viking://`, along with the `viking://user` and `viking://agent` roots, are unconditionally refused); and restricting deletes in `viking://temp` to ROOT only. This tier defends exclusively at the namespace root level and does not differentiate between memory, resource, or skill types. Those type-level distinctions are enforced on the client side by the subsequent three tiers.++**Tier 2: No client-side additions (the MCP surface + dsh / pi / langchain / ov rm).** Here, the differences lie purely in the parameters. In the `viking_forget` implementation for dsh and Pi, `recursive` is hardcoded to false (preventing directory deletion), and semantic query deletions require a score > 0.8. LangChain's `viking_forget` exposes `recursive` as a model-controllable parameter, although the tool is not exposed by default. The CLI command `ov rm -r` explicitly enables recursion without a confirmation prompt, whereas the TUI's `d` key enforces a y/n confirmation and bans the deletion of root or scope directories.++**Tier 3: The two memory-only delete surfaces.**++- In openclaw's `memory_forget`, three regex whitelists restrict deletions strictly to `viking://user/[…/]memories`, `viking://user/<u>/peers/<p>/memories`, and `viking://agent/[…/]memories`. Explicit URIs failing to match these are refused outright. Search-path candidates must pass this same guard first; automatic deletion only proceeds if a candidate is unique and scores ≥ 0.85. Otherwise, candidates are listed so the agent can explicitly select one. The underlying URL always pins `recursive=false`.+- In hermes' `viking_forget`, there are six sequential validations: non-string or empty inputs are refused; a scheme other than `viking://` is refused; queries or fragments are refused; directories or any files not ending in `.md` are refused; the path must match one of four permitted memory path structures and contain at least two additional segments after the `memories` segment (ensuring `memories/` and its category directories are never deleted); finally, the filename must not be `.abstract.md` or `.overview.md`.++**Tier 4: No deletion offered by default (LangChain / Open WebUI).** LangChain's `viking_forget` is only exposed as a tool when configured with `profile="admin"` or `allow_forget=True`. Open WebUI does not offer any deletion tools.++**Add/delete boundary for skills:** The entry points for adding skills are openclaw's `add_skill` (enabled by default), `ov add-skill`, and REST. The delete surfaces that remain entirely read-only for skills (permitting neither addition nor deletion) are openclaw's `memory_forget` and hermes' `viking_forget`. Conversely, the MCP surface, dsh, Pi, and `ov rm` cannot *add* a skill but can *delete* one. This is because addition is blocked by `_USER_MANAGED_SUBTREES` on the write path, whereas deletion succeeds because the delete path does not check that specific constraint.+## 3.6 Degradation and fault tolerance++### 3.6.1 Decision matrix++| harness | When the server is unreachable | Negative cache | HTTP retry | Failure blocks the host |+|---|---|---|---|---|+| claude-code | All hooks catch exceptions → approve (never blocks); at session-start, even pending replays are skipped | context-face 6h + host-cli probe 7d + health 5s | None (relies on pending replay); `peer_scope` degrades once; batch falls back to sequential | No (`uri-guard` deny is by design) |+| codex / trae-cli | All hooks catch exceptions → noop | context-face 6h + compressor runtime_failed (until the next startup) | Same as above (no on-disk pending; resends from the cursor) | No |+| cursor/trae×2/zcode | Fetch errors are swallowed as `status:0`, and catch returns an empty injection; silently skips if the lock isn't acquired within 5s | context-face 6h (no negative cache for unreachable servers; every turn waits the full 15s) | None | No |+| opencode | All paths catch exceptions → WARN; the `event`/`dispose` hooks lack try/catch blocks (non-retryable commit failures bubble up to the host) | context-face 6h only; `/health` is uncached (one round trip per turn) | No synchronous retry; the MCP proxy retries once each for 401/403 and 400/404 | Mostly no (except `event`/`dispose`) |+| dsh | The client swallows all exceptions; `ensureState` failures are not cached (when the server is unreachable, each pre-step makes two 5s health calls) | context-face 6h + an in-process user-space cache that never expires | None; pending queue replays 3 times across processes | Yes (pre-step runs profile+recall serially; session/flush blocks) |+| pi | On health failure, `start()` returns early; subsequent prompts silently retry the connection | context-face 6h | None; pending queue only | Partly (`session_shutdown` is awaited: ~0s with takeover, max 30s without; on a `turn_end` network error, each message waits 10s) |+| openclaw | Client construction never fails; health checks swallow exceptions; recall is skipped if the 500ms precheck fails | No negative cache (one 500ms health precheck per turn) | None (a single fetch); Phase2 polling in commit/afterTurn | No (except when `memory_store` re-raises; `compact()` blocks for up to 5 minutes) |+| hermes | `_client=None` acts as the runtime negative cache (stops retrying in the current process, except for the local auto-start waiter) | No separate structure (`_client=None` handles this) | One retry with a trusted identity, one retry with a fresh sync client, multi-tier degradation; failed commits are not retried | No (a single background worker + per-provider try/except) |+| ov CLI | Mostly exits with 1; `ov status` in table mode always exits with 0; `ov health` exits with 0 even when unhealthy | None | Only one retry on a gateway 401 challenge | n/a (no host) |++### 3.6.2 Common timeouts++General HTTP timeouts are 15000ms (with a 1000ms floor). MCP proxy requests time out at 15000ms, while DELETE requests are pinned to 2000ms. Cross-process lock waits are 5s, becoming stale at 60s; pending `.processing` entries are reclaimed after 10 minutes. Note that the MCP proxy does not register SIGHUP signals (closing the terminal does not send a `DELETE /mcp` request), but since the server runs with `stateless_http=True`, the impact is minimal.++## 3.7 Additional UX comparison++| harness | statusline | slash command | rule/skill | setup wizard | other |+|---|---|---|---|---|---|+| claude-code | ✅ A separate process writes to `settings.json` (rich segments, 1-min TTL) | ✅ `/openviking-memory:ov` (server status + identity + injection provenance) | 1 experience skill | ✅ Line-based Q&A | Diagnostic scripts (`debug-recall`/`debug-capture`); `uri-guard` is not gated by the plugin toggle |+| codex / trae-cli | ❌ | ❌ | 1 experience skill | ✅ | 8-step SOP in `VERIFICATION.md` |+| cursor | ❌ | ❌ | Rule (`alwaysApply`) + skill | ❌ (Shares the installer TUI) | Standalone `uri-guard`, independent of the plugin toggle |+| trae/trae-cn | ❌ | ❌ | None | ❌ | — |+| zcode | ❌ | ❌ | None | ❌ | — |+| opencode | ❌ (Has toasts) | ❌ | None (Deliberately omitted) | ✅ | — |+| dsh | ❌ | ❌ | None | ❌ | Tool-call cards via `presentCall`; `ctx.provide("openvikingMemory")` allows other Cordis plugins to build upon it |+| pi | ✅ `ctx.ui.setStatus` | ✅ `/viking` `/viking commit` | None | ✅ | `e2e-live.sh` |+| openclaw | ❌ | ✅ 5 commands (`/add-resource`, `/add-skill`, `/ov-search`, `/ov-query-config`, `/ov-recall-trace`) | 3 skills shipped with the plugin | ✅ (Key role detection, version compatibility checks, and a `status` command) | Gateway HTTP routes for visualizing recall traces; feature-gated RPCs; health-check script |+| hermes | ❌ | ❌ | None | ✅ Multi-level curses menus | `hermes memory status` (includes env override lists); `hermes backup` covers `ovcli.conf` |+| ov CLI | ❌ | ❌ (The CLI itself acts as the command) | None | ✅ TUI wizard | Comprehensive help system (63 curated entries); language gating; `ov tui` full-screen file browser (includes in-terminal image previews) |++---++# 4. Harness profile cards++Each card serves as a quick-reference entry point. It records only the facts and differences unique to a specific harness, linking back to the dimension chapters for shared mechanisms. All cards follow the same structure: Form / Capability highlights / Behavior notes / Configuration / Dimension index.++## claude-code++- **Integration docs**: [Claude Code Memory Plugin](./02-claude-code.md)+- **Form**: A Claude Code plugin (marketplace) featuring a four-in-one architecture: 9 hooks, an MCP proxy (passing through 15 tools), a slash command, a statusline, and 1 experience skill. Version 0.4.4.+- **Capability highlights**: The harness with the broadest hook coverage — `SessionStart` (120s) / `UserPromptSubmit` (60s) / `PostToolUse:Read` (5s, the skill-experience hook, off by default) / `PreToolUse:Read|Glob|Grep` (5s, `uri-guard`) / `Stop` (45s) / `PreCompact` (30s) / `SessionEnd` (30s) / `SubagentStart` (10s) / `SubagentStop` (45s). Recall digesting is enabled by default (local `claude -p`, falling back to the server-side rewrite automatically when the local CLI is unavailable, [§3.2.5](#_3-2-5-recall-digest)). Provides full sub-session isolation via `SubagentStart`/`Stop` ([§3.3.5](#_3-3-5-subagent-session-comparison)), along with a statusline, slash command, and `uri-guard`. All shutdown paths except `kill -9` trigger a commit ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)).+- **Behavior notes**: The session ID format is `cc-<raw_CC_session_id>`, while subagents use `…__subagent-<agent_id>`. `Stop` commits at a threshold of 20000 (keep 10), and `PreCompact` commits synchronously. Automatic recall excludes resources ([§3.2.1](#_3-2-1-mechanism-foundation-one-shared-pipeline-two-server-side-paths)). The incremental cursor is stored in `/tmp` (if cleared by the system, the entire session is pushed again).+- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.claude_code`), and `ov.conf` (`claude_code` as per [§3.1.4](#_3-1-4-configuration-layers)), offering roughly 40 tunable parameters. The compressor command and model are hardcoded to `claude`/`sonnet`/`low`/30s.+- **Dimension index**: tool surface [§2.1](#_2-1-server-side-mcp-tool-surface) | recall [§3.2](#_3-2-automatic-recall-and-injection) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix) | compaction [§3.4](#_3-4-compaction-takeover) | degradation [§3.6](#_3-6-degradation-and-fault-tolerance) | UX [§3.7](#_3-7-additional-ux-comparison).++## codex++- **Integration docs**: [Codex Memory Plugin](./04-codex.md)+- **Form**: A Codex plugin (marketplace). Features 4 hooks (`SessionStart` 70s / `UserPromptSubmit` 130s / `Stop` 30s / `PreCompact` 60s), an MCP proxy, and 1 experience skill. Version 0.7.5.+- **Capability highlights**: A local recall-compression pipeline (`codex exec`, [§3.2.5](#_3-2-5-recall-digest)). The `SessionStart` active-window heuristic, combined with an idle-TTL scan, automatically reclaims messages left unarchived by earlier sessions ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)).+- **Behavior notes**: The session ID format is `cx-<safeId>` (derived deterministically without reading state). Lacks a shutdown hook (upstream provides no `SessionEnd`), so commits rely on the reclaim path during the next startup. Has no on-disk pending queue (while offline, the cursor simply doesn't advance, and the next turn resends to compensate, [§3.3.4](#_3-3-4-pending-queue-offline-compensation-comparison)). Active-window is 120000ms / idle-TTL is 1800000ms (configured via env). `Stop` detaches by default (the `appended N turn(s)` notice is hidden by default).+- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.codex`), and `ov.conf` (`codex`). Hooks transmit both `Bearer` and the `X-API-Key` compatibility headers ([§3.1.3](#_3-1-3-credential-systems)).+- **Dimension index**: tool surface [§2.1](#_2-1-server-side-mcp-tool-surface) | recall [§3.2](#_3-2-automatic-recall-and-injection) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix) | degradation [§3.6](#_3-6-degradation-and-fault-tolerance).++## trae-cli (TraeCode CLI 2.0)++- **Integration docs**: [TRAE Memory Integration](./13-trae.md)+- **Form**: TraeCode CLI 2.0 is a Codex-family CLI (binary `traecli`, user config `~/.trae/traecli.toml`, TUI support for `/plugins`, `/skills`, and `/mcp`). OpenViking integrates via a **codex plugin alias install**: using `--harness trae-cli` reuses the Codex installation flow, redirecting only the install parameters (binary, home, and config paths) to TraeCode CLI.+- **Capability surface**: Identical to Codex: 4 hooks, an MCP proxy, an experience skill, local recall compression, active-window/idle-TTL commit reclamation, and resume-archive injection. Refer to the Codex profile card.+- **Version support**: TraeCode CLI 2.0 only. 1.0 and 2.0 are not the same CLI — only 2.0 is Codex-family, and only 2.0 can use the codex plugin alias install. The earlier standalone plugin for 1.0, `examples/trae-cli-memory-hooks` (the `~/.trae/cli/hooks.json` + `[mcp_servers."openviking-memory"]` approach), is deprecated.+- **Dimension index**: Same as the Codex card.++## cursor++- **Integration docs**: [Cursor Memory Integration](./12-cursor.md)+- **Form**: Config-driven (modifies `~/.cursor/hooks.json` and `mcp.json`), featuring an MCP proxy, an always-on rule, and a skill. Includes 7 hooks: `sessionStart` (30s) / `beforeSubmitPrompt` (20s) / `beforeReadFile` (5s) / `beforeShellExecution` (5s) / `stop` (30s) / `preCompact` (30s) / `sessionEnd` (30s). The shared library is loaded via relative imports (no vendoring).+- **Capability highlights**: Features a dual `uri-guard` on `beforeReadFile` and `beforeShellExecution` (independent of the plugin toggle). The rule and skill are installed alongside it.+- **Behavior notes**: The session ID format is `cu-<conversation_id>`. `stop` commits every 8 messages (`commitTurnThreshold=8`, counted in messages, keep 0). `sessionEnd` only fires on `window_close`. By then, the host has already destroyed the shell-exec host, so it practically never runs ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)) — sessions ending below the 8-message watermark leave their tail to be archived by a later message in the same session ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). If the server is unreachable, every turn waits out the full 15s recall timeout.+- **Configuration**: Configured strictly via environment variables (the `plugin` section is ignored).+- **Dimension index**: tool surface [§2.1](#_2-1-server-side-mcp-tool-surface) | recall [§3.2](#_3-2-automatic-recall-and-injection) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix) | degradation [§3.6](#_3-6-degradation-and-fault-tolerance).+## trae / trae-cn (IDE editions)++- **Integration docs**: [TRAE Memory Integration](./13-trae.md)+- **Form**: Config-driven (`~/.trae{,-cn}/hooks.json` + a platform-specific mcp.json) utilizing an MCP proxy. It features 4 hooks: SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep\|Bash\|RunCommand(5s) / Stop(30s). The shared library is introduced via relative imports, and the MCP server is named `openviking`.+- **Capability highlights**: Features the simplest and most direct behavior of the group. Every Stop that carries content is committed (keep 0). Consequently, upon shutdown, the largest possible backlog is merely the last in-flight turn ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)).+- **Behavior notes**: trae and trae-cn differ only in their session ID prefixes (`tr-` vs. `trcn-`) and installation paths. The same workload lands in two separate sets of sessions across the two clients, and cross-client sharing occurs via the server-side memory space after extraction rather than by reusing sessions. Note that there is no handling for PreCompact, status lines, skills, or subagents.+- **Configuration**: Environment variables only.+- **Dimension index**: tool surface [§2.1](#_2-1-server-side-mcp-tool-surface) | recall [§3.2](#_3-2-automatic-recall-and-injection) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix).++## zcode++- **Integration docs**: [Community Integrations → ZCode](./08-community-plugins.md)+- **Form**: Config-driven (merged into `~/.zcode/cli/config.json`, forcing `hooks.enabled=true`) utilizing an MCP proxy. It features 4 hooks: SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep(5s) / Stop(30s). This is the only harness that fully vendors all 18 shared files. Version 0.1.1.+- **Capability highlights**: The rollout file `~/.zcode/cli/rollout/model-io-<sid>.jsonl` serves as the source of truth for increments (a `lastTurnId` diff backfills any missed Stop events). Stop detaches by default, meaning Ctrl+C does not result in lost writes.+- **Behavior notes**: Commits on every Stop (keep 0). The capture path only strips the three types of injection blocks without performing any further text cleanup ([§3.2.6](#_3-2-6-injection-backflow-protection)). The initial capture reads the entire rollout at once, meaning that installing it into a long-running session will produce a single large push.+- **Configuration**: Environment variables only; `OPENVIKING_WRITE_PATH_ASYNC` takes effect for zcode.+- **Dimension index**: tool surface [§2.1](#_2-1-server-side-mcp-tool-surface) | recall [§3.2](#_3-2-automatic-recall-and-injection) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix).++## opencode++- **Integration docs**: [OpenCode Plugin](./10-opencode.md)+- **Form**: Provided as the npm plugin `@openviking/opencode-plugin`, featuring a config hook that injects the MCP entry itself (tools carry the `openviking_` prefix). It exposes 7 plugin hooks: config / event / tool.execute.before / experimental.chat.system.transform / chat.message / experimental.session.compacting / dispose. Version 0.2.4.+- **Capability highlights**: The `dispose` hook covers all four standard shutdown paths (on hosts ≥1.15.11). The repository list is injected into the system prompt ([§3.2.3](#_3-2-3-profile-opening-injection)). It boasts the richest host event surface of any integration, with `session.idle`, `compacted`, `deleted`, and `error` each carrying their own specific semantics.+- **Behavior notes**: Features a `commitTokenThreshold` of 20000 (positive values only; 0 falls back to the default) and a commit timeout of 30000ms. A single host compaction equates to two commits. Within the `dispose` hook's 5-second host budget, a slow commit spanning several sessions might be cut short, and the pending queue does not cover this scenario ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). On host versions below 1.15.11, the `dispose` hook is unavailable, meaning shutdowns do not trigger a commit. Leftover sessions are not flushed upon restart. The opening injection is attempted once per session ([§3.2.3](#_3-2-3-profile-opening-injection)). Finally, directory matching in `bypassSessionPatterns` does not apply to opencode, as the input does not carry a current working directory (cwd).+- **Configuration**: Handled via `openviking-config.json` (searched at 4 levels) + environment variables.+- **Dimension index**: tool surface [§2.1](#_2-1-server-side-mcp-tool-surface) | recall [§3.2](#_3-2-automatic-recall-and-injection) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix) | subagent [§3.3.5](#_3-3-5-subagent-session-comparison).++## dsh (DeepSeek Harness)++- **Form**: This is the only in-process, native Cordis plugin (`export function apply`). It natively registers 7 `viking_*` tools (`viking_search/read/browse/remember/forget/add_resource/archive_expand`) and communicates directly via REST. It features 4 events: agent/session-start (emit) / agent/pre-step (waterfall) / session/event / session/flush. Version 0.1.0.+- **Capability highlights**: `ctx.provide("openvikingMemory")` allows other Cordis plugins to build upon it. Pre-step injection is transmitted as a user message, aligning with the `complete:true` rendering mode of the DSH persona.+- **Behavior notes**: Installation requires running `dsh plugin add ./examples/dsh-memory-plugin` (it is not yet covered by the unified installer). The teardown commit is allocated 3 seconds with no threshold, and it does not trigger on SIGHUP or a consecutive Ctrl+C ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). Compaction remains invisible to the plugin: injected content shrinks alongside the host's compaction, and the profile is not re-injected. Each subagent is assigned its own session ([§3.3.5](#_3-3-5-subagent-session-comparison)). Compared to the MCP surface, this tool surface lacks write, edit, tree, grep, glob, watch, and health functionalities. Additionally, `uri-guard` matches tool names without normalizing case.+- **Configuration**: Configured via cordis patch + 4 environment variables. For credentials, the patch overrides env vars; for behavior toggles, env vars override the patch.+- **Dimension index**: tool surface [§1.1](#_1-1-active-tool-surface-agentic-calls) | recall [§3.2](#_3-2-automatic-recall-and-injection) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix) | degradation [§3.6](#_3-6-degradation-and-fault-tolerance).++## pi (pi Coding Agent Extension)++- **Integration docs**: [pi Coding Agent Extension](./11-pi.md)+- **Form**: Operates as a native pi extension (loaded from a directory and dynamically transpiled from TS by jiti). It registers 7 native `viking_*` tools and uses direct REST communication (since pi lacks MCP support). It features 8 events + a `/viking` command. Version 0.1.0.+- **Highlights**: Features takeover compaction (enabled by default, [§3.4.2](#_3-4-2-pi-takeover)). Employs a two-stage recall system: it queues at `before_agent_start` and performs synchronous retrieval during the context event, ensuring the current turn's prompt receives its corresponding memories. It also includes a status line. The `session_shutdown` event triggers across all shutdown paths and is properly awaited.+- **Behavior**: When takeover is enabled, exiting does not trigger a commit. Instead, the handler persists local state, and archiving waits either for the next resumed run to hit the threshold or for a manual `/viking commit` command ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). The takeover threshold is set to 30000 tokens while keeping the last 3 turns (keep 3, which the server interprets as a message count). When takeover is disabled, the threshold is 20000 tokens (keep 10), and exiting triggers an unconditional commit. Tool registration requires `health` and `ensureSession` to be established first ([§1.1](#_1-1-active-tool-surface-agentic-calls)). The `viking_add_resource` tool exclusively accepts HTTP URLs (the guard resides on the server). If takeover is off, resuming via `pi -c` will re-report the entire branch.+- **Config**: Behavior toggles are managed in `config.json` + environment variables (credentials always pass through the credential chain, [§3.1.3](#_3-1-3-credential-systems)). Note that `bypassPatterns` uses prefix matching rather than globs.+- **Dimension index**: tool surface [§1.1](#_1-1-active-tool-surface-agentic-calls) | recall [§3.2](#_3-2-automatic-recall-and-injection) | takeover [§3.4.2](#_3-4-2-pi-takeover) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix).++## openclaw++- **Integration docs**: [OpenClaw Plugin](./03-openclaw.md)+- **Form**: Represents the only full ContextEngine takeover (`ownsCompaction:true`). Features 15 native tools (14 enabled by default) + 5 slash commands + 4 hooks + Gateway HTTP routes + feature-gate RPC. It operates entirely remotely. Version 2026.6.18.+- **Highlights**: Retrieval is split into two non-overlapping entry points by default: `memory_recall` searches memory, while `ov_search` targets resources and user skills (though either can cross over if explicit parameters are provided). The `add_skill` tool is enabled by default, and `memory_forget` is whitelisted exclusively for memory ([§3.5](#_3-5-type-boundaries-for-writes-and-deletes)). Three tool-result tools read server-side externalized outputs (safeguarded across sessions). It features complete ContextEngine takeover ([§3.4.3](#_3-4-3-openclaw-contextengine)), and the setup wizard actively probes the key's role while verifying version compatibility.+- **Behavior**: Recall invokes `/find` without a session ID. Consequently, there is no expansion or deduplication ledger, meaning the same memory might be repeatedly injected during a long session. Shutdowns do not trigger a commit; archiving relies on an explicit `/new` or `/reset` command alongside an approximate 50% threshold ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). There is no local pending queue, so failed turns are not replayed. The `compact()` function can block for up to 5 minutes. By default, recall issues one additional read per leaf memory (`recallPreferAbstract=false`). Configuration validation is exceptionally strict: any unknown key or invalid value immediately forces the plugin into a setup-only mode.+- **Config**: Configured via `plugins.entries.openviking.config` in `openclaw.json` alongside a few environment variables. Utilizes the `X-API-Key` auth header ([§3.1.3](#_3-1-3-credential-systems)). The commit threshold is controlled by `commitTokenThresholdRatio` (default 0.5), and the recall character budget is 4000.+- **Dimension index**: tool surface [§1.1](#_1-1-active-tool-surface-agentic-calls) | recall [§3.2](#_3-2-automatic-recall-and-injection) | ContextEngine [§3.4.3](#_3-4-3-openclaw-contextengine) | deletion [§3.5](#_3-5-type-boundaries-for-writes-and-deletes) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix).++## hermes (Nous Research)++- **Integration docs**: [Hermes Agent](./05-hermes.md)+- **Form**: Implemented as a MemoryProvider bundled directly with Hermes (a single-file Python implementation of 3725 lines, shipped alongside Hermes). It connects directly via `httpx`, eliminating the need for additional plugin installations. It provides 6 tools and over 10 lifecycle hooks (including `prefetch`, `sync_turn`, `on_session_end`, `on_session_switch`, and `on_memory_write`). The baseline is release `e12626b3` (equivalent to brew 2026.7.7.2).+- **Highlights**: Boasts the most comprehensive resource-ingestion surface: `viking_add_resource` supports HTTP, Git, SSH, `file://`, temporary uploads of local files, and zip-packing local directories for upload (automatically skipping symlinks and out-of-tree files). The `viking_remember` tool writes memory files directly, bypassing session commits or extractions. A local server can be initialized on demand; if the configured local endpoint is unreachable, it is automatically launched via `subprocess.Popen openviking-server`. It supports retries with an injected trusted identity. Commits are guaranteed to complete whether triggered by a normal exit, Ctrl+C, SIGTERM, or SIGHUP ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)).+- **Behavior**: During recall, only the preferred `search/search` path carries a session ID and routes to path B (`mode="deep"`). Conversely, the `auto` and `fast` modes call `/find` without a session ID ([§3.2.2](#_3-2-2-decision-matrix)). The `queue_prefetch` hook is implemented synchronously without warm-up. Subagents configured with `skip_memory=True` will not interact with OpenViking ([§3.3.5](#_3-3-5-subagent-session-comparison)). This integration lacks profile injection, a status line, and slash commands. Commits strictly follow a "keep 0" policy; if the queue drain does not finish cleanly, the commit is skipped for that round. Additionally, the in-process queue is never written to disk. Session IDs follow the `%Y%m%d_%H%M%S_<hex6>` format. Recall parameters are strictly defined: 6 results, a 0.15 threshold, a 4000-character budget, and a 4-second total timeout. Memory URIs are formatted as `viking://user/peers/{agent}/memories/{subdir}/mem_<uuid12>.md`. The shutdown sequence incorporates a 1.5-second SIGTERM grace period alongside a 30-second exit watchdog. Finally, a complementary path (`openviking-server ingest hermes`) enables offline replays, though this is disabled by default ([§7](#_7-appendix-non-coding-integrations-at-a-glance) E).+- **Config**: Configured through `OPENVIKING_ENDPOINT` (not `_URL`), 8 `OPENVIKING_RECALL_*` environment variables, and `config.yaml`. In `use_ovcli_config` mode, the corresponding variables in `.env` are cleared.+- **Dimension index**: tool surface [§1.1](#_1-1-active-tool-surface-agentic-calls) | recall [§3.2](#_3-2-automatic-recall-and-injection) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix) | deletion [§3.5](#_3-5-type-boundaries-for-writes-and-deletes).+## ov CLI++- **Integration docs**: [Deployment Guide → CLI](../guides/03-deployment.md#cli)+- **Form**: A native Rust binary that wraps the server's REST API into a command-line interface. It operates without host events, automatic recall, or compaction takeover.+- **Highlights**: The only first-party client capable of sending an `auto_commit_policy` (`ov session new --auto-commit-policy-json`, `ov session config set`). It also offers multi-profile management, admin tools, privacy controls, snapshot management, and TUI capabilities unavailable in any plugin (see [§5.3](#_5-3-capabilities-only-the-cli-has)).+- **Dimension index**: See [§5](#_5-ov-cli-command-reference) for the comprehensive command reference.++---++# 5. ov CLI Command Reference++`ov` (internally identified as `openviking` in clap) is a Rust-based HTTP client. Because all core capabilities reside on the server, the CLI's role is strictly to assemble parameters, pack and upload local files, render output, and manage multiple profiles. It is a standalone tool rather than a harness integration—meaning it does not handle host events, automatic recall, or compaction takeover. This chapter details its complete command surface for using OV directly (either manually or via scripts) and highlights features exclusive to the CLI (such as the TUI, multi-profile management, admin tools, `--sudo`, privacy controls, and snapshots).++> Version note: This guide reflects the HEAD source (with the HEAD tag at `[email protected]`); notable differences from older versions, such as 0.4.10, are explicitly mentioned. Please note that `ov doctor` is not included in the native Rust binary. Instead, the Python wrapper installed via pip intercepts `argv[1]=="doctor"` and routes it to `openviking_cli.doctor`, reading the server's `ov.conf` rather than `ovcli.conf`. The pure Rust `ov` binary distributed via npm/cargo does not include this subcommand.++## 5.1 Command tree++Doc-comment prefixes like `[Data]`, `[Interactive]`, `[Admin]`, or `[Experimental]` only influence the help menu rendering and do not affect runtime behavior. For instance, even `[Experimental]` commands are available by default.++**Writing data**: `add-resource` (supports local files/directories/URLs/Git/sitemaps/RSS; pick one target from `--to`/`--parent`/`-p`; manifest mode via `-m`; Connector via `--add-type`; note that specifying a local path with watch>0 triggers an error) | `add-skill` | `write` (`--content` and `--from-file` are mutually exclusive) | `mkdir` | `rm` (aliases: del/delete; executes without a confirmation prompt; use `-r` for explicit recursion) | `mv` (alias: rename) | `set-tags` (hidden at the top level; use `attrs set-tags` instead) | `add-memory` (experimental; executes a sequence of three serial steps: create session → bulk add → commit)++**Reading/retrieval**: `ls` (alias: list) | `tree` (`-L` defaults to 3) | `stat` / `attrs get` | `read` / `abstract` / `overview` (L2/L0/L1 respectively) | `get` (download) | `find` (requires at least one non-empty query or `--image`; `--image` accepts local paths, data URIs, HTTP URLs, and viking:// schemas) | `search` (experimental; adds `--session-id` on top of find capabilities) | `grep` | `glob`++**Skills**: `skills add` (supports local paths, Git, and GitHub tree URLs; use `-s` to select or `*` for all; prompts for interactive confirmation) | `skills list/find/show/update/remove` | `skills validate` (the only fully offline command)++**Sessions/memory**: `session new` (`--auto-commit-policy-json` and `--no-auto-commit` are mutually exclusive—this is the only first-party client that sends a policy) | `session list/get/delete` | `session get-session-context` (`--token-budget` defaults to 128000) | `session get-session-archive` | `session add-message(s)` | `session config set` (modifies mutable configurations) | `session commit`++**Import/export & snapshots**: `export` / `backup` / `import` / `restore` (.ovpack formats) | `snapshot commit/restore/show/log/diff/ignore-*` (workspace snapshots; rollbacks are achieved by committing forward)++**Privacy/relations**: `privacy categories/list/get/versions/version/activate/upsert` (offers `--key-<name>` syntactic sugar) | `relations`/`link`/`unlink` (experimental)++**Status/observability**: `health` (exits with 0 even when healthy=false) | `status` (table mode always exits with 0) | `observer {queue,vikingdb,models,retrieval,filesystem,system}` | `wait` | `task status/cancel/list` | `task watch {ls,show,rm,pause,resume,update,trigger}` | `version` (probes the server utilizing its own 3-second timeout)++**Config/interactive**: `config` (launches a TUI wizard with a 5-item menu, including User Management) | `config show` (always outputs compact JSON) | `config validate` | `config list/switch/add/edit/delete` (Agent-facing; exit codes 2-6 carry semantic meaning) | `config add ov-service` (cloud) / `config add custom` | `language` (alias: lang) | `tui` (provides a full-screen file browser, in-terminal image previews, a vector view, and deletion confirmations) | `chat` (launches VikingBot with a 300-second timeout) | `compile` (organizes material via a Skill; `--wait` enables local polling)++**Administration (mostly ROOT/`--sudo`)**: `admin create-account/list-accounts/delete-account/set-role/migrate/register-user/list-users/remove-user/regenerate-key` | `system wait/status/health/consistency` | `system crypto init-key` (generates a 32-byte root key entirely locally with 0600 permissions) | `system backend sync-status/sync-retry` | `reindex` (`--mode` defaults to vectors_only; `--wait` defaults to true, making it the only CLI command with this default behavior) | `doctor` (exclusive to the Python wrapper)++## 5.2 Global options and unique mechanisms++- `-o/--output table|json` (defaults to `output` in the config file) | `-c/--compact` (defaults to true) | `--account`/`--user`/`--actor-peer-id` | `--sudo` (utilizes the `root_api_key`; permitted only for admin, system, reindex, task status, and task list commands) | `--profile` (hidden).+- **Multi-profile**: The active profile is stored at `~/.openviking/ovcli.conf`, with alternative profiles named `ovcli.conf.<name>`. The `switch` command performs a direct byte copy (preserving the `plugin` section). Conversely, `add` and `edit` rewrite the file via serde, which drops any keys unrecognized by the Rust Config structure (including the `plugin` section, as detailed in [§3.1.4](#_3-1-4-configuration-layers)).+- **Language gate**: A display language must be configured before executing any commands (if unconfigured in a non-interactive environment, the CLI exits with code 2). As of the HEAD version, `--help` bypasses this gate (unlike version 0.4.10, which lacked this exemption), though `--version` still requires a configured language to run.+- **Three JSON output shapes, categorized by command group**: Under compact mode, standard commands emit `{"ok":true,"result":…}` upon success, a bare payload when `-c false` is passed, and `{"ok":false,"error":…}` upon failure. The configuration command family outputs `{"status":"ok","result":…}`. When a profile is active, `"profile":[…]` is appended to the response. These variations require careful handling when parsing outputs in scripts. Additionally, `echo_command` defaults to true and is not suppressed by `-o json` (meaning the first line of stdout will typically be `cmd: …`).+- **Environment variables**: `OPENVIKING_CLI_CONFIG_FILE`, `OPENVIKING_UPLOAD_MODE` (local/shared), `OPENVIKING_ASSETS_CREDENTIALS_FILE`, `OPENVIKING_LANG`/`LC_*`/`LANG`, along with `VIKINGBOT_ENDPOINT`/`VIKINGBOT_API_KEY`/`OPENVIKING_URL` for chat functionality.++## 5.3 Capabilities only the CLI has++The following operations are inaccessible via the plugin surface and remain exclusive to the CLI/TUI: multi-profile switching and the configuration wizard, the complete `admin` account and user management suite, root operations via `--sudo`, `privacy` policy CRUD and versioning, data movement commands (`snapshot`/`backup`/`restore`/`export`/`import`), index rebuilds via `reindex`, root key generation via `system crypto init-key`, interactive browsing with `ov tui`, VikingBot-dependent features like `ov chat` and `ov compile`, and `ov session config set` for explicitly defining the `auto_commit_policy` (this serves as the only first-party entry point capable of enabling server-side auto-commits).++---++# 6. Custom agent integration guide++If your preferred agent or harness is not among the 11 listed previously, you can integrate it using one of three methods, arranged below from lowest to highest implementation effort.++## 6.1 Integration path × capabilities you get++| Path | Effort | Agent-initiated tool surface | Auto recall/capture hooks | Session/commit | Compaction takeover |+|---|---|---|---|---|---|+| ① [Direct MCP connection](./06-mcp-clients.md) | Minutes (fill in one config block) | ✅ All 15 tools | ❌ The model calls them itself | Only `remember` creates a temporary session | ❌ |+| ② HTTP API / SDK / [LangChain](./07-langchain-langgraph.md) | Hours (requires code) | Flexible (call REST as needed) | Custom implementation | Custom implementation (or use the LangChain middleware) | ❌ |+| ③ Reuse shared-core / the [Agent Plugins portable package](./15-agent-plugins.md) | Days (requires hook adapters) | ✅ 15 tools (through the MCP proxy) | ✅ Full recall/capture/commit/pending set | ✅ | Depends on which events you wire up |++## 6.2 Path ①: Direct MCP connection (recommended starting point)++Any MCP-capable agent simply needs to point its `mcpServers` configuration to the server's `/mcp` endpoint (refer to [MCP Clients](./06-mcp-clients.md) to locate this configuration for each client). Doing so instantly unlocks all 15 tools ([§2.1](#_2-1-server-side-mcp-tool-surface)). The minimal configuration looks like this:++```json+{+ "mcpServers": {+ "openviking": {+ "url": "http://127.0.0.1:1933/mcp",+ "headers": {+ "Authorization": "Bearer <api_key>",+ "X-OpenViking-Account": "<account>",+ "X-OpenViking-User": "<user>",+ "X-OpenViking-Actor-Peer": "<workspace-peer>"+ }+ }+ }+}+```++The last three headers are optional; however, omitting them disables workspace peer isolation and tenant routing. For `stdio`-only clients, you can utilize the portable proxy (Path ③) to bridge `stdio` to streamable HTTP. This path provides a pure tool surface—meaning it does not include automatic recall, capture, or commits (unless the model explicitly invokes the `remember` tool).++## 6.3 Path ②: Programmatic integration++- **Direct REST**: Trigger recall via `POST /api/v1/search/search` (note that expansion and deduplication require `mode:"context"` alongside a `session_id`, as per [§3.2.1](#_3-2-1-mechanism-foundation-one-shared-pipeline-two-server-side-paths); pass `rewrite` to generate a server-side digest, see [§3.2.5](#_3-2-5-recall-digest)). Write data using `POST /api/v1/sessions/{id}/messages/batch` (supports up to 100 messages per batch with `auto_create`). Finalize sessions via `POST /api/v1/sessions/{id}/commit`, and retrieve content using `GET /api/v1/content/read` and related endpoints. To enable server-side auto-commits, explicitly pass the `auto_commit_policy` during `POST /api/v1/sessions`, or modify it later via `PATCH /{id}/config` ([§2.3](#_2-3-server-side-session-and-commit-semantics)).+- **LangChain / LangGraph SDK** (`pip install langchain-openviking`): The `OpenVikingContextMiddleware` provides `wrap_model_call` (which injects recalled content into `<openviking_context>`) and `after_agent` (handling capture and commit actions according to the `CommitPolicy`, which defaults to `never`). Within this group, this is the only out-of-the-box automatic recall solution that includes both session management and a token budget. Its fault-tolerance strategy is to retry read-only methods once and never retry writes. Partial successes raise an `OpenVikingPartialWriteError`, allowing you to retry a specific slice based on `input_messages_consumed`. See [§7](#_7-appendix-non-coding-integrations-at-a-glance) B for more details.+- **Open WebUI** (OpenAPI tool server): Running `python -m openviking_openwebui` launches a standalone process. By adding the resulting Tool Server URL to Open WebUI, you gain access to 7 tools (note that deletion and hooks are unsupported). See [§7](#_7-appendix-non-coding-integrations-at-a-glance) A for more details.+## 6.4 Path ③: Reuse a Reference Implementation for Automatic Hooks++If you need the full spectrum of automation—recall, capture, commit, and pending state management—there is no need to build it from scratch. Consider studying and reusing one of these two existing implementations:++- **`examples/memory-plugin-shared/lib/`** (Node): This provides a complete set of core modules. These include `recall-core` (three-tier degradation recall), `profile-inject`, `capture-utils` (message normalization and injection-echo protection), `pending-queue` (offline replay), `batch-send`, `mcp-proxy-core` (stdio↔HTTP proxy), `session-model` (session ID derivation), and `credentials`. To build a lightweight integration harness, you only need to implement an adapter layer that maps host lifecycle events to these modules. For example, `agent-hook-runtime.mjs` is a ready-made, all-in-one runtime shared by Cursor, Trae, and zcode. Wiring up a new host is usually just a matter of parsing its stdin JSON field names.+- **The Agent Plugins 1.0 Portable Package** (under `agent-plugins/`): This offers a standardized portable format comprising `plugin.json`, the `skills/` directory, and `mcp.json` (stdio→HTTP proxy). It intentionally excludes automatic hooks—instead, recall and persistence rely on a skill that teaches the model to invoke the tools autonomously. This design makes it highly suitable for clients that follow the Agent Plugins specification for direct loading. Additionally, `plugin.test.mjs` defines spec-conformance checks (such as schema URL validation, naming rules, ensuring no secrets in static headers, and preventing `mcp.json` references from escaping the plugin root), which you can use as a linting baseline when packaging your own plugin.++**Three conventions you must follow** (to ensure behavior remains consistent with existing harnesses): ① The recall call site must forward the `session_id`, which enables server-side expansion and cross-turn deduplication (see [§3.2.1](#_3-2-1-mechanism-foundation-one-shared-pipeline-two-server-side-paths)); ② Do not allow the adapter's own timeout to override the deadline dictated by the helper; ③ You must arrange a commit path at shutdown. Otherwise, any remaining conversation tail that falls below the threshold will remain unarchived until a subsequent trigger occurs (see [§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). If the host does not provide a shutdown event, rely on the server-side idle fallback (enable `memory.session_auto_commit.idle_enabled` on the server and pass down a per-session policy). These three rules are exactly what `recall-session-wiring.test.mjs` enforces using cross-plugin regexes.++---++# 7. Appendix: Non-Coding Integrations at a Glance++| Integration | Form | Tool Surface | Session/Commit | Fault Tolerance | Default State |+|---|---|---|---|---|---|+| **A. [Open WebUI](./08-community-plugins.md)** | Standalone FastAPI OpenAPI tool server | 7 local OpenAPI routes (`ov_search`/`ov_recall_memories`/`ov_add_memory`/`ov_list_memories`/`ov_read_resource`/`ov_add_resource`/`ov_session_status`), no deletion tool | No session concept | Most lightweight: bare `httpx`, no retries or negative caching; `/health` only echoes the config and does not probe OpenViking. | Inactive until the process is explicitly started. |+| **B. [LangChain/LangGraph](./07-langchain-langgraph.md)** | Python SDK adapter layer (retriever/tools/store/middleware/recorder) | `create_openviking_tools()` provides 12 StructuredTools (`viking_forget` is not in the agent profile by default) | `thread_id`/`session_id` come from the caller; `CommitPolicy` defaults to `never` | Most robust in this group: read-only methods automatically retry once, writes never retry (to prevent duplicates), and partial successes raise a structured exception that can be retried as a slice. | Requires explicit construction before taking effect. |+| **C. [Agent Plugins 1.0](./15-agent-plugins.md)** | Portable package: `plugin.json` + `skills/` + `mcp.json` (stdio→HTTP proxy) | MCP passthrough for all 15 tools; intentionally excludes hooks (recall relies on a skill instructing the model). | Only `remember` creates a temporary session | Retries handled at the MCP proxy layer (401/403 triggers credential swap, 400/404 triggers re-initialization; max 1 retry each). | Active as soon as loaded by the client. |+| **D. [Direct MCP Connection](./06-mcp-clients.md)** | No local components, connects straight to `/mcp` | Same as C (15 tools) | Same as C | Depends entirely on the client. | `/mcp` is always on. |+| **E. [Log Ingestion](./09-log-ingestion.md)** | `openviking-server ingest` CLI (runs on the machine hosting the logs, importing them in reverse) | None (write-only, no recall) | Session ID `{prefix}__{harness}__{sanitized native id}`; commit token 6000 / idle 5s / keep 0 | The only integration featuring crash recovery: utilizes a SQLite cursor store, single-instance locking, and a reconciliation process to verify batch delivery. | Disabled by default on two levels (`ingest.enabled` and each harness's individual `enabled` flag are both false); adapters available for claude_code, codex, hermes, opencode, openclaw, and cursor. |+| **F. [OpenViking Helper](./14-openviking-helper.md)** | Closed-source desktop app | — | — | — | Outside the scope of this codebase. |++---++*Installation, configuration, and troubleshooting for each integration are governed by their respective integration pages. In the event of a discrepancy between this summary and the individual page, the individual page takes precedence.*++## See also++- [Agent Integrations Overview](./01-overview.md)+- [MCP Clients](./06-mcp-clients.md)+- [MCP Integration Guide](../guides/06-mcp-integration.md)+- [Retrieval API](../api/06-retrieval.md)+- [Sessions API](../api/05-sessions.md)+- [Authentication](../guides/04-authentication.md)diff --git a/docs/zh/agent-integrations/01-overview.md b/docs/zh/agent-integrations/01-overview.mdindex 9949b6a70..4e4772079 100644--- a/docs/zh/agent-integrations/01-overview.md+++ b/docs/zh/agent-integrations/01-overview.md@@ -20,6 +20,10 @@ OpenViking 可以作为多种 Agent 运行时的长期记忆与上下文后端| **Manus / Claude Desktop / ChatGPT / 其他 MCP 客户端** | [MCP 客户端](./06-mcp-clients.md) — 任何兼容 MCP 的客户端直接对接内置 `/mcp` 端点 || **ZCode / AstrBot / …** | [社区插件](./08-community-plugins.md) — 社区维护的各运行时集成 |+## 横向对比各集成能力++想知道各个集成在工具面、自动召回、会话与 commit、压缩接管、降级容错上的具体差异,见 [集成能力参考](./16-capability-reference.md)——一份覆盖全部集成的横向对照矩阵。+## 所有集成的共同前置本页所有集成都需要连接到一个正在运行的 OpenViking 服务。如果你还没有,请先按 [快速开始](../getting-started/02-quickstart.md) 部署。默认端点是 `http://localhost:1933`;远程使用需要 API Key(参见 [鉴权](../guides/04-authentication.md))。diff --git a/docs/zh/agent-integrations/02-claude-code.md b/docs/zh/agent-integrations/02-claude-code.mdindex eb1c90e3f..8bea26e90 100644--- a/docs/zh/agent-integrations/02-claude-code.md+++ b/docs/zh/agent-integrations/02-claude-code.md@@ -112,6 +112,7 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shar## 参见+- [集成能力参考](./16-capability-reference.md)- [博客:在 Claude Code / Codex 中接入 OpenViking](https://blog.openviking.ai/post/openviking-coding-agent/) — 探讨为 Coding Agent 添加长期记忆的动机与实际效果。- [插件 README](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md) — 查看完整的环境变量列表、Hook 运行细节及系统架构图。- [MCP 客户端](./06-mcp-clients.md) — 了解 MCP 工具参数及其他客户端集成指南。diff --git a/docs/zh/agent-integrations/03-openclaw.md b/docs/zh/agent-integrations/03-openclaw.mdindex 9c2a3a3d0..6799d394f 100644--- a/docs/zh/agent-integrations/03-openclaw.md+++ b/docs/zh/agent-integrations/03-openclaw.md@@ -115,6 +115,7 @@ bash uninstall-openviking.sh## 参见+- [集成能力参考](./16-capability-reference.md)- [完整安装指南](https://github.com/volcengine/OpenViking/blob/main/examples/openclaw-plugin/INSTALL.md) — 所有安装路径与参数- [插件设计说明](https://github.com/volcengine/OpenViking/blob/main/examples/openclaw-plugin/README.md) — 架构、身份与路由、hook 生命周期- [Agent 操作指南](https://github.com/volcengine/OpenViking/blob/main/examples/openclaw-plugin/INSTALL-AGENT.md) — 给代用户执行安装的 agent 看diff --git a/docs/zh/agent-integrations/04-codex.md b/docs/zh/agent-integrations/04-codex.mdindex 9538822ab..b0dbc1c20 100644--- a/docs/zh/agent-integrations/04-codex.md+++ b/docs/zh/agent-integrations/04-codex.md@@ -65,14 +65,14 @@ TraeCode CLI 2.0 用户启动 `trae-cli`,并可用 `trae-cli plugin list` 确<details><summary><b>配置</b></summary>-凭据来源:默认使用当前激活的 `ovcli.conf`(`OPENVIKING_CLI_CONFIG_FILE` 或 `~/.openviking/ovcli.conf`),因此 `ov config switch <name>` 会在下次启动时同时影响 hook、MCP 代理和 Codex 内部运行的 `ov` 命令。只有明确希望环境变量覆盖 CLI 配置时,才设置 `OPENVIKING_CREDENTIAL_SOURCE=env`。若没有 ovcli 配置,则依次回退到环境变量、`ov.conf` 和内置默认值。+凭据来源:默认环境变量优先——只要设置了任一 `OPENVIKING_*` 凭据环境变量(`OPENVIKING_URL`/`OPENVIKING_BASE_URL`、`OPENVIKING_BEARER_TOKEN`/`OPENVIKING_API_KEY`、`OPENVIKING_ACCOUNT`、`OPENVIKING_USER`、`OPENVIKING_PEER_ID`),其取值就会覆盖当前激活的 `ovcli.conf`。只有在这些环境变量都未设置时,才由激活的 `ovcli.conf`(`OPENVIKING_CLI_CONFIG_FILE` 或 `~/.openviking/ovcli.conf`)统一驱动 hook、MCP 代理和 Codex 内部运行的 `ov` 命令,此时 `ov config switch <name>` 会在下次启动时生效。若希望在设置了凭据环境变量的情况下仍强制使用 ovcli 配置,可设置 `OPENVIKING_CREDENTIAL_SOURCE=cli`。两者都未覆盖的字段依次回退到 `ovcli.conf`、`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_CREDENTIAL_SOURCE` | `auto` | `auto` 下已设置的凭据环境变量优先;设为 `cli` 强制使用激活的 ovcli 配置,设为 `env` 强制使用环境变量 || `OPENVIKING_NO_AUTO_INJECT` | `false` | 关闭会话启动阶段的固定 profile/背景注入,但不关闭逐 prompt 语义召回 || `OPENVIKING_PROFILE_TOKEN_BUDGET` | `10000` | `profile.md` 及 `preferences/`、`entities/` 索引共用的 CJK-aware token 预算 || `OPENVIKING_CODEX_ACTIVE_WINDOW_MS` | `120000` | `SessionStart` 活动窗口阈值(毫秒) |@@ -93,10 +93,11 @@ TraeCode CLI 2.0 用户启动 `trae-cli`,并可用 `trae-cli plugin list` 确| MCP 工具调用报连接错误 | 服务器不可达或 URL 配置错误 | 执行 `curl "$(jq -r '.url' ~/.openviking/ovcli.conf)/health"` 检查服务器状态 || `4 hooks need review` | 首次启动需要进行安全审批 | 在 Codex 终端内输入 `/hooks` 完成审批 || `ov config switch` 后插件仍指向旧服务器 | 上个会话的代理进程仍在运行 | 重启 Codex;代理在启动时解析凭据 |-| Hook 与 MCP 指向不同服务器 | 某一侧设置了 `OPENVIKING_CREDENTIAL_SOURCE=env` 且环境变量过期 | 取消该设置(让 ovcli.conf 同时驱动两者),或保证环境变量一致 |+| Hook 与 MCP 指向不同服务器 | 某一侧残留了过期的 `OPENVIKING_*` 凭据环境变量(默认环境变量优先于 ovcli.conf) | 清除过期环境变量(让 ovcli.conf 同时驱动两者)、设置 `OPENVIKING_CREDENTIAL_SOURCE=cli`,或保证环境变量一致 |## 参见+- [集成能力参考](./16-capability-reference.md)- [博客:在 Claude Code / Codex 中接入 OpenViking](https://blog.openviking.ai/post/openviking-coding-agent/) — 为什么以及如何给你的 Coding Agent 加上长期记忆- [插件 README](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/README.md) — 完整的环境变量说明与架构图- [DESIGN.md](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/DESIGN.md) — 提交(commit)决策树diff --git a/docs/zh/agent-integrations/05-hermes.md b/docs/zh/agent-integrations/05-hermes.mdindex baab5046e..f40a96bb2 100644--- a/docs/zh/agent-integrations/05-hermes.md+++ b/docs/zh/agent-integrations/05-hermes.md@@ -29,6 +29,7 @@ hermes memory status## 参见+- [集成能力参考](./16-capability-reference.md)- [Hermes — OpenViking memory provider 文档](https://hermes-agent.nousresearch.com/docs/user-guide/features/memory-providers#openviking) — 完整配置指南- [部署指南](../guides/03-deployment.md) — 搭建 OpenViking 服务- [鉴权](../guides/04-authentication.md) — 远程访问的 API Key 设置diff --git a/docs/zh/agent-integrations/06-mcp-clients.md b/docs/zh/agent-integrations/06-mcp-clients.mdindex f022439f7..8d768991e 100644--- a/docs/zh/agent-integrations/06-mcp-clients.md+++ b/docs/zh/agent-integrations/06-mcp-clients.md@@ -86,6 +86,7 @@ HTTPS 配置、部署模板和完整授权流程详见 [OAuth 2.1 指南](../gui## 参见+- [集成能力参考](./16-capability-reference.md)- [MCP 集成指南](../guides/06-mcp-integration.md) — 工具参数、渐进式上传、`OPENVIKING_PUBLIC_BASE_URL`- [OAuth 2.1 指南](../guides/11-oauth.md) — 用于 Claude Desktop、Claude.ai、Cursor- [MCP 规范](https://modelcontextprotocol.io/)diff --git a/docs/zh/agent-integrations/07-langchain-langgraph.md b/docs/zh/agent-integrations/07-langchain-langgraph.mdindex ad0e2e81f..8c10ef821 100644--- a/docs/zh/agent-integrations/07-langchain-langgraph.md+++ b/docs/zh/agent-integrations/07-langchain-langgraph.md@@ -303,5 +303,6 @@ uv run --project integrations/langchain --extra langgraph python examples/langch## 参见+- [集成能力参考](./16-capability-reference.md)- [examples/langchain-langgraph/](https://github.com/volcengine/OpenViking/tree/main/examples/langchain-langgraph) — 上面所有示例的完整源码- [MCP 客户端](./06-mcp-clients.md) — 非 SDK 方式的 MCP 集成diff --git a/docs/zh/agent-integrations/08-community-plugins.md b/docs/zh/agent-integrations/08-community-plugins.mdindex beaa7dfb5..e2d3186ce 100644--- a/docs/zh/agent-integrations/08-community-plugins.md+++ b/docs/zh/agent-integrations/08-community-plugins.md@@ -76,3 +76,6 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shar[examples/](https://github.com/volcengine/OpenViking/tree/main/examples) 目录下还有 Agent 插件之外的部署与集成示例——Grafana 面板、Kubernetes Helm chart、多租户配置、快照流程和 SDK 片段等。+## 参见++- [集成能力参考](./16-capability-reference.md)diff --git a/docs/zh/agent-integrations/09-log-ingestion.md b/docs/zh/agent-integrations/09-log-ingestion.mdindex c90271ecf..21a945f10 100644--- a/docs/zh/agent-integrations/09-log-ingestion.md+++ b/docs/zh/agent-integrations/09-log-ingestion.md@@ -118,5 +118,6 @@ openviking-server ingest status## 参见+- [集成能力参考](./16-capability-reference.md)- [概览](./01-overview.md) — 各 harness 的记忆插件(实时捕获方案)- [部署指南 → CLI](../guides/03-deployment.md#cli) — `ov.conf` / 凭据配置diff --git a/docs/zh/agent-integrations/10-opencode.md b/docs/zh/agent-integrations/10-opencode.mdindex c39a023df..461bfb9ee 100644--- a/docs/zh/agent-integrations/10-opencode.md+++ b/docs/zh/agent-integrations/10-opencode.md@@ -133,11 +133,12 @@ API key 会由 hooks 和 MCP proxy 作为 `Authorization: Bearer ...` 发送;`## 验证-安装后重启 OpenCode。进入 OpenCode session 后,插件应暴露 `openviking` MCP server。OpenCode 会给 MCP 工具加 `openviking_` 前缀,例如:+安装后重启 OpenCode。进入 OpenCode session 后,插件应暴露 `openviking` MCP server,透传服务端完整 MCP 工具集(15 个工具)。OpenCode 会给 MCP 工具加 `openviking_` 前缀:-- `openviking_search`、`openviking_find`(`openviking_search` 的 `mode="context"` 替代原 recall 工具)-- `openviking_read`、`openviking_list`、`openviking_grep`、`openviking_glob`-- `openviking_remember`、`openviking_add_resource`、`openviking_forget`、`openviking_health`+- `openviking_find`、`openviking_search`(`openviking_search` 的 `mode="context"` 替代原 recall 工具)+- `openviking_read`、`openviking_list`、`openviking_tree`、`openviking_grep`、`openviking_glob`+- `openviking_remember`、`openviking_write`、`openviking_edit`、`openviking_add_resource`+- `openviking_list_watches`、`openviking_cancel_watch`、`openviking_forget`、`openviking_health`可以让 OpenCode 搜索或浏览 OpenViking memory。运行时状态和错误日志会写入:@@ -157,3 +158,7 @@ API key 会由 hooks 和 MCP proxy 作为 `Authorization: Bearer ...` 发送;`| 本地 `openviking_add_resource` 失败 | 传入文件路径而不是目录;目前还不支持自动上传本地目录 |完整 tools、配置字段和运行时文件说明见 [插件 README](https://github.com/volcengine/OpenViking/tree/main/examples/opencode-plugin)。++## 参见++- [集成能力参考](./16-capability-reference.md)diff --git a/docs/zh/agent-integrations/11-pi.md b/docs/zh/agent-integrations/11-pi.mdindex e569754d3..7dbcf0fa5 100644--- a/docs/zh/agent-integrations/11-pi.md+++ b/docs/zh/agent-integrations/11-pi.md@@ -44,6 +44,7 @@ git clone https://github.com/volcengine/OpenViking.gitcd OpenVikingmkdir -p ~/.pi/agent/extensionscp -r examples/pi-coding-agent-extension ~/.pi/agent/extensions/openviking+pi install ~/.pi/agent/extensions/openviking```## 配置@@ -94,3 +95,7 @@ Takeover 是 fail-open:如果 pending 写入无法 flush、commit 失败、arc| recall 为空 | 确认 server 中已有记忆,且 prompt 长度超过 `minQueryLength` |完整工具、配置与设计说明见 [扩展 README](https://github.com/volcengine/OpenViking/tree/main/examples/pi-coding-agent-extension)。++## 参见++- [集成能力参考](./16-capability-reference.md)diff --git a/docs/zh/agent-integrations/12-cursor.md b/docs/zh/agent-integrations/12-cursor.mdindex 1d941f6dd..cb0a6766c 100644--- a/docs/zh/agent-integrations/12-cursor.md+++ b/docs/zh/agent-integrations/12-cursor.md@@ -74,5 +74,6 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shar## 参见+- [集成能力参考](./16-capability-reference.md)- [鉴权](../guides/04-authentication.md)- [Cursor Hooks 文档](https://cursor.com/docs/hooks)diff --git a/docs/zh/agent-integrations/13-trae.md b/docs/zh/agent-integrations/13-trae.mdindex e63263b88..14b184651 100644--- a/docs/zh/agent-integrations/13-trae.md+++ b/docs/zh/agent-integrations/13-trae.md@@ -45,7 +45,7 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shar- `UserPromptSubmit`:根据当前问题召回并注入相关内容。- `PreToolUse`:阻止把 `viking://` 虚拟路径当作本地文件访问,并提示改用 OpenViking MCP 工具。- `Stop`:捕获本轮消息并立即提交,使短会话也能进入记忆抽取流程。-- OpenViking MCP Server:提供 `search`、`read`、`remember` 等主动记忆工具;`search` 的 `mode="context"` 可返回组装后的上下文。+- OpenViking MCP Server:透传服务端完整 MCP 工具集(15 个工具):`find`、`search`、`read`、`list`、`tree`、`remember`、`write`、`edit`、`add_resource`、`list_watches`、`cancel_watch`、`grep`、`glob`、`forget`、`health`。其中 `search` 的 `mode="context"` 可返回组装后的上下文。## 验证@@ -89,4 +89,5 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shar## 参见+- [集成能力参考](./16-capability-reference.md)- [鉴权](../guides/04-authentication.md)diff --git a/docs/zh/agent-integrations/14-openviking-helper.md b/docs/zh/agent-integrations/14-openviking-helper.mdindex b7b39b797..c583734d1 100644--- a/docs/zh/agent-integrations/14-openviking-helper.md+++ b/docs/zh/agent-integrations/14-openviking-helper.md@@ -58,6 +58,7 @@ Helper 会按 Agent 和项目展示本地 memory、rule 文件及 `SKILL.md` 技## 参见+- [集成能力参考](./16-capability-reference.md)- [Agent 集成概览](./01-overview.md)- [Claude Code 记忆插件](./02-claude-code.md)- [Codex 记忆插件](./04-codex.md)diff --git a/docs/zh/agent-integrations/15-agent-plugins.md b/docs/zh/agent-integrations/15-agent-plugins.mdindex 11f8f2783..f47b7ff67 100644--- a/docs/zh/agent-integrations/15-agent-plugins.md+++ b/docs/zh/agent-integrations/15-agent-plugins.md@@ -95,3 +95,7 @@ node --test agent-plugins/plugin.test.mjs`plugin.test.mjs` 会校验:清单的 schema URL 及两个清单的规范版本一致、插件 name 规则、清单根字段闭集、semver、每个 `skills/*` 子目录都有带 `name` + `description` frontmatter 且 `name` 与目录同名的 `SKILL.md`、`mcp.json` 引用的文件存在且不逃逸插件根目录,以及包内所有 `.mjs` 都能通过 `node --check`。`servers/shared/*.mjs` 是 `examples/memory-plugin-shared/lib` 的生成副本 —— 请改共享库后重新执行 `node examples/memory-plugin-shared/sync.mjs`;一旦漂移,`examples/memory-plugin-shared/sync.test.mjs` 会失败。两个测试文件都已接入 CI。++## 参见++- [集成能力参考](./16-capability-reference.md)diff --git a/docs/zh/agent-integrations/16-capability-reference.md b/docs/zh/agent-integrations/16-capability-reference.mdnew file mode 100644index 000000000..6b57de5a9--- /dev/null+++ b/docs/zh/agent-integrations/16-capability-reference.md@@ -0,0 +1,690 @@+# 集成能力参考++## 导读++| 你想知道 | 去哪里 |+|---|---|+| 特定 harness 下,agent 可主动调用的工具列表 | [§1.1](#_1-1-主动工具面-agentic-调用能力) 主动工具面 + [§2.1](#_2-1-服务端-mcp-工具面)(MCP 面)+ 各档案卡 |+| 不同关闭方式下,记忆归档的时机 | **[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵) 关闭方式 × harness 终局矩阵** |+| 自动召回是否携带 session_id 及其影响 | [§3.2.2](#_3-2-2-判定矩阵) / [§3.2.3](#_3-2-3-profile-开场注入) |+| 如何开启召回再摘要,以及服务端与客户端的职责划分 | [§3.2.5](#_3-2-5-召回再摘要) |+| `forget` 操作与删除功能的类型边界 | [§3.5](#_3-5-写入与删除的类型边界) |+| 特定环境变量在不同 harness 下的生效情况 | [§3.1.4](#_3-1-4-配置体系分层) 配置体系分层 + 各档案卡"配置" |+| 服务端是否具备自动 commit 兜底机制 | [§2.3](#_2-3-服务端会话与-commit-语义) |+| ov CLI 命令全集 | [§5](#_5-ov-cli-命令参考) |+| 自定义 agent 如何接入 OpenViking | [§6](#_6-自定义-agent-接入指南) |+| 某个集成怎么安装、怎么配、怎么排障 | 该集成的单独页面([§4](#_4-harness-档案卡) 各档案卡首行给出链接) |++---++# 1. 能力总览++## 1.1 主动工具面(Agentic 调用能力)++- **MCP 型 harness(claude-code、codex/trae-cli、cursor、trae/trae-cn、zcode、opencode)的主动工具面完全一致,共 15 个工具**:这些工具由服务端统一定义,插件通过代理获得 `~/.openviking/ovcli.conf` 配置后连接服务器定义的 MCP 工具。++- trae-cli 指 TraeCode CLI 2.0(仅支持 2.0),经 codex 插件别名安装,插件与 codex 格式兼容,下文矩阵并入 codex 行。++| harness | 工具面形态 | 工具数(默认开) | 搜 memory | 搜 resource | 搜 skill | 写 memory | 写 resource | 写 skill | 删除类型边界 |+|---|---|---|---|---|---|---|---|---|---|+| claude-code | MCP 透传 | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | 无类型区分² |+| codex / trae-cli | MCP 透传 | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | 无类型区分² |+| cursor | MCP 透传 | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | 无类型区分² |+| trae / trae-cn | MCP 透传 | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | 无类型区分² |+| zcode | MCP 透传 | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | 无类型区分² |+| opencode | MCP 透传(宿主加 `openviking_` 前缀) | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | 无类型区分² |+| dsh | 原生注册(7 个 `viking_*`) | 7(全开) | ✅ | ✅ | ✅ | ✅ `viking_remember` | ✅ `viking_add_resource`(仅 URL) | ❌ | 无类型区分;query 删除需 score>0.8³ |+| pi | 原生注册(7 个 `viking_*`) | 7(注册需前置检查⁴) | ✅ | ✅ | ✅ | ✅ `viking_remember` | ✅ `viking_add_resource`(仅 URL) | ❌ | 无类型区分;query 删除需 score>0.8³ |+| openclaw | 原生注册(15 个 `memory_*`/`ov_*` 等) | 15(默认开 14⁵) | ✅ `memory_recall` | ✅ `ov_search`(默认双 scope) | ✅ `ov_search` | ✅ `memory_store` | 默认关⁵ | ✅ `add_skill` | memory-only 白名单 + 单候选 score≥0.85 才自动删 |+| hermes | 原生注册(6 个 `viking_*`) | 6(provider 激活即全开) | ✅ | ✅ | ✅ | ✅ `viking_remember`(直写文件,不走抽取) | ✅ 多协议摄取(HTTP/Git/SSH/本地文件/目录 zip) | ❌ | memory-only + `.md` 叶子校验 |+| ov CLI | CLI 命令 | ~40 命令组 | ✅ `ov find` | ✅ `ov find` | ✅ `ov find` | ✅ `ov add-memory` | ✅ `ov add-resource` | ✅ `ov add-skill` | `ov rm` 直接执行(TUI 删除有确认 + root/scope 禁删) |++¹ MCP `write` 的可写域是 `viking://resources|user|agent`,暂不支持 MCP 新增 skill;新增 skill 的入口是 openclaw `add_skill`、`ov add-skill` 与 REST。+² MCP `forget` 不区分 memory/resource/skill 类型;存储层保留了命名空间根保护机制(裸 `viking://`、`viking://user`、`viking://agent` 根拒删),详见 [§3.5](#_3-5-写入与删除的类型边界)。+³ dsh/pi 的 `viking_forget`:其 `recursive` 参数固定为 false(不删除目录),按 query 删除要求匹配分 >0.8。+⁴ pi 工具注册前置:需未命中 bypassPatterns、`client.health()` 通过、`ensureSession` 成功(`index.ts:66-113`);health 未通过时本轮不注册工具面。+⁵ openclaw 的 `add_resource` 需经过双重 opt-in 后方可开启。++**skill 的增删边界**:新增入口包含 openclaw `add_skill`(默认开)、`ov add-skill` 与 REST;删除边界分四档,详见 [§3.5](#_3-5-写入与删除的类型边界)。++## 1.2 自动 hook 面(通过 Harness 自动实现)++| harness | 接入方式 | 自动召回 | 召回带 session_id | 再摘要(客户端)* | profile 注入 | 接管宿主压缩 | 离线补偿(pending queue) | statusline |+|---|---|---|---|---|---|---|---|---|+| claude-code | 9 hook + MCP 代理 + slash + statusline + skill | ✅ | ✅ | ✅ 本地 `claude -p` / 服务端 rewrite(默认 auto) | ✅(10000) | ❌(PreCompact 只 commit) | ✅ | ✅ |+| codex / trae-cli | 4 hook + MCP 代理 + skill | ✅ | ✅ | ✅ 本地 `codex exec`(默认开) | ✅(10000) | ❌ | ❌ 无磁盘队列(靠游标不推进、下一轮重发补偿) | ❌ |+| cursor | 7 hook + MCP 代理 + rule + skill | ✅ | ✅ | ❌ | ✅(6000) | ❌ | ✅ | ❌ |+| trae / trae-cn | 4 hook + MCP 代理 | ✅ | ✅ | ❌ | ✅(6000) | ❌ | ✅ | ❌ |+| zcode | 4 hook + MCP 代理 | ✅ | ✅ | ❌ | ✅(6000) | ❌ | ✅ | ❌ |+| opencode | 7 plugin hook + MCP 代理 | ✅ | ✅ | ❌ | ✅(10000)+ repo 列表进 system prompt | ❌(compacting 前后各 commit 一次) | ✅ | ❌(有 toast) |+| dsh | Cordis 原生插件(同进程) | ✅ | ✅ | ❌ | ✅(10000,每 session 一次) | ❌ | ✅ | ❌ |+| pi | 原生扩展(8 事件) | ✅ | ✅ | ❌ | ✅(10000,进 systemPrompt 每轮重拼) | ✅ **takeover**(默认开) | ✅ | ✅ |+| openclaw | context-engine 插件(`ownsCompaction:true`) | ✅ | ❌(走 `/find`,该接口无 session_id 字段) | ❌ | ❌ | ✅ **ContextEngine 全接管** | ❌ 失败轮次不重放 | ❌ |+| hermes | MemoryProvider 原生插件 | ✅ | 部分(仅 `search/search` 首选路径;降级 `/find` 不带) | ❌ | ❌(静态工具指引块) | ❌ | ✅ 进程内队列(不落盘) | ❌ |+| ov CLI | 一次性命令 | ❌(`ov find/search` 是显式命令) | —(`ov search --session-id` 为显式参数) | ❌ | ❌ | ❌ | ❌ | ❌ |++\* 此列指客户端是否内建了针对召回结果的本地压缩;服务端则在 context 检索面上,统一为所有调用方提供 digest 能力(`rewrite` 参数,[§3.2.5](#_3-2-5-召回再摘要))。++**session_id 携带现状**:除 openclaw(其调用的 `/find` 接口无该字段)与 hermes 的降级路径外,其余所有 harness 的自动召回均显式携带 session_id,并有跨插件回归测试钉死(`examples/memory-plugin-shared/recall-session-wiring.test.mjs:16-39`)。++## 1.3 形态分组++- **全家桶型**(hook 自动化 + MCP 工具面 + 周边 UX 齐全):claude-code、codex(trae-cli 经别名安装同属此档)。+- **瘦 hook 型**(共享 agent-hook-runtime,核心行为基本一致,差异仅体现在宿主事件与阈值上):cursor、trae/trae-cn、zcode。+- **plugin 事件型**:opencode(宿主事件面最丰富,dispose 覆盖关闭)。+- **同进程原生型**:dsh(Cordis)、pi(扩展 + takeover 压缩接管)、openclaw(context-engine 全接管)、hermes(MemoryProvider)。+- **工具型**:ov CLI(所有操作均为显式调用,不存在任何自动行为)。+- **非 coding**:Open WebUI(工具服务器)、LangChain(SDK 库)、Agent Plugins 便携包(MCP+skill 规范包)、通用 MCP 直连、log ingestion(日志反向导入)、Helper(桌面端)。++---++# 2. 公共能力核++per-harness 章节(档案卡)只写差异;所有共享事实均在本章一次性说明完毕。++## 2.1 服务端 MCP 工具面++这些工具定义在服务端,后续更新也会在服务端统一发布,Harness 只需通过插件代理 MCP 拿到最新的 `~/.openviking/ovcli.conf` 即可。++| # | 工具名 | 功能 | 参数要点(定义行号) |+|---|---|---|---|+| 1 | `find` | 不依赖会话上下文的快速语义检索 | `query, target_uri="", limit=10, min_score=0.35, level, context_type`(`:259`) |+| 2 | `search` | 深检索,可带 `session_id` + 意图分析 | `session_id` 仅在服务端 `retrieval.enable_intent`(默认 true)开启时才会加载会话(`:285`,`:302-304`) |+| 3 | `read` | 读取单个或多个 `viking://` 文件全文 | 并发信号量 10;单条失败返回 `(nothing found at <uri>)` 不抛错(`:389`) |+| 4 | `list` | 列目录(函数名 `ls`,注册名显式改写为 `list`) | `recursive=False`(`:423`) |+| 5 | `tree` | 递归目录树 | `level_limit=3, node_limit=1000, include_abstract=False`(`:449`) |+| 6 | `remember` | 写长期记忆 | 内部建一次性会话 `mcp-store-<uuid12>` 并立即 `commit_async`(`:504-523`)——这是 MCP 面唯一的 commit 入口;MCP 没有显式 commit 工具 |+| 7 | `write` | 写 `viking://` 文件 | `mode=replace\|append\|create`,replace 遇 NotFound 自动降级 create;新建文件扩展名白名单 `.md .txt .json .yaml .yml .toml .py .js .ts`;可写域 `resources/user/agent`;用户根下 `skills/ peers/ privacy/ sessions/` 只读;派生文件 `.abstract.md/.overview.md/.relations.json` 不可直写(`:529`;`content_write.py:60-81`) |+| 8 | `edit` | 精确字符串替换 | `old_string` 空/0 命中/多命中且非 replace_all 均报错,且文件内容不变(`:569`) |+| 9 | `add_resource` | 资源摄取(远程 URL / 本地文件签名上传 / Connector) | `watch_interval` 单位为分钟(0=不 watch);本地路径分支返回签名上传 URL(TTL 默认 600s),上传后自动入库,无需二次调用(`:723-947`) |+| 10 | `list_watches` | 列 watch 订阅,商业版尚未支持 | scheduler 未运行时返回错误串(`:958`) |+| 11 | `cancel_watch` | 按 `to_uri` 取消,商业版尚未支持 | 刻意不暴露 pause/resume/trigger/update(`:990`) |+| 12 | `grep` | 正则内容检索 | 多 pattern 并发(信号量 10),`node_limit=10`(`:1032`) |+| 13 | `glob` | 文件名 glob | `node_limit=100`(`:1084`) |+| 14 | `forget` | 删除 URI(不可恢复) | 默认 `recursive=False`;类型边界详见 [§3.5](#_3-5-写入与删除的类型边界)(`:1110-1117`) |+| 15 | `health` | 健康检查 | 无参(`:1123`) |++配套机制:++- **可移植 schema 重写**(`:1149-1218`):模块导入时把所有工具的 `anyOf`/`$ref` 折成扁平类型,以兼容 Gemini 等 OpenAPI 3.0 子集客户端;运行时校验仍用原始 Python 签名(例如 `read` 广播的 schema 是 array,但仍接受裸字符串)。所有 MCP 客户端拿到的 schema 都由服务端统一产出,客户端无差异。+- **身份中间件**(`:149-233`):与 REST 共用 `resolve_identity`,依次读 `x-api-key` / `authorization` / `x-openviking-account` / `x-openviking-user` / `x-openviking-actor-peer`;account/user 缺省回落 `"default"`。++## 2.2 memory-plugin-shared 共享层++`examples/memory-plugin-shared/lib/` 下共 18 个 `.mjs` 模块,是 JS 系 harness 的唯一事实源。两种消费形态:++1. **Vendoring(复制)**:由 `sync.mjs` 分发到 7 个目标,每个文件首行加 `// GENERATED FROM ... DO NOT EDIT.`(因此 vendored 副本行号 = lib 源行号 + 1,交叉读行号引用时要换算)。分发清单:claude-code / codex / opencode 各 16 个(HARNESS 13 + mcp-proxy-core + async-writer + batch-send);dsh / pi 各 13;zcode 全量 18 个;agent-plugins 4 个。当前 HEAD 各目标与 lib 源零漂移。+2. **相对路径直接 import(不复制)**:cursor / trae / trae-cn 直接 `import "../../memory-plugin-shared/lib/..."`;安装器把包与共享 lib 一起复制到 `~/.openviking/agent-integrations/{<client>,memory-plugin-shared}/`,使相对层级成立。运行期这个共享目录被这几个 harness 共用,任一重装都会整体覆盖。++核心模块速览(细节在各维度章展开):++| 模块 | 职责 | 消费方 |+|---|---|---|+| `recall-core.mjs` | 召回请求构造 + 三级降级 + 本地兜底排序注入 | 全部 JS 系 harness |+| `agent-hook-runtime.mjs` | "瘦 hook"一体化运行时(配置面 19 个 env、session id 派生、跨进程锁、fetch、commit) | cursor / trae / trae-cn / zcode |+| `mcp-proxy-core.mjs` | stdio↔streamable-HTTP MCP 代理内核 | 全部 MCP 型 + agent-plugins |+| `pending-queue.mjs` | 磁盘离线队列 + 会话启动重放 | cc / cursor / trae×2 / zcode / opencode / dsh / pi |+| `batch-send.mjs` | 100 条/批写入 + 404/405 逐条降级 + 连续前缀入队 | cc / codex / opencode + agent-hook 系 |+| `profile-inject.mjs` | session-start 的 profile + 可用记忆清单注入 | 9 个 harness(openclaw / hermes 除外) |+| `recall-compress-core.mjs` | 召回压缩 prompt + URI 编辑距离修复 + 缓存 | claude-code |+| `capture-utils.mjs` | 消息归一 + 注入回流防护 + 捕获过滤 | codex / opencode / dsh / pi |+| `credentials.mjs` | 凭据解析链(详见 [§3.1.3](#_3-1-3-凭据体系)) | 全部 JS 系 |+| `session-model.mjs` | 会话 id 前缀派生 + bypass glob | 全部 JS 系 |+| `async-writer.mjs` | 写路径 detach(drain stdin → spawn → approve → write → unref;spawn 失败回落同步) | cc / codex / zcode |+| `workspace-peer.mjs` | cwd → actor peer(非字母数字全替换成 `-`) | 全部 JS 系 |+| `uri-guard.mjs` / `agent-uri-guard.mjs` | 拦截 `viking://` 被误当成本地路径的情况 | 各 harness 的 PreToolUse/tool.execute.before 类 hook |+| `plugin-config.mjs` | ovcli.conf `plugin` 段读取 | claude-code / codex |+| `setup-wizard.mjs` | 交互式写 ovcli.conf | cc / codex / opencode / pi 暴露入口 |+| `retryable.mjs` | 可重试判定:status 0/408/429/≥500,或 409 且 `error.details.retryable===true`;4xx(含 401/403)不重试 | 全部 JS 系 |++## 2.3 服务端会话与 commit 语义++- **会话隐式创建**:插件普遍不显式调用 `POST /sessions`(dsh 例外,它会发一个只含 `session_id` 的 create);首次 `POST /sessions/{id}/messages(/batch)` 时由服务端 `auto_create=True` 建会话。召回侧 `mode="context"` 的 `_load_session(auto_create=True)` 也会建(第一次召回即在服务端创建会话)。+- **commit 两阶段**:`POST /sessions/{id}/commit` 的 Phase 1(归档 archive)同步完成后才返回,Phase 2(记忆抽取)作为后台任务返回 `task_id`。`keep_recent_count` 服务端默认 **0**(全量归档,不留 live tail)。+- **服务端自动 commit 默认关闭,且插件建会话的路径不会打开它**:+ - `memory.session_auto_commit.default_enabled = false`、`idle_enabled = false`(`memory_config.py:15-16`);无存储 policy 的会话自动 commit 关闭(`session_service.py:637-638`);idle 扫描器在 `idle_enabled=false` 时根本不创建(`core.py:440-448`),构成双重门控。+ - `POST /messages` 的 auto_create 不接受 policy 参数;只有 `POST /sessions`(create)与 `PATCH /sessions/{id}/config` 能设 `auto_commit_policy`。+ - 当前没有插件下发 `auto_commit_policy`;第一方客户端中会下发该字段的是 **ov CLI**(`ov session new --auto-commit-policy-json` / `--no-auto-commit`、`ov session config set`)。+ - policy 显式启用时,服务端默认阈值是 `pending_token_threshold=10000(严格大于)/ message_count_threshold=50 / idle_timeout_seconds=86400 / keep_recent_count=2 / min_commit_interval_seconds=0`。注意这组服务端默认值与各插件客户端的 20000/10 是相互独立的两层配置。+- **由此**:现状下所有自动 commit 都是客户端各自实现的阈值逻辑([§3.3](#_3-3-会话与-commit-生命周期)),服务端不做兜底;进程异常终止后遗留的 pending 消息,需在同一会话后续再触发 commit 才会归档与抽取。+- **tool output 外置**:服务端 `tool_output_externalization.enabled=True`、`threshold_chars=20000`(`server/config.py:257-258`)——客户端普遍把 `captureToolMaxChars` 设到 1000000 仅作兜底,真正的截断/外置在服务端做,externalized 结果通过 `tool_output_ref` 引用(openclaw 有三个专门工具读它)。+- **服务端召回相关熔断**:`retrieval.recall_intent_timeout_s=5.0`(query expansion)、`recall_rewrite_timeout_s=30.0`(digest,[§3.2.5](#_3-2-5-召回再摘要))、`enable_intent=true`。客户端超时预算按这两条推导([§3.2.4](#_3-2-4-超时与预算链))。++---++# 3. 维度详解++## 3.1 接入形态、安装与配置体系++### 3.1.1 判定矩阵++| harness | 集成形态 | 安装通道 | 会话 id 前缀/格式 | 配置来源 | 独立 setup 向导 |+|---|---|---|---|---|---|+| claude-code | CC 插件(marketplace):包含 9 hook + MCP 代理 + slash + statusline + skill | 一键 `install.sh --harness claude`(支持现代 plugin 路径与 legacy `claude mcp add` 兼容路径)/ 手动 marketplace / TOS 镜像 | `cc-<CC session_id 原文>`;subagent 格式为 `…__subagent-<agent_id>` | env + ovcli.conf `plugin.claude_code` + ov.conf `claude_code` | ✅ `scripts/setup.mjs` |+| codex | Codex 插件(marketplace):包含 4 hook + MCP 代理 + skill | 一键 `--harness codex` / `codex plugin marketplace add`(TOS 走 dumb-HTTP git 以保留远程更新能力) | `cx-<safeId>`(确定性推导,不读取 state) | env + ovcli.conf `plugin.codex` + ov.conf `codex` | ✅ |+| trae-cli | **codex 插件别名安装**(TraeCode CLI 2.0,仅支持 2.0;Codex 系:binary `traecli`、配置 `~/.trae/traecli.toml`;能力面与 codex 一致) | 一键 `--harness trae-cli`(复用 codex 安装流程;marketplace 命令会随指向的 binary 执行,如 `traecli plugin marketplace add`) | 与 codex 的派生规则一致 | 与 codex 一致(env + ovcli.conf `plugin.codex` + ov.conf) | ✅(同 codex) |+| cursor | 配置驱动(写入 `~/.cursor/hooks.json`+`mcp.json`)+ rule + skill | 一键 `--harness cursor` | `cu-<conversation_id>` | 仅 env | ❌(共用安装器 TUI) |+| trae / trae-cn | 配置驱动(`~/.trae{,-cn}/hooks.json` + 平台相关 mcp.json) | 一键 `--harness trae,trae-cn` | `tr-` / `trcn-` | 仅 env | ❌ |+| zcode | 配置驱动(合并进 `~/.zcode/cli/config.json`,并强制 `hooks.enabled=true`) | 一键 `--harness zcode` | `zc-<sess_…>` | 仅 env | ❌ |+| opencode | npm 插件 `@openviking/opencode-plugin`(config hook 自注入 MCP 条目) | 一键 `--harness opencode`(npm 注册 + 代理快照兜底)/ 手动 npm / 源码 | `oc-<id>`;subagent 格式为 `oc-<parent>__subagent-<child>` | `openviking-config.json`(4 级搜索)+ env | ✅ |+| dsh | Cordis 同进程插件(`cordis.patch.yml` plugin group) | 执行 `dsh plugin add ./examples/dsh-memory-plugin`(统一安装器暂不覆盖 dsh) | `dsh-<session.id 原样>`;subagent 各自独立会话 | cordis patch config + 4 个 env(凭据优先级 patch>env,行为开关优先级 env>patch) | ❌ |+| pi | pi 原生扩展(目录装载,jiti 直译 TS) | 一键 `--harness pi`(含 `pi install` 注册) | `pi-<piSessionId>` | `config.json`(凭据字段由凭据链统一解析)+ env | ✅ |+| openclaw | context-engine 插件(`ownsCompaction:true`)+ 15 工具 + 5 slash + 4 hook + HTTP 路由 | ClawHub 执行 `openclaw plugins install clawhub:@openviking/openclaw-plugin` 搭配 `openclaw openviking setup` / npm 安装器 / TOS 离线包 | UUID 原样小写,否则 `sha256(sessionKey)`;`memory_store` 临时会话 `memory-store-<ts>-<rand>` | `openclaw.json` 的 `plugins.entries.openviking.config`(严格校验:存在未知键/非法值时插件进入 setup-only 模式)+ 少量 env | ✅ `openclaw openviking setup`(交互/非交互 + key 角色探测 + 版本兼容检查) |+| hermes | Hermes bundled MemoryProvider(随 Hermes 发布,无需装插件) | 执行 `hermes memory setup openviking`(curses 向导)或手动 `config set memory.provider openviking` + `.env` | 由 Hermes 生成 `%Y%m%d_%H%M%S_<hex6>`,插件原样使用 | `.env`(`OPENVIKING_*`)或 ovcli.conf 联动(`use_ovcli_config` 模式会清空 .env 里的 5 个对应变量)+ config.yaml | ✅(多层菜单) |+| ov CLI | Rust 原生二进制 | npm `@openviking/cli` / `uv tool install openviking` / cargo / GitHub Releases | 无自有会话(`ov chat` 默认使用 machine-uid) | `ovcli.conf`(多 profile)+ 少量 env | ✅ `ov config`(TUI 向导) |++### 3.1.2 统一安装器++统一安装脚本 `examples/memory-plugin-shared/install.sh`(3253 行)覆盖 9 个 harness id:`claude, codex, cursor, trae, trae-cn, trae-cli, zcode, opencode, pi`(其中 dsh 与 openclaw 走各自渠道;`trae-cli` 则复用 codex 安装流程,[§3.1.1](#_3-1-1-判定矩阵))。要点如下:++- 双分发:`--dist github|tos`;三源:`--source remote|archive|dev`。以 `bash <(curl …)` 方式执行时会从 `/dev/tty` 读取输入,从而保留交互。+- 官方 docs 的规范一键命令是不带 `--harness` 的裸命令(执行后进入 TUI 多选);而各插件自带的 setup-helper 转发脚本在调用时会自动补 `--harness`。+- 幂等合并:hooks/mcp 条目按 `OPENVIKING_INTEGRATION_ID` 标记识别自有条目,做到剔旧追新的同时不动第三方;写入采用原子操作——先备份 `.bak`,写 tmp 后 rename 覆盖,权限 0600。+- 凭据向导写 `~/.openviking/ovcli.conf`:三选一(本地 `http://127.0.0.1:1933` / 火山云 `https://api.vikingdb.cn-beijing.volces.com/openviking` / 自定义),已有配置先展示当前值再问"沿用/重配",API key 掩码。+- 卸载:`--uninstall` 覆盖 cursor / trae / trae-cn / zcode,并顺带清理 trae-cli 遗留的旧 hook 配置;claude / codex / trae-cli / opencode / pi 这些 Codex 格式或宿主托管的插件,通过各自宿主的插件管理卸载。+- 安装后自检:grep 配置 + `node --check` + 一次 `OPENVIKING_MEMORY_ENABLED=0` 的 smoke run。+- Node 门槛:安装器检查 18+。++### 3.1.3 凭据体系++代码中并存着四套并行的凭据解析体系,env 变量名与认证头各不相同,排障时先分清对象:++| 家族 | 消费者 | URL env | Key env | 身份 env | 认证头 |+|---|---|---|---|---|---|+| **A. JS 共享核**(`credentials.mjs`) | claude-code / codex(含 trae-cli)/ cursor / trae×2 / zcode / opencode / pi / dsh / agent-plugins | `OPENVIKING_URL` → `OPENVIKING_BASE_URL` | `OPENVIKING_BEARER_TOKEN` → `OPENVIKING_API_KEY` | `OPENVIKING_ACCOUNT` / `OPENVIKING_USER` / `OPENVIKING_PEER_ID` | `Authorization: Bearer`;注意 codex 的 4 个 hook 脚本会额外发送 `X-API-Key` 兼容头 |+| **B. openclaw**(自有 `config.ts`) | openclaw | `OPENVIKING_BASE_URL` → `OPENVIKING_URL` | `OPENVIKING_API_KEY`(支持 SecretRef env/file) | `OPENVIKING_ACCOUNT_ID` / `OPENVIKING_USER_ID`(注意此处带 `_ID`) | `X-API-Key`(指向 OV Cloud 时注意其实际采用 Bearer 认证) |+| **C. hermes**(Python) | hermes | `OPENVIKING_ENDPOINT` | `OPENVIKING_API_KEY` | `OPENVIKING_ACCOUNT` / `OPENVIKING_USER` / `OPENVIKING_AGENT`(=actor peer) | `X-API-Key` + `Bearer` 双发;有 key 时默认不发租户头(被服务端以 trusted 报错拒绝时会自动补头重试一次) |+| **D. ov CLI**(Rust) | ov | conf 文件为主 | conf | `--account/--user/--actor-peer-id` | `X-API-Key`;LDAP Basic / OIDC Bearer 按 `auth_mode` 切换;api_key 含 ≥2 个 `.` 时自动附加 Bearer(JWT 兜底) |++家族 A 的解析链如下(其余家族见档案卡):++1. 模式由 `OPENVIKING_CREDENTIAL_SOURCE`(别名 `_CREDENTIALS_SOURCE`)控制,取值 ∈ `env|cli|auto`(默认 auto)。+2. **auto 语义是 env 优先**:只要任一 env 凭据字段存在,整体就走 env;只有 env 全空、且 ovcli.conf 存在并含凭据字段时,才整体切换到文件(此时 key/account/user/peer 全部只从文件取)。+3. baseUrl:env → ovcli `url` → ov.conf `server.url` → `http://{server.host|127.0.0.1}:{server.port|1933}`(其中 `0.0.0.0` 归一为 `127.0.0.1`);兜底 `http://127.0.0.1:1933`。+4. apiKey:`BEARER_TOKEN` → `API_KEY` → ovcli `api_key` → ov.conf `codex.apiKey` → `server.root_api_key`。+5. mcpUrl:`OPENVIKING_MCP_URL`(非 cli 模式)→ `${baseUrl}/mcp`。+6. 统一请求头:`Authorization: Bearer` + `X-OpenViking-Account/User/Actor-Peer` + `User-Agent: openviking-memory-<harness>/<version>`。++**workspace peer**(家族 A 全体 + agent-plugins):无显式 peerId 且 `OPENVIKING_WORKSPACE_PEER≠0` 时用 cwd 派生——把路径中所有非字母数字字符替换成 `-`(`/Users/x/Dev/OpenViking` → `-Users-x-Dev-OpenViking`),该值随 `X-OpenViking-Actor-Peer` 发送;服务端会对该头校验,含 `/` 或 `\` 返回 400。openclaw 的 peer 由 `peer_role`/`peer_prefix` 推导(`peer_role=person` 时需保证 sender 信息可用,否则工具调用报错);hermes 的 peer 就是 `OPENVIKING_AGENT`(默认 `hermes`)。++### 3.1.4 配置体系分层++| 配置层 | 生效范围 | 备注 |+|---|---|---|+| env `OPENVIKING_*` | 各家族见上;行为旋钮见各档案卡 | 唯一横跨所有 JS 系的层 |+| ovcli.conf `plugin` 段(`plugin.claude_code` / `plugin.codex` / 共享标量) | claude-code / codex | 其余 harness 名下的 `plugin.<x>` 条目不参与解析。注意:`ov config add/edit` 会以 Rust Config 结构重写整个文件,从而丢弃其不识别的 `plugin` 段;而 `ov config switch` 为字节复制,不受影响 |+| ov.conf harness 段(`claude_code.*` / `codex.*`) | claude-code / codex(legacy 回落) | |+| harness 自有配置文件 | opencode `openviking-config.json`、pi `config.json`、dsh cordis patch、openclaw `openclaw.json`、hermes `config.yaml`+`.env` | |++**配置项生效范围速查**(这些旋钮只在列出的 harness 上生效):++- `OPENVIKING_COMMIT_TURN_THRESHOLD`:仅 cursor(trae×2/zcode 每 Stop 必 commit,不走该阈值)。+- `OPENVIKING_WRITE_PATH_ASYNC`:claude-code / codex / zcode。+- 召回再摘要相关(`OPENVIKING_RECALL_COMPRESS` / `OPENVIKING_RECALL_REWRITE` 及配套项):claude-code / codex(服务端 `rewrite` 参数本身对所有调用方可用,[§3.2.5](#_3-2-5-召回再摘要))。+- `OPENVIKING_RECALL_DEDUP_TURNS`、`OPENVIKING_RECALL_QUERY_EXPANSION`:claude-code / codex。+- ovcli.conf `plugin` 段:claude-code / codex。++## 3.2 自动召回与注入++### 3.2.1 机制底座:一条共享管线,两条服务端路径++JS 系 harness 的召回逻辑均由 `recall-core.mjs` 中的三级降级链处理:++1. **context face**:调用 `POST /api/v1/search/search`,参数设定为 `mode:"context"` 且 `purpose:"coding"`。其核心设计原则为"只声明意图,机制交服务端":对于 `quotas`/`max_tokens`/`query_expansion`/`rewrite_max_bullets` 等参数,仅在用户显式配置时(带有 configured 哨兵字段)才会发送,否则直接采用服务端的默认设定。+2. **legacy `/recall`**:若 context face 请求返回 400/422 错误,且响应报文包含 `extra`/`mode`/`unexpected` 等特征字段,则判定对接了旧版服务端。此时会在本地写入 6 小时的负缓存(路径为 `~/.openviking/state/context-face.json`,该文件全机共享,一旦被任一 harness 标记,同机所有 JS 系 harness 均会跳过 context face 阶段)。随后降级调用已弃用的 `/api/v1/search/recall` 接口;若 `peer_scope` 被拒,则去掉该参数重试一次。+3. **raw find 兜底**:并发请求 `viking://user/memories` 与 `viking://user/skills`,调用两次 `POST /search/find`(注意:resources 被刻意排除在自动召回之外,资源类文档由模型主动调用 `search` 获取)。客户端收到结果后进行本地重排(权重规则为:leaf +0.12 / 时间意图 +0.10 / 偏好意图 +0.08 / 词面重叠 ≤0.2)、去重,最后按客户端 token 预算装填。`recallTokenBudget`、`recallMaxContentChars` 与 `recallPreferAbstract` 三个旋钮只在这一级生效;而在 context face 下,注入预算由服务端 `max_tokens`(默认 1600)决定。++服务端在处理 session_id 时,分为两条截然不同的执行路径:++- **路径 A:`mode="context"`**(适用于 context face 与 `/recall` preset)。此路径负责 query expansion 与跨轮去重台账。expansion 设有三重闸门:`retrieval.enable_intent` 需开启(默认 true) → 会话必须已物化(即 `messages.jsonl` 文件存在) → `latest_archive_overview` 或 `current_messages` 不能为空。扩写后原 query 永远排第一,追加的 planned queries 上限为 3。台账(`.recall_log.json`)按 `dedup_turns` 冷却已发正文的 URI;若"当轮只发了 URI 没发正文",该记录则不参与冷却;digest 判定 no_relevant 时亦不记账。+- **路径 B:`mode="list"`**(不写 mode 时的默认行为)。此路径下,IntentAnalyzer 会整体替换 typed_queries(原 query 不保证保留),无台账、无原-query 保底。实际落在这条路径上的调用方包括:codex 的第二级降级 `searchScope`、hermes 的 `viking_search(mode="deep")` 以及 prefetch 的首选路径。尽管它们带了 session_id,但拿不到 context 面的 expansion 与去重机制。++**`dedup_turns` 的三点说明**:① 服务端 context 面的默认值是 **0**,常见的"5"实则源自客户端 `recall-core.mjs` 兜底与 `/recall` preset(后者仅当带 session_id)——不经共享库直接打 API 的第三方即使带了 session_id,也要显式发 `dedup_turns` 才有跨轮去重;② "turn"的计数单位是消息条数而非对话轮(`_resolve_turn` 用 `total_message_count`),对同时推 user+assistant 的 harness,默认 5 ≈ 1-2 个真实对话轮;③ 注意:`autoCapture=0` 且 `autoRecall=1` 时消息数恒 0 → 台账时钟不走 → 已发过正文的 URI 在本会话内持续冷却;可用 `OPENVIKING_RECALL_DEDUP_TURNS=0` 关闭去重(claude-code / codex)。++### 3.2.2 判定矩阵++| harness | 触发点 | query 构造 | session_id | 服务端路径 | 注入格式 / 位置 | 再摘要(客户端)* |+|---|---|---|---|---|---|---|+| claude-code | 每轮 `UserPromptSubmit` | prompt 原文 trim | ✅ `cc-` | A(context face) | `<openviking-context>` → `hookSpecificOutput.additionalContext` | ✅ 本地/服务端(默认 auto,[§3.2.5](#_3-2-5-召回再摘要)) |+| codex / trae-cli | 每轮 `UserPromptSubmit`(整 hook 120s 硬截止) | prompt 原文 | ✅ `cx-`(确定性推导,不读 state) | A;二级降级 searchScope 落入 B | `<openviking-context source="auto-recall" format="digest">` | ✅ 本地 `codex exec`([§3.2.5](#_3-2-5-召回再摘要)) |+| cursor | `beforeSubmitPrompt` | prompt 原文;基于事件 id 与 500ms 窗口去重,同 promptHash 复用缓存块 | ✅ `cu-` | A | `additional_context` | ❌ |+| trae / trae-cn | `UserPromptSubmit` | 剥离历史注入块后的 prompt(只认 `input.prompt`) | ✅ `tr-`/`trcn-` | A | `additionalContext` | ❌ |+| zcode | `UserPromptSubmit` | 剥离三类注入块(含 `<system-reminder>`) | ✅ `zc-` | A | `additionalContext`(严格 JSON) | ❌ |+| opencode | 每条 `chat.message` 中的 user 消息 | 拼接非 synthetic text part;若正文已含 `<openviking-context` 则跳过本轮召回 | ✅ `oc-` | A(timeoutMs=30000) | 合成 synthetic part 并 `unshift` 到 parts 最前 | ❌ |+| dsh | `agent/pre-step` waterfall(先 await next 再 append) | claimed batch 全部消息(过滤自身注入的内容) | ✅ `dsh-` | A | 借由 `createUserMessage` append 到 `decision.messages` 尾部(source: plugin/openviking-memory) | ❌ |+| pi | `before_agent_start` 阶段排队;在 `context` 事件内检索(当前轮 prompt 拿当前轮记忆) | prompt 原文 | ✅ `pi-`(会话未建立时不带) | A | 前置到最后一条真实 user 消息(通过 `<openviking-context` 幂等检测) | ❌ |+| openclaw | context-engine transformContext assemble(设有 7 道 passthrough 门) | 最后一条 user 消息纯 text,清洗后截 4000 字符 | ❌(`/find` 无该字段) | `/find` | 以 `<relevant-memories>` + `Source: openviking-auto-recall` 格式前置进最后一条 user 消息 | ❌ |+| hermes | 每轮 API 调用前同步执行 `prefetch` | 原始用户输入,双层剥 skill 脚手架;<5 字符跳过 | 部分携带(仅 `search/search` 首选路径,落 B;降级 `/find` 时不带) | B / find | `<memory-context>` fenced 块追加到当轮 user 消息(只进 API 请求体,不写回持久化) | ❌ |++\* 同 [§1.2](#_1-2-自动-hook-面-通过-harness-自动实现):此列的"再摘要"特指客户端本地压缩,而服务端 digest 对所有调用方均可用([§3.2.5](#_3-2-5-召回再摘要))。ov CLI 无自动召回,不在本表。++### 3.2.3 profile / 开场注入++- **实现**:`profile-inject.mjs`——读 `viking://user/<space>/memories/profile.md` 全文 + `preferences/`、`entities/` 递归清单(abs_limit=512)。预算估算引入 CJK 感知(≥U+3000 记 1.5 token/字,其余 chars/4);profile 占一半预算,超限则采用"头 8 行 + 尾部"的中段省略;清单超限则追加 `... +N more` 提示。+- **谁注入、何时、预算**:claude-code(SessionStart 全部 source,10000);codex(SessionStart startup/clear/resume,10000);cursor/trae×2/zcode(SessionStart,6000,2s 去抖);opencode(每会话首条 chat.message 一次,10000,进程内 Set 去重,subagent 会话跳过;注意开场注入每会话只尝试一次,失败后本进程内不重试);dsh(每 session 投一次 `profileDelivered`,10000;compaction 之后不重投);pi(进 systemPrompt,每个 prompt 重拼,10000 常驻)。openclaw、hermes 无 profile 注入。+- **archive 注入**(resume 场景把上次归档摘要拉回来):claude-code(source=resume/compact,`token_budget=32000`,≤5 条 pre_archive_abstracts);codex(resume 且本地 ovSessionId 已清时,32000/截 6000 字符);opencode(开场注入 B 部分,32000);pi 非 takeover 模式(32000)。+- **repo 上下文注入**:opencode 独有——通过 `experimental.chat.system.transform` 把已索引仓库列表放进 system prompt。++### 3.2.4 超时与预算链++- 家族 A 客户端推导:带 rewrite → `max(timeoutMs, 45000)`;带 expansion → `max(timeoutMs, 15000)`;对应服务端熔断 5s(expansion)/30s(rewrite)——设计上让客户端预算覆盖服务端各阶段,防止客户端提前 abort 丢掉整个响应。+- 实际值:cc 15s(hook 预算 60s);codex 召回整 hook 120s 硬截止 + 压缩子进程 110s;cursor/trae×2/zcode 15s(宿主 hook 预算 20s);opencode 30s;dsh 15s(阻塞 pre-step);pi 15s;openclaw 整个召回流程外层 5s 硬超时(500ms health precheck;默认 `recallPreferAbstract=false` 时每条 leaf 记忆多一次 read,预算内最多 1 find + 6 read + 1 health);hermes 总预算 4s / 单请求 3s(可配)。+- 注入体预算:服务端 `max_tokens` 默认 1600(家族 A 默认不发、由服务端决定);openclaw / hermes 用字符预算 4000(两家都是"装不下整条跳过"而非截断)。++### 3.2.5 召回再摘要++**服务端实现(对所有调用方可用)**:context 检索面(涵盖 REST 的 `mode="context"` 与 legacy 的 `/recall`)支持传入 `rewrite` 参数——可选值为 `false | true | "auto"`,默认为 `false`;并配套提供 `rewrite_max_bullets`(默认 6,1-20)。开启后,服务端会用 `query_planner` 模型(`rewrite=true` 时未配置则回落主 `vlm`;`"auto"` 仅在显式配置了 `query_planner` 时生效)把召回结果改写成带引用的 digest:`OpenViking memory digest:` 头 + `- ` bullets,每条 ≤500 字符且必须引用一条本次命中的 `viking://` URI(无引用或引用越界的 bullet 被丢弃);判定无相关记忆时输出哨兵并清空注入块(该轮不记入去重台账)。模型调用受 `retrieval.recall_rewrite_timeout_s=30s` 熔断,超时回落未改写的 rendered 块(`rewrite.py:78-141`、`pipeline.py:122-130`、`search.py:195-196`)。++**客户端侧现状**:++- **claude-code**:`recallRewrite` 四态 `off|client|server|auto`,默认 **auto**——先探测本地压缩器是否可用(`claude --version` 探测,缓存 7 天),若可用则在本地起 `claude -p --model sonnet --effort low --strict-mcp-config` 子进程压缩(30s 超时,输入 <1500 字不压缩,digest 单条缓存;子进程环境强制降级防递归;失败回落未压缩块;URI 编辑距离吸附回真实 URI,修不回的整条丢弃)。若本地不可用,则下发 `rewrite:"auto"` 交服务端。这是唯一接入服务端 rewrite 的 harness。+- **codex**:布尔 `recallCompress` 默认 **true**,完全依赖本地压缩(不使用服务端 rewrite):模型 profile 从 `~/.codex/models_cache.json` 读,候选 `gpt-5.3-codex-spark` → `gpt-5.6-luna`,缓存 7 天;命令 `codex --sandbox read-only --ask-for-approval never exec --ephemeral --ignore-user-config --skip-git-repo-check --output-last-message <tmp> -`,超时 110s;运行期失败后同一会话内跳过压缩、下次 SessionStart 自愈重测;输出规范化截 4000 字符;压缩关闭或失败时用确定性 `fallbackDigest` 兜底。+- **其余 harness**:均不发送 `rewrite`、无本地压缩,而是直接注入服务端返回的原始召回块。直连 API 的第三方可自行传 `rewrite` 获得服务端 digest。++### 3.2.6 注入回流防护++为防止注入内容被二次捕获,注入时会加确定性包装(`<openviking-context>` 等),捕获时再机械剥离:capture-utils 的 `sanitizeCapturedText` 剥注入块、digest 块、元数据围栏与时间戳前缀。各端的特殊处理包括:trae/zcode 用各自的 clean 函数(其中 zcode 剥三类注入块);openclaw 在 afterTurn 写回与下轮 query 构造时各剥一次 `<relevant-memories>`;hermes 则更彻底,直接把三个召回类工具的 tool_call/result 从 sync batch 里整条剔除(写类工具保留)。++## 3.3 会话与 commit 生命周期++### 3.3.1 机制底座++- **写入路径**:JS 系统一通过 `batch-send.mjs` 处理(对应接口 `POST /messages/batch`,每批最多 100 条,与服务端的 `max_length=100` 限制保持一致;若遇 404/405 错误则降级为逐条发送)。增量游标由各家自行实现(cc 按 transcript turn 序号计算,codex 机制相同;cursor 采用 `sha256(index+role+content)`;zcode 基于 rollout 的 `turn_id`;opencode 依赖事件流 Map;dsh 基于事件白名单;pi 依据 branch 条目水位;hermes 则按当前轮切片)。+- **commit 是客户端触发的**(详见 [§2.3](#_2-3-服务端会话与-commit-语义)):服务端默认不自动 commit。下表所有的"阈值/触发"条件,均指客户端逻辑。+- **keep_recent_count 差异**(即 commit 后给宿主留多少 live tail):服务端默认值为 0。各家传参如下:cc/codex 阈值提交传 10;cursor、trae×2、zcode 发空 body `{}`,即传 0(每次均为全量归档);opencode 传 10;dsh 传 10;pi 在非 takeover 模式传 10,takeover 模式传 3(本地含义是"保留 3 个用户轮",而服务端按消息条数解释,实际保留更少);openclaw 在 afterTurn 阈值触发时传 10,在 compact/reset/memory_store 操作时传 0;hermes 恒定传 0。+- **写路径 detach**(`async-writer.mjs`,cc/codex/zcode 的 Stop 默认开):drain stdin → spawn detached worker → approve → write payload → unref(注:spawn 失败时尚未 approve,回落同步恰好只输出一次)。detached worker 自成进程组,不受终端信号波及——这是保证 cc 在关闭链路时具有高可靠性、zcode 在按下 Ctrl+C 时不丢失写入数据的关键机制。附带效果:执行 detach 后,Stop 的 `appended N turn(s)` 提示将不再展示(设置 `OPENVIKING_WRITE_PATH_ASYNC=0` 可恢复该提示)。++### 3.3.2 常规 commit 触发条件++| harness | 轮内阈值触发 | 显式/边界触发 | 压缩触发 |+|---|---|---|---|+| claude-code | Stop:`pending_tokens ≥ 20000`(读服务端值),keep 10 | SessionEnd:无条件触发;SubagentStop:无条件触发(无阈值);SessionStart:重放 pending | PreCompact:无条件触发(同步执行,不 detach) |+| codex / trae-cli | Stop:同上,20000 / keep 10 | SessionStart(startup\|clear):基于 active-window 的启发式(2min 内恰好 1 个 state → commit;≥2 个则跳过) + idle-TTL 扫描(>30min 一律 commit 并清理) | PreCompact:全量 commit(发空 body `{}`),随后置 `ovSessionId=null` |+| cursor | stop:`capturedSinceCommit ≥ 8`(按消息条数计算,≈4 轮问答;纯客户端计数),keep 0 | sessionEnd:已注册该事件(但实践中不触达,见 [§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵)) | preCompact:无条件触发 |+| trae / trae-cn | 每个有内容的 Stop 都 commit(无阈值),keep 0 | — | 无(上游无 PreCompact 事件) |+| zcode | 同 trae(每 Stop 都 commit,keep 0;rollout 增量游标保守推进,若有漏掉的轮次,将在同会话的下个 Stop 补齐) | — | 无(上游无 PreCompact 事件) |+| opencode | `session.idle` 路径:flush 执行后,需满足 `pending_tokens ≥ 20000` 才 commit,keep 10 | `session.deleted` / `session.error`:强制 commit;dispose:强制 commit | 在 `experimental.session.compacting` 前与 `session.compacted` 后各触发一次(即一次宿主压缩 = 两次 commit) |+| dsh | `turn/end`:`pending_tokens ≥ 20000`(30s 超时),keep 10 | teardown(见 [§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵)) | 无(不监听 compaction 事件) |+| pi(takeover 默认开) | `onTurnSynced`:本地估算 `pendingTokens ≥ 30000` 且 `lastSeenUserTurns > 3` 时,执行 commitAndAdvance(keep 3;overview 15×2s 轮询,拿不到则边界不推进,但 pendingTokens 会清零,重新累计后重试) | 手动执行 `/viking commit` | `session_before_compact`(需 `firstKeptEntryId` 非空) |+| pi(takeover off) | syncBranch 执行后:服务端 `pending_tokens ≥ 20000`,keep 10 | `session_shutdown`:无条件 commit;手动执行 `/viking commit` | `session_before_compact`:无条件 commit |+| openclaw | afterTurn:`pending_tokens ≥ floor(tokenBudget × 0.5)`(ratio 默认 0.5,tokenBudget 缺省 128000,即阈值 ~64000),wait=false,keep 10 | `before_reset`(执行 `/new` `/reset`):wait=true,keep 0;`memory_store` 工具:wait=true,keep 0 | `compact()`:wait=true,keep 0(Phase2 轮询上限 5 分钟) |+| hermes | 无阈值 commit——触发面全是会话边界:`on_session_end`(drain 10s,drain 不净则本次不 commit)、`on_session_switch`(涉及 `/new`、`/resume`、`/branch` 或压缩 fork,异步 drain 预算 65s)、gateway 缓存驱逐;`/undo` 与原地压缩不 commit。用幂等集合防二次 commit;keep 0 | atexit 兜底 | fork 型压缩边界 commit;原地压缩不 commit |+| ov CLI | 无 | `ov session commit`;`ov add-memory` 第三步固定 commit | — |+| ingest | `pending ≥ 6000` 或 idle 5s,keep 0;backfill 在每个会话结束时执行 `commit_if_needed` | 退出时执行 `_flush_all()` | — |+| LangChain | `CommitPolicy.mode` 默认 `never`;`pending_tokens` 模式阈值为 8000;`always` 模式每次 record 均触发 | 调用方自理 | — |++### 3.3.3 关闭方式 × harness 终局矩阵++图例:**C** = 会 commit;**C\*** = 会 commit 但有前提(见注);**—** = 不 commit(已 POST 的消息仍留在服务端 live 区:不丢消息本体,等待后续触发归档与抽取);**n/a** = 无此形态。所有行的服务端侧行为一律为 **—**([§2.3](#_2-3-服务端会话与-commit-语义))。++| harness | 正常退出 | Ctrl+C | SIGTERM | SIGHUP/关终端/关窗口·tab | kill -9/崩溃 | 补救路径 |+|---|---|---|---|---|---|---|+| claude-code | **C**(SessionEnd → detach 子进程 commit,用户不等待) | **C** | **C** | **C**(detached worker 自成进程组,不受 SIGHUP 波及) | **—** | 下次 Stop 越阈值 / `/compact` / 下次 SessionEnd |+| codex / trae-cli | **—**(上游不提供 SessionEnd 类事件) | **—** | **—** | **—** | **—** | 下次 `SessionStart(startup\|clear)` 的启发式(2min 内恰好 1 个活跃 → commit)或 30min idle-TTL 扫描;≥2 并发会话时启发式让位于 TTL 扫描 |+| cursor | **—**(chat 关闭 / new-chat 无事件) | **—** | **—** | **—**(`sessionEnd` 已注册且仅 window_close 触发,但此时宿主已销毁 shell-exec host,hook 在 spawn 前中止) | **—** | 结束在 <8 条消息水位的会话,尾部依赖同一会话的后续消息触发 commit |+| trae / trae-cn | **—**(无 session-end 类事件) | **—** | **—** | **—** | **—** | 每 Stop 已 commit,最大待归档量 = 最后一轮 in-flight |+| zcode | **—**(无 session-end 类事件) | **C\*** | **—** | **—** | **—** | C\* 前提:Ctrl+C 时该轮 Stop 已触发(detached worker 照常写完);每 Stop 已 commit,漏掉的轮次靠 rollout 游标在同一会话的下个 Stop 补回 |+| opencode | **C\***(≥1.15.11 的 `dispose` → `flushAll({commit:true})`,覆盖全部四种关闭;<1.15.11 无该 hook → —) | **C\*** | **C\*** | **C\*** | **—** | C\* 前提:宿主 shutdown 预算 5s,单会话最坏 health 5s + batch 10s + commit 30s,多会话串行累加——超预算的 commit 会被截断,且 pending queue 不覆盖此场景(fetch 未 settle 不入队);重启后 `init()` 不主动 flush 遗留会话 |+| dsh | **C**(Cordis teardown → 每 session 一次 3s 超时 commit,无阈值) | **C**(第一次;第二次 Ctrl+C 强退 → —) | **C** | **—**(无 SIGHUP 监听) | **—** | teardown commit 与阈值 commit 共享同一条串行写链,5s 进程 grace 内前方有慢请求时可能挤不进;web 形态关浏览器 tab 不触发 teardown |+| pi(takeover 默认) | **—**(`session_shutdown` 全关闭方式都触发且被 await,handler 持久化本地 takeover 状态,不 commit) | **—** | **—** | **—** | **—** | 下次续跑攒满 30000,或手动 `/viking commit` |+| pi(takeover off) | **C**(`await sync.commit()`,失败入 pending 队列) | **C** | **C** | **C** | **—** | — |+| openclaw | **—**(上游发 awaited `session_end(reason=shutdown\|restart)`,handler 缓存 agentId 后返回,不触发 commit;`gateway_stop` 未注册;无信号处理) | **—** | **—** | **—** | **—** | 显式 `/new` `/reset` 与 ~50% 阈值;低于阈值的会话依赖这两条路径归档 |+| hermes | **C**(atexit `_run_cleanup` → flush 10s → on_session_end) | **C**(交互与非交互最终都走 atexit) | **C**(`_signal_handler`,grace 默认 1.5s → 干净退出 → atexit) | **C**(SIGHUP 同 SIGTERM 路径) | **—**(atexit 不执行) | drain 不净时本次不 commit(避免提交半截数据);退出看门狗 30s 终止慢 commit |+| ov CLI | n/a(一次性命令) | n/a | n/a | n/a | n/a | 无 pending queue;命令失败重跑即可 |+| ingest | **C**(`finally _flush_all`) | **C**(SIGINT → stop) | **C** | **—**(无 SIGHUP handler) | **—** | 唯一有崩溃恢复的写路径:`needs_commit` 持久化在游标库,下次运行 reconcile 补 commit |+| LangChain / Open WebUI / Agent Plugins / 通用 MCP | **—**(无会话生命周期挂钩;MCP 代理退出时的 `DELETE /mcp` 只释放协议会话,与记忆 commit 无关) | — | — | — | — | LangChain 靠调用方 `close()`;进程内 pending-commit 集合随进程消失 |++**三点阅读提示**:++1. 正常退出即 commit 的有五家:claude-code、opencode(≥1.15.11)、dsh、pi(takeover off)、hermes;其余各家均依赖表中"补救路径"列的回收机制。+2. kill -9 场景所有集成都不触发 commit——已提交的消息保留在服务端 live 区,后续同一会话再触发 commit 时一并归档;服务端提供 per-session idle 兜底能力([§2.3](#_2-3-服务端会话与-commit-语义)),当前插件默认不下发该 policy。+3. 每轮必 commit 的 trae×2 / zcode 关闭语义最简单(即最大待归档量 = 最后一个未走到 Stop 的回合),代价是每个 Stop 都触发一次全量归档 + 记忆抽取(keep 0)。++### 3.3.4 pending queue / 离线补偿对照++| harness | 机制 | 要点 |+|---|---|---|+| cc / cursor / trae×2 / zcode / opencode / dsh / pi | 磁盘队列 `~/.openviking/pending`(0700/0600) | 仅可重试的失败入队(4xx 含 401/403 判为不可重试,不入队,debug 日志可见);重放在会话启动时执行:≤50 条/次、≤3 次/条、TTL 7 天;`.processing` 原子认领,10min 陈旧回收;addMessage 失败即 break 保序 |+| codex / trae-cli | 无磁盘队列 | 服务端不可达时,靠 `capturedTurnCount` 游标不推进、下一轮 Stop 重发同批实现补偿(进程存活且有下一轮时生效) |+| openclaw | 无本地队列 | addSessionMessage 失败被 catch,该轮消息不重放 |+| hermes | 进程内 daemon 线程队列 | drain 有预算(10s/65s);不落盘 |+| LangChain | 进程内 `_pending_commit_sessions` 集合 | commit 失败下次 record 自动重试;不落盘。部分成功时抛 `OpenVikingPartialWriteError`(携带 `messages_written`、`input_messages_consumed`、`context_attached`,调用方可按位置切片重试后缀)——全部集成里唯一的部分成功上报协议 |+| ingest | SQLite 游标库 + 单实例锁 | append 前持久化意图,崩溃后 reconcile 按服务端消息数判定该批是否落地——唯一有崩溃恢复语义的写路径 |++### 3.3.5 subagent 会话对照++| harness | 处理方式 |+|---|---|+| claude-code | 隔离最完整:SubagentStart 派生 `cc-<sid>__subagent-<agent_id>` 独立会话,SubagentStop 读 subagent transcript 推送后无条件 commit 并清 state |+| codex / trae-cli | 不单独建会话:subagent 输出(`agent_message` / `sub_agent_activity`)折叠进主会话的 assistant/tool part |+| opencode | `oc-<parent>__subagent-<child>` 挂在父命名空间下;开场注入跳过 subagent(召回不跳过);ID 派生依赖事件顺序——`chat.message` 先于 `session.created` 到达时会丢 `__subagent-` 后缀 |+| dsh | 每个 subagent = 独立 `dsh-<id>` 会话,父子关系不保留;N 个 subagent = N 份 profile 注入 + N 个独立会话 |+| hermes | `delegate_task` 传 `skip_memory=True` → subagent 不接 OV(无会话/召回/工具面);子任务产出不回灌 |+| cursor / trae×2 / zcode / pi / openclaw | 无 subagent 处理(有独立会话 id 就各自成会话,否则混入主会话;openclaw 可用 `bypassSessionPatterns` 屏蔽) |+| ingest | claude_code 适配器跳过 `isSidechain` / `isMeta` 记录——subagent 对话不入库 |++## 3.4 压缩 / compaction 接管++### 3.4.1 判定矩阵++| harness | 对宿主压缩的姿态 | 压缩前动作 | 压缩后动作 |+|---|---|---|---|+| claude-code | 不接管 | PreCompact 同步 commit(唯一不 detach 的写路径,因为 CC 随后立刻重写 transcript) | `source="compact"` 的 SessionStart 会把 OV 的 `latest_archive_overview` + ≤5 条 abstracts 重新注回 |+| codex / trae-cli | 不接管 | PreCompact 补齐未捕获轮次 → 全量 commit → `ovSessionId=null`(补齐不全时不 commit,留待重试);无 PostCompact 接线,依靠 Stop 的转录收缩做防御性纠偏 | resume 时注入 archive digest |+| cursor / trae×2 / zcode | 不接管 | cursor:preCompact 无条件 commit(trae×2/zcode 上游无该事件) | — |+| opencode | 不接管 | compacting 前 flush+commit | `session.compacted` 触发后再 flush+commit(共两次) |+| dsh | 不感知(不监听 compaction 事件;注入走 pre-step user 消息,随宿主压缩一起收缩,profile 不重投) | — | — |+| pi | **takeover 双层接管**(默认开,[§3.4.2](#_3-4-2-pi-takeover)) | `session_before_compact`:flush → commit → pollOverview。成功则返回自定义 compaction 摘要覆盖 pi 的;失败则 fail-open 回退到 pi 默认压缩 | 成功后 resetBoundary |+| openclaw | **全接管**:`ownsCompaction: true`,宿主不再跑自己的摘要([§3.4.3](#_3-4-3-openclaw-contextengine)) | `compact()` = commit(wait=true, keep 0) → 读回 overview 当 summary | 主 assemble 用 `[Session History Summary]` 重建上下文 |+| hermes | 不接管(`on_pre_compress` 接口预留,当前不参与压缩摘要) | fork 型压缩边界会触发旧会话 commit;原地压缩不动 | — |++### 3.4.2 pi takeover++- 接管面是 `context` 事件的 messages 改写,不接管 pi 的历史存储。触发是 token 压力(30000 + 保留 3 轮),而非 pi 的压缩事件。+- 替换动作:先定位边界,再把边界前的全部消息替换成一条合成 user 消息 `[OpenViking Session Context]`。其中 overview 按 3000 token 截断;timestamp 取保留首条 -1,以稳定 provider payload 吃 prompt cache。+- 数据源是 `GET /sessions/{id}/context` 的 `latest_archive_overview`(轮询 15×2s);状态持久化在 pi 自己的 branch custom entry `ov-takeover`。+- 失败姿态 = fail-open 回完整历史(指纹不匹配 / 历史短于边界 / overview 拿不到三重回退)。+- 与 pi 原生压缩的关系:`session_before_compact` 成功时返回 `{compaction:{summary, firstKeptEntryId, …, details:{source:"openviking"}}}` 覆盖 pi 摘要;缺 `firstKeptEntryId` 时走 pi 默认压缩。++### 3.4.3 openclaw ContextEngine++- 实现宿主 `ContextEngine` 接口,`assemble()` 分两个分支:transformContext(只做召回前置注入,5 道 passthrough 守卫)与 main-assemble(`getSessionContext(tokenBudget)` → 用服务端返回替换宿主 live 历史,四层预算切分,3 道 passthrough 保护 + provider 消息 sanitize 管线)。+- `compact()` = `commit(wait=true, keep 0)`(500ms 轮询,Phase2 上限 5 分钟)→ `latest_archive_overview` 当 summary、`archive_uri` 末段当 `firstKeptEntryId`。`customInstructions`/`compactionTarget` 保留接口,当前不参与压缩产物。+- `ingest()/ingestBatch()` 是刻意 no-op,写入全走 `afterTurn`。+- 有归档时额外注入 20 行 "Session Context Guide" systemPromptAddition,指示模型在说"没有信息"之前先重读摘要,并用 `ov_archive_search` 尝试至少 2 组关键词。++### 3.4.4 pi 与 openclaw 接管方式对照++| 维度 | pi takeover | openclaw ContextEngine |+|---|---|---|+| 宿主契约 | 一个 context 钩子的 messages 改写 | 注册 ContextEngine,`ownsCompaction: true` |+| 历史真相源 | 仍是 pi 本地 branch | OV 服务端 getSessionContext |+| 触发 | 客户端 token 阈值 30000 + 保留 3 轮 | 宿主调用 assemble/compact |+| 压缩产物 | 一条合成 user 消息(3000 token 截断) | 重建后的整个 messages 数组 + compaction summary |+| 失败姿态 | fail-open 回完整历史 | passthrough 回宿主 live 消息 |+| 召回与 session | context face 带 session_id | `/find` 不带(expansion/台账不参与) |++## 3.5 写入与删除的类型边界++### 3.5.1 写入边界++MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可写域限 `viking://resources|user|agent`;新建文件扩展名需符合白名单 `.md .txt .json .yaml .yml .toml .py .js .ts`;用户根下 `skills/ peers/ privacy/ sessions/` 四个托管子树只读(`_USER_MANAGED_SUBTREES`);派生文件 `.abstract.md/.overview.md/.relations.json` 不可直写。++### 3.5.2 删除边界++**第一档:服务端通用防线(所有删除入口共享)**。`VikingFS.rm` 第一句 `_ensure_delete_access`(`_access.py:182-229`)实施 5 道检查:命名空间可访问性;用户删除进行中 → FailedPrecondition;actor-peer 隐藏视图 → PermissionDenied;命名空间根保护:裸 `viking://`、`viking://user` 根、`viking://agent` 根一律拒删;非 ROOT 删 `viking://temp` 拒。这一档按命名空间根设防,不区分 memory/resource/skill 类型——类型级差异由后三档在客户端实施。++**第二档:客户端零附加(MCP 面 + dsh/pi/langchain/ov rm)**。差异只在参数面:dsh/pi 的 `viking_forget` 里 `recursive` 固定 false(不删除目录),且 query 删除需 score>0.8;LangChain `viking_forget` 的 `recursive` 是模型可控参数(但默认不在工具面);`ov rm -r` 则显式开递归、无确认提示(TUI 的 `d` 键有 y/n 确认 + root/scope 目录禁删)。++**第三档:memory-only 的两个删除面**。++- openclaw `memory_forget`:三条白名单正则只放行 `viking://user/[…/]memories`、`viking://user/<u>/peers/<p>/memories`、`viking://agent/[…/]memories`;显式 uri 不匹配直接拒绝;搜索路径候选先过同一 guard,且只有在候选唯一且 score≥0.85 时才自动删,否则列出候选让 agent 指名;底层 URL 固定 `recursive=false`。+- hermes `viking_forget`:六道顺序校验——非 str / 空拒;scheme≠viking 拒;带 query/fragment 拒;目录或非 `.md` 结尾拒;必须命中 4 种 memories 路径形状之一,且 `memories` 段后至少还有 2 段(不删除 `memories/` 与分类目录本身);文件名不能是 `.abstract.md/.overview.md`。++**第四档:默认不提供删除(LangChain / Open WebUI)**。LangChain `viking_forget` 需配置 `profile="admin"` 或 `allow_forget=True` 才加入工具面;Open WebUI 则完全不提供删除工具。++**skill 的增删边界**:新增入口是 openclaw `add_skill`(默认开)、`ov add-skill` 与 REST。对 skill 完全只读(不增不删)的删除面是 openclaw `memory_forget` 与 hermes `viking_forget`;相对地,MCP 面、dsh、pi、`ov rm` 加不了 skill 但删得掉——加不了是写路径 `_USER_MANAGED_SUBTREES` 的保护,删得掉是删除路径不检查该集合。++## 3.6 降级与容错++### 3.6.1 判定矩阵++| harness | 服务端不可达时 | 负缓存 | HTTP 重试 | 失败阻塞宿主 |+|---|---|---|---|---|+| claude-code | 各 hook catch→approve,不阻塞;session-start 时连 pending 重放都跳过 | context-face 6h + host-cli 探测 7d + health 5s | 无(靠 pending 重放);peer_scope 降级 1 次;batch→逐条 | 否(uri-guard deny 是设计意图) |+| codex / trae-cli | 各 hook catch→noop | context-face 6h + 压缩器 runtime_failed(至下次启动) | 同上(无磁盘 pending,靠游标重发) | 否 |+| cursor/trae×2/zcode | fetch 吞成 status:0,catch 返回空注入;锁 5s 拿不到则静默跳过 | context-face 6h(服务端整体不可达时无负缓存,每轮等满 15s) | 无 | 否 |+| opencode | 各路径 catch→WARN;`event`/`dispose` hook 无 try/catch(不可重试的 commit 失败会冒泡宿主) | 仅 context-face 6h;`/health` 无缓存(每轮一次往返) | 无同步重试;MCP 代理 401/403、400/404 各一次 | 基本否(event/dispose 例外) |+| dsh | client 全吞异常;`ensureState` 失败不缓存(服务端不可达时每 pre-step 两次 health 各 5s) | context-face 6h + user-space 缓存进程内不过期 | 无;pending 跨进程重放 3 次 | 是(pre-step 串行 profile+recall;session/flush 阻塞) |+| pi | health 失败时 start() 提前返回,此后每 prompt 静默重试连接 | context-face 6h | 无;仅 pending queue | 部分(session_shutdown 被 await:takeover 近 0、非 takeover 最坏 30s;turn_end 网络异常时逐条各等 10s) |+| openclaw | client 构造永不失败;health 吞异常;召回 500ms precheck 失败跳过 | 无负缓存(每轮一次 500ms health 预检) | 无(单次 fetch);commit/afterTurn 的 Phase2 轮询 | 否(`memory_store` 重抛例外;`compact()` 最长阻塞 5 分钟) |+| hermes | `_client=None` 即运行期负缓存(本进程不再重试,除本地自启 waiter 外) | 无独立结构(`_client=None` 承担) | trusted 补身份 1 次、sync 全新 client 1 次、多档降级;commit 失败不重试 | 否(后台单 worker + 逐 provider try/except) |+| ov CLI | 多数 exit 1;`ov status` 表格模式始终退 0;`ov health` 即使 unhealthy 也退 0 | 无 | 仅网关 401 挑战重试 1 次 | n/a(无宿主) |++### 3.6.2 通用超时++通用 HTTP 15000ms(下限 1000);MCP 代理请求 15000ms、DELETE 固定 2000ms;跨进程锁等待 5s、陈旧 60s;pending `.processing` 陈旧回收 10min。需注意 MCP 代理未注册 SIGHUP(关终端不发 `DELETE /mcp`;但服务端 `stateless_http=True`,影响有限)。++## 3.7 附加 UX 对照++| harness | statusline | slash command | rule/skill | setup 向导 | 其他 |+|---|---|---|---|---|---|+| claude-code | ✅ 独立进程写 settings.json(段位丰富,1min TTL) | ✅ `/openviking-memory:ov`(服务状态 + 身份 + 注入溯源) | 1 experience skill | ✅ 行式问答 | debug-recall/debug-capture 诊断脚本;uri-guard 不受插件开关门控 |+| codex / trae-cli | ❌ | ❌ | 1 experience skill | ✅ | VERIFICATION.md 8 步 SOP |+| cursor | ❌ | ❌ | rule(alwaysApply)+ skill | ❌(共用安装器 TUI) | 独立 uri-guard,不受插件开关控制 |+| trae/trae-cn | ❌ | ❌ | 无 | ❌ | — |+| zcode | ❌ | ❌ | 无 | ❌ | — |+| opencode | ❌(有 toast) | ❌ | 无(设计上不提供) | ✅ | — |+| dsh | ❌ | ❌ | 无 | ❌ | 工具调用卡片 presentCall;`ctx.provide("openvikingMemory")` 供其他 Cordis 插件二次开发 |+| pi | ✅ `ctx.ui.setStatus` | ✅ `/viking` `/viking commit` | 无 | ✅ | e2e-live.sh |+| openclaw | ❌ | ✅ 5 个(/add-resource /add-skill /ov-search /ov-query-config /ov-recall-trace) | 3 skill 随插件分发 | ✅(key 角色探测 + 版本兼容检查 + `status` 命令) | Gateway HTTP 路由做 recall trace 可视化;feature-gate RPC;健康检查脚本 |+| hermes | ❌ | ❌ | 无 | ✅ curses 多层菜单 | `hermes memory status`(含 env 覆盖列表);`hermes backup` 带 ovcli.conf |+| ov CLI | ❌ | ❌(自身即命令) | 无 | ✅ TUI 向导 | 完整 help 系统(63 条 curated);语言门禁;`ov tui` 全屏文件浏览器(含终端内图片预览) |++---++# 4. Harness 档案卡++每卡都是检索入口,只写该 harness 的独有事实与差异,共享机制回链维度章。统一字段:形态 / 能力亮点 / 行为要点 / 配置 / 维度索引。++## claude-code++- **集成文档**:[Claude Code 记忆插件](./02-claude-code.md)+- **形态**:CC 插件(marketplace),采用四合一架构:9 hook + MCP 代理(15 工具透传)+ slash command + statusline + 1 experience skill。版本 0.4.4。+- **能力亮点**:hook 覆盖最全的 harness——SessionStart(120s) / UserPromptSubmit(60s) / PostToolUse:Read(5s,默认关的 skill-experience) / PreToolUse:Read\|Glob\|Grep(5s,uri-guard) / Stop(45s) / PreCompact(30s) / SessionEnd(30s) / SubagentStart(10s) / SubagentStop(45s);默认启用召回再摘要(本地 `claude -p`,本地不可用时自动回落服务端 rewrite,[§3.2.5](#_3-2-5-召回再摘要));支持 SubagentStart/Stop 的完整子会话隔离([§3.3.5](#_3-3-5-subagent-会话对照));statusline + slash + uri-guard;关闭链路除 kill -9 外全部 commit([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))。+- **行为要点**:session id 为 `cc-<CC session_id 原文>`,subagent 为 `…__subagent-<agent_id>`;Stop 阈值 commit 20000/keep 10,PreCompact 同步 commit;自动召回排除 resources([§3.2.1](#_3-2-1-机制底座-一条共享管线-两条服务端路径));增量游标存于 `/tmp`(被系统清理后,同一会话会整段重推)。+- **配置**:env + ovcli.conf `plugin.claude_code` + ov.conf `claude_code`([§3.1.4](#_3-1-4-配置体系分层)),约 40 个旋钮;压缩器命令与模型固定为 `claude`/`sonnet`/`low`/30s。+- **维度索引**:工具面 [§2.1](#_2-1-服务端-mcp-工具面) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵) |压缩 [§3.4](#_3-4-压缩-compaction-接管) |降级 [§3.6](#_3-6-降级与容错) |UX [§3.7](#_3-7-附加-ux-对照)。++## codex++- **集成文档**:[Codex 记忆插件](./04-codex.md)+- **形态**:Codex 插件(marketplace),4 hook(SessionStart 70s / UserPromptSubmit 130s / Stop 30s / PreCompact 60s)+ MCP 代理 + 1 experience skill。版本 0.7.5。+- **能力亮点**:本地召回压缩管线(`codex exec`,[§3.2.5](#_3-2-5-召回再摘要));SessionStart 的 active-window 启发式 + idle-TTL 扫描,可自动回收历史会话中未归档的消息([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))。+- **行为要点**:session id 为 `cx-<safeId>`(确定性推导,不读 state);关闭时无 hook(上游不提供 SessionEnd),commit 依赖下次启动的回收路径;不使用磁盘 pending queue(离线靠游标不推进、下一轮重发补偿,[§3.3.4](#_3-3-4-pending-queue-离线补偿对照));active-window 120000ms / idle-TTL 1800000ms(env 配置);Stop 默认 detach(`appended N turn(s)` 提示默认不展示)。+- **配置**:env + ovcli.conf `plugin.codex` + ov.conf `codex`;hooks 同时发送 Bearer 与 `X-API-Key` 兼容头([§3.1.3](#_3-1-3-凭据体系))。+- **维度索引**:工具面 [§2.1](#_2-1-服务端-mcp-工具面) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵) |降级 [§3.6](#_3-6-降级与容错)。++## trae-cli(TraeCode CLI 2.0)++- **集成文档**:[TRAE 记忆集成](./13-trae.md)+- **形态**:TraeCode CLI 2.0 是 Codex 系 CLI(binary `traecli`,用户配置 `~/.trae/traecli.toml`,TUI 支持 `/plugins` `/skills` `/mcp`)。OpenViking 经 **codex 插件别名安装**接入:`--harness trae-cli` 复用 codex 安装流程,仅安装参数(binary / home / 配置路径)指向 TraeCode CLI。+- **能力面**:与 codex 完全一致——4 hook + MCP 代理 + experience skill、本地召回压缩、active-window/idle-TTL commit 回收、resume archive 注入等,详见 codex 档案卡。+- **版本支持**:仅支持 TraeCode CLI 2.0。1.0 与 2.0 不是同一套 CLI,2.0 才是 Codex 系、才能走 codex 插件别名安装;早期面向 1.0 的独立插件 `examples/trae-cli-memory-hooks`(`~/.trae/cli/hooks.json` + `[mcp_servers."openviking-memory"]` 方案)已废弃。+- **维度索引**:同 codex 卡。++## cursor++- **集成文档**:[Cursor 记忆集成](./12-cursor.md)+- **形态**:配置驱动(写 `~/.cursor/hooks.json`+`mcp.json`)+ MCP 代理 + always-on rule + skill。7 hook:sessionStart(30s) / beforeSubmitPrompt(20s) / beforeReadFile(5s) / beforeShellExecution(5s) / stop(30s) / preCompact(30s) / sessionEnd(30s)。相对 import 共享 lib(不 vendoring)。+- **能力亮点**:beforeReadFile/beforeShellExecution 双 uri-guard(不受插件开关控制);rule + skill 随装。+- **行为要点**:session id 为 `cu-<conversation_id>`;stop 每 8 条消息 commit(`commitTurnThreshold=8`,消息条数计数,keep 0);`sessionEnd` 仅 window_close 触发,且此时宿主已销毁 shell-exec host,实践中不执行([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))——结束在 <8 条消息水位的会话,尾部依赖后续同会话消息触发归档([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵));服务端不可达时,每轮等满 15s 召回超时。+- **配置**:仅 env(`plugin` 段不参与解析)。+- **维度索引**:工具面 [§2.1](#_2-1-服务端-mcp-工具面) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵) |降级 [§3.6](#_3-6-降级与容错)。++## trae / trae-cn(IDE 版)++- **集成文档**:[TRAE 记忆集成](./13-trae.md)+- **形态**:配置驱动(`~/.trae{,-cn}/hooks.json` + 平台相关 mcp.json)+ MCP 代理。4 hook:SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep\|Bash\|RunCommand(5s) / Stop(30s)。相对 import 共享 lib。MCP server 名为 `openviking`。+- **能力亮点**:行为最简单直接的一档——每个有内容的 Stop 都 commit(keep 0),关闭场景下最大待归档量只有最后一轮 in-flight([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))。+- **行为要点**:trae 与 trae-cn 的差异是 session id 前缀 `tr-` / `trcn-` 与安装路径——同一份记忆在两个客户端落到两组不同 session,跨客户端共享靠服务端抽取后的记忆空间而非 session 复用;无 PreCompact/statusline/skill/subagent 处理。+- **配置**:仅 env。+- **维度索引**:工具面 [§2.1](#_2-1-服务端-mcp-工具面) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵)。++## zcode++- **集成文档**:[社区插件 → ZCode](./08-community-plugins.md)+- **形态**:配置驱动(合并进 `~/.zcode/cli/config.json`,强制 `hooks.enabled=true`)+ MCP 代理。4 hook:SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep(5s) / Stop(30s)。唯一全量 vendoring 18 个共享文件的 harness。版本 0.1.1。+- **能力亮点**:以 rollout 文件 `~/.zcode/cli/rollout/model-io-<sid>.jsonl` 为增量真相源(`lastTurnId` 差集补齐漏掉的 Stop);Stop 默认 detach(Ctrl+C 不丢写入)。+- **行为要点**:每 Stop commit(keep 0);捕获路径仅剥离三类注入块(不做额外文本清洗,[§3.2.6](#_3-2-6-注入回流防护));首次捕获会一次性读取整个 rollout(长会话首装时单次推送量大)。+- **配置**:仅 env;`OPENVIKING_WRITE_PATH_ASYNC` 对 zcode 生效。+- **维度索引**:工具面 [§2.1](#_2-1-服务端-mcp-工具面) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵)。++## opencode++- **集成文档**:[OpenCode 插件](./10-opencode.md)+- **形态**:npm 插件 `@openviking/opencode-plugin`,config hook 自注入 MCP 条目(工具带 `openviking_` 前缀)。7 个 plugin hook:config / event / tool.execute.before / experimental.chat.system.transform / chat.message / experimental.session.compacting / dispose。版本 0.2.4。+- **能力亮点**:`dispose` hook 覆盖全部四种常规关闭方式(宿主 ≥1.15.11);repo 列表进 system prompt([§3.2.3](#_3-2-3-profile-开场注入));宿主事件面最丰富(session.idle/compacted/deleted/error 各有语义)。+- **行为要点**:`commitTokenThreshold=20000`(取正数,0 回落默认值);commit 超时 30000ms;一次宿主压缩 = 两次 commit;dispose 的 5s 宿主预算下,多会话慢 commit 可能被截断,且 pending queue 不覆盖此场景([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵));<1.15.11 无 dispose 时关闭不 commit;重启后不主动 flush 遗留会话;开场注入每会话尝试一次([§3.2.3](#_3-2-3-profile-开场注入));`bypassSessionPatterns` 的目录匹配在 opencode 上不适用(input 无 cwd)。+- **配置**:`openviking-config.json`(4 级搜索)+ env。+- **维度索引**:工具面 [§2.1](#_2-1-服务端-mcp-工具面) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵) |subagent [§3.3.5](#_3-3-5-subagent-会话对照)。++## dsh(DeepSeek Harness)++- **形态**:唯一同进程 Cordis 原生插件(`export function apply`),原生注册 7 个 `viking_*` 工具(`viking_search/read/browse/remember/forget/add_resource/archive_expand`),REST 直连。4 事件:agent/session-start(emit)/ agent/pre-step(waterfall)/ session/event / session/flush。版本 0.1.0。+- **能力亮点**:`ctx.provide("openvikingMemory")` 供其他 Cordis 插件二次开发;pre-step 注入走 user 消息,适配 DSH persona 的 `complete:true` 渲染模式。+- **行为要点**:安装走 `dsh plugin add ./examples/dsh-memory-plugin`(统一安装器暂不覆盖);teardown commit 3s 无阈值,SIGHUP/二次 Ctrl+C 不触发([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵));compaction 不感知(注入内容随宿主压缩收缩,profile 不重投);subagent 各自独立会话([§3.3.5](#_3-3-5-subagent-会话对照));工具面较 MCP 面少 write/edit/tree/grep/glob/watch/health;uri-guard 匹配工具名不做大小写归一化。+- **配置**:cordis patch + 4 个 env;凭据 patch>env,行为开关 env>patch。+- **维度索引**:工具面 [§1.1](#_1-1-主动工具面-agentic-调用能力) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵) |降级 [§3.6](#_3-6-降级与容错)。++## pi(pi Coding Agent Extension)++- **集成文档**:[pi Coding Agent 扩展](./11-pi.md)+- **形态**:pi 原生扩展(目录装载,jiti 直译 TS),原生注册 7 个 `viking_*` 工具,REST 直连(pi 无 MCP 支持)。8 事件 + `/viking` 命令。版本 0.1.0。+- **能力亮点**:takeover 压缩接管(默认开,[§3.4.2](#_3-4-2-pi-takeover));两段式召回(before_agent_start 排队 + context 事件同步检索,当前轮 prompt 拿当前轮记忆);statusline;`session_shutdown` 在所有关闭方式下都触发且被 await。+- **行为要点**:默认 takeover 下退出不 commit(handler 持久化本地状态,归档靠下次续跑攒满阈值或 `/viking commit`,[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵));takeover 阈值 30000 token + 保留 3 轮(keep 3,服务端按消息条数解释);非 takeover 阈值 20000/keep 10、退出无条件 commit;工具注册需 health+ensureSession 前置([§1.1](#_1-1-主动工具面-agentic-调用能力));`viking_add_resource` 仅 HTTP URL(guard 在服务端);非 takeover 模式下 `pi -c` 续跑会重新上报整条 branch。+- **配置**:`config.json` 行为旋钮 + env(凭据统一走凭据链,[§3.1.3](#_3-1-3-凭据体系));`bypassPatterns` 为前缀匹配(非 glob)。+- **维度索引**:工具面 [§1.1](#_1-1-主动工具面-agentic-调用能力) |召回 [§3.2](#_3-2-自动召回与注入) |takeover [§3.4.2](#_3-4-2-pi-takeover) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵)。++## openclaw++- **集成文档**:[OpenClaw 插件](./03-openclaw.md)+- **形态**:唯一 context-engine 全接管型(`ownsCompaction:true`)。15 原生工具(默认开 14)+ 5 slash + 4 hook + Gateway HTTP 路由 + feature-gate RPC。remote-only。版本 2026.6.18。+- **能力亮点**:检索拆两个默认不重叠入口——`memory_recall` 默认搜 memory、`ov_search` 默认搜 resource+user skills(都可显式参数越界);`add_skill` 默认开;`memory_forget` memory-only 白名单([§3.5](#_3-5-写入与删除的类型边界));三个 tool-result 工具读服务端外置输出(跨会话 guard);ContextEngine 全接管([§3.4.3](#_3-4-3-openclaw-contextengine));setup 向导带 key 角色探测与版本兼容检查。+- **行为要点**:召回走 `/find` 不带 session_id(expansion/去重台账不参与,长会话中同一记忆可能重复注入);关闭不触发 commit,归档依赖显式 `/new`/`/reset` 与 ~50% 阈值([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵));无本地 pending queue(失败轮次不重放);`compact()` 最长阻塞 5 分钟;召回默认对每条 leaf 记忆多一次 read(`recallPreferAbstract=false`);配置严格校验,存在未知键/非法值时插件进入 setup-only 模式。+- **配置**:`openclaw.json` 的 `plugins.entries.openviking.config` + 少量 env;认证头 `X-API-Key`([§3.1.3](#_3-1-3-凭据体系));commit 阈值由 `commitTokenThresholdRatio` 控制(默认 0.5);召回字符预算 4000。+- **维度索引**:工具面 [§1.1](#_1-1-主动工具面-agentic-调用能力) |召回 [§3.2](#_3-2-自动召回与注入) |ContextEngine [§3.4.3](#_3-4-3-openclaw-contextengine) |删除 [§3.5](#_3-5-写入与删除的类型边界) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵)。++## hermes(Nous Research)++- **集成文档**:[Hermes Agent](./05-hermes.md)+- **形态**:Hermes bundled MemoryProvider(Python 单文件实现,共 3725 行,随 Hermes 一同发布)。通过 `httpx` 直连,无需额外安装插件。提供 6 工具及 10+ 生命周期 hook(prefetch/sync_turn/on_session_end/on_session_switch/on_memory_write/…)。基线为发行版 `e12626b3`(= brew 2026.7.7.2)。+- **能力亮点**:具备最全面的资源摄取面——`viking_add_resource` 支持 HTTP、Git、SSH、`file://`、本地文件 temp_upload 以及本地目录 zip 打包上传(跳过 symlink + 越界文件);`viking_remember` 直写记忆文件(不依赖 session commit/抽取);支持本地服务端自启(当 endpoint 位于本地且不可达时,通过 `subprocess.Popen openviking-server` 拉起);支持 trusted 补身份重试;无论正常退出还是接收到 Ctrl+C、SIGTERM、SIGHUP 信号,均能保证完成 commit(详见 [§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))。+- **行为要点**:在召回上,仅有 `search/search` 的首选路径携带 session_id 并落到路径 B(`mode="deep"`;而 `auto`/`fast` 走 `/find` 且不带 session_id,详见 [§3.2.2](#_3-2-2-判定矩阵))。`queue_prefetch` 为同步实现,无预热;subagent 传入 `skip_memory=True` 时不接 OV(详见 [§3.3.5](#_3-3-5-subagent-会话对照))。无 profile 注入/statusline/slash;commit 恒 keep 0,drain 不净则本次不 commit;进程内队列不落盘。session id 格式为 `%Y%m%d_%H%M%S_<hex6>`。召回参数:6 条/阈值 0.15/字符预算 4000/总超时 4s。记忆 URI 为 `viking://user/peers/{agent}/memories/{subdir}/mem_<uuid12>.md`。退出机制包含 SIGTERM grace 1.5s 与退出看门狗 30s。互补路径支持 `openviking-server ingest hermes`(离线重放,默认关,详见 [§7](#_7-附录-非-coding-集成速览) E)。+- **配置**:通过 `OPENVIKING_ENDPOINT`(非 `_URL`)、8 个 `OPENVIKING_RECALL_*` env 以及 `config.yaml` 进行配置。在 `use_ovcli_config` 模式下,系统会清空 `.env` 里的对应变量。+- **维度索引**:工具面 [§1.1](#_1-1-主动工具面-agentic-调用能力) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵) |删除 [§3.5](#_3-5-写入与删除的类型边界)。++## ov CLI++- **集成文档**:[部署指南 → CLI](../guides/03-deployment.md#cli)+- **形态**:Rust 原生二进制,把服务端 REST 包成命令行;无宿主事件、无自动召回、不接管压缩。+- **能力亮点**:唯一会下发 `auto_commit_policy` 的第一方客户端(`ov session new --auto-commit-policy-json`、`ov session config set`);提供多 profile、admin、privacy、snapshot、TUI 等插件面没有的能力(详见 [§5.3](#_5-3-cli-独有于插件面的能力))。+- **维度索引**:完整命令参考请见 [§5](#_5-ov-cli-命令参考)。++---++# 5. ov CLI 命令参考++`ov`(clap 内部名 `openviking`)是 Rust HTTP 客户端,所有能力都在服务端,CLI 只做参数拼装、本地打包上传、输出渲染与多 profile 管理。它不是 harness 集成——没有宿主事件、不自动召回、不接管压缩;本章覆盖它作为"人/脚本直接使用 OV"的完整命令面,以及它独有于插件面的能力(TUI、多 profile、admin、`--sudo`、privacy、snapshot 等)。++> 版本说明:以 HEAD 源码为准(HEAD tag 已到 `[email protected]`),0.4.10 等旧版本的差异处已标注。需要注意的是,`ov doctor` 不在 Rust 二进制里——pip 装的 Python wrapper 会拦截 `argv[1]=="doctor"` 并走 `openviking_cli.doctor`,读取的是服务端 `ov.conf` 而非 `ovcli.conf`;npm/cargo 装的纯 Rust `ov` 无该子命令。++## 5.1 命令树++命令 doc-comment 前缀 `[Data]`/`[Interactive]`/`[Admin]`/`[Experimental]` 等只影响 help 渲染,不影响运行时——即使是 `[Experimental]` 命令,默认也可用。++**数据写入**:`add-resource`(支持本地文件/目录/URL/Git/sitemap/RSS;目标 `--to`/`--parent`/`-p` 三选一;manifest 模式 `-m`;Connector `--add-type`;注意本地路径 + watch>0 会报错)|`add-skill`|`write`(`--content`/`--from-file` 互斥)|`mkdir`|`rm`(别名 del/delete,无确认提示,`-r` 显式递归)|`mv`(别名 rename)|`set-tags`(顶层隐藏,用 `attrs set-tags`)|`add-memory`(实验性;执行逻辑为建 session → 批量 add → commit 三步串行)++**读取/检索**:`ls`(别名 list)|`tree`(`-L` 默认 3)|`stat`/`attrs get`|`read`/`abstract`/`overview`(分别对应 L2/L0/L1)|`get`(下载)|`find`(query 或 `--image` 至少一个非空;`--image` 支持本地路径、data URI、http、viking://)|`search`(实验性,比 find 多一个 `--session-id`)|`grep`|`glob`++**Skills**:`skills add`(支持本地路径、git 及 GitHub tree URL,`-s` 选装、`*` 全装,有交互确认)|`skills list/find/show/update/remove`|`skills validate`(唯一完全离线的命令)++**会话/记忆**:`session new`(`--auto-commit-policy-json` 与 `--no-auto-commit` 互斥——唯一下发 policy 的第一方客户端)|`session list/get/delete`|`session get-session-context`(`--token-budget` 默认 128000)|`session get-session-archive`|`session add-message(s)`|`session config set`(改可变配置)|`session commit`++**导入导出/快照**:`export`/`backup`/`import`/`restore`(.ovpack)|`snapshot commit/restore/show/log/diff/ignore-*`(工作区快照,前向 commit 回滚)++**隐私/关系**:`privacy categories/list/get/versions/version/activate/upsert`(`--key-<name>` 语法糖)|`relations`/`link`/`unlink`(实验性)++**状态/可观测**:`health`(healthy=false 时仍退 0)|`status`(表格模式始终退 0)|`observer {queue,vikingdb,models,retrieval,filesystem,system}`|`wait`|`task status/cancel/list`|`task watch {ls,show,rm,pause,resume,update,trigger}`|`version`(独立 3s 超时探服务端)++**配置/交互**:`config`(TUI 向导,5 项菜单含 User Management)|`config show`(固定 json+compact 输出)|`config validate`|`config list/switch/add/edit/delete`(面向 Agent,退出码 2-6 语义化)|`config add ov-service`(云)/`config add custom`|`language`(别名 lang)|`tui`(全屏文件浏览器 + 终端内图片预览 + 向量视图 + 删除确认)|`chat`(VikingBot,300s 超时)|`compile`(用 Skill 整理素材,`--wait` 本地轮询)++**管理(多为 ROOT/`--sudo`)**:`admin create-account/list-accounts/delete-account/set-role/migrate/register-user/list-users/remove-user/regenerate-key`|`system wait/status/health/consistency`|`system crypto init-key`(纯本地生成 32 字节 root key,权限 0600)|`system backend sync-status/sync-retry`|`reindex`(`--mode` 默认 vectors_only;`--wait` 默认 true,全 CLI 唯一)|`doctor`(仅 Python wrapper)++## 5.2 全局选项与独有机制++- `-o/--output table|json`(默认取 conf `output`)|`-c/--compact`(默认 true)|`--account`/`--user`/`--actor-peer-id`|`--sudo`(用 root_api_key,只允许 admin/system/reindex/task status/task list)|`--profile`(隐藏)+- **多 profile**:active 为 `~/.openviking/ovcli.conf`,命名规范为 `ovcli.conf.<name>`;`switch` 是字节复制(保留 `plugin` 段),而 `add/edit` 走 serde 重写(会丢弃 Rust Config 不识别的键,含 `plugin` 段,见 [§3.1.4](#_3-1-4-配置体系分层))。+- **语言门禁**:跑任何命令前要求先存显示语言(未存 + 非交互 → exit 2);HEAD 起 `--help` 在门禁前豁免(0.4.10 尚无此豁免),但 `--version` 仍需先过门禁。+- **三种 JSON 输出格式(按命令组不同)**:普通命令 compact 下输出 `{"ok":true,"result":…}`,`-c false` 输出裸 payload,失败输出 `{"ok":false,"error":…}`;config 系为 `{"status":"ok","result":…}`;带 profile 时追加 `"profile":[…]`。脚本解析时需注意;此外 `echo_command` 默认 true 且不受 `-o json` 抑制(stdout 第一行是 `cmd: …`)。+- **env**:`OPENVIKING_CLI_CONFIG_FILE`、`OPENVIKING_UPLOAD_MODE`(local/shared)、`OPENVIKING_ASSETS_CREDENTIALS_FILE`、`OPENVIKING_LANG`/`LC_*`/`LANG`,以及 chat 用的 `VIKINGBOT_ENDPOINT`/`VIKINGBOT_API_KEY`/`OPENVIKING_URL`。++## 5.3 CLI 独有于插件面的能力++以下是插件面拿不到、只有 CLI/TUI 能做的:多 profile 切换与向导、`admin` 全套账号/用户管理、`--sudo` root 操作、`privacy` 隐私策略 CRUD + 版本、`snapshot`/`backup`/`restore`/`export`/`import` 数据搬运、`reindex` 重建索引、`system crypto init-key` 生成 root key、`ov tui` 交互浏览、依赖 VikingBot 能力的 `ov chat`/`ov compile`,以及 `ov session config set` 显式设 `auto_commit_policy`(唯一能开服务端自动 commit 的第一方入口)。++---++# 6. 自定义 agent 接入指南++如果你使用的 agent/harness 不在上面 11 家里,可以参考以下三条接入路径(按投入成本从低到高排列)。++## 6.1 接入路径 × 能获得的能力++| 路径 | 投入 | agent 主动工具面 | 自动召回/捕获 hook | 会话/commit | 压缩接管 |+|---|---|---|---|---|---|+| ① [通用 MCP 直连](./06-mcp-clients.md) | 分钟级(填写一段 config 即可) | ✅ 15 工具全量 | ❌ 由模型主动调用 | 仅 `remember` 建临时会话 | ❌ |+| ② HTTP API / SDK / [LangChain](./07-langchain-langgraph.md) | 小时级(需写代码) | 自选(按需调 REST) | 自己实现 | 自己实现(或用 LangChain middleware) | ❌ |+| ③ 复用 shared-core / [Agent Plugins 便携包](./15-agent-plugins.md) | 天级(需写 hook 适配) | ✅ 15 工具(经 MCP 代理) | ✅ 召回/捕获/commit/pending 全套 | ✅ | 视接入哪些事件而定 |++## 6.2 路径①:通用 MCP 直连(推荐起步)++任何支持 MCP 的 agent,只需在其 `mcpServers` 配置里指向服务端 `/mcp`(各客户端的具体配置位置见 [MCP 客户端](./06-mcp-clients.md)),即可立刻获得全部 15 个工具([§2.1](#_2-1-服务端-mcp-工具面))。最小配置如下:++```json+{+ "mcpServers": {+ "openviking": {+ "url": "http://127.0.0.1:1933/mcp",+ "headers": {+ "Authorization": "Bearer <api_key>",+ "X-OpenViking-Account": "<account>",+ "X-OpenViking-User": "<user>",+ "X-OpenViking-Actor-Peer": "<workspace-peer>"+ }+ }+ }+}+```++后三个 header 可选,缺省时没有 workspace peer 隔离与租户路由。stdio-only 的客户端可用便携代理(路径③)把 stdio 桥到 streamable-HTTP。该路径得到的是纯工具面——无自动召回、无捕获、无 commit(除非模型主动调 `remember`)。++## 6.3 路径②:程序化接入++- **直连 REST**:召回用 `POST /api/v1/search/search`(必须 `mode:"context"` + `session_id` 才有 expansion/去重,[§3.2.1](#_3-2-1-机制底座-一条共享管线-两条服务端路径);可传 `rewrite` 获得服务端 digest,[§3.2.5](#_3-2-5-召回再摘要));写入用 `POST /api/v1/sessions/{id}/messages/batch`(≤100 条/批,auto_create);提交用 `POST /api/v1/sessions/{id}/commit`;读取用 `GET /api/v1/content/read` 等。要用服务端自动 commit,需在 `POST /api/v1/sessions` 时显式带 `auto_commit_policy`,或通过 `PATCH /{id}/config` 修改([§2.3](#_2-3-服务端会话与-commit-语义))。+- **LangChain / LangGraph SDK**(`pip install langchain-openviking`):`OpenVikingContextMiddleware` 提供 `wrap_model_call`(把召回内容注入 `<openviking_context>`)与 `after_agent`(捕获 + 按 `CommitPolicy` 提交,默认 `never`)。这是本组唯一带 session + token 预算的现成自动召回;容错是"只读方法重试一次、写方法不重试",部分成功时抛 `OpenVikingPartialWriteError`(可按 `input_messages_consumed` 切片重试)。参考 [§7](#_7-附录-非-coding-集成速览) B。+- **Open WebUI**(OpenAPI 工具服务器):`python -m openviking_openwebui` 起独立进程,在 Open WebUI 里添加 Tool Server URL,即可得 7 个工具(无删除、无 hook)。参考 [§7](#_7-附录-非-coding-集成速览) A。+## 6.4 路径③:要自动 hook 面时复用参考实现++如果希望实现召回、捕获、commit、pending 的全套自动化,完全不必从零开始编写。建议直接参考并复用以下两个现成的实现:++- **`examples/memory-plugin-shared/lib/`**(Node):包含完整的核心功能模块,例如 `recall-core`(三级降级召回)、`profile-inject`、`capture-utils`(消息归一 + 注入回流防护)、`pending-queue`(离线重放)、`batch-send`、`mcp-proxy-core`(stdio↔HTTP 代理)、`session-model`(会话 id 派生)以及 `credentials`。构建瘦 harness 时,只需实现一个适配层,把宿主生命周期事件映射到这些模块即可(例如 `agent-hook-runtime.mjs` 就是 cursor、trae、zcode 共用的现成一体化运行时,接新宿主时的主要工作只是解析其 stdin JSON 字段名)。+- **Agent Plugins 1.0 便携包**(位于 `agent-plugins/`):采用 `plugin.json` + `skills/` + `mcp.json`(stdio→HTTP 代理)的规范化便携格式。该方案刻意不含 hooks(召回/沉淀靠 skill 教模型自调工具),非常适合符合 Agent Plugins 规范的客户端直接加载;此外,`plugin.test.mjs` 定义了规范一致性校验(schema URL、name 规则、静态 headers 不含机密、`mcp.json` 引用不逃逸插件根等),可作为自行打包的 lint 依据。++**接入时务必对齐的三个约定**(与现有 harness 保持一致的行为):① 召回调用点必须转发 `session_id`,这样才有服务端 expansion + 跨轮去重(详见 [§3.2.1](#_3-2-1-机制底座-一条共享管线-两条服务端路径));② 适配器不要用自己的超时压过 helper 下发的 deadline;③ 关闭时要安排一条 commit 路径,否则未达阈值的尾部对话需等待后续触发才能归档(详见 [§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))——若宿主不提供关闭事件,可依赖服务端 idle 兜底(在服务端开 `memory.session_auto_commit.idle_enabled` 并下发 per-session policy)。这三条正是 `recall-session-wiring.test.mjs` 用跨插件正则钉死的。++---++# 7. 附录:非 coding 集成速览++| 集成 | 形态 | 工具面 | 会话/commit | 容错 | 默认状态 |+|---|---|---|---|---|---|+| **A. [Open WebUI](./08-community-plugins.md)** | 独立的 FastAPI OpenAPI 工具服务器 | 7 个本地 OpenAPI 路由(`ov_search`/`ov_recall_memories`/`ov_add_memory`/`ov_list_memories`/`ov_read_resource`/`ov_add_resource`/`ov_session_status`),无删除工具 | 无会话概念 | 最薄:裸 httpx,无 retry/负缓存;`/health` 仅回显配置,不探测 OV | 进程不启动即不存在 |+| **B. [LangChain/LangGraph](./07-langchain-langgraph.md)** | Python SDK 适配层(retriever/tools/store/middleware/recorder) | `create_openviking_tools()` 提供 12 个 StructuredTool(`viking_forget` 默认不在 agent profile 中) | `thread_id`/`session_id` 由调用方给;`CommitPolicy` 默认 `never` | 本组最稳:只读方法自动重试 1 次、写方法不重试(防重复)、部分成功抛结构化异常可切片重试 | 需全部显式构造才生效 |+| **C. [Agent Plugins 1.0](./15-agent-plugins.md)** | 便携包 `plugin.json` + `skills/` + `mcp.json`(stdio→HTTP 代理) | MCP 透传 15 工具;刻意无 hooks(召回靠 skill 教模型) | 仅 `remember` 建临时会话 | MCP 代理层重试(401/403 换凭据、400/404 重初始化各 1 次) | 客户端加载后工具即用 |+| **D. [通用 MCP 直连](./06-mcp-clients.md)** | 零本地组件,直连 `/mcp` | 同 C(15 工具) | 同 C | 由客户端自定 | `/mcp` 常驻 |+| **E. [log ingestion](./09-log-ingestion.md)** | `openviking-server ingest` CLI(跑在日志所在机器,反向导入) | 无(只写不召回) | 会话 id `{prefix}__{harness}__{sanitized native id}`;commit token 6000/idle 5s/keep 0 | 唯一有崩溃恢复:SQLite 游标库 + 单实例锁 + reconcile 判定批次落地 | 双重默认关(`ingest.enabled` + 每 harness `enabled` 都 false);支持 claude_code/codex/hermes/opencode/openclaw/cursor 适配器 |+| **F. [OpenViking Helper](./14-openviking-helper.md)** | 闭源桌面 App | — | — | — | 不在本文代码基线内 |++---++*各集成的安装、配置与排障以对应的单独集成页面为准;当本页与单独页面不一致时,以单独页面为准。*++## 参见++- [Agent 集成概览](./01-overview.md)+- [MCP 客户端](./06-mcp-clients.md)+- [MCP 集成指南](../guides/06-mcp-integration.md)+- [检索 API](../api/06-retrieval.md)+- [会话 API](../api/05-sessions.md)+- [鉴权](../guides/04-authentication.md)diff --git a/examples/claude-code-memory-plugin/README.md b/examples/claude-code-memory-plugin/README.mdindex db52c0157..9f9253fbd 100644--- a/examples/claude-code-memory-plugin/README.md+++ b/examples/claude-code-memory-plugin/README.md@@ -357,7 +357,7 @@ Claude Code has a built-in `MEMORY.md` file system. This plugin **complements**There is no TypeScript build step and no runtime npm bootstrap. Hooks are plain `.mjs` files that talk to OpenViking over HTTP; MCP uses `servers/mcp-proxy.mjs` as a zero-dependency stdio bridge to the OpenViking server's `/mcp` endpoint.-A persistent OpenViking session is created on first contact and reused for the entire Claude Code session. The OV session ID is `cc-<sha256(cc_session_id)>`, so resume / compact / multi-hook events all target the same session, and OV's `auto_commit_threshold` drives archival + memory extraction naturally.+A persistent OpenViking session is created on first contact and reused for the entire Claude Code session. The OV session ID is `cc-<cc_session_id>` (the CC session_id verbatim, no hashing), so resume / compact / multi-hook events all target the same session. Archival + memory extraction is triggered client-side: the `Stop` hook commits when server-reported pending tokens cross `commitTokenThreshold` (default 20000), and `PreCompact` / `SessionEnd` / `SubagentStop` commit unconditionally.### Hook responsibilities@@ -370,6 +370,8 @@ A persistent OpenViking session is created on first contact and reused for the e| `SessionEnd` | Claude Code session closes | Final commit so the last window is archived || `SubagentStart` | Parent spawns a subagent via Task tool | Derive an isolated OV session ID for the subagent, persist start state || `SubagentStop` | Subagent finishes | Read subagent transcript → push to an isolated session with subagent peer identity → commit |+| `PreToolUse` | Native `Read` / `Glob` / `Grep` on a `viking://` URI | Deny the call and point Claude to the equivalent OpenViking MCP tool |+| `PostToolUse` | `Read` of a `SKILL.md` file | Optional (default off): inject an experience block when OV has relevant skill-experience memories |### Async write path@@ -394,7 +396,7 @@ claude-code-memory-plugin/├── .claude-plugin/│ └── plugin.json # plugin manifest├── hooks/-│ └── hooks.json # 7 hook registrations+│ └── hooks.json # 9 hook registrations├── servers/│ └── mcp-proxy.mjs # stdio -> OpenViking /mcp bridge├── scripts/diff --git a/examples/claude-code-memory-plugin/README_CN.md b/examples/claude-code-memory-plugin/README_CN.mdindex fbca1cde5..0dc48db04 100644--- a/examples/claude-code-memory-plugin/README_CN.md+++ b/examples/claude-code-memory-plugin/README_CN.md@@ -351,7 +351,7 @@ Claude Code 自带 `MEMORY.md` 文件系统,本插件**与之互补**:没有 TypeScript 编译步骤,也没有运行时 npm 引导。Hook 都是直接走 HTTP 调 OpenViking 的 `.mjs` 文件;MCP 使用 `servers/mcp-proxy.mjs` 作为零依赖 stdio 桥接,转发到 OpenViking 服务器自身的 `/mcp` endpoint。-首次接触时创建一个持久化的 OpenViking session,整个 Claude Code 会话期间复用。OV session ID 是 `cc-<sha256(cc_session_id)>`,所以 resume / compact / 多 hook 事件都打到同一个 session,OV 的 `auto_commit_threshold` 自然驱动归档与记忆抽取。+首次接触时创建一个持久化的 OpenViking session,整个 Claude Code 会话期间复用。OV session ID 是 `cc-<cc_session_id>`(CC session_id 原样保留,不做哈希),所以 resume / compact / 多 hook 事件都打到同一个 session。归档与记忆抽取由客户端触发:`Stop` hook 在服务端报告的 pending tokens 超过 `commitTokenThreshold`(默认 20000)时 commit,`PreCompact` / `SessionEnd` / `SubagentStop` 则无条件 commit。### 各 hook 职责@@ -364,6 +364,8 @@ Claude Code 自带 `MEMORY.md` 文件系统,本插件**与之互补**:| `SessionEnd` | Claude Code 会话关闭 | 最后一次 commit || `SubagentStart` | 父 session 通过 Task 工具孵化子 agent | 为子 agent 派生隔离的 OV session ID,写 start state || `SubagentStop` | 子 agent 结束 | 读子 agent transcript → 推到带子 agent peer 身份的隔离 session → commit |+| `PreToolUse` | 原生 `Read` / `Glob` / `Grep` 指向 `viking://` URI | 拒绝该调用,提示 Claude 改用对应的 OpenViking MCP 工具 |+| `PostToolUse` | `Read` 读到 `SKILL.md` 文件 | 可选(默认关闭):OV 有相关 skill 经验记忆时注入经验块 |### 异步写路径@@ -388,7 +390,7 @@ claude-code-memory-plugin/├── .claude-plugin/│ └── plugin.json # plugin manifest├── hooks/-│ └── hooks.json # 7 个 hook 注册+│ └── hooks.json # 9 个 hook 注册├── servers/│ └── mcp-proxy.mjs # stdio -> OpenViking /mcp 桥接├── scripts/diff --git a/examples/codex-memory-plugin/README.md b/examples/codex-memory-plugin/README.mdindex a57c3f614..e180652c5 100644--- a/examples/codex-memory-plugin/README.md+++ b/examples/codex-memory-plugin/README.md@@ -103,13 +103,13 @@ If you don't want the installer touching your rc, do these things yourself:Connection / identity source (applies to hooks, MCP, and `ov` commands run inside Codex):-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.+1. **Default (auto)**: env-var credentials (`OPENVIKING_URL` / `OPENVIKING_BASE_URL`, `OPENVIKING_API_KEY` / `OPENVIKING_BEARER_TOKEN`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, `OPENVIKING_PEER_ID`) win when any is set; otherwise the active `ovcli.conf` is used: `OPENVIKING_CLI_CONFIG_FILE` or `~/.openviking/ovcli.conf`. With no credential env vars set, `ov config switch <name>` changes the active credentials for the CLI, hooks, MCP, and child `ov` commands together.+2. **Forced**: set `OPENVIKING_CREDENTIAL_SOURCE=cli` to force `ovcli.conf`, or `OPENVIKING_CREDENTIAL_SOURCE=env` to force env-var credentials.+3. **Fallback**: without credential env vars or an ovcli config, `ov.conf` is used (`server.url` / `server.root_api_key` plus legacy `codex.*` tuning); then `http://127.0.0.1:1933` unauthenticated.Hooks and the MCP proxy call the same resolver directly, so the model tools and lifecycle hooks follow the same target.-Auth is sent as `Authorization: Bearer <api_key>` to both the REST API (used by hooks) and the `/mcp` endpoint (used by the model).+Auth is sent as `Authorization: Bearer <api_key>` to both the REST API (used by hooks) and the `/mcp` endpoint (used by the model); the hooks also send the same key as `X-API-Key` for compatibility with older servers.By default the plugin derives a peer from the current workspace path using Claude's project-directory naming rule: every non-letter-or-digit character becomes `-`, with no path normalization. For example, `/Users/x/Dev/OpenViking` becomes `-Users-x-Dev-OpenViking`. Hooks pass the effective peer as `peer_id` for captured session messages and as `X-OpenViking-Actor-Peer` for retrieval/filesystem calls; MCP gets the same header mapping.diff --git a/examples/codex-memory-plugin/scripts/config.mjs b/examples/codex-memory-plugin/scripts/config.mjsindex 526144ffb..b8e393d57 100644--- a/examples/codex-memory-plugin/scripts/config.mjs+++ b/examples/codex-memory-plugin/scripts/config.mjs@@ -2,10 +2,12 @@* Shared configuration loader for the Codex OpenViking memory plugin.** Credential source:- * - Default: active ovcli.conf wins when present, so `ov config switch`+ * - Default (auto): env-var credentials win when any credential env var is+ * set; otherwise the active ovcli.conf is used, 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.+ * - Set OPENVIKING_CREDENTIAL_SOURCE=cli to force ovcli.conf, or =env to+ * force env-var credentials.+ * - Without env vars or ovcli.conf, ov.conf/defaults are used.** Tuning resolution remains env vars > ov.conf codex.* > built-in defaults.*diff --git a/examples/memory-plugin-shared/install.sh b/examples/memory-plugin-shared/install.shindex 2881bb1e2..d26f53d46 100644--- a/examples/memory-plugin-shared/install.sh+++ b/examples/memory-plugin-shared/install.sh@@ -158,7 +158,8 @@ Options:--user ID Optional OpenViking user.--statusline Register the Claude Code statusline without asking.--no-statusline Skip the statusline prompt.- --uninstall Remove Cursor/TRAE OpenViking integration files and config.+ --uninstall Remove Cursor/TRAE/TRAE CN/ZCode integration files and config,+ plus any legacy TraeCode CLI hook config.For Codex-format plugins, use the client's plugin uninstall command.--yes, -y Use defaults for prompts when possible.EOFdiff --git a/examples/opencode-plugin/INSTALL-ZH.md b/examples/opencode-plugin/INSTALL-ZH.mdindex 112b250fe..400a3ce44 100644--- a/examples/opencode-plugin/INSTALL-ZH.md+++ b/examples/opencode-plugin/INSTALL-ZH.md@@ -151,8 +151,9 @@ OpenCode 的 `mcp.openviking` 配置。进入新的 OpenCode session 后,可以让 agent 浏览 OpenViking memory,或搜索一个已索引的资源。插件应暴露 OpenViking MCP server,OpenCode 中的工具名会带 `openviking_` 前缀:- `openviking_search`、`openviking_find`-- `openviking_read`、`openviking_list`、`openviking_grep`、`openviking_glob`-- `openviking_remember`、`openviking_add_resource`、`openviking_forget`、`openviking_health`+- `openviking_read`、`openviking_list`、`openviking_tree`、`openviking_grep`、`openviking_glob`+- `openviking_remember`、`openviking_write`、`openviking_edit`、`openviking_add_resource`+- `openviking_list_watches`、`openviking_cancel_watch`、`openviking_forget`、`openviking_health`- `openviking_list_watches`、`openviking_cancel_watch`如果行为异常,先查看运行时文件:@@ -177,8 +178,11 @@ curl http://localhost:1933/health- `openviking_remember`:存储重要事实或决策,供记忆提取- `openviking_read`:读取一个或多个 `viking://` 文件- `openviking_list`:列出 `viking://` 目录+- `openviking_tree`:展示 `viking://` 目录树- `openviking_grep`:精确文本或正则搜索- `openviking_glob`:glob 文件匹配+- `openviking_write`:创建、覆盖或追加 `viking://` 文件+- `openviking_edit`:对 `viking://` 文件做精确字符串替换- `openviking_add_resource`:添加 URL、本地文件、sitemap 或 feed- `openviking_forget`:在用户明确确认后删除 `viking://` URI- `openviking_list_watches` / `openviking_cancel_watch`:查看或取消资源 watchdiff --git a/examples/opencode-plugin/INSTALL.md b/examples/opencode-plugin/INSTALL.mdindex bffbfcb01..c7679eff9 100644--- a/examples/opencode-plugin/INSTALL.md+++ b/examples/opencode-plugin/INSTALL.md@@ -148,8 +148,9 @@ Restart OpenCode after changing plugin or OpenViking configuration.In a new OpenCode session, ask the agent to browse OpenViking memory or search for a known indexed resource. The plugin should expose the OpenViking MCP server, with tools namespaced by OpenCode as `openviking_*`:- `openviking_search`, `openviking_find`-- `openviking_read`, `openviking_list`, `openviking_grep`, `openviking_glob`-- `openviking_remember`, `openviking_add_resource`, `openviking_forget`, `openviking_health`+- `openviking_read`, `openviking_list`, `openviking_tree`, `openviking_grep`, `openviking_glob`+- `openviking_remember`, `openviking_write`, `openviking_edit`, `openviking_add_resource`+- `openviking_list_watches`, `openviking_cancel_watch`, `openviking_forget`, `openviking_health`- `openviking_list_watches`, `openviking_cancel_watch`If anything looks wrong, check the runtime files:@@ -174,8 +175,11 @@ The plugin registers OpenViking's stdio MCP proxy through OpenCode config. The s- `openviking_remember`: store important facts or decisions for memory extraction.- `openviking_read`: read one or more `viking://` files.- `openviking_list`: list a `viking://` directory.+- `openviking_tree`: show a `viking://` directory tree.- `openviking_grep`: exact text or regex search.- `openviking_glob`: glob file matching.+- `openviking_write`: create, overwrite, or append to a `viking://` file.+- `openviking_edit`: exact string replacement in a `viking://` file.- `openviking_add_resource`: add a URL, local file, sitemap, or feed.- `openviking_forget`: delete a `viking://` URI after explicit user confirmation.- `openviking_list_watches` / `openviking_cancel_watch`: inspect or cancel resource watches.diff --git a/examples/opencode-plugin/README.md b/examples/opencode-plugin/README.mdindex 61b5bfdae..2f40d2d47 100644--- a/examples/opencode-plugin/README.md+++ b/examples/opencode-plugin/README.md@@ -191,8 +191,11 @@ OpenCode sees the OpenViking MCP server as `openviking`, so tool names are names- `openviking_remember`: store important facts or decisions for memory extraction.- `openviking_read`: read one or more `viking://` files.- `openviking_list`: list a `viking://` directory.+- `openviking_tree`: show a `viking://` directory tree.- `openviking_grep`: exact text or regex search.- `openviking_glob`: glob file matching.+- `openviking_write`: create, overwrite, or append to a `viking://` file.+- `openviking_edit`: exact string replacement in a `viking://` file.- `openviking_add_resource`: add a URL, local file, sitemap, or feed.- `openviking_forget`: delete a `viking://` URI after explicit user confirmation.- `openviking_list_watches` / `openviking_cancel_watch`: inspect or cancel resource watches.diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.pyindex 8cab3ccf3..c6553146c 100644--- a/openviking/server/mcp_endpoint.py+++ b/openviking/server/mcp_endpoint.py@@ -2,8 +2,9 @@# SPDX-License-Identifier: AGPL-3.0"""MCP (Model Context Protocol) endpoint for OpenViking server.-Exposes tools to Claude Code (or any MCP client) via streamable HTTP:- find, search, read, write, edit, list, tree, remember, add_resource, grep, glob, forget, health+Exposes OpenViking tools (filesystem, retrieval, memory, watch management,+health) to Claude Code (or any MCP client) via streamable HTTP; the+`@mcp.tool` registrations below are the authoritative list.Mounted on the FastAPI app at /mcp. The MCP session manager lifecycle istied to the FastAPI app lifespan (not a sub-app lifespan) so the task group