Skip to content

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

docs: migrate user-facing details and remove historical design notes (#5512)

Zayn Jarvisd9a21bc77bf1
diff --git a/agent-plugins/README.md b/agent-plugins/README.md
index 9c154ea70..93e11a7e8 100644
--- a/agent-plugins/README.md
+++ b/agent-plugins/README.md
@@ -25,7 +25,7 @@ Use `ov-memory-troubleshoot` to trace backward from a memory file to its archive
`openviking-skills` covers the skills stored in OpenViking itself: how to find one with `find(context_type="skill")`, read and follow its `SKILL.md`, create or replace one with the `add_skill` MCP tool, install one from Git or a local folder, share one with the account, and move local skill folders into OpenViking when you ask. This package has no session-start hook, so there is no `<available-skills>` catalog here and the skill has the model search for a skill instead.
-Use `ov-kanban` to run long or multi-agent work through a kanban board in OpenViking. A board holds many tasks; each task is one markdown file (`viking://agent/kanban/<board>/<id>.md`, falling back to `viking://resources/kanban` on servers that reject writes under `viking://agent`) whose header and body are the handoff, so any agent with the `ov` CLI can claim, continue, and write it back. Process detail is folded into `archive/<id>.md` instead of being summarized away, and agents read in layers: board view, task, archive. `references/loop.sh` drives unattended ticks; see the skill's [README](skills/ov-kanban/README.md) for the idea and roadmap, and [docs/design/ov-kanban.md](../docs/design/ov-kanban.md) for design notes.
+Use `ov-kanban` to run long or multi-agent work through a kanban board in OpenViking. A board holds many tasks; each task is one markdown file (`viking://agent/kanban/<board>/<id>.md`, falling back to `viking://resources/kanban` on servers that reject writes under `viking://agent`) whose header and body are the handoff, so any agent with the `ov` CLI can claim, continue, and write it back. Process detail is folded into `archive/<id>.md` instead of being summarized away, and agents read in layers: board view, task, archive. `references/loop.sh` drives unattended ticks; see the skill's [README](skills/ov-kanban/README.md) for the idea, design choices, and roadmap.
Zero npm dependencies; the proxy and tests run on the Node.js standard library (Node 18+ for global `fetch`).
diff --git a/agent-plugins/skills/ov-kanban/README.md b/agent-plugins/skills/ov-kanban/README.md
index 42ffef9f7..885184b5d 100644
--- a/agent-plugins/skills/ov-kanban/README.md
+++ b/agent-plugins/skills/ov-kanban/README.md
@@ -34,10 +34,33 @@ viking://agent/kanban/<board>/<id>.md task
viking://agent/kanban/<board>/archive/<id>.md folded detail
```
-Servers that reject writes under `viking://agent` use
-`viking://resources/kanban`. Design notes, the mapping to PowerContext and
-LoopX, and the rehearsal record are in
-[docs/design/ov-kanban.md](../../../docs/design/ov-kanban.md).
+The skill and `loop.sh` probe `viking://agent/kanban` with `ov stat` / `ov mkdir`.
+Servers that reject that location use `viking://resources/kanban` instead.
+Set `OV_KANBAN_ROOT` to choose a root explicitly. The task protocol does not
+depend on which root is used; a board's URI and ACL define its boundary.
+
+## Design choices
+
+The task file is the handoff: frontmatter records `id`, `status`, `owner`,
+`board`, and `updated`; the body holds Goal, Context, Decisions, Progress,
+Next, Questions, and Log. There is no separate handoff object or status store.
+Replaced plans and decisions, older Log entries, and evidence longer than one
+line move verbatim to the append-only archive. Keep the latest 10 Log entries
+in the task, but archive the older entries before removing them.
+
+| Choice | Reason and limit |
+| --- | --- |
+| One mutable task plus an append-only archive | Replaces separate revision, acknowledgement, and outcome objects. Claiming is recorded in Log; completion is status plus verified Progress. |
+| Any CLI agent executes the task; OpenViking stores it | No separate execution kernel, capability/provider hierarchy, or extension runtime is needed. |
+| A loop bounded by `max_ticks` | Each turn must write back; `needs_user` tasks stop for input. Scheduling, quota management, and self-repair are outside this protocol. |
+| `owner` + `updated`, with a two-hour stale-claim convention | OpenViking writes do not provide compare-and-set. This is coordination by convention, not an atomic lease; concurrent claims can collide. |
+| URI and ACL as the board boundary | A second opaque scope ID would duplicate the existing address and permission model. |
+| Frontmatter queried with `ov grep` | Mirroring status and owner into retrieval tags would require another write and could drift out of sync. |
+| CLI board views | A separate dashboard or Lark projection is deferred until needed. Experience extraction continues through OpenViking's existing `remember` path, outside the task protocol. |
+
+The name `ov-kanban` distinguishes this board from `ov task`, which manages
+server-side asynchronous jobs. A board is the task container; “scope” is
+reserved for the planned repository/directory/branch matching rules.
## Roadmap
@@ -48,4 +71,4 @@ LoopX, and the rehearsal record are in
| Recall on session start | The agent reads the board when the skill triggers. | Hook plugins inject the board view of matching boards at session start. Depends on scoped kanban. |
| Claim-aware loop | `loop.sh` counts every `open` or `in_progress` task as runnable, so a tick can find nothing to claim. | Count `open` tasks, stale claims, and the caller's own claims. |
| Atomic claim | `owner` + `updated` with a 2-hour convention; two agents can claim the same task at once. | Compare-and-set on write, once OpenViking `write` supports it. |
-| `ov compile` | Not supported: compile rejects kanban targets and file sources. | `ov compile --from <board> --to <board> --skill ov-kanban` runs one turn on the server. Blockers are listed in the design doc. |
+| `ov compile` | Not supported: compile rejects kanban targets and file sources. | `ov compile --from <board> --to <board> --skill ov-kanban` runs one turn on the server. It also needs an output tool that rewrites task files in place; the existing compile agent submits a wiki bundle. |
diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts
index 86c3f31a3..841500c91 100644
--- a/docs/.vitepress/config.ts
+++ b/docs/.vitepress/config.ts
@@ -2,7 +2,7 @@ import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { defineConfig, type DefaultTheme } from 'vitepress'
-import { titleFromMarkdown, sidebarSection, localizedSectionSidebarItems, localizedGroupedSidebarItems, localizedReferenceSidebarItems, localizedAboutSidebarItems, designSidebar } from './docs-navigation'
+import { titleFromMarkdown, sidebarSection, localizedSectionSidebarItems, localizedGroupedSidebarItems, localizedReferenceSidebarItems, localizedAboutSidebarItems } from './docs-navigation'
const docsRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const repo = process.env.GITHUB_REPOSITORY || 'volcengine/OpenViking'
@@ -229,8 +229,8 @@ export default defineConfig({
description: 'Open-source context database for AI Agents',
cleanUrls: true,
lastUpdated: true,
- // The existing Markdown corpus links to examples, bot docs, localhost snippets,
- // and historical design notes that are outside the VitePress page tree.
+ // The existing Markdown corpus links to examples, bot docs, and localhost
+ // snippets that are outside the VitePress page tree.
ignoreDeadLinks: true,
// Repository translations and maintainer guides are browsed on GitHub.
srcExclude: ['repository/**'],
@@ -324,8 +324,7 @@ export default defineConfig({
'/en/context-compilation/': localizedGroupedSidebarItems('en', ['guides']),
'/en/api/': localizedReferenceSidebarItems('en'),
'/en/faq/': [sidebarSection('en/faq', 'FAQ', false)],
- '/en/about/': localizedAboutSidebarItems('en'),
- '/design/': designSidebar
+ '/en/about/': localizedAboutSidebarItems('en')
}
}
},
diff --git a/docs/.vitepress/docs-navigation.ts b/docs/.vitepress/docs-navigation.ts
index 4afc995e9..ebcc8768b 100644
--- a/docs/.vitepress/docs-navigation.ts
+++ b/docs/.vitepress/docs-navigation.ts
@@ -13,8 +13,7 @@ const sectionNames: Record<string, string> = {
'context-compilation': 'Context Compilation',
api: 'API Reference',
faq: 'FAQ',
- about: 'About',
- design: 'Design Notes'
+ about: 'About'
}
const zhSectionNames: Record<string, string> = {
@@ -26,8 +25,7 @@ const zhSectionNames: Record<string, string> = {
'context-compilation': '上下文编译',
api: 'API 参考',
faq: '常见问题',
- about: '关于',
- design: '设计文档'
+ about: '关于'
}
export function titleFromMarkdown(filePath: string): string {
@@ -675,11 +673,6 @@ export function localizedAboutSidebarItems(locale: 'en' | 'zh'): DefaultTheme.Si
return [sidebarSection(`${locale}/about`, labels.about, false)]
}
-export const designSidebar: DefaultTheme.SidebarItem[] = [
- sidebarSection('design', sectionNames.design, false)
-]
-
-
// The homepage map uses the same entries, labels and order as article sidebars.
export function documentationSections(locale: 'en' | 'zh') {
const labels = locale === 'zh' ? zhSectionNames : sectionNames
diff --git a/docs/design/agent-evolution-global-switch-design.md b/docs/design/agent-evolution-global-switch-design.md
deleted file mode 100644
index ff746face..000000000
--- a/docs/design/agent-evolution-global-switch-design.md
+++ /dev/null
@@ -1,111 +0,0 @@
-# Global Agent Evolution Switch Design
-
-## Scope
-
-Agent Evolution is controlled by one deployment-level switch for the entire
-OpenViking server instance. All accounts and users served by the same process
-share the same effective value.
-
-The switch controls whether session commits may generate or update these memory
-types:
-
-- `cases`
-- `trajectories`
-- `experiences`
-
-Disabling the switch does not delete existing files and does not prevent
-existing experiences from being searched or read.
-
-## Configuration
-
-Add the switch directly to `ServerConfig`:
-
-```json
-{
- "server": {
- "agent_evolution": {
- "enabled": false
- }
- }
-}
-```
-
-The default is `false`.
-
-`server.user_config_defaults` remains responsible only for existing per-user
-defaults such as add targets. Agent Evolution is no longer part of active
-`UserConfig` resolution.
-
-This setting belongs to the HTTP server deployment surface. A directly
-constructed `SessionService` retains its enabled default for internal service
-callers that do not load `ServerConfig`.
-
-## Commit Behavior
-
-`SessionService` passes the deployment-level Agent Evolution configuration into
-each `Session`. A commit applies the global value after validating the
-session-level `memory_policy`:
-
-- When enabled, the session policy remains authoritative. A session may still
- exclude `cases`, `trajectories`, or `experiences`.
-- When disabled, the commit removes all three Agent Evolution memory types from
- the effective policy. A session cannot enable them through `memory_policy`.
-
-Phase 1 stores the effective boolean and skip reason in archive metadata.
-Asynchronous Phase 2 reads that snapshot, so normal queue processing and direct
-recovery of that archive use the value accepted at commit time.
-
-When a later commit rolls earlier failed archives into one recovery batch, the
-entire batch uses the triggering archive's snapshot. OpenViking keeps one
-extraction policy per batch instead of splitting the merged conversation across
-different Agent Evolution settings. Therefore, changing the deployment setting
-before a later recovery commit can affect replayed messages from earlier failed
-archives.
-
-Archives created before the snapshot field existed preserve the historical
-enabled behavior during recovery.
-
-## Removed User-Level Surface
-
-Remove Agent Evolution from the active per-user configuration and resolution
-logic. Retain a deprecated parse-only schema field so existing
-`user_config.json` files remain loadable; its value is ignored.
-
-Remove the user-level management surfaces introduced by the current branch:
-
-- `GET /api/v1/user-settings/memory`
-- `PATCH /api/v1/user-settings/memory`
-- Python SDK memory-setting methods
-- `ov user-settings memory`
-- `ov user-settings set-memory`
-- Agent Evolution fields accepted during account or user creation
-
-Existing stored `agent_evolution` fields are ignored after upgrade. They do not
-override the deployment-level setting.
-
-## Compatibility
-
-- Existing experiences remain readable and searchable.
-- Directly constructed services preserve their enabled default because they do
- not have the HTTP server configuration surface.
-- Existing user config files containing `agent_evolution` continue to parse,
- preventing an upgrade from breaking users that already wrote the branch-era
- configuration.
-- Session-level `memory_policy` remains supported as an allow-list below the
- global switch.
-- Queue payload structure remains unchanged; the commit-time decision stays in
- archive metadata.
-
-## Verification
-
-Tests cover:
-
-- Default global value is disabled.
-- Explicit global enablement produces Agent Evolution memory when the session
- policy permits it.
-- Global disablement cannot be bypassed by session `memory_policy`.
-- Different users in one server receive the same effective value.
-- Existing user config with the deprecated field loads but does not affect the
- result.
-- Phase 2 uses the archived commit-time value.
-- Existing experiences remain readable while production is disabled.
diff --git a/docs/design/agent-evolution-global-switch-implementation-plan.md b/docs/design/agent-evolution-global-switch-implementation-plan.md
deleted file mode 100644
index f79ebb324..000000000
--- a/docs/design/agent-evolution-global-switch-implementation-plan.md
+++ /dev/null
@@ -1,391 +0,0 @@
-# Global Agent Evolution Switch Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Replace the per-user Agent Evolution setting with one deployment-level switch shared by every account and user in an OpenViking server instance.
-
-**Architecture:** `ServerConfig.agent_evolution.enabled` is the only active Agent Evolution setting for HTTP server deployments. `SessionService` snapshots it into each `Session`; commit Phase 1 stores the effective value in archive metadata and Phase 2 consumes that snapshot. Directly constructed services retain the enabled default because they do not load `ServerConfig`. The former user field remains parse-only for compatibility, while user-facing management APIs, clients, and CLI commands are removed.
-
-**Tech Stack:** Python 3.10+, Pydantic v2, FastAPI, pytest, Rust/clap CLI.
-
----
-
-### Task 1: Define the global configuration contract
-
-**Files:**
-- Modify: `openviking/server/config.py`
-- Modify: `openviking/server/user_config.py`
-- Test: `tests/server/test_agent_evolution_global_setting.py`
-
-- [ ] **Step 1: Replace user-resolution tests with global configuration tests**
-
-Add tests that assert:
-
-```python
-def test_agent_evolution_is_disabled_by_default():
- assert ServerConfig().agent_evolution.enabled is False
-
-
-def test_agent_evolution_can_be_enabled_for_the_server():
- config = ServerConfig.model_validate(
- {"agent_evolution": {"enabled": True}}
- )
- assert config.agent_evolution.enabled is True
-
-
-def test_deprecated_user_agent_evolution_value_is_ignored():
- user_config = UserConfig.model_validate(
- {"agent_evolution": {"enabled": True}}
- )
- assert user_config.agent_evolution.enabled is True
- assert "agent_evolution" not in user_config.model_dump(exclude_none=True)
-```
-
-- [ ] **Step 2: Run the tests and verify they fail**
-
-Run:
-
-```bash
-uv run pytest -q --no-cov --tb=short tests/server/test_agent_evolution_global_setting.py
-```
-
-Expected: failures because `ServerConfig.agent_evolution` does not exist and the user field is still active.
-
-- [ ] **Step 3: Add the global model and make the old user field parse-only**
-
-Implement:
-
-```python
-class AgentEvolutionConfig(BaseModel):
- enabled: bool = False
-
- model_config = {"extra": "forbid"}
-
-
-class DeprecatedUserAgentEvolutionConfig(BaseModel):
- enabled: Optional[bool] = None
-
- model_config = {"extra": "forbid"}
-
-
-class UserConfig(BaseModel):
- add_targets: AddTargetsConfig = Field(default_factory=AddTargetsConfig)
- agent_evolution: DeprecatedUserAgentEvolutionConfig = Field(
- default_factory=DeprecatedUserAgentEvolutionConfig,
- exclude=True,
- )
-
-
-class ServerConfig(BaseModel):
- agent_evolution: AgentEvolutionConfig = Field(default_factory=AgentEvolutionConfig)
-```
-
-Remove `ResolvedMemorySettings`, `write_user_memory_settings()`,
-`resolve_memory_settings()`, and `public_memory_settings()` from
-`openviking/server/user_config.py`.
-
-- [ ] **Step 4: Run the configuration tests**
-
-Run:
-
-```bash
-uv run pytest -q --no-cov --tb=short tests/server/test_agent_evolution_global_setting.py
-```
-
-Expected: all remaining global configuration and compatibility tests pass.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add openviking/server/config.py openviking/server/user_config.py tests/server/test_agent_evolution_global_setting.py
-git commit -m "refactor(agent-evolution): use global configuration"
-```
-
-### Task 2: Apply the global switch to session commit
-
-**Files:**
-- Modify: `openviking/server/app.py`
-- Modify: `openviking/service/session_service.py`
-- Modify: `openviking/session/session.py`
-- Modify: `tests/unit/session/test_agent_evolution_policy.py`
-- Modify: `tests/unit/session/test_session_commit_resume.py`
-- Modify: `tests/session/test_session_commit.py`
-
-- [ ] **Step 1: Add failing global-switch session tests**
-
-Cover these behaviors:
-
-```python
-def test_disabled_global_switch_removes_agent_memory_types():
- policy = _apply_agent_evolution_setting(
- MemoryPolicy.default(),
- agent_evolution_enabled=False,
- )
- assert AGENT_EVOLUTION_MEMORY_TYPES.isdisjoint(policy.memory_types)
-
-
-async def test_commit_uses_global_enabled_value(session_with_messages):
- session_with_messages._agent_evolution_enabled = True
- result = await session_with_messages.commit_async()
- task = await _wait_for_task(result["task_id"])
- assert task["result"]["agent_evolution_enabled"] is True
-
-
-async def test_phase2_uses_archived_global_value(session):
- archive_meta = {
- "agent_evolution": {
- "enabled": True,
- "skip_reason": None,
- }
- }
- session._agent_evolution_enabled = False
- await session.resume_queued_commit(
- _queued_commit_with_archive_meta(archive_meta)
- )
- assert (
- session._run_memory_extraction.await_args.kwargs[
- "agent_evolution_enabled"
- ]
- is True
- )
-```
-
-- [ ] **Step 2: Run the focused tests and verify they fail**
-
-Run:
-
-```bash
-uv run pytest -q --no-cov --tb=short \
- tests/unit/session/test_agent_evolution_policy.py \
- tests/unit/session/test_session_commit_resume.py \
- tests/session/test_session_commit.py
-```
-
-Expected: failures because sessions still resolve per-user settings.
-
-- [ ] **Step 3: Pass the deployment value into sessions**
-
-In `SessionService`, replace `_user_config_defaults` with:
-
-```python
-# Direct-service default. HTTP app setup overrides it from
-# ServerConfig, whose default is false.
-self._agent_evolution_enabled = True
-
-def set_agent_evolution_config(self, config: AgentEvolutionConfig) -> None:
- self._agent_evolution_enabled = config.enabled
-```
-
-Pass `agent_evolution_enabled=self._agent_evolution_enabled` when constructing
-`Session`, and pass the same value to manual extraction.
-
-In `openviking/server/app.py`, configure the service with:
-
-```python
-sessions.set_agent_evolution_config(config.agent_evolution)
-```
-
-- [ ] **Step 4: Remove per-user resolution from commit**
-
-In `Session.__init__`, store:
-
-```python
-self._agent_evolution_enabled = bool(agent_evolution_enabled)
-```
-
-In `commit_async`, derive the effective policy directly from that value:
-
-```python
-agent_evolution_enabled = self._agent_evolution_enabled
-effective_policy = _apply_agent_evolution_setting(
- effective_policy,
- agent_evolution_enabled=agent_evolution_enabled,
-)
-```
-
-Remove the user-config exception path and `user_config_error` from new archive
-metadata and task results. Keep Phase 2 compatibility reads for old archive
-metadata, but do not consult current configuration during resume.
-
-- [ ] **Step 5: Run the focused session tests**
-
-Run:
-
-```bash
-uv run pytest -q --no-cov --tb=short \
- tests/unit/session/test_agent_evolution_policy.py \
- tests/unit/session/test_session_commit_resume.py \
- tests/session/test_session_commit.py
-```
-
-Expected: all tests pass.
-
-- [ ] **Step 6: Commit**
-
-```bash
-git add openviking/server/app.py openviking/service/session_service.py \
- openviking/session/session.py tests/unit/session/test_agent_evolution_policy.py \
- tests/unit/session/test_session_commit_resume.py tests/session/test_session_commit.py
-git commit -m "feat(agent-evolution): apply global commit switch"
-```
-
-### Task 3: Remove user-level management surfaces
-
-**Files:**
-- Modify: `openviking/server/routers/admin.py`
-- Modify: `openviking/server/routers/user_settings.py`
-- Modify: `sdk/python/openviking_sdk/client.py`
-- Modify: `crates/ov_cli/src/commands/mod.rs`
-- Delete: `crates/ov_cli/src/commands/user_settings.rs`
-- Modify: `crates/ov_cli/src/main.rs`
-- Modify: `crates/ov_cli/src/help_ui.rs`
-- Delete: `tests/client/test_user_memory_settings.py`
-- Modify: `sdk/python/tests/test_async_client_behaviors.py`
-- Modify: `tests/server/test_admin_api.py`
-
-- [ ] **Step 1: Change API tests to assert the user-level endpoint is absent**
-
-Add:
-
-```python
-async def test_agent_evolution_user_endpoint_is_not_registered(client):
- response = await client.get("/api/v1/user-settings/memory")
- assert response.status_code == 404
-```
-
-Remove tests that patch or retrieve the former user-level setting.
-
-- [ ] **Step 2: Run API/client tests and verify they fail**
-
-Run:
-
-```bash
-uv run pytest -q --no-cov --tb=short \
- tests/server/test_agent_evolution_global_setting.py \
- sdk/python/tests/test_async_client_behaviors.py
-```
-
-Expected: the endpoint and client methods still exist.
-
-- [ ] **Step 3: Remove the Python and HTTP surfaces**
-
-Delete the memory request model and `/user-settings/memory` routes. Remove
-`get_memory_settings()` and `patch_memory_settings()` from HTTP and SDK
-clients. Remove Agent Evolution handling from account
-and user creation; deprecated user input remains accepted by `UserConfig` but
-is ignored.
-
-- [ ] **Step 4: Remove the Rust CLI commands**
-
-Delete the `user-settings` command group, dispatcher, help entries, parser
-tests, and `commands/user_settings.rs`.
-
-- [ ] **Step 5: Run Python and Rust tests**
-
-Run:
-
-```bash
-uv run pytest -q --no-cov --tb=short \
- tests/server/test_agent_evolution_global_setting.py \
- tests/client/test_base_client_compatibility.py \
- sdk/python/tests/test_async_client_behaviors.py
-cargo test --manifest-path crates/ov_cli/Cargo.toml user_settings
-cargo test --manifest-path crates/ov_cli/Cargo.toml plain_help
-```
-
-Expected: Python tests pass; the filtered Rust suites complete without a
-failure.
-
-- [ ] **Step 6: Commit**
-
-```bash
-git add -A crates/ov_cli openviking sdk/python tests
-git commit -m "refactor(agent-evolution): remove user settings surface"
-```
-
-### Task 4: Update public configuration documentation
-
-**Files:**
-- Delete: `docs/design/agent-evolution-user-configuration.md`
-- Modify: `docs/en/guides/01-configuration.md`
-- Modify: `docs/zh/guides/01-configuration.md`
-- Modify or delete: `docs/en/api/12-user-settings.md`
-- Modify or delete: `docs/zh/api/12-user-settings.md`
-- Modify: `docs/en/api/01-overview.md`
-- Modify: `docs/zh/api/01-overview.md`
-- Modify: `docs/.vitepress/config.ts`
-- Modify: `docs/scripts/check-api-reference.mjs`
-
-- [ ] **Step 1: Replace user-setting examples with global server configuration**
-
-Document:
-
-```json
-{
- "server": {
- "agent_evolution": {
- "enabled": false
- }
- }
-}
-```
-
-State that the value applies to every account and user served by the process,
-controls only future production, and does not hide or delete existing files.
-
-- [ ] **Step 2: Remove API references for `/user-settings/memory`**
-
-Keep existing add-location documentation only where it existed independently
-of this branch. Remove navigation entries introduced solely for the deleted
-memory-setting API.
-
-- [ ] **Step 3: Run documentation checks**
-
-Run:
-
-```bash
-npm --prefix docs run docs:check-api-reference
-git diff --check
-```
-
-Expected: documentation validation and whitespace checks pass.
-
-- [ ] **Step 4: Commit**
-
-```bash
-git add -A docs
-git commit -m "docs(agent-evolution): document global switch"
-```
-
-### Task 5: Full regression and PR review
-
-**Files:**
-- Test only
-
-- [ ] **Step 1: Run the focused Python suite**
-
-```bash
-uv run pytest -q --no-cov --tb=short \
- tests/unit/session/test_session_commit_resume.py \
- tests/storage/test_session_commit_processor_identity.py \
- tests/server/test_agent_evolution_global_setting.py \
- tests/unit/session/test_agent_evolution_policy.py \
- tests/unit/usage_reporter \
- tests/session/test_compressor_v3.py \
- tests/session/test_session_commit.py
-```
-
-- [ ] **Step 2: Run formatting and static checks**
-
-```bash
-uv run ruff check openviking tests sdk/python
-uv run ruff format --check openviking tests sdk/python
-cargo fmt --manifest-path crates/ov_cli/Cargo.toml --check
-git diff --check
-```
-
-- [ ] **Step 3: Push and run `review-pr`**
-
-Push the branch, review PR #3223 against `main`, fix every blocking finding
-with a failing regression test first, and repeat until the current HEAD has no
-blocking findings.
diff --git a/docs/design/assets/tau2-train-eval-architecture.png b/docs/design/assets/tau2-train-eval-architecture.png
deleted file mode 100644
index 020fe6cbd..000000000
Binary files a/docs/design/assets/tau2-train-eval-architecture.png and /dev/null differ
diff --git a/docs/design/assets/tau2-train-eval-architecture.svg b/docs/design/assets/tau2-train-eval-architecture.svg
deleted file mode 100644
index d9151bc8b..000000000
--- a/docs/design/assets/tau2-train-eval-architecture.svg
+++ /dev/null
@@ -1,169 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="760" viewBox="0 0 1280 760" role="img" aria-labelledby="title desc">
- <title id="title">tau2 接入 OpenViking 新训练评测框架架构图</title>
- <desc id="desc">展示 tau2 runtime service、batch train/eval runner 和 OpenViking server 之间的 case 查询、rollout 执行、session.commit 训练写入和当前 memories 读取关系。</desc>
- <defs>
- <marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse">
- <path d="M 0 0 L 10 5 L 0 10 z" fill="#334155"/>
- </marker>
- <marker id="arrowBlue" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse">
- <path d="M 0 0 L 10 5 L 0 10 z" fill="#2563eb"/>
- </marker>
- <marker id="arrowGreen" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse">
- <path d="M 0 0 L 10 5 L 0 10 z" fill="#16a34a"/>
- </marker>
- <marker id="arrowOrange" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse">
- <path d="M 0 0 L 10 5 L 0 10 z" fill="#ea580c"/>
- </marker>
- <style>
- .bg { fill: #f8fafc; }
- .panel { fill: #ffffff; stroke-width: 2; rx: 18; }
- .tau2 { stroke: #2563eb; }
- .runner { stroke: #16a34a; }
- .ov { stroke: #ea580c; }
- .box { fill: #f8fafc; stroke: #94a3b8; stroke-width: 1.5; rx: 10; }
- .boxBlue { fill: #eff6ff; stroke: #60a5fa; }
- .boxGreen { fill: #f0fdf4; stroke: #4ade80; }
- .boxOrange { fill: #fff7ed; stroke: #fb923c; }
- .store { fill: #fffbeb; stroke: #f59e0b; stroke-width: 1.8; rx: 10; }
- .title { font: 700 24px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; fill: #0f172a; }
- .panelTitle { font: 700 18px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; fill: #0f172a; }
- .text { font: 600 14px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; fill: #1e293b; }
- .small { font: 500 12px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; fill: #475569; }
- .edge { fill: none; stroke: #334155; stroke-width: 2; marker-end: url(#arrow); }
- .edgeBlue { fill: none; stroke: #2563eb; stroke-width: 2.5; marker-end: url(#arrowBlue); }
- .edgeGreen { fill: none; stroke: #16a34a; stroke-width: 2.5; marker-end: url(#arrowGreen); }
- .edgeOrange { fill: none; stroke: #ea580c; stroke-width: 2.5; marker-end: url(#arrowOrange); }
- .edgeDashed { fill: none; stroke: #2563eb; stroke-width: 2.5; stroke-dasharray: 8 6; marker-end: url(#arrowBlue); }
- .label { font: 600 12px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; fill: #334155; }
- .legendText { font: 500 12px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; fill: #475569; }
- </style>
- </defs>
-
- <rect class="bg" x="0" y="0" width="1280" height="760"/>
- <text class="title" x="40" y="46">tau2 接入 OpenViking 新训练评测框架</text>
- <text class="small" x="40" y="70">baseline_eval → train epoch(s) → final_eval;tau2 service 执行 rollout 时读取 OV memories,训练写入通过 session.commit 回到 OV。</text>
-
- <!-- Panels -->
- <rect class="panel tau2" x="40" y="105" width="360" height="540" rx="18"/>
- <text class="panelTitle" x="65" y="138">Tau2 Runtime Service :1944</text>
- <text class="small" x="65" y="160">依赖 tau2 / VikingBot / 环境工具</text>
-
- <rect class="panel runner" x="460" y="105" width="360" height="540" rx="18"/>
- <text class="panelTitle" x="485" y="138">Batch Train/Eval Runner</text>
- <text class="small" x="485" y="160">通用训练评测编排,不直接依赖 tau2 runtime</text>
-
- <rect class="panel ov" x="880" y="105" width="360" height="540" rx="18"/>
- <text class="panelTitle" x="905" y="138">OpenViking Server :1933</text>
- <text class="small" x="905" y="160">session.commit / memory extraction / experience update</text>
-
- <!-- Tau2 boxes -->
- <rect class="box boxBlue" x="80" y="195" width="280" height="58" rx="10"/>
- <text class="text" x="220" y="220" text-anchor="middle">tau2 data</text>
- <text class="small" x="220" y="239" text-anchor="middle">tasks / split / domain fixtures</text>
-
- <rect class="box boxBlue" x="80" y="285" width="280" height="58" rx="10"/>
- <text class="text" x="220" y="310" text-anchor="middle">POST /v1/cases/query</text>
- <text class="small" x="220" y="329" text-anchor="middle">返回通用 Case JSON</text>
-
- <rect class="box boxBlue" x="80" y="375" width="280" height="58" rx="10"/>
- <text class="text" x="220" y="400" text-anchor="middle">POST /v1/rollouts/execute</text>
- <text class="small" x="220" y="419" text-anchor="middle">执行 case batch</text>
-
- <rect class="box boxBlue" x="80" y="465" width="280" height="70" rx="10"/>
- <text class="text" x="220" y="492" text-anchor="middle">Tau2RolloutExecutor</text>
- <text class="small" x="220" y="511" text-anchor="middle">VikingBot + tau2 env tools</text>
- <text class="small" x="220" y="529" text-anchor="middle">生成 Message / ToolPart</text>
-
- <rect class="box boxBlue" x="80" y="565" width="280" height="58" rx="10"/>
- <text class="text" x="220" y="590" text-anchor="middle">RubricEvaluation</text>
- <text class="small" x="220" y="609" text-anchor="middle">reward / passed / feedback</text>
-
- <!-- Runner boxes -->
- <rect class="box boxGreen" x="500" y="195" width="280" height="58" rx="10"/>
- <text class="text" x="640" y="220" text-anchor="middle">RemoteCaseLoader</text>
- <text class="small" x="640" y="239" text-anchor="middle">拉取 train/test cases</text>
-
- <rect class="box boxGreen" x="500" y="285" width="280" height="58" rx="10"/>
- <text class="text" x="640" y="310" text-anchor="middle">OfflinePolicyOptimizationPipeline</text>
- <text class="small" x="640" y="329" text-anchor="middle">baseline_eval / train / final_eval</text>
-
- <rect class="box boxGreen" x="500" y="375" width="280" height="58" rx="10"/>
- <text class="text" x="640" y="400" text-anchor="middle">RemoteRolloutExecutor</text>
- <text class="small" x="640" y="419" text-anchor="middle">HTTP 调用 tau2 rollout service</text>
-
- <rect class="box boxGreen" x="500" y="475" width="280" height="58" rx="10"/>
- <text class="text" x="640" y="500" text-anchor="middle">SessionCommitPolicyTrainer</text>
- <text class="small" x="640" y="519" text-anchor="middle">CaseSpec + Rollout + OutcomeEvaluation</text>
-
- <rect class="box boxGreen" x="500" y="565" width="280" height="58" rx="10"/>
- <text class="text" x="640" y="590" text-anchor="middle">Report</text>
- <text class="small" x="640" y="609" text-anchor="middle">accuracy / avg_reward / delta</text>
-
- <!-- OV boxes -->
- <rect class="box boxOrange" x="920" y="190" width="280" height="56" rx="10"/>
- <text class="text" x="1060" y="215" text-anchor="middle">session.commit</text>
- <text class="small" x="1060" y="234" text-anchor="middle">接收训练 rollout</text>
-
- <rect class="box boxOrange" x="920" y="270" width="280" height="56" rx="10"/>
- <text class="text" x="1060" y="295" text-anchor="middle">SessionCompressorV3</text>
- <text class="small" x="1060" y="314" text-anchor="middle">commit 后台抽取与训练入口</text>
-
- <rect class="box boxOrange" x="920" y="350" width="280" height="56" rx="10"/>
- <text class="text" x="1060" y="375" text-anchor="middle">TrajectoryRolloutAnalyzer</text>
- <text class="small" x="1060" y="394" text-anchor="middle">extract trajectories</text>
-
- <rect class="box boxOrange" x="920" y="430" width="280" height="56" rx="10"/>
- <text class="text" x="1060" y="455" text-anchor="middle">ExperienceGradientEstimator</text>
- <text class="small" x="1060" y="474" text-anchor="middle">trajectory → gradient</text>
-
- <rect class="box boxOrange" x="920" y="510" width="280" height="56" rx="10"/>
- <text class="text" x="1060" y="535" text-anchor="middle">PatchMergePolicyOptimizer</text>
- <text class="small" x="1060" y="554" text-anchor="middle">全局 merge / split / delete plan</text>
-
- <rect class="store" x="920" y="590" width="280" height="56" rx="10"/>
- <text class="text" x="1060" y="615" text-anchor="middle">memories / experiences</text>
- <text class="small" x="1060" y="634" text-anchor="middle">PolicyStore / latest experience set</text>
-
- <!-- Internal arrows -->
- <path class="edgeBlue" d="M220 253 L220 285"/>
- <path class="edgeBlue" d="M220 433 L220 465"/>
- <path class="edgeBlue" d="M220 535 L220 565"/>
-
- <path class="edgeGreen" d="M640 253 L640 285"/>
- <path class="edgeGreen" d="M640 343 L640 375"/>
- <path class="edgeGreen" d="M640 433 L640 475"/>
-
- <path class="edgeOrange" d="M1060 246 L1060 270"/>
- <path class="edgeOrange" d="M1060 326 L1060 350"/>
- <path class="edgeOrange" d="M1060 406 L1060 430"/>
- <path class="edgeOrange" d="M1060 486 L1060 510"/>
- <path class="edgeOrange" d="M1060 566 L1060 590"/>
-
- <!-- Cross-panel arrows -->
- <path class="edgeGreen" d="M500 224 C445 224 420 314 360 314"/>
- <text class="label" x="388" y="254" text-anchor="middle">query cases</text>
-
- <path class="edgeGreen" d="M500 404 C445 404 420 404 360 404"/>
- <text class="label" x="429" y="392" text-anchor="middle">execute rollout</text>
-
- <path class="edgeBlue" d="M360 594 C420 594 445 404 500 404"/>
- <text class="label" x="430" y="575" text-anchor="middle">Rollout + evaluation</text>
-
- <path class="edgeOrange" d="M780 504 C835 504 860 218 920 218"/>
- <text class="label" x="850" y="355" text-anchor="middle">session.commit</text>
-
- <path class="edgeDashed" d="M360 500 C560 690 800 690 920 618"/>
- <text class="label" x="650" y="704" text-anchor="middle">read current OV memories via VikingBot / openviking tools</text>
-
- <path class="edgeGreen" d="M780 594 C840 594 855 618 920 618"/>
- <text class="label" x="852" y="590" text-anchor="middle">final_eval sees latest experiences</text>
-
- <!-- Legend -->
- <rect x="40" y="685" width="1200" height="44" rx="12" fill="#ffffff" stroke="#cbd5e1"/>
- <line x1="70" y1="707" x2="120" y2="707" class="edgeGreen"/>
- <text class="legendText" x="132" y="711">runner 编排调用</text>
- <line x1="270" y1="707" x2="320" y2="707" class="edgeOrange"/>
- <text class="legendText" x="332" y="711">训练写入链路</text>
- <line x1="470" y1="707" x2="520" y2="707" class="edgeDashed"/>
- <text class="legendText" x="532" y="711">rollout 执行时读取当前 OpenViking memories</text>
-</svg>
diff --git a/docs/design/assets/train-execution-details.png b/docs/design/assets/train-execution-details.png
deleted file mode 100644
index 8b9baeb36..000000000
Binary files a/docs/design/assets/train-execution-details.png and /dev/null differ
diff --git a/docs/design/assets/train-execution-details.svg b/docs/design/assets/train-execution-details.svg
deleted file mode 100644
index 502e01c5e..000000000
--- a/docs/design/assets/train-execution-details.svg
+++ /dev/null
@@ -1,187 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" width="1480" height="900" viewBox="0 0 1480 900" role="img" aria-labelledby="title desc">
- <title id="title">OpenViking session.train 训练执行细节图</title>
- <desc id="desc">展示训练框架中的输入、并行 rollout、并行信号抽取、串行 policy update,以及 trajectories、experiences、remote service、session archive 等存储关系。</desc>
- <defs>
- <marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#334155"/></marker>
- <marker id="arrowBlue" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#2563eb"/></marker>
- <marker id="arrowGreen" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#16a34a"/></marker>
- <marker id="arrowOrange" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#ea580c"/></marker>
- <style>
- .bg{fill:#f8fafc}.title{font:700 25px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;fill:#0f172a}.subtitle{font:500 13px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;fill:#475569}.panel{fill:#fff;stroke:#cbd5e1;stroke-width:2;rx:18}.panelInput{stroke:#2563eb}.panelSignal{stroke:#16a34a}.panelUpdate{stroke:#ea580c}.panelStore{stroke:#64748b}.panelTitle{font:700 17px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;fill:#0f172a}.tag{font:700 12px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;fill:#fff}.tagBlue{fill:#2563eb}.tagGreen{fill:#16a34a}.tagOrange{fill:#ea580c}.box{fill:#f8fafc;stroke:#94a3b8;stroke-width:1.5;rx:10}.boxBlue{fill:#eff6ff;stroke:#60a5fa}.boxGreen{fill:#f0fdf4;stroke:#4ade80}.boxOrange{fill:#fff7ed;stroke:#fb923c}.boxLLM{fill:#fef2f2;stroke:#ef4444;stroke-width:2.5}.boxPurple{fill:#faf5ff;stroke:#c084fc}.data{fill:#fefce8;stroke:#eab308;stroke-width:1.5;rx:999}.store{fill:#f1f5f9;stroke:#64748b;stroke-width:1.8;rx:10}.text{font:700 14px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;fill:#1e293b}.small{font:500 12px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;fill:#475569}.tiny{font:500 11px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;fill:#64748b}.edge{fill:none;stroke:#334155;stroke-width:2;marker-end:url(#arrow)}.edgeBlue{fill:none;stroke:#2563eb;stroke-width:2.5;marker-end:url(#arrowBlue)}.edgeGreen{fill:none;stroke:#16a34a;stroke-width:2.5;marker-end:url(#arrowGreen)}.edgeOrange{fill:none;stroke:#ea580c;stroke-width:2.5;marker-end:url(#arrowOrange)}.edgeDashed{fill:none;stroke:#64748b;stroke-width:2;stroke-dasharray:8 6;marker-end:url(#arrow)}.label{font:600 12px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;fill:#334155}.mono{font:600 11px ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono",monospace;fill:#334155}.llm{fill:#fee2e2;stroke:#ef4444;stroke-width:1.5;rx:999}.llmText{font:800 11px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;fill:#991b1b}
- </style>
- </defs>
-
- <rect class="bg" width="1480" height="900"/>
- <text class="title" x="40" y="44">OpenViking session.train 训练执行细节</text>
- <text class="subtitle" x="40" y="68">Domain model 作为流程中的数据产物出现;图中标明哪些阶段并行、哪些阶段被 ExperienceSet.lock() 串行化,以及每个阶段读写哪些存储。</text>
-
- <!-- Input panel -->
- <rect class="panel panelInput" x="40" y="105" width="330" height="430" rx="18"/>
- <text class="panelTitle" x="65" y="138">1. Input / Rollout</text>
- <rect class="tagBlue" x="250" y="116" width="88" height="24" rx="12"/><text class="tag" x="294" y="133" text-anchor="middle">parallel</text>
-
- <rect class="box boxPurple" x="75" y="170" width="255" height="64" rx="10"/>
- <text class="text" x="202" y="196" text-anchor="middle">CaseLoader</text>
- <text class="small" x="202" y="215" text-anchor="middle">ListCaseLoader / RemoteCaseLoader</text>
-
- <rect class="data" x="102" y="260" width="200" height="40" rx="20"/>
- <text class="text" x="202" y="285" text-anchor="middle">Case[]</text>
-
- <rect class="box boxBlue" x="75" y="326" width="255" height="64" rx="10"/>
- <text class="text" x="202" y="352" text-anchor="middle">PolicySnapshotter</text>
- <text class="small" x="202" y="371" text-anchor="middle">snapshot current ExperienceSet</text>
-
- <rect class="box boxBlue" x="75" y="416" width="255" height="72" rx="10"/>
- <text class="text" x="202" y="442" text-anchor="middle">RolloutExecutor.execute</text>
- <text class="small" x="202" y="461" text-anchor="middle">case batch can run concurrently</text>
- <text class="tiny" x="202" y="480" text-anchor="middle">Remote executor / agent loop / simulator</text>
-
- <!-- Signal panel -->
- <rect class="panel panelSignal" x="410" y="105" width="390" height="430" rx="18"/>
- <text class="panelTitle" x="435" y="138">2. Learning Signal Extraction</text>
- <rect class="tagGreen" x="665" y="116" width="88" height="24" rx="12"/><text class="tag" x="709" y="133" text-anchor="middle">parallel</text>
-
- <rect class="data" x="505" y="170" width="200" height="40" rx="20"/>
- <text class="text" x="605" y="195" text-anchor="middle">Rollout[]</text>
-
- <rect class="box boxGreen boxLLM" x="455" y="235" width="300" height="72" rx="10"/>
- <text class="text" x="605" y="261" text-anchor="middle">RolloutAnalyzer.analyze</text>
- <text class="small" x="605" y="280" text-anchor="middle">parallel per rollout · LLM ExtractLoop</text>
- <text class="tiny" x="605" y="299" text-anchor="middle">uses rollout.evaluation / evaluator feedback</text>
-
- <rect class="llm" x="688" y="224" width="56" height="20" rx="10"/>
- <text class="llmText" x="716" y="238" text-anchor="middle">LLM</text>
-
- <rect class="data" x="485" y="335" width="240" height="44" rx="22"/>
- <text class="text" x="605" y="362" text-anchor="middle">RolloutAnalysis[]</text>
-
- <rect class="box boxGreen boxLLM" x="455" y="405" width="300" height="72" rx="10"/>
- <text class="text" x="605" y="431" text-anchor="middle">GradientEstimator.estimate</text>
- <text class="small" x="605" y="450" text-anchor="middle">parallel per analysis · LLM ExtractLoop</text>
- <text class="tiny" x="605" y="469" text-anchor="middle">proposes experience operations</text>
-
- <rect class="llm" x="688" y="394" width="56" height="20" rx="10"/>
- <text class="llmText" x="716" y="408" text-anchor="middle">LLM</text>
-
- <!-- Update panel -->
- <rect class="panel panelUpdate" x="840" y="105" width="395" height="650" rx="18"/>
- <text class="panelTitle" x="865" y="138">3. Policy Update Transaction</text>
- <rect class="tagOrange" x="1110" y="116" width="96" height="24" rx="12"/><text class="tag" x="1158" y="133" text-anchor="middle">serialized</text>
-
- <rect class="data" x="925" y="170" width="225" height="44" rx="22"/>
- <text class="text" x="1037" y="197" text-anchor="middle">SemanticGradient[]</text>
-
- <rect class="box boxOrange" x="895" y="242" width="285" height="58" rx="10"/>
- <text class="text" x="1037" y="267" text-anchor="middle">ExperienceSet.lock()</text>
- <text class="small" x="1037" y="286" text-anchor="middle">wait indefinitely; serialize writers</text>
-
- <rect class="box boxOrange" x="895" y="322" width="285" height="58" rx="10"/>
- <text class="text" x="1037" y="347" text-anchor="middle">ExperienceSet.reload()</text>
- <text class="small" x="1037" y="366" text-anchor="middle">read latest experiences under lock</text>
-
- <rect class="box boxOrange boxLLM" x="895" y="402" width="285" height="74" rx="10"/>
- <text class="text" x="1037" y="429" text-anchor="middle">PatchMergePolicyOptimizer.plan</text>
- <text class="small" x="1037" y="448" text-anchor="middle">serialized · LLM ExtractLoop</text>
- <text class="tiny" x="1037" y="467" text-anchor="middle">merge / split / delete via PatchMergeContextProvider</text>
-
- <rect class="llm" x="1108" y="382" width="56" height="20" rx="10"/>
- <text class="llmText" x="1136" y="396" text-anchor="middle">LLM</text>
-
- <rect class="data" x="925" y="505" width="225" height="44" rx="22"/>
- <text class="text" x="1037" y="532" text-anchor="middle">PolicyUpdatePlan</text>
-
- <rect class="box boxOrange" x="895" y="575" width="285" height="74" rx="10"/>
- <text class="text" x="1037" y="602" text-anchor="middle">PolicyUpdater.apply</text>
- <text class="small" x="1037" y="621" text-anchor="middle">MemoryFilePolicyUpdater</text>
- <text class="tiny" x="1037" y="640" text-anchor="middle">upsert/delete with before_content guard</text>
-
- <rect class="data" x="925" y="680" width="225" height="44" rx="22"/>
- <text class="text" x="1037" y="707" text-anchor="middle">PolicyApplyResult</text>
-
- <!-- Stores panel -->
- <rect class="panel panelStore" x="1265" y="105" width="175" height="650" rx="18"/>
- <text class="panelTitle" x="1290" y="138">Stores</text>
-
- <rect class="store" x="1285" y="170" width="135" height="70" rx="10"/>
- <text class="text" x="1352" y="196" text-anchor="middle">Case Source</text>
- <text class="tiny" x="1352" y="216" text-anchor="middle">local list</text>
- <text class="tiny" x="1352" y="232" text-anchor="middle">remote service</text>
-
- <rect class="store" x="1285" y="282" width="135" height="76" rx="10"/>
- <text class="text" x="1352" y="309" text-anchor="middle">Trajectory</text>
- <text class="tiny" x="1352" y="329" text-anchor="middle">memories/</text>
- <text class="tiny" x="1352" y="345" text-anchor="middle">trajectories</text>
-
- <rect class="store" x="1285" y="405" width="135" height="88" rx="10"/>
- <text class="text" x="1352" y="432" text-anchor="middle">Experience</text>
- <text class="tiny" x="1352" y="452" text-anchor="middle">memories/</text>
- <text class="tiny" x="1352" y="468" text-anchor="middle">experiences</text>
- <text class="tiny" x="1352" y="484" text-anchor="middle">policy set</text>
-
- <rect class="store" x="1285" y="540" width="135" height="88" rx="10"/>
- <text class="text" x="1352" y="567" text-anchor="middle">Session</text>
- <text class="tiny" x="1352" y="587" text-anchor="middle">archive</text>
- <text class="tiny" x="1352" y="603" text-anchor="middle">memory_diff</text>
- <text class="tiny" x="1352" y="619" text-anchor="middle">trace_id</text>
-
- <!-- Streaming panel bottom -->
- <rect class="panel" x="40" y="570" width="760" height="185" rx="18"/>
- <text class="panelTitle" x="65" y="603">Realtime / Streaming path</text>
- <rect class="box boxPurple" x="75" y="630" width="180" height="62" rx="10"/>
- <text class="text" x="165" y="655" text-anchor="middle">submit_rollout</text>
- <text class="small" x="165" y="674" text-anchor="middle">requires Rollout.case</text>
-
- <rect class="box boxGreen boxLLM" x="300" y="630" width="185" height="62" rx="10"/>
- <text class="text" x="392" y="655" text-anchor="middle">analyze + estimate</text>
- <text class="small" x="392" y="674" text-anchor="middle">immediate per rollout</text>
-
- <rect class="box boxPurple" x="530" y="630" width="220" height="62" rx="10"/>
- <text class="text" x="640" y="655" text-anchor="middle">StreamingBatcher</text>
- <text class="small" x="640" y="674" text-anchor="middle">max gradients / max wait</text>
-
- <text class="small" x="65" y="724">submit_rollout 会等待当前 rollout 所在 batch 完成 flush + apply 后返回;flush 后进入同一个 serialized Policy Update Transaction。</text>
-
- <!-- Flow arrows -->
- <path class="edgeBlue" d="M202 234 L202 260"/>
- <path class="edgeBlue" d="M202 300 L202 326"/>
- <path class="edgeBlue" d="M202 390 L202 416"/>
- <path class="edgeBlue" d="M330 452 C370 452 370 190 505 190"/>
- <path class="edgeGreen" d="M605 210 L605 235"/>
- <path class="edgeGreen" d="M605 307 L605 335"/>
- <path class="edgeGreen" d="M605 379 L605 405"/>
- <path class="edgeGreen" d="M755 441 C815 441 835 192 925 192"/>
- <path class="edgeOrange" d="M1037 214 L1037 242"/>
- <path class="edgeOrange" d="M1037 300 L1037 322"/>
- <path class="edgeOrange" d="M1037 380 L1037 402"/>
- <path class="edgeOrange" d="M1037 476 L1037 505"/>
- <path class="edgeOrange" d="M1037 549 L1037 575"/>
- <path class="edgeOrange" d="M1037 649 L1037 680"/>
-
- <!-- Store arrows -->
- <path class="edgeDashed" d="M330 202 L1285 205"/>
- <text class="label" x="815" y="193" text-anchor="middle">case query/read</text>
- <path class="edgeGreen" d="M755 271 C930 271 1100 320 1285 320"/>
- <text class="label" x="990" y="296" text-anchor="middle">write trajectory memory</text>
- <path class="edgeDashed" d="M1180 351 C1210 351 1240 449 1285 449"/>
- <text class="label" x="1226" y="395" text-anchor="middle">reload latest</text>
- <path class="edgeDashed" d="M1285 449 C1238 449 1226 439 1180 439"/>
- <text class="label" x="1230" y="432" text-anchor="middle">read required + candidates</text>
- <path class="edgeOrange" d="M1180 612 C1225 612 1235 449 1285 449"/>
- <text class="label" x="1228" y="552" text-anchor="middle">write/delete</text>
- <path class="edgeDashed" d="M1180 218 C1225 218 1238 584 1285 584"/>
- <text class="label" x="1220" y="268" text-anchor="middle">via session.commit</text>
-
- <!-- Streaming arrows -->
- <path class="edgeGreen" d="M255 661 L300 661"/>
- <path class="edgeGreen" d="M485 661 L530 661"/>
- <path class="edgeOrange" d="M750 661 C835 661 840 271 895 271"/>
- <text class="label" x="812" y="642" text-anchor="middle">flush batch</text>
-
- <!-- Eval bypass -->
- <path class="edgeBlue" d="M330 452 C380 520 585 545 760 527 C820 520 835 705 925 702"/>
- <text class="label" x="570" y="552" text-anchor="middle">eval bypasses analyzer/trainer and uses Rollout.evaluation only</text>
-
- <!-- Footer -->
- <rect x="40" y="815" width="1400" height="48" rx="12" fill="#ffffff" stroke="#cbd5e1"/>
- <text class="small" x="65" y="840">并行边界:case rollout、rollout analysis、gradient estimation。LLM 调用:trajectory ExtractLoop、experience gradient ExtractLoop、patch merge ExtractLoop。串行边界:ExperienceSet.lock() 内的 reload → optimizer.plan → updater.apply。</text>
-</svg>
diff --git a/docs/design/assets/train-framework-overview.svg b/docs/design/assets/train-framework-overview.svg
deleted file mode 100644
index 1218c2a54..000000000
--- a/docs/design/assets/train-framework-overview.svg
+++ /dev/null
@@ -1,188 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="780" viewBox="0 0 1280 780" role="img" aria-labelledby="title desc">
- <title id="title">OpenViking session.train 框架模块关系图</title>
- <desc id="desc">展示 CaseLoader、RolloutExecutor、PolicyTrainer、RolloutAnalyzer、GradientEstimator、PolicyOptimizer、PolicyUpdater、ExperienceSet 和 StreamingPolicyTrainer 等模块之间的关系。</desc>
- <defs>
- <marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse">
- <path d="M 0 0 L 10 5 L 0 10 z" fill="#334155"/>
- </marker>
- <marker id="arrowGreen" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse">
- <path d="M 0 0 L 10 5 L 0 10 z" fill="#16a34a"/>
- </marker>
- <marker id="arrowBlue" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse">
- <path d="M 0 0 L 10 5 L 0 10 z" fill="#2563eb"/>
- </marker>
- <marker id="arrowOrange" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse">
- <path d="M 0 0 L 10 5 L 0 10 z" fill="#ea580c"/>
- </marker>
- <style>
- .bg { fill: #f8fafc; }
- .title { font: 700 24px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; fill: #0f172a; }
- .subtitle { font: 500 13px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; fill: #475569; }
- .panel { fill: #ffffff; stroke: #cbd5e1; stroke-width: 2; rx: 18; }
- .panelTitle { font: 700 17px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; fill: #0f172a; }
- .box { fill: #f8fafc; stroke: #94a3b8; stroke-width: 1.5; rx: 10; }
- .boxCore { fill: #eef2ff; stroke: #818cf8; }
- .boxData { fill: #fefce8; stroke: #eab308; }
- .boxTrain { fill: #f0fdf4; stroke: #4ade80; }
- .boxComp { fill: #eff6ff; stroke: #60a5fa; }
- .boxWrite { fill: #fff7ed; stroke: #fb923c; }
- .boxRemote { fill: #faf5ff; stroke: #c084fc; }
- .text { font: 700 14px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; fill: #1e293b; }
- .small { font: 500 12px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; fill: #475569; }
- .edge { fill: none; stroke: #334155; stroke-width: 2; marker-end: url(#arrow); }
- .edgeGreen { fill: none; stroke: #16a34a; stroke-width: 2.5; marker-end: url(#arrowGreen); }
- .edgeBlue { fill: none; stroke: #2563eb; stroke-width: 2.5; marker-end: url(#arrowBlue); }
- .edgeOrange { fill: none; stroke: #ea580c; stroke-width: 2.5; marker-end: url(#arrowOrange); }
- .edgeDashed { fill: none; stroke: #64748b; stroke-width: 2; stroke-dasharray: 8 6; marker-end: url(#arrow); }
- .label { font: 600 12px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; fill: #334155; }
- </style>
- </defs>
-
- <rect class="bg" width="1280" height="780"/>
- <text class="title" x="40" y="44">OpenViking session.train 框架模块关系</text>
- <text class="subtitle" x="40" y="68">离线 batch、实时 streaming、远程 session.commit 三种训练入口共享同一套 rollout → trajectory → semantic gradient → policy update 语义。</text>
-
- <!-- Domain panel -->
- <rect class="panel" x="40" y="100" width="220" height="610" rx="18"/>
- <text class="panelTitle" x="65" y="132">Domain Model</text>
-
- <rect class="box boxData" x="70" y="165" width="160" height="54" rx="10"/>
- <text class="text" x="150" y="188" text-anchor="middle">Case</text>
- <text class="small" x="150" y="207" text-anchor="middle">task + input + rubric</text>
-
- <rect class="box boxData" x="70" y="245" width="160" height="54" rx="10"/>
- <text class="text" x="150" y="268" text-anchor="middle">Rubric</text>
- <text class="small" x="150" y="287" text-anchor="middle">what good means</text>
-
- <rect class="box boxData" x="70" y="325" width="160" height="54" rx="10"/>
- <text class="text" x="150" y="348" text-anchor="middle">Rollout</text>
- <text class="small" x="150" y="367" text-anchor="middle">case + messages + eval</text>
-
- <rect class="box boxData" x="70" y="405" width="160" height="54" rx="10"/>
- <text class="text" x="150" y="428" text-anchor="middle">Trajectory</text>
- <text class="small" x="150" y="447" text-anchor="middle">trainable trace</text>
-
- <rect class="box boxData" x="70" y="485" width="160" height="54" rx="10"/>
- <text class="text" x="150" y="508" text-anchor="middle">SemanticGradient</text>
- <text class="small" x="150" y="527" text-anchor="middle">before/after MemoryFile</text>
-
- <rect class="box boxData" x="70" y="565" width="160" height="70" rx="10"/>
- <text class="text" x="150" y="592" text-anchor="middle">ExperienceSet</text>
- <text class="small" x="150" y="611" text-anchor="middle">experiences directory</text>
- <text class="small" x="150" y="629" text-anchor="middle">lock() + reload()</text>
-
- <!-- Pipeline panel -->
- <rect class="panel" x="300" y="100" width="650" height="610" rx="18"/>
- <text class="panelTitle" x="325" y="132">OfflinePolicyOptimizationPipeline</text>
-
- <rect class="box boxCore" x="340" y="165" width="220" height="58" rx="10"/>
- <text class="text" x="450" y="190" text-anchor="middle">CaseLoader</text>
- <text class="small" x="450" y="209" text-anchor="middle">ListCaseLoader / RemoteCaseLoader</text>
-
- <rect class="box boxCore" x="650" y="165" width="220" height="58" rx="10"/>
- <text class="text" x="760" y="190" text-anchor="middle">PolicySnapshotter</text>
- <text class="small" x="760" y="209" text-anchor="middle">ContentHashPolicySnapshotter</text>
-
- <rect class="box boxCore" x="340" y="265" width="220" height="58" rx="10"/>
- <text class="text" x="450" y="290" text-anchor="middle">RolloutExecutor</text>
- <text class="small" x="450" y="309" text-anchor="middle">execute cases under snapshot</text>
-
- <rect class="box boxTrain" x="340" y="365" width="220" height="74" rx="10"/>
- <text class="text" x="450" y="392" text-anchor="middle">PolicyTrainer</text>
- <text class="small" x="450" y="411" text-anchor="middle">Batch / Streaming / SessionCommit</text>
- <text class="small" x="450" y="429" text-anchor="middle">train_rollouts(...)</text>
-
- <rect class="box boxComp" x="650" y="345" width="220" height="54" rx="10"/>
- <text class="text" x="760" y="368" text-anchor="middle">RolloutAnalyzer</text>
- <text class="small" x="760" y="387" text-anchor="middle">extract trajectory</text>
-
- <rect class="box boxComp" x="650" y="425" width="220" height="54" rx="10"/>
- <text class="text" x="760" y="448" text-anchor="middle">GradientEstimator</text>
- <text class="small" x="760" y="467" text-anchor="middle">trajectory → gradient</text>
-
- <rect class="box boxComp" x="650" y="505" width="220" height="54" rx="10"/>
- <text class="text" x="760" y="528" text-anchor="middle">PolicyOptimizer</text>
- <text class="small" x="760" y="547" text-anchor="middle">patch merge plan</text>
-
- <rect class="box boxWrite" x="650" y="585" width="220" height="54" rx="10"/>
- <text class="text" x="760" y="608" text-anchor="middle">PolicyUpdater</text>
- <text class="small" x="760" y="627" text-anchor="middle">write/delete experiences</text>
-
- <rect class="box boxTrain" x="340" y="585" width="220" height="54" rx="10"/>
- <text class="text" x="450" y="608" text-anchor="middle">PipelineResult</text>
- <text class="small" x="450" y="627" text-anchor="middle">accuracy / score / plan / apply</text>
-
- <!-- Remote / realtime panel -->
- <rect class="panel" x="990" y="100" width="250" height="610" rx="18"/>
- <text class="panelTitle" x="1015" y="132">Integration Paths</text>
-
- <rect class="box boxRemote" x="1020" y="165" width="190" height="68" rx="10"/>
- <text class="text" x="1115" y="191" text-anchor="middle">Batch train/eval</text>
- <text class="small" x="1115" y="210" text-anchor="middle">CaseLoader → executor</text>
- <text class="small" x="1115" y="228" text-anchor="middle">baseline/train/final eval</text>
-
- <rect class="box boxRemote" x="1020" y="270" width="190" height="74" rx="10"/>
- <text class="text" x="1115" y="297" text-anchor="middle">Realtime rollout</text>
- <text class="small" x="1115" y="316" text-anchor="middle">train_from_rollouts</text>
- <text class="small" x="1115" y="334" text-anchor="middle">StreamingPolicyTrainer</text>
-
- <rect class="box boxRemote" x="1020" y="385" width="190" height="74" rx="10"/>
- <text class="text" x="1115" y="412" text-anchor="middle">session.commit</text>
- <text class="small" x="1115" y="431" text-anchor="middle">CaseSpec + rollout</text>
- <text class="small" x="1115" y="449" text-anchor="middle">OutcomeEvaluation</text>
-
- <rect class="box boxRemote" x="1020" y="500" width="190" height="74" rx="10"/>
- <text class="text" x="1115" y="527" text-anchor="middle">Remote benchmark</text>
- <text class="small" x="1115" y="546" text-anchor="middle">HTTP cases / rollouts</text>
- <text class="small" x="1115" y="564" text-anchor="middle">tau2 service</text>
-
- <rect class="box boxRemote" x="1020" y="615" width="190" height="54" rx="10"/>
- <text class="text" x="1115" y="638" text-anchor="middle">Report</text>
- <text class="small" x="1115" y="657" text-anchor="middle">accuracy + avg_reward</text>
-
- <!-- Main pipeline arrows -->
- <path class="edgeBlue" d="M560 194 L650 194"/>
- <text class="label" x="604" y="184" text-anchor="middle">snapshot</text>
-
- <path class="edgeBlue" d="M450 223 L450 265"/>
- <text class="label" x="497" y="248" text-anchor="middle">Case[]</text>
-
- <path class="edgeBlue" d="M760 223 C760 250 610 250 560 294"/>
- <text class="label" x="682" y="256" text-anchor="middle">policy_snapshot_id</text>
-
- <path class="edgeGreen" d="M450 323 L450 365"/>
- <text class="label" x="497" y="348" text-anchor="middle">Rollout[]</text>
-
- <path class="edgeGreen" d="M560 402 L650 372"/>
- <path class="edgeGreen" d="M760 399 L760 425"/>
- <path class="edgeGreen" d="M760 479 L760 505"/>
- <path class="edgeOrange" d="M760 559 L760 585"/>
- <path class="edgeOrange" d="M650 612 L560 612"/>
-
- <!-- ExperienceSet relation -->
- <path class="edgeOrange" d="M230 600 C330 685 580 690 650 612"/>
- <text class="label" x="438" y="690" text-anchor="middle">lock + reload before plan/apply</text>
- <path class="edgeDashed" d="M230 600 C390 530 500 300 340 294"/>
- <text class="label" x="294" y="452" text-anchor="middle">current policy set</text>
-
- <!-- Domain hints -->
- <path class="edgeDashed" d="M230 192 L340 194"/>
- <path class="edgeDashed" d="M230 352 C285 352 300 294 340 294"/>
- <path class="edgeDashed" d="M650 372 C565 438 320 432 230 432"/>
- <path class="edgeDashed" d="M650 452 C560 512 330 512 230 512"/>
-
- <!-- Integration arrows -->
- <path class="edgeDashed" d="M1020 199 C960 199 930 294 870 294"/>
- <path class="edgeDashed" d="M1020 307 C930 307 650 402 560 402"/>
- <path class="edgeDashed" d="M1020 422 C930 422 870 402 560 402"/>
- <path class="edgeDashed" d="M1020 537 C965 537 930 404 870 404"/>
- <path class="edgeDashed" d="M1020 642 C900 662 640 662 560 612"/>
-
- <!-- Eval path -->
- <path class="edgeBlue" d="M450 323 C450 540 500 565 640 594"/>
- <text class="label" x="535" y="552" text-anchor="middle">eval uses rollout.evaluation only</text>
-
- <!-- Legend -->
- <rect x="40" y="730" width="1200" height="34" rx="10" fill="#ffffff" stroke="#cbd5e1"/>
- <text class="small" x="65" y="752">蓝色:rollout 执行 / eval;绿色:训练信号生成;橙色:policy plan/apply 写入;虚线:数据依赖或可选集成路径。</text>
-</svg>
diff --git a/docs/design/freshness-aware-parent-bubbling-design.md b/docs/design/freshness-aware-parent-bubbling-design.md
deleted file mode 100644
index 0a4b9db78..000000000
--- a/docs/design/freshness-aware-parent-bubbling-design.md
+++ /dev/null
@@ -1,357 +0,0 @@
-# 设计草案:基于 Freshness 的上级摘要冒泡策略
-
-状态:讨论稿
-
-关联 RFC:`docs/design/l0-l1-okf-sidecars-rfc.md`
-
-## 摘要
-
-本文继续细化 L0/L1 OKF sidecar RFC 中的 `Freshness-Aware Parent Bubbling`。目标是在不引入复杂调度基础设施、不扩大 freshness 数据模型的前提下,减少没有实际收益的上级摘要生成、模型调用和逐级写放大。
-
-首版策略只做两层判断:
-
-1. 子目录摘要完成后,先判断父目录实际使用的子目录 L0 正文是否发生变化;如果 L0 未变,停止冒泡。
-2. 如果 L0 确实变化,则小目录立即刷新;宽目录只累计现有的 `pending_child_changes`,变化比例达到阈值后再刷新。文件的新增、删除和修改在这里统一视为一次直接子项变化。
-
-对于宽目录,采样只是一次摘要生成过程中的有界输入手段,不是一个需要持久化、追踪或参与调度判断的“采样成员集合”。
-
-首版不提供最长陈旧时间兜底,不维护唯一变化子项集合,也不调整现有 freshness 字段的定义。它是一套务实的成本控制策略,而不是严格的实时一致性协议。
-
-## 当前实现与四个具体问题
-
-当前 resource/skill 语义任务成功后,会执行以下流程:
-
-1. 将父目录 sidecar 的 `pending_child_changes` 加一。
-2. 立即为父目录入队一次非递归语义刷新。
-3. 父目录刷新成功后,对更上一级重复同样的流程。
-
-这个实现简单,但存在四个值得明确的问题。
-
-### 1. 子目录 L0 未变时仍然冒泡
-
-父目录生成摘要时,消费的是直接子目录的 L0 正文,而不是子目录 L1,也不是 sidecar metadata。
-
-如果子目录重新生成后只有 L1 或 metadata 发生变化,而 L0 正文没有变化,那么父目录的实际输入没有改变。此时仍然刷新父目录属于无效冒泡。
-
-这是首版最应优先解决的问题,因为判断依据明确、实现成本低,而且每一级目录都可以独立停止继续向上传播。
-
-### 2. `pending_child_changes` 统计的是事件次数
-
-当前实现对每次观察到的变化执行整数累加。因此,同一个热点子目录连续变化十次,会被计为十次 pending change,而不是一个发生变化的直接子项。
-
-这与“唯一变化直接子项数”的理想语义并不完全一致。不过,OpenViking 中常规文件变化频率并不高;即使偶尔出现热点连续变化,它最多让目录更早达到刷新阈值,不会让摘要比现在更陈旧。
-
-因此,首版有意容忍这个近似:
-
-- 不持久化 changed child key;
-- 不对跨事件的同一 URI 去重;
-- 不引入集合截断、哈希冲突或额外 metadata;
-- 继续将 `pending_child_changes` 当作简单的变化事件计数使用。
-
-一次批量请求内部仍可对重复 URI 做自然去重,但不建立跨请求的唯一子项状态。
-
-### 3. 采样发生在子项摘要工作之后
-
-当前目录语义树会先生成或读取所有直接子项的摘要,最后才使用 `overview_sample_limit` 选出进入父目录 overview prompt 的部分输入。
-
-这能够限制 prompt 大小,却没有避免未参与本次聚合的子项摘要工作。对于宽目录,如果我们的目标是降低重新摘要成本,就应当在调度本轮父目录聚合所需的子项摘要之前完成有界采样。
-
-这里的采样是本轮生成过程中的临时决策,不形成持久化的“当前采样成员”概念,也不参与是否立即刷新的判断。
-
-### 4. 仅使用变化比例可能长期不刷新
-
-例如,一个包含 161 个直接子项的目录始终只有 3 个文件发生变化,那么它可能长期达不到 10% 的刷新阈值。
-
-这是比例阈值的已知取舍。首版不为此引入最长陈旧时间、定时扫描、延迟消息或 dirty-directory registry,原因是这些机制会显著扩大实现和运维复杂度,而当前场景中的预期收益有限。
-
-在没有后续变化的情况下,目录可以通过显式刷新、重新导入或其他自然语义任务获得更新。是否需要时间兜底,应在上线观察真实 pending 分布后再决定,先不讨论。
-
-## 设计原则
-
-- 比较父目录真正消费的语义输入,而不是比较包含 metadata 的原始 sidecar 字节。
-- 子目录向上冒泡时,只以 L0 正文变化作为语义信号。
-- 文件新增、删除和修改对于宽目录阈值统计是等价的。
-- 不把“是否属于上次 sample”作为调度条件。
-- 不持久化变化子项集合,只累计简单计数。
-- 不改变现有 freshness 的四个字段及其基本含义。
-- 显式刷新、首次导入和同步等待应保持可预测,不应被自动阈值静默延迟。
-- 文件自身的解析、摘要和向量维护,与目录聚合摘要是否延迟分开处理。
-- 首版复用现有持久队列、路径锁和 coalesce 机制,不新增时间调度系统。
-
-## 非目标
-
-首版明确不解决以下问题:
-
-- 不保证 pending change 在固定时间内一定被聚合。
-- 不精确统计唯一变化的直接子项数。
-- 不记录或维护某个目录的持久化采样成员集合。
-- 不根据新增、删除、修改设置不同权重。
-- 不根据文件大小、类型或摘要差异程度计算加权变化率。
-
-## 保持现有 Freshness 模型
-
-继续使用 RFC 已定义的字段:
-
-```yaml
-freshness:
- total_entries: 161
- sampled_entries: 32
- unsampled_entries: 129
- pending_child_changes: 3
-```
-
-字段解释保持不变:
-
-- `total_entries`:上一次成功生成目录摘要时观察到的直接子项总数。
-- `sampled_entries`:上一次生成实际使用的直接子项数量。
-- `unsampled_entries`:上一次生成未采样的直接子项数量。
-- `pending_child_changes`:上一次生成完成后,已知发生变化、但尚未反映到当前正文中的直接子项数。
-
-上述字段定义不变。首版只是在实现上使用轻量的事件累加来近似维护 `pending_child_changes`,暂不对跨事件的同一直接子项去重。因此实际计数可能被重复事件保守高估。该近似只用于判断变化规模是否值得触发一次父目录刷新,不应被当作精确审计数据。
-
-新增和删除可能使当前真实直接子项数与 `total_entries` 暂时不一致。首版仍使用上一次成功生成记录的 `total_entries` 作为阈值分母;下一次成功刷新会重新列目录并修正这些计数。
-
-## 语义变化判断
-
-### 子目录变化
-
-子目录语义任务开始前读取旧 L0 body,生成完成后取得新 L0 body,对规范化正文计算 digest:
-
-```text
-old_l0_digest = hash(normalize(old_l0_body))
-new_l0_digest = hash(normalize(new_l0_body))
-```
-
-digest 不包含:
-
-- YAML frontmatter;
-- freshness;
-- source;
-- generated_by;
-- 文件修改时间或其他存储属性。
-
-决策规则:
-
-- 新旧 L0 digest 相同:不标记父目录 pending,不为父目录入队,冒泡在当前层终止。
-- 新旧 L0 digest 不同:向父目录上报一次普通的 direct-child change。
-- 旧 L0 不存在或无法可靠解析:保守地视为发生变化。
-
-L1 是否变化只决定当前目录自己的写回或向量维护,不决定是否继续向祖先冒泡。
-
-### 直接文件变化
-
-对于直接文件,新增、删除和修改都向所在目录贡献变化计数。首版不要求在入队前比较新旧文件摘要,因为这样会把语义生成工作前移到调度判断阶段,抵消低成本策略的收益。
-
-一次批量操作中有多少个不同的 changed URI,就对本轮 pending 增加多少;后续独立事件再次修改同一个 URI,可以再次累加。
-
-## 调度决策
-
-策略输出只有三种:
-
-```text
-NOOP
-MARK_PENDING
-REFRESH_NOW
-```
-
-建议按以下顺序判断:
-
-| 条件 | 决策 | 说明 |
-| --- | --- | --- |
-| 子目录新旧 L0 正文相同 | `NOOP` | 父目录实际输入没有变化 |
-| 父目录不存在有效 sidecar | `REFRESH_NOW` | 没有可继续使用的摘要基线 |
-| 首次导入或显式语义刷新 | `REFRESH_NOW` | 保持调用者意图 |
-| 父目录上次记录的 `total_entries <= overview_sample_limit` | `REFRESH_NOW` | 小目录变化后直接刷新 |
-| 宽目录累计变化率低于阈值 | `MARK_PENDING` | 只更新 freshness,不入队 |
-| 宽目录累计变化率达到阈值 | `REFRESH_NOW` | 入队一次有界父目录刷新 |
-
-这里没有以下特殊规则:
-
-- sampled child 变化不要求立即刷新;
-- 新增导致本轮临时 sample 变化不要求立即刷新;
-- 删除导致本轮临时 sample 变化不要求立即刷新;
-- 目录变化和文件变化不设置不同阈值。
-
-对于宽目录,所有增删改都只是 `pending_child_changes` 的增量。
-
-## 宽目录阈值
-
-继续用 `semantic.overview_sample_limit` 区分小目录和宽目录,当前默认值为 32。
-
-首版只新增一个比例配置:
-
-```yaml
-semantic:
- overview_sample_limit: 32
- freshness_refresh_ratio: 0.10
-```
-
-宽目录的判断为:
-
-```text
-pending_after = pending_before + current_change_count
-change_ratio = pending_after / max(total_entries, 1)
-
-refresh_now = change_ratio >= freshness_refresh_ratio
-```
-
-等价的整数阈值为:
-
-```text
-refresh_threshold = ceil(freshness_refresh_ratio * total_entries)
-```
-
-示例:
-
-| 上次记录的直接子项数 | 10% 阈值 |
-| ---: | ---: |
-| 33 | 4 |
-| 161 | 17 |
-| 1000 | 100 |
-
-首版不额外设置最小变化数或最大变化数,以减少配置项并保持“变化比例”含义直观。如果真实运行数据显示超宽目录等待过久或一次刷新积压过多,再考虑增加上限。
-
-由于热点子项可重复累计,阈值可能比真实的唯一文件变化率更早达到。这是有意接受的保守偏差:它可能多触发一次刷新,但不会让目录更久不刷新。
-
-代码实现时注意将公式的上述解释注释到代码。
-
-## 达到阈值后的刷新方式
-
-宽目录达到阈值后,不应只携带“最后一次变化的 URI”执行普通增量刷新。此前被延迟的变化没有持久化 URI 集合,仅保留了计数;只处理最后一次变化会遗漏先前事件。
-
-因此,阈值触发的任务应被定义为一次当前目录的有界完整聚合:
-
-1. 重新列举当前直接子项。
-2. 根据 `overview_sample_limit` 选出本轮有界输入。
-3. 为本轮选中的输入读取或生成当前摘要。
-4. 生成新的 L1,并从 L1 正文提取 L0。
-5. 写入最新的 `total_entries`、`sampled_entries` 和 `unsampled_entries`。
-6. 消费本轮刷新开始时已经观察到的 pending 计数。
-
-这里的“完整”是指从当前目录状态重新开始一次聚合决策,不是读取宽目录中的全部文件内容。实际进入目录摘要的输入仍受 `overview_sample_limit` 限制。
-
-每次刷新都可以根据当时的目录状态重新进行确定性采样。系统不记录“上次 sample 中有哪些成员”,调度器也不基于 sample membership 做判断。
-
-## 将采样前移
-
-为了让宽目录阈值真正降低成本,应把本轮目录聚合采样前移到昂贵工作之前:
-
-```text
-列举直接子项
- -> 确定本轮有界 sample
- -> 只为本轮聚合准备 sample 所需的摘要输入
- -> 生成目录 L1/L0
-```
-
-采样算法只需要满足两个条件:
-
-- 对同一个稳定目录重复执行时结果确定;
-- 能够覆盖目录中不同位置的子项,而不是永远只取前 32 个。
-
-可以继续使用现有的确定性保序采样。是否改成哈希采样不属于 freshness 冒泡首版的必要条件,因为我们不再赋予 sample membership 调度语义。
-
-必须区分两类工作:
-
-- 文件自身的解析、摘要或向量更新;
-- 文件摘要作为输入参与父目录 L1/L0 聚合。
-
-父目录聚合被延迟或采样,不能导致发生变化的文件失去自身应有的向量维护。采样前移只减少为“生成目录摘要”而进行的额外工作。
-
-## Sidecar 写回结果
-
-当前 sidecar 写回只返回成功与否,无法区分正文变化和 metadata 变化。建议返回结构化结果:
-
-```python
-AbstractOverviewWriteResult(
- wrote=True,
- overview_body_changed=True,
- abstract_body_changed=False,
-)
-```
-
-语义如下:
-
-- `wrote`:是否成功完成写回流程;
-- `overview_body_changed`:L1 可见正文是否改变;
-- `abstract_body_changed`:L0 可见正文是否改变。
-
-metadata 从 `pending_child_changes > 0` 重置或减少,也可能造成 raw sidecar 变化,但这种变化不应被视为 L0/L1 语义变化。
-
-后续行为:
-
-- L0 正文改变:可以向父目录上报一次变化;
-- 只有 L1 正文改变:只处理当前目录自己的写回和向量维护;
-- L0/L1 正文都未改变:不需要重新向量化正文,也不继续冒泡;
-- 只有 freshness 改变:只写 metadata。
-
-### 标记和决策
-
-在 sidecar exact-path lease 下:
-
-1. 读取当前 `pending_child_changes`。
-2. 加上本次 `current_change_count`。
-3. 写回新计数。
-4. 基于写回后的计数和现有 `total_entries` 做阈值判断。
-5. 释放 lease 后再执行 enqueue。
-
-这样 metadata 更新和调度判断来自同一个一致快照。并发事件即使同时到达,也不会简单覆盖彼此的计数。
-
-## API 语义
-
-以下操作默认绕过宽目录阈值,立即刷新:
-
-- 首次资源导入;
-- reindex 等触发的显式语义刷新;
-
-普通后台文件变化可以被阈值延迟。如果一次操作只更新 freshness 而没有入队目录摘要,返回结果应明确表达:
-
-```json
-{
- "semantic_status": "deferred",
- "semantic_root_uri": "viking://resources/example"
-}
-```
-
-此时文件自身的向量维护状态应单独表达,不能因为目录摘要被延迟就返回整体 `complete` 或错误地声称已经 `queued`。
-
-## 实现边界
-
-保持 `SemanticProcessor` 是 resource、skill 和 memory 语义处理的统一入口,不引入新的顶层 processor。
-
-建议职责划分如下:
-
-| 位置 | 职责 |
-| --- | --- |
-| `openviking/storage/queuefs/semantic_ops/freshness_policy.py` | 纯粹的 `NOOP` / `MARK_PENDING` / `REFRESH_NOW` 判断 |
-| `openviking/storage/semantic_sidecar.py` | 在 lease 下原子累加、读取和消费现有 freshness 计数 |
-| `SemanticTreeExecutor` | 在宽目录聚合前完成本轮采样,并返回 L0/L1 正文变化结果 |
-| `SemanticProcessor` | 根据 L0 是否变化决定是否继续向父目录冒泡 |
-| content write、delete、resource 路径 | 将文件增删改统一记录为所在目录的变化计数 |
-
-不新增 maintenance service、定时 sweep、延迟队列或 dirty-directory registry。
-
-### 采样前移
-
-- 宽目录在生成子项聚合输入前完成采样。
-- 未进入本轮目录 sample 的子项不会仅为父目录聚合而产生额外摘要调用。
-- 发生变化的文件仍然完成自身需要的向量维护。
-- 稳定目录重复刷新产生确定性的采样结果。
-
-### API 行为
-
-- 自动延迟返回 `semantic_status: deferred`。
-- 实际入队返回 `queued`,同步完成返回 `complete`。
-- 目录聚合延迟与文件自身向量状态可以被调用方区分。
-
-## 示例
-
-假设一个目录上次生成时有 161 个直接子项,`overview_sample_limit=32`,刷新比例为 10%。
-
-1. 子目录 `a/` 完成语义生成,但新旧 L0 相同:不修改父目录 freshness,也不继续冒泡。
-2. 文件 `x.md`、`y.md` 和 `z.md` 发生修改:`pending_child_changes` 变为 3,低于阈值 17,不刷新目录摘要。
-3. `x.md` 后续又被修改十次:pending 可以累计到 13。首版不做跨事件去重。
-4. 再发生四次任意直接子项增删改后,pending 达到 17,触发一次父目录刷新。
-5. 刷新重新列举当前目录并选择本轮最多 32 个输入,不关心这些输入是否属于某个历史 sample。
-6. 刷新开始时捕获 pending snapshot;执行期间新增的变化计数会在写回后保留。
-7. 如果刷新后的父目录 L0 仍然未变,则冒泡在父目录停止,不再刷新祖父目录。
-8. 如果目录长期停留在 3 个 pending 且没有其他自然刷新,首版允许它继续保持这一 freshness 状态。
diff --git a/docs/design/git-version-control-design.md b/docs/design/git-version-control-design.md
deleted file mode 100644
index e1c21e503..000000000
--- a/docs/design/git-version-control-design.md
+++ /dev/null
@@ -1,1270 +0,0 @@
-# OpenViking 多版本管理技术方案 — 基于 Gitoxide 的 in-process Git 集成
-
-> 💡 **一句话摘要**:在现有 OpenViking 的 RAGFS Rust 实现中嵌入一套基于 `gitoxide` 的 in-process Git 服务,以 **账号(account\_id)粒度** 提供 `commit / restore / show` 三个版本管理原语;通过 PyO3 binding 直接被 `VikingFS` Python 层调用,全程零 HTTP、零额外进程,Git 对象/Ref 后端复用现有 `localfs`/`s3fs` 客户端,实现"本地或远程"对称配置。
-
-# 1. 背景与目标
-
-## 1.1 业务背景
-
-OpenViking 现有存储架构是一套以 `viking://` URI 为入口的双层抽象:上层 `VikingFS`(Python)负责 URI 规范化、L0/L1 摘要、向量同步、租户隔离;下层 RAGFS(Rust + PyO3 binding)提供 `FileSystem` trait 与 `MountableFS` radix-trie 路由,实际数据落到 `localfs`、`s3fs`、`memfs` 等插件后端。
-
-在持续运行过程中,用户/Agent 对 `viking://resources/`、`viking://agent/skills/` 等命名空间的写入是连续且不可逆的——出错后无法回滚,跨多个文件的"逻辑事务"难以原子化捕获,实验性改动需要手动备份。这些场景的本质需求都是一套**面向账号的多版本快照机制**,语义与 Git 的 commit/restore/show 高度同构。
-
-## 1.2 设计目标
-
-- **显式版本化**:用户/Agent 通过 API 显式触发 commit/restore/show,不引入隐式 hook,避免影响现有写链路的延迟与一致性语义
-- **账号粒度仓库**:每个 `account_id` 一个逻辑 Git 仓库,跨 scope (resources/agent/user/session) 共享同一棵 root tree,支持跨 scope 的原子快照
-- **多后端对称**:Git objects / refs 的实际存储类型与 resources 目录一致,可在配置中切换本地(local)或远程(s3),运维心智零增量
-- **零进程膨胀**:Git 服务以 in-process binding 形式嵌入现有 RAGFS,共享 Tokio runtime 与配置加载链路,不引入新 HTTP server
-- **对现有代码侵入最小**:不修改 `content_write.py`、`viking_fs.write/rm/mv` 等核心写链路,仅在 `VikingFS` 上增加 3 个新方法
-- **定向恢复 (restore)**:支持以 **(project\_dir, commit\_id)** 为输入,将指定 project 目录恢复到目标 commit 的快照状态,并以 HEAD 为父节点*正向生成一个新 commit*。非目标 project 目录保持当前最新状态不动。
-
-## 1.3 非目标 (Out of Scope)
-
-- 不实现自动 commit hook (首版纯主动 API 触发)
-- 不实现分支 merge / rebase / cherry-pick / push/pull (首版只覆盖快照 + 回滚 + 查看)
-- 不暴露 Git 数据到 `viking://` 用户命名空间 (避免被用户误删/误改)
-- 不支持向量索引数据的版本化 (向量索引由 watcher 异步重建, restore 后需触发重建;L0/L1 派生文件已纳入版本管理)
-- 不支持 ref 回退式 checkout:本方案不提供 "把 main / HEAD 指针直接移动到旧 commit" 的能力。所有恢复操作都通过正向新增 commit 实现,保证 HEAD 单调前进、commit 链完整可审计。如需查看旧版本,使用 **show** 接口的只读路径。
-
-***
-
-# 2. 核心设计决策
-
-| 决策 | 设计含义 | 替代方案被淘汰的原因 |
-| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
-| **单 Repo per account\_id** | 同一账号下的 `resources/`、`agent/`、`user/`、`session/` 全部在一棵 root tree 之下;一次 commit 可覆盖任意 scope 的子集 | per-resource repo 会产生 N×账号数量的索引数据,跨 resource 的"事务性快照"需要协调多 repo,复杂度高 |
-| **纯 API 触发,不接 hook** | `content_write.py` / `viking_fs.write/rm/mv` 完全不动;Git 仅通过 `VikingFS.commit/restore/show` 三个新方法被显式调用 | hook 模式会让每次小写入都触发 Git 写入,放大延迟、放大冲突窗口、放大 ref CAS 失败率;首版优先简单 |
-| **Git 存储后端与 resources 同构** | 定义 `ObjectStore` / `RefStore` trait,提供 local 与 s3 两种实现,直接复用 `plugins::localfs::LocalFileSystem` 和 `plugins::s3fs::S3Client` | 独立实现 Git 存储后端会重复造轮子;走 `MountableFS` 又会让 Git 数据进入用户命名空间 |
-| **嵌入为 crates/ragfs 子模块** | 新增 `crates/ragfs/src/git/` 模块,与 `core/`、`plugins/`、`server/` 平级;PyO3 binding 在 `RAGFSBindingClient` 上加 3 个方法 | 独立 crate 会引入额外配置、额外 runtime、额外鉴权;`ServicePlugin` 又无法表达 commit 这种非文件操作的语义 |
-| **暴露方式 = PyO3 binding,非 HTTP** | 三个新方法挂在现有 `RAGFSBindingClient` 上,通过 `AsyncAGFSClient.run` 由 `VikingFS` 调用,与 `ls/read/write` 一致 | HTTP server 路径在 OpenViking 当前架构中已是 legacy,生产路径是 in-process binding |
-
-***
-
-# 3. 整体架构
-
-## 3.1 分层与依赖关系
-
-```mermaid
-flowchart TB
- subgraph Py[Python 层]
- VFS["VikingFS
-commit / checkout / show"]
- Async["AsyncAGFSClient
-(asyncio.to_thread)"]
- end
-
- subgraph BindCrate["crates/ragfs-python (PyO3 cdylib)"]
- RBC["RAGFSBindingClient
-+ git_commit / git_checkout / git_show"]
- end
-
- subgraph CoreCrate[crates/ragfs]
- MFS["core/MountableFS
-(现有 VFS 路由)"]
- Plugins["plugins/
-localfs · s3fs · memfs ..."]
- GitMod["git/ (新增)
-GitService · ObjectStore · RefStore"]
- end
-
- subgraph Backends[底层存储后端]
- Local["LocalFileSystem
-(本地磁盘)"]
- S3["S3Client
-(TOS / S3 / OSS)"]
- end
-
- VFS --> Async
- Async --> RBC
- RBC --> MFS
- RBC --> GitMod
- GitMod -- "checkout 写回阶段" --> MFS
- MFS --> Plugins
- Plugins --> Local
- Plugins --> S3
- GitMod -- "直接持有 struct
-(不经过 MountableFS)" --> Local
- GitMod -- "直接持有 struct
-(不经过 MountableFS)" --> S3
-```
-
-## 3.2 数据流(三个核心命令)
-
-```mermaid
-sequenceDiagram
- participant U as User/Agent
- participant V as VikingFS (Python)
- participant B as RAGFSBindingClient
- participant G as GitService
- participant M as MountableFS
- participant O as ObjectStore
- participant R as RefStore
-
- Note over U,R: --- commit ---
- U->>V: commit(message, paths)
- V->>B: git_commit(account, branch, ...)
- B->>G: GitService::commit(req)
- G->>M: tree_directory / read (枚举+读 blob)
- M-->>G: 文件内容流
- G->>O: put(blob_oid, zlib)
- G->>O: put(tree_oid, zlib)
- G->>O: put(commit_oid, zlib)
- G->>R: cas_update(refs/heads/main, parent, new)
- R-->>G: ok / conflict
- G-->>B: CommitResponse
- B-->>V: dict
- V-->>U: commit_oid
-
- Note over U,R: --- show (只读) ---
- U->>V: show(ref, path)
- V->>B: git_show(account, ref, path)
- B->>G: GitService::show
- G->>R: read(refs/heads/main)
- G->>O: get(commit_oid) → tree_oid
- G->>O: get(tree_oid) → blob_oid
- G->>O: get(blob_oid)
- G-->>B: blob bytes
- B-->>V: bytes
- V-->>U: bytes
-
- Note over U,R: --- checkout (写回 VFS) ---
- U->>V: checkout(ref, paths)
- V->>B: git_checkout(account, ref, paths, dry_run)
- B->>G: GitService::checkout
- G->>O: 加载 commit → root tree → 递归列 (path, blob_oid)
- G->>M: stat / read 对比当前态
- G->>M: write / remove (走完整 VFS 语义)
- G-->>B: 差异报告
- B-->>V: dict
- V-->>U: applied / deleted / skipped
-```
-
-## 3.3 关键设计原则
-
-> 💡 **Git 数据不进 viking 命名空间**
->
-> Git 模块直接持有 `LocalFileSystem`/`S3Client` 实例,**不**通过 `MountableFS` 路由。Git 数据存到 `git/{account}/objects/...`,用户在 `viking://` 下看不到、也改不到。
-
-> 💡 **LocalObjectStore 和 S3ObjectStore 直接调用 tokio::fs 和 Arc\<aws\_sdk\_s3::Client>, 不复用 LocalFileSystem/S3Client**
->
-> LocalFileSystem/S3Client 是面向"用户文件树"的抽象,而 Git 后端是面向"内容寻址对象库"的存储,两者的语义需求不重叠。强行复用会导致更复杂的胶水代码。
-
-***
-
-# 4. Repo 边界与 Tree 布局
-
-## 4.1 Tree 镜像 VikingFS 命名空间
-
-由于 `viking_fs._uri_to_path` 已经定义了 `viking://X → /local/{account_id}/X` 的映射规则,我们让 Git 的 root tree 完全镜像 `/local/{account_id}/` 下的子目录结构。这样 tree path 与 viking URI 后缀一一对应,语义直观、无歧义。
-
-## 4.2 路径剪枝(自动排除)
-
-剪枝规则集中实现在 `crates/ragfs/src/git/enumerate.rs::prune_path`,在 `commit` 入口对 `paths=Some(...)` 与 `paths=None`(全量枚举)两条路径都生效:
-
-| 类别 | 规则 | 理由 |
-| ------------- | ------------------------------------------------------- | --------------------------------------------------------------- |
-| 内部 scope / 目录 | 第一段命中 `_system` / `tasks` / `temp` / `queue` / `upload` | 与 `VikingFS._INTERNAL_NAMES` / `INTERNAL_SCOPES` 一致,均为运行时锁/系统状态 |
-| 运行时锁文件 | 任意段以 `.path.ovlock` 开头 | VFS 内部锁,不应纳入版本 |
-| 向量缓存目录 | 任意非叶段等于 `embedding_cache` | embedding 缓存为派生数据 |
-| 向量索引文件 | 叶子文件以 `.faiss` 或 `.index` 结尾 | 纯计算产物,体积大且可重建 |
-
-L0/L1 派生文件(`.abstract.md`、`.overview.md`)未命中任一剪枝规则,**会**纳入主线 commit。restore 时随源文件一起回滚,无需重新生成;Python 层在 `restore` 完成后按 `(written_paths, deleted_paths)` 精确触发 L0/L1/DETAIL 向量异步重建。
-
-此外,版本管理支持账号级 `.ovgitignore` 控制文件,物理路径为 `/local/{account_id}/.ovgitignore`,Git tree path 为 `.ovgitignore`。该文件使用账号根相对的 glob 子集规则,在 `commit` 枚举当前 VFS 文件和扫描上一版 tree 时共同生效;匹配的文件不会进入新的 snapshot commit,即使它们曾存在于历史 commit 中。`.ovgitignore` 文件自身始终进入版本管理,规则无法把它排除。
-
-## 4.3 单库多命名空间的优势
-
-1. **原子跨 scope 快照**:一次 commit 可同时覆盖 `resources/docs` 和 `agent/skills`,对应"Agent 一次任务的所有产出"这种逻辑事务
-2. **定向回滚**:restore 时可指定 `paths=["resources/docs/auth.md"]`,只回滚单个文件
-3. **索引数据线性**:objects/refs 数量随账号线性,不随 resource 数量指数膨胀
-4. **权限边界清晰**:account\_id 已经是天然的隔离单位,Git 仓库边界与现有权限模型完全对齐
-
-***
-
-# 5. 物理布局
-
-## 5.1 Crate 目录结构
-
-Git 模块作为 `crates/ragfs` 的子模块,与 `core/`、`plugins/`、`server/` 平级。新增文件全部位于 `crates/ragfs/src/git/` 下,Python binding 仅在 `crates/ragfs-python/src/lib.rs` 上追加方法,无新 crate。
-
-```
-crates/ragfs/src/
-├── core/ # 既有(不动)
-├── plugins/ # 既有(不动)
-├── server/ # 既有(不动)
-└── git/ # 新增
- ├── mod.rs # 模块入口 + 重导出
- ├── service.rs # GitService(commit/restore/show 主流程,均在此文件)
- ├── object_store.rs # ObjectStore trait
- ├── ref_store.rs # RefStore trait
- ├── tree_builder.rs # TreeEditor + flatten/lookup 工具
- ├── commit.rs # write_commit / Actor / 时间戳
- ├── enumerate.rs # 从 MountableFS 枚举 + prune_path 剪枝
- ├── util.rs # zlib 压缩/解压、ref 名校验、loose object 读写
- ├── types.rs # 请求/响应 DTO
- ├── error.rs # GitError / ObjectStoreError / RefStoreError(thiserror)
- ├── config.rs # GitConfig(serde)
- └── backends/
- ├── mod.rs
- ├── local.rs # LocalObjectStore / LocalRefStore(直接使用 tokio::fs)
- └── s3.rs # S3ObjectStore / S3RefStore(直接使用 aws_sdk_s3 + If-Match)
-
-crates/ragfs-python/src/
-└── lib.rs # 追加 git_commit / git_restore / git_show 方法
-
-openviking/openviking/storage/
-└── viking_fs.py # 追加 commit / restore / show / log + URI↔tree-path 工具
-```
-
-## 5.2 依赖增量
-
-仅引入 gitoxide 中实现 commit/restore/show MVP 所需的最小子 crate 集合,通过 `crates/ragfs/Cargo.toml` 增量声明:
-
-```toml
-[dependencies]
-# === Git (gitoxide) ===
-gix-hash = "0.14" # ObjectId / Hash 抽象
-gix-object = "0.42" # Blob/Tree/Commit 编解码 + tree::Editor
-gix-actor = "0.31" # 作者/提交者签名(name ts tz)
-gix-date = "0.8" # 时间戳格式化
-
-# === Zlib 压缩 ===
-flate2 = "1" # loose object zlib 编解码
-
-# === S3 后端 ===
-aws-sdk-s3 = ... # S3 API client(直接依赖,不复用 plugins/s3fs 内部封装)
-aws-config = ...
-
-[dev-dependencies]
-tempfile = "3"
-```
-
-> 💡 **说明:** 不引入 `gitoxide` 顶层 crate,只挑选 commit/restore/show MVP 必需的子 crate;不引入 `gix-pack`(MVP 只用 loose object 格式)、不引入 `gix-protocol`(无 push/pull 需求)、不引入 `gix-worktree`(restore 通过 VFS 完成)。
->
-> - 实际实现使用 `flate2` 直接做 zlib 编解码,而非 `gix-features`,以减少 gitoxide 依赖面。
-> - ref 名校验由 `crates/ragfs/src/git/util.rs` 中自实现的 `validate_ref_name` 完成,未引入 `gix-validate`。
-> - 并发模型测试(`loom`)与 fuzz 测试(`proptest`)在 MVP 阶段未引入,以单测 + 集成测试覆盖。
-
-***
-
-# 6. 核心 Trait 设计
-
-## 6.1 ObjectStore
-
-`ObjectStore` 是 Git 内容寻址存储的抽象,提供 blob/tree/commit 三类对象的存取。所有写入按 SHA-1 内容寻址,天然幂等(同样的字节 → 同样的 oid)。trait 必须 `Send + Sync + 'static`,以便在 Tokio 多线程运行时中跨任务共享。
-
-```rust
-// crates/ragfs/src/git/object_store.rs
-use async_trait::async_trait;
-use bytes::Bytes;
-use gix_hash::ObjectId;
-
-/// 内容寻址的 Git 对象存储抽象
-/// put 必须幂等;get 不存在返回 NotFound;exists 不读取内容
-#[async_trait]
-pub trait ObjectStore: Send + Sync + 'static {
- /// 写入一个已 zlib 压缩的 loose object
- /// oid 必须等于 SHA-1(未压缩 header + payload)
- async fn put(
- &self,
- account: &str,
- oid: &ObjectId,
- zlib_body: Bytes,
- ) -> Result<(), ObjectStoreError>;
-
- /// 读取并 zlib 解压(返回 header + payload 的原始字节)
- async fn get(
- &self,
- account: &str,
- oid: &ObjectId,
- ) -> Result<Bytes, ObjectStoreError>;
-
- /// 仅检查存在性(HEAD/stat 优化,跳过内容传输)
- async fn exists(
- &self,
- account: &str,
- oid: &ObjectId,
- ) -> Result<bool, ObjectStoreError>;
-}
-
-#[derive(Debug, thiserror::Error)]
-pub enum ObjectStoreError {
- #[error("object not found: {0}")]
- NotFound(ObjectId),
- #[error("backend io: {0}")]
- Io(#[from] std::io::Error),
- #[error("zlib decode: {0}")]
- Zlib(String),
- #[error("oid mismatch: expected {expected}, got {actual}")]
- OidMismatch { expected: ObjectId, actual: ObjectId },
- #[error("backend error: {0}")]
- Backend(String),
-}
-```
-
-> ℹ️ **说明:** 物理路径布局由各实现自行决定(local 走 fanout 目录,s3 走 key prefix),trait 层不暴露物理路径,只暴露逻辑寻址。
-
-## 6.2 RefStore
-
-`RefStore` 是分支/标签的命名引用存储,核心是 **CAS(Compare-And-Swap)** 更新原语 — 这是 Git 一致性的基石。CAS 保证"两个并发 commit 先到先得,后到的看到 `Conflict` 并需要重试或 rebase",避免静默覆盖。
-
-```rust
-// crates/ragfs/src/git/ref_store.rs
-use async_trait::async_trait;
-use gix_hash::ObjectId;
-
-#[async_trait]
-pub trait RefStore: Send + Sync + 'static {
- /// 读取 ref 的当前值;不存在返回 NotFound
- async fn read(
- &self,
- account: &str,
- ref_name: &str,
- ) -> Result<ObjectId, RefStoreError>;
-
- /// Compare-And-Swap 更新:仅当当前值 == expected 时才写入 new
- /// expected = None 表示"仅当 ref 不存在时创建"
- async fn cas_update(
- &self,
- account: &str,
- ref_name: &str,
- expected: Option<ObjectId>,
- new: ObjectId,
- ) -> Result<(), RefStoreError>;
-
- /// 列出 account 下的所有 refs(用于 log / branch 列表)
- async fn list(
- &self,
- account: &str,
- prefix: &str,
- ) -> Result<Vec<(String, ObjectId)>, RefStoreError>;
-}
-
-#[derive(Debug, thiserror::Error)]
-pub enum RefStoreError {
- #[error("ref not found: {0}")]
- NotFound(String),
- #[error("CAS conflict: expected {expected:?}, actual {actual:?}")]
- Conflict {
- expected: Option<ObjectId>,
- actual: Option<ObjectId>,
- },
- #[error("invalid ref name: {0}")]
- InvalidName(String),
- #[error("backend io: {0}")]
- Io(#[from] std::io::Error),
- #[error("backend: {0}")]
- Backend(String),
-}
-```
-
-> ⚠️ **注意:** ref 名必须经 `crate::git::util::validate_ref_name(...)` 校验,拒绝 `..`、空字符、特殊保留字等,避免路径穿越和注入(实现位于 `git/util.rs`,未引入 `gix-validate`)。
-
-## 6.3 命名约定
-
-| 类别 | 路径模板 | 说明 |
-| ----------- | --------------------------------------- | -------------------------------------------------------- |
-| Object | `{root}/{account}/objects/{aa}/{bb...}` | Git 标准 fanout(前 2 hex 为目录,后 38 hex 为文件名),便于分布式存储 list 优化 |
-| Ref (heads) | `{root}/{account}/refs/heads/{branch}` | 文件内容 = 40 hex 字符 + `\n` |
-| HEAD | `{root}/{account}/HEAD` | 内容 = `ref: refs/heads/main\n` |
-| Packed-refs | (不实现) | MVP 全部 loose,后续如 ref 数量爆炸再补 pack |
-
-***
-
-# 7. 后端实现
-
-## 7.1 LocalObjectStore / LocalRefStore
-
-**LocalObjectStore** 直接调用 `tokio::fs`(不经 MountableFS、也不复用 `LocalFileSystem`),把 Git 对象写入本地磁盘的 `{base_dir}/{account}/objects/{aa}/{bb...}`。**LocalRefStore** 使用进程内的 `DashMap<(account, ref_name), Arc<Mutex<()>>>` 串行化同 ref 的 CAS,叠加 `tempfile + rename(2)` 的原子重命名,覆盖同进程并发场景。
-
-> **当前实现限制:** MVP 仅做了进程内 Mutex,**未叠加** `flock` 跨进程锁。生产部署若存在同 host 多进程同时写同一账号的场景,需要在后续版本补 `flock`。
-
-```rust
-// crates/ragfs/src/git/backends/local.rs (节选)
-pub struct LocalObjectStore {
- base_dir: PathBuf, // e.g. /data/openviking/git
-}
-
-#[async_trait]
-impl ObjectStore for LocalObjectStore {
- async fn put(&self, account: &str, oid: &ObjectId, body: Bytes) -> Result<()> {
- let hex = oid.to_hex().to_string();
- let path = self.base_dir
- .join(account).join("objects")
- .join(&hex[..2]).join(&hex[2..]);
- // 内容寻址 → 已存在则跳过(幂等)
- if tokio::fs::try_exists(&path).await? { return Ok(()); }
- tokio::fs::create_dir_all(path.parent().unwrap()).await?;
- // 写临时文件 + rename 保证原子性
- let tmp = path.with_extension("tmp");
- tokio::fs::write(&tmp, &body).await?;
- tokio::fs::rename(&tmp, &path).await?;
- Ok(())
- }
- // get / exists 略
-}
-
-pub struct LocalRefStore {
- base_dir: PathBuf,
- // 进程内串行化 CAS,key = (account, ref_name)
- locks: dashmap::DashMap<(String, String), Arc<Mutex<()>>>,
-}
-
-#[async_trait]
-impl RefStore for LocalRefStore {
- async fn cas_update(
- &self,
- account: &str,
- name: &str,
- expected: Option<ObjectId>,
- new: ObjectId,
- ) -> Result<()> {
- validate_ref_name(name)?; // util.rs 自实现
- let lock = self.locks
- .entry((account.into(), name.into()))
- .or_default().clone();
- let _guard = lock.lock().await;
- let path = self.ref_path(account, name);
- let actual = read_ref_opt(&path).await?;
- if actual != expected {
- return Err(RefStoreError::Conflict { expected, actual });
- }
- let tmp = path.with_extension("tmp");
- tokio::fs::write(&tmp, format!("{}\n", new.to_hex())).await?;
- // rename 保证 crash-consistency
- tokio::fs::rename(&tmp, &path).await?;
- Ok(())
- }
-}
-```
-
-## 7.2 S3ObjectStore / S3RefStore
-
-**S3ObjectStore** 直接持有一个 `Arc<aws_sdk_s3::Client>`(MVP 不复用 `plugins::s3fs::S3Client`,以解耦 git 模块与 plugin 体系),将 object 存为 `{prefix}/{account}/objects/{aa}/{bb...}`。由于内容寻址,`put` 用 `If-None-Match: *` 头实现幂等"仅首次写入"。**S3RefStore** 用 `If-Match: "{etag}"` 实现 CAS,先 `GET` 拿当前值与 ETag,再用 `PUT` 条件写。
-
-> **CAS 模式:** `CasMode::Native` 已实现并默认启用;`CasMode::RedisLock` 仅作为枚举占位,**实际尚未实现**,调用会直接返回 `RefStoreError::Backend("RedisLock CAS mode not yet implemented")`。
-
-```rust
-// crates/ragfs/src/git/backends/s3.rs (节选)
-pub struct S3RefStore {
- client: Arc<aws_sdk_s3::Client>,
- bucket: String,
- prefix: String,
- cas_mode: CasMode, // Native | RedisLock(占位,未实现)
-}
-
-#[async_trait]
-impl RefStore for S3RefStore {
- async fn cas_update(
- &self,
- account: &str,
- name: &str,
- expected: Option<ObjectId>,
- new: ObjectId,
- ) -> Result<()> {
- validate_ref_name(name)?;
- match self.cas_mode {
- CasMode::Native => {
- // 1. GET 当前 body 与 ETag
- let current = self.read_ref_opt(account, name).await?;
- let (current_oid, current_etag) = match current {
- Some((oid, etag)) => (Some(oid), etag),
- None => (None, None),
- };
- if current_oid != expected {
- return Err(RefStoreError::Conflict {
- expected, actual: current_oid,
- });
- }
- // 2. 条件 PUT
- let body = format!("{}\n", new.to_hex());
- let put = self.client.put_object()
- .bucket(&self.bucket).key(&self.ref_key(account, name))
- .body(body.into_bytes().into());
- let put = match (current_etag, expected) {
- (Some(etag), Some(_)) => put.if_match(etag),
- (None, None) => put.if_none_match("*"),
- _ => return Err(RefStoreError::Conflict {
- expected, actual: current_oid,
- }),
- };
- // 412 → Conflict;其他 → Backend
- map_precondition_failed(put.send().await, expected, current_oid)
- }
- CasMode::RedisLock => Err(RefStoreError::Backend(
- "RedisLock CAS mode not yet implemented".into(),
- )),
- }
- }
-}
-```
-
-> ⚠️ **S3 CAS 兼容性提示:** AWS S3 自 2024 年起支持 `If-Match` / `If-None-Match` 条件写;TOS / OSS 实现情况需在选型时验证。若某后端不支持原生 CAS,需退化为"分布式锁 + GET-then-PUT"模式;`RedisLock` 模式已在配置/枚举中预留,但实现待补。
-
-***
-
-# 8. GitService 主流程
-
-## 8.1 commit 完整实现
-
-commit 主流程:**枚举 → 读 blob → 构建 tree → 构建 commit → CAS 更新 ref**。所有 ObjectStore 写入按账号粒度幂等(同 oid 多次 put 安全),tree 写入由 `TreeEditor` 自底向上完成。tree 未变 → 不创建空 commit(no-op 优化)。绝大多数 commit 场景下,被调用方声明为 "改动" 的文件里仍有大量未真正修改,需要通过三级 fast path 层层过滤,保证只有真正变化的字节才进入 streaming hash 与 blob 写入。
-
-| 层级 | 触发条件 | 节省的开销 | 实现位置 |
-| ------------------------------ | --------------------------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| **Fast Path 1**: Stat 索引复用 oid | 文件 (size, mtime\_ns) 与 prev\_index 完全一致 | 跳过 `vfs.read` + sha1 hash | **已实现**(`IndexStore` trait + `LocalIndexStore`/`S3IndexStore`,`CommitIndex` 与 `parent_oid` 绑定,索引 miss/decode 错误/parent 不匹配 → 静默回退 slow path;通过 `git.tuning.commit_index_enabled` 关闭) |
-| **Fast Path 2**: Tree 子树原样保留 | 子树下所有路径都没 upsert/remove | 跳过子树重 hash + 新 tree object 写入 | **已实现**(`TreeEditor::from_tree` 惰性加载 root,未被 upsert/remove/upsert\_subtree 触及的子树连读取+zlib 解压都省掉,由 `write_subtree` 的 `None` 分支原样复用其 OID) |
-| **Fast Path 3**: Blob CAS 去重 | 算出的 oid 在 object\_store 已存在 | 跳过 zlib 压缩 + put\_blob (本地写盘 / S3 PUT) | **已实现**(slow path 写 blob 前在 service 层调用 `object_store.exists` 预检,命中则跳过 zlib 压缩与 `put`;范围严格限定 blob,tree/commit 不预检;通过 `git.tuning.blob_exists_precheck_enabled` 关闭) |
-
-```rust
-// crates/ragfs/src/git/service.rs ::commit (节选)
-pub async fn commit(&self, req: CommitRequest) -> Result<CommitResponse> {
- let CommitRequest {
- account, branch, message, paths, author_name, author_email,
- } = req;
-
- // 1. 解析当前 HEAD,加载 prev_tree(若 ref 不存在则空 tree)
- let prev_head = self.resolve_ref(&account, &branch).await.ok();
- let prev_tree = match prev_head {
- Some(oid) => self.load_commit(&account, &oid).await?.tree,
- None => empty_tree_oid(),
- };
- let mut editor = TreeEditor::from_tree(
- &self.object_store, &account, prev_tree,
- ).await?;
- let mut changed = 0usize;
-
- // 2. 候选路径:paths=Some → 经 prune_path 过滤后的清单;paths=None → enumerate::collect_all 全量
- let candidates = match &paths {
- Some(ps) => ps.iter().filter_map(prune_path).collect(),
- None => enumerate::collect_all(&self.vfs, &account).await?,
- };
-
- for path in candidates {
- match self.vfs.stat(&account_path(&account, &path)).await {
- Ok(_) => {
- // 读全量 + streaming hash + 写 blob(无 Fast Path 1/3)
- let bytes = self.vfs.read(&account_path(&account, &path)).await?;
- let oid = sha1_blob_streaming(&bytes);
- self.write_object(&account, &oid, &bytes).await?; // 幂等
- editor.upsert(&path, oid)?;
- changed += 1;
- }
- Err(e) if is_not_found(&e) => {
- // 文件被删 → 从 tree 中移除
- editor.remove(&path)?;
- changed += 1;
- }
- Err(e) => return Err(e.into()),
- }
- }
-
- // 3. 无任何变化 → noop
- if changed == 0 {
- return Ok(CommitResponse::Noop {
- commit_oid: prev_head.unwrap_or_default(),
- });
- }
-
- // 4. 写 tree + commit
- let new_tree = editor.write(&self.object_store, &account).await?;
- let commit_oid = write_commit(&self.object_store, &account, CommitObject {
- tree: new_tree,
- parents: prev_head.into_iter().collect(),
- author: Actor::now(&author_name, &author_email),
- committer: Actor::now(&author_name, &author_email),
- message: message.into(),
- }).await?;
-
- // 5. CAS 更新 ref;失败 → ConcurrentCommit 直接上抛
- // 注意:当前实现中 commit() 内部不做 retry,由调用方决定如何处理冲突。
- self.ref_store.cas_update(
- &account, &format!("refs/heads/{}", branch),
- prev_head, commit_oid,
- ).await?;
-
- Ok(CommitResponse::Created { commit_oid, changed })
-}
-```
-
-> **关于 retry:** 当前实现中 `commit()` 内部 **不包含 CAS 重试循环**(代码中明确注释 `// There is intentionally no retry loop inside commit().`)。冲突直接以 `ConcurrentCommit` 上抛,由 Python 层或上游业务决定重试策略;这与 §11.3 旧版描述的"内部最多重试 3 次"不一致,以本节为准。
-
-## 8.2 restore 完整实现
-
-restore 主流程:**解析目标 commit → 提取该 commit 中 project\_dir 子树 → 与当前 HEAD 中同路径子树 diff → 通过 MountableFS.write/rm 回写 → 删除回写后空目录 → 以当前 HEAD 为 parent 生成新 commit → CAS 更新 ref → 把受影响路径返回给调用方**。`dry_run` 模式只计算差异不写,用于预检。
-
-> **`.ovgitignore` 与 restore:** `.ovgitignore` 只影响 `commit`,不影响 `restore` / `show` / `log`。restore 的输入是 source commit 与当前 HEAD 的 Git tree diff,不能用当前工作区 `.ovgitignore` 过滤,否则会导致历史 commit 中已经被跟踪的文件无法恢复。全账号 restore 时 `.ovgitignore` 作为普通已跟踪文件随 source commit 恢复;子目录 restore 默认不触碰账号根 `.ovgitignore`。
-
-向量索引重建在 service 层**不直接触发**,而是通过把 `written_paths` / `deleted_paths` 放到 `RestoreResponse::Applied` 中返回,Python 层(`VikingFS.restore`)再调度 `ReindexExecutor`。
-
-关键差异:与 git checkout 不同,本接口**不移动分支指针到旧 commit**,而是把"旧内容"作为新 commit 的工作树内容,正向写入。新 commit 的 parent 是当前 HEAD,不是目标 commit,这保证了:(1) HEAD 单调前进;(2) 非 `project_dir` 路径自动保留 HEAD 的最新内容,无需特殊处理;(3) restore 本身可以被再次 restore (因为它就是一个普通 commit)。
-
-```rust
-pub async fn restore(&self, req: RestoreRequest) -> Result<RestoreResponse> {
- let RestoreRequest {
- account, branch, project_dir, source_commit, dry_run, message,
- author_name, author_email,
- } = req;
-
- // 0. 校验 project_dir(非空、不含 ..、不命中 prune 规则)
- validate_project_dir(&project_dir)?;
-
- // 1. 解析两端 commit
- let source_oid = self.resolve_ref(&account, &source_commit).await?;
- let source = self.load_commit(&account, &source_oid).await?;
- let head_oid = self.resolve_ref(&account, &branch).await?; // 必须已有 HEAD
- let head = self.load_commit(&account, &head_oid).await?;
-
- // 2. 在两棵 tree 中分别"截取" project_dir 子树
- // source 没有该子目录 → 视为空树(等价于把整个目录删掉)
- let source_subtree = tree_builder::subtree(...).await?
- .unwrap_or(empty_tree_oid());
- let head_subtree = tree_builder::subtree(...).await?
- .unwrap_or(empty_tree_oid());
-
- // 3. 子树之间 diff,得到三类操作(只限 project_dir 范围内)
- let target_entries = flatten(&self.object_store, &account, source_subtree).await?;
- let current_entries = flatten(&self.object_store, &account, head_subtree).await?;
- let diff = compute_subtree_diff(&target_entries, &current_entries);
-
- if dry_run {
- return Ok(RestoreResponse::DryRun { diff, source_oid, head_oid });
- }
- if diff.is_empty() {
- return Ok(RestoreResponse::Noop { head: head_oid, source: source_oid });
- }
-
- // 4. 并发回写 VFS:路径要带上 project_dir 前缀
- // 走完整 viking_fs.write/rm,触发现有 lock、加密
- let prefixed = |p: &str| format!("{}/{}", project_dir.trim_end_matches('/'), p);
- let written_paths: Vec<String> = stream::iter(diff.to_write)
- .map(|(path, blob_oid)| async move {
- let body = self.read_blob(&account, &blob_oid).await?;
- self.vfs.write(&account_path(&account, &prefixed(&path)), body).await?;
- Ok::<_, GitError>(prefixed(&path))
- })
- .buffer_unordered(32) // 当前实现硬编码 32
- .try_collect().await?;
- let deleted_paths: Vec<String> = stream::iter(diff.to_delete)
- .map(|path| {
- let p = prefixed(&path);
- async move {
- // 幂等删除:NotFound 视为成功,允许 restore 在已被并发删除的路径上完成
- match self.vfs.rm(&account_path(&account, &p)).await {
- Ok(()) => Ok(p),
- Err(e) if is_not_found(&e) => Ok(p),
- Err(e) => Err(e.into()),
- }
- }
- })
- .buffer_unordered(32)
- .try_collect().await?;
-
- // 6b. 删除空目录:沿被删路径的祖先链向上 rmdir,直到第一个非空目录或 project_dir 边界
- // (gix tree 不存空目录,而 VFS 写到本地后会留下空 dir,造成 ls 不一致)
- self.prune_empty_dirs(&account, &project_dir, &deleted_paths).await?;
-
- // 5. 在 head.tree 之上做增量编辑:
- // 把 project_dir 子树整体替换为 source_subtree。
- // 非 project_dir 路径原样保留 head 中的 tree_oid。
- let mut editor = TreeEditor::from_tree(&self.object_store, &account, head.tree).await?;
- editor.upsert_subtree(&project_dir, source_subtree)?;
- let new_tree = editor.write(&self.object_store, &account).await?;
-
- // 6. 构造新 commit:parent = 当前 HEAD(不是 source_oid!)
- let new_commit_oid = write_commit(&self.object_store, &account, CommitObject {
- tree: new_tree,
- parents: vec![head_oid], // ← 关键:HEAD 单向前进
- author: Actor::now(&author_name, &author_email),
- committer: Actor::now(&author_name, &author_email),
- message: message.unwrap_or_else(|| format!(
- "restore {} from {}", project_dir, &source_oid.to_hex()[..12],
- )),
- }).await?;
-
- // 7. CAS 更新 ref:expect=head_oid, new=new_commit_oid
- // 若期间有别的 commit 进入 → ConcurrentCommit,调用方按提示重试
- self.ref_store.cas_update(
- &account, &format!("refs/heads/{}", branch),
- Some(head_oid), new_commit_oid,
- ).await?;
-
- Ok(RestoreResponse::Applied {
- new_commit_oid,
- source_commit: source_oid,
- parent_commit: head_oid,
- // 计数 + 受影响路径(供上层精确触发向量重建)
- written: written_paths.len(),
- deleted: deleted_paths.len(),
- unchanged: diff.unchanged.len(),
- written_paths,
- deleted_paths,
- })
-}
-```
-
-> 当前实现相对早期设计的差异
->
-> - **空目录清理(步骤 6b)**:删除完文件后会沿祖先链 rmdir 至 `project_dir` 或第一个非空目录,避免 VFS 残留空目录。
-> - **幂等删除**:`vfs.rm` 返回 NotFound 视为成功,使 restore 可以在已被并发清理的路径上继续推进。
-> - **written\_paths / deleted\_paths**:`Applied` 响应除了 `written/deleted` 计数外,还返回**全量受影响路径(已加 project\_dir 前缀)**;Python 层按 marker / 源文件分类,精确触发 L0/L1/DETAIL 向量更新,不再依赖广义的 `_trigger_vector_rebuild(paths)`。
-> - **没有 commit\_index 刷新**:对应 §8.1 的 Fast Path 1 未实现,restore 末尾也无须刷新 index。
-> - **回写并发度**:当前硬编码 `buffer_unordered(32)`,尚未提供配置项。
->
-> ✅ **推荐:** 生产环境调用前先以 `dry_run=true` 跑一遍取得差异列表,再让用户确认,避免误覆盖未提交的本地变更。
-
-## 8.3 show 完整实现
-
-show 是**纯读路径**,无任何 VFS 写入或 ref 变更,易于实现与验证。支持两种模式:`path=None` 返回 commit 元信息(用于 log 列表);`path=Some(p)` 返回该 path 的 blob 字节(零拷贝 `Bytes` 切片)。
-
-```rust
-pub async fn show(&self, req: ShowRequest) -> Result<ShowResponse> {
- let ShowRequest { account, target_ref, path } = req;
-
- // 1. ref 解析:依次尝试
- // a. 40-hex commit_oid → 直接解析
- // b. 4..=39 hex 的缩写 oid → 沿 HEAD 父链回溯,找到唯一前缀匹配的 commit
- // (歧义返回 AmbiguousOid;无匹配返回 OidPrefixNotFound)
- // c. branch 名(如 "main") → 加前缀 refs/heads/{branch}
- // d. 全路径 refs/heads/xxx → 透传
- let commit_oid = self.resolve_ref(&account, &target_ref).await?;
- let commit = self.load_commit(&account, &commit_oid).await?;
-
- match path {
- // 模式 A:返回 commit 元信息(log 用)
- None => Ok(ShowResponse::Commit {
- oid: commit_oid,
- tree: commit.tree,
- parents: commit.parents,
- author: commit.author.into(),
- committer: commit.committer.into(),
- message: commit.message.to_string(),
- }),
-
- // 模式 B:返回该 path 的 blob 字节
- Some(p) => {
- // 按 / 拆分,在 tree 上逐层递归;
- // - path 命中目录 → PathIsDirectory(p)
- // - path 完全无对应 → PathNotFound(p)
- let blob_oid = tree_builder::lookup(
- &self.object_store, &account, commit.tree, &p,
- ).await?;
-
- let blob_full = self.load_blob(&account, &blob_oid).await?;
- // 去掉 "blob {len}\0" header,使用 Bytes::slice 零拷贝返回 payload
- let payload = strip_object_header(blob_full)?;
- Ok(ShowResponse::Blob {
- oid: blob_oid,
- size: payload.len() as u64,
- bytes: payload,
- })
- }
- }
-}
-```
-
-***
-
-# 9. Python Binding 与 VikingFS 集成
-
-## 9.1 PyO3 binding 新增方法
-
-在现有 `RAGFSBindingClient`(`crates/ragfs-python/src/lib.rs`)上追加三个 `#[pymethods]`。模式与 `ls/read/write` 一致:用 `py_detach_blocking` 释放 GIL,在 Tokio runtime 内调 `GitService`,返回结果序列化为 `PyDict`。
-
-```rust
-// crates/ragfs-python/src/lib.rs (追加)
-#[pymethods]
-impl RAGFSBindingClient {
- /// 提交一次快照
- /// kwargs: account, branch, message, paths(Option<Vec<String>>),
- /// author_name, author_email
- /// returns: {"commit_oid": str, "result": "created" | "noop"}
- fn git_commit(&self, py: Python<'_>, kwargs: &PyDict) -> PyResult<PyObject> {
- let req = parse_commit_request(kwargs)?;
- let svc = self.git_service()?; // FeatureDisabled 时返回 PyErr
- py_detach_blocking(py, || {
- self.runtime.block_on(svc.commit(req))
- .map_err(map_git_error)
- }).map(|r| commit_response_to_pydict(py, r))
- }
-
- /// 定向恢复某个 project 目录,正向生成新 commit
- /// kwargs: account, branch(默认 "main"), project_dir, source_commit,
- /// dry_run(bool=false), message(Option<String>),
- /// author_name, author_email
- /// returns:
- /// Applied: {"new_commit_oid": str, "source_commit": str, "parent_commit": str,
- /// "written": int, "deleted": int, "unchanged": int}
- /// Noop: {"noop": true, "head": str, "source": str}
- /// DryRun: {"dry_run": true, "diff": {...}, "head": str, "source": str}
- fn git_restore(&self, py: Python<'_>, kwargs: &PyDict) -> PyResult<PyObject> {
- let req = parse_restore_request(kwargs)?;
- let svc = self.git_service()?;
- py_detach_blocking(py, || self.runtime.block_on(svc.restore(req))
- .map_err(map_git_error))
- .map(|r| restore_response_to_pydict(py, r))
- }
-
- /// 读取 ref / commit / blob
- /// kwargs: account, target_ref, path(Option)
- /// returns:
- /// path=None: {"oid","tree","parents","author","committer","message"}
- /// path=str: {"oid","size","bytes": PyBytes}
- fn git_show(&self, py: Python<'_>, kwargs: &PyDict) -> PyResult<PyObject> {
- let req = parse_show_request(kwargs)?;
- let svc = self.git_service()?;
- py_detach_blocking(py, || {
- self.runtime.block_on(svc.show(req))
- .map_err(map_git_error)
- }).map(|r| show_response_to_pydict(py, r))
- }
-}
-
-/// GitError → Python 异常映射(在 openviking 侧定义对应异常类)
-fn map_git_error(e: GitError) -> PyErr {
- match e {
- GitError::FeatureDisabled => PyRuntimeError::new_err("git feature disabled"),
- GitError::ConcurrentCommit => PyValueError::new_err("concurrent commit conflict"),
- GitError::PathNotFound(p) => PyFileNotFoundError::new_err(p),
- GitError::RefNotFound(r) => PyFileNotFoundError::new_err(r),
- other => PyRuntimeError::new_err(other.to_string()),
- }
-}
-```
-
-## 9.2 Python 侧 VikingFS 新增方法
-
-在 `openviking/openviking/storage/viking_fs.py` 的 `VikingFS` 类上追加 4 个公开方法。Python 调用方使用 `viking://` URI,内部经 `_uri_to_tree_path` 转换为账号内 tree 路径后再传给 binding。
-
-```python
-# openviking/storage/viking_fs.py (追加)
-class VikingFS:
- # 已有: read / write / rm / ls / mv / mkdir ...
-
- async def commit(
- self,
- *,
- message: str,
- paths: list[str] | None = None, # viking://... URIs
- branch: str = "main",
- author_name: str | None = None,
- author_email: str | None = None,
- ) -> dict:
- """提交一次跨 scope 快照。返回 {commit_oid, result}."""
- account = self._current_account()
- tree_paths = [self._uri_to_tree_path(p) for p in (paths or [])]
- return await self._async_client.run(
- "git_commit",
- account=account,
- branch=branch,
- message=message,
- paths=tree_paths or None,
- author_name=author_name or self._default_author_name(),
- author_email=author_email or self._default_author_email(),
- )
-
- async def get_gitignore(self, ctx: RequestContext | None = None) -> str:
- """读取账号级 .ovgitignore;不存在时返回空字符串。"""
-
- async def set_gitignore(
- self,
- content: str,
- ctx: RequestContext | None = None,
- ) -> None:
- """写入账号级 .ovgitignore,不触发语义索引。"""
-
- async def delete_gitignore(self, ctx: RequestContext | None = None) -> None:
- """删除账号级 .ovgitignore;不存在视为成功。"""
-
- async def restore(
- self,
- *,
- project_dir: str, # viking://resources/proj_a/ 或 "resources/proj_a"
- source_commit: str, # 40-hex / branch / tag
- branch: str = "main",
- dry_run: bool = False,
- message: str | None = None,
- author_name: str | None = None,
- author_email: str | None = None,
- ) -> dict:
- """将 project_dir 恢复到 source_commit 状态,生成一个新 commit。
-
- 语义等价于 git restore --source=<source_commit> --worktree --staged
- <project_dir>/ && git commit。HEAD 单调前进,不会回退。
- """
- account = self._current_account()
- tree_dir = self._uri_to_tree_path(project_dir).rstrip("/")
- result = await self._async_client.run(
- "git_restore",
- account=account, branch=branch,
- project_dir=tree_dir, source_commit=source_commit,
- dry_run=dry_run, message=message,
- author_name=author_name or self._default_author_name(),
- author_email=author_email or self._default_author_email(),
- )
- if dry_run or result.get("noop"):
- return result
-
- # 增量向量更新:只对受影响的源文件,逐个 vectors_only 重算。
- # L0/L1 派生文件已随源文件一起从 git 回写到 VFS,不需要重新生成。
- from openviking.service.reindex_executor import ReindexExecutor
- executor = ReindexExecutor()
- ctx = self._current_request_context()
- for affected_path in result.get("affected_files", []):
- affected_uri = self._tree_path_to_uri(affected_path)
- if self._is_derived_file(affected_uri):
- continue
- asyncio.create_task(executor.execute(
- uri=affected_uri, mode="vectors_only",
- wait=False, ctx=ctx,
- ))
- return result
-
- async def show(
- self,
- target_ref: str,
- *,
- path: str | None = None,
- ) -> dict | bytes:
- """path=None → commit 元信息;path=str → blob 字节。"""
- account = self._current_account()
- tree_path = self._uri_to_tree_path(path) if path else None
- resp = await self._async_client.run(
- "git_show",
- account=account,
- target_ref=target_ref,
- path=tree_path,
- )
- if "bytes" in resp:
- return resp["bytes"]
- return resp
-
- async def log(
- self,
- *,
- branch: str = "main",
- limit: int = 20,
- ) -> list[dict]:
- """便捷封装:沿 parent 链反向遍历 commit。"""
- account = self._current_account()
- head = await self._async_client.run(
- "git_show", account=account, target_ref=branch, path=None,
- )
- result, current = [head], head.get("parents", [])
- while current and len(result) < limit:
- parent_oid = current[0]
- commit = await self._async_client.run(
- "git_show", account=account, target_ref=parent_oid, path=None,
- )
- result.append(commit)
- current = commit.get("parents", [])
- return result
-
- # --- 工具方法 ---
- def _uri_to_tree_path(self, uri: str) -> str:
- """viking://resources/a.md → 'resources/a.md'
- (去掉 viking:// 前缀,保留 scope 段作为 tree 一级目录)"""
- parsed = VikingURI.parse(uri)
- if parsed.scope in INTERNAL_SCOPES:
- raise ValueError(f"internal scope not versioned: {parsed.scope}")
- return f"{parsed.scope}/{parsed.relative_path}"
-
- async def _trigger_vector_rebuild(
- self, account: str, paths: list[str]
- ) -> None:
- """restore 后异步触发向量索引重建。
- 实现可对接现有的 watcher / 任务队列;失败不影响 restore 结果。"""
- try:
- await self._vector_service.rebuild(account, paths)
- except Exception:
- logger.exception("vector rebuild failed for %s", account)
-```
-
-***
-
-# 10. 配置规范
-
-## 10.1 与 resources 对称的配置布局
-
-配置位于现有 RAGFS 配置文件的 `[git]` 段,布局与 `[plugins.localfs_resources]` / `[plugins.s3fs_resources]` 完全对称,便于运维心智复用。`enabled = false` 时 binding 方法返回 `FeatureDisabled`,不影响现有 VFS。
-
-```toml
-# ragfs.toml 新增 [git] 段
-[git]
-enabled = true
-backend = "local" # "local" | "s3"
-default_branch = "main"
-author_name = "openviking-bot" # commit 默认作者
-author_email = "[email protected]"
-
-# 本地后端
-[git.local]
-base_dir = "/data/openviking/git" # objects/refs 存储根
-
-# 远程后端(与 plugins.s3fs_resources 配置同构)
-[git.s3]
-bucket = "openviking-prod"
-prefix = ".ovgit" # 全部 key = {prefix}/{account}/...
-region = "us-east-1"
-endpoint = "https://s3.amazonaws.com"
-access_key_env = "OV_S3_AK" # 从环境变量读
-secret_key_env = "OV_S3_SK"
-cas_mode = "native" # "native"(If-Match):当前唯一支持的模式
-use_path_style = true # path-style addressing(MinIO/LocalStack/TOS 默认开)
-
-# 高级调优
-[git.tuning]
-commit_index_enabled = true # Fast Path 1 总开关(默认 true);关闭后强制走 slow path,适合测试 / mtime 不可靠环境
-blob_exists_precheck_enabled = true # Fast Path 3 总开关(默认 true)
-```
-
-## 10.2 切换本地↔远程
-
-| 维度 | local → s3 改动 |
-| ---------- | ----------------------------------------------------- |
-| 配置文件 | `backend = "local"` → `backend = "s3"`;填 `[git.s3]` 块 |
-| Service 代码 | 无 |
-| Python 调用方 | 无 |
-| 数据迁移 | 一次性脚本:本地 `{base_dir}` 全量上传至 S3 key prefix(保持目录结构) |
-
-> 💡 从本地切到远程的全部成本 = 修改 `backend = "local"` → `backend = "s3"` + 填 `[git.s3]` 块。Service 代码、Python 调用方完全无感。这与 resources 目录"`plugins.localfs_resources` ↔ `plugins.s3fs_resources`"的切换体验完全对称。
-
-***
-
-# 11. 并发与一致性
-
-## 11.1 写并发模型
-
-| 层次 | 并发原语 | 说明 |
-| --------- | ------------------------ | -------------------------------- |
-| Blob 上传 | 逐文件串行 | slow path 逐个读取并写入 blob;内容寻址保证同 oid 重复 put 安全 |
-| Tree 写入 | 串行(`Editor::write` 自底向上) | 同 oid 幂等,但顺序必须自底向上 |
-| Commit 写入 | 串行,最后一步 | 同 oid 幂等 |
-| Ref 更新 | CAS | 本地: 进程锁 + rename(2);S3: If-Match |
-
-## 11.2 并发冲突处理
-
-```mermaid
-flowchart LR
- A[Client A: commit] --> A1[Read ref
-= parent_a]
- B[Client B: commit] --> B1[Read ref
-= parent_b]
- A1 --> A2[Build tree A]
- B1 --> B2[Build tree B]
- A2 --> A3[CAS update
-expected=parent_a]
- B2 --> B3[CAS update
-expected=parent_b]
- A3 --> OK1[OK new=commit_a]
- B3 --> FAIL[CasConflict
-current=commit_a]
- FAIL --> RETRY{调用方重试?}
- RETRY -- yes --> B1
- RETRY -- no --> ERR[返回 409
-给上层]
-```
-
-## 11.3 重试策略
-
-- **幂等部分(blob/tree/commit 写)**: 同 oid 多次 put 安全;后端层面通过 `If-None-Match: *`(S3)与 `try_exists`(local)短路重复写;service 层不额外做 retry。
-- **CAS 冲突**: **当前实现** GitService::commit/restore **内部不做自动重试,直接以 GitError::ConcurrentCommit 上抛给 Python 层,由调用方决定是否 re-read parent 重建 tree 重新提交。后续若实现内部重试,再增加对应调优配置。
-- **跨账号**: 不同 account\_id 的 ref 路径不同,天然无冲突,可完全并行
-
-***
-
-# 12. 安全与隔离
-
-## 12.1 账号隔离
-
-- Git 数据路径全部以 `{account_id}` 为顶层前缀,与现有 `/local/{account_id}/` 隔离模型完全一致
-- `GitService` 所有方法的第一个参数都是 `account_id`,binding 层从 `RequestContext.account_id` 注入,不允许跨账号访问
-- Path 解析时必须经过 `validate_account_id`(白名单字符集与结构规则),防止 `../` 注入
-
-## 12.2 加密
-
-> 💡 **重要:** 现有 `viking_fs.write` 在写入前会调 `_encrypt_content`。**commit 时不应再次加密**——blob 内容 = 当前 VFS 已加密内容,Git 是对密文做版本管理。restore 写回时走 `viking_fs.write`,会再次"加密"——这里需要绕过(或保持密文不变):restore 路径走 `MountableFS.write` 而非 `viking_fs.write`,避免双重加密;或为 `viking_fs.write` 增加 `raw=True` 参数,restore 调用时传入。
-
-## 12.3 资源限制
-
-| 维度 | 限制 | 措施 | 当前状态 |
-| ------------ | -------------------------------- | ------------------------------------ | ------------------------------------------------ |
-| 单 blob 大小 | ≤ 100MB | commit 前 stat 检查,超限报错 | **未实现**:commit 和普通 show 均无 100MB 全局限制;`show_with_limit` 仅在调用方显式传入上限时生效 |
-| 单 commit 文件数 | ≤ 50000 | enumerate 阶段提前拒绝 | **未实现**(`GitError::TooManyFiles` 已定义,但无运行时检查) |
-| 账号 Git 容量 | 由 quota 系统单独管控 | 放在 `[git.quota]`,首版默认 10GB | **未实现**(配置块未引入) |
-| restore 并发 | 同子树串行,同一 account\_id 全量 restore 互斥 | `VikingFS.restore` 用 `LockContext` 树锁包裹 writeback:scoped restore 锁 `project_dir`,全量 restore 锁账号根;防止 VFS 写竞态 | **已实现**(写回阶段加锁;后台 reindex 在锁释放后调度,冲突映射为 `ResourceBusyError`) |
-| 账号 ID 校验 | 白名单字符集,防 `../` 注入 | `validate_account_id` 在 service 公开入口拒绝 | **已实现**,覆盖 commit/show/log/restore 等入口并有 Rust/Python binding 测试 |
-
-***
-
-# 13. 错误处理
-
-## 13.1 错误分类
-
-顶层错误类型为 `GitError`(`crates/ragfs/src/git/error.rs`),按可恢复性与归属分组:
-
-| 类别 | Variant | 说明 |
-| --------- | ------------------------------------------------------------------------------------------- | ------------------------------------------- |
-| 后端透传 | `ObjectStore(ObjectStoreError)`、`RefStore(RefStoreError)`、`Vfs(...)` | 来自存储后端 / VFS |
-| 路径校验 | `PathNotFound(String)`、`PathIsDirectory(String)`、`InvalidProjectDir(String)`、`InvalidAccountId(String)` | show / restore / 账号入参校验 |
-| Tree 内容缺失 | `SubtreeNotFoundInCommit { commit, path }` | restore 时 source 中缺失目标子树(已通过空树语义包装,正常路径不抛出) |
-| Ref 解析 | `OidPrefixNotFound(String)`、`AmbiguousOid { prefix, candidates }` | 缩写 OID 解析失败 |
-| 并发 | `ConcurrentCommit` | CAS 失败(由 ref\_store conflict 上抛) |
-| 资源限制 | `BlobTooLarge { size, limit }`、`TooManyFiles { count, limit }` | 可选的受限 show 会触发 `BlobTooLarge`;全局 blob 大小和 commit 文件数限制尚未实现,详见 §12.3 |
-| 其他 | `FeatureDisabled`、`CorruptedObject(...)`、`Other(String)` | binding 关闭、对象腐烂、兜底 |
-
-## 13.2 Python 异常映射
-
-| Rust Error | Python Exception | 语义 |
-| -------------------------------------------------------------------- | --------------------------- | ----------- |
-| `FeatureDisabled` | `AGFSNotSupportedError` | git 模块未启用 |
-| `ConcurrentCommit` | `GitConcurrentCommitError` | 需要上层重试或人工介入 |
-| `PathNotFound` / `OidPrefixNotFound` / 后端 NotFound | `AGFSNotFoundError` | 404 语义 |
-| `PathIsDirectory` / `TooManyFiles` / `AmbiguousOid` | `AGFSInvalidOperationError` | 入参或资源错误 |
-| `BlobTooLarge` | `AGFSResourceExhaustedError` | 调用方指定的 blob 读取上限被触发 |
-| `InvalidAccountId` / `InvalidProjectDir` | `AGFSInvalidPathError` | 路径/账号 ID 非法 |
-| `CorruptedObject` / `Other` / `Vfs` | `AGFSInternalError` | 底层异常 |
-
-***
-
-# 14. 可观测性
-
-> **当前状态:** §14.1/§14.2 中描述的 tracing span / metrics **MVP 尚未接入**;§14.3 健康检查仅暴露 `git_enabled` / `git_backend` 两个字段。下面保留为目标态,未带状态标注的均为待实现项。
-
-## 14.1 Tracing/日志关键字段(目标态)
-
-- **span 名**: `git.commit`, `git.restore`, `git.show`
-- **tag**: `account_id`, `branch`, `parent_oid`, `commit_oid`, `backend`
-- **event**: `git.blob.put`(`oid`, `size`), `git.tree.write`, `git.ref.cas`(`expected`, `new`, `result`), `git.cas.conflict`
-
-## 14.2 Metrics(目标态)
-
-| 指标 | 类型 | 维度 |
-| ---------------------------------- | --------- | ---------------------------- |
-| `git_commit_total` | counter | account\_id, branch, result |
-| `git_commit_duration_seconds` | histogram | backend |
-| `git_commit_files` | histogram | — |
-| `git_commit_bytes` | histogram | backend |
-| `git_cas_conflict_total` | counter | account\_id, branch |
-| `git_object_store_latency_seconds` | histogram | op (put/get/exists), backend |
-| `git_ref_store_latency_seconds` | histogram | op (read/cas), backend |
-
-## 14.3 健康检查
-
-- **当前实现**: `RAGFSBindingClient.health()` 在原有字段上追加 `git_enabled: bool` 和 `git_backend: Option<String>`(关闭时为 None)。
-- **目标态(未实现)**: 增加 `git` 子结构,返回 `{"backend", "writable", "last_commit_age_sec"}`;每分钟后台心跳对 `refs/heads/main` 做一次 read,失败则标记 degraded。
-
-***
-
-# 15. 测试策略
-
-## 15.1 测试层次
-
-| 层级 | 范围 |
-| ---------------- | ------------------------------------------------------------------------------------------------------------------------ |
-| **单元测试 (Rust)** | ObjectStore 各操作的幂等性;RefStore CAS 在并发下的正确性(MVP 用普通并发测,未引入 loom);tree\_builder 的 upsert/remove/write;错误映射 |
-| **集成测试 (Rust)** | LocalObjectStore 跑全套场景(MVP 暂未引入 MemObjectStore);commit → show 路径 → bytes 一致;commit → restore → 文件一致;并发 commit 的 CAS 冲突处理 |
-| **端到端 (Python)** | VikingFS.commit → restore 全流程;跨 scope 原子快照;派生文件被正确纳入 commit 并随 restore 回滚;向量索引在 restore 后被精确重建;多账号并发隔离 |
-
-## 15.2 关键测试用例清单
-
-1. **幂等性**: 同一 commit\_req 调用两次,第二次应快速返回(blob exists 跳过 + ref 未变 → no-op 或 same oid)
-2. **跨 scope 原子性**: 一次 commit 同时改 `resources/a.md` 和 `agent/skills/b.py`,restore 父 commit 后两者都应回滚
-3. **派生文件纳入**: 创建 `resources/x.md` 与 `resources/x.md.abstract.md`,commit 后 `show` 两者均可见;restore 父 commit 后两者都应回滚;向量索引文件不被 commit
-4. **CAS 冲突**: 两个并发 commit,后到的必须看到 `ConcurrentCommit` 错误而非默默覆盖
-5. **dry\_run 不写**: restore dry\_run 后再 ls,VFS 状态不变
-6. **账号隔离**: A 账号的 commit\_oid 在 B 账号下 show 必须返回 not found
-7. **后端等价性**: LocalObjectStore 与 S3ObjectStore (LocalStack/MinIO) 跑同一组用例输出一致
-8. **大文件**: 单 blob 80MB 可正确 commit / show / restore
-9. **双重加密**: restore 写回后 VFS read 内容与原始明文一致
-
-***
-
-# 16. 实施计划 (MVP)
-
-| 阶段 | 工作内容 | 交付物 | 预估 |
-| ----- | --------------------------------------------------------------------------------------------------------------------- | ---------------------- | ---- |
-| D1-D2 | 新建 `crates/ragfs/src/git/`,定义 trait + LocalObjectStore/LocalRefStore + S3ObjectStore/S3RefStore (含 If-Match CAS) + 单测 | 裸 Git 存储跑通 put/get/CAS | 2d |
-| D3 | 接入 `gix_object::tree::Editor`,实现 `GitService::commit` | commit 流程单测绿 | 1d |
-| D4 | 实现 `GitService::show` (纯读路径,易验证) | commit + show 闭环 | 1d |
-| D5 | 实现 `GitService::restore`,dry\_run 优先,验证幂等 | commit + restore 闭环 | 1d |
-| D6 | PyO3 binding: `RAGFSBindingClient` 三个新方法 + 错误映射 | Python 端可调 | 1d |
-| D7 | `VikingFS.commit/restore/show/log` + URI ↔ tree path 转换 | Python 端到端 | 1d |
-| D9 | tracing/metrics 接入 + health check | 可观测性完备 | 0.5d |
-| D10 | 文档 + 灰度发布 | 上线 Phase 1 | 0.5d |
-
-> 💡 **总工期**: \~10 人日 (MVP, 单人); 双后端等价测试与 S3 CAS 兼容性验证可能引入额外 2-3 天。
-
-***
-
-# 17. 当前实现进度与未实现项
-
-下面汇总文档中已写出但当前**尚未实现**的部分,供后续阶段补齐:
-
-### Rust 侧
-
-- **commit / restore 内部 CAS 重试循环** —— 文档 §11.3 旧版描述。当前 `commit()` 明确不做 retry,`ConcurrentCommit` 直接上抛。
-- **可配置并发度与 CAS 重试** —— restore 回写并发度当前硬编码 32,commit blob 上传为串行,commit 内部不做 retry;待实现行为时再增加对应配置项。
-- **S3 RedisLock CAS 模式** —— 文档 §7.2。`CasMode::RedisLock` 仅作为枚举占位,实际调用返回 "not yet implemented" 错误。
-- **commit 资源限制实际生效** —— 文档 §12.3。100MB blob 限制、commit 文件数限制与 `[git.quota]` 配置块尚未实现;`show_with_limit` 只提供调用方指定的读取上限,当前 snapshot diff 使用 10MiB,不代表普通 show 存在全局上限。同账号 restore 写竞态防护已通过 `VikingFS.restore` 的 `LockContext` 树锁实现(见 §12.3)。
-- **本地 ref 跨进程锁** —— 文档 §7.1。`LocalRefStore` 仅有进程内 `DashMap<Mutex>`,未叠加 `flock`。
-- **观测性 (tracing / metrics)** —— 文档 §14.1 / §14.2。span / event / 各类 counter / histogram 均未接入。
-- **健康检查增强** —— 文档 §14.3。当前仅 `git_enabled` / `git_backend`,未接入 `writable` / `last_commit_age_sec` / 心跳。
-- **GC / pack file / branch & tag 管理 / diff API** —— 文档 §19。属后续 Phase。
-- **loom 并发模型测试 + proptest fuzz** —— 文档 §5.2。MVP 未引入。
-- **账号级 `.ovgitignore`** —— 已实现。支持账号根 `.ovgitignore` glob 子集规则,规则仅在 `commit` 时生效;`.ovgitignore` 自身进入版本管理,不进入向量索引;`restore` 不应用当前 ignore 过滤。
-
-### Python 侧
-
-- **VikingFS.commit / restore / show / log 已实现**(`openviking/storage/viking_fs.py`),`_uri_to_tree_path` / `_tree_path_to_uri` / `_classify_restore_path` / `_schedule_vector_rebuild` / `_run_vector_rebuild` 均已实现,精确按 marker / source-file 调度 `ReindexExecutor`。
-- **VikingFS.\_trigger\_vector\_rebuild(account, paths)(早期设计)** 已被更精确的 `_schedule_vector_rebuild(written, deleted)` 替代,**不会**再实现旧 API。
-
-***
-
-# 18. 风险与缓解
-
-| 风险 | 影响 | 缓解 |
-| -------------------------------------- | -- | ----------------------------------------------------------------------------------- |
-| S3/TOS CAS 兼容性差异 | 高 | POC 阶段验证目标后端的 If-Match 条件写支持;不支持时该后端不可用于 git ref 存储 |
-| 大账号 commit 时 enumerate 慢 | 中 | `paths` 参数限定 scope;后续引入增量 diff(基于 mtime + parent tree) |
-| 双重加密导致 restore 后内容损坏 | 高 | restore 路径绕过 `viking_fs.write` 加密,直接走 `MountableFS`;集成测试覆盖 |
-| L0/L1 派生文件纳入版本历史,模型异步重建导致 commit 间差异增加 | 中 | 用户主动控制 commit 时机,不自动触发;L0/L1 文件通常较小(< 10KB),存储成本可控;如需降频可配置 commit 时忽略 mtime-only 变更 |
-| 同一账号多 Agent 高并发 commit | 中 | CAS 冲突直接返回调用方,由调用方决定是否重试;长期可引入"基于队列的串行化提交器" |
-| Git 数据无 GC,长期膨胀 | 中 | 首版不做 GC,运维侧定期 dump + 压缩;后续接入 reachability-based GC |
-| loose object 数量爆炸,本地 inode 紧张 | 低 | Phase 4 引入 pack file;Git fanout 已经缓解一半 |
-
-***
-
-# 19. 后续演进方向
-
-1. **Pack file 支持**: 引入 `gix-pack`,对历史 commit 做 delta 压缩,降低存储成本 80%+
-2. **Auto-commit hook**: 在 `content_write.ContentWriteCoordinator` 末尾追加可选 hook,实现"每次写自动 commit"模式(Phase 2 重新评估)
-3. **Branch / Tag 管理**: 暴露 `branch_create / branch_delete / tag` API
-4. **Diff API**: `diff(ref_a, ref_b)` 返回结构化差异,供 UI 渲染
-5. **跨账号镜像**: 支持账号间的 commit 分享(类似 GitHub fork)
-6. **向量索引版本化(可选)**: 若后续需要向量索引的快照回滚能力,可引入轻量 manifest 记录 index 版本与对应 commit\_oid 的映射,避免全量存储向量数据
-7. **外部 Git 工具兼容**: 输出标准 Git 仓库格式,允许通过 `git clone file://...` 检视
-
-***
-
-# 20. 附录
-
-## 20.1 术语表
-
-| 术语 | 含义 |
-| ------------ | ------------------------------------------------------------------------------------------------ |
-| VFS | Virtual File System,本文特指 OpenViking 的 `MountableFS` + plugin 体系 |
-| Loose Object | Git 的基础存储单元,zlib 压缩,按 SHA 寻址的单文件 |
-| CAS | Compare-And-Swap,本文特指 ref 更新时"仅当当前值 = 期望值才写入" |
-| Root Tree | commit 对象指向的最顶层 tree 对象,代表整个仓库快照 |
-| Tree Editor | `gix_object::tree::Editor`,gitoxide 提供的内存中 tree 构建器,支持 upsert/remove/write |
-| 派生文件 | `.abstract.md` / `.overview.md`,由 OpenViking 模型异步生成的 L0/L1 摘要文件,已纳入 Git 版本管理 |
-
-## 20.2 参考资料
-
-- [GitoxideLabs/gitoxide](https://github.com/GitoxideLabs/gitoxide)
-- [volcengine/OpenViking](https://github.com/volcengine/OpenViking)
-- [OpenViking 存储架构文档](../zh/concepts/05-storage.md)
-- [Git Pack Format (后续 Phase 参考)](https://git-scm.com/docs/gitformat-pack)
-
-> 💡 **文档完成**。如需对某一章节细化(如某后端实现细节、某测试用例代码、迁移脚本),请告知具体目标。
diff --git a/docs/design/l0-l1-okf-sidecars-rfc.md b/docs/design/l0-l1-okf-sidecars-rfc.md
deleted file mode 100644
index 0bbf69584..000000000
--- a/docs/design/l0-l1-okf-sidecars-rfc.md
+++ /dev/null
@@ -1,261 +0,0 @@
-# RFC: Upgrade L0/L1 Semantic Sidecars to OKF Markdown
-
-Status: Draft
-
-## Summary
-
-OpenViking today stores built-in context-layer summaries as directory-level Markdown sidecars:
-
-- `.abstract.md` for L0
-- `.overview.md` for L1
-
-This RFC proposes keeping those filenames and the visible Markdown body, while upgrading their internal document format to minimal OKF-style Markdown: YAML frontmatter metadata followed by the summary body.
-
-The change makes L0/L1 sidecars more self-describing without changing the public context-layer model described in `docs/zh/concepts/03-context-layers.md`.
-
-## Background
-
-OpenViking uses a three-layer context model:
-
-| Layer | Current file | Role |
-| --- | --- | --- |
-| L0 | `.abstract.md` | short summary for fast filtering and vector retrieval |
-| L1 | `.overview.md` | directory overview for navigation and rerank |
-| L2 | source files and subdirectories | full content loaded on demand |
-
-The current implementation treats `.abstract.md` and `.overview.md` as generated hidden sidecars. `SemanticProcessor` / `SemanticTreeExecutor` generate them bottom-up, and the vector pipeline maps those two filenames to `ContextLevel.ABSTRACT` and `ContextLevel.OVERVIEW`.
-
-## Goals
-
-- Keep the existing L0/L1 file names and directory-level sidecar convention.
-- Add a small structured metadata block to L0/L1 documents.
-- Exclude metadata from embedding by default.
-- Preserve current preview behavior: `find`, `ls`, tree, and agent previews should show only the visible summary body unless explicitly reading the file.
-- Make metadata available through direct `read` / `get` access to the sidecar files.
-- metadata is protected from directly `write`.
-- Leave room for a future metadata embedding whitelist for index-able fields.
-
-## Non-Goals
-
-- Do not change L0/L1 into per-file sidecars.
-- Do not expose hidden sidecars in normal directory listings.
-- Do not redesign semantic generation prompts, metadata is hidden for re-generation.
-- Do not make all Markdown frontmatter globally invisible to embedding.
-- Do not require OKF parsing for ordinary user-authored Markdown resources.
-
-## Proposed Format
-
-L0 and L1 remain UTF-8 Markdown files with `.md` suffixes. Each generated file starts with YAML frontmatter:
-
-### L0 Example Across Surfaces
-
-Use one directory as the running example:
-
-```text
-viking://resources/images_2/
-```
-
-#### Raw Storage
-
-The stored `.abstract.md` keeps metadata and body together:
-
-```markdown
----
-directory: viking://resources/images_2/
-source:
- kind: http
- uri: http://demo.com/demo.pdf
-generated_by:
- component: SemanticProcessor
- trigger: resource_ingest
-freshness:
- total_entries: 161
- sampled_entries: 32
- unsampled_entries: 129
- pending_child_changes: 0
----
-
-This directory contains a collection of visual assets including screenshots, diagrams, logos, and QR codes related to a context database for AI agents, AI coding assistant tools, and cloud-based AI model management.
-```
-
-#### Preview Reads
-
-`abstract()`, `ls output=agent`, tree agent output, and `find` previews use the body only:
-
-```markdown
-This directory contains a collection of visual assets including screenshots, diagrams, logos, and QR codes related to a context database for AI agents, AI coding assistant tools, and cloud-based AI model management.
-```
-
-Normal `ls` still hides `.abstract.md` unless hidden files are explicitly requested.
-
-#### Full Reads
-
-`read()` / `get()` of the sidecar file return the raw stored document, including frontmatter and body. This is the path for callers that intentionally need metadata.
-
-#### Embedding Text
-
-Embedding uses the body plus whitelisted metadata. The initial whitelist contains `directory`, so the text sent to the embedder is equivalent to:
-
-```text
----
-directory: viking://resources/images_2/
----
-
-This directory contains a collection of visual assets including screenshots, diagrams, logos, and QR codes related to a context database for AI agents, AI coding assistant tools, and cloud-based AI model management.
-```
-
-`source`, `generated_by`, and `freshness` are intentionally absent from this embedding text.
-
-#### Regeneration Input
-
-When a parent summary is regenerated from this L0, the semantic pipeline uses the body only:
-
-```text
-This directory contains a collection of visual assets including screenshots, diagrams, logos, and QR codes related to a context database for AI agents, AI coding assistant tools, and cloud-based AI model management.
-```
-
-Metadata is not prompt input for re-summarization. `freshness` may still be updated out of band to indicate that the stored body is stale relative to child changes.
-
-L1 uses the same storage and access rules. Its body is longer and navigation-oriented, but metadata handling is identical.
-
-The metadata block is intentionally narrower than general OKF wiki pages. L0/L1 are generated context abstractions, so metadata should only carry machine-facing fields that are not already available from file attributes such as `stat`, and not repeat the visible summary itself.
-
-The initial metadata should stay small and deterministic. Timestamps are intentionally omitted at first to avoid rewriting sidecars when semantic content has not changed.
-
-Existing L0/L1 content length limits apply to the Markdown body only. Metadata is outside those limits and should not be truncated by summary-size enforcement.
-
-## Metadata Fields
-
-The initial metadata set should stay small:
-
-| Field | Purpose | Notes |
-| --- | --- | --- |
-| `directory` | Directory represented by this L0/L1 sidecar | Initial embedding whitelist field |
-| `source` | Optional original source, when known | Top-level import root only unless a nested source boundary exists |
-| `generated_by` | Component and coarse trigger that created or updated the sidecar | Operational metadata, not content provenance |
-| `freshness` | Child counts, sampling coverage, and known pending child changes | A freshness signal; not a replacement for semantic refresh |
-
-`freshness` counts direct child entries, not the total recursive subtree size. Files and child directories share the same counters because both contribute one direct input to the parent summary. For large directories, it should distinguish total input size from the subset actually read for summary generation. A directory with many entries may record `total_entries: 161`, `sampled_entries: 32`, and `unsampled_entries: 129`. `freshness.pending_child_changes > 0` means the body is still readable, but known to lag behind lower-level changes.
-
-Sampling should be deterministic for a stable tree so repeated refreshes do not rewrite sidecars unnecessarily. The first policy can be simple: summarize all direct children up to a threshold, and for larger directories use a bounded sample that preserves useful ordering and diversity. Freshness metadata should make that choice visible without forcing the body to enumerate unsampled files.
-
-Metadata should not duplicate information already available through `stat`, such as file name, file size, mode, modified time, or lock state.
-
-## Embedding Behavior
-
-The embedding input for generated L0/L1 sidecars should be the visible Markdown body plus explicitly whitelisted metadata fields.
-
-The initial whitelist includes `directory`, because the directory URI helps retrieval connect a summary to its location in the context tree. Operational and provenance fields remain excluded by default, including `source`, `generated_by`, and `freshness`.
-
-Conceptually:
-
-```text
-raw sidecar bytes
- -> parse OKF frontmatter
- -> body_markdown
- -> append whitelisted metadata fields (`directory` initially)
- -> embedding text
-```
-
-This keeps the semantic vector space focused on user-facing summaries and stable location context, while avoiding accidental ranking changes from source URLs, generator details, or freshness counters.
-
-## Read and Preview Semantics
-
-Direct file reads of sidecar files remain raw: callers receive frontmatter plus body.
-
-Semantic accessors return body-only content. Preview surfaces also use body-only content:
-
-- `find` result summaries
-- `ls output=agent`
-- tree output in agent mode
-- search/rerank preview snippets
-
-Normal `ls` behavior remains unchanged: hidden sidecars are not listed unless the caller explicitly asks for hidden entries.
-
-## Compatibility
-
-Existing sidecars without frontmatter remain valid. Readers should treat them as legacy Markdown and return the full content as body.
-
-Writers should emit OKF-formatted sidecars after the feature lands. There is no need for an eager migration job. Existing directories migrate naturally when semantic refresh rewrites their L0/L1 files.
-
-The current L0 extraction rule should continue to operate on the L1 body, not the raw OKF document. This preserves the current convention that L0 is derived from the brief paragraph before the first `##` section in L1.
-
-## Implementation Sketch
-
-Introduce a small semantic-sidecar document helper near the existing sidecar write/read code:
-
-- `render_abstract_overview(level, dir_uri, body, metadata) -> str`
-- `parse_abstract_overview(raw) -> {metadata, body}`
-- `body_for_preview(raw) -> str`
-- `body_for_embedding(raw, whitelist=()) -> str`
-
-Use it in these paths:
-
-| Area | Required change |
-| --- | --- |
-| Sidecar writeback | Render OKF frontmatter before writing `.abstract.md` / `.overview.md` |
-| Source propagation | Carry optional source metadata to the import root sidecars when available |
-| Generation metadata | Record the component and trigger that created or updated each sidecar |
-| Freshness accounting | Write direct child input counters during semantic generation |
-| Large directory sampling | Record total direct children, sampled children, and unsampled count when generation uses a bounded sample |
-| Deferred changes | Increment pending child-change counters when filesystem changes do not immediately refresh the parent summary |
-| `abstract()` / `overview()` | Strip OKF frontmatter before returning semantic accessor content |
-| Incremental summary reuse | Parse `.overview.md` body before extracting file summaries |
-| L0 derivation | Extract abstract from L1 body |
-| Vectorization | Enqueue the body plus explicitly whitelisted metadata for L0/L1 embeddings |
-| Preview formatting | Keep using semantic accessor/body-only content |
-
-The parser should be tolerant: valid YAML object frontmatter is metadata; missing frontmatter means legacy body; malformed frontmatter should not silently enter embeddings. For generated sidecars, malformed frontmatter should be treated as a processing error.
-
-Size-limit enforcement should parse the sidecar and apply existing L0/L1 limits only to the body before rendering metadata back around it. Metadata size should remain bounded by field policy rather than by the summary body limit.
-
-## Test Plan
-
-Format and compatibility:
-
-- Unit-test rendering and parsing of OKF sidecars.
-- Verify legacy sidecars without frontmatter still read as body-only content.
-- Verify malformed generated sidecar frontmatter fails loudly instead of being embedded as body text.
-- Verify ordinary user-authored Markdown frontmatter is not affected by semantic-sidecar parsing.
-
-Read and preview behavior:
-
-- Verify `abstract()` and `overview()` return body-only content.
-- Verify direct `read_file()` returns raw frontmatter plus body.
-- Verify `ls output=agent`, tree agent output, and `find` previews do not include metadata fields.
-- Verify normal `ls` still hides `.abstract.md` / `.overview.md` unless hidden files are requested.
-
-Metadata generation:
-
-- Verify optional `source` metadata is preserved on the generated import root and not repeated in nested directories unless a nested source boundary exists.
-- Verify `generated_by` records the component and trigger for generated sidecars.
-- Verify L0/L1 size limits truncate only the body and preserve metadata.
-- Verify direct writes cannot mutate protected metadata independently from semantic sidecar generation.
-
-Freshness and sampling:
-
-- Verify freshness counters match direct child entries used for generation.
-- Verify large directories record deterministic sampling coverage, including total, sampled, and unsampled direct entries.
-- Verify repeated refreshes on an unchanged large directory produce the same sample metadata and do not rewrite sidecars unnecessarily.
-- Verify deferred child changes update `pending_child_changes` without changing the visible summary body.
-- Verify a completed parent refresh resets `pending_child_changes` and updates freshness coverage.
-
-Semantic reuse and embedding:
-
-- Verify L0 extraction ignores frontmatter in L1.
-- Verify incremental refresh can reuse summaries from an OKF-formatted `.overview.md`.
-- Verify regeneration prompts use body-only child summaries and do not include metadata.
-- Verify vectorization text for `.abstract.md` and `.overview.md` includes whitelisted `directory` metadata.
-- Verify vectorization text excludes `source`, `generated_by`, and `freshness`.
-
-## Decisions
-
-- Do not add a dedicated `read_metadata()` API in the first version. Direct `read()` / `get()` of the sidecar file is enough for callers that intentionally need metadata.
-- Use the metadata embedding policy described above: `directory` is included initially; `source`, `generated_by`, and `freshness` are excluded.
-- Include OKF metadata in Git diffs as-is. Body-only diff rendering can be a future viewer feature, not part of the storage format.
-
-## Future Work: Freshness-Aware Parent Bubbling
-
-The current implementation schedules a parent refresh after every successful resource/skill semantic task, even when the newly generated child summary is unchanged. It marks the parent `pending_child_changes` before enqueue so freshness remains accurate, but unconditional bubbling is not the intended final scheduling policy.
-
-Future work should use freshness state to control bubbling frequency. Candidate inputs include `pending_child_changes`, sampling coverage, direct-child change volume, whether the child L0 body actually changed, and recent parent-refresh state. The scheduler may coalesce changes, apply thresholds, or use a time window to reduce repeated refreshes and upward write amplification in hot directory trees while preserving eventual consistency.
diff --git a/docs/design/local-embedding-llama-cpp-design.md b/docs/design/local-embedding-llama-cpp-design.md
deleted file mode 100644
index 5e35ed55d..000000000
--- a/docs/design/local-embedding-llama-cpp-design.md
+++ /dev/null
@@ -1,432 +0,0 @@
-# OpenViking 本地 Embedding Llama-cpp 设计文档
-
-Date: 2026-04-11
-Status: 已批准进入实现
-
-## 目标
-
-为 OpenViking 增加内置的本地 dense embedding 能力,并满足以下产品行为:
-
-- 当用户没有显式配置 `embedding` 时,OpenViking 默认使用本地 embedding backend
-- 默认本地模型为 `bge-small-zh-v1.5-f16`
-- 本地推理基于 `llama-cpp-python` 加载 GGUF 模型
-- 本地推理依赖不放入主依赖,而是通过 optional extra 单独分发,降低安装风险
-
-最终效果是:在不改变“默认走本地 embedding”这一产品目标的前提下,让方案具备可实现性和可维护性。
-
-## 范围
-
-本次设计包含:
-
-- 新增 `embedding.backend = "local"` backend
-- 当用户未提供 embedding 配置时,自动生成隐式本地 embedding 配置
-- 基于 `llama-cpp-python` 的 dense embedder
-- 默认模型 `bge-small-zh-v1.5-f16`
-- 模型路径解析、下载和缓存目录管理
-- query/document 双路编码语义
-- collection 元数据校验和 rebuild 规则
-- 启动期校验与错误提示
-- 测试方案和 benchmark 预留
-
-本次设计不包含:
-
-- 本地 sparse embedding
-- 本地 hybrid embedding
-- 本地失败后静默回退到远程 provider
-- 运行时自动安装依赖
-- 替换现有远程 provider
-
-## 决策摘要
-
-OpenViking 采用以下组合策略:
-
-1. 产品默认行为:如果用户没有配置 embedding,OpenViking 会隐式选择本地 embedding backend。
-2. 依赖分发策略:`llama-cpp-python` 不进入主依赖,而是通过 `openviking[local-embed]` 之类的 optional extra 分发。
-3. 默认本地模型:`bge-small-zh-v1.5-f16`。
-4. 失败策略:如果系统默认选择了本地 embedding,但本地依赖或模型不可用,则直接报错,并给出清晰恢复指引;不会静默回退到远程模型。
-
-这和 QMD 的做法不完全相同。QMD 是 Node CLI 产品,可以把 `node-llama-cpp` 作为主依赖;而 OpenViking 是 Python SDK 和服务组件,如果让原生依赖阻断主包安装,代价会更高。
-
-## 为什么这样设计
-
-调研结论和当前代码约束基本指向同一个方向:
-
-- QMD 证明了“默认本地 embedding”这个产品方向是成立的。
-- OpenClaw / ArkClaw 证明了基于 GGUF 的本地 memory search 有明确用户价值。
-- OpenViking 当前架构决定了 embedding 初始化失败会在启动期暴露,而不是延后到查询时。
-- 在 Python 生态里,原生依赖失败的成本通常比 QMD 所在的 npm/Node 生态更高。
-
-因此,这个设计是在保留产品目标的前提下,尽量缩小原生依赖失败的影响范围。
-
-## 用户可见行为
-
-### 默认行为
-
-如果配置中没有 `embedding`:
-
-- OpenViking 自动生成一份隐式 local dense embedding 配置
-- backend 设置为 `local`
-- model 设置为 `bge-small-zh-v1.5-f16`
-- dimension 设置为该模型对应维度
-
-用户应感知到的行为是:“本地 embedding 是默认值”。
-
-### 显式行为
-
-如果用户显式配置了 `embedding`,则始终以显式配置为准,包括:
-
-- 显式 `backend: "local"`
-- 显式远程 backend,例如 `openai`、`volcengine`、`vikingdb`
-- 显式 `model_path`
-- 显式 `cache_dir`
-
-不应存在覆盖用户配置的隐式重写。
-
-### 安装体验
-
-基础安装:
-
-```bash
-pip install openviking
-```
-
-启用本地 embedding:
-
-```bash
-pip install "openviking[local-embed]"
-```
-
-如果用户依赖默认本地行为,但没有安装 local extra,系统必须在启动时给出可执行的错误提示,至少包含:
-
-- 当前默认启用了本地 embedding
-- 缺少 `llama-cpp-python`
-- 启用本地 embedding 的安装命令
-- 如果用户想改成远程 provider,应如何显式配置
-
-## 配置设计
-
-在 `EmbeddingModelConfig` 中新增 `local` 作为合法 backend。
-
-本地 dense backend 支持的字段:
-
-- `backend`: `"local"`
-- `model`: 逻辑模型名,默认 `bge-small-zh-v1.5-f16`
-- `model_path`: 可选,显式指定 GGUF 文件路径
-- `cache_dir`: 可选,缓存根目录,默认 `~/.cache/openviking/models/`
-- `dimension`: 可选,但通常应由内置模型注册表推导
-- `batch_size`: 预留给后续批量 embedding
-
-建议配置示例:
-
-```json
-{
- "embedding": {
- "dense": {
- "backend": "local",
- "model": "bge-small-zh-v1.5-f16",
- "cache_dir": "~/.cache/openviking/models"
- }
- }
-}
-```
-
-显式模型路径示例:
-
-```json
-{
- "embedding": {
- "dense": {
- "backend": "local",
- "model": "bge-small-zh-v1.5-f16",
- "model_path": "/data/models/bge-small-zh-v1.5-f16.gguf"
- }
- }
-}
-```
-
-## 架构设计
-
-### 新增组件
-
-新增一个本地 dense embedder 实现,例如:
-
-- `openviking/models/embedder/local_embedders.py`
-- `LocalDenseEmbedder`
-
-其职责包括:
-
-- 校验 `llama-cpp-python` 是否可用
-- 将逻辑模型名解析为 GGUF 模型规格
-- 解析或下载模型文件
-- 初始化 llama embedding context
-- 提供 query/document 双路 embedding 方法
-- 返回模型维度
-- 在 `close()` 时释放本地资源
-
-### Factory 与配置改造
-
-需要修改:
-
-- `EmbeddingModelConfig.validate_config()` 以接受 `backend == "local"`
-- `EmbeddingConfig._create_embedder()` 以支持 `("local", "dense")`
-- 默认配置生成逻辑,使“缺失 embedding 配置”自动变成 local dense
-
-### 模型注册表
-
-新增一个内置本地模型注册表。第一版可以先做成简单映射,按逻辑模型名索引:
-
-- 逻辑模型名
-- GGUF 下载 URL 或 HuggingFace 定位信息
-- 预期维度
-- 推荐 prompt 规则
-- 可选的目标文件名
-
-首个内置模型为:
-
-- `bge-small-zh-v1.5-f16`
-
-## Query / Document 双路编码
-
-这部分不是可选优化,而是本方案必须处理的设计点。
-
-BGE/E5 一类模型是检索导向模型,通常需要区分:
-
-- query:用户输入的搜索词或问题
-- document:被存储和检索的文本块
-
-OpenViking 当前只有 `embed(text)`,这不足以表达这种语义差异。
-
-设计上新增显式接口:
-
-- `embed_query(text: str) -> EmbedResult`
-- `embed_document(text: str) -> EmbedResult`
-
-为了兼容现有代码,`embed(text)` 可以保留为一个薄封装,但内部必须带角色语义。新的检索代码应调用 `embed_query()`,新的入库代码应调用 `embed_document()`。
-
-query/document 的格式规则必须封装在本地 embedder 内部,而不是散落在业务层拼装。
-
-## 模型解析与下载流程
-
-### 解析顺序
-
-1. 如果配置了 `model_path`,直接使用该路径。
-2. 否则通过内置本地模型注册表解析 `model`。
-3. 如果目标文件不存在,则下载到 `cache_dir`。
-4. 用解析后的 GGUF 文件初始化 `llama-cpp-python`。
-
-### 缓存目录
-
-默认目录:
-
-- `~/.cache/openviking/models/`
-
-行为要求:
-
-- 目录不存在时自动创建
-- 下载后的 GGUF 文件保存在这里
-- 如果目标文件已存在,则不重复下载
-
-### 下载策略
-
-第一版需要支持:
-
-- 可读性好的错误输出
-- 稳定可预测的文件命名
-- 失败后可手动重试
-
-第一版暂不要求:
-
-- 断点续传
-- 多镜像源自动切换
-- 后台异步下载器
-
-## 启动时机与失败行为
-
-OpenViking 当前在 client 启动时就初始化 embedder,本地方案保持这一行为。
-
-因此,下面这些问题都会在启动期直接暴露:
-
-- 没有安装 local extra
-- `llama-cpp-python` import 失败
-- 模型文件缺失且下载失败
-- GGUF 文件存在但加载失败
-- 当前 collection 元数据与配置模型不一致
-
-### 错误处理规则
-
-缺少本地依赖:
-
-- 直接抛出明确的配置/运行时错误
-- 错误信息中必须包含:缺失包名、安装命令、切换远程 provider 的方法
-
-模型下载失败:
-
-- 抛出包含逻辑模型名、解析 URL、缓存目录和原始异常的错误
-
-模型加载失败:
-
-- 抛出 GGUF 不兼容、文件损坏或当前运行环境不支持的错误
-
-元数据不一致:
-
-- 抛出“当前 embedding 设置与已有索引不兼容,需要 rebuild”的错误
-
-不允许静默回退:
-
-- 本地初始化失败时,不得悄悄切换到 `openai`、`volcengine` 或 `vikingdb`
-
-## Collection 元数据与重建规则
-
-当前系统只在写入时校验向量维度,这在本地模型成为默认值之后是不够的。
-
-需要至少持久化以下元数据:
-
-- `embedding_backend`
-- `embedding_model`
-- `embedding_dimension`
-- `embedding_model_identity`
-
-其中 `embedding_model_identity` 用于区分“看起来模型名相同,但实际模型文件不同”的情况,可以采用:
-
-- 解析后的模型路径
-- 模型路径哈希
-- 文件哈希(如果成本可接受)
-
-### 重建触发条件
-
-只要以下任一项发生变化:
-
-- backend
-- model
-- dimension
-- model identity
-
-都应判定现有向量不可兼容。系统需要:
-
-- 在启动时直接报错并提示 rebuild,或
-- 在用户显式触发时执行 rebuild 流程
-
-第一版建议采用显式 rebuild,而不是隐式迁移。
-
-## 数据流改造
-
-### 入库流程
-
-当前流程:
-
-- 语义处理得到文本
-- 队列消费者调用 `embed()`
-
-改造后流程:
-
-- 队列消费者调用 `embed_document()`
-- 本地 embedder 自动套用 document 侧规则
-- 向量写入时附带与当前模型一致的 collection 元数据
-
-### 检索流程
-
-当前流程:
-
-- retriever 调用 `embed()`
-
-改造后流程:
-
-- retriever 调用 `embed_query()`
-- 本地 embedder 自动套用 query 侧规则
-- 检索时使用与 document 同体系生成的向量
-
-## 开发顺序
-
-1. 增加 `local` backend 的配置校验和 factory 注册。
-2. 增加“缺失 embedding 配置时默认生成 local dense 配置”的逻辑。
-3. 实现基于 `llama-cpp-python` 的 `LocalDenseEmbedder`。
-4. 增加内置本地模型注册表,并接入 `bge-small-zh-v1.5-f16`。
-5. 增加模型路径解析、缓存目录和自动下载逻辑。
-6. 增加 `embed_query()` / `embed_document()` 双路接口。
-7. 持久化 collection embedding 元数据,并补一致性检查。
-8. 增加 rebuild-required 错误流。
-9. 更新用户文档、示例配置和安装说明。
-
-## 测试计划
-
-### 配置测试
-
-- 缺失 `embedding` 时自动生成隐式 local dense 配置
-- 显式远程配置时不触发默认本地逻辑
-- `model_path` 能覆盖逻辑模型解析
-- `cache_dir` 覆盖生效
-
-### 依赖与初始化测试
-
-- 缺少 `llama-cpp-python` 时,启动错误信息正确
-- 显式 local backend 且依赖已安装时可成功初始化
-- 非法 GGUF 路径会触发模型加载失败
-- 下载失败时错误信息完整可读
-
-### Embedding 行为测试
-
-- `embed_query()` 与 `embed_document()` 走不同路径
-- 返回维度与模型维度一致
-
-### 元数据与重建测试
-
-- 首次启动时能生成和当前模型一致的元数据
-- 改变 model identity 时会触发需要重建
-- 改变 dimension 时会触发需要重建
-
-### 检索回归测试
-
-- 中文 query 能正确召回中文文档
-- query/document 双路编码不会破坏现有检索链路
-- 现有远程 provider 行为保持不变
-
-### 打包测试
-
-- `pip install openviking` 可以在不安装本地依赖的情况下成功
-- `pip install "openviking[local-embed]"` 可以启用本地 import 路径
-- 缺少 extra 且触发默认本地行为时,报错应明确,而不是模糊 import failure
-
-## 基准测试
-
-至少记录以下指标:
-
-- 依赖已安装且模型已缓存时的启动耗时
-- 首次下载模型时的启动耗时
-- 单条 embedding 延迟
-- 批量 embedding 延迟
-- 在代表性中文语料上的索引构建吞吐
-
-在 benchmark 出来之前,不应假设“默认本地 embedding”在所有环境里都同样合适。
-
-## 运维说明
-
-推荐安装命令:
-
-```bash
-pip install "openviking[local-embed]"
-```
-
-如果用户想使用远程 embedding:
-
-- 显式配置 `embedding.dense.backend`
-- 提供相应 provider 的凭证
-
-## 风险
-
-- 原生依赖安装失败
-- 预编译 wheel 覆盖不足
-- GGUF 与运行时版本不兼容
-- 用户预期“零配置”但实际缺少 local extra
-- 模型切换后索引不兼容
-- 未做批量聚合时索引吞吐偏低
-
-## 交付物
-
-- 本地 dense embedder 实现
-- local backend 配置与 factory 集成
-- 内置模型注册表
-- 启动期错误提示与安装指引
-- collection 元数据校验
-- rebuild-required 机制
-- 测试和 benchmark 脚手架
-- 用户文档更新
diff --git a/docs/design/mcp-oauth2-1.md b/docs/design/mcp-oauth2-1.md
deleted file mode 100644
index 4371dba5e..000000000
--- a/docs/design/mcp-oauth2-1.md
+++ /dev/null
@@ -1,401 +0,0 @@
-# OpenViking 原生 OAuth 2.1(MCP 客户端授权)实施方案
-
-> **更新(Studio 迁移)**:本文档保留 Phase 1 的设计与术语作为历史记录。当前
-> 默认授权 UI 已经从独立的 `/console` (端口 8020) 迁移到主服务上的 OpenViking
-> Studio(同源、挂载在 `/studio`)。要点:
->
-> - `provider.authorize()` 默认 redirect 到 `/studio/oauth/consent?pending=<id>`
-> 而不是 `/oauth/authorize/page`。consent SPA 跑在 Studio 自己的 tab 里,
-> 直接复用 `sessionStorage` 里已有的 API Key 调
-> `POST /api/v1/auth/oauth-verify`(请求体改用 `pending_id` 取代
-> `display_code`,并通过新增的公开端点
-> `GET /api/v1/auth/oauth/pending/{pending_id}` 拿 client_name /
-> redirect_host / scopes 渲染 consent 卡片)。
-> - 服务端 HTML 页面 `/oauth/authorize/page` 退化为**跨设备 fallback**:
-> 显示 6 字符 `display_code` + 引导文案,让用户在另一台已登录 Studio 的设备
-> 打开 `/studio/oauth/verify` 输入码完成授权。同设备的 quick-authorize
-> 面板(依赖 `sessionStorage.ov_console_api_key` 跨 tab 探测)已移除,
-> 不再需要把 API Key 写到 `localStorage`。
-> - OTP push 流程(`POST /api/v1/auth/otp` 签发、Studio 里"OAuth client OTP"
-> 区块生成短期码交给客户端)从未接通消费端,已整体移除(后端端点 + 前端入口 +
-> `otp_ttl_seconds` 配置)。Studio 侧边栏底部的那个槽位改造成"OAuth 验证"入口,
-> 直接打开跨设备 `display_code` 验证表单。
-> - 旧的 `/console` 独立服务(8020 + `openviking.console` Python 包 +
-> `python -m openviking.console.bootstrap`)已在 #2160 整体下线,本次迁移
-> 是该 PR commit message 里明确指向的 OAuth follow-up。Caddy 仍保留
-> `:1934 → openviking:1933` 的 legacy 单上游反代以兼容旧书签,公网 HTTPS
-> 按 12-public-access 指南在 Caddyfile 里 append `:443` domain block。
->
-> 下文的 "Phase 1" 描述仍然刻画了 device-flow 的核心思路(含已移除的 OTP push
-> 端点,仅作历史记录);新迁移在此之上把 UI 层从 `/console` 替换为 `/studio`,
-> 并把 Studio consent 作为同设备主路径。
-
-## Context
-
-**问题**:Claude.ai / Claude Desktop / ChatGPT 等只接受 OAuth 2.1 的 MCP 客户端,必须经由社区项目 [MCP-Key2OAuth](https://github.com/t0saki/MCP-Key2OAuth) 的 Cloudflare Workers 代理才能连接 OpenViking 的 `/mcp`。痛点:
-
-1. **额外部署单元** — 自建 CF Worker + 2 个 KV namespace,运维成本高
-2. **生态绑定** — `@cloudflare/workers-oauth-provider` + KV 强绑定 CF Workers,无法脱离 CF 生态
-3. **体验差与信任风险** — 用户在浏览器手动粘贴 API Key,且 Worker 部署方有解密 Key 的能力
-
-**目标**:在 OpenViking 服务端原生实现 OAuth 2.1(MCP 子集),消除中间代理;保留 API Key 认证向后兼容;提供顺手的浏览器授权 UX。
-
-**最终决策(与设计早期不同)**:
-
-- **协议层用 `mcp.server.auth` SDK**(已在依赖中)。SDK 提供完整的 RFC 6749 / 7591 / 8414 实现:DCR、authorize 解析、token endpoint、metadata、PKCE S256 校验、redirect_uri 校验、错误码格式化。
-- **Token 用 opaque + SQLite,不用 JWT**。Access / refresh / auth_code / OTP 全部是 `secrets.token_urlsafe()` 随机串,按 SHA-256 哈希存表,每次校验做一次 SQLite 查询。**OpenViking 侧零密码学代码**。
-- **不做 redirect_uri 白名单**,但 SDK 会强制 strict-equal 校验防 code injection。
-- **Phase 1 用 device-flow 风格的 OTP 流程**:authorize page **显示** 6 字符码,用户在 console(已登录环境)**输入** 该码确认授权。比早期的"console 取码、page 输入"流程少一次 tab 切换,且符合 RFC 8628 的心理模型。
-
----
-
-## 架构
-
-```
-┌─────────────────────────────────────────────────────────────────┐
-│ OpenViking 1933 │
-│ │
-│ ┌────────────────────┐ ┌──────────────────────────┐ │
-│ │ mcp.server.auth │ │ openviking.server.oauth │ │
-│ │ (SDK, 协议层) │ │ (适配 + 自定义路由) │ │
-│ ├────────────────────┤ ├──────────────────────────┤ │
-│ │ /.well-known/ │ │ /.well-known/ │ │
-│ │ oauth-auth-server│ │ oauth-protected- │ │
-│ │ /register (DCR) │ │ resource (PRM 9728) │ │
-│ │ /authorize │ │ /oauth/authorize/page │ │
-│ │ /token │ │ /oauth/authorize/page/ │ │
-│ │ /revoke │ │ status (轮询) │ │
-│ └─────────┬──────────┘ │ /api/v1/auth/oauth- │ │
-│ │ │ verify (确认入口) │ │
-│ │ │ /api/v1/auth/otp │ │
-│ │ │ (legacy push) │ │
-│ │ └──────────┬───────────────┘ │
-│ │ │ │
-│ ↓ load_access_token() ↓ DELETE/INSERT │
-│ ┌────────────────────┐ ┌──────────────────────────┐ │
-│ │ auth.py │ │ workspace/oauth.db │ │
-│ │ resolve_identity │ │ oauth_clients │ │
-│ │ 识别 ovat_ → │ │ oauth_codes (otp+code) │ │
-│ │ provider 查找 │ │ oauth_refresh_tokens │ │
-│ │ → ResolvedIdentity │ │ oauth_access_tokens │ │
-│ └────────────────────┘ │ oauth_pending_authorizations │
-│ │ (display_code, verified, ...) │
-│ └──────────────────────────┘ │
-└─────────────────────────────────────────────────────────────────┘
- ↑ verify (Bearer)
-┌─────────────────────────────────────────────────────────────────┐
-│ OpenViking Console 8020 │
-│ Settings → "Authorize an MCP client" 表单 │
-│ - 输入 6 字符 display_code → 调 /console/api/v1/ov/auth/ │
-│ oauth-verify (proxy → 1933 /api/v1/auth/oauth-verify) │
-│ 浏览器 sessionStorage 存 API Key (key=ov_console_api_key) │
-└─────────────────────────────────────────────────────────────────┘
-```
-
----
-
-## 设计要点
-
-### 1. 认证模式
-
-不引入新的 `AuthMode.OAUTH`。OAuth 叠加在现有 `AuthMode.API_KEY` 之上:当 `oauth.enabled = true` 时,`Authorization: Bearer <token>` 优先按 OAuth 处理:
-
-- 若 token 以 `ovat_` 前缀开头 → 走 `provider.load_access_token()` 路径,**fail-closed**(前缀正确但查不到不会回退到 API Key 路径)
-- 否则 → 走现有 APIKeyManager 路径,行为与改动前完全一致
-
-`ResolvedIdentity` 新增 `from_oauth: bool` 标记位;`get_request_context` 对 OAuth 身份跳过 ROOT-tenant-headers 强校验(claims 已钉死 account/user)。
-
-### 2. Token 权限范围与撤销
-
-OAuth token = API Key 等效,能调任何当前用户身份能调的 REST 端点(不仅 `/mcp`)。
-
-- **不是权限放大**:opaque token 都钉死 `(account_id, user_id, role)`
-- **撤销粒度**:以 `(account, user)` 为单位 — 删除某 user 的 API Key 时一刀切撤销该 user 名下所有 OAuth token,见 `OAuthStore.revoke_tokens()`
-- Phase 2 计划引入 OAuth scope 做更细收紧
-
-### 3. Token 形态(全部 opaque)
-
-| 类型 | 形态 | 前缀 | TTL | 存储 |
-|---|---|---|---|---|
-| access_token | `secrets.token_urlsafe(40)` | `ovat_` | 1h | SQLite (SHA-256 哈希) |
-| refresh_token | `secrets.token_urlsafe(40)` | `ovrt_` | 30d | SQLite (SHA-256 哈希) |
-| authorization_code | `secrets.token_urlsafe(40)` | `ovac_` | 5min | SQLite (SHA-256 哈希) |
-| display_code (人类可读) | 6 字符(去歧义字母+数字) | — | 10min | pending_authorizations |
-| OTP(legacy push) | 同上 | — | 5min | oauth_codes |
-
-前缀是 fast-path discriminator(不参与鉴权决策)— 让 `auth.py` 在每次请求只对 `ovat_` 开头的 bearer 做 DB 查询,普通 API Key 不受影响。
-
-### 4. 公网 URL 解析(issuer / PRM resource / WWW-Authenticate / page 链接)
-
-统一 4 级回退:
-
-1. `OPENVIKING_PUBLIC_BASE_URL` 环境变量(最高优先级,部署 override)
-2. `oauth.issuer` 配置项
-3. `X-Forwarded-Proto` + `X-Forwarded-Host`(反代场景)
-4. 请求 scheme + `Host` 头(直连)
-
-非 localhost 部署强烈建议显式设置 (1) 或 (2),因为 SDK 强制 issuer 必须是 HTTPS(除 loopback)。
-
-### 5. PKCE / redirect_uri / 错误格式
-
-由 SDK 强制 S256,`plain` 拒绝;`code_verifier` 长度 43–128。SDK 在 `TokenHandler` 中验证。`/authorize` 时 `OAuthClientMetadata.validate_redirect_uri` 做 strict-equal;`/token` 时再次比对(防 code injection)。RFC 6749 错误码由 SDK 返回。
-
-### 6. WWW-Authenticate 401 头
-
-`/mcp` 鉴权失败时 `_IdentityASGIMiddleware` 注入:
-```
-WWW-Authenticate: Bearer resource_metadata="https://<host>/.well-known/oauth-protected-resource"
-```
-URL 走 §4 的 4 级回退。RFC 9728 客户端发现入口。
-
----
-
-## 端到端流程(device-flow / pull 模式)
-
-```
-1. 用户输入 https://my.ov/mcp 到 Claude.ai
-2. Claude POST /mcp → 401 + WWW-Authenticate: Bearer resource_metadata="..."
-3. Claude GET /.well-known/oauth-protected-resource → 拿 issuer
-4. Claude GET /.well-known/oauth-authorization-server → 拿 endpoint [SDK]
-5. Claude POST /register {redirect_uris} → 拿 client_id [SDK]
-6. Claude 浏览器跳到 /authorize → SDK 校验 → 调 provider.authorize() →
- server 生成 display_code (e.g. "AB3X7K") + pending → 302 →
- /oauth/authorize/page?pending=... [SDK→OV]
-7. Page 显示大字 "AB3X7K" + 链接 https://my.ov/console,
- 并启动 JS 轮询 /oauth/authorize/page/status?pending=...
-8. 用户切到 console (sessionStorage 已经在登录) → Settings →
- "Authorize an MCP client" 输入 AB3X7K → 点 Authorize
-9. Console JS POST /console/api/v1/ov/auth/oauth-verify {code, decision}
- ↓ proxy
- 1933 POST /api/v1/auth/oauth-verify
- → server 找 pending by display_code → mark verified, 写入 caller 身份
-10. Page 下次轮询命中 status=approved → response.redirect_url 含 auth_code
-11. Page JS window.location.replace(redirect_url) → Claude 收到 ?code=...&state=...
-12. Claude POST /token (PKCE) → ovat_ + ovrt_ [SDK]
-13. Claude POST /mcp (Authorization: Bearer ovat_...) → 通过 [SDK→auth.py]
-```
-
-**同源加速(可选)**:第 7 步 page JS 检测到 `sessionStorage.ov_console_api_key` 存在(即与 console 同域 + 已登录)时,显示绿色 "Quick authorize" 面板。点击该按钮等价于在 console 输入码 → 直接跳到第 10 步。**仍要点击确认**,不会自动一步跳转。要让同源生效,nginx 反代把 8020 与 1933 放到同一域名(`/console/...` → 8020,`/...` → 1933)。
-
----
-
-## 模块清单
-
-### 新增 / 改写
-
-| 文件 | 用途 | 行数 |
-|---|---|---|
-| `openviking/server/oauth/storage.py` | SQLite 5 张表 + CRUD + GC + verify/find_pending_by_display_code | ~620 |
-| `openviking/server/oauth/provider.py` | `OAuthAuthorizationServerProvider` Protocol 适配;子类化 SDK 的 `AuthorizationCode/RefreshToken/AccessToken` 嵌入 `(account, user, role)`;`authorize()` 自动生成 display_code | ~280 |
-| `openviking/server/oauth/router.py` | PRM、authorize page (HTML+JS)、page/status 轮询、`/api/v1/auth/oauth-verify` | ~440 |
-| `openviking/server/oauth/otp.py` | `generate_otp`(cross-device display_code)/ `hash_secret`(stdlib) | ~30 |
-| `openviking_cli/utils/config/oauth_config.py` | `OAuthConfig` pydantic | ~70 |
-
-### 修改
-
-| 文件 | 改动 |
-|---|---|
-| `openviking/server/auth.py` | `_try_resolve_oauth_token`:识别 `ovat_` → `provider.load_access_token` → `ResolvedIdentity(from_oauth=True)` |
-| `openviking/server/identity.py` | `ResolvedIdentity.from_oauth: bool` |
-| `openviking/server/mcp_endpoint.py` | 401 注入 `WWW-Authenticate` 头;`_scope_to_origin` 4 级回退含 env |
-| `openviking/server/app.py` | lifespan 初始化 `OAuthStore` + GC 任务;`create_app` 用 `mcp.server.auth.routes.create_auth_routes()` 挂 SDK routes + 自定义 router;issuer 优先读 `OPENVIKING_PUBLIC_BASE_URL` env |
-| `openviking_cli/utils/config/open_viking_config.py` | 接入 `OAuthConfig` |
-| `openviking/console/app.py` | 加 `POST /console/api/v1/ov/auth/otp` 和 `POST /console/api/v1/ov/auth/oauth-verify` 转发路由 |
-| `openviking/console/static/index.html` | Settings 面板加 "Authorize an MCP client" 表单(device flow 入口)和折叠的 legacy "Get OTP" 入口 |
-| `openviking/console/static/app.js` | 表单事件 handler;调 verify 端点;keydown=Enter 触发授权 |
-
-### 删除(vs 早期 JWT 方案)
-
-- `openviking/server/oauth/jwt.py`(手搓 HS256)
-- `tests/server/oauth/test_jwt.py`
-
----
-
-## 端点全表
-
-| 端点 | 方法 | 由谁实现 | 鉴权 | 说明 |
-|---|---|---|---|---|
-| `/.well-known/oauth-authorization-server` | GET | SDK | 无 | RFC 8414 |
-| `/.well-known/oauth-protected-resource` | GET | OpenViking | 无 | RFC 9728,列出 issuer 和 bearer_methods |
-| `/register` | POST | SDK | 无 | DCR (RFC 7591),SDK 生成 client_id/secret,调 `provider.register_client()` |
-| `/authorize` | GET/POST | SDK → provider.authorize() | 无 | SDK 校验 client + redirect_uri + PKCE,调 `provider.authorize()` 生成 display_code + pending_id;返回 302 → `/oauth/authorize/page?pending=...` |
-| `/oauth/authorize/page` | GET | OpenViking | 无 | 显示 display_code + console 链接 + 同源 quick-authorize 面板(如检测到 sessionStorage 中的 API key);JS 轮询 status |
-| `/oauth/authorize/page/status` | GET | OpenViking | 无 | 返回 `{status: pending\|approved\|expired, redirect_url?}`;status=approved 时原子签发 auth_code 并删除 pending |
-| `/token` | POST | SDK | client auth | SDK 验 PKCE / redirect_uri / client,调 `provider.exchange_authorization_code()` 或 `exchange_refresh_token()` |
-| `/revoke` | POST | SDK | client auth | SDK 调 `provider.revoke_token()` |
-| `POST /api/v1/auth/oauth-verify` | POST | OpenViking | 现有 API Key(`Depends(get_request_context)`) | 接受 `{pending_id 或 code, decision: approve\|deny}`;approve 时把 caller 身份写入 pending;deny 时删除 pending |
-
----
-
-## 部署运维
-
-### 启动
-
-| 服务 | 命令 | 默认端口 |
-|---|---|---|
-| 主服务(API + MCP + OAuth) | `openviking-server [--host --port --config --workers]` | 1933 |
-| Web Console | `python -m openviking.console.bootstrap [--host --port --openviking-url --write-enabled]` | 8020 |
-
-> Console 当前没有 `openviking-console` entry point,只能 `python -m`。后续可加。
-
-### 关键配置
-
-| 项 | 何处 | 说明 |
-|---|---|---|
-| 存储路径 | `ov.conf:storage.workspace`(默认 `./data`) | `oauth.db` 落在 `<workspace>/oauth.db` |
-| OAuth 启用 | `ov.conf:oauth.enabled = true` | 默认 false,关闭时所有 OAuth 路径不挂载 |
-| Issuer URL | `OPENVIKING_PUBLIC_BASE_URL` env > `ov.conf:oauth.issuer` | 非 localhost 必须 HTTPS |
-| TTL | `ov.conf:oauth.{access,refresh,auth_code,otp}_ttl_seconds` | 默认 1h / 30d / 5min / 5min |
-| Console 上游 | `--openviking-url`(默认 `http://127.0.0.1:1933`) | 反代后改成 `http://127.0.0.1:1933` 即可 |
-
-### nginx 反代模板(推荐部署形态,**未在仓库**)
-
-```nginx
-server {
- listen 443 ssl;
- server_name my.ov;
-
- # 8020 console
- location /console {
- proxy_pass http://127.0.0.1:8020;
- proxy_set_header Host $host;
- proxy_set_header X-Forwarded-Proto $scheme;
- proxy_set_header X-Forwarded-Host $host;
- }
-
- # 其他都走 1933 (REST + MCP + OAuth + .well-known)
- location / {
- proxy_pass http://127.0.0.1:1933;
- proxy_set_header Host $host;
- proxy_set_header X-Forwarded-Proto $scheme;
- proxy_set_header X-Forwarded-Host $host;
- }
-}
-```
-
-这种部署下 console 和 OAuth page 同源,page 的"quick-authorize"面板自动可用。后续可在 `deploy/` 下落一份正式模板。
-
----
-
-## 实施进度
-
-### ✅ M1 — 基础设施
-- `OAuthConfig` 接入 `OpenVikingConfig`(默认 disabled)
-- `OAuthStore` 5 张表 + CRUD + 原子一次性消费 + revoke_tokens
-- `oauth/otp.py` OTP 生成
-- `app.py` lifespan 注入 store + provider + GC
-
-### ✅ M2 — Bearer 路径与 401 头
-- `auth.py` `_try_resolve_oauth_token` 识别 `ovat_` 前缀走 OAuth 路径
-- `ResolvedIdentity.from_oauth` 标记位 + `get_request_context` 跳过 ROOT-tenant 强校验
-- `mcp_endpoint.py` 401 注入 `WWW-Authenticate` 头(含 4 级 origin 回退)
-
-### ✅ M3 — SDK 接入与完整流程
-- `OpenVikingOAuthProvider`(8 个 Protocol 方法)
-- 自定义 authorize HTML 页 + display_code 显示 + JS 轮询
-- `POST /api/v1/auth/oauth-verify`(device flow 确认入口)
-- `POST /api/v1/auth/otp`(legacy push flow,**已移除**——从未接通消费端)
-- `GET /.well-known/oauth-protected-resource`(RFC 9728)
-- `app.py` 用 `create_auth_routes()` 挂 SDK 路由
-
-### ✅ M4 — Console 集成
-- console proxy 加 `oauth-verify` / `otp` 转发
-- Settings 加 "Authorize an MCP client" 表单(device flow)
-- legacy "Get OTP" 折叠在 details 内
-- 同源 quick-authorize 面板(page JS 检测 sessionStorage)
-
-### ✅ M5 — `OPENVIKING_PUBLIC_BASE_URL` 环境变量
-- 4 级 origin 回退在 `_public_origin` (router) 和 `_scope_to_origin` (mcp_endpoint) 共用
-- SDK issuer 启动时读
-
-### ⏳ Phase 1 剩余
-1. **Claude.ai / Claude Desktop / Cursor 端到端实测**(需要起 server,等 benchmark 跑完)
-2. **`deploy/nginx.conf.example`** + 部署文档(同源 quick-authorize 的运维侧条件)
-3. **`openviking-console` entry point script**(让 8020 启动统一为 `openviking-console`)
-
-### 🔜 Phase 2 / 3(不在本 PR 范围)
-- OAuth scope 机制(`mcp` / `fs.read` / `fs.write` / `admin`)
-- GitHub / Google 第三方登录(`identity_links` 表)
-- 邮件 OTP 投递(SMTP 集成)
-- `ov otp` Rust CLI 子命令
-
----
-
-## 验证
-
-### 单元 / 集成测试
-```bash
-pytest tests/server/oauth/ -v # 38 通过(含完整 device flow happy path)
-pytest tests/server/test_auth.py tests/server/test_mcp_endpoint.py -v # 回归
-```
-
-### 端到端 curl(device flow)
-```bash
-# 1. 注册客户端
-curl -X POST -H "Content-Type: application/json" \
- -d '{"redirect_uris":["http://127.0.0.1:9999/cb"],"client_name":"test","token_endpoint_auth_method":"none"}' \
- http://127.0.0.1:1933/register
-
-# 2. PKCE
-VERIFIER=$(openssl rand -base64 64 | tr -d '=+/' | head -c 64)
-CHALLENGE=$(printf "%s" "$VERIFIER" | openssl dgst -sha256 -binary | basenc --base64url | tr -d '=')
-
-# 3. 浏览器: GET /authorize?... → 跳到 /oauth/authorize/page → 显示 6 字符码 e.g. "AB3X7K"
-
-# 4. 用户在 console 输入 AB3X7K(或直接 curl)
-curl -X POST -H "X-Api-Key: $ROOT_KEY" -H "Content-Type: application/json" \
- -d '{"code":"AB3X7K","decision":"approve"}' \
- http://127.0.0.1:1933/api/v1/auth/oauth-verify
-
-# 5. Page 自动 302 回 redirect_uri,从中取 auth_code
-
-# 6. 换 token
-curl -X POST -d "grant_type=authorization_code&code=ovac_...&client_id=...&code_verifier=$VERIFIER&redirect_uri=..." \
- http://127.0.0.1:1933/token
-# → {"access_token":"ovat_...","refresh_token":"ovrt_...","expires_in":3600}
-
-# 7. 调 MCP
-curl -X POST -H "Authorization: Bearer ovat_..." \
- http://127.0.0.1:1933/mcp -d '{"jsonrpc":"2.0","method":"tools/list","id":1}'
-```
-
-### 向后兼容
-- `oauth.enabled=false`(默认):`auth.py` 中 `oauth_provider is None`,OAuth 分流被跳过;行为与改动前一致
-- `oauth.enabled=true`:`Authorization: Bearer <api_key>`(无 `ovat_` 前缀)仍走 APIKeyManager;现有客户端无感知
-
----
-
-## 关键文件路径速查
-
-**新增**:
-- `openviking/server/oauth/{provider,storage,router,otp,__init__}.py`
-- `openviking_cli/utils/config/oauth_config.py`
-- `tests/server/oauth/test_{storage,router,auth_integration,mcp_www_authenticate}.py`
-
-**修改**:
-- `openviking/server/auth.py`(`_try_resolve_oauth_token`)
-- `openviking/server/mcp_endpoint.py`(`WWW-Authenticate` + `_scope_to_origin`)
-- `openviking/server/identity.py`(`from_oauth` 字段)
-- `openviking/server/app.py`(lifespan + `create_auth_routes` + env-aware issuer)
-- `openviking_cli/utils/config/open_viking_config.py`(接入 `OAuthConfig`)
-- `openviking/console/app.py`(proxy `/auth/otp`, `/auth/oauth-verify`)
-- `openviking/console/static/{index.html,app.js}`(device flow 表单 + 同源 quick-authorize)
-
-**复用**(不改):
-- `openviking/server/identity.py:AuthMode/Role/ResolvedIdentity`
-- `openviking_cli/utils/config/storage_config.py:StorageConfig.workspace`
-- `mcp.server.auth.*`(官方 SDK,无新依赖)
-
----
-
-## 风险与已识别问题
-
-| 风险 | 处理 |
-|---|---|
-| 反代后 `issuer` 派生错(HTTPS 终结于代理) | `OPENVIKING_PUBLIC_BASE_URL` env 或 `oauth.issuer` 配置;非 localhost 部署强烈建议显式设 |
-| 同源 quick-authorize 是隐式确认 | 即使检测到 sessionStorage,**仍需点击 "Authorize" 按钮**才生效,不会一步跳转 |
-| display_code 暴力枚举 | 6 字符 × 32 字母表 = ~1B 组合;TTL 10min;pending 一次性消费;建议在反代层加每 IP 速率限制 |
-| Refresh token 重放 | 实现:检测重放→`store.revoke_tokens(account, user)` 一并撤销该 user 名下所有 OAuth state |
-| Token 权限范围 = 整个 REST API | 已与用户确认 Phase 1 不限制;Phase 2 引入 scope 机制收紧 |
-| API Key → 撤销 OAuth token 的精度 | 当前粒度 `(account, user)`:删 user 时调 `revoke_tokens` cascade;满足需求 |
-| Console 与 OAuth page 同源依赖反代 | 文档提供 nginx 模板;不反代时退化为"console 复制 OTP,page 输入"流程仍可用 |
diff --git a/docs/design/memory-link-design.md b/docs/design/memory-link-design.md
deleted file mode 100644
index afd5febcd..000000000
--- a/docs/design/memory-link-design.md
+++ /dev/null
@@ -1,1945 +0,0 @@
-# Memory Link 设计文档
-
-> 日期: 2026-04-23
-> 状态: Draft
-> 分支: feat/memory_isolation
-
-## 1. 概述
-
-Memory Link 是在现有记忆体系(profile/preferences/entities/events 等)之上建立的统一关系层,将分散的记忆文件通过有向链接互联。
-
-**核心目标:**
-- 实体关系与链接:记忆之间建立有向、带类型、带权重的链接,支持双向回链
-- 主题整合:外部 Bot T+1 触发整理,从已有记忆中发现问题,生成问题驱动的研究报告
-
-**设计原则:**
-- 记忆类型扩展链接能力 — 扩展现有 MemoryTypeSchema,所有记忆文件自带链接能力
-- 存储载体:VikingFS 文件,与现有记忆体系一致
-- 链接存储在记忆文件的 `MEMORY_FIELDS` 元数据中,content 保持纯净,检索时按需渲染
-- Memory Link 是 memory 内部 links/backlinks 机制,不依赖已废弃的 resource relation 边
-
-## 2. 竞品实现分析
-
-### 2.1 GBrain
-
-**定位:** 个人知识大脑,AI agent 在每次响应前读取、对话后写入的持久化知识库。
-
-**Skill 执行模型:** GBrain = CLI 工具(TypeScript,确定性操作如 search/put/sync/embed)+ Skillpack(29 个 fat markdown 指令文件)。Skill 是指令不是代码——告诉宿主 agent 什么时候调什么 CLI、什么条件下调 LLM,但不含运行时,没有 hook。
-
-`gbrain skillpack install --all` 将 skill 文件复制到运行时 workspace。
-
-
-
-```mermaid
-flowchart TB
- gb_msg[用户对话消息] --> gb_signal[signal-detector\n行为指令,异步调子代理]
- gb_meeting[Meeting 转录] --> gb_mtingest[meeting-ingestion skill]
- gb_media[链接/文章/视频/Email] --> gb_ingest[idea-ingest / media-ingest / email-to-brain]
- gb_git[Git 仓库] --> gb_sync[gbrain sync\n增量导入]
-
- gb_signal --> gb_write
- gb_mtingest --> gb_write
- gb_ingest --> gb_write
- gb_sync --> gb_write
-
- subgraph gb_write[写入操作(CLI)]
- gb_page[put_page\n覆写 compiled truth\n+ auto-link hook 写 links]
- gb_addlink[add_link\nLLM 手动建链]
- gb_timeline[add_timeline_entry\n追加 timeline]
- end
-
- gb_page --> gb_pages[pages 数据库表\ncompiled_truth + timeline]
- gb_page --> gb_links[links 数据库表]
- gb_addlink --> gb_links
- gb_timeline --> gb_pages
- gb_page --> gb_dream[Dream Cycle\n每夜四阶段]
- gb_dream --> gb_page2[整理产物\n重编译页面 + 富化实体]
- gb_page --> gb_embed[写入时\n分块 + embedding + 全文索引]
- gb_links --> gb_search[搜索 + backlink boost]
- gb_pages --> gb_search
- gb_brainops[brain-ops\n每次响应前查 brain] --> gb_search
- style gb_signal fill:#ff9,stroke:#333
- style gb_dream fill:#cfc,stroke:#333
- style gb_brainops fill:#9cf,stroke:#333
-```
-
-#### 输入写入
-
-**输入源:**
-
-| 输入 | 机制 | 负责 Skill |
-|------|------|------------|
-| 对话消息 | CLAUDE.md / RESOLVER.md 写入"signal-detector on every inbound message",用户每条消息触发子代理异步执行:①检测原创想法→`brain/originals/`(原文逐字记录)②`gbrain search`检测实体引用→已有页面追加 timeline / 无页面则创建③回链铁律:实体页面补写回链④`gbrain sync` | `signal-detector` |
-| Meeting 转录 | 拉取完整转录(非 AI 摘要),创建会议页,传播到所有参会者/公司的 timeline,双向建链 | `meeting-ingestion` |
-| 链接/文章/Tweet | 用户分享链接 → 创建页面 + 作者人物页 + 交叉链接 | `idea-ingest` |
-| 视频/音频/PDF | 转录 → 实体提取 → 回链传播 | `media-ingest` |
-| Email | 确定性脚本拉取邮件 → LLM 判断实体/行动项 → 更新 brain 页面 | `email-to-brain` recipe |
-| Git 仓库 | `gbrain sync` 增量导入变更文件,逐文件走 put_page | CLI |
-
-**对话读取机制**(brain-ops,行为指令):每次响应前先查 brain(`gbrain search` / `gbrain get`),形成 read-enrich-write 循环。同样是 LLM 行为指令,非程序级 hook。
-
-
-**数据模型:** `pages` 表存储页面,每个页面由 `---` 分隔为两部分:
-
-```markdown
----
-title: Pedro Franceschi
-type: person
-tags: [ceo, brex]
----
-
-Pedro is CEO of Brex. Previously co-founded Cognito.
----
-
-- 2026-04-10 | Presented Q1 numbers [Source: board meeting, 2026-04-10]
-- 2026-04-05 | Met for coffee, discussed Series D [Source: conversation, 2026-04-05]
-```
-
-- **Compiled Truth**(`---` 上方):agent 对该实体的当前认知摘要,每次更新**整体覆写**。类似维基条目的当前版本
-- **Timeline**(`---` 下方):带日期 + source attribution 的证据链,**只追加不覆写**。类似 git log,记录"谁在什么时候说了什么"
-
-#### compile机制
-
-**核心事实(基于 GBrain v0.12 源代码分析):**
-- compiled_truth 和 timeline 是两个独立存储,**没有自动从 timeline 编译到 compiled_truth 的代码逻辑**
-- compiled_truth 更新**完全依赖 LLM agent** 主动调用 `put_page` 覆写
-- timeline 只追加不覆写,通过 `add_timeline_entry` 写入
-
-**更新路径:**
-
-| 路径 | 触发 | 计算方式 | 说明 |
-|------|------|----------|------|
-| 1. 实时更新 | 用户对话中 agent 主动调用 | LLM | agent 读取现有 compiled_truth + timeline,重新生成新 compiled_truth,调用 `put_page` 覆写 |
-| 2. stale 页面更新 | Dream Cycle 未实现 | LLM(未实现) | 设计文档提到的 "T+1 compile" 概念,代码中未实现 |
-
-**stale-link reconciliation:**
-- auto-link post-hook 在 `put_page` 时自动移除不再存在的链接(基于内容重新提取)
-- 但 slug 改名问题仍存在:指向旧 slug 的 Markdown 链接不会自动更新,读取端用 pg_trgm 模糊匹配缓解
-
-#### 链接系统
-
-**写入方式**(两条路径,都会写 `links` 表):
-
-**路径 A:put_page 内 auto-link hook**(`runAutoLink`,零 LLM,每次 `put_page` 自动执行,`gbrain sync` 也会触发):
-
-1. **Entity-ref 提取**:从 compiled_truth 中提取 Markdown 链接(`[张三](../people/zhangsan.md)`)和裸 slug 引用(`people/zhangsan`),自动剥离 code fence 避免代码块误提取
-2. **类型推断级联**:对 compiled_truth 做正则匹配 + 页面元数据启发式,推断 link_type(零 LLM)。从强到弱级联,同一对页面(from_slug, to_slug)只保留一条边、优先级最高的类型:
-
- | 内容模式 | link_type | 示例 |
- |----------|-----------|------|
- | `"founded"/"co-founded"` | `founded` | `"Alice founded Acme AI"` → `founded` |
- | `"invested in"` | `invested_in` | `"Bob invested in Acme AI"` → `invested_in` |
- | `"advises"/"advisor"` | `advises` | `"Carol advises Acme AI"` → `advises` |
- | `"CEO of"/"CTO of"` 等 | `works_at` | `"Alice, CEO of Acme AI"` → `works_at` |
- | 会议页(type=meeting)+ 人物引用 | `attended` | 会议页提到 `[Alice](people/alice)` → `attended` |
- | partner-bio 语言 | `invested_in` | VC 机构人物页提到某公司 → `invested_in` |
-
-3. **Within-page 去重**:同一页面内指向同一目标的多个引用只保留一条链接
-
-
-**路径 B:LLM agent 手动调用 `add_link`**:meeting-ingestion 等 skill 指令调 `add_link` CLI。两页面间只有一条边,重复调用覆盖
-
-
-#### 核心路径
-
-| # | 路径 | 触发 | 处理摘要 |
-|---|------|------|----------|
-| 1 | **put_page** | CLI / MCP / Agent | 解析 frontmatter → SHA256 去重 → 分块(300词) → embedding → 旧值快照 → 覆写 pages → 对账 tags → **runAutoLink**(auto-link hook,写 links 表 + stale-link reconciliation) |
-| 2 | **gbrain sync** | CLI / cron / `--watch` | `git pull` → `git diff` → 按 A/M/D/R 分类 → 逐文件走 put_page |
-| 3 | **add_link** | LLM agent 按 skill 指令调用 | `INSERT ON CONFLICT DO UPDATE`(两页面间一条边) |
-| 4 | **add_timeline_entry** | LLM agent 按 skill 指令调用 | 参数:slug + date(YYYY-MM-DD,严格校验)+ summary + detail(可选)+ source(可选)→ 追加单条 timeline_entries 记录,不动 compiled_truth;DB trigger 自动刷新 search_vector(timeline 内容参与全文搜索)和 updated_at |
-| 5 | **extract links** | 首次启用 / 版本升级 | 遍历所有页面 → 提取实体引用 → 类型推断级联 → 写入 links。支持 `--since` 增量、`--dry-run` |
-| 6 | **check-backlinks** | CLI / maintain skill | 正则扫描正文 Markdown 链接 → `check` 报告缺失 / `fix` 补写 timeline |
-
-#### 定时整理
-
-Dream Cycle,通过 cron + skills 实现的 6 阶段维护管道(从 GBrain v0.12 源代码分析得出):
-
-| 阶段 | 输入 | 计算方式 | 输出 |
-|------|------|----------|------|
-| Phase 1: Lint | 所有页面 | CLI(无 LLM) | lint 报告,检查缺失字段等结构问题 |
-| Phase 2: Backlinks | 所有页面 | CLI(无 LLM) | 检查回链完整性,调用 `check-backlinks fix` |
-| Phase 3: Sync | Git 仓库 | CLI(无 LLM) | `gbrain sync` 拉取并导入变更 |
-| Phase 4: Extract | 新增/变更页面 | CLI + auto-link post-hook(零 LLM) | 调用 `gbrain extract links` 批量提取链接 |
-| Phase 5: Embed | 嵌入过期的页面 | CLI(无 LLM) | `gbrain embed --stale` 重新计算向量 |
-| Phase 6: Orphans | 孤立实体 | CLI(无 LLM) | 识别无入边的实体页面 |
-
-**核心事实:**
-- Dream Cycle 是**维护管道**,全部 6 个阶段均为 CLI 确定性操作,零 LLM 调用
-- auto-link post-hook 已在 `put_page` 时自动执行,Extract 阶段用于批量回填历史页面
-- Orphans 阶段只统计孤立页面数量(>20 则状态 warn),不自动处理
-
-
-#### 搜索管线(读路径)
-
-```
-1. Query → 意图分类器(entity/temporal/event/general)
-2. 多查询扩展(llm 生成 2 个query + 原始query 共3路)
-3. 向量搜索(HNSW cosine)+ 关键词搜索(tsvector)→ RRF 融合
-4. compiled truth boost: compiled_truth 权重是timeline的两倍
-5. backlink boost: r.score *= (1.0 + 0.05 * Math.log(1 + count)) 被更多页面链接的实体分数更高(P@5 +5.4pts,Recall@5 +11.5pts)
-6. cosine 重评分: const blended = 0.7 * normRrf + 0.3 * cosine
-7. 去重逻辑:
-(1)同一页面只保留top3 chunks
-(2)Jaccard相似度大于 0.85 trunk去重。
-(3)同一页面类型不超过结果60% (比如 person)
-(4)同一页面只保留top2 chunks
-```
-
-**Backlink boost**:被更多页面链接的实体排名更高。BrainBench v1(240 页):P@5 +5.4pts,Recall@5 +11.5pts。
-
-#### 图遍历
-```
- 基于链接提供了图遍历的CLI供模型调用(基于postgresql实现)
- 例 1:谁在 Acme 工作?(入边 + 类型过滤)
- gbrain graph-query companies/acme --type works_at --direction in
-
- 例 2:谁投资了 Acme?(入边 + 不同类型)
- gbrain graph-query companies/acme --type invested_in --direction in
-
- 例 3:两跳关系——Alice 通过会议间接见过谁?
- gbrain graph-query people/alice --type attended --depth 2
-```
-
-#### 关键取舍
-
-- 建链依赖 LLM 行为指令(skill markdown),没有代码级 hook 保证执行——agent 可能跳过建链
-- backlink boost 是简单排序加分,不做图传播,无法发现种子文件多跳之外的关联
-- auto-link post-hook 基于正则提取,无法验证目标页面是否存在(可能产生悬空链接)
-- 正文 Markdown 链接不会随 slug 改名自动更新,stale-link reconciliation 修复内容修改引起的失效,但 slug rename 场景未完全解决
-
-#### 评测
-
-提供了BrainBench 用于评测
-https://github.com/garrytan/gbrain-evals
-
-### 2.2 OpenClaw
-
-**定位:** 开源自托管 AI 个人助理平台,插件架构,memory 是一个特殊 plugin slot。
-
-**输入源:** 对话(memory-core 和 memory-wiki 分别消费对话)。
-
-**memory-wiki** 为独立于**memory-core**的记忆加工与存储模块
-
-**memory-core 在线写入(攒批提取):** 对话达到阈值时 LLM flush 写入,生成每日笔记 history/date.md。SQLite 索引做搜索。
-
-**memory-wiki 在线写入(工具调用写入):** LLM 在对话中调用 `wiki_apply` 工具,写入带 Claims 的 wiki 页面(YAML frontmatter)。memory-wiki 是独立子系统,通过跨插件资源同步从 memory-core 导入整理产物(MEMORY.md、history/date.md)作为资源输入。
-
-#### Claims — 结构化知识可信度管理
-
-OpenClaw 最核心的设计是 Claims 体系,将页面中的事实声明结构化,支持可信度评估和矛盾检测。
-
-**Claim 结构:** 每个页面可包含多个 claim,每个 claim 有:
-- `text`:声明内容(如 "Alpha uses PostgreSQL")
-- `status`:supported / contested / contradicted / refuted / superseded
-- `confidence`:0~1 可信度
-- `evidence`:证据数组,每条证据指向源页面 + 行号范围 + 权重
-
-**三层链接机制:**
-1. **Claim ID 跨页引用**:相同 claim `id` 出现在不同页面时,自动聚类检测矛盾
-2. **sourceIds 页面溯源**:页面级指向源页面,编译时生成 Sources / Referenced By / Related Pages 三类关联
-3. **Evidence 证据溯源**:每条证据指向具体源页面的行号,比页面级溯源更精细
-
-**矛盾检测与健康评估:** 按 claim ID 聚类检测矛盾,按更新时间计算 freshness(fresh < 30天 / aging 30-89天 / stale ≥ 90天)。Dashboard 展示 Open Questions、Contradictions、Low Confidence 等报告。
-
-
-```mermaid
-flowchart TB
- subgraph oc_core[memory-core 插件]
- direction TB
- oc_in[对话] --> oc_flush[攒批提取\n对话达到阈值时 flush]
- oc_flush --> oc_daily[每日笔记\nhistory/date.md]
- oc_in --> oc_search[memory_search\n副作用记录 recall]
- oc_search --> oc_recall[recall 跟踪 JSON]
- oc_daily --> oc_dream1[定时整理 Phase 1 Light\n每 6h 规则切片]
- oc_recall --> oc_dream1
- oc_dream1 --> oc_dream2[Phase 2 Deep\n每日 3AM\n6维评分提升]
- oc_dream2 --> oc_dream3[Phase 3 REM\n每周日\n关键词频率标记主题]
- oc_dream3 --> oc_memory[整理产物\nMEMORY.md\nhistory/date.md]
- end
-
- subgraph oc_wiki_plugin[memory-wiki 插件 — 3 个数据来源]
- direction TB
- oc_src1[来源1: wiki_apply\nLLM 工具调用写入] --> |syntheses/ 页面| oc_compile[wiki 编译器\n全量编译\n零LLM]
- oc_src2[来源2: 跨插件资源同步\nMEMORY.md + history/date.md] --> |sources/ 页面| oc_compile
- oc_src3[来源3: wiki.ingest\n本地文件导入] --> |sources/ 页面| oc_compile
- oc_compile --> oc_related[页面 Related 块\nSources / Referenced By]
- oc_compile --> oc_dashboard[5 个 Dashboard\n矛盾 / 低置信度 / 过期]
- oc_compile --> oc_digest[agent-digest.json\n+ claims.jsonl]
- oc_compile --> oc_index[6 个索引页]
- end
-
- oc_memory -.-> oc_src2
- style oc_compile fill:#ff9,stroke:#333
- style oc_src1 fill:#9f9,stroke:#333
- style oc_src2 fill:#9cf,stroke:#333
- style oc_src3 fill:#9cf,stroke:#333
- style oc_dream1 fill:#cfc,stroke:#333
- style oc_dream2 fill:#fcf,stroke:#333
- style oc_dream3 fill:#ccf,stroke:#333
-```
-
-**memory core部分**
-
-**Phase 1 Light Sleep 规则切片示例**:
-
-输入 `history/2026-04-05.md`:
-```markdown
-## 运维
-- 重启了网关,auth 偏移导致的。
-- Token 现在对齐了。
-
-## 小王
-- 她喜欢直接定时间,不喜欢"改天再说"。
-- 最好给一个具体时间段。
-```
-
-切片产出(写入 short-term-recall.json):
-
-| chunk | 行号 | snippet | 分数 |
-|-------|------|---------|------|
-| 1 | 2-3 | `运维: 重启了网关,auth 偏移导致的。; Token 现在对齐了。` | 0.62(硬编码) |
-| 2 | 6-7 | `小王: 她喜欢直接定时间,不喜欢"改天再说"。; 最好给一个具体时间段。` | 0.62(硬编码) |
-
-切片规则:按 `## heading` 分组 → 列表项用 `; ` 拼接 → 每组最多 4 行/280 字符 → 不调 LLM → 分数硬编码(daily=0.62, session=0.58)
-
-**Phase 2 Deep Sleep 评分提升示例**:
-
-假设"小王"这条 snippet 在接下来几天被搜索召回了 4 次,跨 3 天、2 个不同 query:
-
-| 维度 | 权重 | 值 | 加权 |
-|------|------|------|------|
-| frequency | 0.24 | log1p(4)/log1p(10) = 0.66 | 0.158 |
-| relevance | 0.30 | avgScore = 0.78 | 0.234 |
-| diversity | 0.15 | max(2,3)/5 = 0.60 | 0.090 |
-| recency | 0.15 | exp(-ln2/14 × 2) = 0.91 | 0.137 |
-| consolidation | 0.10 | max(spread=0.55, grounded=0) = 0.55 | 0.055 |
-| conceptual | 0.06 | 2tags/6 = 0.33 | 0.020 |
-| **总分** | | | **0.694** |
-
-门控条件:signalCount(4) ≥ 3 ✓ | diversity(3) ≥ 3 ✓ | score(0.694) < 0.8 ✗ → **未通过,不提升**
-
-若后续又被召回 2 次(共 6 次),分数升至 0.86,则通过门控,追加到 MEMORY.md:
-```markdown
-## Promoted From Short-Term Memory (2026-04-08)
-<!-- openclaw-memory-promotion:memory:memory/2026-04-05.md:6:7:a1b2c3d4e5f6 -->
-- 小王: 她喜欢直接定时间,不喜欢"改天再说"。; 最好给一个具体时间段。
- [score=0.86 recalls=6 avg=0.80 source=memory/2026-04-05.md:6-7]
-```
-
-**Phase 3 REM Sleep 关键词频率标记主题示例**:
-
-关键词来源:对每个 snippet 做规则分词(词表匹配 + 复合 token 正则 + Intl.Segmenter 分词),过滤停用词和太短的词,最多 8 个关键词。不调 LLM。
-
-假设 short-term-recall.json 中有 20 条 snippet,关键词频率统计:
-
-| 关键词 | 出现次数 | 总条目数 | strength | 标记主题? |
-|--------|----------|----------|----------|----------|
-| 网关 | 3 | 20 | min(1, 3/20×2) = 0.30 | ✗ (< 0.75) |
-| 定时间 | 12 | 20 | min(1, 12/20×2) = 1.0 | ✓ |
-
-超过阈值(0.75)的关键词输出为标记主题:
-```markdown
-### 标记主题
-- Theme: `定时间` kept surfacing across 12 memories.
- - confidence: 1.0
- - evidence: memory/2026-04-05.md:6-7, memory/2026-04-06.md:2-3, ...
-
-### Possible Lasting Truths
-- 小王: 她喜欢直接定时间。[confidence=0.72 evidence=memory/2026-04-05.md:6-7]
-```
-
-标记主题不直接提升记忆,只是发现高频关键词;candidate truths 列出的条目会被 REM 写入 phase-signals.json(remHits += 1),后续 Deep Sleep 评分时通过 phaseBoost(0.09 × remStrength × remRecency)间接加分,仍需通过 6 维评分门控才能提升到 MEMORY.md。注意这不是关键词共现分析,只是单个关键词的频率统计。
-
-memory core最终输出的为MEMORY.md及history/2026-04-26.md
-
-**memory-wiki 部分 — 3 个数据来源,写入后均触发全量编译**
-
-**来源1: wiki_apply(LLM 工具调用写入)**
-- **触发**:LLM 在对话中调用 `wiki_apply` 工具
-- **输入**:JSON,包含 op + title + body + sourceIds + claims + contradictions + questions
-- **处理**:写入 wiki 页面(YAML frontmatter + markdown body)→ 触发全量编译
-- **输出**:wiki 页面 .md 文件 + 编译产物
-
- wiki_apply 只支持两种操作:`create_synthesis`(写入 `syntheses/xxx.md`)和 `update_metadata`(更新已有页面 frontmatter)。不支持创建 entity/concept 页面。sourceIds 和 claims 均由 LLM 填写,编译器只做被动 Map 查找。
-
- **输入示例**(LLM 发送的工具调用):
- ```json
- {
- "op": "create_synthesis",
- "title": "小王运维手册",
- "body": "小王负责生产环境 Kubernetes 集群的日常运维,包括滚动升级和故障排查。",
- "sourceIds": ["source.小王周报", "source.oncall-log"],
- "claims": [
- {
- "id": "claim.小王.k8s",
- "text": "小王是生产环境 K8s 集群的一线运维负责人",
- "status": "supported",
- "confidence": 0.92,
- "evidence": [{"sourceId": "source.小王周报", "lines": "3-7", "weight": 0.9}]
- }
- ],
- "contradictions": ["与旧版值班表冲突"],
- "questions": ["小王是否还负责测试环境?"],
- "confidence": 0.8
- }
- ```
-
- **输出示例**(写入 `syntheses/小王运维手册.md`):
- ```markdown
- ---
- pageType: synthesis
- id: synthesis.小王运维手册
- title: 小王运维手册
- sourceIds:
- - source.小王周报
- - source.oncall-log
- claims:
- - id: claim.小王.k8s
- text: 小王是生产环境 K8s 集群的一线运维负责人
- status: supported
- confidence: 0.92
- evidence:
- - sourceId: source.小王周报
- lines: 3-7
- weight: 0.9
- contradictions:
- - 与旧版值班表冲突
- questions:
- - 小王是否还负责测试环境?
- confidence: 0.8
- updatedAt: "2026-04-26T10:00:00.000Z"
- ---
-
- # 小王运维手册
-
- ## Summary
- <!-- openclaw:wiki:generated:start -->
- 小王负责生产环境 Kubernetes 集群的日常运维,包括滚动升级和故障排查。
- <!-- openclaw:wiki:generated:end -->
-
- ## Notes
- <!-- openclaw:human:start -->
- <!-- openclaw:human:end -->
- ```
-
- 页面结构:YAML frontmatter 存结构化数据(claims/contradictions/questions/confidence/sourceIds),正文分 Summary(编译器管理)和 Notes(人类可编辑)两个 managed block。
-
-**来源2: 跨插件资源同步(memory-core → memory-wiki)**
-- **触发**:几乎每次 wiki 操作前先跑
-- **输入**:memory-core 的整理产物(MEMORY.md、history/date.md)
-- **处理**:按 mtime + size 做增量跳过 → 写入 sources/ 页面 → 判断是否需要编译
-- **输出**:sources/*.md 页面 + 可能触发全量编译
-
- 同步是纯文件搬运,不对内容做任何提取或加工。原始内容整体放入 `## Content` 代码块,frontmatter 记录元信息。
-
- **同步示例**:
-
- 输入:memory-core 的 `MEMORY.md`(mtime 或 size 变化)
-
- 产出:写入 `sources/bridge-workspace-a1b2c3d4-memory-ef567890.md`:
- ```yaml
- ---
- pageType: source
- id: source.bridge.workspace-a1b2c3d4.memory-ef567890
- title: "Memory Bridge (main): memory / MEMORY"
- sourceType: memory-bridge
- sourcePath: /absolute/path/to/workspace/MEMORY.md
- bridgeRelativePath: MEMORY.md
- bridgeWorkspaceDir: /absolute/path/to/workspace
- bridgeAgentIds:
- - main
- updatedAt: "2026-04-26T12:00:00.000Z"
- ---
-
- # Memory Bridge (main): memory / MEMORY
-
- ## Bridge Source
- - Workspace: `/absolute/path/to/workspace`
- - Relative path: `MEMORY.md`
- - Updated: 2026-04-26T12:00:00.000Z
-
- ## Content
- ```markdown
- <MEMORY.md 的原始内容>
- ```
-
- ## Notes
- <!-- openclaw:human:start -->
- <!-- openclaw:human:end -->
- ```
-
- 增量跳过逻辑:读取 `.openclaw-wiki/source-sync.json`,比对 mtime + size + renderFingerprint,三项都没变则跳过写入。
-
-**来源3: wiki.ingest(本地文件导入)**
-- **触发**:CLI / gateway 调用
-- **输入**:本地文件路径 + 可选 title
-- **处理**:读取文件 → 断言 UTF-8 文本 → slug 化标题 → 写入 sources/ 页面 → 触发全量编译
-- **输出**:sources/*.md 页面
-
- 纯文件搬运,不对内容做任何提取或 LLM 调用。产出格式与 bridge 类似,但 frontmatter 用 `sourceType: local-file`,正文用 `## Source` 块记录文件元信息 + `## Content` 块放原始内容。
-
-**全量编译 compileMemoryWikiVault(全程零 LLM)**
-- **触发**:每次写入后自动触发 / CLI 命令 / gateway 调用
-- **输入**:所有 wiki 页面
-- **处理**:全量读所有页面 → 计算每个页面的 Related 块 → 矛盾检测 + freshness 评估 → 生成 5 个 Dashboard → 生成 agent-digest.json + claims.jsonl → 生成索引页
-- **输出**:页面 `## Related` 块 + 5 个 Dashboard 页面 + agent-digest.json + claims.jsonl + index.md + 分组 index.md
-
- **编译示例**(3 个页面):
-
- 输入页面:
- | 页面 | kind | sourceIds | claims |
- |------|------|-----------|--------|
- | `sources/小王周报.md` | source | — | — |
- | `syntheses/小王运维手册.md` | synthesis | source.小王周报 | claim.小王.k8s: "小王是 K8s 一线运维" (supported, 0.92) |
- | `syntheses/运维排班.md` | synthesis | source.小王周报 | claim.小王.k8s: "小王已不负责 K8s,转交小李" (contested, 0.6) |
-
- 编译产出 1 — Related 块(注入各页面):
-
- `syntheses/小王运维手册.md` 获得:
- ```markdown
- ## Related
- <!-- openclaw:wiki:related:start -->
- ### Sources
- - [小王周报](sources/小王周报.md)
-
- ### Related Pages
- - [运维排班](syntheses/运维排班.md)
- <!-- openclaw:wiki:related:end -->
- ```
-
- `sources/小王周报.md` 获得:
- ```markdown
- ## Related
- <!-- openclaw:wiki:related:start -->
- ### Referenced By
- - [小王运维手册](syntheses/小王运维手册.md)
- - [运维排班](syntheses/运维排班.md)
- <!-- openclaw:wiki:related:end -->
- ```
-
- Related 块计算逻辑:Sources = 当前页 sourceIds 指向的页面(Map 查找);Referenced By = sourceIds 包含当前页 id 的页面 + `[[wikilink]]` 指向当前页的页面;Related Pages = 共享 sourceIds 但不在前两者中的页面。全量遍历,非增量。
-
- 编译产出 2 — 矛盾检测(按 claim ID 聚类):
-
- 同一 claim ID `claim.小王.k8s` 出现在 2 个页面,且文本不同 + 状态不同 → 形成矛盾聚类:
- ```
- key: "claim.小王.k8s"
- entries: [运维排班(contested, stale), 小王运维手册(supported, fresh)]
- ```
-
- 矛盾检测全部依赖 LLM 填写的 claim id 和 contradictions 字段:claim 级矛盾按 claim.id 分组(同一 id 在 ≥2 页且 text/status 不同),页面级矛盾按 contradictions 文本归一化分组。编译器只做被动聚类,不调 LLM。
-
- 编译产出 3 — freshness 评估(按 updatedAt 天数):
-
- | 页面 | updatedAt | 天数 | level |
- |------|-----------|------|-------|
- | 小王运维手册 | 2026-04-26 | 0 | fresh |
- | 运维排班 | 2026-01-05 | 111 | stale (≥90) |
-
- 编译产出 4 — Dashboard 页面:
-
- `reports/contradictions.md`:
- ```markdown
- # Contradictions
- - Competing claim clusters: 1
- ### Claim Clusters
- - `claim.小王.k8s`: 运维排班 -> contested, stale | 小王运维手册 -> supported, fresh
- ```
-
- `reports/stale-pages.md`:
- ```markdown
- # Stale Pages
- - [运维排班](syntheses/运维排班.md): stale (2026-01-05)
- ```
-
- 编译产出 5 — agent-digest.json(元数据摘要):
-
- `.openclaw-wiki/cache/agent-digest.json`:
- ```json
- {
- "generatedAt": "2026-04-26T10:30:00.000Z",
- "stats": {
- "totalPages": 3,
- "sources": 1,
- "syntheses": 2,
- "entities": 0,
- "concepts": 0,
- "totalClaims": 2,
- "contradictionClusters": 1,
- "openQuestions": 1
- },
- "pages": [
- {
- "path": "syntheses/小王运维手册.md",
- "title": "小王运维手册",
- "kind": "synthesis",
- "id": "synthesis.小王运维手册",
- "updatedAt": "2026-04-26T08:00:00.000Z",
- "freshness": "fresh",
- "claimCount": 1,
- "questionCount": 1,
- "contradictionCount": 1,
- "sourceIds": ["source.小王周报.2026w17"],
- "topClaims": [
- {
- "id": "claim.小王.k8s",
- "text": "小王是 K8s 一线运维负责人",
- "status": "supported",
- "confidence": 0.92
- }
- ]
- },
- {
- "path": "syntheses/运维排班.md",
- "title": "运维排班",
- "kind": "synthesis",
- "id": "synthesis.运维排班",
- "updatedAt": "2026-01-05T14:00:00.000Z",
- "freshness": "stale",
- "claimCount": 1,
- "questionCount": 0,
- "contradictionCount": 1,
- "sourceIds": ["source.小王周报.2026w17"],
- "topClaims": [
- {
- "id": "claim.小王.k8s",
- "text": "小王主要负责测试环境维护",
- "status": "contested",
- "confidence": 0.65
- }
- ]
- },
- {
- "path": "sources/小王周报.md",
- "title": "小王周报",
- "kind": "source",
- "id": "source.小王周报.2026w17",
- "updatedAt": "2026-04-22T18:00:00.000Z",
- "freshness": "aging",
- "claimCount": 0,
- "questionCount": 0,
- "contradictionCount": 0,
- "sourceIds": [],
- "topClaims": []
- }
- ],
- "claimHealth": {
- "contradictionClusters": [
- {
- "key": "claim.小王.k8s",
- "type": "claim-id",
- "entries": [
- {
- "path": "syntheses/运维排班.md",
- "status": "contested",
- "freshness": "stale"
- },
- {
- "path": "syntheses/小王运维手册.md",
- "status": "supported",
- "freshness": "fresh"
- }
- ]
- }
- ]
- }
- }
- ```
-
-**读路径(全程零 LLM)**
-
-**wiki_search(wiki 内搜索)**
-- **触发**:LLM 调用 `wiki_search` 工具 / CLI / gateway
-- **输入**:query 字符串 + corpus(wiki/memory/all)
-- **处理**:先读 agent-digest.json 做元数据预筛选 → 对候选页面全文本搜索评分
-- **输出**:排序结果列表
-
- 评分规则(纯数值,不调 LLM):
-
- | 匹配位置 | 加分 |
- |----------|------|
- | title 精确匹配 | +50 |
- | title 包含 | +20 |
- | claim text 包含 | +25 |
- | sourceId 包含 | +12 |
- | 正文出现(每次) | +1(上限 10) |
- | claim confidence | +0~10 |
- | freshness | fresh +8 / aging +4 / stale -2 |
-
- 搜索结果示例:
- ```json
- {
- "corpus": "wiki",
- "path": "syntheses/小王运维手册.md",
- "title": "小王运维手册",
- "kind": "synthesis",
- "score": 53,
- "snippet": "小王是 K8s 一线运维负责人",
- "id": "synthesis.小王运维手册",
- "updatedAt": "2026-04-26T08:00:00.000Z"
- }
- ```
-
-**wiki_lint(结构检查)**
-- **触发**:CLI / gateway / tool 调用
-- **输入**:所有 wiki 页面
-- **处理**:编译先跑一遍 → 然后逐页检查 16 种问题
-- **输出**:`reports/lint.md`
-
- 16 种检查全部是纯字段过滤,不调 LLM:
-
- | 类别 | 代码 | 严重度 | 检测什么 |
- |------|------|--------|----------|
- | 结构 | missing-id / duplicate-id / missing-page-type / page-type-mismatch / missing-title | error | frontmatter 完整性和一致性 |
- | 溯源 | missing-source-ids / missing-import-provenance / claim-missing-evidence | warning | 页面和 claim 的来源可追溯性 |
- | 链接 | broken-wikilink | warning | [[wikilink]] 目标不存在 |
- | 矛盾 | contradiction-present / claim-conflict | warning | 页面级矛盾声明 + claim ID 聚类冲突 |
- | 问题 | open-question | warning | 页面有未解决问题 |
- | 质量 | low-confidence / claim-low-confidence / stale-page / stale-claim | warning | 低置信度 + 过时(stale ≥ 90天) |
-
- 产出示例(`reports/lint.md`):
- ```markdown
- # Lint Report
- - Errors: 0
- - Warnings: 3
-
- ### Contradictions
- - `syntheses/小王运维手册.md`: Claim cluster `claim.小王.k8s` has competing variants across 2 pages.
-
- ### Quality Follow-Up
- - `syntheses/运维排班.md`: Claim `claim.小王.k8s` is missing structured evidence.
- - `syntheses/运维排班.md`: Page freshness is stale (2026-01-05).
- ```
-
-**Prompt Section(agent digest 注入 LLM 上下文)**
-- **触发**:每次 LLM 调用前构建 prompt 时(需 `includeCompiledDigestPrompt=true`,默认关闭)
-- **输入**:`.openclaw-wiki/cache/agent-digest.json`
-- **处理**:按 claim/question/contradiction 数量对页面排序 → 取 top 4 页面 → 每页取 top 2 claims → 拼接摘要
-- **输出**:注入 LLM system prompt 的 wiki 概要
-
- LLM 看到的内容:
- ```markdown
- ## Compiled Wiki
- Use the wiki when the answer depends on accumulated project knowledge.
- Workflow: wiki_search first, then wiki_get for the exact page.
-
- ## Compiled Wiki Snapshot
- Compiled wiki currently tracks 2 claims across 1 high-signal pages.
- Contradiction clusters: 1.
- - 小王运维手册: synthesis, 1 claims, 1 open questions, 1 contradiction notes
- - 小王是 K8s 一线运维负责人 (status supported, confidence 0.92, freshness fresh)
- - 小王是否还负责测试环境? (open question)
- ```
-
- 本质:把编译产物的摘要注入 LLM 上下文,让 LLM 知道 wiki 里有什么,决定是否调 wiki_search/wiki_get 获取详情。
-
-**关键取舍:**
-- Claims 三层链接提供了结构化的知识可信度管理,但增加了写作负担
-- 矛盾检测依赖 claim `id` 的一致性(无 id 的 claim 无法跨页关联),而 claim id 由 LLM 填写,一致性无保证
-- 编译器全程零 LLM,所有关系计算依赖 LLM 在 wiki_apply 时填写的 sourceIds、claims、contradictions 字段
-
-### 2.3 nashsu_llm_wiki
-
-**定位:** 桌面应用(Tauri + React),实现 Karpathy LLM Wiki 模式——LLM 增量构建并维护持久化 wiki,而非每次查询重新推导。
-
-**架构:** 原始素材(不可变)→ wiki(LLM 生成的页面)→ schema(配置 wiki 结构)
-
-**输入源:** 两种方式并存:
-1. **文件导入(主要)**:文件/网页剪藏/Deep Research → 自动触发知识提取 → 生成完整 wiki 页面
-2. **Save to Wiki(对话)**:用户与 LLM 对话 → 手动点击 "Save to Wiki" → 仅保存单条助手回复为 `wiki/queries/` 页面
-
-```mermaid
-flowchart TB
- nw_in[资源\n文件/网页/Deep Research] --> nw_ingest[知识提取\n两步 LLM 链式推理]
- nw_ingest --> nw_page[页面\n含 wikilink 正文]
-
- nw_chat[用户对话\n与 LLM 聊天] --> nw_save[Save to Wiki\n手动点击保存]
- nw_save --> nw_query_page[wiki/queries/\n单条回复页面]
- nw_query_page --> nw_page
-
- nw_page --> nw_enrich[enrichWithWikilinks\nLLM 补充链接]
- nw_page --> nw_graph[按需图构建\n聊天/图视图触发]
- nw_enrich --> nw_graph
- nw_graph --> nw_relevance[4 信号相关性\n在线计算不持久化]
- nw_page --> nw_lint[Lint 检查\n孤立 / 死链 / 矛盾]
- style nw_ingest fill:#fcf,stroke:#333
- style nw_graph fill:#ccf,stroke:#333
- style nw_save fill:#ffc,stroke:#333
-```
-
-**1. 知识提取(两步 LLM)**
-- **第一步分析**:读取源内容 + wiki/index.md + wiki/purpose.md,输出结构化分析(关键实体/关键概念/核心论点/矛盾/建议)
-- **第二步生成**:把第一步分析作为上下文(不解析,直接传文本),输出的是**纯文本**,格式是多个块依次拼接:
- 1. 每个要写入的页面对应一个 `---FILE: wiki/path/to/page.md---` 开头、`---END FILE---` 结尾的块,中间是完整的 Markdown 内容(含 frontmatter)
- 2. 所有页面块之后,可选输出 `---REVIEW: type | Title---` 开头、`---END REVIEW---` 结尾的块,标注需要人工确认的项
-- 生成的页面通常包括:sources/(源摘要)+ entities/(实体页)+ concepts/(概念页)+ index.md(索引)+ log.md(日志)+ overview.md(概览)
-- SHA256 缓存去重,不变的素材不重复处理
-
- **具体例子**:
-
- 假设导入一份 `acme-k8s-migration.pdf`(Acme 公司的 Kubernetes 迁移报告):
-
- - **第一步分析输出**:
- ```
- ## 关键实体
- - Alice Smith (人物,核心,技术负责人)
- - Acme Corp (组织,核心,迁移实施方)
- - Kubernetes (产品,边缘,已有页面可能存在)
-
- ## 关键概念
- - 微服务架构:将应用拆分为独立服务的方法,本报告核心
- - CI/CD 流水线:自动化构建测试部署流程
-
- ## 核心论点
- - Acme Corp 从单体应用迁移到微服务,使用 Kubernetes
- - 部署时间减少 70%
- - 证据:报告中提供的迁移前后部署指标对比
-
- ## 矛盾
- - 无外部矛盾
- - 内部张力:部署变快但运维复杂度上升
-
- ## 建议
- - 创建 Alice Smith 和 Acme Corp 的实体页
- - 创建微服务架构概念页(如果不存在)
- - 更新 overview 加入这个迁移案例
- ```
-
- - **第二步生成输出**:
- ```
- ---FILE: wiki/sources/acme-k8s-migration.md---
- ---
- type: source
- title: "Source: Acme K8s Migration Report"
- created: 2026-04-28
- updated: 2026-04-28
- tags: [migration, kubernetes]
- sources: ["acme-k8s-migration.pdf"]
- ---
- # Source: Acme K8s Migration Report
-
- ## 摘要
- Acme Corp 成功从单体应用迁移到基于 Kubernetes 的微服务架构,由 Alice Smith 主导。
-
- ## 关键发现
- - 部署时间减少 70%
- - 运维复杂度有所上升
- ---END FILE---
-
- ---FILE: wiki/entities/alice-smith.md---
- ---
- type: entity
- title: "Alice Smith"
- created: 2026-04-28
- updated: 2026-04-28
- tags: [engineer, migration-lead]
- related: [[acme-corp]]
- sources: ["acme-k8s-migration.pdf"]
- ---
- # Alice Smith
-
- ## 角色
- Acme Corp 技术负责人,主导微服务迁移。
-
- ## 背景
- 推动 Acme Corp 从单体迁移到 Kubernetes 的核心人物。
- [[acme-corp]]
- ---END FILE---
-
- ---FILE: wiki/entities/acme-corp.md---
- ---
- type: entity
- title: "Acme Corp"
- created: 2026-04-28
- updated: 2026-04-28
- tags: [company, technology]
- related: [[alice-smith]]
- sources: ["acme-k8s-migration.pdf"]
- ---
- # Acme Corp
-
- ## 简介
- 一家最近完成微服务迁移的科技公司。
-
- ## 关键行动
- - 2026: 从单体迁移到 Kubernetes 微服务
- [[alice-smith]]
- ---END FILE---
-
- ---FILE: wiki/concepts/microservices-architecture.md---
- ---
- type: concept
- title: "微服务架构"
- created: 2026-04-28
- updated: 2026-04-28
- tags: [architecture, cloud]
- related: [[kubernetes]]
- sources: ["acme-k8s-migration.pdf"]
- ---
- # 微服务架构
-
- ## 定义
- 将应用开发为一组小型独立服务,通过 API 通信。
-
- ## 权衡
- - 部署更快
- - 运维复杂度上升
- ---END FILE---
-
- ---FILE: wiki/index.md---
- ---
- type: overview
- title: "Wiki Index"
- created: 2026-04-01
- updated: 2026-04-28
- ---
- # Wiki Index
-
- ## 实体
- - [[alice-smith]]
- - [[acme-corp]]
-
- ## 概念
- - [[microservices-architecture]]
- ---END FILE---
-
- ---REVIEW: duplicate | Kubernetes 可能已存在---
- 分析提到 Kubernetes,但不确定是否已有页面,建议检查后再决定是否创建。
- OPTIONS: Create Page | Skip
- SEARCH: kubernetes 容器编排 | 微服务 kubernetes 部署
- ---END REVIEW---
- ```
-
-**2. enrichWithWikilinks(链接补充)**
-- LLM 判断哪些术语应链接到已有页面 → 在正文插入 `[[wikilink]]`
-
-**3. 按需图构建**
-- 读所有 .md 文件 → 正则提取 `[[wikilink]]` → 构建图结构 → 缓存在内存(模块级变量)
-- 使用时:如果 `cachedGraph.dataVersion === 当前 dataVersion` 则直接用缓存,否则重新构建
-- 需要相关性分数时:调用 `calculateRelevance` 函数**在线实时计算**(不缓存)
-
-4 信号相关性:
-
-| 信号 | 权重 | 来源 |
-|------|------|------|
-| 直接链接 | 3.0 | `[[wikilink]]` 语法 |
-| 源文件重叠 | 4.0 | frontmatter `sources: []` 共享 |
-| Adamic-Adar | 1.5 | 共同邻居,按 1/log(度) 加权 |
-| 类型亲和 | 1.0 | 同类型页面加分 |
-
-
-**4. 检索**
-- 分词搜索 + 向量搜索(LanceDB,可选)→ RRF 融合 → 排序结果(最多 20 条):
-
-| 步骤 | 说明 |
-|------|------|
-| 分词搜索 | 本地文件扫描,分数计算:文件名精确匹配(+200)> 标题包含短语(+50)> 正文包含短语(每次+20,最多10次)> 标题token匹配(每个+5)> 正文token匹配(每个+1) |
-| 向量搜索 | 可选(LanceDB),返回 top10 语义相似结果 |
-| RRF 融合 | `fused(p) = 1/(60 + token_rank) + 1/(60 + vector_rank) |
-| 去重排序 | 按 RRF 分数降序,同分按路径字母顺序,取前 20 条 |
-
-
-**5. Lint 检查**
-- 结构检查(孤立/死链)+ 语义检查(LLM 检测矛盾/过期)
-
-**无定时整理**:所有知识产出依赖知识提取时一次性完成,没有后续的矛盾发现、过时更新或跨页面整合
-
-**关键取舍:**
-- 链接存正文(`[[wikilink]]`),slug 变更时链接失效
-- 没有链接类型、没有权重,关系计算靠源文件重叠和图拓扑
-- 4 信号相关性模型比纯 PPR 更丰富,但权重硬编码
-
-### 2.4 OpenKB
-
-**定位:** 开源 CLI 工具,将原始文档编译成结构化、相互链接的 wiki 风格知识库。受 Andrej Karpathy "LLM Wiki" 想法启发——LLM 自动生成摘要、概念页和交叉引用,让知识随时间积累,而非每次查询重新推导(传统 RAG 的做法)。
-
-**输入源:** 文件导入(PDF、docx、pptx、md 等),或文件系统监控(watchdog 自动处理 `raw/` 目录新增文件)。
-
-**架构:** 文档 → 转换 → 编译(多步 LLM 管线)→ wiki 页面(summaries + concepts + index)
-
-```mermaid
-flowchart TB
- okb_file[文件\nPDF/docx/pptx/md等] --> okb_hash[Hash去重\nSHA-256\n纯代码]
- okb_hash -->|已知| okb_skip[跳过]
- okb_hash -->|新文件| okb_convert[文档转换\nmarkitdown/pymupdf\n纯代码]
-
- okb_convert -->|短文档| okb_md[wiki/sources/.md\n全文Markdown]
- okb_convert -->|长PDF\n≥threshold页| okb_pi[PageIndex索引\nLLM在服务端]
-
- okb_pi --> okb_tree[层级树结构\n+逐页内容]
- okb_pi --> okb_pi_summary[摘要页\n纯代码渲染]
-
- okb_md --> okb_step1[Step 1: 生成摘要\nLLM\nsystem+doc=上下文A]
- okb_pi_summary --> okb_step1_long[Step 1: 生成概述\nLLM\nsystem+doc=上下文A]
- okb_step1 --> okb_step2
- okb_step1_long --> okb_step2
-
- okb_step2[Step 2: 概念规划\nLLM\n复用上下文A] --> okb_plan[create/update/related\n三类动作]
- okb_plan --> okb_step3[Step 3: 概念生成\nLLM并发\n复用上下文A]
-
- okb_step3 --> okb_step3b[Step 3b: related链接\n纯代码追加]
- okb_step3b --> okb_step3c[Step 3c: 双向回链\n纯代码追加]
- okb_step3c --> okb_step4[Step 4: 更新index.md\n纯代码]
-
- style okb_step1 fill:#fcf,stroke:#333
- style okb_step1_long fill:#fcf,stroke:#333
- style okb_step2 fill:#fcf,stroke:#333
- style okb_step3 fill:#fcf,stroke:#333
- style okb_pi fill:#fcf,stroke:#333
-```
-
-#### 文档转换(纯代码,零 LLM)
-
-| 文件类型 | 转换方式 | 输出 |
-|----------|----------|------|
-| `.md` | 直接读取 + 复制相对路径图片并改写链接 | `wiki/sources/{name}.md` |
-| `.pdf`(短,< threshold 页) | pymupdf dict-mode 逐页遍历 text/image block → Markdown + 内联图片 | `wiki/sources/{name}.md` + `wiki/sources/images/{name}/*.png` |
-| `.pdf`(长,≥ threshold 页) | 仅标记 `is_long_doc=True`,不转换,交给 PageIndex | 返回标记 |
-| 其他(docx/pptx/xlsx/html/txt/csv) | markitdown 库转换 → 解码 base64 图片保存磁盘并改写链接 | `wiki/sources/{name}.md` + `wiki/sources/images/{name}/*.png` |
-
-额外操作:原始文件复制到 `raw/` 目录存档,SHA-256 哈希注册到 `hashes.json`。
-
-#### PageIndex 索引(仅长 PDF,LLM 在服务端)
-
-| 子步骤 | 输入 | 计算 | LLM | 输出文件 |
-|--------|------|------|-----|----------|
-| 索引 | PDF 文件 | `PageIndexClient.collection().add(pdf)` — 上传 PDF 到 PageIndex 服务,服务端用 LLM 解析文档结构 | 是(PageIndex 内部) | `doc_id`, `doc_description`, `structure`(层级树) |
-| 获取页面内容 | doc_id, page_count | Cloud 模式:OCR 后的 Markdown;失败回退本地 pymupdf | Cloud 模式用 OCR | `wiki/sources/{name}.json`(per-page 内容数组) |
-| 渲染摘要 | tree 结构 | `render_summary_md()` — 递归遍历树节点,渲染为 Markdown 层级标题 + summary | 否 | `wiki/summaries/{name}.md` |
-
-PageIndex 使用无向量(vectorless)的推理式检索——通过层级树索引实现长文档的结构化访问,不依赖 embedding。
-
-#### Wiki 编译(多步 LLM 管线,prompt 缓存)
-
-编译管线的核心设计是**上下文 A 复用**:Step 1 构造 system_msg(AGENTS.md schema + 语言指令)+ doc_msg(文档内容/PageIndex 摘要),作为 prompt 缓存的前缀;Step 2-3 复用同一前缀,让 LLM 服务端命中缓存,减少重复计算。
-
-**Step 1: 生成摘要/概述**
-
-| 项 | 短文档 | 长文档 |
-|----|--------|--------|
-| Prompt | `_SUMMARY_USER` — 文档全文 + "写摘要页" | `_LONG_DOC_SUMMARY_USER` — PageIndex 摘要 + "写概述" |
-| LLM 调用 | 1 次同步 | 1 次同步 |
-| 输出格式 | JSON `{"brief": "...", "content": "..."}` | 纯 Markdown |
-| 写入文件 | `wiki/summaries/{name}.md`(frontmatter: doc_type=short) | 摘要已在 PageIndex 步骤写好,此步输出作为后续输入 |
-
-**Step 2: 概念规划**
-
-| 项 | 说明 |
-|----|------|
-| 输入 | 上下文 A + 上一步 summary + 已有概念页的 briefs |
-| LLM 调用 | 1 次同步 |
-| 输出 | JSON plan: `{"create": [...], "update": [...], "related": [...]}` |
-
-三种动作:
-- **create**: 新概念,需生成全新页面
-- **update**: 已有概念有新信息,需全文重写(不是追加)
-- **related**: 轻量关联,只加交叉链接不改内容
-
-已有概念页以紧凑格式呈现给 LLM:`- {slug}: {brief}`(brief 从 frontmatter 读取,缺省时截取正文前 150 字符)。
-
-**Step 3: 概念页生成/更新**
-
-| 项 | 说明 |
-|----|------|
-| LLM 调用 | N 次并发异步(N = create 数 + update 数,默认 concurrency=5) |
-| create Prompt | `_CONCEPT_PAGE_USER` — title + doc_name,生成新概念页 |
-| update Prompt | `_CONCEPT_UPDATE_USER` — title + doc_name + **已有概念页全文**,LLM 被要求"全文重写融入新信息,不要追加" |
-| 输出格式 | JSON `{"brief": "...", "content": "..."}` |
-
-写入逻辑:
-- **create**: 新文件,frontmatter 含 `sources` 和 `brief`
-- **update**: 读取已有 frontmatter → 追加 source_file 到 sources 列表 → 替换 body 为 LLM 重写内容 → 更新 brief
-
-**Step 3b/3c: 关联链接 + 双向回链(纯代码,零 LLM)**
-
-| 操作 | 做什么 |
-|------|--------|
-| `_add_related_link()` | 在 related 概念页末尾追加 `See also: [[summaries/{doc}]]` + frontmatter 追加 source |
-| `_backlink_summary()` | 在摘要页追加 `## Related Concepts` 章节,列出所有 `[[concepts/{slug}]]` |
-| `_backlink_concepts()` | 在每个概念页追加 `## Related Documents` 章节,列出 `[[summaries/{doc}]]` |
-
-目的:确保双向链接闭环——摘要链接概念,概念也链接摘要。
-
-**Step 4: 更新索引(纯代码,零 LLM)**
-
-在 `wiki/index.md` 的 `## Documents` 下插入文档条目,`## Concepts` 下插入或更新概念条目。条目格式:`- [[link]] (type) — brief text`。
-
-#### 全流程 LLM 调用汇总
-
-| 步骤 | LLM 调用次数 | 缓存利用 | 备注 |
-|------|-------------|----------|------|
-| Hash 去重 | 0 | — | 纯代码 |
-| 文档转换 | 0 | — | 纯代码 |
-| PageIndex 索引(仅长PDF) | 1+(PageIndex 内部) | — | 对 OpenKB 透明 |
-| Step 1: 生成摘要/概述 | **1** | system+doc 构成缓存上下文 A | 短文档用全文,长文档用 PageIndex 摘要 |
-| Step 2: 概念规划 | **1** | 复用上下文 A(缓存命中) | |
-| Step 3: 概念页生成 | **N**(create+update 数) | 复用上下文 A(缓存命中) | 并发执行,默认 concurrency=5 |
-| Step 3b/3c: 关联+回链 | 0 | — | 纯代码 |
-| Step 4: 更新索引 | 0 | — | 纯代码 |
-
-典型短文档:2 + N 次 LLM 调用(1 摘要 + 1 规划 + N 概念页)。典型长 PDF:2 + N 次加 PageIndex 内部调用。
-
-#### 链接系统
-
-**链接载体:** 正文内 `[[wikilink]]` 语法(如 `[[concepts/attention]]`、`[[summaries/attention-is-all-you-need]]`)。
-
-**链接类型:** 无类型系统,所有链接都是无类型的 wikilink,无法区分"属于""导致""矛盾"等关系语义。
-
-**链接权重:** 无权重,所有链接等价。
-
-**双向链接机制:** 通过代码级回链保证——编译管线的 Step 3b/3c 在写入后立即补全反向链接。但只在编译时执行,如果后续手动编辑页面删除了链接,反向链接不会自动清理。
-
-**链接精度:** 页面级(`[[concepts/slug]]`),不支持行号级定位。
-
-#### 搜索/问答
-
-- **query 命令**:OpenAI Agents SDK 驱动的 LLM agent,3 个工具(`read_file`、`get_page_content`、`get_image`)导航已编译 wiki 回答问题
-- **chat 命令**:交互式多轮对话 REPL,支持会话持久化、slash commands
-- **无向量化搜索**:query/chat agent 依赖 LLM 自主决策读哪些页面,不做 embedding 检索
-
-#### Lint 检查
-
-| 层级 | 检查内容 | 计算方式 |
-|------|----------|----------|
-| 结构性 lint | 断链、孤儿页、raw 文件缺 wiki 条目、index.md 不同步 | 纯代码(正则匹配 wikilink) |
-| 语义 lint | 矛盾、遗漏、过时、冗余、概念覆盖 | LLM agent(OpenAI Agents SDK) |
-
-#### 定时整理
-
-**无定时整理。** 所有知识产出在文件导入时一次性完成(多步 LLM 编译管线),没有后续的矛盾发现、过时更新或跨页面整合机制。随着页面增多,概念页可能过时但不自动刷新。
-
-#### 关键取舍
-
-- 链接存正文(`[[wikilink]]`),slug 变更时链接失效,无 stale-link reconciliation
-- 无链接类型和权重,所有关系等价,无法区分"属于""导致""矛盾"等语义
-- 双向回链仅在编译时保证,手动编辑后可能不一致
-- 无定时整理/矛盾发现,知识库长期维护依赖人工 lint
-- 多步 LLM 管线的 prompt 缓存设计有效降低重复计算,但每次编译都是全量生成(无增量更新)
-- PageIndex 的无向量检索是对传统 RAG 的有趣替代,但仅限于长 PDF 场景
-
-### 2.5 竞品启发与设计决策
-
-**1. PageIdMap 消除死链(vs GBrain auto-link + check-backlinks / OpenKB 编译时回链)**
-GBrain 在 `put_page` 时通过 auto-link post-hook 自动提取实体引用并创建链接,还通过 `check-backlinks` 命令检查并修复回链,用 pg_trgm 模糊 slug matching 缓解读取端问题。但 auto-link 基于正则提取,无法验证目标页面是否存在(可能产生悬空链接)。OpenKB 在编译时通过代码级 `_backlink_summary` / `_backlink_concepts` 保证双向链接,但仅在编译时刻执行,手动编辑或 slug 变更后链接可能断裂,且无 stale-link reconciliation。OV 的 PageIdMap 从结构上杜绝死链——page_id 只分配给上下文中确认存在的文件,链接不可能指向不存在的页面。
-
-**2. 延迟渲染替代写入时链接(vs GBrain 正文 Markdown 链接 / OpenKB [[wikilink]] 正文链接)**
-GBrain 的 auto-link post-hook 有 stale-link reconciliation 功能,在内容修改时自动移除失效链接。但正文中的 Markdown 链接(如 `[张三](../people/zhangsan.md)`)不会随 slug 改名自动更新,仍是断裂风险点。OpenKB 同样把链接写在正文中(`[[wikilink]]`),编译时生成,无 reconciliation 机制,slug 变更直接导致断链。OV 的 content 保持纯净,链接存在 `links` 元数据中,检索时按需渲染 match_text。target_uri 变化只改元数据,content 不动。
-
-**3. LinkType 枚举 + weight 权重(vs GBrain 自由文本 + 类型推断 / OpenClaw 无权重 / OpenKB 无类型无权重)**
-GBrain 的 `links` 表的 `link_type` 列是自由文本,但 auto-link post-hook 能通过类型推断级联自动推断标准类型(founded → invested_in → advises → works_at)。不过 LLM 调 `add_link` 时仍可填入任意值(同义歧义如 `knows` vs `familiar_with`)。OpenClaw 没有权重。OpenKB 的 `[[wikilink]]` 完全没有类型和权重,所有链接等价,无法区分"属于""导致""矛盾"等语义。OV 用枚举约束关系类型,用 weight 表达关联强度,支持更精细的检索排序。
-
-**4. 不引入 Claims 层(from OpenClaw 启发)**
-OpenClaw 的 Claims 三层链接 + 矛盾检测 + freshness 评估是一套完整的知识可信度管理,但 OV 不引入独立 claims 层。原因:原始 md 已包含事实记录,links 体系已覆盖 claim 的核心能力——矛盾(`CONTRADICTS`)、演变(`EVOLVED_FROM`)、可信度(`weight`)、证据溯源(`t_uri + t_field + t_line_ranges`)。独立 claim 层只是 links 的冗余子集。
-
-**5. 链接元数据 vs 正文内链接(from nashsu_llm_wiki / OpenKB 启发)**
-nashsu_llm_wiki 和 OpenKB 都把链接写在正文中(`[[wikilink]]`),slug 变更时链接失效,且无法携带类型和权重。GBrain 的结构化链接存储在独立数据库表中(不在正文中),auto-link post-hook 通过 stale-link reconciliation 自动修复内容变更引起的失效链接,但正文中的 Markdown 交叉引用仍有 slug 变更问题。OV 的链接存在元数据中,正文保持纯净,与第 2 点延迟渲染策略一致。
-
-**6. 外部 Bot T+1 触发主题整合 vs Dream Cycle 维护管道(from GBrain + nashsu_llm_wiki + OpenKB 启发)**
-nashsu_llm_wiki 和 OpenKB 都没有定时整理,全靠导入/编译时一次性产出。GBrain 的 Dream Cycle 是纯维护管道(lint → backlinks → sync → extract → embed → orphans),不涉及 LLM,没有记忆整合或实体升级功能。随着页面增多,一次性提取或纯维护都难以发现跨页面的矛盾、过时和遗漏。OpenKB 的语义 lint 能发现矛盾和过时,但需人工触发,无自动整理。OV 的整理由外部 Bot T+1 触发,从已有记忆中发现问题,调用 ExtractLoop 生成报告,保持知识库活力。
-
-**7. 现有 merge_op 映射(vs GBrain 页面内容覆写 / OpenClaw Dreaming)**
-OV 已有的 merge_op 体系与竞品的记忆整理模式天然对应:
-- `upsert`(PATCH)≈ GBrain compiled_truth(LLM 主动覆写式重编译)
-- `add_only`(SUM)≈ GBrain timeline / OpenClaw history/date.md(追加式)
-- 外部 Bot T+1 触发主题整合 ≈ OpenClaw Phase 2/3(短期→长期提升 + 关键词频率标记主题)
-无需新建整理范式,复用现有机制即可。
-
-**8. PPR 搜索增强(vs GBrain backlink boost / nashsu_llm_wiki 4 信号图扩展 / OpenKB LLM agent 导航)**
-GBrain 已实现 backlink boost——搜索排序时被更多页面链接的实体排名更高(BrainBench v1: P@5 +5.4pts, Recall@5 +11.5pts),但这是简单排序加分,不做图传播,无法发现种子文件多跳之外的关联。OV 用 PPR 算法实现 query 相关的图增强检索,从搜索种子出发沿 links 做带权随机游走,天然支持多种子桥接发现,详见 3.5 节。nashsu_llm_wiki 用 4 信号加权做图扩展,但权重硬编码且无类型区分;OV 的 PPR 按 `(link_type, links/backlinks)` 配置表驱动,灵活可调。OpenKB 不做图增强,query/chat 完全依赖 LLM agent 自主决策导航 wiki 页面,召回能力受 agent 推理能力限制。
-
-**9. ExtractLoop 统一提取 vs 多步编译管线(from OpenKB 启发)**
-OpenKB 的编译管线是精心设计的多步 LLM 调用链:摘要 → 概念规划 → 并发概念生成 → 代码级回链 → 索引更新,每步有明确的输入/输出契约,且通过 prompt 缓存复用上下文降低成本。但每次新文档导入都独立走完整管线,概念页的"update"路径依赖 LLM 全文重写(非增量),随着页面增多成本线性增长。OV 的 ExtractLoop 在单次 LLM 调用中统一输出记忆操作 + links,由 merge_op 体系处理增量合并(`upsert` PATCH / `add_only` SUM),更轻量且天然支持增量更新。
-
-## 3. OpenViking 链接设计
-
-### 3.1 设计总览
-
-**定位:** AI agent 的持久化记忆系统,在对话中实时写入记忆,外部 Bot T+1 触发整理发现主题生成研究报告。
-
-**输入源:** 对话消息 + 资源(默认进 wiki / 默认不进 wiki)。
-
-**数据写入(3 种输入场景):**
-
-| 场景 | 触发 | 说明 |
-|------|------|------|
-| (1) 对话消息 | session.commit | 对话进记忆,互链 |
-| (2) 邮件会议纪要等默认进 wiki 的 resource | add-resource | 资源进记忆,互链 |
-| (3) 默认不进 wiki 的 resource | add-resource | 资源不进记忆,但记忆可链接到资源 |
-
-三种场景统一走 ExtractLoop,LLM 按 schema 输出记忆操作 + links
-
-**链接机制:** 链接存在文件元数据 JSON(VikingFS)中,content 保持纯净。6 种 LinkType 枚举约束,weight 表达关联强度,t_line_ranges 行号级精度。一条链接写入 from 端 links + to 端 backlinks,两侧记录完全相同。PageIdMap 从结构上杜绝死链。
-
-**T+1整理:** 主题整合。从已有记忆中发现问题(新记忆无关联 report / CONTRADICTS 链接 / report_candidate),逐主题调用 ExtractLoop(DreamContextProvider)生成 report。暴露 CLI 供 Bot 通过 Cron 触发。report_candidate 来源:session 中提到的研究主题 / CLI 提交研究主题 / 基于搜索结果分布。
-
-**整理产物:** 问题驱动的研究报告(report memory_type)。
-
-```mermaid
-flowchart TB
- ov_s1["(1) 对话消息 session.commit"]
- ov_s2["(2) 邮件会议纪要等默认进wiki的 resource"]
- ov_s3["(3) 默认不进wiki的 resource"]
- ov_s1 --> ov_extract["ExtractLoop\n(SessionContextProvider)"]
- ov_s2 --> ov_extract
- ov_s3 --> ov_extract
- ov_extract <--> ov_memory[entity/event/preference等记忆\n links + backlinks]
- ov_extract --> |session中提到的研究主题|ov_rc
- ov_rc[report_candidate\n候选主题] --> ov_dream["ExtractLoop\n(DreamContextProvider) (per report)"]
- ov_memory --> ov_dream
- ov_bot[暴露CLI供Bot通过Cron触发] --> ov_dream
- ov_bot --> |CLI提交研究主题| ov_rc
- ov_search[search请求] -->|基于search结果分布| ov_rc
- ov_dream --> ov_report[问题驱动的研究报告]
-
-
- style ov_s1 fill:#ffe6cc,stroke:#333
- style ov_s2 fill:#ffe6cc,stroke:#333
- style ov_s3 fill:#ffe6cc,stroke:#333
- style ov_extract fill:#9f9,stroke:#333
- style ov_dream fill:#9f9,stroke:#333
- style ov_memory fill:#9cf,stroke:#333
- style ov_rc fill:#9cf,stroke:#333
- style ov_report fill:#9cf,stroke:#333
- style ov_bot fill:#ffc,stroke:#333
-```
-
-**关键路径**:对话消息/资源 → ExtractLoop(LLM 统一输出记忆 + links)→ merge_op 合并写入 → 向量化/摘要异步入队 → report_candidate → Bot Cron 触发 T+1 整理 → PPR 在线图增强
-
-**1. 在线写入(3 种输入场景统一走 ExtractLoop)**
-
-| 场景 | 触发 | 说明 |
-|------|------|------|
-| (1) 对话消息 | session.commit | 记忆间互链 |
-| (2) 邮件会议纪要等默认进 wiki 的 resource | add-resource | 资源进记忆,互链 |
-| (3) 默认不进 wiki 的 resource | add-resource | 资源不进记忆,但记忆可链接到资源 |
-
-- **处理**:
- 1. SessionExtractContextProvider.prefetch() — 搜索/读取已有记忆文件和资源
- 2. ExtractLoop.run() — LLM 按 schema 输出记忆操作 + links(统一输出)
- 3. resolve_operations() — page_id 转 URI,链接分发到 from 端 links + to 端 backlinks
- 4. MemoryUpdater.apply_operations() — merge_op 合并 + 写入记忆文件 + 行号修正 + 向量化入队
-- **输出**:记忆 .md 文件(含 links/backlinks 元数据)+ EmbeddingMsg 入队 + memory_diff.json
-
-**2. MergeOp 字段合并**
-- **触发**:apply_operations 中对每个 field 调用
-- **输入**:current_value + patch_value
-- **处理**:patch(SEARCH/REPLACE 搜索替换)/ sum(数值加法)/ immutable(不可变)
-- **输出**:合并后的字段新值
-
-**3. 向量化计算**
-- **触发**:记忆写入后入队
-- **输入**:记忆文件内容(去除 MEMORY_FIELDS 注释)
-- **处理**:后台 worker 从队列取出 → embedder 计算向量 → upsert 到向量存储
-- **输出**:向量索引记录
-
-**4. Semantic Processor(摘要生成)**
-- **触发**:记忆写入后入队 SemanticMsg
-- **输入**:目录中的 .md 文件
-- **处理**:LLM 生成每文件摘要 → 汇总生成 .abstract.md 和 .overview.md → 摘要文件入队向量化
-- **输出**:.abstract.md + .overview.md + 摘要 EmbeddingMsg
-
-**5. T+1 触发整理**
-- **触发**:暴露 CLI 供 Bot 通过 Cron 触发
-- **输入**:当天新增/修改的记忆文件 + 已有 report 列表 + report_candidate
-- **处理**:
- 1. 主题发现:新记忆无关联 report → 新主题;CONTRADICTS 链接 → 冲突主题;report_candidate → 候选主题
- 2. 逐主题生成:DreamContextProvider 读取相关文件 → ExtractLoop 调 LLM 按 report schema 输出 → MemoryUpdater 写入
-- **输出**:report 文件(问题驱动的研究报告)+ report_candidate 标记已处理
-
-**6. PPR 图增强检索**
-- **触发**:搜索请求 / prefetch 阶段
-- **输入**:搜索种子 + links/backlinks 元数据
-- **处理**:从种子沿 links 做带权随机游走 → 按 (link_type, links/backlinks) 配置表决定权重/继续/深度 → 分数合并
-- **输出**:补充召回的文件列表 + 排序分数(临时,不持久化)
-
-### 3.2 Link 数据模型
-
-#### 3.2.1 两层模型设计
-
-链接系统分为两层:**LLM 输出层**(使用 page_id 引用)和**存储层**(使用 URI)。
-
-##### LLM 输出层:WikiLink
-
-LLM 在 structured output 中统一输出链接,不散在每个记忆字段内:
-
-```python
-class LinkType(str, Enum):
- RELATED_TO = "related_to"
- BELONGS_TO = "belongs_to"
- CAUSED_BY = "caused_by"
- DERIVED_FROM = "derived_from"
- CONTRADICTS = "contradicts"
- EVOLVED_FROM = "evolved_from"
-
-class WikiLink(BaseModel):
- f: int # page_id A
- t: int # page_id B
- t_field: str # B 的字段名(to 端精确定位)
- t_line_ranges: Optional[str] # B 的行号范围:"3-5"(to 端精确定位)
- link_type: LinkType # 关系类型(枚举)
- weight: float = 1.0 # 关联权重 0~1
- match_text: Optional[str] # A 中需链接化的文本片段(检索时用于渲染)
- description: str = "" # 链接描述:为什么建立此关联
-```
-
-**链接不对称**:from 侧是锚点(`match_text`),to 侧是展开信息(`t_field` + `t_line_ranges`)。存储时,一条链接写入两端文件的独立列表:from 文件的 `links`(正链,需渲染)+ to 文件的 `backlinks`(反链,不渲染,只用于遍历)。两侧记录内容完全相同,不翻转 link_type。
-
-LLM 输出示例:
-
-```json
-{
- "preferences": [
- {"page_id": 100, "topic": "Python code style", "content": "User dislikes type hints..."},
- {"page_id": 101, "topic": "Communication style", "content": "User prefers direct..."}
- ],
- "events": [
- {"page_id": 102, "event_name": "Code review", "content": "Caroline reviewed Python code..."}
- ],
- "links": [
- {"f": 100, "t": 3, "t_field": "content", "t_line_ranges": "3-5",
- "link_type": "belongs_to", "weight": 0.9, "match_text": "User",
- "description": "该偏好属于 Caroline"},
- {"f": 102, "t": 100, "t_field": "content", "t_line_ranges": "1-2",
- "link_type": "related_to", "weight": 0.7, "match_text": "Python code",
- "description": "事件中讨论的代码风格与该偏好相关"}
- ]
-}
-```
-
-**page_id 分配规则**:
-- 已有页面(prefetch/search/read 获取的):1~99,由 PageIdMap 自动分配
-- 新建页面(本次 LLM 输出的记忆):从 100 开始自增,每个记忆项自带 `page_id` 字段
-- page_id 是 ExtractLoop 生命周期内的临时标识,**不持久化**
-
-##### 存储层:StoredWikiLink
-
-写入文件后,page_id 全部转换为 URI:
-
-```python
-class StoredWikiLink(BaseModel):
- f_uri: str # 源文件 URI
- t_uri: str # 目标文件 URI
- t_field: str # 目标字段名
- t_line_ranges: Optional[str] # 目标行号范围
- link_type: LinkType # 关系类型(枚举)
- weight: float # 权重
- match_text: Optional[str] # 源中需链接化的文本
- description: str # 链接描述
-```
-
-#### 3.2.2 PageIdMap 组件
-
-URI ↔ page_id 双向映射,ExtractLoop 生命周期内有效:
-
-```python
-class PageIdMap:
- """URI ↔ page_id 双向映射,ExtractLoop 生命周期内有效"""
-
- def get_or_assign(self, uri: str) -> int:
- """URI → page_id。首次分配,后续返回同一 id"""
-
- def get_uri(self, page_id: int) -> Optional[str]:
- """page_id → URI。从 id 还原 uri"""
-
- def next_new_page_id(self) -> int:
- """分配新建页面的 page_id(从 100 开始自增)"""
-```
-
-**page_id 范围隔离**:
-- 1~99:已有页面(prefetch 阶段分配)
-- 100+:新建页面(LLM 输出时自增)
-
-#### 3.2.3 存储方式
-
-content 保持纯净,不插入 Markdown 链接。链接存储在每个记忆文件尾部的 `MEMORY_FIELDS` 元数据中,复用现有 memory file serialize/deserialize 流程。
-
-#### Memory Link 与 resource relation 的边界
-
-Memory Link 只属于 memory 子系统,用于在记忆文件之间维护 `links` / `backlinks`:
-
-- 写入入口:`ExtractLoop` 解析 LLM 输出的 links,`MemoryUpdater` 将其分发到 from/to 两端记忆文件
-- 存储位置:记忆文件自身的 `MEMORY_FIELDS.links` 和 `MEMORY_FIELDS.backlinks`
-- 读取用途:memory 检索、PPR 图增强、graph view、整理任务上下文
-- 不依赖已废弃的 resource relation API,也不通过独立 relation sidecar 存取
-
-因此,本次删除 resource relation 边,不应删除 memory 内部 links/backlinks。两者只是都表达“关系”,但数据入口、存储位置和消费链路不同。
-
-#### 存储结构
-
-链接存储在 endpoint 记忆文件的 `MEMORY_FIELDS` 中。`StoredLink` 包含 `from_uri`/`to_uri`/`link_type`/`weight`/`t_field`/`t_line_ranges`/`match_text`/`description` 字段:
-
-```json
-{
- "version": 3,
- "links": [
- {
- "id": "link_1",
- "from_uri": "viking://user/caroline/memories/preferences/Python_code_style.md",
- "to_uri": "viking://user/caroline/memories/profile.md",
- "link_type": "belongs_to",
- "weight": 0.9,
- "t_field": "content",
- "t_line_ranges": "3-5",
- "match_text": "User",
- "description": "该偏好属于 Caroline",
- "created_at": "2026-04-27T10:00:00.000Z"
- }
- ],
- "backlinks": [
- {
- "id": "link_2",
- "from_uri": "viking://user/caroline/memories/events/2026/04/27/code_review.md",
- "to_uri": "viking://user/caroline/memories/preferences/Python_code_style.md",
- "link_type": "related_to",
- "weight": 0.7,
- "t_field": "content",
- "t_line_ranges": "1-2",
- "match_text": "Python code style",
- "description": "事件中讨论的代码风格与该偏好相关",
- "created_at": "2026-04-27T10:00:00.000Z"
- }
- ]
-}
-```
-
-- from 端记忆文件写入 `MEMORY_FIELDS.links`,表示当前文件引用别人,渲染时可替换 `match_text`
-- to 端记忆文件写入 `MEMORY_FIELDS.backlinks`,表示别人引用当前文件,不渲染,只用于 PPR 遍历和整理主题发现
-- 两侧 `StoredLink` 记录内容完全相同(`link_type` 不翻转)
-
-#### 向下兼容
-
-`MEMORY_FIELDS` 是当前 memory file 的正式元数据载体。memory link 写入只产生 `links` / `backlinks` 字段,不兼容或迁移已废弃的 resource relation 产物。
-
-#### 与 StoredWikiLink 的关系
-
-3.1 节的 `StoredWikiLink` 是 LLM 输出后 page_id→URI 转换后的逻辑模型,字段与 `StoredLink` 一致。写入 `MEMORY_FIELDS` 时额外携带 `id`/`from_uri`/`created_at`。
-
-#### 查询接口
-
-- `MemoryFileUtils.parse()` / memory 读取工具 — 从记忆文件尾部 `MEMORY_FIELDS` 解析 links/backlinks
-- graph / PPR / context provider — 按 memory URI 读取 endpoint 文件的 links/backlinks 后参与图增强或上下文构建
-
-#### 3.2.4 检索时按需渲染
-
-content 原文不修改,链接渲染延迟到检索阶段,根据 `match_text` 在 content 中做运行时替换:
-
-```
-存储: "User dislikes type hints, prefers concise comments."
-渲染: "[User](viking://.../profile.md) dislikes type hints, prefers concise comments."
-```
-
-**不同场景的渲染策略**:
-
-| 场景 | 是否替换 match_text | 原因 |
-| ------------------ | ------------ | ------------------------ |
-| LLM prefetch 读入上下文 | 不替换 | LLM 更新时处理链接增加复杂度,PPR 已做实体关联召回 |
-| 向量化嵌入 | 不替换 | 纯文本语义更干净 |
-| search 返回摘要 | 替换(仅 links) | 用户可见的链接提升可读性和导航 |
-| 外部 Bot T+1 整理读取全量 | 不替换 | 原文做去重/合并更准确 |
-| 展示页查看 | 替换(仅 links) | 用户可见的链接提升可读性 |
-
-**渲染规则**:
-- match_text 替换**所有出现**
-- match_text 在正文中找不到时降级:links 保留该链接,正文不替换
-- 多个 match_text 有包含关系时,按长度降序匹配(先匹配长的)
-
-**好处**:
-- 写入幂等——content 是 LLM 原始输出不被修改
-- 链接可更新——target_uri 变化只改 links 元数据,content 不用动(GBrain 的 stale-link reconciliation 修复内容修改引起的链接失效,但 slug rename 场景未完全解决)
-- match_text 可修正——外部 Bot T+1 整理发现 match_text 不准确,直接改 links
-- 链接更新无需重算 embedding——links 存在 `MEMORY_FIELDS` 中,不参与可见 content 向量化,更新链接不触发重新 embedding
-
-#### 3.2.5 Links Merge 策略
-
-`links` 和 `backlinks` 的合并逻辑在 `memory/merge_op/link_merge.py` 中独立实现。两个方向使用相同的合并规则。
-
-**合并规则:**
-- 按 `from_uri` + `to_uri` + `t_field` + `t_line_ranges` 组合去重(同一对文件同一字段不同行号范围视为不同链接)
-- 权重冲突时取 max
-- `link_type` 和 `description` 以最新写入为准
-- 结果按 weight 降序排列
-
-#### 3.2.6 t_line_ranges 行号修正机制
-
-文件 PATCH 更新后,`t_line_ranges` 可能偏移。修正流程嵌入 `apply_operations()` 的写入后阶段,实时完成:
-
-**修正步骤:**
-
-```
-文件写入完成后,对该文件的所有 links(links + backlinks)执行修正:
- 1. 读取旧文件内容(_apply_upsert 前缓存的 old_memory_file_content)
- 2. 对每条链接的 t_line_ranges,提取原始段落文本
- - 解析 "3-5" → 读取旧文件第3~5行
- 3. 在新文件内容中定位该段落的新行号
- - 先用字符串精确查找(str.find())
- - 找不到 → 调 LLM 语义匹配重新定位
- - 还是找不到 → 删除该链接(从两端 `MEMORY_FIELDS` 同时清除)
- 4. 双向一致性:修正/删除操作同时作用于两端 `MEMORY_FIELDS`(从 links 删除 = 从对端 backlinks 删除)
-```
-
-**查找规则:**
-- 对 `t_line_ranges` 中的每个连续段落(如 "3-5,8-10" 有两个段落),独立查找
-- 段落文本 trim 后在新文件中 `str.find()`,匹配第一次出现
-- 多个段落都找到则合并为新 ranges(如 "4-6,9-11"),任一找不到则走 LLM 语义匹配
-- LLM 语义匹配仍找不到 → 从两端 `MEMORY_FIELDS` 删除该链接
-
-#### 3.2.7 链接类型与使用
-
-##### 3.2.7.1 类型定义
-
-```python
-class LinkType(str, Enum):
- RELATED_TO = "related_to" # 一般关联
- BELONGS_TO = "belongs_to" # 归属关系
- CAUSED_BY = "caused_by" # 因果关系
- DERIVED_FROM = "derived_from" # 派生关系(从已有记忆推导出的合成产物)
- CONTRADICTS = "contradicts" # 矛盾关系
- EVOLVED_FROM = "evolved_from" # 演变关系(知识/观点随时间迭代)
-```
-
-- LLM 只输出这 6 种类型,系统不生成额外反向类型
-- `link_type` 始终从 from 视角定义(如 `A CAUSED_BY B` = A 被 B 导致)
-- 遍历 `backlinks` 时,当前文件是 to 端,通过 `(link_type, links/backlinks)` 组合解读反链语义(如当前文件是 to 端的 `CAUSED_BY` = 当前文件是原因)
-
-##### 3.2.7.2 行为分层
-
-按系统行为影响划分,不是按语义:
-
-**信号型**(触发整理主题发现的独立代码分支):
-
-| link_type | links 语义 | backlinks 语义 | 整理行为 |
-|---|---|---|---|
-| CONTRADICTS | 我与 to 矛盾 | from 与我矛盾 | 冲突信号 → 生成冲突报告 |
-| DERIVED_FROM | 我从 to 派生 | from 从我派生 | 源更新 → 检查源记忆是否更新,触发重研 |
-| EVOLVED_FROM | 我从 to 演进 | from 从我演进 | 版本过时 → 旧版本被替代,触发更新 |
-
-**结构型**(影响 PPR 遍历策略,算法统一,不需要独立代码分支):
-
-| link_type | links 语义 | backlinks 语义 |
-|---|---|---|
-| BELONGS_TO | 我属于 to(追上下文) | from 属于我(追细节) |
-| CAUSED_BY | 我由 to 导致(追根因) | 我导致了 from(找影响范围) |
-
-**兜底型**(无特殊行为):RELATED_TO,1 跳即止。
-
-##### 3.2.7.3 各模块使用
-
-**PPR**:统一配置表驱动,按 `(link_type, links/backlinks)` 组合查询权重、是否继续、最大深度。不需要为每种类型写不同的遍历逻辑。
-
-**Prefetch**:消费 PPR 结果排序 + CONTRADICTS 强制包含(确保矛盾信息不遗漏)。
-
-**在线检索**:1 跳扩展,仅对 CONTRADICTS / EVOLVED_FROM 强制跟随(毫秒级 budget,不做多跳)。
-
-**整理主题发现**:3 种信号型各有独立逻辑:
-- CONTRADICTS → 沿边找冲突,生成冲突报告候选主题
-- DERIVED_FROM + backlinks → 已有报告的源记忆是否更新,决定重新研究
-- EVOLVED_FROM + backlinks → 旧版本是否被新记忆替代,决定更新报告
-
-##### 3.2.7.4 PPR 配置表 (# TODO 这一章挪到ppr实现那边讲吧)
-
-| (link_type, links/backlinks) | 传播权重 | 是否继续 | 最大深度 | 说明 |
-|---|---|---|---|---|
-| (CONTRADICTS, links) | 0.8 | 否 | 1 | 直接矛盾,必须跟随 |
-| (CONTRADICTS, backlinks) | 0.8 | 否 | 1 | 对称 |
-| (BELONGS_TO, links) | 0.7 | 是 | 3 | 追上下文,传递 |
-| (BELONGS_TO, backlinks) | 0.7 | 是 | 3 | 追细节,传递 |
-| (CAUSED_BY, links) | 0.5 | 是 | 2 | 追根因,链式衰减 |
-| (CAUSED_BY, backlinks) | 0.3 | 否 | 1 | 找影响范围,不扩散 |
-| (DERIVED_FROM, links) | 0.2 | 否 | 1 | 溯源,低权重 |
-| (DERIVED_FROM, backlinks) | 0.6 | 否 | 1 | 合成产物,中权重 |
-| (EVOLVED_FROM, links) | 0.3 | 否 | 1 | 新→旧,一般不需要 |
-| (EVOLVED_FROM, backlinks) | 0.9 | 是 | 5 | 旧→新,找最新版本 |
-| (RELATED_TO, links) | 0.4 | 否 | 1 | 1跳即止 |
-| (RELATED_TO, backlinks) | 0.4 | 否 | 1 | 1跳即止 |
-
-### 3.3 Schema 扩展
-
-#### 3.3.1 MemoryTypeSchema 扩展
-
-```python
-class MemoryTypeSchema(BaseModel):
- # ... 现有字段不变 ...
-
- # 新增链接字段
- link_enabled: bool = Field(True, description="Whether linking is active for this type")
-```
-
-- `link_enabled: true` 时,该记忆类型参与链接
-- 链接天然双向,resolve_operations 时自动分发到两端文件,无需额外配置
-
-#### 3.3.2 YAML 扩展
-
-现有 YAML 文件无需改动(默认启用)。如需禁用链接能力:
-
-```yaml
-memory_type: some_type
-link_enabled: false
-```
-
-#### 3.3.3 链接字段注入方式
-
-links 不作为 MemoryField 注入到每个记忆类型的 schema 中,而是作为 `StructuredMemoryOperations` 的独立顶层字段 `links: List[WikiLink]`。同时在每个记忆类型的 flat data model 中注入 `page_id: int` 字段(从 100 开始自增)。
-
-### 3.4 链接生成流程
-
-#### 3.4.1 Session.commit 实时整理
-
-```
-Prefetch 阶段:
- ls/search/read 已有文件 → PageIdMap 分配 page_id (1~99)
- 已有页面的 links 读入 LLM 上下文,避免重复建链
- ↓
-ExtractLoop:
- LLM 上下文中用 [page:N] 引用已有文件
- LLM 输出记忆操作(每项带 page_id 从 100 起)+ 统一 links
- ↓
-resolve_operations():
- f page_id → PageIdMap.get_uri() 或 ResolvedOperations[idx].uri → f_uri
- t page_id → 同上 → t_uri
- t_field + t_line_ranges → 从目标文件计算实际行号范围和字符数
- 将链接分发到 endpoint 记忆文件的 MEMORY_FIELDS:
- - from 文件 → MEMORY_FIELDS.links
- - to 文件 → MEMORY_FIELDS.backlinks
- ↓
-MemoryUpdater.apply_operations():
- ├─ _apply_upsert(): 写入记忆文件(content 纯净,links/backlinks 在 MEMORY_FIELDS 中)
- │ - from 文件的 MEMORY_FIELDS.links 包含以该文件为 from 的链接
- │ - to 文件的 MEMORY_FIELDS.backlinks 包含以该文件为 to 的反向链接
- ├─ t_line_ranges 行号修正(3.6 节,精确匹配 + LLM 语义匹配)
- └─ 链接双向一致性保证
-```
-
-**链接场景**:
-
-| 场景 | from | to | 示例 |
-|------|------|----|------|
-| 新记忆 → 已有页面 | page_id (100+) | page_id (1~99) | 新偏好 → 已有 profile |
-| 新记忆 → 新记忆 | page_id (100+) | page_id (100+) | 新 event → 新 preference |
-| 已有页面 → 新记忆 | page_id (1~99) | page_id (100+) | 已有 profile → 新偏好 |
-
-所有链接天然双向,一条 WikiLink 同时写入 from 端的 `links` 和 to 端的 `backlinks`,两侧记录内容完全相同。
-
-**死链不可能存在**:page_id 只在 ExtractLoop 上下文中产生,对应文件一定存在(已有文件已读入,新建文件即将写入)。
-
-**一趟写入策略:**
-- `resolve_operations()` 阶段将链接分发:from 端链接写入 from 文件的 `MEMORY_FIELDS.links`,to 端反向链接写入 to 文件的 `MEMORY_FIELDS.backlinks`
-- `MemoryUpdater` 内部通过 `memory/merge_op/link_merge.py` 与已有链接合并
-- 无需写入后额外 read → merge → write,一趟完成
-
-#### 3.4.2 外部 Bot T+1 触发整理
-
-整理是通用框架:从已有记忆中发现问题(主题),基于已注册的 memory_type schema 生成报告。用户通过 YAML 配置 dream_task,不写死产出什么。
-
-**框架流程:**
-
-```
-外部 Bot T+1 触发(如次日由外部 Bot 调用)
- ↓
-Step 1: 主题发现
- 输入:当天新增/修改的记忆文件 + 已有的 report 列表
- 输出:新主题列表(question)+ 需更新的已有 report URI 列表
- ↓
-Step 2: 逐主题生成
- 对每个主题:
- 整理 ContextProvider 读取该主题相关文件 → ExtractLoop 调 LLM 按 schema 输出 → MemoryUpdater 写入
-```
-
-**主题发现的输入:**
-
-| 数据 | 说明 | 获取方式 |
-|------|------|---------|
-| 当天新增/修改的记忆文件 | 增量,不是全量 | 按时间筛选 VikingFS 文件 |
-| 当天新文件的 links | 新文件关联了谁 | deserialize_metadata() 提取 |
-| 已有 report 列表 | 避免重复 + 决定哪些需更新 | 按 memory_type=report 搜索 |
-| report_candidate 列表 | 用户主动提出的主题 | 按 memory_type=report_candidate 搜索 |
-
-**主题发现的逻辑:**
-- 新记忆没有关联到已有 report → 可能是新主题
-- 新记忆关联到已有 report 的 source_uris → 该 report 需要更新(新信息补充)
-- 新记忆之间存在 CONTRADICTS 链接 → 冲突主题
-- 用户提交的 report_candidate → 直接作为主题候选(用户主动提出的主题优先)
-
-**report_candidate:** 用户在对话中主动提出"帮我研究 X"时,实时阶段提取为 report_candidate 写入。外部 Bot T+1 整理消费后生成对应 report 时,该 candidate 标记为已处理。
-
-```yaml
-memory_type: report_candidate
-fields:
- - name: question
- field_type: string
- merge_op: patch
- - name: user_requirement
- field_type: string
- merge_op: patch
- - name: created_at
- field_type: string
- merge_op: patch
- - name: status
- field_type: string
- merge_op: patch
-```
-
-**复用实时阶段组件:**
-
-| 外部 Bot T+1 整理 | 实时阶段 |
-|-------|---------|
-| 整理 ContextProvider(按主题选文件) | SessionContextProvider(按对话 prefetch) |
-| ExtractLoop(调 LLM 按 schema 输出) | ExtractLoop(同样) |
-| MemoryUpdater.apply_operations(写入) | MemoryUpdater.apply_operations(同样) |
-
-核心区别只在 ContextProvider 的输入选择策略不同。
-
-**整理 ContextProvider 流程(Step 2 逐主题生成时):**
-
-```
-1. 按主题读取相关文件
- - memory_type 锚点:找指定类型(entity/preferences/events 等)的所有文件,沿 links 入边收集 1-hop 邻居
- - conflict:检测有 CONTRADICTS 链接的文件对
-
-2. 读取每组文件的内容
- - VikingFS.read_file() 读每个 URI 的内容,并从 `MEMORY_FIELDS` 解析 links/backlinks
- - 从 links 过滤组内链接
-
-3. 读已有同类 report
- - 按 memory_type=report 搜索已有报告
- - 相关 report 读入 LLM 上下文,避免重复产出
-
-4. 组装 LLM 输入
- - 文件正文(plain_content)
- - 组内 links(关系结构,特别是 CONTRADICTS / EVOLVED_FROM)
- - 已有相关 report
- - output memory_type 的 schema 定义
-
-5. LLM 产出 0~N 个 report(无值得研究的问题则跳过)
-```
-
-**配置示例:**
-
-```yaml
-dream_tasks:
- - input:
- source: entity
- scope: 1-hop-neighbors
- output:
- memory_type: report
- - input:
- source: conflict
- output:
- memory_type: report
-```
-
-**report schema 定义:**
-
-```yaml
-memory_type: report
-fields:
- - name: question
- field_type: string
- merge_op: patch
- - name: answer
- field_type: string
- merge_op: patch
- - name: source_uris
- field_type: list
- merge_op: sum
- - name: conflicts
- field_type: list
- merge_op: sum
- - name: created_at
- field_type: string
- merge_op: patch
-content_template: |
- # {{question}}
-
- > 产出时间: {{created_at}}
-
- {{answer}}
-
- ## 依据
-
- {% for uri in source_uris %}
- - [{{uri|filename}}]({{uri|relative_path}})
- {% endfor %}
-
- {% if conflicts %}
- ## 矛盾
-
- {% for c in conflicts %}
- - {{c}}
- {% endfor %}
- {% endif %}
-```
-
-**实时阶段已保证:** 死链不存在(PageIdMap)、双向链接强制分发,外部 Bot T+1 整理无需做全局健康检查。
-
-### 3.5 链接消费
-
-#### 3.5.1 PPR 搜索增强
-
-基于 Personalized PageRank (PPR) 算法,利用 links 数据增强检索。PPR 从种子文件出发沿 links 做带权随机游走,分数随传播衰减,实现 query 相关的图增强检索。
-
-**算法核心:**
-
-```
-Phase 1: 种子获取
- 向量搜索 + 关键词搜索 → 融合排序 → top-K 文件作为 seed set
- 每个 seed 有 base_score(搜索排序分数)
-
-Phase 2: PPR 传播
- 以 seed set 为 preference nodes,沿 links 和 backlinks 做带权随机游走
- - 每步传播分数 × damping_factor (默认 0.85)
- - 传播策略按 (link_type, links/backlinks) 查 3.2.7.4 配置表决定权重、是否继续、最大深度
- - link_weight 低于阈值(如 0.3)的边跳过,控制扩展量
-
-Phase 3: 分数合并
- 对每个文件:
- - 在 seed 中: final_score = α × base_score + (1-α) × ppr_score
- - 不在 seed 中: final_score = ppr_score
- - ppr_score 低于阈值(如 0.05)的补充文件丢弃
-
-Phase 4: 返回
- 合并 seed + 补充文件,按 final_score 降序返回
-```
-
-**参数:**
-
-| 参数 | 默认值 | 说明 |
-|------|--------|------|
-| α | 0.7 | 搜索分数权重,PPR 定位为补充而非主导 |
-| damping_factor | 0.85 | PPR 衰减因子,每跳分数 × 0.85 |
-| depth | 1 | 传播深度,1 跳已足够(2 跳仅搜索质量差时启用) |
-| min_link_weight | 0.3 | 传播时跳过低权重边 |
-| min_ppr_score | 0.05 | 补充文件的最低分数阈值 |
-
-**计算成本:** 纯数值计算,不需要 LLM 或 embed。假设 top-K=10,每文件平均 5 条 links,一跳扩展最多 50 个文件。瓶颈仅在文件 I/O(读取 endpoint 记忆文件的 `MEMORY_FIELDS` links/backlinks),计算本身毫秒级。
-
-##### 3.5.1.1 在线检索增强
-
-搜索 API 的后处理层,补充召回 + 重排序。
-
-**场景:** 用户主动搜索记忆(如搜"Caroline 的代码风格"),返回结果可能遗漏关联文件。
-
-**流程:** 向量+关键词搜索返回 seed → PPR 传播 → 补充召回向量未命中但图上强关联的文件 → 重排序返回。
-
-**举例:**
-
-```
-seed = {code_review.md(0.8), Python_style.md(0.7)}
-
-PPR 传播 (damping=0.85, 按 3.2.7.4 配置表):
- code_review.md →[belongs_to, links, w=0.7]→ caroline.md
- Python_style.md →[evolved_from, links, w=0.3]→ old_style.md
-
-结果:
- caroline.md: 0.7×0.85 = 0.60 (补充召回,向量未命中)
- old_style.md: 0.3×0.85 = 0.26 (低于 min_ppr_score,丢弃)
-
-返回 [code_review.md, Python_style.md, caroline.md]
- caroline.md 是向量未命中但 PPR 补充召回的高关联文件
-```
-
-**特点:** 单次短 query,seed 通常 1~3 个,PPR 传播量小,补充召回为主。
-
-##### 3.5.1.2 记忆提取 Prefetch 扩展
-
-ExtractLoop 的 prefetch 阶段,将 PPR 高分文件主动读入 LLM 上下文。
-
-**场景:** session.commit 时 prefetch 已有记忆。query 是完整对话,向量搜索可能返回多个不相关的种子文件。
-
-**多种子桥接:** prefetch 的 query 是完整对话,向量搜索可能返回多个不同主题的种子。PPR 在多种子同时传播时,桥接文件会获得多个种子的分数叠加,自然浮出——这是单种子场景无法发现的价值。
-
-```
-对话涉及 "Caroline" 和 "Go 语言兴趣"
-
-向量搜索 seed:
- seed1: entities/caroline.md (命中"Caroline")
- seed2: preferences/go_interest.md (命中"Go语言")
-
-PPR 传播(多种子叠加,按 3.2.7.4 配置表):
- caroline.md →[belongs_to, links, w=0.7]→ Python_style.md: 0.7 × 0.85 = 0.60
- go_interest.md →[evolved_from, links, w=0.3]→ Python_style.md: 0.3 × 0.85 = 0.26
- Python_style.md 的 ppr_score = 0.60 + 0.26 = 0.86 ← 桥接文件,多种子叠加
-
- Python_style.md 连接了两个种子,向量搜索未命中(query 没提 Python),
- 但 PPR 多种子传播使其自动浮出
-```
-
-**特点:** 完整对话 query,seed 数量多(可能 5~10 个),多种子叠加是核心价值。PPR 高分的桥接文件读入 LLM 上下文,避免重复建链和遗漏关联。
-
-##### 3.5.1.3 外部 Bot T+1 整理阶段文件群选取
-
-外部 Bot T+1 整理阶段,PPR 用于整理 ContextProvider 的输入选择——从记忆图中定位枢纽文件,优先处理高链接密度的区域。
-
-**场景:** 整理 ContextProvider 按 memory_type 策略选取文件群时,全量遍历成本高。PPR 可以快速定位"枢纽区域"——哪些文件的入边邻居最多、权重最高。
-
-**流程:** 以某 memory_type 的所有文件为均匀种子 → PPR 传播 → 分数高的文件是图中的枢纽(多条链接汇聚)→ 对高分区文件及其入边邻居生成 report。
-
-**特点:** 均匀种子(所有目标类型文件等权),PPR 分数反映图的拓扑结构——链接越多、权重越高的文件分数越高,天然对应"值得研究的知识集群"。source 可以是任意已注册的 memory_type(entity、preferences、events 等),不限于 entity。
-
-### 3.6 与现有系统的集成点
-
-#### 3.6.1 修改清单
-
-| 模块 | 改动 |
-|------|------|
-| `dataclass.py` | `MemoryTypeSchema` 新增 `link_enabled`;新增 `WikiLink`, `StoredWikiLink`, `LinkType` 模型 |
-| `schema_model_generator.py` | `create_flat_data_model()` 中 link_enabled 时自动注入 `page_id` 字段 |
-| `memory_updater.py` | `apply_operations()` 中链接分发(from→links, to→backlinks 写入 `MEMORY_FIELDS`)+ 行号修正 |
-| `memory_type_registry.py` | `_parse_memory_type()` 解析 `link_enabled` 字段;支持 `dream_tasks` 配置 |
-| `resource_memory_link_service.py` | 基于资源引用维护 memory links/backlinks |
-| `tools.py` | 搜索 API 新增 PPR 后处理层(6.1.1);prefetch 扩展 PPR(6.1.2) |
-| `session/compressor_v3.py` | 通过共享 `MemoryUpdater` 应用并持久化 memory links |
-| `session/session.py` | `_run_memory_extraction()` 使用新 `link()` 签名 |
-| YAML templates | 新增 `report` + `report_candidate` memory_type 定义 + `dream_tasks` 配置;现有模板默认 link_enabled=true |
-| 新增模块 | `memory/dream_context_provider.py` — 整理上下文提供者;`utils/links_merge.py` — links/backlinks 合并逻辑;`retrieve/ppr.py` — PPR 算法 |
-
-#### 3.6.2 不改动的部分
-
-- `extract_loop.py` — LLM 自然输出 links 字段,不需要改 ReAct 循环逻辑
-- `session_extract_context_provider.py` — prefetch 基础逻辑不变,PPR 扩展作为后处理层叠加
-- `memory_isolation_handler.py` — 隔离逻辑不变,links 的 URI 遵循隔离规则
-- 现有 YAML 文件 — 不需修改,默认启用
-
-### 3.7 开放问题
-
-1. ~~**语义补充的向量计算成本**~~:已去掉 session.commit 时的语义补充和零 LLM 扫描,关联发现统一交给外部 Bot T+1 触发整理
-2. ~~**link_type 词汇表**~~:已确定为枚举,定义 6 种类型(related_to, belongs_to, caused_by, derived_from, contradicts, evolved_from)
-3. ~~**links 字段是否放入 LLM prompt**~~:已确认需要,prefetch 时将已有页面的 links 读入上下文,避免重复建链
-4. ~~**backlink 同步的并发安全**~~:已确认无并发问题——所有读取的文件都加锁,backlink 只对已读取的文件回链
-5. ~~**target_ranges 行号偏移**~~:实时阶段一步到位——精确匹配 + LLM 语义匹配 + 找不到则删除,无需 pending_repair
-6. ~~**Dream 具体产出**~~:Dream 为通用框架,产出 report memory_type 实例(问题驱动的报告),用户通过 YAML 配置 dream_task
-
-## 4. 竞品对比总结
-
-| 维度 | GBrain | OpenClaw | nashsu_llm_wiki | OpenViking(目标) |
-|------|--------|----------|-----------------|-------------------|
-| 输入源 | 对话 + Git 资源 | 对话 | 资源 | 对话 + 资源(待建) |
-| 页面写入 | LLM 直接写入 | 攒批提取(memory-core)+ 工具调用写入(memory-wiki) | 攒批提取(两步 LLM) | hook 攒批提取(session.commit)+ 资源目录提取(add-resource) |
-| 链接存储 | 数据库表(整数 ID 引用) | 页面 sourceIds + 编译计算 | 正文 [[wikilink]] | 文件元数据 JSON(VikingFS) |
-| 链接权重 | 无 | 无 | 无(4 信号加权替代) | 有(weight 字段) |
-| 链接精度 | 文件级 | 文件级 | 文件级 | 行号级(target_ranges) |
-| 链接类型 | 有(auto-link 推断标准类型 + LLM 填写自由文本) | 无(隐式 sourceIds) | 无(无类型,[[wikilink]] 平等) | 有(枚举约束) |
-| 自动链接 | 已实现(put_page auto-link post-hook + 类型推断级联) | 编译器全量计算(零 LLM) | 正文 [[wikilink]] 解析 | LLM 统一输出 |
-| 双向回链 | auto-link 自动建链 + check-backlinks 审计 | 编译时计算 | 无反向链接 | 自动生成反向链接 |
-| 定时整理 | Dream Cycle 6阶段维护管道(cron + skills) | Dreaming 三阶段 | 无 | 外部 Bot T+1 触发主题整合 |
-| 整理产物 | 维护产物(lint/backlinks/sync/extract/embed/orphans) | MEMORY.md + 重编译关联 | 无 | 问题驱动的研究报告(外部 Bot T+1 触发) |
-| 搜索 | 向量+关键词+RRF+多查询扩展+backlink boost | 混合搜索 + 多样性重排 | 分词+向量 → RRF 融合 → 图扩展 | 向量+关键词 + PPR 图增强 |
-| 链接参与检索 | Backlink boost(简单排序加分,非图传播) | 编译产物参与搜索 | 4 信号图扩展参与排序 | PPR 图增强,链接直接参与检索排序 |
-| 知识可信度 | 无 | Claims + 矛盾检测 + 新鲜度评估 | Lint 检查(结构+语义) | links 已覆盖矛盾/演变/权重/溯源,不引入独立 claims 层 |
-
-**OpenViking 的差异化:**
-- 唯一支持链接权重(weight),支持更精细的关联强度
-- 唯一支持行号级链接精度(target_ranges),检索时可只读目标行范围,减少 token 消耗
-- 唯一支持 hook 攒批提取 + 资源目录提取双模式在线写入
-- 唯一支持链接类型枚举约束(GBrain link_type 为自由文本,LLM 手动填写可能产生同义歧义如 knows vs familiar_with)
-- 唯一支持 PPR 图增强检索(GBrain backlink boost 是简单排序加分,不做图传播;nashsu_llm_wiki 4 信号图扩展权重硬编码)
-- 唯一支持外部 Bot T+1 触发主题整合(GBrain Dream Cycle 是纯维护管道不做知识整合;nashsu_llm_wiki 无定时整理)
-
-**核心差异:**
-
-| | GBrain | OpenClaw | nashsu_llm_wiki | OpenViking |
-|---|---|---|---|---|
-| 在线写入 | put_page + auto-link post-hook(零 LLM) + LLM 调 add_link | 攒批提取 + 工具调用写入,编译器全量计算关系 | 攒批提取(两步 LLM),链接写正文 | hook 攒批提取(session.commit)+ 资源目录提取(add-resource),LLM 统一输出记忆 + links |
-| 离线整理 | Dream Cycle(cron + skills)6阶段维护管道 | Dreaming 三阶段提升 + 关键词频率标记主题 | 无 | 外部 Bot T+1 触发主题整合,从已有记忆生成 report |
-| 自动建链 | put_page auto-link post-hook(零 LLM) + extract links 批量回填 | 编译器全量计算 | 正文 [[wikilink]] 解析 | 不自动建链,靠 LLM 输出 + 外部 Bot T+1 整理补充 |
-| 链接参与检索 | Backlink boost(简单排序加分,非图传播) | 编译产物参与搜索 | 4 信号图扩展参与排序 | PPR 图增强,链接直接参与检索排序 |
diff --git a/docs/design/metric-design.md b/docs/design/metric-design.md
deleted file mode 100644
index 46471c7e7..000000000
--- a/docs/design/metric-design.md
+++ /dev/null
@@ -1,923 +0,0 @@
-# OpenViking 指标体系设计方案
-
-## 背景
-
-本方案讨论的是 OpenViking 的“指标体系(metrics)”,目标是把 `/metrics` 做成一个可持续抓取的 Prometheus 导出端点,并与 `/api/v1/observer/*`(瞬时状态)和 `/api/v1/stats/*`(分析统计)形成清晰边界。
-
-### 现状入口与实现特征
-
-OpenViking 当前已经存在三类与“观测”相关的入口:
-
-| 入口 | 当前定位 | 当前实现特征 |
-| --- | --- | --- |
-| `/api/v1/observer/*` | 组件瞬时状态查询 | `ObserverService` 组装 queue/vikingdb/models/lock/retrieval 状态 |
-| `/api/v1/stats/*` | 业务统计与内容质量分析 | `StatsAggregator` 动态查询 memory 分类、热度、陈旧度、session extraction 等 |
-| `/metrics` | Prometheus 指标导出 | 当前依赖 `PrometheusObserver.render_metrics()` 输出文本 |
-
-结合代码现状可以归纳出关键事实:
-
-| 模块 | 位置 | 当前职责 | 问题摘要 |
-| --- | --- | --- | --- |
-| `BaseObserver` | `openviking/storage/observers/base_observer.py` | `get_status_table/is_healthy/has_errors` | 瞬时状态语义清晰 |
-| `PrometheusObserver` | `openviking/storage/observers/prometheus_observer.py` | 进程内存储 Counter/Histogram + 渲染 `/metrics` | 与 Observer 体系职责不一致,属于“异类” |
-| 业务埋点(retrieval/embedding/vlm 等) | 多处 | 直接回调 observer 写指标 | 采集层与导出层强耦合,难扩展/难测试 |
-| `/metrics` 路由 | `openviking/server/routers/metrics.py` | 直接取 `app.state.prometheus_observer` | 路由层绑定具体实现对象,而非 exporter 抽象 |
-
-当前 `/metrics` 已打通的指标主要集中在 retrieval/embedding/vlm/cache 的少量 counter/histogram 指标族,覆盖面偏窄。
-
-### 关键问题
-
-- `PrometheusObserver` 破坏 Observer 一致性:它本质是“注册中心 + 导出器”混合体,而非瞬时状态读取器。
-- 采集与导出强耦合:业务代码需要感知 Prometheus 是否启用,未来接入其他 exporter 会反向侵入业务埋点。
-- 指标类型与语义不完整:缺 gauge/health、缺统一命名与标签边界,难扩展到 queue/task/lock/vikingdb 等运行态。
-- 多租户可观测性不足但风险高:缺 `account_id` 切片能力,同时必须防止演化为高基数(user/session/resource 等维度严禁进入 `/metrics`)。
-- `/metrics` 与 `/api/v1/stats` 易混淆:分析型统计不应迁入高频抓取的 Prometheus 模型。
-
-### 设计目标与非目标
-
-设计目标:
-
-1. 让 `Observer` 回归“瞬时状态观测”本位。
-2. 建立独立 metrics 核心层:采集(DataSource)/语义分流(Collector)/存储(Registry)/导出(Exporter)解耦。
-3. 把零散埋点统一接入同一套事件与状态契约(Event/State/DomainStats/Probe)。
-4. 为 `/metrics` 提供系统化的 Gauge / Counter / Histogram,并明确失败语义(best-effort、valid/stale)。
-5. 明确 `/metrics` 与 `/api/v1/stats` 边界,避免抓取放大成本。
-
-非目标:
-
-- 不重写现有 operation telemetry 响应结构。
-- 不要求把所有业务统计都变为 Prometheus 指标。
-- 不引入分布式聚合层,也不解决跨进程汇总问题。
-- 首版不强制落地 OTel exporter。
-
-## 1. 架构概览
-
-### 1.1 核心原则
-
-本节明确指标体系设计中需要持续成立的几项基础原则。这些原则用于约束后续的抽象分层、模块边界、Telemetry 关系以及对外观测接口的职责划分。
-
-#### 原则 A:先抽象职责,再落实现类型
-
-概览层保留以下四个核心抽象:
-
-- `MetricDataSource`
-- `BaseMetricCollector`
-- `MetricRegistry`
-- `BaseMetricExporter`
-
-#### 原则 B:数据源与指标体系解耦
-
-现有 Observer、Telemetry、TaskTracker、业务事件埋点,本质上都属于“数据来源”,但不等同于指标系统本身。
-
-因此:
-
-- 数据源负责提供原始状态或原始事件;
-- Collector 负责把这些原始语义转换为指标;
-- Registry 负责保存指标;
-- Exporter 负责把指标转换为外部协议。
-
-这种拆分可以避免 retrieval、embedding、vlm 等业务代码直接耦合某一个 exporter。
-
-#### 原则 C:Registry 是唯一真实指标存储
-
-`MetricRegistry` 作为进程内指标的唯一真实来源,负责承接统一的读写与约束。
-
-职责范围如下:
-
-- 指标定义注册;
-- 标签规范校验;
-- 当前值读写;
-- 并发安全;
-- 向 exporter 提供可读取的当前视图。
-
-注意:这里的“当前视图”仅指读取时获取 registry 内部状态,不引入独立的 Snapshot 架构层。
-
-#### 原则 D:Exporter 只负责协议导出
-
-Exporter 只负责协议导出,不负责指标语义生成。
-
-Exporter 不负责:
-
-- 业务埋点;
-- 状态采集;
-- 指标语义转换。
-
-Exporter 只负责:
-
-- 读取 registry;
-- 根据目标协议格式化;
-- 输出给 `/metrics` 或其他监控后端。
-
-这意味着 Prometheus 只是首个落地实现,而不是整个 metrics 架构的中心。
-
-#### 原则 E:保留三类观测入口的职责边界
-
-`/metrics`、`/api/v1/observer/*`、`/api/v1/stats/*` 三类入口继续并存,但必须保持清晰分工。
-
-- `/metrics` 面向机器抓取,强调低基数、低成本、可持续聚合;
-- `/api/v1/observer/*` 面向人工诊断,强调瞬时状态可读性;
-- `/api/v1/stats/*` 面向业务分析,允许更重的查询与统计逻辑。
-
-这三个入口共享部分数据来源,但不共享同一种输出模型。
-
-### 1.2 抽象分层设计
-
-本节给出指标体系的抽象主链路,只保留最小且稳定的四类角色,不提前展开任何具体实现类。
-
-抽象主链路如下:
-
-```mermaid
-graph LR
- A["MetricDataSource"]
- B["BaseMetricCollector"]
- C["MetricRegistry"]
- D["BaseMetricExporter"]
-
- A --> B
- B --> C
- C --> D
-```
-
-四类抽象角色的职责如下:
-
-| 抽象角色 | 作用 | 只负责什么 | 不负责什么 |
-| --- | --- | --- | --- |
-| `MetricDataSource` | 提供原始状态或原始事件 | 产生可观测输入 | 不直接生成 Prometheus 文本 |
-| `BaseMetricCollector` | 将输入转为统一指标语义 | 采集、归一化、写 registry | 不直接暴露 HTTP |
-| `MetricRegistry` | 统一存储进程内指标 | 注册、校验、读写、并发控制 | 不关心数据源来自哪里 |
-| `BaseMetricExporter` | 按协议导出指标 | 格式化与导出 | 不直接理解业务链路语义 |
-
-抽象主链路对应的数据流顺序如下:
-
-1. `MetricDataSource` 提供瞬时状态、请求结束摘要或运行时事件;
-2. `BaseMetricCollector` 将这些输入映射为 Counter / Gauge / Histogram 等统一指标;
-3. `MetricRegistry` 保存当前进程内全部指标状态;
-4. `BaseMetricExporter` 在需要时读取 registry 并输出给外部系统。
-
-### 1.3 设计边界
-
-抽象分层确定之后,还需要从设计边界上进一步保证:
-
-* 指标体系可以观测业务主链路,但不成为业务主链路的组成部分;
-* 指标链路可以缺失或降级,但不能反向改变 retrieval、embedding、VLM、resource、session、task 与 observer 等核心功能的行为语义。
-
-因此,需要对相应角色施加明确约束:
-
-* **DataSource**:业务接触面收敛到 DataSource。业务对象、业务状态、业务事件、已有统计快照与探针执行结果,只允许由 `MetricDataSource` 接触和读取。`Collector`、`MetricRegistry`、`Exporter` 不再直接访问业务服务、业务存储或业务上下文。
-* **Collector**:Collector 禁止重新参与业务流程。Collector 的职责仅为把标准化输入映射为指标语义,并写入 `MetricRegistry`,不拥有业务真实状态。
- * 事件类(如 HTTP API 调用)链路由业务事件发生点触发,DataSource 到 Collector 之间只传递轻量事件;
- * 状态类(如系统状态)链路由采集时机触发,例如 `/metrics` 抓取前刷新,对应读取只能是轻量快照、已有聚合结果或轻量探针结果。
-
-### 1.4 目录与模块边界
-
-在边界约束成立之后,模块划分也需要与之保持一致,避免目录结构重新把已经划清的职责边界混回同一层。为避免新指标体系继续与 `storage/observers/` 的职责混杂,集中放入 `openviking/metrics/`,并按“注册中心 / 采集器 / 导出器 / 规则 / 启动装配”进行分组。
-
-逻辑分组如下:
-
-| 模块分组 | 职责 |
-| --- | --- |
-| `registry` | 指标存储、指标定义、标签校验 |
-| `collectors` | retrieval / embedding / vlm / queue / task / observer / telemetry 等采集器 |
-| `exporters` | Prometheus / 未来 OTel / InfluxDB |
-| `naming` | 指标命名规则、label 规则、bucket 约定 |
-| `bootstrap` | app 启动时初始化 registry / exporters / collector manager |
-
-### 1.5 与现有 telemetry 的关系
-
-operation telemetry 与 metrics 并不是两套彼此替代的系统。前者继续作为请求级结构化摘要存在,服务于单次调用的解释与排障;后者则只对白名单字段做低基数抽取,用于持续抓取、聚合与告警。
-
-operation telemetry 已经拥有很多有价值的数据字段,如:
-
-- `duration_ms`
-- `tokens.*`
-- `vector.*`
-- `queue.*`
-- `semantic_nodes.*`
-- `memory.extract.*`
-- `errors.*`
-
-但并非所有字段都适合直接进入 `/metrics`,因此这里只对白名单字段进行指标化抽取:
-
-| telemetry 分组 | 是否指标化 | 原因 |
-| --- | --- | --- |
-| `duration_ms` | 是 | 低基数、高通用性 |
-| `tokens.total / llm / embedding` | 是 | 有明确容量与成本价值 |
-| `vector.searches / scored / returned` | 是 | 检索链路核心运行指标 |
-| `queue.*` | 是 | 适合形成任务吞吐与错误指标 |
-| `semantic_nodes.*` | 有条件 | 更适合资源导入链路,不应无限扩散标签 |
-| `memory.extract.*` | 部分保留在 stats / telemetry | 更偏业务分析,首版不全面指标化 |
-| `errors.message` | 否 | 高基数、可能泄漏上下文 |
-
-### 1.6 `/metrics`、`/api/v1/observer`、`/api/v1/stats` 的职责边界
-
-三类对外观测接口共享部分数据来源,但并不共享同一种输出模型,也不应追求由同一套接口承担全部观测需求。明确这一边界,是为了避免后续设计在机器抓取、人工诊断与业务分析之间发生职责漂移。
-
-| 接口 | 定位 | 数据特征 | 输出风格 |
-| --- | --- | --- | --- |
-| `/metrics` | 机器消费型监控接口 | 低基数、可持续抓取、可聚合 | Prometheus exposition |
-| `/api/v1/observer/*` | 人工诊断型瞬时状态接口 | 组件当前状态、表格或结构化描述 | JSON + 可读状态文本 |
-| `/api/v1/stats/*` | 业务分析型接口 | 可能昂贵、可扫描、可聚合但非高频 | JSON 统计结果 |
-
-## 2. 核心设计细节
-
-### 2.1 `MetricDataSource` 设计
-
-在实现层,抽象角色 `MetricDataSource` 统一落为基类 `BaseMetricDataSource`,并在其下进一步划分 `EventMetricDataSource`、`StateMetricDataSource`、`DomainStatsMetricDataSource`、`ProbeMetricDataSource` 四类中间抽象。这四类中间抽象并非单纯的逻辑标签,而是分别对应不同的数据访问契约与刷新方式,因此在架构层被明确区分。
-
-这些输入可能是:
-
-- 某个组件的瞬时状态;
-- 某个运行时事件;
-- 某个领域内部维护的累计统计;
-- 某个探针执行结果。
-
-在 OpenViking 中,`MetricDataSource` 采用“统一基类 + 中间契约层 + 具体实现类”的三层结构。具体继承关系如下:
-
-```mermaid
-graph LR
- A["BaseMetricDataSource"]
-
- B["EventMetricDataSource"]
- C["StateMetricDataSource"]
- D["DomainStatsMetricDataSource"]
- E["ProbeMetricDataSource"]
-
- F["HttpRequestLifecycleDataSource"]
- G["ResourceIngestionEventDataSource"]
- H["SessionLifecycleDataSource"]
- O["EncryptionEventDataSource"]
-
- I["QueuePipelineStateDataSource"]
- J["TaskStateDataSource"]
-
- K["RetrievalStatsDataSource"]
- L["ModelUsageDataSource"]
- M["ObserverStateDataSource"]
-
- N["ServiceProbeDataSource"]
- P["StorageProbeDataSource"]
- Q["RetrievalBackendProbeDataSource"]
- R["ModelProviderProbeDataSource"]
- S["AsyncSystemProbeDataSource"]
- T["EncryptionProbeDataSource"]
-
- A --> B
- A --> C
- A --> D
- A --> E
-
- B --> F
- B --> G
- B --> H
- B --> O
-
- C --> I
- C --> J
-
- D --> K
- D --> L
- D --> M
-
- E --> N
- E --> P
- E --> Q
- E --> R
- E --> S
- E --> T
-```
-
-这四类中间抽象对应的数据访问契约如下:
-
-| 中间抽象 | 契约语义 | 典型读取方式 | 典型指标类型 |
-| --- | --- | --- | --- |
-| `EventMetricDataSource` | 提供增量事件流或生命周期事件 | 读取事件批次、消费新事件、按游标增量拉取 | Counter、Histogram |
-| `StateMetricDataSource` | 提供当前状态快照 | 按需读取当前状态、重复读取返回最新值 | Gauge |
-| `DomainStatsMetricDataSource` | 提供领域内部已经维护好的累计统计 | 读取累计计数、汇总结果、统计快照 | Counter、Gauge、部分 Histogram 输入 |
-| `ProbeMetricDataSource` | 提供探针执行结果或健康检查结果 | 执行探测、读取最近一次探测结果 | Gauge、Health |
-
-各类具体数据源的职责如下:
-
-| 实现 | 分类 | 主要对接对象 | 输出形态 | 适用场景 |
-| --- | --- | --- | --- | --- |
-| `HttpRequestLifecycleDataSource` | `EventMetricDataSource` | FastAPI middleware、路由响应 | 请求生命周期事件 | request total、duration、status code、in-flight |
-| `ResourceIngestionEventDataSource` | `EventMetricDataSource` | ResourceProcessor、ResourceService、watch / wait 流程 | 资源处理事件与阶段摘要 | parse / finalize / summarize / wait / watch duration |
-| `SessionLifecycleDataSource` | `EventMetricDataSource` | session create / commit / archive | 会话生命周期状态与事件 | commit 生命周期、archive 状态 |
-| `EncryptionEventDataSource` | `EventMetricDataSource` | Encryptor、API Key 验证路径、KDF / Key Loader | 加密操作事件与密钥处理事件 | encrypt / decrypt / verify count、duration、bytes、kdf / key_load 耗时、auth_failed |
-| `QueuePipelineStateDataSource` | `StateMetricDataSource` | `QueueManager`、Semantic tree、request queue stats | 队列与流水线状态 | pending、in_progress、processed、error_count、semantic_nodes |
-| `TaskStateDataSource` | `StateMetricDataSource` | `TaskTracker` | 当前任务状态 | pending、running、completed、failed 数量 |
-| `RetrievalStatsDataSource` | `DomainStatsMetricDataSource` | `RetrievalStatsCollector` | 检索累计统计 | query count、zero result、latency、rerank 情况 |
-| `ModelUsageDataSource` | `DomainStatsMetricDataSource` | VLM / Embedding / Rerank token tracker | 模型使用统计 | 调用次数、耗时、token 消耗 |
-| `ObserverStateDataSource` | `DomainStatsMetricDataSource` | `ObserverService`、`LockManager`、`VikingDBManager` | 诊断聚合视图 | component health、lock、vikingdb、models、retrieval |
-| `ServiceProbeDataSource` | `ProbeMetricDataSource` | 服务初始化、组件装配状态 | 服务探针结果 | startup completion、service readiness |
-| `StorageProbeDataSource` | `ProbeMetricDataSource` | AGFS / VikingFS、系统表访问检查 | 存储探针结果 | storage readability、storage writability、system table readiness |
-| `RetrievalBackendProbeDataSource` | `ProbeMetricDataSource` | VikingDB、检索后端最小能力检查 | 检索后端探针结果 | backend readiness、collection availability |
-| `ModelProviderProbeDataSource` | `ProbeMetricDataSource` | VLM / Embedding / Rerank provider 可用性检查 | 模型依赖探针结果 | provider readiness、credential availability |
-| `AsyncSystemProbeDataSource` | `ProbeMetricDataSource` | Queue、默认 asyncio executor monitor | 异步系统探针与 executor 指标 | queue readiness、executor threads / tasks |
-| `EncryptionProbeDataSource` | `ProbeMetricDataSource` | Root Key、KMS / Vault Provider、加密组件检查 | 加密探针结果 | root key readiness、kms availability、encryption component health |
-
-设计边界如下:
-
-- 同一个业务模块可以暴露多个 DataSource,例如 session 相关能力既可以贡献 `SessionLifecycleDataSource`,也可能间接贡献 `TaskStateDataSource`。
-- 加密相关监控优先建模为 `EncryptionEventDataSource`;涉及 Root Key readiness、KMS / Vault Provider 可用性、加密组件健康度时,则由 `EncryptionProbeDataSource` 承接。
-- `SessionLifecycleDataSource` 只支持聚合级监控,不支持 `session_id` 级细粒度监控,也不允许把 `session_id` 作为指标标签。
-- `ObserverStateDataSource` 属于诊断视图适配结果,适合承接当前 Observer 体系的聚合输出,但不应继续向更高层堆叠新的 summary。
-- `operation telemetry` 属于请求级链路汇总能力,不作为一级 `MetricDataSource` 建模;如需复用其结果,应通过 collector 或兼容适配层接入。
-- memory health、category、staleness 等分析型统计继续通过 `/api/v1/stats` 暴露,不在本节中抽象为独立 DataSource。
-- `ProbeMetricDataSource` 采用方案 B:不再设置总的 `SystemProbeDataSource` 聚合父类,而是直接按依赖类型细分为 Service / Storage / Retrieval Backend / Model Provider / Async System / Encryption 六类 probe 子类。
-
-Observer、Telemetry、TaskTracker、HTTP Router 与各类业务服务继续保持原有职责;指标系统只把它们视为数据源,而不将其改造成 exporter 或 collector。
-
-### 2.2 `BaseMetricCollector` 设计
-
-Collector 位于指标体系中的语义转换层,负责接收不同类型的可观测输入,并将其稳定映射为对 `MetricRegistry` 的统一写入操作。随着 `MetricDataSource` 被进一步划分为 Event、State、DomainStats 与 Probe 四类,Collector 侧采用对应的分层组织,而不再停留在仅区分 Event / State 的简化模型。
-
-在这一设计下,Collector 不再只是“埋点写入器”,而是承担统一收口职责:一方面屏蔽上游数据源在访问方式与更新节奏上的差异,另一方面对下游 registry 暴露一致的写入语义。这样可以保证新增指标链路时,扩展点仍然集中在 Collector 层,而不会把 source-specific 逻辑扩散到 registry 或 exporter。
-
-Collector 采用“基类 + 四类子抽象 + 多个具体实现”的组织方式:
-
-```mermaid
-graph LR
- A["BaseMetricCollector"]
- B["EventMetricCollector"]
- C["StateMetricCollector"]
- D["DomainStatsMetricCollector"]
- E["ProbeMetricCollector"]
- F["RetrievalCollector(event)"]
- G["EmbeddingCollector"]
- H["VLMCollector"]
- I["CacheCollector"]
- J["EncryptionCollector"]
- K["QueueCollector"]
- L["RagfsMetricCollector"]
- M["VikingDBCollector"]
- N["ObserverHealthCollector"]
- O["TaskTrackerCollector"]
- P["RetrievalCollector(stats)"]
- Q["ModelUsageCollector"]
- R["ObserverStateCollector"]
- S["ServiceProbeCollector"]
- T["StorageProbeCollector"]
- U["RetrievalBackendProbeCollector"]
- V["ModelProviderProbeCollector"]
- W["AsyncSystemProbeCollector"]
- X["EncryptionProbeCollector"]
-
- A --> B
- A --> C
- A --> D
- A --> E
- B --> F
- B --> G
- B --> H
- B --> I
- B --> J
- C --> K
- D --> L
- C --> M
- C --> N
- C --> O
- D --> P
- D --> Q
- D --> R
- E --> S
- E --> T
- E --> U
- E --> V
- E --> W
- E --> X
-```
-
-抽象层次的分工如下:
-
-| 抽象层次 | 职责 | 典型触发方式 |
-| --- | --- | --- |
-| `BaseMetricCollector` | 定义 collector 统一行为与 registry 写入约束 | 所有 collector 共用 |
-| `EventMetricCollector` | 处理“事件发生一次,就写一次”的场景 | HTTP 请求完成、资源处理完成、VLM 调用完成、加密操作完成 |
-| `StateMetricCollector` | 处理“读取当前状态并刷新 gauge”的场景 | `/metrics` 抓取前刷新 |
-| `DomainStatsMetricCollector` | 处理“读取已有累计统计并写入 registry”的场景 | 检索统计、模型使用统计、Observer 聚合视图刷新 |
-| `ProbeMetricCollector` | 处理“执行探针并映射为健康类指标”的场景 | readiness / dependency probe 刷新 |
-
-Collector 与 DataSource 的主映射关系如下:
-
-| DataSource 分类 | 优先对应的 Collector 分类 | 说明 |
-| --- | --- | --- |
-| `EventMetricDataSource` | `EventMetricCollector` | 事件型输入天然适合 Counter / Histogram |
-| `StateMetricDataSource` | `StateMetricCollector` | 当前状态快照天然适合 Gauge |
-| `DomainStatsMetricDataSource` | `DomainStatsMetricCollector` | 已聚合统计应直接桥接到 registry |
-| `ProbeMetricDataSource` | `ProbeMetricCollector` | 健康检查结果应统一映射为 readiness / health 指标 |
-
-具体 collector 分工如下:
-
-| Collector | 分类 | 数据输入 | 写入指标 |
-| --- | --- | --- | --- |
-| `RetrievalCollector` | `EventMetricCollector` | retrieval 完成事件 | 请求数、零结果数、结果数、耗时、rerank 使用情况 |
-| `EmbeddingCollector` | `EventMetricCollector` | embedding 完成事件 | 请求数、耗时、错误数 |
-| `VLMCollector` | `EventMetricCollector` | token / duration 事件 | 调用数、耗时、token 统计 |
-| `CacheCollector` | `EventMetricCollector` | cache 命中或未命中事件 | hit / miss |
-| `EncryptionCollector` | `EventMetricCollector` | encrypt / decrypt / verify / kdf / key_load 事件 | 加密次数、认证失败、耗时、字节量、密钥处理统计 |
-| `QueueCollector` | `StateMetricCollector` | QueueManager / tree 当前状态 | pending、in_progress、processed、errors |
-| `RagfsMetricCollector` | `DomainStatsMetricCollector` | `RagfsMetricDataSource`,一次 RAGFS `metrics()` 调用 | 文件操作、Cache、multi-backend、Lock |
-| `VikingDBCollector` | `StateMetricCollector` | VikingDB collection 当前状态 | health、vectors、collections |
-| `ObserverHealthCollector` | `StateMetricCollector` | ObserverService 结果 | component health、component errors |
-| `TaskTrackerCollector` | `StateMetricCollector` | TaskTracker 当前状态 | pending、running、completed、failed |
-| `RetrievalCollector` | `DomainStatsMetricCollector` | RetrievalStatsDataSource | 检索累计统计桥接 |
-| `ModelUsageCollector` | `DomainStatsMetricCollector` | ModelUsageDataSource | 模型使用累计统计桥接 |
-| `ObserverStateCollector` | `DomainStatsMetricCollector` | ObserverStateDataSource | 诊断聚合视图桥接 |
-| `ServiceProbeCollector` | `ProbeMetricCollector` | ServiceProbeDataSource | service readiness、startup completion |
-| `StorageProbeCollector` | `ProbeMetricCollector` | StorageProbeDataSource | storage readiness、system table availability |
-| `RetrievalBackendProbeCollector` | `ProbeMetricCollector` | RetrievalBackendProbeDataSource | backend readiness、collection availability |
-| `ModelProviderProbeCollector` | `ProbeMetricCollector` | ModelProviderProbeDataSource | provider readiness、credential availability |
-| `AsyncSystemProbeCollector` | `ProbeMetricCollector` | AsyncSystemProbeDataSource | queue readiness、默认 executor 线程与任务指标 |
-| `EncryptionProbeCollector` | `ProbeMetricCollector` | EncryptionProbeDataSource | root key readiness、kms availability、encryption component health |
-
-设计理由:在引入四类 Collector 之后,整个体系的语义边界更清晰:
-
-- EventCollector 偏向增量写入,天然适合 Counter / Histogram;
-- StateCollector 偏向覆盖写入,天然适合 Gauge。
-- DomainStatsCollector 偏向桥接已有累计统计,避免把已聚合结果重新拆回事件。
-- ProbeCollector 偏向健康检查与 readiness 映射,避免把探针逻辑塞进 StateCollector 或 EventCollector。
-
-对于 retrieval 链路,统一保留 `RetrievalCollector` 命名:它既可以接收 retrieval 完成事件,也可以读取 `RetrievalStatsDataSource` 的累计快照。两类输入在实现上可以走不同分支,但不再拆出单独的 `RetrievalStatsCollectorAdapter` 名称,以避免把“同一指标域的两条输入路径”误写成两套 collector。
-
-### 2.3 `MetricRegistry` 设计
-
-`MetricRegistry` 是整个体系的稳定中心,负责统一注册、校验、存储和读取指标,但不负责采集触发,也不承担协议导出职责。它对外维持统一接口,不针对 Event / State / DomainStats / Probe 四类 Collector 再拆分多套写入 API,语义分流应由 Collector 自身完成。
-
-`MetricRegistry` 必须满足以下能力:
-
-| 能力 | 要求 |
-| --- | --- |
-| 统一注册 | 每个指标在进程内只注册一次,防止重复定义 |
-| 类型约束 | 同名指标不能一会儿是 Counter、一会儿是 Gauge |
-| 标签约束 | 每个指标的 label key 集合固定,运行时只允许填充固定维度 |
-| 并发安全 | 允许 FastAPI 协程、队列线程、后台清理线程同时读写 |
-| 低开销读取 | `/metrics` 抓取不应持有长时间大锁 |
-| 可扩展性 | 不耦合 Prometheus 专属概念,避免 registry 层直接出现 exposition 文本逻辑 |
-| 统一写入接口 | 对外维持统一的 counter / gauge / histogram 写入接口,不按 source 类型暴露分裂 API |
-
-Registry 只解决“如何统一保存指标”,不解决:
-
-- 数据从哪里来;
-- 谁来触发采集;
-- 以什么协议导出。
-
-统一接口策略如下:
-
-- EventCollector 决定何时调用 `inc_counter` 或 `observe_histogram`;
-- StateCollector 决定何时调用 `set_gauge`;
-- DomainStatsCollector 决定如何把已有累计统计映射到统一写接口;RAGFS 使用绝对值覆盖;
-- ProbeCollector 决定如何把 probe 结果翻译成 readiness / health gauge。
-
-也就是说,Registry 不感知“当前写入的是事件、状态、统计还是探针”,它只感知“要写入哪种指标类型、哪个指标名、哪些标签和值”。
-
-RAGFS 使用单一 `metrics()` 接口,返回扁平指标记录,不暴露内部对象层级。
-`RagfsMetricDataSource` 校验整批记录,`RagfsMetricCollector` 只按类型分发:
-
-```text
-Counter -> value * scale -> set_counter()
-Gauge -> value -> set_gauge()
-Histogram -> bounds/sum * scale -> set_histogram()
-```
-
-耗时在 Rust 内部以整数纳秒累计,通过 `scale=1e-9` 转为小数秒。
-Registry 的绝对值 setter 支持零值和计数重置,原有增量接口保持不变。
-Collector 不保存前值、不计算差分;只保存序列标识,用于删除消失的序列。
-读取或校验失败时保留旧数据;写入失败后由下一轮全量覆盖恢复。
-采集锁覆盖整轮读取和写入,避免超时线程与后续刷新并行更新。
-
-RAGFS 首期导出 20 个指标族,不带 `mount` 或 `account_id` 标签。
-`openviking_lock_active` 保留原名和 Gauge 类型,表示当前已发布的锁租约数。
-`openviking_lock_stale` 保留原名和 Gauge 类型,表示累计已清理的过期锁 token 数。
-`get_stats()` 在 Binding 输出层转换回微秒,Python Observer 不变。
-
-由此,registry 可以作为整个指标系统的稳定核心,而不随 exporter 或 collector 的演化频繁变动。
-
-### 2.4 `BaseMetricExporter` 设计
-
-Exporter 位于指标体系最下游,只负责把 registry 中的当前指标状态转换成外部协议。与 Registry 相同,Exporter 也遵循统一接口原则:它只依赖统一的读接口,不感知指标来自 Event / State / DomainStats / Probe 中的哪一路。
-
-Exporter 采用如下继承关系:
-
-```mermaid
-graph TB
- A["BaseMetricExporter"]
- B["PrometheusExporter"]
- C["OtelExporter"]
- D["InfluxDBExporter"]
-
- A --> B
- A --> C
- A --> D
-```
-
-各 exporter 的定位如下:
-
-| Exporter | 定位 | 首版状态 |
-| --- | --- | --- |
-| `PrometheusExporter` | 负责 `/metrics` exposition 输出 | 首版必须落地 |
-| `OtelExporter` | 对接未来 OTel 指标导出 | 预留 |
-| `InfluxDBExporter` | 对接未来 InfluxDB | 预留 |
-
-统一读取策略如下:
-
-- Exporter 通过统一的 registry 读取接口获取当前样本集合;
-- Exporter 不关心某个样本来自哪类 DataSource 或哪类 Collector;
-- Exporter 只关心指标定义、标签集合、当前值与目标协议的序列化方式;
-- source/category 语义在 Collector 写入 registry 前已经完成收敛,不应渗透到 exporter 层。
-
-### 2.5 Prometheus 方式数据路径
-
-本节讨论 `/metrics` 请求从进入服务到返回结果之间的完整运行时序,并明确导出前刷新策略的边界。Prometheus 抓取 `/metrics` 时,先执行必要的 collector 刷新,再统一读取 registry 快照,最后由 exporter 完成协议序列化。
-
-Prometheus 抓取 `/metrics` 时,执行以下流程:
-
-```mermaid
-sequenceDiagram
- participant P as Prometheus
- participant R as /metrics Router
- participant E as PrometheusExporter
- participant C as StateCollectors
- participant G as MetricRegistry
-
- P->>R: GET /metrics
- R->>E: export()
- E->>C: refresh()
- C->>G: set Gauge values
- E->>G: read unified metric snapshot
- G-->>E: metric samples
- E-->>R: text exposition
- R-->>P: 200 text/plain
-```
-
-设计理由:采用“导出前刷新 StateCollector”的原因是:
-
-- 不需要额外后台采样协程;
-- 指标与抓取时间点一致;
-- 避免无人抓取时持续消耗资源;
-- 与现有 Observer 的按需读取模式一致。
-- Exporter 保持协议层纯度,不因 source/category 增长而扩展额外分支逻辑。
-
-### 2.6 State / Probe 刷新控制策略
-
-对于 Queue、Lock、VikingDB、Task、Observer health 以及各类 probe 而言,设计目标不应是“每次 `/metrics` 抓取都严格同步拿到瞬时最新值”,而应是“在保证抓取路径稳定、延迟可控的前提下,提供足够新的状态视图”。换句话说,`/metrics` 首先是一个可持续抓取的监控接口,其次才是状态刷新触发点。
-
-基于这一点,State / Probe 刷新统一采用“默认 scrape-triggered refresh + 基于 TTL 的刷新控制 + stale-while-revalidate” 组合策略:
-
-- 默认情况下,State / Probe Collector 仍在 Prometheus 抓取 `/metrics` 时触发刷新;
-- 对读取成本高、依赖外部系统或容易抖动的 Collector,允许引入短 TTL 的刷新控制窗口;
-- 当当前时间仍处于 TTL 控制窗口内时,不重复触发刷新;
-- 当 TTL 控制窗口结束后,允许先返回最近一次成功值,再触发一次受控刷新;
-- 刷新策略属于 Collector 运行时能力,而不是 `MetricRegistry` 的职责。
-
-这里需要进一步明确两类信息的边界:
-
-- `MetricRegistry` 保存的是对外可见的当前指标值,是 Exporter 读取并序列化的唯一真实来源;
-- State / Probe Collector 不保存另一份对外指标结果,而只负责在合适的时机触发刷新。
-
-因此,TTL、超时、是否允许返回旧值、是否触发后台刷新等策略不下沉到 `MetricRegistry`。Registry 只负责统一存储指标,不负责刷新调度,也不在其读取接口上附带“读取即触发刷新”的副作用。刷新时机由 `/metrics` 导出路径中的执行层显式控制,例如由 Exporter 或独立的 CollectorManager 在导出前调用 `refresh_if_needed()`,随后再统一读取 Registry。
-
-对于返回旧值(stale value),本方案默认允许该行为,而不是把它当作异常分支。原因在于大多数状态类与探针类指标本身就不是强瞬时一致性的观测对象;相比“为了获取最新值而阻塞整个 `/metrics` 抓取路径”,继续导出 `MetricRegistry` 中最近一次成功写入的指标值更符合监控系统的使用语义。
-
-为了避免“旧值长期存在但不可见”,本方案采用更明确的可观测语义:对于无法定义失败默认值的状态类指标,指标设置之初即包含一个最小的有效性标签(如 `valid=1/0`),以便让告警与看板显式识别“当前值是否可用”。当刷新失败时,不强行覆盖写入默认值,而是将该 `valid` 标签置为 `0`,并继续导出 `MetricRegistry` 中最近一次成功写入值。
-
-- 对启用基于 TTL 的刷新控制的 State / Probe 指标,指标定义中统一包含 `valid` 标签;Collector 在刷新成功时写入 `valid=1`,刷新失败时写入 `valid=0`;
-- 对具有明确失败语义的探针类指标(如 readiness / dependency probe),刷新失败时应显式覆盖写入失败值(例如 UP -> DOWN),而不依赖“值消失”或隐式过期;
-
-在 Collector 分类上,以下对象优先视为“启用基于 TTL 的刷新控制”的候选:
-
-- 需要访问外部依赖的 Probe Collector,例如 retrieval backend、model provider、storage、encryption provider;
-- 需要做聚合、扫描或多对象汇总的 State Collector,例如 collection 级状态或复杂 observer 聚合视图;
-- 在运行中已观测到刷新耗时抖动明显、超时概率较高的 Collector。
-
-相对地,Queue、Task 等纯内存态或低成本状态读取,仍应优先保持同步 scrape-triggered refresh,不必默认引入基于 TTL 的刷新控制。
-
-### 2.7 HTTP Metrics Middleware 语义
-
-当前实现中,HTTP 请求指标并不只是“某个 EventMetricCollector 的普通上游事件源”,而是由一个专门的 middleware 负责把请求生命周期翻译为低基数、best-effort 的 HTTP metrics 事件。其运行时语义如下:
-
-#### 2.7.1 路由忽略与低基数路径归一化
-
-- middleware 必须先按 **raw path** 忽略内部接口:
- - `/metrics`
- - `/health`
- - `/ready`
-- 这样可以保证即使当前请求尚未绑定 Starlette route template,也不会把内部健康接口错误纳入业务 HTTP 指标。
-- 对普通业务请求,优先使用 route template(例如 `/api/v1/sessions/{session_id}`)作为 `route` 标签;
-- 当 route template 不可用时,禁止回退到原始 URL path,而统一回落到固定低基数字符串(例如 `"/__unmatched__"`),以避免把动态 ID、UUID、资源路径直接带入标签,造成基数爆炸。
-
-#### 2.7.2 inflight 语义是“进程内近似值”,不是强一致计数
-
-- HTTP inflight 计数可以通过进程内字典按 `(route, account_id)` 维持;
-- 该值的目标是为实时看板和排障提供“足够合理的当前并发近似视图”,而不是全局严格正确性机制;
-- 为避免多线程运行时的读改写竞态,应使用轻量锁保护该近似计数的更新过程;
-- 当 inflight 计数归零后,应及时删除对应键,避免零值键长期残留并放大内存占用。
-
-#### 2.7.3 middleware 必须保持 best-effort
-
-- HTTP metrics middleware 不能影响主请求链路;
-- 任何指标写入、inflight 调整、request 计时上报失败,都只能影响 observability side-channel,而不能影响业务响应;
-- 统一将此类异常收敛为 debug 级日志,并在日志中带上 `route` 与 `account_id` 等上下文字段;
-- 默认不开启高频错误日志,仅在 debug 诊断场景下用于排查 metrics 自身问题。
-
-#### 2.7.4 请求链路中的 `account_id` 解析分两阶段完成
-
-- middleware 进入请求时,可以先尝试从 request state 或 header 提取一个 provisional account id,用于 inflight 早期打点;
-- 请求结束后,应重新读取最终的 request-scoped account identity,并在必要时对 inflight 指标做一次 rebalance;
-- 这样可兼顾:
- - 早期 inflight 可见性;
- - 认证完成后的最终租户归属正确性。
-
-## 3. 指标策略
-
-### 3.1 指标映射总览
-
-在展开具体指标清单之前,先把“指标族 → DataSource → Collector → Metric Type”的关系收敛成统一视图,可以避免后续列表只见指标名、不见来源链路。对于首版范围内的所有指标,都应能够映射回明确的 DataSource 与 Collector;如果某个指标无法说明其输入来源或采集责任,就不应直接进入首版清单。
-
-| 指标族 | 主要 DataSource | 主要 Collector | 主要指标类型 | 代表指标 |
-| --- | --- | --- | --- | --- |
-| HTTP 请求监控 | `HttpRequestLifecycleDataSource` | `HTTPCollector` | Counter、Histogram | request total、duration、status code |
-| 检索链路监控 | `RetrievalStatsDataSource`、retrieval 完成事件 | `RetrievalCollector` | Counter、Histogram | retrieval requests、zero result、latency |
-| 模型链路监控 | `ModelUsageDataSource`、模型调用事件 | `VLMCollector`、`EmbeddingCollector`、`ModelUsageCollector` | Counter、Histogram | model calls、tokens、duration |
-| 资源导入监控 | `ResourceIngestionEventDataSource` | `ResourceIngestionCollector` | Counter、Histogram | parse / finalize / summarize / wait duration |
-| Session 与异步任务监控 | `SessionLifecycleDataSource`、`TaskStateDataSource`、`QueuePipelineStateDataSource` | `TaskTrackerCollector`、`QueueCollector` | Gauge、Counter | task pending、queue backlog、session lifecycle count |
-| 诊断与状态监控 | `ObserverStateDataSource`、`VikingDBStateDataSource` | `ObserverHealthCollector`、`VikingDBCollector` | Gauge | component health、collection health |
-| RAGFS 监控 | `RagfsMetricDataSource` | `RagfsMetricCollector` | Counter、Histogram、Gauge | 文件操作、Cache、multi-backend、Lock |
-| 加密监控 | `EncryptionEventDataSource`、`EncryptionProbeDataSource` | `EncryptionCollector`、`EncryptionProbeCollector` | Counter、Histogram、Gauge | encrypt count、decrypt duration、root key readiness |
-| 系统探针监控 | 各类 `*ProbeDataSource` | 各类 `*ProbeCollector` | Gauge、Health | service readiness、storage readiness、kms availability |
-| Python executor 监控 | `AsyncSystemProbeDataSource` | `AsyncSystemProbeCollector` | Gauge、Counter | 默认 executor 线程数、任务数、提交/完成/失败计数 |
-| 操作级 Telemetry 指标化 | telemetry adapter / bridge | `TelemetryBridgeCollector` | Counter、Histogram、Gauge | operation requests、vector scanned、memory extracted |
-
-### 3.2 指标对象模型
-
-当前指标对象模型收敛为三类基础指标:Counter、Gauge 与 Histogram。`Summary` 不纳入当前范围,以避免在聚合语义、实现复杂度与使用收益之间引入不必要的失衡。
-
-当前统一支持三种指标类型:
-
-| 类型 | 用途 | 典型场景 |
-| --- | --- | --- |
-| Counter | 单调递增计数 | 请求量、错误数、cache 命中数、任务完成数 |
-| Gauge | 当前值 | 队列 backlog、运行中任务数、锁持有数、健康状态 |
-| Histogram | 分布统计 | 请求耗时、embedding 耗时、VLM 调用耗时、资源处理耗时 |
-
-当前不支持 `Summary`,原因如下:
-
-- 对 Prometheus 多实例聚合不友好;
-- 与 Histogram 的职责边界重叠;
-- 会增加 registry 与 exporter 实现复杂度;
-- 当前 OpenViking 真实缺的是 Gauge,不是 Summary。
-
-### 3.3 标签策略
-
-标签策略的核心,不在于“尽可能表达更多业务信息”,而在于在可观测性价值与高基数风险之间取得稳定平衡。为此,标签设计必须遵守“低基数优先”原则,默认只允许有限、可枚举、可控的标签集合。
-
-#### 允许的常用标签
-
-| 标签 | 说明 | 默认策略 |
-| --- | --- | --- |
-| `operation` | 操作名,如 `search.find`、`resources.add_resource` | 默认启用 |
-| `status` | `ok` / `error` | 默认启用 |
-| `queue` | `Embedding` / `Semantic` / 其他队列名 | 默认启用 |
-| `level` | cache level,如 `L0` / `L1` / `L2` | 默认启用 |
-| `context_type` | retrieval context,如 `memory` / `resource` | 默认启用 |
-| `component` | queue / models / lock / retrieval / vikingdb | 默认启用 |
-| `task_type` | 如 `session_commit` | 默认启用 |
-| `account_id` | 租户 ID | 条件启用 |
-| `provider` | 模型供应商,如 openai / volcengine | 条件启用 |
-| `model_name` | 模型名 | 谨慎启用,需归一化后有限枚举 |
-
-#### 租户标签策略
-
-`account_id` 仅用于:
-
-- 请求量;
-- 请求耗时;
-- 任务堆积;
-- 资源导入吞吐。
-
-运行时保护规则如下:
-
-1. 默认关闭;
-2. 仅对明确列入白名单的指标启用;
-3. 提供最大活跃租户数保护,超出后回退到无标签聚合。
-
-#### `account_id` 运行时解析与回退语义
-
-在当前实现中,`account_id` 已不再只是“是否在指标定义里声明一个标签”的静态设计问题,而是一个运行时解析过程。其落地语义如下:
-
-1. **支持集(support set)比 allowlist 更窄**
- - 只有被明确标记为“支持多租户维度”的指标族,才允许在运行时注入 `account_id`;
- - 即使配置上开启了 `account_id`,不在支持集中的指标也不得携带该标签;
- - allowlist 只用于在“支持集内部”进一步决定哪些指标真正启用租户维度。
-
-2. **最终标签值不是简单的“真实租户 ID 或空”**
- - 运行时解析结果允许出现三类稳定标签值:
- - 真实租户 ID;
- - `__unknown__`:当前请求/事件无法解析出可信租户;
- - `__overflow__`:已启用活跃租户数上限保护,当前租户超出上限,统一回落到溢出桶。
-
-3. **解析路径按“显式值 > 请求上下文 > 所有权信息”收敛**
- - 对事件类指标,优先使用事件调用方显式传入的 `account_id`;
- - 对 HTTP / 请求链路类指标,优先使用 request-scoped context 中已认证/已解析出的租户身份;
- - 对资源、任务等存在 owner 语义的场景,可回退到 owner account 信息;
- - 无法得到可信结果时统一落到 `__unknown__`,而不是直接省略标签。
-
-4. **运行时策略作为独立配置对象**
- - 配置项至少应包含:
- - `enabled`
- - `metric_allowlist`
- - `max_active_accounts`
- - Collector 在写指标时不自行实现租户裁剪逻辑,而统一调用 account-dimension runtime helper 解析最终标签值。
-
-5. **文档层面应明确:`account_id` 是“有损但可控”的可观测维度**
- - 其目标是为低基数、在线监控场景提供有限的租户切片;
- - 它不是审计维度,也不保证所有租户都能长期以真实 ID 形式保留在 `/metrics` 中。
-
-#### 应避免的高基数标签
-
-- `user_id`
-- `session_id`
-- `resource_uri`
-- 原始 `error_message`
-- 原始 `query`
-- 文件路径
-- request id / telemetry id
-
-### 3.4 命名规范
-
-命名规范的目标,是让同一类指标在不同 collector、不同链路中保持一致的表达方式,减少命名漂移与语义歧义。为此,指标命名统一采用 `openviking_<domain>_<metric>_<unit>` 模板,并对 Counter / Histogram / Health 指标施加额外约束。
-
-指标命名统一采用:
-
-`openviking_<domain>_<metric>_<unit>`
-
-示例:
-
-- `openviking_retrieval_requests_total`
-- `openviking_queue_pending`
-- `openviking_task_running`
-- `openviking_operation_duration_seconds`
-
-设计要求:
-
-- Counter 以 `_total` 结尾;
-- Histogram / duration 统一使用 `_seconds`;
-- Gauge 不强制带单位后缀,但应显式表达;
-- health 指标统一使用 `0/1` 数值。
-
-### 3.5 明确不纳入 `/metrics` 的指标
-
-以下指标保留在 `/api/v1/stats` 或 telemetry JSON 中更合适:
-
-| 数据项 | 原因 |
-| --- | --- |
-| memory category 分布 | 需要扫描或查询聚合,更接近业务分析 |
-| hotness / staleness 分布 | 不适合高频抓取 |
-| 单 session extraction 明细 | 高基数、偏诊断 |
-| 原始错误文本 | 高基数且可能包含敏感信息 |
-| 任意 resource / URI 级统计 | 高基数 |
-
-### 3.6 指标桶策略
-
-所有耗时类 Histogram 统一使用秒级桶,便于跨模块比较:
-
-| 桶值(秒) | 适用场景 |
-| --- | --- |
-| `0.005` / `0.01` / `0.025` | 极短本地操作 |
-| `0.05` / `0.1` / `0.25` | retrieval / cache / 轻量 API |
-| `0.5` / `1.0` / `2.5` | embedding / 中等资源操作 |
-| `5.0` / `10.0` / `30.0` | VLM / wait 模式 / 重处理任务 |
-
-如果某条链路需要独立桶配置,应通过指标定义层配置,而不是在业务埋点中写死。
-
-### 3.7 Telemetry 指标化细则
-
-对于 operation telemetry,只抽取“结束时就已具备、并且不会导致高基数”的字段。结合 `docs/zh/guides/05-observability.md`、`docs/zh/guides/07-operation-telemetry.md` 与 `openviking/telemetry/operation.py` 的当前能力。
-
-| telemetry 字段 | 映射指标 |
-| --- | --- |
-| `summary.operation` + `summary.status` | `openviking_operation_requests_total` |
-| `summary.duration_ms` | `openviking_operation_duration_seconds` |
-| `summary.tokens.total` | 不直接落单独指标;通过对 `openviking_operation_tokens_total` 的原子分量在查询层聚合得到 |
-| `summary.tokens.llm.input` | `openviking_operation_tokens_total{token_type="llm_input"}` |
-| `summary.tokens.llm.output` | `openviking_operation_tokens_total{token_type="llm_output"}` |
-| `summary.tokens.embedding.total` | `openviking_operation_tokens_total{token_type="embedding"}` |
-| `summary.vector.searches` | `openviking_vector_searches_total` |
-| `summary.vector.scored` | `openviking_vector_scored_total` |
-| `summary.vector.passed` | `openviking_vector_passed_total` |
-| `summary.vector.returned` | `openviking_vector_returned_total` |
-| `summary.vector.scanned` | `openviking_vector_scanned_total` |
-| `summary.semantic_nodes.{total|done|pending|running}` | `openviking_semantic_nodes_total{status=...}` |
-| `summary.memory.extracted` | `openviking_memory_extracted_total{memory_type=...}` |
-
-### 3.8 Python 默认 executor 指标
-
-Python executor 指标用于观察当前服务进程内 asyncio 默认 executor 的线程和任务状态。
-它只覆盖 Python 默认 executor,不覆盖 Rust / RAGFS 内部 Tokio runtime。
-
-当前代码路径:
-
-| 文件 | 符号 | 职责 |
-| --- | --- | --- |
-| `openviking/server/app.py` | `lifespan()` | 在 `_configure_default_executor(config)` 后安装 monitor,在 shutdown metrics 后卸载 |
-| `openviking/metrics/core/runtime.py` | `DefaultExecutorMonitor` | 保存 event loop、原始 `run_in_executor`、计数器和锁 |
-| `openviking/metrics/core/runtime.py` | `install_executor_monitor()` / `uninstall_executor_monitor()` | 安装和恢复当前 event loop 的默认 executor 入口 |
-| `openviking/metrics/datasources/probes.py` | `AsyncSystemProbeDataSource.read_async_system_state()` | 合并 queue readiness 和 executor metrics |
-| `openviking/metrics/collectors/async_system_probe.py` | `AsyncSystemProbeCollector` | 写 `openviking_async_system_readiness` 和 `openviking_executor_*` |
-
-采集链路:
-
-```text
-/metrics
--> CollectorManager.collect_all()
--> asyncio.to_thread(collector.collect, registry)
--> AsyncSystemProbeCollector.read_metric_input()
--> AsyncSystemProbeDataSource.read_async_system_state()
--> get_executor_monitor().read_metrics()
--> AsyncSystemProbeCollector.collect_hook()
--> MetricRegistry
-```
-
-统计范围:
-
-```text
-统计:loop.run_in_executor(None, func, *args)
-统计:asyncio.to_thread(func, *args, **kwargs)
-不统计:loop.run_in_executor(custom_executor, func, *args)
-不统计:concurrent.futures.ThreadPoolExecutor(...) 直接创建的 executor
-不统计:Rust / RAGFS 内部 runtime 或线程
-```
-
-指标定义:
-
-| 指标名 | 类型 | 标签 | 说明 |
-| --- | --- | --- | --- |
-| `openviking_executor_max_workers` | Gauge | `pool,process_role,worker` | 默认 executor 最大 worker 数 |
-| `openviking_executor_threads` | Gauge | `pool,process_role,worker` | 默认 executor 已创建线程数 |
-| `openviking_executor_active_tasks` | Gauge | `pool,process_role,worker` | 当前正在执行的默认 executor 任务数 |
-| `openviking_executor_pending_tasks` | Gauge | `pool,process_role,worker` | 当前等待执行的默认 executor 任务数 |
-| `openviking_executor_submitted_total` | Counter | `pool,process_role,worker` | 累计提交到默认 executor 的任务数 |
-| `openviking_executor_completed_total` | Counter | `pool,process_role,worker` | 累计执行结束的默认 executor 任务数,失败也计入 |
-| `openviking_executor_failed_total` | Counter | `pool,process_role,worker` | 默认 executor callable 抛异常的累计次数 |
-
-固定标签:
-
-```text
-pool="asyncio_default"
-process_role="legacy_server"
-worker=multiprocessing.current_process().name
-```
-
-`failed_total` 的语义:
-
-- 该指标统计 worker callable 抛出的 `Exception`。
-- 如果异常被上层业务捕获并作为正常分支处理,也会计入。
-- 它不等同于业务请求失败数。
-- `/metrics` scrape 自身会通过 `asyncio.to_thread()` 刷新 collector,因此也会计入 executor 指标。
-
-运行观测:
-
-- monitor 在服务初始化前安装,会统计启动阶段的默认 executor 调用。
-- AGFS 初始化中的文件不存在、目录已存在等探测式异常会计入 `failed_total`。
-- 当前运行时如果加载旧版 `ragfs_python` binding,`RagfsMetricCollector` 调用
- `service._agfs_client.metrics()` 会失败。
-- repo 当前源码 `crates/ragfs-python/src/lib.rs` 已定义 `metrics()`;若运行时对象没有该方法,
- 说明 `.venv` 里的 native binding 产物与源码能力不一致。
-
-### 3.9 多租户支持范围
-
-当前代码中,只有进入 `ACCOUNT_DIMENSION_SUPPORTED_METRICS` 支持集的指标族允许注入 `account_id`。支持集如下:
-
-| 指标域 | 当前支持 `account_id` 的指标 |
-| --- | --- |
-| HTTP | `openviking_http_requests_total`、`openviking_http_request_duration_seconds`、`openviking_http_inflight_requests` |
-| Retrieval | `openviking_retrieval_requests_total`、`openviking_retrieval_results_total`、`openviking_retrieval_zero_result_total`、`openviking_retrieval_latency_seconds`、`openviking_retrieval_rerank_used_total`、`openviking_retrieval_rerank_fallback_total` |
-| Resource | `openviking_resource_stage_total`、`openviking_resource_stage_duration_seconds`、`openviking_resource_wait_duration_seconds` |
-| Session | `openviking_session_lifecycle_total`、`openviking_session_archive_total` |
-| Operation Telemetry | `openviking_operation_requests_total`、`openviking_operation_duration_seconds`、`openviking_operation_tokens_total` |
-| VLM | `openviking_vlm_calls_total`、`openviking_vlm_call_duration_seconds`、`openviking_vlm_tokens_input_total`、`openviking_vlm_tokens_output_total`、`openviking_vlm_tokens_total` |
-| Embedding | `openviking_embedding_requests_total`、`openviking_embedding_latency_seconds`、`openviking_embedding_errors_total` |
-
-除上述指标外,其他指标族即使在配置上开启了 `account_id`,当前实现也不会为其注入租户标签。
-
-## 5. 兼容性策略
-
-Openviking 指标体系采用如下兼容性策略:
-
-- 保持现有 retrieval / embedding / vlm / cache 指标名尽量不变;
-- `/metrics` 路由地址保持不变;
-- `server.observability.metrics.enabled` 配置保持不变;
-- `server.observability.metrics.exporters.*` 作为 exporter 扩展点:默认 Prometheus exporter 可继续工作,OTLP exporter 可按需启用;
-- `/api/v1/observer/*` 与 `/api/v1/stats/*` 行为保持不变。
-
-## 6. 风险与缓解
-
-| 风险 | 描述 | 缓解策略 |
-| --- | --- | --- |
-| 指标高基数 | 租户、模型、错误码维度无限增长 | 严格标签白名单 + 上限保护 |
-| 抓取放大成本 | StateCollector / ProbeCollector 在 `/metrics` 时做重查询 | 限制为轻量瞬时状态源与轻量 probe,不扫描业务大表 |
-| 迁移期间重复计数 | 老 PrometheusObserver 与新 registry 并存 | 引入过渡期开关,避免双写 |
-| 并发锁争用 | 高频写入与高频抓取互相影响 | registry 采用细粒度结构与最小持锁时间 |
-| 指标语义漂移 | 同一指标在不同 collector 中含义不一致 | 统一命名文档与 contract test |
-| Probe 副作用 | 外部依赖 probe 超时或失败拖慢 `/metrics` | 为 probe 设置超时、隔离失败并限制 probe 数量 |
-| Adapter 语义漂移 | telemetry bridge 或 domain stats bridge 与原始事件语义不一致 | 明确 bridge 边界并增加 contract test |
-| 双路径重复上报 | 一级事件链路与 bridge 链路同时写入同类指标 | 以指标所有权清单约束单一写入责任 |
diff --git a/docs/design/openclaw-agent-experience-memory-design.md b/docs/design/openclaw-agent-experience-memory-design.md
deleted file mode 100644
index 57bbb76cb..000000000
--- a/docs/design/openclaw-agent-experience-memory-design.md
+++ /dev/null
@@ -1,530 +0,0 @@
-# OpenClaw 接入 OpenViking Agent Experience Recall 设计
-
-日期:2026-05-28
-
-## 当前结论
-
-OpenViking 已经负责从 session commit 后的轨迹中抽取 agent experience。本 PR 不重做经验抽取、不改 commit policy,也不新增“长期记忆/经验记忆是否抽取”的控制面。
-
-本 PR 只做运行期使用面:
-
-1. 经验记忆功能默认关闭,必须显式配置 `agentExperience.enabled: true` 才启用。
-2. 启用后,OpenClaw 在 `transformContext assemble` 阶段判断当前 turn 是否像执行任务。
-3. 符合条件时,从 `viking://user/memories/experiences` 检索 agent experience。
-4. 同一轮也保留原有长期记忆 auto recall,并把 experience 和长期记忆分成不同 section。
-5. 使用统一的 `<openviking-context>` 外壳注入到 latest user message 前;即使只有长期记忆,也使用这个外壳。
-6. `afterTurn` 写 session 前剥离 `<openviking-context>`,避免把召回内容再次写回 OV。
-
-这是一版“OpenClaw 能用 OV 经验记忆”的基准实现,不是完整的多 hook experience system。
-
-## 不在本 PR 中处理的事
-
-以下内容明确不属于本 PR:
-
-- 不新增或修改 OV 服务端的 trajectory -> experience 抽取逻辑。
-- 不新增 commit 时的 extraction policy。一次 commit 是否抽长期记忆、是否抽 experience,由 OV core 后续控制面解决。
-- 不改变现有 `afterTurn()` session capture 主链路。
-- 不改变现有 `compact()` / `commitSession()` 触发策略。
-- 不新增 OpenClaw host hook。
-- 不实现 skill load / subagent start / write preflight 的自动注入。
-- 不新增 `experience_recall` 工具。
-- 不把 experience 和普通长期记忆混成同一种记忆格式。
-
-## 为什么接在 transformContext assemble
-
-OpenClaw 插件当前有两类 assemble:
-
-- preflight assemble:用于回读 OV session context,把已有 session 上下文给 OpenClaw。
-- transformContext assemble:LLM 看到消息前最后一次改写消息上下文。
-
-经验记忆是“执行前提醒”,应该发生在 LLM 决策前。当前 OpenClaw 插件没有 MemOS 那种 `before_prompt_build` hook,也没有 `before_subagent_start` / 可中断 `before_tool_call`。因此当前可落地的正确位置是 transformContext assemble。
-
-当前代码路径:
-
-```text
-examples/openclaw-plugin/context-engine.ts
- assemble()
- -> isTransformContextAssemble
- -> latestMessage.role === "user"
- -> prepareRecallQuery()
- -> shouldRecallAgentExperience()
- -> buildAgentExperienceRecallContext()
- -> buildLongTermMemoryRecallContext()
- -> buildOpenVikingContextBlock()
- -> prependRecallToLatestUserMessage()
-```
-
-## 当前 PR 的文件改动
-
-### `examples/openclaw-plugin/config.ts`
-
-新增 `agentExperience` 配置,并在 parse 阶段补齐默认值:
-
-```ts
-agentExperience?: {
- enabled?: boolean;
- recallLimit?: number;
- scoreThreshold?: number;
- maxInjectedChars?: number;
- minQueryChars?: number;
-};
-```
-
-默认值:
-
-```ts
-{
- enabled: false,
- recallLimit: 3,
- scoreThreshold: 0.35,
- maxInjectedChars: 6000,
- minQueryChars: 12,
-}
-```
-
-`enabled` 默认是 `false`,这是保守发布开关:默认不触发 experience recall,也不增加额外检索请求。用户确认服务端 experience 数据质量和注入效果后,再显式打开。
-
-`ParsedMemoryOpenVikingConfig` 是 schema parse 后的运行期类型,重点是让 `agentExperience` 的子字段也变成 required,避免 TypeScript 仍然认为 `recallLimit` / `maxInjectedChars` 可能是 undefined。
-
-### `examples/openclaw-plugin/auto-recall.ts`
-
-新增经验召回相关逻辑,但仍放在 `auto-recall.ts` 中。原因是当前插件还没有统一 recall source 目录体系,经验召回和长期记忆召回共享 query preparation、timeout、token estimate、context block 构造等基础设施。
-
-核心新增/调整:
-
-- `OPENVIKING_CONTEXT_TAG = "openviking-context"`
-- `ExperienceRecallTrigger`
-- `shouldRecallAgentExperience()`
-- `isCronSession()`
-- `buildAgentExperienceRecallContext()`
-- `buildOpenVikingContextBlock()`
-- `buildLongTermMemorySection()`
-- `buildLongTermMemoryRecallContext()` 过滤掉 experience memory,避免 experience 出现在长期记忆区;同时生成 `Long-term Memories` section,交给统一外壳注入。
-
-经验召回复用配置项 `autoRecallTimeoutMs`,不单独开 experience timeout;默认值仍是 `5000ms`。
-
-### `examples/openclaw-plugin/context-engine.ts`
-
-在 transformContext assemble 中接入两路 recall:
-
-```text
-experience recall
- -> 只查 viking://user/memories/experiences
- -> 受 agentExperience 配置和 shouldRecallAgentExperience 控制
-
-long-term recall
- -> 查 viking://user/memories
- -> recallResources=true 时查 viking://resources
- -> 过滤掉 experiences
-```
-
-然后统一生成 `<openviking-context>` 外壳:
-
-```ts
-const combinedBlock = buildOpenVikingContextBlock({
- sections: [experienceRecall.block, recall.section],
-});
-```
-
-如果没有 experience 命中,普通长期记忆仍然作为 `Long-term Memories` section 放入 `<openviking-context>`。如果两个结果都为空,直接 passthrough,不改写 messages。
-
-### `examples/openclaw-plugin/text-utils.ts`
-
-新增剥离:
-
-```text
-<openviking-context ...>...</openviking-context>
-```
-
-并保留历史格式清理:
-
-```text
-<relevant-memories>...</relevant-memories>
-```
-
-这样 `afterTurn()` 写 session 前会清理当前格式和历史格式注入块,避免本轮召回内容进入下一轮抽取。运行时新注入统一使用 `<openviking-context>`。
-
-### tests
-
-PR 中保留单元测试:
-
-- `tests/ut/agent-experience-recall.test.ts`
-- `tests/ut/context-engine-assemble.test.ts`
-- `tests/ut/context-engine-afterTurn.test.ts`
-- `tests/ut/text-utils.test.ts`
-
-`tests/integration/test_openclaw_openviking_strict_e2e.py` 只作为本地严格联调脚本保留,不进入远端 PR。
-
-## 运行时流程
-
-### 1. 进入 assemble
-
-当前只在 transformContext assemble 阶段自动注入。前置条件:
-
-- session 没有被 `bypassSessionPatterns` 命中。
-- latest message 是 user。
-- `cfg.autoRecall` 或 `cfg.agentExperience.enabled` 至少一个开启。
-- latest user message 没有已经包含 `<openviking-context>`。
-- `prepareRecallQuery()` 清理后的 query 非空,且长度至少 5。
-
-如果以上任一条件不满足,直接 passthrough。
-
-### 2. 生成 query
-
-query 来自 latest user message:
-
-```ts
-const recallQuery = prepareRecallQuery(extractAgentMessageText(latestMessage));
-```
-
-`prepareRecallQuery()` 会先调用 `sanitizeUserTextForCapture()`,因此旧的注入块、sender metadata、conversation metadata 等噪音不会进入 recall query。query 最长 4000 字符,超出会截断并写日志。
-
-### 3. 判断是否要查 experience
-
-经验召回首先受总开关控制:`agentExperience.enabled` 默认关闭。只有显式开启后,才会进入 `shouldRecallAgentExperience()`。这个 task gate 是内置逻辑,不再提供单独配置开关。
-
-硬跳过:
-
-- session bypass。
-- query 为空或短于 `agentExperience.minQueryChars`。
-- latest user text 已包含 `<openviking-context>`。
-
-强制召回:
-
-- `triggerHint` 不是 `task_start`,例如 `cron_start`。
-- `sessionKey` 包含 `:cron:`,或 `runtimeContext.isCron === true`,或 `runtimeContext.automationKind === "cron"`。
-
-普通 task gate 使用确定性打分:
-
-```text
-+3 write/edit/modify/delete/migrate/deploy/release/configure/patch 等副作用动作
-+2 fix/debug/test/build/run/implement/refactor/integrate/troubleshoot 等执行动作
-+2 error/exception/failed/retry/traceback/test failed 等失败信号
-+2 文件路径、代码对象、hook/API/tool/package/module 等工程对象
-+1 经验/踩坑/最佳实践/avoid/best practice/lesson/pitfall 等经验意图
--3 闲聊、翻译、总结当前对话等非执行场景
--2 纯知识问答,并且没有工程对象和执行动词
-```
-
-`score >= 3` 才自动查 experience。
-
-### 4. 检索 experience
-
-经验召回只查 agent experience 目录:
-
-```ts
-client.find(queryText, {
- targetUri: "viking://user/memories/experiences",
- limit: Math.max(expCfg.recallLimit * 4, 12),
- scoreThreshold: expCfg.scoreThreshold,
-}, agentId)
-```
-
-后处理:
-
-- 只保留 URI/category 看起来是 experience 的结果。
-- 按 URI 去重。
-- 截到 `agentExperience.recallLimit` 条,默认 3。
-- `level === 2` 时用 `client.read()` 读取完整内容;否则使用 abstract / overview / uri。
-- 只渲染结构化 experience,或者 metadata/URI 明确标记为 experience 的内容。
-- 总注入字符不超过 `agentExperience.maxInjectedChars`。
-- 受 `autoRecallTimeoutMs` 控制;超时或失败只 warn,不阻塞 OpenClaw。
-
-当前不查 raw trajectories。
-
-### 5. 渲染 experience
-
-OV experience 当前主要结构是:
-
-```markdown
-## Situation
-...
-
-## Approach
-...
-
-## Reflect
-...
-```
-
-OpenClaw 注入时映射为更适合执行期阅读的字段:
-
-```markdown
-### Experience: <filename>
-Source: <uri>
-Score: <score>
-
-Trigger:
-- from Situation
-
-Do:
-- from Approach
-
-Avoid:
-- from Reflect
-
-Scope:
-- from Situation
-
-Check:
-- from Reflect or Approach
-```
-
-如果原文缺某个字段,会用摘要或固定 fallback 补齐,避免给 LLM 一个空标题。
-
-### 6. 检索长期记忆
-
-原有 auto recall 保留,但输出不再直接包 `<relevant-memories>`。它现在只生成 `## Long-term Memories` section,再交给统一外壳。transformContext assemble 和非 transformContext assemble 都统一注入 `<openviking-context>`。
-
-搜索范围:
-
-- `viking://user/memories`
-- `viking://resources`,仅 `recallResources=true`
-
-后处理:
-
-- 合并结果并按 URI 去重。
-- 只保留 leaf memory。
-- 过滤掉 experience memory,避免和 `Agent Experiences` 重复。
-- 使用现有 `postProcessMemories()` / `pickMemoriesForInjection()` 排序和截断。
-- 使用 `recallMaxInjectedChars` 做完整条目预算控制,单条记忆不截半。
-
-### 7. 注入外壳
-
-长期记忆单独注入时也使用统一外壳:
-
-```markdown
-<openviking-context>
-## Long-term Memories
-
-Source: openviking-auto-recall
-The following OpenViking memories may be relevant:
-- [profile] ...
-</openviking-context>
-
-<original latest user message>
-```
-
-同时注入 agent experience 和长期记忆时:
-
-```markdown
-<openviking-context>
-## Agent Experiences
-
-These are prior execution lessons learned by this agent. Use them as task guidance, not as user facts.
-
-### Experience: openclaw-plugin-file-write-guard
-Source: viking://user/default/memories/experiences/openclaw-plugin-file-write-guard.md
-Score: 0.910
-
-Trigger:
-- 当修改 OpenClaw 插件 afterTurn 写回逻辑时。
-
-Do:
-- 在写回 OV session 前剥离注入上下文块。
-
-Avoid:
-- 避免把注入经验再次写回 transcript。
-
-Scope:
-- 当修改 OpenClaw 插件 afterTurn 写回逻辑时。
-
-Check:
-- 避免把注入经验再次写回 transcript。
-
-## Long-term Memories
-
-Source: openviking-auto-recall
-The following OpenViking memories may be relevant:
-- [profile] ...
-</openviking-context>
-
-<original latest user message>
-```
-
-规则:
-
-- 外壳统一用 `<openviking-context>`,表达“OpenViking 注入的上下文”,不绑定 OpenClaw/VikingBot/Codex 任一消费方。
-- 内部用 Markdown section 区分经验记忆和长期记忆。
-- `Agent Experiences` 在前,因为它影响执行策略。
-- `Long-term Memories` 在后,因为它更多是用户事实、偏好、资源。
-- 没有命中的 section 直接省略。
-- 两个 section 都没有时,不注入任何东西。
-- 清理逻辑兼容历史 `<relevant-memories>` 和当前 `<openviking-context>`。
-
-## 为什么 experience block 和 long-term block 不合成一个 section
-
-它们都属于 recall,但语义不同:
-
-- long-term memory 是事实/偏好/资源,回答时可以当作上下文事实。
-- agent experience 是执行策略/踩坑/验证方式,只能当作任务指导,不能当成用户事实。
-
-如果混在同一个 bullet list 里,模型容易把“以前修 bug 的做法”当成“当前用户事实”。所以它们共享 `<openviking-context>` 外壳,但必须分 section。
-
-## 与 MemOS 的关系
-
-MemOS OpenClaw adapter 的自动注入点是 `before_prompt_build`,返回 `{ prependContext }`。它不是每个 tool 调用前无脑注入,也不是 subagent 启动时一定注入。
-
-OV OpenClaw 当前没有这个 hook,但 transformContext assemble 在语义上等价于“LLM prompt 构造前最后一次上下文改写”。所以本 PR 采用 transformContext assemble。
-
-MemOS 值得参考的是三点:
-
-- 用一个外层 block 包住注入内容,便于清理。
-- 经验和普通记忆分区展示。
-- 经验要渲染成行动指导,而不是原始轨迹。
-
-本 PR 不复刻 MemOS 的 L1 Trace / L2 Policy / L3 World Model / Skill 层级。OV 服务端已经负责 trajectory 和 experience 的沉淀,OpenClaw 插件只消费结果。
-
-## 与 VikingBot 的关系
-
-VikingBot 目前已有多个经验注入点:
-
-- skill 读取后追加 `## Related Experiences`
-- subagent task 前追加 `## Agent Experience`
-- write tool 前检测写类工具,插入 `## Relevant Agent Experience`
-- cron/benchmark 场景通过任务 prompt 读取 experience
-
-这些是 VikingBot 内部 agent loop 的直接拼接逻辑,不是一个跨插件的公共 envelope。
-
-因此新外壳不应该叫 `vikingbot-context`,也不应该叫 `openclaw-context`。`<openviking-context>` 更适合作为 OV 面向不同 agent 插件的统一注入外壳。未来 VikingBot 如果迁移到公共插件协议,也可以选择复用这个 envelope;但本 PR 不改 VikingBot。
-
-## 后续更精确接入点
-
-下列入口从原理上适合注入 experience,但需要 OpenClaw host 暴露更精确的 hook 或可中断控制面。当前 PR 不实现。
-
-### Skill 加载时
-
-适合原因:agent 已经选择读取某个 `SKILL.md`,此时用 skill name/description 查经验,注入到 skill 内容旁边,相关性比全局 prompt 更高。
-
-需要 host 支持:
-
-```ts
-tool_result_persist / after_tool_call
- -> 允许插件修改 read_file(SKILL.md) 返回给 LLM 的 tool result
-```
-
-插件逻辑:
-
-```text
-read_file(SKILL.md)
- -> parse name/description
- -> query experiences
- -> append "Related Experiences" to this tool result only
-```
-
-### Subagent 启动时
-
-适合原因:subagent 是冷启动,最需要携带“类似子任务过去怎么做”的经验。
-
-需要 host 支持:
-
-```ts
-before_subagent_start(event: {
- task?: string;
- mission?: string;
- profile?: string;
- childSessionKey?: string;
-}) -> { prependContext?: string }
-```
-
-如果 host 只有 `subagent_spawned`,那通常已经太晚,只能记录元数据,不能保证改到子 agent 初始 prompt。
-
-### Write 类工具调用前
-
-适合原因:写文件、改文件、删除文件是副作用动作,经验最能减少“写了又改”的情况。
-
-但正确实现必须支持 cancel/replan:
-
-```text
-LLM 准备调用 write_file/edit_file
- -> plugin 查经验
- -> 若命中,取消当前 tool call
- -> 把经验作为 user/context message 插入
- -> 重新让 LLM 决定是否还要写、怎么写
-```
-
-如果 host 只允许不可变的 `before_tool_call`,那这点不能正确做。继续执行原 tool call 意味着经验来得太晚。
-
-### Cron 重复任务
-
-cron 原理上适合注入 experience,因为任务重复、经验命中率高。
-
-当前 PR 已经支持在 transformContext assemble 中识别:
-
-```text
-sessionKey includes ":cron:"
-runtimeContext.isCron === true
-runtimeContext.automationKind === "cron"
-```
-
-识别后 trigger 是 `cron_start`,并绕过普通 task gate。前提是该 cron session 没被 `bypassSessionPatterns` 跳过。不要默认把 cron 加入 bypass。
-
-如果未来 host 暴露 automation name/prompt,query 应该从当前 latest user message 扩展为:
-
-```text
-sessionKey
-automation name
-automation prompt
-latest task text
-recent failure/success summary
-```
-
-## 清理与防污染
-
-经验召回最容易出的问题是自我污染:本轮注入的经验被当成本轮用户输入写回 session,下次 commit 又把它抽成新的经验。
-
-当前 PR 的防线:
-
-1. assemble 前检查 latest user message 是否已有 `<openviking-context>`,有则不重复注入。
-2. `sanitizeUserTextForCapture()` 会剥离:
- - `<openviking-context>`
- - 历史 `<relevant-memories>`
-3. `afterTurn()` 写 session 前走现有文本清理路径,因此注入块不会写回 OV。
-4. long-term recall 过滤 experience URI/category,避免 experience 被长期记忆 section 再注入一次。
-
-## 测试覆盖
-
-当前 PR 的单元测试覆盖:
-
-- 普通知识问答不会触发 experience recall。
-- 执行型任务会触发 experience recall。
-- cron trigger 会强制 recall。
-- experience memory 不会出现在 `Long-term Memories` section。
-- 已存在 `<openviking-context>` 会阻止重复注入。
-- `<openviking-context>` / 历史 `<relevant-memories>` 会被清理。
-- afterTurn 写 session 前会剥离注入块。
-
-本地严格 e2e 脚本保留在工作区,但不进入远端 PR。
-
-## 验收标准
-
-合并前应满足:
-
-- `npm run typecheck` 通过。
-- `npm run build` 通过。
-- `npm run test` 通过。
-- PR diff 不包含 `tests/integration/test_openclaw_openviking_strict_e2e.py`。
-- 默认配置下不会触发 experience recall;必须显式设置 `agentExperience.enabled: true`。
-- 默认关闭 experience 时,普通长期记忆 auto recall 也使用 `<openviking-context>` 外壳。
-- 普通问答不会因为默认配置无脑注入 experience。
-- 执行型任务在有相关 experience 命中时注入 `Agent Experiences` section。
-- 同一 block 中长期记忆和经验记忆分区清晰。
-- 注入块不会被写回 OV session。
-
-## 最终边界
-
-```text
-OpenClaw 插件负责:
- - 判断当前 turn 是否值得使用 agent experience
- - 检索 viking://user/memories/experiences
- - 渲染 Agent Experiences section
- - 与 Long-term Memories 共同放入 <openviking-context>
- - 写 session 前清理注入块
-
-OpenViking 服务端负责:
- - session commit
- - trajectory 抽取
- - experience 生成和更新
- - memory vectorization
- - 未来的抽取 policy / world model / skill 演进
-```
diff --git a/docs/design/openviking-cuvs-benchmark-plan.md b/docs/design/openviking-cuvs-benchmark-plan.md
deleted file mode 100644
index aa47e0585..000000000
--- a/docs/design/openviking-cuvs-benchmark-plan.md
+++ /dev/null
@@ -1,243 +0,0 @@
-# OpenViking cuVS benchmark plan
-
-相关文档:[集成计划](./openviking-cuvs-integration-plan.md)、
-[初步结果](../../benchmark/cuvs/PRELIMINARY_RESULTS.md)。
-
-## 目标
-
-本 benchmark 不追求单个“最高 QPS”数字,而是回答四个对集成决策更有用的问题:
-
-1. 在精确检索下,cuVS brute-force 相比 OpenViking native flat 的延迟和吞吐拐点在哪里?
-2. 在相同 Recall@K 下,CAGRA 能提供多少延迟、吞吐和容量收益?
-3. 标量过滤、Python 调用和记录回表后,GPU 优势还剩多少?
-4. 当前延迟重建策略对冷启动和写后首查造成多大代价?
-
-cuVS 官方建议从 build time、search quality 和 search performance 三个维度比较向量索引;
-本方案沿用这个原则,并增加 OpenViking 集成层与 mutation lifecycle 的测量。
-
-参考:
-
-- [cuVS: comparing vector search index performance](https://docs.rapids.ai/api/cuvs/stable/getting_started/)
-- [cuVS Bench](https://docs.rapids.ai/api/cuvs/stable/cuvs_bench/)
-
-## 被测后端
-
-| 名称 | OpenViking 配置 | 作用 |
-| --- | --- | --- |
-| Native exact | `backend=local`, `IndexType=flat` | CPU flat 基线;精确性相对于其实际存储表示定义 |
-| cuVS exact | `backend=cuvs`, `algorithm=brute_force` | GPU 在配置的 device dtype(默认 float32,可显式选择 float16)表示上的精确检索 |
-| cuVS ANN | `backend=cuvs`, `algorithm=cagra` | 在固定 Recall@K 下比较 ANN 性能 |
-
-可以使用 `cuvs-bench` 的 HNSWlib 或其他算法作为算法级参考,但不能把它们当作
-OpenViking 端到端基线,因为它们没有经过相同的过滤、label mapping 和记录回表路径。
-
-### Dtype 与非侵入性原则
-
-cuVS 是 opt-in dense-search sidecar,不修改默认 backend,也不改变 native CPU
-索引的默认 `int8` 量化。cuVS host shadow 保存预处理后的 Python 浮点值;仅在创建
-device dataset 和 query 时将它们 cast 为配置的 `dtype`,默认是 float32,也可以
-显式选择 float16。因此:
-
-- L1 index-only harness 在隔离 kernel 时显式锁定 float32 CPU / float32 GPU;评估低精度
- frontier 时另跑配置为 float16 的 cuVS,并相对于 exact reference 报告 Recall@K;
-- L2/L3 保留真实应用行为,即 native int8 / cuVS 配置的 device dtype,并同时报告实际
- dtype、Recall@K 和内存占用;
-- L2/L3 不能表述为等 dtype、等内存或完全相同数值语义的比较;
-- native fallback 始终继续使用原有 int8 CPU index,启用 cuVS 不触发迁移或重写。
-
-低精度 GPU 路线作为显式配置分开评估:使用 `dtype=float16` 将 cuVS dataset/query
-cast 为 float16,并与 float32 exact ground truth 比较 Recall@K、延迟和显存;随后再
-评估 CAGRA int8 或 VPQ。native 的逐向量 scale int8 不能直接映射到 cuVS
-brute-force,若要求数值兼容,需要自定义 int8 distance/top-k 或候选召回后按 scale
-rerank,不能用简单 cast 代替。
-
-## 与 agent-memory benchmark 的关系
-
-OpenViking 仓库已经包含多类 benchmark,它们可以作为 cuVS 集成的质量与端到端 guardrail:
-
-| 仓库目录 | 主要问题 | 在 cuVS 评测中的用途 |
-| --- | --- | --- |
-| `benchmark/locomo/` | 长期对话记忆、跨 session QA | memory quality 回归;比较 local exact、cuVS exact、CAGRA |
-| `benchmark/longmemeval/openviking/` | 信息提取、多 session/时间推理、更新与拒答 | 首选的长期记忆质量 benchmark |
-| `benchmark/RAG/` | LoCoMo、Qasper、FinanceBench、SyllabusQA | 检查通用 RAG 质量和领域差异 |
-| `benchmark/tau2/llm/` | memory 对 agent tool-task success 的贡献 | 端到端任务收益,不用于隔离 vector-search 性能 |
-| `benchmark/custom/session_contention_benchmark.py` | Server 混合负载的 QPS、延迟、错误率和积压 | 扩展为 `local`/`cuvs` backend matrix,测真实服务退化 |
-
-这些质量 benchmark 不能替代 ANN benchmark。LoCoMo 只有少量长对话,LongMemEval-S 也以
-500 个问题和每题有限 session 为主;单个 user 的向量规模通常不足以让 GPU 展现优势。它们最适合
-验证“替换后端后答案质量不下降”,而不是证明最大 QPS。
-
-领域内建议优先考虑以下公开 benchmark:
-
-1. [LoCoMo(ACL 2024)](https://aclanthology.org/2024.acl-long.747/):使用广泛,覆盖长期对话
- QA、事件总结和多模态对话;适合作为兼容性基线。
-2. [LongMemEval(ICLR 2025)](https://github.com/xiaowu0162/LongMemEval):覆盖信息提取、
- multi-session reasoning、时间推理、knowledge update 和 abstention;官方 harness 同时支持
- retrieval 与 QA 评测,适合做主要 memory-quality 结果。
-3. [MemBench(Findings of ACL 2025)](https://aclanthology.org/2025.findings-acl.989/):同时考虑
- factual/reflective memory、participation/observation 场景,以及 accuracy、recall、capacity、
- temporal efficiency,适合补充系统容量与效率。
-4. [MemoryAgentBench(ICLR 2026)](https://github.com/HUST-AI-HYZ/MemoryAgentBench):覆盖
- accurate retrieval、test-time learning、long-range understanding 和 conflict resolution,适合
- 评估更广义的 agent memory 能力。
-5. [LongMemEval-V2](https://github.com/xiaowu0162/LongMemEval-V2):面向 agent trajectory memory,
- 最大 haystack 达到约 1.15 亿 token,并同时考察 answer accuracy 和 query latency;它是后续
- 展示“大规模 agent memory + cuVS”价值最匹配的公开方向。
-
-推荐最终报告采用三张相互独立的 scoreboard:
-
-- **Vector index performance**:本方案的 L1/L2,展示 latency、QPS、recall、build 和 memory。
-- **Memory quality**:LongMemEval 为主、LoCoMo 为辅,固定 embedder、reader、judge、top-k 和
- context budget,只改变 vector backend。
-- **Agent task utility**:TAU-2 或 MemoryAgentBench,比较 no-memory、native-memory 和
- cuVS-memory 的任务成功率与总成本。
-
-为了让公开 memory benchmark 达到能够体现 GPU 的规模,不应简单复制相同 memory。建议使用
-LongMemEval 的可扩展 filler sessions、LongMemEval-V2 trajectory haystack,或者独立的真实噪声
-corpus,把总索引扩展到 100K/1M/5M/10M,同时保留原题 evidence 作为 retrieval ground truth。
-
-## 三层 benchmark
-
-### L1:索引层
-
-只测 native flat、cuVS brute-force 和 CAGRA 的 build/search,不包含 embedding、HTTP、
-持久化写入和结果回表。这一层最容易解释 GPU kernel 与算法本身的收益。
-
-测量:
-
-- build wall time,其中单独记录 host-to-device transfer;
-- warm search 的 p50、p95、p99 和 QPS;
-- Recall@10、Recall@100;
-- peak host RSS、peak GPU memory 和 index size。
-
-### L2:OpenViking collection 层
-
-通过 `search_by_vector()` 发起查询,包含 Python adapter、filter translation、label mapping
-和记录回表,但使用预先生成的 query vectors,避免 embedding 服务掩盖检索差异。
-
-这一层应作为当前 feature integration 的主要结果,因为它测量了用户实际经过的代码路径。
-
-### L3:服务层
-
-通过 OpenViking server 发起请求,分别报告:
-
-- vector-ready 请求:客户端直接提供 query vector;
-- full retrieval 请求:包含 embedding 和其他业务处理。
-
-full retrieval 只用于判断向量检索在总延迟中的占比,不用于证明 cuVS kernel 的加速比。
-
-## 数据集矩阵
-
-先跑能够代表 OpenViking 的 synthetic workload,再用公开 ANN 数据集交叉验证。
-
-| 维度 | 建议取值 | 说明 |
-| --- | --- | --- |
-| Vector count | 10K、100K、1M、5M、10M | 用来找到 GPU break-even point |
-| Dimension | 128、768、1024 | 128 对齐 SIFT;768/1024 接近常见 embedding |
-| Metric | cosine/IP,补充 L2 | cosine 在两端使用相同的 L2 normalization |
-| K | 10、100 | 同时覆盖常见 retrieval 与较大候选集 |
-| Query batch | 1、8、32、128、512 | 区分低延迟与吞吐场景 |
-
-公开数据集优先使用 cuVS Bench 已支持且带 ground truth 的数据:
-
-- SIFT-1M,128D,L2;
-- GloVe-1.1M,100D,angular;
-- Deep-10M,96D,angular;
-- Wiki-all 1M/10M,768D,用于更接近 RAG embedding 的场景。
-
-## 公平性与正确性
-
-- 同一份 base vectors、query vectors、metric、K 和 normalization 输入所有后端。
-- 用 native exact 或 cuVS brute-force 生成 ground truth;精确后端必须达到 Recall@K = 1.0。
-- CAGRA 只在固定 recall bucket 下比较,例如 Recall@10 >= 0.95 和 >= 0.99。
-- CAGRA 参数至少扫描:`graph_degree={32,64}`、
- `intermediate_graph_degree={64,96}`、`itopk_size={32,64,128}`。
-- 固定 CPU threads、NUMA placement 和 GPU 数量,并在结果中记录硬件、软件版本和配置。
-- 每组先 warm up,再至少执行 10K queries;重复五轮,报告中位数与离散程度。
-- cold build、cold first query 和 warm steady state 分开报告。
-
-## 过滤 benchmark
-
-过滤会影响 CAGRA 的搜索路径,也是本集成区别于裸 cuVS benchmark 的关键部分。
-
-每个规模测试以下 selectivity:100%、10%、1%、0.1%,并包含两种分布:
-
-- uniform:符合条件的 label 在数据集中均匀分布;
-- clustered/skewed:符合条件的数据集中在少数类别或路径前缀。
-
-每个过滤场景重新生成 filtered ground truth,同时报告 Recall@K、p95 和 QPS。不能用未过滤
-ground truth 计算 recall。
-
-## 生命周期 benchmark
-
-当前实现保留 host shadow,并在 upsert/delete 后把 GPU index 标脏;下一次查询执行批量重建。
-因此必须独立测量:
-
-- 首次建库时间;
-- 进程重启后的 rehydrate + rebuild 时间;
-- 1、100、10K 和 1% 数据变更后的 write latency;
-- 从 write 返回到下一次成功查询的总时间;
-- rebuild 期间的 peak host/GPU memory。
-
-这个结果决定延迟重建适合的 workload 边界。steady-state search 图不能把 rebuild 时间平均掉,
-否则会对写密集 workload 产生误导。
-
-## 当前集成的吞吐限制
-
-默认路径仍按一次公开 API 请求提交一个 query。当前已提供默认关闭、仅适用于 brute-force 的
-request micro-batching:它可把兼容的并发单 query 请求合并为最多 8 行的 matrix-query。
-对于当前 generation 的 clean immutable snapshot,无 filter 或 device filter cache hit 可通过
-warm fast path 直接入队,不获取 caller 侧 device gate;dirty/cold snapshot、filter cache miss
-和 device filter preparation 仍先走串行的 gated preparation。入队后只有 micro-batch worker
-会在持有 device-search gate 时执行 GPU matrix search,caller 不会持 gate 等待结果。
-
-这消除了旧版“一次 GPU search 全程持有 caller/index lock”的主要并发瓶颈,但每次 dispatch
-仍会创建 query/result device array,并在返回前把结果同步到 host。因此:
-
-- batch > 1 的 L1 结果仍代表显式 vector-index batch 的能力上限,不等同于公开 API 吞吐;
-- L2/L3 应继续以单 query 请求为主,同时分别测默认关闭和 opt-in micro-batching,并记录
- 实际 batch-size 分布、`batch_wait`、`gpu_gate_queue`、QPS 与 P95;
-- 下一阶段优先评估 persistent query/result buffers、allocator reuse 和 host 同步优化,再决定
- 是否支持 CAGRA micro-batching 或多个并行 batch dispatch;OpenViking 的 scheduler 与 cuVS
- 官方的 Dynamic Batching 组件不是同一实现。
-
-## 主要图表
-
-1. p50/p95 latency vs vector count:native exact 对比 cuVS exact,展示 break-even point。
-2. QPS vs Recall@10 frontier:CAGRA 参数扫描结果,并标出 0.95/0.99 recall bucket。
-3. build/rebuild/first-query time vs vector count:展示冷启动和延迟重建代价。
-4. p95/QPS vs filter selectivity:分别展示 uniform 和 skewed filter。
-5. host RSS/GPU memory vs vector count:说明容量上限和 host shadow 成本。
-
-## 第一阶段最小矩阵
-
-先用较小但足以观察趋势的矩阵建立可重复 harness:
-
-- synthetic 1024D cosine,100K/1M/5M vectors;
-- K=10,batch=1 和 128;
-- native exact、cuVS exact、CAGRA;
-- CAGRA Recall@10 >= 0.95 和 >= 0.99;
-- 无过滤、1% uniform filter;
-- 记录 build、warm p50/p95/p99、QPS、recall、host RSS 和 GPU memory;
-- 额外执行一次 100-record update,记录 write + next-query rebuild latency。
-
-第一阶段结束后再决定是否下载 10M/100M 公开数据集,避免在 harness 尚未稳定时消耗大量
-存储和 GPU 时间。
-
-## 建议的实现结构
-
-```text
-benchmark/cuvs/
-├── README.md
-├── generate_dataset.py
-├── run_index_benchmark.py
-├── run_collection_benchmark.py
-├── configs/
-│ ├── smoke.yaml
-│ └── scale.yaml
-└── plot_results.py
-```
-
-每次运行输出一个自描述 JSON/JSONL 文件,至少包含 git revision、backend、algorithm、全部参数、
-dataset hash、hardware metadata、软件版本、raw latency samples 和 summary。图表必须能够只依赖
-这些结果文件离线重建。
diff --git a/docs/design/openviking-cuvs-integration-plan.md b/docs/design/openviking-cuvs-integration-plan.md
deleted file mode 100644
index 01f0cb1f4..000000000
--- a/docs/design/openviking-cuvs-integration-plan.md
+++ /dev/null
@@ -1,531 +0,0 @@
-# OpenViking × cuVS 集成计划
-
-> 状态:功能集成与第一轮向量索引验证已完成,后续进入数据面性能化阶段。
-> 原则:cuVS 是可选的 dense-search sidecar,不改变 OpenViking 默认 CPU 行为。
-> 相关文档:[benchmark 计划](./openviking-cuvs-benchmark-plan.md)、[初步结果](../../benchmark/cuvs/PRELIMINARY_RESULTS.md)、[用户指南(中文)](../zh/guides/16-cuvs.md)、[User guide (English)](../en/guides/16-cuvs.md)。
-
-## 1. 目标
-
-本集成只替换 OpenViking 本地 VectorDB 的 dense vector search 执行器,继续复用现有的:
-
-- 权威记录存储和持久化恢复;
-- scalar/path index 与过滤 DSL;
-- sparse/hybrid retrieval;
-- sort、aggregate、label mapping 和结果回表;
-- upsert、delete 和 collection 生命周期。
-
-当前阶段需要做到:
-
-1. 通过显式配置启用 cuVS,不改变上层检索 API 和默认 `local` 行为;
-2. pure dense query 能进入 cuVS brute-force 或 CAGRA;
-3. cosine、inner product 和 L2 的返回分数保持现有接口语义;
-4. scalar、URI/path 和组合过滤复用 native 语义,并作为 cuVS 前置过滤;
-5. upsert、delete、重启恢复后结果正确;
-6. 显存不足或 GPU 不可用时,auto 模式安全保留 native 路径;
-7. 用可复现 benchmark 量化适用规模、过滤选择性、显存和 lifecycle 成本。
-
-## 2. 非目标
-
-本阶段不做以下扩展:
-
-- 不把 cuVS 变成独立的完整数据库后端;
-- 不移除或改写 OpenViking 原生 dense index;
-- 不改变 native CPU index 的默认 int8 量化;
-- 不把 cuVS 序列化文件作为权威持久化格式;
-- 不实现多 GPU、跨机分片或共享 GPU 资源池;
-- 不在功能版中承诺写密集 workload 的低延迟;
-- 不用未过滤 top-k 后置过滤代替正确的 prefilter;
-- 不把 CAGRA 的 ANN 结果描述为精确检索。
-
-## 3. 核心决策
-
-| 决策 | 选择 | 原因 |
-| --- | --- | --- |
-| 集成位置 | `LocalIndex.search()` 的 pure dense 分支 | 边界小,可复用 Store、恢复、过滤和回表 |
-| 权威状态 | Local Store | GPU index 可随时由当前记录重建 |
-| 默认算法 | cuVS brute-force | 适合功能对齐和 exact ground truth |
-| ANN 算法 | CAGRA,显式开启 | 必须结合 Recall@K、延迟、build time 和显存评估 |
-| mutation | host shadow 标脏,下一次查询全量重建 | 首先保证 upsert/delete 语义正确 |
-| 过滤 | native bitmap 投影为 cuVS row bitset | 复用既有 DSL 和 scalar/path index,不重复实现语义 |
-| 持久化 | 不持久化 cuVS index | 避免绑定 GPU、CUDA/cuVS 版本和序列化兼容性 |
-| 默认 CPU dtype | 保持现有 per-vector-scale int8 | cuVS opt-in 不能改变未启用用户的行为 |
-| GPU dtype | device dataset/query 默认 float32,可显式配置 float16 | host shadow 保存预处理后的 Python 浮点值;仅 device dataset/query 在创建时 cast 为配置 dtype;低精度按独立能力报告 Recall@K 和显存 |
-
-## 4. 总体架构
-
-```mermaid
-flowchart TD
- API[OpenViking API / Service] --> Adapter[VectorDB Adapter]
- Adapter --> Collection[LocalCollection]
-
- Collection --> Store[(Local Store<br/>single source of truth)]
- Collection --> LocalIndex[LocalIndex]
-
- LocalIndex --> Native[Native IndexEngine<br/>dense / scalar / sparse / sort / aggregate]
- LocalIndex --> Shadow[CuVSDenseIndex<br/>host shadow / dirty state / label map]
-
- Native --> Bridge[Native filter bitmap bridge]
- Bridge -->|packed uint32 words| Shadow
- Shadow --> GPU[cuVS + CuPy / CUDA<br/>brute-force / CAGRA / prefilter]
-
- Store -. restart recovery .-> Native
- Store -. candidate reload .-> Shadow
-```
-
-一句话概括:OpenViking 管数据、生命周期和查询语义,cuVS 管 GPU dense top-k;两者通过 label layout 和 native filter bitmap 对接。
-
-### 4.1 组件职责
-
-| 组件 | 职责 | 当前状态 |
-| --- | --- | --- |
-| `VectorDBBackendConfig` / `CuVSConfig` | backend、算法、显存预算、路由阈值和 CAGRA 参数校验 | 已实现 |
-| `CuVSCollectionAdapter` | 复用 local adapter,注入 cuVS dense-search 配置 | 已实现 |
-| `LocalCollection` | schema、Store、delta、恢复和结果回表 | 复用原生 |
-| `LocalIndex` | pure dense 路由、跨后端 mutation 一致性和 native fallback | 已扩展 |
-| `CuVSDenseIndex` | host shadow、dirty lifecycle、label map、bitset cache 和 GPU index | 已实现 |
-| `_CuVSRuntime` | 延迟导入 CuPy/cuVS,调用 brute-force/CAGRA build/search | 已实现 |
-| Native `IndexEngine` | 完整 native 能力和 filter bitmap 生成 | 已扩展 bitmap bridge |
-| ABI3 backend | 暴露 filter layout 注册与 bitmap projection | 已实现 |
-| `StoreManager` | 权威记录、向量和字段存储 | 复用原生 |
-
-### 4.2 数据所有权
-
-| 状态 | 是否权威 | 生命周期 |
-| --- | --- | --- |
-| Local Store | 是 | 持久化,恢复从这里开始 |
-| Native index | 否 | 由 snapshot + delta 维护,承担完整本地能力 |
-| cuVS host shadow | 否 | 按 label 保存 dense vector 和重建所需记录 |
-| cuVS GPU index | 否 | 首次查询或 dirty 后构建,进程退出即丢弃 |
-| Device filter cache | 否 | LRU 缓存,mutation 时清空 |
-
-OpenViking 主键按现有规则映射为 `uint64 label`。cuVS 返回 dataset row id,`CuVSDenseIndex` 再通过构建时的 label 数组映射回 OpenViking label,最后由 Collection 回表得到完整记录。
-
-## 5. 核心链路
-
-### 5.1 Upsert / delete
-
-```mermaid
-sequenceDiagram
- participant C as LocalCollection
- participant N as Native IndexEngine
- participant G as CuVSDenseIndex
- participant S as Local Store
-
- C->>S: 写入权威记录 / delta
- C->>N: upsert 或 delete
- N->>N: 更新 native index 并清空 filter layout
- C->>G: 更新 host shadow
- G->>G: dirty=true,清空 filter cache
- Note over G: 下一次 GPU 查询同步重建 index
-```
-
-`LocalIndex` 使用跨后端读写锁覆盖 native mutation 和 cuVS shadow mutation,避免查询获得新 native bitmap 却使用旧 GPU row layout。warmed query 持有共享读锁并发搜索,mutation 和同步 rebuild 持有写锁。当前 mutation 后不增量修改 CAGRA,而是标脏并在下一次 dense 查询全量重建。
-
-### 5.2 Dense query
-
-```mermaid
-flowchart TD
- Q[LocalIndex.search] --> Pure{有 dense vector<br/>且无 sparse terms?}
- Pure -->|否| N[Native search]
- Pure -->|是| Ready{cuVS 已配置且可用?}
- Ready -->|否| N
- Ready -->|是| Preflight{auto filtered query?}
- Preflight -->|是| Bitmap[native bitmap + eligible count<br/>共享读并行 preflight]
- Bitmap --> Route{候选数低于<br/>native 阈值?}
- Route -->|是| N
- Route -->|否| Dirty{GPU index dirty?}
- Preflight -->|否| Dirty
- Dirty -->|是| Admit{auto 显存预算允许?}
- Admit -->|否| N
- Admit -->|是| Build[批量构建 GPU index<br/>注册 label layout]
- Dirty -->|否| Filter
- Build --> Filter{存在 filter?}
- Filter -->|否| GPU[cuVS top-k]
- Filter -->|是| DeviceBitmap[native bitmap<br/>投影为 cuVS row bitset]
- DeviceBitmap --> GPU
- GPU --> Map[row id → label → record]
-```
-
-显式 `backend=cuvs` 对支持的 pure dense query 固定使用 GPU,并在初始化或运行错误时 fail-fast。`auto_cuvs` 才执行显存准入和候选数路由。
-
-### 5.3 Filter bitmap bridge
-
-过滤路径不再扫描全部 Python records:
-
-1. GPU rebuild 后调用 `set_filter_layout(ordered_labels)`;
-2. native engine 将每个 cuVS row 预映射到 native logical offset;
-3. 查询时 native filter parser 与 scalar/path index 计算原生 bitmap;
-4. `evaluate_filter(dsl)` 按已注册 layout 投影,返回 packed `uint32` words 和 eligible count;
-5. 宽过滤把 preflight words 直接交给 cuVS,通过 `filters.from_bitset()` 构造 prefilter,不重复计算 native bitmap;
-6. 窄过滤由 native engine 返回一个有界、短生命周期的 bitmap token,CPU recall 直接复用;token miss 时安全回退到普通 search;
-7. 相同 filter 复用 device bitset;mutation 同时使 layout、device cache 和 native token 失效。
-
-auto 模式会在进入 cuVS search 前完成候选数 preflight。native engine 对
-`evaluate_filter` 使用共享读锁,因此不同的首次过滤条件可以并行计算;layout 注册和
-mutation 使用写锁。cuVS shadow 的 generation 校验会丢弃跨 mutation 得到的旧路由结果。
-
-该 bridge 继承 native 对以下能力的处理:
-
-- `and`、`or`;
-- `must`、`must_not`;
-- `contains`;
-- `range`、`range_out`;
-- URI/path prefix 和 depth;
-- `date_time`、`geo_point` 等 native 字段转换语义。
-
-bitmap 在 CPU 上生成是有意选择。native scalar/path index 已经维护了对应结构;把 URI DSL 解析、Trie 遍历和 bitmap union 搬到 GPU 会引入额外索引副本、同步和 kernel launch,而当前主要收益来自 GPU distance/top-k。只有 profiling 表明 bitmap 生成成为主要瓶颈时,才评估 GPU 化。
-
-### 5.4 Restart recovery
-
-1. 读取 collection 和 index metadata;
-2. 恢复 native snapshot 并 replay delta;
-3. 从 Store 读取当前 candidates;
-4. 恢复 cuVS host shadow,但不立即构建 GPU index;
-5. 第一次 pure dense query 按配置执行显存准入和 lazy build。
-
-cuVS index 文件未来可以作为带严格版本约束的 cache,但不能成为事实来源。
-
-## 6. 查询路由策略
-
-### 6.1 能力路由
-
-| 查询类型 | 执行路径 |
-| --- | --- |
-| pure dense,无 filter | cuVS 或 auto/native |
-| pure dense + scalar/path filter | native bitmap → cuVS prefilter,或 auto 路由 native recall |
-| sparse / hybrid | native |
-| scalar sort / aggregate | native |
-| 空数据集 / filter 无候选 | 返回空结果 |
-
-不采用 post-filter。先取未过滤 top-k 再过滤,无法保证高选择性过滤后的结果数量和真实 top-k;无限 over-fetch 也不能提供稳定正确性。
-
-### 6.2 Auto mode
-
-auto 模式包含两层决策:
-
-1. **Build admission**:根据空闲显存和保守峰值估算决定是否构建 GPU index;
-2. **Per-query routing**:根据 native bitmap 返回的 eligible count 决定 filtered query 走 CPU 还是 GPU。
-
-当前默认阈值:
-
-| 配置 | 默认值 | 含义 |
-| --- | ---: | --- |
-| `auto_filter_native_threshold` | 2000 | 普通过滤候选数不超过该值时走 native recall |
-| `auto_path_filter_native_threshold` | 200 | URI/path 过滤使用的更保守阈值 |
-
-URI/path 使用更低阈值,是因为宽路径需要 native Trie traversal 和 subtree bitmap union;这个成本会先于 GPU search 发生。阈值设为 `0` 可关闭对应 native 路由。阈值是当前测量得到的默认值,不是跨硬件、维度和 workload 的常数。
-
-候选数 preflight 和 native fallback 使用跨后端共享读锁,既保留 native engine
-原有的读并发,也避免与 mutation 交错;相同 filter 的路由决策由 LRU 直接复用。
-
-## 7. Dtype 与数值语义
-
-### 7.1 当前边界
-
-- native collection 默认保持 per-vector-scale int8;
-- cuVS host shadow 保存预处理后的 Python 浮点值,不随 `dtype` 改写;
-- 仅 cuVS device dataset/query 在创建时 cast 为配置的 `dtype`,默认是 float32,
- 可显式配置为 float16;
-- 启用 cuVS 不迁移、不重写 native index metadata;
-- native fallback 始终使用原有 CPU representation;
-- auto 模式可能按 query 在两种 representation 间路由。
-
-因此:
-
-- index-only exact benchmark 可显式使用 FP32 CPU / FP32 GPU 隔离 kernel;
-- collection/service benchmark 必须说明是 native int8 / cuVS 配置的 float32 或 float16;
-- 结果必须同时报告 Recall@K、显存和 host memory,不能声称 equal-dtype 或 equal-memory;
-- 要求固定 numerical representation 的应用应选择显式 backend,或关闭 native 候选路由。
-
-### 7.2 低精度路线
-
-低精度 GPU 存储作为显式新能力实现,不做隐式 cast:
-
-1. 先支持可配置的 float16 dataset/query;
-2. 以 float32 brute-force 为 ground truth,测 Recall@K、延迟、吞吐和显存;
-3. 再评估 CAGRA int8 或 VPQ;
-4. native scaled-int8 若要求数值兼容,需要 scale-aware distance/top-k 或候选 rerank,不能直接 cast 成普通 int8。
-
-## 8. 显存准入
-
-当前保守估算包含:
-
-- device vector payload 跟随配置的 dtype:float32 为 `N * dimension * 4`,
- float16 为 `N * dimension * 2`;
-- CAGRA retained graph:约 `N * graph_degree * 4`;
-- CAGRA build intermediate graph:约 `N * intermediate_graph_degree * 4`;
-- device filter cache:每个 bitset 约 `N / 8`;
-- 默认 `2.0` safety factor;
-- 默认保留 1 GiB 空闲显存。
-
-若预算不足,auto 模式本次查询走 native,并保留 dirty 状态供后续查询重试。显式 `backend=cuvs` 不经过该 gate。估算不是硬保证,allocator、build algorithm、batch 和并发 workload 都可能改变实际 peak;已准入后的 allocation failure 仍会在 auto 模式回退 native。
-
-## 9. 配置
-
-### 9.1 显式 cuVS backend
-
-```json
-{
- "storage": {
- "vectordb": {
- "backend": "cuvs",
- "distance_metric": "cosine",
- "cuvs": {
- "algorithm": "brute_force",
- "dtype": "float32",
- "max_concurrent_gpu_searches": 1,
- "fallback_to_native": true
- }
- }
- }
-}
-```
-
-### 9.2 CAGRA
-
-```json
-{
- "storage": {
- "vectordb": {
- "backend": "cuvs",
- "cuvs": {
- "algorithm": "cagra",
- "build_params": {
- "graph_degree": 64,
- "intermediate_graph_degree": 128,
- "build_algo": "nn_descent"
- },
- "search_params": {
- "itopk_size": 64,
- "search_width": 1
- },
- "fallback_to_native": true
- }
- }
- }
-}
-```
-
-### 9.3 保留 local 默认并自动启用
-
-```json
-{
- "storage": {
- "vectordb": {
- "backend": "local",
- "cuvs": {
- "auto_enable": true,
- "algorithm": "brute_force",
- "auto_memory_reserve_mb": 1024,
- "auto_memory_safety_factor": 2.0,
- "auto_filter_native_threshold": 2000,
- "auto_path_filter_native_threshold": 200,
- "filter_cache_size": 16,
- "auto_background_rebuild": true,
- "auto_rebuild_debounce_ms": 500
- }
- }
- }
-}
-```
-
-### 9.4 配置语义
-
-| 配置 | 默认值 | 说明 |
-| --- | --- | --- |
-| `algorithm` | `brute_force` | `brute_force` exact 或 `cagra` ANN |
-| `dtype` | `float32` | GPU dataset/query dtype;可显式设为 `float16`,不改变 native CPU dtype |
-| `max_concurrent_gpu_searches` | `1` | 单 index 同时进入 GPU search 的上限;host preflight/filter 仍可并行 |
-| `micro_batching_enabled` | `false` | 可选地合并兼容的并发单 query 请求;仅支持 `brute_force`,且要求 `max_concurrent_gpu_searches=1` |
-| `micro_batching_max_batch_size` | `8` | 单次 matrix-query 的最大行数,范围 1 到 8 |
-| `micro_batching_max_wait_ms` | `1.0` | 等待兼容请求的 collection window,范围 0 到 100 ms;0 表示不主动等待、仅 opportunistic batching |
-| `build_params` | `{}` | 传给 CAGRA `IndexParams` |
-| `search_params` | `{}` | 传给 CAGRA `SearchParams` |
-| `fallback_to_native` | `true` | sparse/hybrid 等非 cuVS dense top-k 能力使用 native |
-| `auto_enable` | `false` | 在 `backend=local` 下按空闲显存自动启用 |
-| `auto_memory_reserve_mb` | `1024` | auto admission 后保留的显存 |
-| `auto_memory_safety_factor` | `2.0` | 已知 allocation 的峰值安全系数 |
-| `auto_filter_native_threshold` | `2000` | auto 普通过滤 native 路由阈值 |
-| `auto_path_filter_native_threshold` | `200` | auto URI/path native 路由阈值 |
-| `filter_cache_size` | `16` | device bitset 或 native 路由决策的 LRU 大小 |
-| `auto_background_rebuild` | `false` | auto 模式合并 mutation 并在后台构建新 snapshot;dirty 期间查询走 native |
-| `auto_rebuild_debounce_ms` | `500` | 后台 rebuild 前用于合并连续 mutation 的静默窗口 |
-
-依赖安装方式和 CUDA 12/13 wheel 选择见中英文用户指南,不在本计划中复制易过期的版本命令。
-
-## 10. 一致性、并发与错误策略
-
-### 10.1 当前保证
-
-- 顺序 upsert/delete 返回后,下一次 GPU dense query 会先重建,提供 read-after-write;
-- native mutation 与 cuVS shadow mutation 由跨后端读写锁协调;filter layout 和 bitmap
- preflight 由 native engine 读写锁及 cuVS generation 校验保证一致性;
-- GPU index、dataset ownership、label mapping 和 generation 组成 immutable snapshot;
-- 默认非 micro-batch 路径可使用复用的 cuVS resources/CUDA stream;启用 micro-batching 后,
- compatible warm query 可在不获取 caller 侧 device gate 的情况下入队,micro-batch worker
- 是唯一在持有 device-search gate 时执行 matrix search 的组件;
-- dirty/cold snapshot、device filter cache miss 和 rebuild 仍在同一 gate 内完成 GPU preparation,
- caller 入队后立即释放 gate,不会持 gate 等待 worker;
-- mutation 不会破坏已被查询持有的 snapshot;同步 rebuild 仍由写锁合并为一次;
-- 同一 GPU 上不同 collection 的 admission/build 由进程级 coordinator 串行,避免并发超卖显存;
-- native fallback 不持有 GPU 锁,可以继续并发读取;
-- 边界明确的多调用 bulk ingest 可显式延迟 derived GPU maintenance;native/store 仍逐批
- 可见,最外层 scope 退出后只调度一次 rebuild,该 scope 不提供事务或原子性;
-- background worker 在 debounce 到期、candidate build 后和 commit 前都校验 generation;
- index 替换会先继承 bulk suspension、停止旧 maintenance worker,再启动新 worker;
-- Store 是最终事实来源,重启后派生状态会重新收敛。
-
-### 10.2 错误矩阵
-
-| 场景 | 显式 `backend=cuvs` | Auto mode |
-| --- | --- | --- |
-| cuVS/CuPy 缺失或无 CUDA device | 初始化失败 | 保留 native |
-| 向量维度错误 | 显式报错 | 显式报错 |
-| 显存预算不足 | 不适用预算 gate | 本次查询 native,后续重试 |
-| GPU allocation failure | 异常上抛 | 释放资源并回退 native |
-| GPU build/search 其他异常 | 异常上抛 | 异常上抛 |
-| sparse/hybrid | `fallback_to_native=true` 时 native | native |
-| 空数据集 / filter 无候选 | 空结果 | 空结果 |
-
-### 10.3 已知事务窗口
-
-写链路仍跨 Store、native index 和 cuVS shadow。若进程在中间退出,重启会从 Store 收敛;若进程不退出且 shadow mutation 抛错,内存派生状态可能暂时分叉。后续可用统一 mutation journal、失败后强制 reload,或构建新 snapshot 后原子交换封闭窗口。
-
-## 11. 当前限制
-
-| 限制 | 影响 | 后续方向 |
-| --- | --- | --- |
-| 每次 mutation 后整体重建 | 写后首查和 build 为 O(N) | base + delta、阈值重建、后台 build、原子切换 |
-| host shadow 保存完整 dense vectors | Store/native/GPU 之外增加 host memory | 连续 buffer、共享内存、减少 Python object |
-| 高并发小 query | 已有 opt-in micro-batching,但仍有每次 dispatch 的 device allocation、host sync 和单 worker 上限 | persistent buffers、allocator reuse、CAGRA batching 或多个并行 batch dispatch |
-| Python/CuPy 数据面 | 对象构造、复制和同步有固定开销 | 先 profiling,再决定是否下沉 C++ cuVS C API |
-| 重启后 lazy rebuild | 大 collection 的首次查询延迟高 | 后台预热、版本化派生 cache |
-| native dense 与 GPU shadow 并存 | CPU 内存和写放大 | 覆盖率和回退策略稳定后再评估裁剪 |
-| CPU int8 / GPU float32 或 float16 | 数值和内存语义不同 | 明确报告 dtype、Recall@K 和两侧 memory |
-| auto admission 是估算 | 实际 peak 随 allocator 和 workload 波动 | telemetry、校准 safety factor、OOM fallback |
-| 路由阈值来自当前 workload | 不能直接泛化 | 按规模、维度、filter type 做自适应或离线调参 |
-
-## 12. 实施阶段
-
-### Phase 0:功能集成 — 已完成
-
-- cuVS backend 与 local adapter 复用;
-- brute-force / CAGRA;
-- host shadow 与 lazy dirty rebuild;
-- native bitmap bridge 与 cuVS prefilter;
-- memory-aware auto admission;
-- filtered-query candidate routing;
-- mutation、delete、restart 和错误路径测试;
-- 中英文用户文档和 smoke example。
-
-### Phase 1:向量索引与 collection benchmark — 进行中
-
-- 公共 ANN dataset 的 FP32 exact 和 CAGRA recall frontier;
-- 100K/1M、768D/1024D exact scaling;
-- collection-level filter selectivity;
-- first filter、cached filter 和 URI subtree 成本;
-- retained VRAM、build、restart 和 mutation rebuild。
-
-完整矩阵与已有数据分别记录在 benchmark 计划和初步结果文档中。
-
-### Phase 2:数据面并发与 lifecycle 优化
-
-优先级顺序:
-
-1. 已将可搜索 GPU index 变成 immutable snapshot;
-2. 已保证 in-flight query 在 rebuild 期间安全持有旧 snapshot;后台 build 期间的新请求路由仍待实现;
-3. 已实现完成后原子交换,并延迟到最后一个持有者退出再回收旧资源;
-4. 已实现可选的连续 mutation 合并与后台 rebuild;默认关闭以保留现有 auto 行为;
-5. 已实现可复用 cuVS resources/CUDA stream,以及默认关闭的 brute-force request
- micro-batching 和 warm admission fast path;persistent query/result buffers、allocator reuse、
- CAGRA batching 和多个并行 batch dispatch 待评估;
-6. 已补充 build queue、fallback reason、eligible count 和分阶段 latency telemetry;VRAM 指标待统一管理器。
-
-### Phase 3:容量与低精度
-
-- 已实现显式 float16 brute-force/CAGRA 路径;recall/latency/VRAM 矩阵待补齐;
-- CAGRA int8 或 VPQ frontier;
-- 大 collection 的 host shadow 内存优化;
-- 根据 benchmark 决定 CAGRA 启用规模和参数策略。
-
-### Phase 4:更深层集成 — 按收益决定
-
-只有 Python/CuPy 数据面被证明是主要瓶颈时,才评估:
-
-- cuVS C API 接入 native C++ engine;
-- 共享 CUDA resource、stream 和 memory pool;
-- 多 GPU、分片和 collection 资源隔离;
-- 受 GPU/CUDA/cuVS 版本约束的持久化派生 cache。
-
-## 13. 验收标准
-
-### 13.1 功能正确性
-
-- brute-force 和 CAGRA 在真实 GPU runtime 上可构建、查询和重建;
-- cosine/IP/L2 的 score mapping 符合 OpenViking 接口;
-- scalar + URI 组合过滤结果不越权;
-- arbitrary cuVS row order 能正确映射 native bitmap;
-- upsert 后新值可检索、delete 后旧值不可检索;
-- persistent collection reopen 后可以由 Store 恢复并重建;
-- explicit/auto backend 的失败策略符合错误矩阵;
-- 默认 `backend=local` 和 native dtype 不受影响。
-
-### 13.2 性能报告
-
-每组结果至少包括:
-
-- dataset、dimension、N、metric、K 和 query batch;
-- native/GPU dtype 与 normalization;
-- build time、cold first query、warm p50/p95/p99 和 QPS;
-- Recall@K;
-- host RSS、retained VRAM,能测量时增加 peak VRAM;
-- filter 类型、selectivity、eligible count 和 route;
-- mutation size、write latency 与 next-query rebuild latency;
-- 硬件和公开软件版本。
-
-### 13.3 当前验证状态
-
-- 目标 VectorDB 单元/集成测试通过;
-- stable-ABI loader 测试通过;
-- standalone C++ engine bitmap projection 测试通过;
-- native bitmap token 复用、mutation 失效及旧 ABI fallback 测试通过;
-- brute-force/CAGRA GPU smoke 覆盖组合过滤、update、delete 和 rebuild;
-- Python lint、C++ syntax 和 diff check 通过;
-- 提交前扫描 staged/committed diff,不允许包含凭据、私钥或非公开环境标识。
-
-## 14. 代码映射
-
-| 文件 | 职责 |
-| --- | --- |
-| `openviking/storage/vectordb/index/cuvs_index.py` | runtime、host shadow、native bitmap 消费、cache、build/search 和 score mapping |
-| `openviking/storage/vectordb/index/local_index.py` | dense 路由、跨后端 mutation lock、native fallback |
-| `openviking/storage/vectordb/collection/local_collection.py` | 传递配置,恢复时注入当前 candidates |
-| `openviking/storage/vectordb_adapters/local_adapter.py` | cuVS adapter 与 auto 配置 |
-| `openviking/storage/vectordb_adapters/factory.py` | 注册 `backend=cuvs` |
-| `openviking_cli/utils/config/vectordb_config.py` | 强类型 cuVS 配置 |
-| `src/index/detail/index_manager_impl.cpp` | label layout 与 native bitmap projection |
-| `src/abi3_engine_backend.cpp` | filter bridge 的稳定 Python ABI |
-| `examples/cuvs_smoke.py` | 真实 GPU 最小功能验证 |
-| `benchmark/cuvs/` | index、collection、service benchmark 与结果汇总 |
-| `tests/vectordb/test_cuvs_index.py` | cuVS index、filter cache、路由和错误测试 |
-| `tests/vectordb/test_cuvs_collection.py` | collection、auto mode、mutation 和恢复集成测试 |
-| `tests/engine/test_index_engine.cpp` | native bitmap 的外部 row-order projection 测试 |
-
-## 15. 待评审问题
-
-1. 目标 workload 的向量维度、单 collection 规模、collection 数量和更新比例是什么?
-2. tenant/URI filter 的真实选择性分布和重复率是什么?
-3. 生产目标更重视单请求 P95,还是多请求 aggregate throughput?
-4. CAGRA 可以接受的 Recall@K、build time 和最低启用规模是什么?
-5. 写后查询是否允许读取旧 GPU snapshot,还是必须同步等待最新 snapshot?
-6. 多 collection 是否共享 CUDA stream/memory pool,如何设置隔离与显存限额?
-7. native dense 副本需要永久保留,还是在 cuVS 覆盖率稳定后允许按配置裁剪?
-
-## 16. 参考资料
-
-- [OpenViking](https://github.com/volcengine/OpenViking)
-- [NVIDIA RAPIDS cuVS](https://github.com/rapidsai/cuvs)
-- [cuVS Getting Started](https://docs.rapids.ai/api/cuvs/stable/getting_started/)
-- [cuVS brute-force Python API](https://docs.rapids.ai/api/cuvs/stable/python_api/neighbors_brute_force/)
-- [cuVS CAGRA Python API](https://docs.rapids.ai/api/cuvs/stable/python_api/neighbors_cagra/)
-- [cuVS filtering](https://docs.rapids.ai/api/cuvs/stable/filtering/)
diff --git a/docs/design/openviking-usage-count-record-implementation-plan.md b/docs/design/openviking-usage-count-record-implementation-plan.md
deleted file mode 100644
index 12a02d2d8..000000000
--- a/docs/design/openviking-usage-count-record-implementation-plan.md
+++ /dev/null
@@ -1,84 +0,0 @@
-# File Usage Event Log Implementation Plan
-
-**Goal:** 将 Usage Reporter 生成的 `UsageEvent` 转换为稳定的
-计量日志协议,供部署侧日志采集系统读取并投递到下游。
-
-**Architecture:** `MemoryUsageExtractor` 继续生成内部 `UsageEvent`。
-`FileLogUsageSink` 在写入专用日志文件前执行单向转换,每行保存一个扁平 JSON
-计量事件。`object_id` 作为稳定事件标识,供下游在 best-effort 投递发生重复时
-与 `tenant_id` 组成复合键去重。
-
-**Tech Stack:** Python 3.10+、dataclasses、标准库
-`datetime` / `json` / `logging`、pytest、Ruff。
-
----
-
-## 文件结构
-
-- `openviking/usage_reporter/file_log_sink.py`
- - 定义 `UsageEvent -> 计量日志` 私有转换。
- - 构造资源归属 `tenant_id`。
- - 将记录追加到按 UTC 小时滚动的专用日志文件。
-- `tests/unit/usage_reporter/test_file_log_sink.py`
- - 固定 recall/inject 字段映射、UTC 时间、租户字段和未知事件行为。
- - 验证多 worker 共享文件时的写入和滚动行为。
-- `docs/design/openviking-usage-reporter-sink-design.md`
- - 定义 Usage Reporter、Sink 扩展点和文件日志协议。
-
-## 计量日志映射契约
-
-`memory.recalled` 事件映射为:
-
-```json
-{
- "event_time": "2026-08-05 11:30:00",
- "tenant_id": "resource_id:ov-resource-id;account_id:2101858484;user_id:user-1;resource_uri:viking://user/user-1/memories/experiences/exchange.md",
- "event_name": "experience.recall.count",
- "object_id": "ue_recall",
- "count": 1,
- "tags": {
- "resource_type": "experience"
- }
-}
-```
-
-映射规则:
-
-- `memory.recalled` 映射为 `event_name=experience.recall.count`。
-- `memory.injected` 映射为 `event_name=experience.inject.count`。
-- `count` 固定为 `1`。
-- `occurred_at` 转换为 UTC `YYYY-MM-DD HH:MM:SS`。
-- `event_id` 写入 `object_id`,为空时拒绝写入。
-- `tenant_id` 拼接部署 `resource_id`、`account_id`、`user_id` 和 `resource_uri`。
-- `resource_id` 从 `resource_id_env` 指定的环境变量读取,未配置时拒绝启动 Sink。
-- `tags.resource_type` 记录资源类型。
-- 未知 `event_type` 拒绝写入,避免产生无法解释的计量记录。
-
-## 文件日志协议
-
-日志行格式:
-
-```text
-{"event_time":"<UTC time>","tenant_id":"resource_id:<resource>;account_id:<account>;user_id:<user>;resource_uri:<uri>","event_name":"<event>","object_id":"<event_id>","count":1,"tags":{"resource_type":"experience"}}
-```
-
-日志文件不复用 OpenViking stdout,按 UTC 小时滚动,并保留配置数量的历史
-文件。多个 server worker 写入同一路径时,文件追加和滚动通过进程间锁串行化。
-
-文件落盘及后续采集均采用 best-effort 语义。下游必须按
-`(tenant_id, object_id)` 复合键去重,不能跨 tenant 仅按 `object_id` 全局去重。
-次数查询按 `tenant_id`、`event_name` 和 `event_time` 范围过滤,并计算
-`sum(count)`。
-
-## 验证
-
-```bash
-uv run pytest -q --no-cov tests/unit/usage_reporter
-uv run ruff check \
- openviking/usage_reporter/file_log_sink.py \
- tests/unit/usage_reporter/test_file_log_sink.py
-uv run ruff format --check \
- openviking/usage_reporter/file_log_sink.py \
- tests/unit/usage_reporter/test_file_log_sink.py
-git diff --check
-```
diff --git a/docs/design/openviking-usage-reporter-sink-design.md b/docs/design/openviking-usage-reporter-sink-design.md
deleted file mode 100644
index bc62936b9..000000000
--- a/docs/design/openviking-usage-reporter-sink-design.md
+++ /dev/null
@@ -1,291 +0,0 @@
-# OpenViking Usage Reporter / Sink 技术方案
-
-## 1. 背景
-
-OpenViking 在 session commit 时会收到完整的 session messages。Agent runtime 调用 tool 后,会在 session messages 中留下 tool parts。部分 tool parts 可以表达某个记忆文件被检索、读取、注入等行为。
-
-OpenViking 需要从 session 中解析出这些使用行为,并将结构化事件交给可扩展的下游。内核不绑定具体消息队列、Webhook、日志系统或数据库,而是提供通用的 Usage Reporter / Sink 扩展机制。
-
-## 2. 业界做法
-
-这种模式是开源基础设施里常见的设计。
-
-OpenTelemetry Collector 把数据链路拆成 receivers、processors、exporters、pipelines。exporters 专门负责把数据发送到不同 backend 或 destination,例如 OTLP、Kafka、Prometheus、file 等。配置 exporter 本身不代表启用,需要在 pipeline 中声明。
-
-参考:https://opentelemetry.io/docs/collector/configuration/
-
-Vector 使用 sinks 概念,把 observability data 投递到不同目的地,例如 File、HTTP、Kafka、S3、ClickHouse、Prometheus remote write 等。
-
-参考:https://vector.dev/docs/reference/configuration/sinks/
-
-Fluent Bit 使用 Outputs 概念。官方定义里,Outputs 用来定义数据目的地,常见目的地包括远端服务、本地文件系统或标准接口,并且 Outputs 以 plugin 形式实现。
-
-参考:https://docs.fluentbit.io/manual/data-pipeline/outputs
-
-所以 OpenViking 采用“核心定义事件 + 插件式 Sink 输出”是合理的。它的核心价值是把“事件产生”和“事件去哪”解耦。
-
-## 3. 设计目标
-
-- OpenViking 内核只定义 UsageEvent 标准结构。
-- OpenViking 内核负责从 session commit 中解析 UsageEvent。
-- OpenViking 内核不绑定具体下游及其依赖。
-- 部署方可以通过自定义 Sink 接入目标系统。
-- Sink 失败默认不影响 session commit。
-- 默认不上报完整 session,只上报结构化事件,并保留定位原始 session ToolPart 所需的证据信息。
-
-## 4. 总体架构
-
-数据流:
-
-```text
-Agent runtime 调用 tool
--> session message 留下 tool part
--> client 上传 session 并 commit
--> OpenViking archive session
--> UsageExtractor 从 session messages 解析 UsageEvent
--> UsageReporter 分发 UsageEvent
--> UsageSink 写入目标系统
-```
-
-模块拆分:
-
-```text
-UsageExtractor:负责从 session 里解析事件
-UsageEvent:标准结构化事件
-UsageReporter:负责分发事件
-UsageSink:负责写入不同下游
-```
-
-## 5. UsageEvent
-
-UsageEvent 是 OpenViking 内核和外部 Sink 之间的稳定协议。
-
-示例:
-
-```json
-{
- "schema_version": "v1",
- "event_id": "ue_<sha256>",
- "event_type": "memory.injected",
- "resource_uri": "viking://user/test/memories/experiences/xxx.md",
- "resource_type": "experience",
- "account_id": "new",
- "user_id": "test",
- "session_id": "510bb5f9-4671-498e-adf4-27bb1b3691fe",
- "task_id": "b174eb56-e7d4-4fee-98a6-c53c0ddf62ed",
- "occurred_at": "2026-07-09T12:00:00Z",
- "evidence": {
- "archive_uri": "viking://user/test/sessions/510bb5f9/history/archive_001",
- "message_id": "msg_xxx",
- "tool_call_id": "call_xxx",
- "tool_name": "mcp__openviking__read"
- },
- "attributes": {}
-}
-```
-
-默认只上报结构化事件,不上报完整 session 内容。
-
-`resource_uri` 和 `resource_type` 描述被使用的资源,不限定为记忆文件;事件类型特有的数据写入 `attributes`。当前 `MemoryUsageExtractor` 只接受属于 `UsageContext.user_id` 的规范 experience URI,其他用户 URI 不生成 UsageEvent。ToolPart 必须包含非空 `tool_id`,无法稳定标识具体调用的 ToolPart 不进入统计。
-
-UsageEvent 是可独立传输和消费的完整事件。`UsageContext` 只用于 Extractor 构造事件,不再重复传给 Sink。
-
-### 5.1 Experience 使用事件识别
-
-插件使用 OpenViking 原生通用工具消费 Experience,不额外注册 Experience 专用工具:
-
-- 成功的 `find`、`search`、`list` 调用结果中出现 Experience URI,产生 `memory.recalled`。
-- 成功的 `read`、`multi_read` 调用实际读取 Experience URI,产生 `memory.injected`。
-- 支持 OpenCode 的 `openviking_*`、OpenClaw 的 `ov_*` 和
- `mcp__openviking__*` 命名空间形式;仅按受支持的工具名精确识别。
-- 通用工具返回其他记忆类型时,只保留当前用户 `memories/experiences/` 目录下的规范文件 URI。
-- 只识别上述正式通用工具,不为未发布的专用工具名提供解析或配置兼容。
-
-## 6. UsageSink 机制
-
-OpenViking 开源包定义统一的 Sink 抽象:
-
-```python
-class UsageSink:
- async def write(self, *, events: list[UsageEvent]) -> None:
- ...
-```
-
-具体 Sink 可以作为外部扩展通过 `class_path` 动态加载。开源包同时提供不依赖第三方消息队列 SDK 的内置文件日志 Sink,供日志采集系统读取。
-
-配置示例:
-
-```yaml
-server:
- usage_reporter:
- enabled: true
- sinks:
- - type: custom
- class_path: example_usage.custom_sink.CustomUsageSink
- config:
- endpoint: https://usage.example.com/events
-```
-
-OpenViking 用 `importlib` 动态加载:
-
-```python
-import importlib
-
-def load_class(class_path: str):
- module_name, class_name = class_path.rsplit(".", 1)
- module = importlib.import_module(module_name)
- return getattr(module, class_name)
-```
-
-只有配置了该 Sink 时才 import 对应模块。OpenViking 内核不 import 或安装具体下游依赖。
-
-每个 Sink 的 `write()` 调用最多等待 5 秒。超时或异常只记录日志,不影响其他 Sink。Reporter 在应用生命周期内只创建一次,应用退出时调用 Sink 可选的 `close()` 方法。同步和异步 `close()` 均受同一超时限制;同步 hook 在独立 daemon 线程中执行,超时后不会阻塞事件循环、后续 Sink 清理或进程退出。
-
-内置文件日志 Sink 将事件立即追加到专用日志文件,不写默认 stdout,也不发起
-HTTP 请求。日志文件使用 UTC 小时滚动,默认保留 168 个小时文件。部署侧应将
-专用目录挂载到日志采集系统可见的宿主机路径。多个 server worker 写入同一路径
-时,通过进程间文件锁串行化写入和滚动;Windows worker 写入后主动关闭文件句柄,
-避免其他进程滚动重命名失败。
-
-### 6.1 文件日志计量协议
-
-`UsageEvent` 继续作为 OpenViking 内部抽取结果和自定义 Sink 的稳定协议。内置
-文件日志 Sink 将 `UsageEvent` 转换为计量接收端使用的扁平 JSON。每个事件写成
-一行:
-
-```json
-{"event_time":"2026-08-05 11:30:00","tenant_id":"resource_id:ov-xxx;account_id:new;user_id:test;resource_uri:viking://user/test/memories/experiences/example.md","event_name":"experience.recall.count","object_id":"ue_<sha256>","count":1,"tags":{"resource_type":"experience"}}
-```
-
-字段映射:
-
-- `event_time` 由 `occurred_at` 转换为 UTC `YYYY-MM-DD HH:MM:SS`。
-- `tenant_id` 固定为
- `resource_id:<resource_id>;account_id:<account_id>;user_id:<user_id>;resource_uri:<resource_uri>`。
-- `memory.recalled` 映射为 `event_name=experience.recall.count`。
-- `memory.injected` 映射为 `event_name=experience.inject.count`。
-- `object_id` 使用稳定的 `event_id`。下游以 `(tenant_id, object_id)` 作为复合去重键,
- 不跨 tenant 单独按 `object_id` 去重。
-- `count` 固定为 `1`。
-- `tags.resource_type` 固定记录被使用资源的类型;本期只产生
- `experience` 使用事件。
-
-接收端按 `tenant_id`、`event_name` 和 `event_time` 范围过滤,并通过
-`sum(count)` 聚合使用次数。
-
-无法识别的 `event_type` 不生成含义不明确的计量记录,转换时抛出错误并由
-Reporter 的 best-effort 隔离机制处理。
-
-## 7. 配置设计
-
-默认关闭:
-
-```yaml
-server:
- usage_reporter:
- enabled: false
-```
-
-自定义 Sink:
-
-```yaml
-server:
- usage_reporter:
- enabled: true
- sinks:
- - type: custom
- class_path: example_usage.custom_sink.CustomUsageSink
- config:
- endpoint: https://usage.example.com/events
-```
-
-内置文件日志 Sink:
-
-```yaml
-server:
- usage_reporter:
- enabled: true
- sinks:
- - type: file_log
- config:
- path: /var/log/openviking_usage/usage.log
- resource_id_env: OV_RESOURCE_ID
- rotation_interval_hours: 1
- backup_count: 168
-```
-
-部署时必须设置 `resource_id_env` 指定的环境变量。Sink 使用其值构造
-`tenant_id`,保证不同 OpenViking resource 的数据相互隔离。
-
-## 8. 对 OpenViking 的侵入
-
-侵入点控制在 4 个地方。
-
-1. 新增 config
-
-增加 `usage_reporter` 配置段。
-
-2. 新增数据模型
-
-增加 `UsageEvent`、`UsageContext`。
-
-3. session commit 增加 hook
-
-在 session archive 成功后触发:
-
-```text
-archive session success
--> usage extractor
--> usage reporter
-```
-
-4. 新增 reporter/sink 模块
-
-新增通用扩展点和 custom sink 动态加载能力。
-
-不侵入的地方:
-
-- 不改 `find/search` 语义。
-- 不改 `read` 语义。
-- 不把具体下游写死进 session commit。
-- 不默认上传完整 session。
-- 不强制写 MEMORY_FIELDS。
-- 不强制写 search_tags。
-- 不影响 snapshot。
-- Sink 调用具有 5 秒超时边界,失败不会中断 phase2。
-
-整体侵入属于低到中等,核心主链路只增加一个旁路 hook。
-
-## 9. 可靠性策略
-
-Usage Reporter 采用 best-effort 投递语义:
-
-- Sink 成功:正常返回。
-- Sink 失败或超时:记录日志,不影响 session commit。自定义 Sink 是否重试由其实现决定。
-- 多个 Sink 相互隔离,某个 Sink 失败不影响其他 Sink。
-- Sink 失败时事件可能丢失,因此本机制不保证 at-least-once。
-- 如果 Sink 已写入成功,但进程在 phase2 写入完成标记前退出,phase2 恢复执行时可能重复发送同一事件。
-- 每个事件包含稳定的 `event_id`。Sink 可将其作为 Kafka message key;消费端按
- `(tenant_id, object_id)` 复合键去重。
-- `event_id` 只用于识别重复事件,不代表事件一定成功送达。
-
-`event_id` 为以下字段规范序列化后的 SHA-256:
-
-```text
-schema_version
-+ event_type
-+ account_id
-+ user_id
-+ session_id
-+ evidence.message_id
-+ evidence.tool_call_id
-+ resource_uri
-```
-
-`occurred_at`、`task_id`、`archive_uri` 和 `attributes` 不参与计算,避免重放时间差、
-任务恢复或附加属性变化破坏幂等性。同一 session message 中同一 tool call
-对同一资源产生的事件,在 phase2 重放后仍得到相同 `event_id`。
-
-内置文件日志 Sink 在 `write()` 返回前完成本地追加,但不负责 TLS 采集、Kafka
-投递或下游确认。文件写入、TLS 采集和下游消费任一阶段都可能在故障时产生丢失
-或重复,消费端需按 `(tenant_id, object_id)` 复合键去重,整体保持 best-effort 语义。
diff --git a/docs/design/ov-compile-design.md b/docs/design/ov-compile-design.md
deleted file mode 100644
index 7a549c68f..000000000
--- a/docs/design/ov-compile-design.md
+++ /dev/null
@@ -1,716 +0,0 @@
-# `ov compile` 技术设计
-
-| 项目 | 信息 |
-| --- | --- |
-| 状态 | 历史设计,现行方案见下方说明 |
-| 目标版本 | v1 |
-| 更新日期 | 2026-08-28 |
-
-> 本文保留最初由 VikingBot 直接托管任务的历史设计。现行方案由 OpenViking 托管 TaskRecord、QueueFS、查询和取消,外部 Server 只负责执行。
-
-## 1. 概述
-
-`ov compile` 使用指定 Skill 整理 OpenViking 中的材料,并在目标目录生成或更新 Wiki 页面。
-
-命令由 VikingBot 执行。`ov` CLI 通过 OpenViking 的 Bot 代理调用 VikingBot,VikingBot 运行 AgentLoop,并使用当前用户身份读取和写入 OpenViking 数据。
-
-```text
-ov compile
- -> OpenViking /bot/v1/compile
- -> VikingBot Compile AgentLoop
- -> OpenViking content APIs
-```
-
-v1 的核心目标:
-
-- 支持一个或多个来源目录;
-- 加载用户指定的 OV Skill;
-- 根据任务描述生成一个或多个 Wiki 页面;
-- 增量更新已有 Wiki;
-- 通过异步任务返回进度和结果。
-
-## 2. 用户接口
-
-### 2.1 命令格式
-
-```bash
-ov compile \
- --from viking://resources/周报 \
- --to viking://resources/团队知识库 \
- --instruction "按月整理团队的成本优化进展" \
- --skill viking://agent/skills/monthly_wiki \
- --args '{"model_name":"your-model-endpoint-id"}'
-```
-
-| 参数 | 规则 |
-| --- | --- |
-| `--from` | 必填,可重复,也可使用逗号分隔多个目录 |
-| `--to` | 必填,目标 Wiki 目录 |
-| `--skill` | 必填,Skill 目录或 `SKILL.md` 的 Viking URI |
-| `--instruction` | 可选,本次整理任务的描述 |
-| `--args` | 可选,Provider 扩展参数 JSON 对象;`model_name` 可传模型 Endpoint ID |
-
-参数在 OpenViking 用户身份下 canonicalize 后满足以下约束:
-
-- `from` 必须是一个或多个可读目录;重复项去重,空项报错;
-- `to` 必须是可写的 resource 或 memory 目录,不能是 namespace 根、文件、Skill 目录或 OpenViking 派生目录;
-- `skill` 必须解析为 Skill root,目录 URI 和其 `SKILL.md` URI 视为同一个 Skill;
-- `from`、`to` 和 `skill` 的权限最终仍由 OpenViking Server 校验,CLI 不根据 URI 文本推断权限。
-
-`--instruction` 为空时,VikingBot 使用以下默认任务描述:
-
-```text
-Follow the loaded Skill's instructions to transform the provided source materials into the outputs required by the Skill.
-```
-
-### 2.2 返回结果
-
-CLI 在任务创建后立即返回:
-
-```text
-task_id: cmp_01...
-status: accepted
-to: viking://resources/团队知识库
-```
-
-CLI 不等待任务完成。用户通过 `ov task status <task_id>` 查询状态和结果,通过 `ov task cancel <task_id>` 取消任务。
-
-Task 结果中的 `created`、`updated` 和 `unchanged` 只统计 Agent 本次提交的页面;未被草稿触达的目标页面不计入 `unchanged`。`page_count` 等于三者之和,`link_count` 只统计最终正文中实际渲染出的 bundle 内 WikiLink。
-
-### 2.3 记忆整理模式(`--skill memory`)
-
-除了上面基于 VikingBot Skill 的 Wiki 整理,`ov compile` 还支持一种**记忆整理模式**:把 `--skill`
-设为哨兵值 `memory`,即可对 `--to` 指定的 memories 根目录或某个记忆类型目录做**就地整理**(去重、合并、拆分、原地精简),
-产物严格遵守各自记忆类型的 schema。该模式完全在 OpenViking 进程内通过现有 memory 框架
-(`ExtractLoop` + `MemoryUpdater`)执行,**不经过 VikingBot**。
-
-```bash
-# 整理 entities 记忆(就地去重/合并/规范化)
-ov compile \
- --to viking://user/<user_id>/memories/entities \
- --skill memory \
- --instruction "合并明显重复的实体,但不同实体不要合并;保留每个实体的独立事实"
-
-# 也可以整理其它记忆类型,例如 preferences
-ov compile \
- --to viking://user/<user_id>/memories/preferences \
- --skill memory
-```
-
-参数规则:
-
-| 参数 | 规则 |
-| --- | --- |
-| `--skill` | 固定值 `memory`(哨兵,不解析为真实 Skill)触发记忆整理模式 |
-| `--to` | 必填,可为 `.../memories` 根目录或某个记忆类型目录(如 `.../memories/entities`);不接受用户根目录 |
-| `--from` | 记忆模式下**不接受**;整理就地发生在 `--to` 空间内 |
-| `--instruction` | 可选,作为整理指令(软提示)喂给整理模型;用于点破"两条其实是同一实体需合并"这类模型无法自行判断的场景 |
-
-行为要点:
-
-- **类型范围**:指定类型目录时只加载该类型;指定 memories 根目录时按 schema 存储路径发现已存在且已启用的类型,包括根目录单文件记忆,在同一任务、同一 ExtractLoop 中联合整理,不拆子任务。各类型仍遵守自身 schema;结果的 `memory_types` 列出本次范围,根目录请求的 `memory_type` 为 `null`。
- 改名或合并时,系统仍可更新其它类型的相邻记忆文件以迁移 links/backlinks。
-- **就地整理**:`--from` 与 `--to` 是同一空间,不引入外部来源,因此不存在跨身份空间的串号问题;
- 空间(self 或某个 `peers/{peer_id}`)由 `--to` 的 URI 决定。
-- **保守合并**:默认只合并明显同一身份的记忆;模型无法从内容判断的合并(如"阿珍就是陈静娴"),
- 必须通过 `--instruction` 明确点破。
-- **安全改名**:schema 允许 URI 字段变更时,公共 memory 写入层按“写入新 URI、迁移引用、删除旧 URI”
- 执行,结果记为 `adds` 新 URI + `deletes` 旧 URI。若目标 URI 已存在则报冲突、不覆盖,模型读取两份
- 记忆后需显式更新目标,并用 replacement 关系删除源文件。
-- **异步任务**:与普通 compile 一致,命令返回一个 `cmp_` 前缀的 `task_id`,通过 `ov task status <task_id>`
- 查询结果。记忆模式的任务结果包含变化文件清单,字段沿用 `memory_diff.json` 的语义
- (`adds` / `updates` / `deletes` 及对应 `total_*`,仅文件 URI,不含内容),并带上本次整理的 `trace_id`。
-
-## 3. 架构
-
-```text
-┌──────────────┐
-│ ov CLI │
-└──────┬───────┘
- │ POST /bot/v1/compile
- ▼
-┌────────────────────────────┐
-│ OpenViking Bot Proxy │
-│ auth + identity forwarding │
-└──────────────┬─────────────┘
- ▼
-┌────────────────────────────┐
-│ VikingBot │
-│ │
-│ Compile Task │
-│ ├─ Skill Loader │
-│ ├─ Context Tools │
-│ ├─ AgentLoop │
-│ ├─ Wiki Renderer │
-│ └─ OpenViking Writer │
-└──────────────┬─────────────┘
- │ read / search / batch-write
- ▼
-┌────────────────────────────┐
-│ OpenViking Data APIs │
-└────────────────────────────┘
-```
-
-职责划分:
-
-| 模块 | 职责 |
-| --- | --- |
-| `crates/ov_cli` | 参数解析、HTTP 调用、任务轮询和结果展示 |
-| `openviking/server/routers/bot.py` | 认证请求并代理到 VikingBot |
-| `bot/vikingbot/compile` | Compile 任务、Skill、AgentLoop、渲染和写入编排 |
-| OpenViking content service | 数据权限、内容读写和索引刷新 |
-
-OpenViking Server 必须启用 Bot 服务。未启用时,命令返回与 `ov chat` 一致的 503 错误。
-
-### 3.1 现有能力复用
-
-Compile 只增加任务编排和领域规则,基础能力使用现有实现:
-
-| 步骤 | 复用实现 | Compile 适配 |
-| --- | --- | --- |
-| CLI | `CliContext`、`HttpClient`、全局认证、`OutputFormat`、`output_success()` | compile request、状态轮询和 human formatter |
-| Bot proxy | `get_bot_url()`、`_create_bot_proxy_client()`、`_attach_openviking_connection()` | create/status 路由 |
-| Gateway 认证 | `OpenAPIChannel` 的 Gateway Token dependency、`OpenVikingConnection` 和 principal scope | compile request model 和 task owner 绑定 |
-| URI 与权限 | `fs/attrs` 返回的 canonical URI、请求边界 URI 校验与简写展开、`context_type_for_uri()`、VikingFS access check | 用户上下文中的目录约束和 target containment |
-| Skill | OpenViking Skills API、`SkillLoader.parse()`、VikingBot `SkillsLoader`、`SandboxManager` | OV bundle 快照和 task-local materialization |
-| Agent | `AgentLoop._run_agent_loop()`、`ToolRegistry`、`register_default_tools()` | structured wrapper、scope guard 和 `submit_wiki_bundle` |
-| 内容读取 | `openviking_list/search/grep/glob/multi_read` | 限定允许的 URI roots;不增加同义读取工具 |
-| Link 与 metadata | `WikiLink`、`StoredLink`、`LinkRenderer`;Memory 目标额外复用 `MemoryFileUtils`、`next_memory_version()` 和 resource refs helper | OKF path、citation 和严格校验 |
-| 写入与刷新 | `ContentWriteCoordinator` 的校验/refresh helper、`LockManager`、`VikingFS.write_file(..., lock_handle=...)`、`RequestWaitTracker` | batch mode 和多文件编排 |
-
-新增能力保持在以下边界内:
-
-- Bot 侧 Compile request/task/result 和最小 task store;
-- `submit_wiki_bundle` 工具及其 schema;
-- Compile 特有的 OKF/path/citation 规则;
-- `/bot/v1/compile` API family 和 `/api/v1/content/batch-write` 数据接口。
-
-## 4. Compile API
-
-### 4.1 创建任务
-
-```http
-POST /bot/v1/compile
-```
-
-```json
-{
- "from": ["viking://resources/周报"],
- "to": "viking://resources/团队知识库",
- "instruction": "按月整理团队的成本优化进展",
- "skill": "viking://agent/skills/monthly_wiki"
-}
-```
-
-成功时返回 HTTP 202:
-
-```json
-{
- "task_id": "cmp_01...",
- "status": "accepted",
- "to": "viking://resources/团队知识库"
-}
-```
-
-VikingBot 负责规范化参数并计算实际任务描述:
-
-```python
-effective_instruction = (request.instruction or "").strip() or DEFAULT_COMPILE_INSTRUCTION
-```
-
-### 4.2 查询任务
-
-```http
-GET /bot/v1/compile/{task_id}
-```
-
-```json
-{
- "task_id": "cmp_01...",
- "status": "running",
- "stage": "agent",
- "created_at": "2026-07-20T10:00:00Z",
- "updated_at": "2026-07-20T10:01:12Z"
-}
-```
-
-任务状态:
-
-| status | stage |
-| --- | --- |
-| `accepted` | `queued` |
-| `running` | `loading_skill`、`collecting_context`、`agent`、`rendering` |
-| `committing` | `writing`、`refreshing`、`salvaging` |
-| `completed` | `completed`、`salvaged` |
-| `failed` | 失败时所在阶段 |
-
-完成结果:
-
-```json
-{
- "task_id": "cmp_01...",
- "status": "completed",
- "result": {
- "from": ["viking://resources/周报"],
- "to": "viking://resources/团队知识库",
- "skill": "viking://agent/skills/monthly_wiki",
- "okf_version": "0.1",
- "created": ["viking://resources/团队知识库/成本优化月度进展.md"],
- "updated": [],
- "unchanged": [],
- "page_count": 1,
- "link_count": 0,
- "warnings": []
- }
-}
-```
-
-任务只能由创建它的用户查询。
-
-失败结果使用同一查询接口返回稳定结构:
-
-```json
-{
- "task_id": "cmp_01...",
- "status": "failed",
- "stage": "writing",
- "error": {
- "code": "WRITE_CONFLICT",
- "message": "Target Wiki changed while the compile task was running."
- }
-}
-```
-
-创建请求继续通过 body 中的 `openviking_connection` 传递当前用户身份。查询请求是 GET,没有 body;OpenViking proxy 转发原认证凭证,并从已认证的 `RequestContext` 设置 canonical `X-OpenViking-Account/User` header。VikingBot 先做现有 Gateway Token/loopback 校验,再通过 `_resolve_request_principal()` 向 OpenViking 验证凭证并计算 principal scope。无权查询与 task 不存在统一返回 `NOT_FOUND`,避免泄露其他用户的 task ID。
-
-## 5. 执行流程
-
-VikingBot 创建异步任务后依次执行:
-
-1. 计算 `effective_instruction`,并对 `from`、`to` 和 `skill` 做 URI 语法校验。
-2. 通过 OpenViking 现有 `fs/attrs` 取得来源和目标的 canonical URI,再用 stat/list/read 路径验证形状与权限;Skill API 直接返回 canonical Skill root。VikingBot 后续只使用这些响应中的 canonical URI。
-3. 通过 Skills API 取得 Skill root、定义和文件清单,通过现有 content read/download 路径读取辅助文件,在 task workspace 中物化快照,并交给 `SkillsLoader` 加载。
-4. 为每个来源建立 `source_id + directory_uri + overview` 描述,并使用现有 list/tree 能力建立目标 Wiki 的有界轻量 catalog。
-5. 从现有 `ToolRegistry` 构建 request-local 工具集,用显式 Compile Prompt 和 selected Skill 正文运行 structured AgentLoop;不加载普通 chat history、自动 memory recall 或其他 workspace Skill。
-6. 接收 Agent 提交的结构化 `WikiBundleDraft`。
-7. 对草稿中的每个 `update_uri` 读取一次最新 raw content,生成 base hash;新页面不需要预读全部目标正文。
-8. 校验并渲染最终 Wiki 文件,区分 created、updated 和 unchanged。
-9. 有 write operation 时通过 batch-write 一次提交并等待索引刷新;空 bundle 或全部 unchanged 时跳过写入接口。
-10. 保存任务结果并清理 task workspace。
-
-其中 AgentLoop 是唯一的内容生成阶段。后续校验、路径生成和写入都是确定性操作。
-
-## 6. Skill 与上下文
-
-### 6.1 Skill 加载
-
-`--skill` 支持 Skill 目录或目录内的 `SKILL.md`。
-
-VikingBot 从 canonical Skill URI 拆出 `skill_name` 和 `target_uri`,调用现有 Skills API 取得 Skill root、`SKILL.md` 和文件列表,再通过同一用户连接调用现有 content read/download 路径读取辅助文件;确定性加载阶段不调用 Agent tool,也不解析 `openviking_multi_read` 的展示文本。`SKILL.md` 使用现有 `openviking.core.skill_loader.SkillLoader.parse()` 校验并取得 `allowed_tools`;该 parser 增加 `allowed_tools_declared` 布尔值,以保留“未声明”和“显式空数组”的区别,Compile 不为此再解析一遍 YAML。快照物化到 task-local workspace 后,使用现有 `vikingbot.agent.skills.SkillsLoader` 加载正文和 VikingBot metadata。requirements 使用 `SkillsLoader` 解析出的 `requires.bins/env`,但在实际 task sandbox 中做存在性检查,避免使用 Bot host 环境误判。
-
-该层只负责远程 bundle 的快照和物化,不实现新的 frontmatter parser、Skill 目录规范或 requirements 协议。OpenViking 派生文件和 Skill source metadata 不进入快照;加载过程限制文件数量、单文件大小和总大小,并拒绝逃逸 Skill root 的相对路径。task workspace 只包含本次选择的 Skill,selected Skill 正文直接加入 structured system prompt。任务结束后先调用 `SandboxManager.cleanup_session()` 停止 backend,再删除 compile 专属 workspace;现有 `cleanup_session()` 本身不会删除 direct-backend 目录,不能把它当成文件清理。
-
-Skill package 内的文件使用 `read_file` 读取 task workspace 路径 `skills/<skill-name>/...`;`openviking_*` 工具只读取任务范围内的 `viking://` URI。
-
-Skill 用于描述整理方法,例如:
-
-- 应关注哪些信息;
-- 页面如何分层;
-- 使用什么表达风格;
-- 何时生成索引页或专题页。
-
-### 6.2 来源上下文
-
-VikingBot 按 canonical `from` 顺序为每个来源分配稳定的 request-local ID:
-
-```text
-source_id, directory_uri, overview
-```
-
-`source_id` 只标识用户传入的来源目录,例如 `src_1`;它不是文件读取追踪 ID。Agent 首先获得这些来源描述和有界轻量目录信息,再通过 VikingBot 已有 OpenViking 工具按需读取:
-
-- `openviking_list`:浏览来源目录;
-- `openviking_search`:语义检索;
-- `openviking_grep` / `openviking_glob`:按内容或路径查找;
-- `openviking_multi_read`:读取具体内容和 overview。
-
-Compile 不注册另一组 source tools。它在现有工具执行前增加 request-local URI scope guard:所有 URI 参数必须位于 `from`、`to` 或 Skill root 内;`openviking_search/list/grep/glob` 不能省略 scope 后退化为全库查询;`multi_read` 的 URI 数量、递归 list 的节点数、单次结果和任务累计工具结果字节数受 Compile 上限约束。原工具没有上限的地方由这个 guard 补齐,但实际读取和权限判断仍由原工具完成。
-
-### 6.3 目标上下文
-
-运行 Agent 前,VikingBot 使用现有 list/tree/read API 将 Resource 目标完整物化到任务工作区:
-
-```text
-__compile_staging__/target_checkout/<target-relative-path>
-```
-
-Agent 直接在该目录内新增、修改和重构最终文件,不需要声明 create/update,也不维护 target manifest 或 baseline hash。提交时 Compile 扫描完整 checkout、执行确定性 Wiki 内链处理,再将全部文件以 `upsert` 写回;checkout 中没有出现的目标文件不会被删除。
-
-### 6.4 工具集合
-
-`request_tools` 从 `register_default_tools()` 创建的 task-local registry 中筛选:
-
-```text
-compile_tools = available_tools ∩ (_COMPILE_CORE_TOOLS ∪ _OV_READ_TOOLS)
-request_tools = compile_tools + submit_wiki_bundle
-```
-
-`_COMPILE_CORE_TOOLS` 固定为 `read_file`、`write_file`、`edit_file` 和 `exec`;`_OV_READ_TOOLS` 固定为 `openviking_list`、`openviking_search`、`openviking_grep`、`openviking_glob`、`openviking_multi_read` 和 `openviking_export`。OpenViking 工具仍受用户权限和 Compile URI scope 限制,本地文件和 shell 工具仍受 task workspace 与 sandbox policy 限制。
-
-Compile 不使用 Skill 的 `allowed-tools` 推导、授权或限制工具,也不为 Skill 连接 MCP。该字段可作为其他 Skill 宿主的兼容 metadata 保留。Skill 需要飞书、方舟等外部能力时,通过 `exec` 调用 task sandbox 中预装的 CLI;可选的 `requires.bins/env` 只用于提前检查运行条件,不负责安装 CLI 或依赖。
-
-固定 allowlist 已排除 `message`、`cron`、`spawn`、Web、image、MCP 和 OpenViking 写入/提交工具,无需维护额外 blocklist。`exec` 仍可能产生外部副作用;现有 `direct` sandbox 只提供 task cwd,不是 OS 级隔离。`bot.sandbox.backends.direct.allow_compile_exec` 默认为 `true`(Compile 工具链开源,`exec` 默认直接以用户 shell 权限运行),使用 `direct` 时 Compile 工具集默认注册 `exec`;普通整理任务仍可通过文件工具完成。声明 `requires.bins` 或 `requires.env` 的 Skill 会先探测命令;如需关闭 `exec`,可显式设为 `false`,此时此类 Skill 会在执行任何命令探测前返回 `SKILL_CAPABILITY_UNAVAILABLE`。生产或多用户部署应使用配置了文件系统和网络 policy 的隔离 backend。
-
-### 6.5 结构感知探索(survey → 定向精读)
-
-Compile 不采用“每个文件读开头 N 行”的线性扫描(开头几行通常是 `session_meta`/文件头/import,几乎不含信号,还会误导 Agent 把中段内容判为低价值)。它也不在代码里实现确定性结构采样器,而是改为 **纯 prompt 教会模型用已有工具做 survey → 定向精读**,与 Claude Code / Codex 探索陌生语料的方式一致:
-
-1. **先看目录结构**:用 `openviking_list`(recursive)或 `openviking_glob` 拿文件清单(路径/大小/扩展名)。
-2. **分层采样几个文件**:跨目录/扩展名/大小,用 `openviking_multi_read` 的 offset/limit 读 **head + middle + tail 三个窗口**(不是只读头几行),理解每个文件的格式、正文分布与内容大致区间。
-3. **推断结构(靠模型自己,不靠代码代劳)**:JSONL 每行一条记录、判别字段是什么、哪些字段承载长文本;Markdown 的 heading 结构等。
-4. **定向精读**:用 `openviking_grep` 定位信号、`openviking_multi_read` 窗口读,或(已物化到 `compile_resources/` 的)用 `exec` 跑 jq/grep/sed/python 读中段;明确禁止只凭文件头几行判断价值。
-5. **一次性写输出**:所有输出文件尽量在一个回复里用多个 `write_file` 写完。
-
-覆盖语义与 Codex 对齐:**没有任何逐文件覆盖门禁或读取追踪**。物化文件与未物化文件都不做运行时“是否读过”校验;模型在 prompt 指导下自行保证“未物化(二进制/下载失败)的源文件提交前用 `openviking_*` 读工具读过”。
-
-### 6.6 物化与来源采样
-
-物化与 `to` 类型解耦:只要有 sandbox(`--to` 为 resource/memory/skill 均满足),`--from` 的所有源文件都会 eager 物化到 `compile_resources/<source_id>/...`(无单文件/总字节上限;二进制与下载失败文件记为未物化,URI → 本地路径映射记录在 `compile_resources/_manifest.tsv`)。物化让模型能用 `exec` 本地 grep/jq/python 扫文件,而不是逐个 round-trip 到 OpenViking server。memory/skill 目标同样物化。salvage 仍仅 resource 目标(memory 只支持 Wiki pages、skill 走原子 add/update,均无“捞 workspace 产物”语义)。
-
-来源清单(`_build_sources`)生成每源紧凑清单(文件数、字节数、扩展名分布,作为 prompt 里的 Source inventory),模型据此在 prompt 指导下自行完成 survey 与定向精读。
-
-## 7. AgentLoop 输出协议
-
-Compile 不实现第二套 loop。VikingBot 在现有 `AgentLoop._run_agent_loop()` 上提供薄的 `run_structured_task()` 入口,并复用已有参数:
-
-```python
-await agent_loop.run_structured_task(
- system_prompt=compile_system_prompt,
- user_prompt=compile_user_prompt,
- session_key=SessionKey(type="compile", channel_id=task_id, chat_id=task_id),
- tool_registry=request_tools,
- openviking_tool_names=openviking_read_tool_names,
- stop_tool_names=["submit_wiki_bundle"],
- openviking_connection=connection,
-)
-```
-
-BotCompileService 使用当前 provider/config、`workspace=task_workspace` 和 task-local `SandboxManager` 创建 request-local `AgentLoop`。`run_structured_task()` 用显式的 system/user prompt 建立 messages 后委托给 `_run_agent_loop()`;后者增加可选 `tool_registry` 和 `openviking_tool_names` 参数,并以选定 registry 同时生成 definitions 和执行工具。只有名称属于 `openviking_tool_names` 的现有 OV adapter 才在 `ToolContext`/post-call hook 中收到用户 connection;file 和 shell tool 收到 `None`。普通 chat 未传这些参数时仍使用 `self.tools` 和现有 connection 行为。
-
-该入口不使用普通 chat history、自动 memory/experience recall 或普通最终回答。只有 `submit_wiki_bundle` 成功执行并保存合法 bundle 后才能结束;参数校验或领域校验返回 `Error:` 时继续同一 loop 修复。只有自然语言而没有 submit 时,wrapper 追加提交提醒后继续;达到 `bot.agents.max_tool_iterations` 配置的 iteration limit(默认 50)时,不执行现有聊天路径的“禁用工具后再回答一次”。Resource 目标会先在独立、受限的 salvage 阶段尝试保存符合条件的 workspace 产物:存在可保存产物时任务以 `completed/salvaged` 结束,否则返回 `AGENT_OUTPUT_INVALID`;Memory 和 Skill 目标直接返回 `AGENT_OUTPUT_INVALID`。模型调用、工具执行和 token usage 仍沿用现有实现。
-
-现有 `_run_agent_loop()` 的 stop 判定需要从“出现 stop tool name”改成“该 stop tool 的结果通过 `_is_tool_result_success()`”;这是 structured task 正确重试的必要条件,默认聊天未传 `stop_tool_names`,行为不变。
-
-`request_tools` 仍使用现有 `ToolRegistry` 中的工具实例;OpenViking 权限不在 Bot 中模拟,实际调用继续由 Server 校验。`submit_wiki_bundle` 最后注册。Skill 的文件操作和 CLI 命令继续在 task-local `SandboxManager` 中执行;Prompt 明确要求将 Bash、shell 或 CLI 指令交给 `exec`。
-
-当 `write_file` 可用时,artifact 必须先由 `write_file` 或 `exec` 生成到 task workspace,再通过 `workspace_path` 提交;Wiki page body 同样先写到 `__compile_staging__/wiki_pages/`,再通过 `body_workspace_path` 提交。此时 `submit_wiki_bundle` 的动态 schema 不暴露内联 `content` / `body_markdown`,运行时也执行相同校验,避免大型多文件产物被拼进单次 tool call。
-
-Agent 必须通过 `submit_wiki_bundle` 提交最终结果。
-
-核心结构:
-
-```python
-class WikiPageDraft(BaseModel):
- page_id: int
- title: str
- page_type: str
- summary: str
- body_markdown: str
- source_ids: list[str]
- tags: list[str] = Field(default_factory=list)
- path_hint: str | None = None
- update_uri: str | None = None
-
-class WikiBundleDraft(BaseModel):
- pages: list[WikiPageDraft]
- links: list[WikiLink] = Field(default_factory=list)
-```
-
-`WikiLink` 直接复用 `openviking.session.memory.dataclass.WikiLink` 做运行时校验,使用其 `f/t/link_type/weight/match_text/description` 字段,不定义 compile 专属 link model。`submit_wiki_bundle` 的 tool schema 将 `match_text` 描述覆盖为“必须出现在来源草稿正文中的锚点”,避免沿用 Memory 模型中“original conversation”的提示语义。
-
-约束:
-
-- `pages=[]` 表示没有足够依据生成可靠页面,此时 `links` 必须为空,任务成功但返回 warning;
-- `page_id` 在 bundle 内唯一;
-- `update_uri` 必须来自目标 catalog;
-- update 保持原 URI,不能通过 `path_hint` rename 或 move;create 的 `path_hint` 只能是 `to` 下的相对 Markdown 路径;
-- create 的最终 canonical path 不能与 catalog 中的已有文件或本 bundle 的其他页面冲突;
-- link 的 `f/t` 必须非空、非 self-link,并引用 bundle 中的页面;
-- `pages` 非空时,每个页面至少引用一个 `source_id`,且必须来自本次请求的来源描述;
-- Agent 不提供最终文件 URI,也不能直接写入 OpenViking。
-
-Pydantic model 使用 `extra="forbid"`;字段校验和 CompileLimits 都在 `submit_wiki_bundle` 内执行。校验失败时,工具将错误返回给 Agent 修复。达到迭代上限仍未提交合法结果时,Resource 目标按上述规则尝试 salvage;其他目标或没有合格 workspace 产物的 Resource 任务失败。
-
-页面数量由 instruction、Skill 和材料决定。高层总结可以只生成一个页面,`link_count=0` 是合法结果。
-
-## 8. Wiki 渲染与写入
-
-VikingBot renderer 将 `WikiBundleDraft` 转成最终写入计划。Compile 新代码只负责 OKF、目标路径和 citation 规则,其余复用现有内容模型:
-
-1. 解析已有 OKF frontmatter;Memory 目标先用 `MemoryFileUtils.read()` 分离可见文档与 hidden metadata,Resource 目标不生成 `MEMORY_FIELDS`。
-2. 将现有 `ExtractLoop._resolve_links()` 中 page ID 解析、self-link 和去重的纯逻辑提取为共享 helper;Compile 使用严格校验模式。
-3. 使用 `LinkRenderer` 已有的 anchor 查找、竞争处理和 escaping 生成相对 WikiLink,并补充 canonical target-root 相对路径与 Markdown protected span 两个纯 helper。
-4. 确定性生成 OKF v0.1 concept frontmatter、目标路径和 citation section,Agent 不直接生成 YAML。
-5. Memory 目标把 resolved `StoredLink` 合并到 `links/backlinks`、复用 resource refs helper,并用 `MemoryFileUtils` round-trip metadata;Resource 目标只存储 OKF Markdown。
-6. Resource checkout 直接形成最终写入集合;服务端以 `upsert` 写回,不在 Compile 层计算 hash 或区分 create/update。
-
-### 8.1 OKF 与 metadata
-
-v1 以 [Open Knowledge Format v0.1 Draft](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md) 为格式基线。每个 Compile 页面都是 UTF-8 Markdown concept document:YAML frontmatter 中 `type` 必填;OpenViking 额外要求 `title` 和单行 `description` 非空,`tags` 可选。
-
-字段映射固定为:
-
-| Draft | OKF frontmatter |
-| --- | --- |
-| `page_type` | `type` |
-| `title` | `title` |
-| `summary` | `description` |
-| `tags` | `tags`,trim、去空并稳定去重;空列表不输出 |
-
-renderer 使用 `yaml.safe_dump(allow_unicode=True, sort_keys=False)` 生成 YAML,拒绝 `body_markdown` 中的第二份 frontmatter。`title`、`page_type` 和 `summary` trim 后必须非空,`summary` 不允许换行。update 保留不与上述平台字段冲突的未知 frontmatter 字段;不自动生成 `timestamp`,避免重复执行仅因时间变化产生更新。
-
-只有 Memory 目标使用 `MemoryFileUtils` round-trip `MEMORY_FIELDS`。create 写入 `category=page_type` 和 `version=1`;update 保留未知字段、同步 `category`,先以原 version 生成 candidate,除 version 外的最终 raw bytes 发生变化时才通过 `next_memory_version()` 推进 version。为避免 hidden links 再次命中 frontmatter,`MemoryFileUtils.write()` 增加默认保持现状的 `render_links=True` 参数,Compile 在已经渲染可见正文后以 `render_links=False` 调用。Resource 目标不写 `category`、`version` 或其他 Memory metadata。
-
-concept 页面不写 `okf_version`;该字段按 OKF 只能出现在 bundle-root `index.md`。v1 不生成或修改 `index.md`、`log.md`,但保留目标中已有的这些文件。API/result 中的 `okf_version: "0.1"` 表示本次 renderer 的目标规范版本。
-
-### 8.2 路径、链接与 Citations
-
-create 的目标路径通过 `sanitize_relative_viking_path()` 和 `safe_join_viking_uri()` 约束在 canonical `to` 下;`path_hint` 为空时使用 `VikingURI.sanitize_segment(title)`,并自动追加 `.md`。点号文件、`index.md`、`log.md`、OpenViking 派生文件名和清洗后的重复路径均拒绝。update 始终使用已有 URI。
-
-bundle link 的两端必须是本次提交的页面。`match_text` 必须实际命中来源页面的 `body_markdown`,且命中位置不能位于 YAML、代码块、inline code、已有 Markdown link 或 Citations section;renderer 只对正文做 link rendering,再拼接 frontmatter 和 Citations。它使用 target-root-aware 相对路径生成标准 Markdown link,未渲染出的 link 不计入 `link_count`。Resource 目标只保留可见链接;Memory 目标还将 resolved link/backlink 合并进 `MEMORY_FIELDS`,但 v1 不写独立 relation store。
-
-renderer 把每页 `source_ids` 映射为用户传入的 canonical source directory URI,并在可见正文末尾合并成唯一的顶层 `# Citations`。已有 citation 先保留,再按 canonical target 去重追加本次来源;最终统一渲染为连续的 `[n] [label](target)` 列表,来源目录使用 canonical URI 的末级目录名作为 label,无法取得时回退为 `Source src_n`。代码块中的同名标题不视为 citation section。Agent 也可以在正文中引用来源范围内的具体文件 URI,这些 Markdown citation 的 label 和 target 会被保留并参与去重。`viking://` 是 OpenViking 对 citation target 的内部扩展,其他 OKF consumer 未必能够解析该 scheme。
-
-写入使用通用内容接口。它是现有内容写入能力的批量入口,不实现新的存储或索引协议:
-
-```http
-POST /api/v1/content/batch-write
-```
-
-```json
-{
- "root_uri": "viking://resources/团队知识库",
- "wait": false,
- "timeout": 300,
- "operations": [
- {
- "uri": "viking://resources/团队知识库/成本优化月度进展.md",
- "content": "...",
- "mode": "upsert"
- },
- {
- "uri": "viking://resources/团队知识库/既有页面.md",
- "content": "...",
- "mode": "upsert"
- }
- ]
-}
-```
-
-`content` 是 checkout 中的最终 UTF-8 存储内容。接口支持 `replace`、`append`、`create` 和 `upsert`,不支持 delete;请求限制 operation 数量、单文件字节数和总字节数。
-
-Batch write 负责:
-
-- 要求 `root_uri` 和 operation URI 都是规范 URI,且 `root_uri` 是已存在的可写目录;拒绝空 operations、重复 URI、跨 context type 以及 root 之外的目标,并按 URI 稳定排序;
-- 校验用户对每个目标 URI 的写权限;
-- 保证目标 URI 位于 `root_uri` 下;
-- 在目标 tree lock 内按每个 operation 的 mode 调用与单文件 `write()` 相同的底层写入逻辑;`upsert` 对已有文件执行 replace,对缺失文件执行 create;
-- 完成全部底层写入后,以整批 `changed_uris` 刷新语义和向量索引;
-- resource/skill 按 refresh root 合并变更,每个 root 只提交一个包含全部变更的 `SemanticMsg`,由现有 semantic pipeline 自底向上更新 `.abstract.md` 和 `.overview.md`;
-- memory 为变更文件分别更新 embedding,但每个受影响目录只调用一次 `refresh_schema_overview()`;
-- 将本批次产生的 refresh 工作绑定到同一个 `RequestWaitTracker`,当 `wait=true` 时统一等待一次。
-
-实现调用链:
-
-```text
-content.batch-write router
- -> validate_viking_uri / current-user shorthand expansion / existing target-shape check
- -> LockManager target tree lease
- -> resolve each operation mode (`upsert` -> `replace` or `create`)
- -> for each operation: shared write-in-place helper
- -> collect changed_uris and group them by refresh scope
- -> release target tree lease
- -> register one request in RequestWaitTracker
- -> existing ContentWriteCoordinator / MemoryUpdater refresh helpers
- -> one RequestWaitTracker waits for the batch's semantic and embedding work
-```
-
-Batch coordinator 放在现有 `openviking/storage/content_write.py` 附近,并从 `ContentWriteCoordinator` 下沉双方共同使用的 target validation、SemanticMsg 构造和 refresh helper。单文件 `write()` 与 batch 使用同一组底层实现,不复制 namespace、锁、Memory、semantic 或 embedding 逻辑。Batch coordinator 不得针对每个 operation 循环调用高层 `ContentWriteCoordinator.write()`,否则每个文件都会独立触发并等待 refresh;它必须先完成所有底层写入、释放 tree lock,再对汇总后的变更执行一次批量 refresh 编排,避免 semantic processor 与请求持有的 tree lock 相互阻塞。
-
-Memory 现有 `refresh_schema_overview()` / `refresh_file_embedding()` 会记录 warning 后吞掉部分异常。Batch 路径需要为共享 helper 增加保持旧调用行为的 `strict=False` 默认值,并以 `strict=True` 调用;overview、semantic 或 embedding 任一登记工作失败,或 `wait=true` 得到 failed queue status 时,batch 返回失败,Compile task 不能标记 completed。
-
-该接口不是跨文件原子存储事务:底层 I/O 在中途失败时可能已有少量文件可见。错误路径必须释放 tree lock,并为已成功写入的 `changed_uris` 触发一次 refresh;调用方可重试同一组 `upsert` operation。
-
-成功响应使用 OpenViking 标准 envelope:
-
-```json
-{
- "status": "ok",
- "result": {
- "created": ["viking://resources/团队知识库/新页面.md"],
- "updated": ["viking://resources/团队知识库/既有页面.md"],
- "unchanged": [],
- "queue_status": {}
- }
-}
-```
-
-Bot 以该响应为最终提交事实,不根据请求计划假定所有文件都已写入;最终 Compile result 将 renderer 预先识别的 unchanged 与 batch 响应中的 unchanged 合并、稳定去重。
-
-任一页面在读取后被其他请求修改时,本次写入以 `WRITE_CONFLICT` 失败,不覆盖新内容。
-
-## 9. 身份与安全
-
-OpenViking Bot proxy 认证 CLI 请求,并将当前用户的 OpenViking connection 转交给 VikingBot。VikingBot 使用同一身份完成所有读取和写入。
-
-OpenViking proxy 复用 `bot.py` 现有 Bot URL、httpx client、Gateway Token、身份附加和错误映射。VikingBot compile router 复用 `OpenAPIChannel._verify_gateway_request()` 和 `OpenVikingConnection`,不定义第二套 Gateway 认证或 principal 格式。
-
-安全要求:
-
-- task 查询校验创建者身份;
-- API key 只存在于运行中任务的内存,不写入 task store 和日志;
-- Agent 的 OpenViking 读取范围只包含 `from`、`to` 和 Skill;
-- OpenViking adapter 的写入和删除工具不进入 request registry;Compile 管理的 Wiki 写入只能由 batch-write 完成;
-- 用户 connection 只注入 scope-guarded OpenViking read adapter,不传给 file 或 shell tool;
-- Compile 忽略 Skill 的 `allowed-tools`,固定工具集合中的 `exec` 可能产生 Compile 之外的副作用,不纳入 batch-write 的一致性保证;
-- Compile Prompt 明确把来源正文、catalog 和工具结果视为待整理数据,不能把其中的文本当作指令;只有用户的 instruction、所选 Skill 和系统 Compile 规则构成指令层;
-- file tool 只能访问 task workspace;shell 的隔离强度取决于 backend,多用户部署必须关闭 `direct` Compile exec 或使用隔离 backend;
-- 最终 URI、写入条件和 metadata 由可信代码生成;
-- 日志不记录 source 正文、Skill 正文、完整 Prompt 或凭证。
-
-远程使用时,Bot 运行在 OpenViking Server 一侧。CLI 不在用户本机启动 Bot。
-
-## 10. 任务存储与并发
-
-Compile task 保存在 VikingBot 的 `bot_data_path/compile_tasks/`,包含:
-
-```text
-task_id, principal_scope, sanitized_request, status, stage, timestamps, result, error
-```
-
-Bot 当前没有通用的持久化后台任务管理器,因此这里实现一个最小 JSON task store,使用 per-task lock 和临时文件原子替换。进程内以有界的 `asyncio.Task` 集合和 semaphore 承载 accepted task;全局和单 principal admission 在任务创建前计数,超限同步返回 `RESOURCE_EXHAUSTED`。现有 `SessionManager` 继续只管理 chat JSONL,不承载 Compile 状态。
-
-`sanitized_request` 只包含 canonical `from/to/skill` 和 effective instruction;`openviking_connection` 仅由运行中 `asyncio.Task` 持有,不进入 JSON、异常详情或日志。
-
-运行中任务目录可以保存有大小限制的 Skill 快照、catalog 和 draft,但不能保存用户凭证。任务进入终态后删除 workspace、Skill snapshot 和 draft;task/result/error JSON 最长保留 24 小时且最多保留 1,000 条,启动和任务结束时都会清理。
-
-VikingBot 使用独立的 compile 并发限制,并对同一 canonical 目标目录串行执行。accepted task 最多排队 60 分钟,取得 target lock 和全局执行 slot 后持续运行,直到任务完成、失败或被取消。Agent 阶段达到迭代上限时允许 salvage;salvage 与 cleanup 各自受独立的短 grace deadline 约束。该锁只减少同一 Bot 进程内的浪费;跨进程或人工写入冲突仍由 batch-write 的 tree lock 和 content hash 检查解决。v1 task store 以单个 VikingBot gateway 进程为部署边界,不承诺多副本共享 task 查询。
-
-VikingBot 启动时把 store 中所有非终态任务统一标记为 `BOT_RESTARTED`,包括处于 committing 的任务;因为 API key 不落盘,重启后不能安全恢复原任务。用户可以重新提交,batch-write 通过最终 content hash 跳过已落盘内容并继续收敛。
-
-### 10.1 v1 资源上限
-
-v1 先使用集中定义、可测试的 `CompileLimits`,不把常量散落在 router/tool/renderer 中:
-
-| 项目 | 默认值 |
-| --- | --- |
-| source roots | 16 |
-| source materialization files / 总大小 | 5,000 / 1 GiB |
-| Skill files / 单文件 / 总大小 | 128 / 8 MiB / 32 MiB |
-| target inventory entries / relevance catalog pages | 2,000 / 10 |
-| initial prompt characters | 200,000 |
-| tool URI count / 单次结果 / 任务累计结果 | 32 / 1 MiB / 8 MiB |
-| output pages / files / combined operations / 最终总大小 | 128 / 128 / 256 / 4 MiB |
-| concurrent Compile tasks / task runtime maximum and default | 10 / 60 min |
-| salvage / cleanup grace | 120 sec / 40 sec |
-| accepted tasks(全局 / 单 principal)/ queue wait | 40 / 10 / 60 min |
-| terminal task retention / records | 24 h / 1,000 |
-
-OpenViking batch-write 自己还要设置独立的 request 上限,至少覆盖 Compile 的 256 combined operations / 4 MiB,但不能信任 Bot 已经做过限制。超限统一返回 `RESOURCE_EXHAUSTED`。
-
-## 11. 错误处理
-
-| code | 场景 |
-| --- | --- |
-| `INVALID_ARGUMENT` | 参数缺失或 URI 格式错误 |
-| `UNAVAILABLE` | Bot 未启用或不可达;与现有 `ov chat` 一致 |
-| `PERMISSION_DENIED` | 无权读取来源或写入目标 |
-| `NOT_FOUND` | 来源、Skill、任务不存在,或 task 不属于当前用户 |
-| `SKILL_INVALID` | Skill 结构或引用不合法 |
-| `SKILL_CAPABILITY_UNAVAILABLE` | Skill 声明的 requirement 或 tool 不可用 |
-| `AGENT_OUTPUT_INVALID` | Agent 未提交合法 bundle |
-| `MODEL_UNAVAILABLE` | 模型服务不可用 |
-| `WRITE_CONFLICT` | 目标页面在任务期间发生变化 |
-| `WRITE_FAILED` | 内容写入或索引刷新失败 |
-| `RESOURCE_EXHAUSTED` | Skill、catalog、工具输入或输出超过 Compile 上限 |
-| `DEADLINE_EXCEEDED` | Agent、batch refresh 或 CLI 等待超时 |
-| `BOT_RESTARTED` | Bot 重启中断了非终态 Compile 任务 |
-
-同步参数和服务错误沿用 OpenViking 标准 HTTP error code。任务执行错误通过 task 的 `status=failed` 和 `error` 返回;其中 batch API 的标准 `CONFLICT` 在 Compile task 中映射为更具体的 `WRITE_CONFLICT`。
-
-## 12. 代码改动
-
-### CLI
-
-- `crates/ov_cli/src/main.rs`:注册 `compile` 子命令;
-- `crates/ov_cli/src/commands/compile.rs`:使用 `CliContext`/`HttpClient` 请求和轮询,使用全局 `OutputFormat`/`output_success()` 输出;
-- `crates/ov_cli/src/commands/mod.rs`:导出 command;
-- `crates/ov_cli/src/client.rs`:增加 compile create/status 的 typed request 方法;
-- `crates/ov_cli/src/help_ui.rs`:增加命令说明和示例。
-
-### OpenViking
-
-- `openviking/server/routers/bot.py`:基于现有 Bot proxy helper 增加 compile 创建和查询请求;
-- `openviking/server/routers/content.py`:提供 batch write API;
-- `openviking/service/fs_service.py`:暴露 batch coordinator,保持 router 不直接操作 VikingFS;
-- `openviking/core/skill_loader.py`:继续兼容解析 `allowed-tools`,Compile 不消费该字段;
-- `openviking/storage/content_write.py`:在现有 target validation、锁和 refresh helper 上增加 batch coordinator;
-- `openviking/session/memory/`:仅下沉 Link、Memory 或 refresh 双方共用的小型纯 helper,为 `MemoryFileUtils.write()` 增加兼容默认值的 link-render 开关,并为 refresh 增加默认关闭的 strict 失败传播;
-- `sdk/python/openviking_sdk/client.py`:为 Bot 使用的现有 async/sync HTTP client 增加 `batch_write()` 和 Skill 辅助文件 download 方法。
-
-### VikingBot
-
-```text
-bot/vikingbot/compile/
- models.py
- router.py
- service.py
- store.py
- renderer.py
-```
-
-`service.py` 只编排现有 Skills API/loader、OpenViking tools、AgentLoop 和 batch-write client;不为这些能力增加一层同义 wrapper。只有某部分出现独立状态或被第二个调用者复用时再拆文件。
-
-同时对现有模块做小型扩展:
-
-- `bot/vikingbot/agent/loop.py`:为 `_run_agent_loop()` 增加可选 request registry,并提供薄的 `run_structured_task()`;
-- `bot/vikingbot/channels/openapi.py`:接收 `BotCompileService` 并用现有 Gateway auth/principal resolver 注册 compile router;
-- `bot/vikingbot/agent/tools/`:增加 `submit_wiki_bundle` 和 request-local URI scope guard;
-- `bot/vikingbot/openviking_mount/ov_server.py`:在现有 request-scoped `VikingClient` 上薄封装 Skills/read/download/batch-write 调用;
-- `bot/vikingbot/cli/commands.py`:gateway 先构造共享 provider/config 所属的 AgentLoop,再创建 `BotCompileService` 并注入 OpenAPIChannel;不增加全局 service holder。
-
-## 13. 测试与验收
-
-至少覆盖:
-
-- CLI 参数展开、默认 instruction 和 Task ID 返回;
-- Bot proxy 的创建/GET 查询身份转交、未启用 Bot 的 503 和上游错误;
-- Skill 复用现有 parser/loader、相对引用、requirements 和路径逃逸检查;`allowed-tools` 可正常解析但不影响 Compile 工具集合;
-- request registry 固定包含本地核心工具、scope-guarded OpenViking 只读工具和 `submit_wiki_bundle`,不包含 message/cron/spawn/Web/image/MCP/OV write,用户 connection 只进入 OV read adapter;
-- Agent structured wrapper 复用原 loop;失败 submit 不停止、plain text 会修复、iteration limit 不额外生成普通回答,Resource 目标只 salvage 合格产物,普通 chat 行为不回归;
-- OpenViking 工具的 URI scope、缺省全库参数和数量/单次/累计输出上限,并确认没有注册第二组 source tools;
-- 非法 bundle 的 loop 内修复、空 bundle no-op 和最终失败;
-- 单页面零 link、多页面互链和已有页面更新;
-- OKF frontmatter、保留未知字段、Resource/Memory 格式差异、protected anchor、路径 containment、citation merge、WikiLink、Memory version 和 resource refs;
-- batch-write 复用现有锁/write/refresh helper,覆盖 canonical URI/重复 operation、权限、content hash conflict、响应丢失/refresh 失败/部分写入后的安全重试,并验证释放 tree lock 后才 refresh;
-- 多文件 resource 每个 refresh root 只产生一个 SemanticMsg,memory 每个目录只刷新一次 overview,strict refresh 失败不会返回成功;
-- task owner 隔离、同目标并发、终态 workspace 清理和 Bot 重启时所有非终态任务失败。
-
-验收命令:
-
-```bash
-ov compile \
- --from viking://resources/周报 \
- --to viking://resources/团队知识库 \
- --instruction "按月整理团队的成本优化进展" \
- --skill viking://agent/skills/monthly_wiki
-```
-
-验收结果:
-
-1. VikingBot 加载指定 Skill 并运行 Compile AgentLoop。
-2. 目标目录生成符合 OKF v0.1 的 Wiki 页面。
-3. 重复执行只创建或更新发生变化的页面;最终 raw bytes 相同时不 write、不推进 Memory version。
-4. 未触达的已有页面保持不变。
-5. 多页面通过一次 batch-write 提交,并按 refresh scope 合并刷新。
-6. 未启用 Bot 时命令返回与 `ov chat` 一致的明确错误。
diff --git a/docs/design/ov-kanban.md b/docs/design/ov-kanban.md
deleted file mode 100644
index f31c765c1..000000000
--- a/docs/design/ov-kanban.md
+++ /dev/null
@@ -1,100 +0,0 @@
-# ov-kanban:把结构化 handoff 做成 OpenViking 上的看板
-
-| 项目 | 信息 |
-| --- | --- |
-| 状态 | 可用(skill 已落地,herdr 演练通过) |
-| Skill | `agent-plugins/skills/ov-kanban/`(原名 `ov-tasks`,PR #5157) |
-| 存储 | `viking://agent/kanban/<board>/<id>.md`;server 拒绝时兜底 `viking://resources/kanban`(见下) |
-| 更新日期 | 2026-09-29 |
-
-## 一句话
-
-一个看板 = OV 里的一个目录,存放多个任务。一个任务 = 一个 markdown 文件:frontmatter 头(id/status/owner/board/updated)+ 固定七段正文(Goal/Context/Decisions/Progress/Next/Questions/Log)。文件本身就是 handoff,任何有 `ov` CLI 的 agent 读到就能继续,每轮结束整文件写回。过程详情折叠进 `archive/<id>.md`,不删除。没有其他状态。
-
-## 改名原因(2026-09-29)
-
-| 原因 | 说明 |
-| --- | --- |
-| 与 CLI 重名 | `ov task list` 指 server 的异步处理任务,`ov-tasks` 与之混淆 |
-| 容器语义 | 看板存放多个任务;`tasks` 这个名字指不出容器 |
-| `scope` 让位 | 原 `<scope>` 目录改称 `<board>`;`scope` 留给 roadmap 的 scoped kanban(看板声明自己关联的目录、分支) |
-
-## 折叠,不压缩
-
-长任务跨多个会话,状态必须在会话之外。压缩(摘要后丢弃原文)会丢掉下一轮需要的细节。ov-kanban 把过程折叠成层,agent 自上而下读,读到能回答问题的那一层为止。
-
-| 层 | 内容 | 读取 |
-| --- | --- | --- |
-| 看板列表 | 每个看板一条摘要 | `ov ls <root>` |
-| 看板视图 | 每个任务的 title/status/owner/updated | `ov grep '^(title\|status\|owner\|updated):'`,一次调用 |
-| 任务文件 | 当前状态,足够继续工作 | `ov read` |
-| archive | 从任务文件移出的原文:被替换的 Next/Decisions、10 行以外的 Log、超过一行的证据 | 按需 `ov grep` / `ov read` |
-
-不变量:文本只能通过移入 archive 离开任务文件。PR #5157 的版本里 `Log` 只保留最近 10 行(其余丢弃)、archive 为可选,本次改为上述规则。
-
-## 与 PowerContext / LoopX 的对应
-
-| 概念 | PowerContext | LoopX | ov-kanban |
-| --- | --- | --- | --- |
-| 隔离边界 | Scope(server 生成的 opaque id) | Goal + project registry | `<root>/<board>/` 目录,`ov acl` 管权限 |
-| 目标与完成边界 | Work Contract | Objective + Operating Contract | `## Goal` 验收清单 + `## Context` |
-| 交接内容 | Prepared/Committed Handoff | ACTIVE_GOAL_STATE.md | 任务文件全文 |
-| 待办 | — | Agent Todo / User Todo | `## Next` 清单 / `## Questions` + `status: needs_user` |
-| 用户门 | Acknowledgement needs clarification | user gate | `status: needs_user`,agent 在会话内向用户提问并停下 |
-| 证据 | Source / Task Outcome | evidence + Progress Ledger | `## Progress`(只写已验证条目,带证据)+ `## Log` |
-| 所有权 | receiver acknowledgement | claim / lease | `owner` + `updated`;超过 2h 未更新视为可重新认领 |
-| 历史 | 不可变 Revision + lineage | run history | `archive/<id>.md`,追加式;status 变化和折叠出的原文都写入 |
-| 长期运行 | — | quota + scheduler + kernel | `references/loop.sh`:一轮一次 agent 调用,直到无可跑任务或轮数用尽 |
-| 跨 agent | 同 Scope 内继续 Handoff | peer agents + writeback | 同一文件;agent id 写在 `owner` |
-| 检索 | Handoff Report | `loopx status` | 看板视图(`ov grep`)、`ov find`、`ov ls` |
-
-## 丢弃的概念与原因
-
-| 丢弃 | 原因 |
-| --- | --- |
-| LoopX Kernel / Capability / Provider / Extension 分层 | OV 只负责存储与检索;执行方是任意 CLI agent。分层没有承载者,30 行 loop.sh 覆盖"一轮一 tick"。 |
-| LoopX quota / 调度 / 自修复 | 用 `max_ticks` 一个数字替代。任务不会自旋,因为每轮必须写回且 needs_user 不可跑。 |
-| LoopX typed claim / lease / 原子 writeback | OV write 没有 CAS。用 `owner`+`updated` 的 2h 约定替代,并在 skill 中写明。并发同一任务是已知上限。 |
-| PowerContext 不可变 Revision / lineage / Acknowledgement / Task Outcome | 四个对象折叠为一个可变文件 + 追加式 archive。Acknowledgement = claim 时写 Log;Outcome = 最终 status + Progress。 |
-| PowerContext Candidate 审核、Experience/Skill 家族 | 与 handoff 无关;经验沉淀走 OV 已有的 `remember`。 |
-| PowerContext opaque scope id | OV URI 本身就是 scope 且带 ACL,不需要第二套 id。 |
-| Dashboard / Lark 看板投影 | `ov ls`、`ov tui`、`ov find` 已够;需要时再做。 |
-| retrieval tags 镜像 status/owner | 云端 0.4.17.3 的 write 不接受 `--tags`,需要第二次 `set-tags` 调用;frontmatter + `ov grep` 已能过滤,避免双写漂移。 |
-
-## 存储位置:viking://agent/kanban 优先,探测失败兜底 viking://resources/kanban
-
-| 事实 | 证据 |
-| --- | --- |
-| 云端 server 拒绝 `viking://agent/<非 skills>` 的 mkdir/write(v0.4.17.3 用 `agent/tasks` 验证;2026-09-29 `loop.sh` 探测 `agent/kanban` 同样退回兜底) | `PERMISSION_DENIED: viking://agent/{agent_id} is deprecated. Use viking://user/.../peers/{agent_id}` |
-| main 分支 namespace 只把 `agent/skills` 视为内容目录 | `openviking/core/namespace.py:16` `_CONTENT_TYPES_BY_SCOPE["agent"] = {"skills": "skill"}`;`viking://agent/<其他目录>/x.md` 得到 `context_type=resource`,main 上无显式写保护 |
-| `viking://resources/kanban` 在云端可用:create / read / append / grep 均通过 | 本文演练;原 `viking://resources/tasks` 已于 2026-09-29 用 `ov mv` 迁入 |
-
-开源 main 已允许在 `viking://agent` 下新建目录。skill 与 loop.sh 每次先 `ov stat`/`ov mkdir viking://agent/kanban` 探测,失败才退回 `viking://resources/kanban`;`OV_KANBAN_ROOT` 可强制指定。协议与 root 无关。
-
-## `ov compile` 接入(下一步)
-
-目标:`ov compile --from <root>/<board> --to <root>/<board> --skill viking://agent/skills/ov-kanban`,由 VikingBot 按 skill 执行一轮并把任务文件写回。
-
-| 阻塞点 | 位置 |
-| --- | --- |
-| `--to` 只允许 resource/memory/skills 目录 | `openviking/service/compile_service.py:464` `_validate_target`(`viking://agent/kanban/<board>` 需放行) |
-| `--from` 必须是目录 | `compile_service.py:446`,单任务文件需放行文件源,或约定 from = board 目录 + `--instruction "task <id>"` |
-| Compile agent 的产物是 wiki bundle(`submit_wiki_bundle`) | 需要一个"原地改写源文件"的输出工具;改动在 VikingBot 侧 |
-
-建议顺序:先把 `ov-kanban` 用 `ov add-skill agent-plugins/skills/ov-kanban -p viking://agent/skills` 装到 OV,再改 compile 的两处校验,最后补写回工具。
-
-## Roadmap
-
-任务 DAG(`blocked_by`)、scoped kanban、会话启动召回、claim-aware loop、原子 claim、`ov compile`,见 [skill README](https://github.com/volcengine/OpenViking/blob/main/agent-plugins/skills/ov-kanban/README.md#roadmap)。
-
-## 演练记录(2026-09-18,herdr,board `demo`)
-
-演练时 skill 名为 `ov-tasks`,存储在 `viking://resources/tasks/demo`。
-
-| 轮 | 执行者 | 动作 | 结果 |
-| --- | --- | --- | --- |
-| A | codex(`codex exec`) | 认领 `wc-top`,只做 Next 第一项,验证后 handoff(status open、owner 清空) | 文件写回正确;archive 记录 open→in_progress→open;脚本可运行 |
-| B | claude(`claude -p`) | 读 A 的 handoff 继续,补测试和 README | status done,Goal 三项全勾且带证据;本地复跑 `pytest` 4 passed |
-| C | `loop.sh demo 4` 驱动 codex | tick1 认领 `makefile`:写好 Makefile,但本机 `make` 被 Xcode license 挡住 → `needs_user` 并写明问题;tick2 认领 `report-format`:输出格式未定 → `needs_user`;tick3 无可跑任务,循环停止 | 两次 user gate 都是真实阻塞,没有假 pass;循环按预期收敛 |
-
-演练中修的两个问题:`write --mode create` 需要 `archive/` 目录先存在(skill 已写明);`ov` 输出 JSON 前有一行 `cmd:`,loop.sh 改为只解析 JSON 行。另外 codex 侧的 OV MCP `write` 会在 15s 超时后仍写入成功,skill 已注明优先用 CLI 并回读确认。
diff --git a/docs/design/parser-two-layer-refactor-plan.md b/docs/design/parser-two-layer-refactor-plan.md
deleted file mode 100644
index 25f01add8..000000000
--- a/docs/design/parser-two-layer-refactor-plan.md
+++ /dev/null
@@ -1,272 +0,0 @@
-# OpenViking 解析器两层架构重构
-
-> 本文是 Accessor / Parser 两层拆分的历史重构记录。当前 `add_resource` 的完整入口分流、Understanding、Connector 与异步执行规则,见 [添加资源后的解析路由](./resource-ingestion-routing.md)。
-
-| 项目 | 信息 |
-|-----|------|
-| 状态 | `已完成` |
-| 创建日期 | 2026-04-13 |
-| 完成日期 | 2026-04-14 |
-
----
-
-## 概述
-
-将原有的单一层 Parser 架构拆分为 **Accessor(数据访问层)** 和 **Parser(数据解析层)** 两层,实现职责分离和代码复用。
-
----
-
-## 目录
-
-- [背景与问题](#背景与问题)
-- [架构设计](#架构设计)
-- [核心抽象](#核心抽象)
-- [实现进度](#实现进度)
-- [文件结构](#文件结构)
-
----
-
-## 背景与问题
-
-### 当前架构的问题
-
-| 问题 | 说明 |
-|-----|------|
-| 平铺式注册 | 所有 Parser 在同一层级,职责不清晰 |
-| 后缀冲突 | `.zip` 可被 `CodeRepositoryParser` 和 `ZipParser` 同时处理 |
-| URL 处理逻辑分散 | `UnifiedResourceProcessor._process_url()` 和 `ParserRegistry.parse()` 都有 URL 检测 |
-| 职责混合 | 部分 Parser 既负责下载又负责解析 |
-
-### 重构目标
-
-1. **职责分离**:数据获取 ≠ 数据解析
-2. **代码复用**:HTTP/Git 下载逻辑可被多个 Parser 复用
-3. **易于扩展**:新增数据源只需添加 Accessor
-4. **解决冲突**:通过优先级机制解决 `.zip` 等后缀冲突
-
----
-
-## 架构设计
-
-### 两层架构
-
-| 层级 | 抽象接口 | 职责 | 示例 |
-|-----|---------|------|------|
-| **L1: Accessor** | `DataAccessor` | 获取数据:远程 URL / 特殊路径 → 本地文件/目录 | `GitAccessor`, `HTTPAccessor`, `FeishuAccessor` |
-| **L2: Parser** | `BaseParser` | 解析数据:本地文件/目录 → `ParseResult` | `MarkdownParser`, `PDFParser`, `ZipParser` |
-
-### 调用流程
-
-```
-add_resource(path)
- ↓
-ResourceProcessor.process_resource()
- ↓
-UnifiedResourceProcessor.process()
- ↓
-┌─────────────────────────────────────────┐
-│ 第一阶段:数据访问 (Accessor Layer) │
-├─────────────────────────────────────────┤
-│ AccessorRegistry.route(source) │
-│ ├─→ GitAccessor (priority: 80) │
-│ ├─→ FeishuAccessor (priority: 100) │
-│ ├─→ HTTPAccessor (priority: 50) │
-│ └─→ LocalAccessor (priority: 10) │
-│ ↓ │
-│ 返回: LocalResource │
-│ (本地路径 + 元数据) │
-└─────────────────────────────────────────┘
- ↓
-┌─────────────────────────────────────────┐
-│ 第二阶段:数据解析 (Parser Layer) │
-├─────────────────────────────────────────┤
-│ ParserRegistry.route(local_resource) │
-│ ├─→ 是目录? → DirectoryParser │
-│ ├─→ 是文件? → 按扩展名匹配 │
-│ │ ├─→ .md → MarkdownParser │
-│ │ ├─→ .pdf → PDFParser │
-│ │ ├─→ .zip → ZipParser │
-│ │ └─→ ... │
-│ └─→ 返回: ParseResult │
-└─────────────────────────────────────────┘
- ↓
-TreeBuilder + SemanticQueue (保持不变)
-```
-
----
-
-## 核心抽象
-
-### 1. LocalResource(数据类)
-
-位置:`openviking/parse/accessors/base.py`
-
-表示一个可在本地访问的资源,是 Accessor 层的输出。
-
-```python
-@dataclass
-class LocalResource:
- path: Path # 本地文件/目录路径
- source_type: str # 原始来源类型 (SourceType.GIT/HTTP/FEISHU/LOCAL)
- original_source: str # 原始 source 字符串
- meta: Dict[str, Any] # 元数据(repo_name, branch, content_type 等)
- is_temporary: bool = True # 是否为临时文件,解析后可清理
-
- def cleanup(self) -> None # 清理临时资源
- def __enter__/__exit__ # 支持上下文管理器
-```
-
-### 2. DataAccessor(抽象基类)
-
-位置:`openviking/parse/accessors/base.py`
-
-```python
-class DataAccessor(ABC):
- @abstractmethod
- def can_handle(self, source: Union[str, Path]) -> bool
- """判断是否能处理该来源"""
-
- @abstractmethod
- async def access(self, source: Union[str, Path], **kwargs) -> LocalResource
- """获取数据到本地,返回 LocalResource"""
-
- @property
- @abstractmethod
- def priority(self) -> int
- """优先级:数字越大优先级越高
- - 100: 特定服务 (Feishu)
- - 80: 版本控制 (Git)
- - 50: 通用协议 (HTTP)
- - 10: 兜底 (Local)
- """
-
- def cleanup(self, resource: LocalResource) -> None
- """清理资源(默认调用 resource.cleanup())"""
-```
-
-### 3. AccessorRegistry
-
-位置:`openviking/parse/accessors/registry.py`
-
-```python
-class AccessorRegistry:
- def __init__(self, register_default: bool = True)
- """初始化注册表,可选是否注册默认 Accessor"""
-
- def register(self, accessor: DataAccessor) -> None
- """注册 Accessor(按优先级降序插入)"""
-
- def unregister(self, accessor_name: str) -> bool
- """注销 Accessor"""
-
- def get_accessor(self, source) -> Optional[DataAccessor]
- """获取能处理该 source 的最高优先级 Accessor"""
-
- async def access(self, source, **kwargs) -> LocalResource
- """路由到合适的 Accessor 获取数据"""
-```
-
-默认注册的 Accessor(按优先级):
-1. `FeishuAccessor` (100) - 处理飞书/ Lark 文档
-2. `GitAccessor` (80) - 处理 Git 仓库
-3. `HTTPAccessor` (50) - 处理 HTTP/HTTPS URL
-4. `LocalAccessor` (10) - 处理本地文件(兜底)
-
----
-
-## 实现进度
-
-### ✅ 已完成
-
-- [x] 创建 `openviking/parse/accessors/` 目录结构
-- [x] 实现 `DataAccessor` 抽象基类和 `LocalResource` 数据类
-- [x] 实现 `AccessorRegistry`(含优先级机制)
-- [x] 实现 `GitAccessor` - 处理 Git 仓库
-- [x] 实现 `HTTPAccessor` - 处理 HTTP URL
-- [x] 实现 `FeishuAccessor` - 处理飞书文档
-- [x] 实现 `LocalAccessor` - 处理本地文件
-- [x] 全局注册表 `get_accessor_registry()`
-- [x] 更新 `PDFParser`、`resources.py`、`local_input_guard.py` 使用新架构
-
----
-
-## 文件结构
-
-```
-openviking/parse/
-├── accessors/ # ✅ 新增:数据访问层
-│ ├── __init__.py
-│ ├── base.py # DataAccessor, LocalResource, SourceType
-│ ├── registry.py # AccessorRegistry
-│ ├── git_accessor.py # GitAccessor
-│ ├── http_accessor.py # HTTPAccessor
-│ ├── feishu_accessor.py # FeishuAccessor
-│ └── local_accessor.py # LocalAccessor
-├── parsers/ # 数据解析层(保持不变)
-│ ├── base_parser.py
-│ ├── markdown.py
-│ ├── pdf.py
-│ ├── zip_parser.py
-│ └── ...
-└── registry.py # ParserRegistry(保持不变)
-```
-
----
-
-## 使用示例
-
-### 使用 AccessorRegistry
-
-```python
-from openviking.parse.accessors import get_accessor_registry
-
-# 获取全局注册表
-registry = get_accessor_registry()
-
-# 访问资源(自动路由)
-async with await registry.access("https://github.com/user/repo") as resource:
- print(f"本地路径: {resource.path}")
- print(f"来源类型: {resource.source_type}")
- # 使用 resource.path 进行解析...
- # 退出 with 块时自动清理临时资源
-```
-
-### 自定义 Accessor
-
-```python
-import tempfile
-from pathlib import Path
-
-from openviking.parse.accessors import DataAccessor, LocalResource
-
-class MyAccessor(DataAccessor):
- @property
- def priority(self) -> int:
- return 90
-
- def can_handle(self, source: str) -> bool:
- return source.startswith("myprotocol://")
-
- async def access(self, source: str, **kwargs) -> LocalResource:
- # 获取数据到本地...
- temp_path = Path(tempfile.mkdtemp(prefix="openviking_"))
- # ... 下载逻辑 ...
- return LocalResource(
- path=temp_path,
- source_type="myprotocol",
- original_source=source,
- meta={},
- is_temporary=True
- )
-
-# 注册
-registry = get_accessor_registry()
-registry.register(MyAccessor())
-```
-
----
-
-## 相关文档
-
-- [解析系统 README](https://github.com/volcengine/OpenViking/blob/main/openviking/parse/parsers/README.md)
-- [OpenViking 整体架构](../zh/concepts/01-architecture.md)
diff --git a/docs/design/resource-ingestion-routing.md b/docs/design/resource-ingestion-routing.md
deleted file mode 100644
index bf27bdb0e..000000000
--- a/docs/design/resource-ingestion-routing.md
+++ /dev/null
@@ -1,334 +0,0 @@
-# 添加资源后的解析路由
-
-本文描述当前 `add_resource` 从收到资源到落盘、建索引的真实执行链。重点回答四个问题:入口在哪里分流、资源类型在哪里确定、Understanding 与 Connector 分别做什么,以及 `wait` 到底等待什么。
-
-## 先记住五条规则
-
-1. 对外只有一个资源添加入口:`ResourceService.add_resource`。SDK、HTTP API、MCP 最终都应调用它;Worker 不再拿后台任务冒充一次新的资源添加请求。
-2. Connector 是一条独立的端到端导入链;Understanding 只是标准链里的一个 Parser 后端。
-3. 普通文件只做一次 Parser 选择。选择依据是 Accessor 获取资源后冻结的 `resolved_extension`,不是临时文件名,也不会在队列消费者里重新猜;原始飞书 URL 是一个显式例外,可在 Accessor 前按配置直达 Understanding。
-4. 目录、网站目录以及内部 Parser 遍历出的子文件不逐个调用 Understanding,统一留在内置 Parser 链内处理。
-5. Watch 是一次新的来源刷新,会重新走提交分流,但不会创建、取消或覆盖自身的 Watch 任务。
-
-## 总流程
-
-```text
-SDK / HTTP API / MCP
- |
- v
-ResourceService.add_resource 对外入口
- |
- v
-ResourceService._submit_resource_ingestion 阶段一:对新请求选择执行方式
- |
- +-- Connector 命中且参数受支持 ------> Connector doc/add
- | |
- | +--> 轮询 Connector task/info
- | +--> Connector 自己解析并写入资源
- |
- +-- Git && wait=false ----------------> 预检 + AddResource 队列 --> 返回 task_id
- |
- +-- HTTP 服务远程资源 && wait=false && Understanding 已启用
- | |
- | +-- 原始 URL 可直达 -----------> 提交 Understanding --> ExternalParse 队列
- | | |
- | | +--> 返回 task_id --> Worker
- | |
- | +-- 需要先确定本地类型 --------> Accessor 下载并识别
- | |
- | +-- 命中 Understanding --> 上传同一文件 --> ExternalParse 队列
- | | |
- | | +--> 返回 task_id --> Worker
- | |
- | +-- 未命中 ------------> 复用 LocalResource,进入当前请求标准链
- |
- +-- 其余场景(包括所有 wait=true) -----> _execute_resource_ingestion
-
-_execute_resource_ingestion 阶段二:执行标准链
- |
- v
-ResourceProcessor.process_resource
- |
- v
-UnifiedResourceProcessor
- |
- +-- 已有 understanding_response_id ----> ParserRouter --> Understanding 恢复任务
- |
- +-- 原始 URL 可直达 Understanding -----> ParserRouter --> Understanding 提交并等待
- |
- +-- 原始文本 --------------------------> 内置 ParserRegistry
- |
- +-- 路径 / URL --> AccessorRegistry.access(选择数据访问器)
- |
- v
- LocalResource
- |
- +-- 目录 --> DirectoryParser(内置)
- |
- +-- 文件 --> ParserRouter.parse(选择 Parser,只选一次)
- |
- +-- 内置 ParserRegistry
- +-- Understanding 上传并等待
- |
- v
- ParseResult --> TreeBuilder 落盘
- |
- v
-阶段三:返回策略
- |
- +-- wait=true --> 继续等待摘要 / 语义队列 / 向量索引后返回
- |
- +-- wait=false --> 普通标准链落盘后进入 AddResource 队列并返回
-
-后台队列 Worker
- |
- +-- source job -----------------------> _execute_resource_ingestion(wait=true)
- | 使用消息中冻结的 backend / response_id / extension
- |
- +-- prepared job ---------------------> finish_prepared_resource
- |
- +-- 不再调用 add_resource,也不再重做 Connector / Git 顶层分类
-
-WatchScheduler
- |
- +-- refresh_resource -----------------> _submit_resource_ingestion(manage_watch=false)
- 重新获取和解析来源,但不修改 Watch 任务
-```
-
-Understanding 不受 `wait=false` 限制。`wait=true` 在当前请求内完成 Understanding 提交、轮询、解析和 TreeBuilder,并继续等待后续队列;`wait=false` 的远程服务路径会先提交 Understanding、将 `response_id` 入队,再由 Worker 恢复任务。
-
-分类发生的位置:
-
-| 分类内容 | 代码位置 | 输出 |
-|---|---|---|
-| Connector、异步 Git、标准执行链 | `ResourceService._submit_resource_ingestion` | 选定新请求的顶层执行方式 |
-| 异步 Understanding 或当前请求内执行 | `ResourceService._execute_resource_ingestion` | 根据 `wait`、配置和已识别类型决定提交还是同步执行 |
-| Feishu、Git、Feed、HTTP、本地文件 | `AccessorRegistry.access` | `LocalResource` |
-| Understanding 能否直接接收原始 URL | `ParserRouter.should_use_understanding_directly` | 直达 Understanding 或继续 Accessor |
-| Understanding 与内置 Parser | `ParserRouter.parse` | `ParseResult` |
-
-后台资源任务统一使用可恢复的 `AddResourceMsg`,但按工作类型进入两个独立队列:Understanding 使用受外部解析并发限制的 `ExternalParse`;Git 和已落盘的本地后处理使用 `AddResource`。两个队列都由 `AddResourceProcessor` 消费,锁接管失败时仍回到原队列。消息已经冻结了生产端做出的选择,例如 `parser_backend`、`understanding_response_id` 和 `resolved_extension`。Worker 直接执行该选择,不再把任务送回公开 `add_resource` 重新分类。
-
-## 顶层路由表
-
-| 输入或场景 | 获取数据 | 解析者 | 是否走标准 `ParseResult -> TreeBuilder` | 返回时机 |
-|---|---|---|---|---|
-| Connector 配置允许的 TOS 或 Git,提供精确 `to` 且参数受支持 | Connector 服务 | Connector 服务 | 否 | 提交成功立即返回 `task_id`,后台轮询状态 |
-| `tos://` 但 Connector 不可用或参数不支持 | 不降级 | 不执行 | 否 | 直接报清晰的参数或配置错误 |
-| Git 未命中 Connector 或无凭证回退,`wait=false` | GitAccessor 在后台 clone | 内置目录/代码仓库 Parser | 是 | 预检仓库并预占 URI 后返回 |
-| Git,`wait=true` | GitAccessor | 内置目录/代码仓库 Parser | 是 | 解析、落盘及语义队列完成后返回 |
-| 飞书 URL,`parser_api.enable_feishu_url=true` 且有 user/app 凭证 | Understanding 直接读取飞书 | Understanding | 是 | `wait=false` 时提交并入队;`wait=true` 时同步解析 |
-| 飞书 URL,直达配置关闭或无可用凭证 | FeishuAccessor | 内置 Markdown Parser | 是 | Accessor 拉取、归一化后走标准链 |
-| HTTP 服务请求,`wait=false`,命中 Understanding | HTTPAccessor 识别类型并上传同一份本地文件 | Understanding | 是 | 类型识别、Understanding 提交、URI 预占和入队后返回 |
-| 其他 URL、文件、目录、原始文本 | 对应 Accessor;原始文本无需 Accessor | 内置 Parser 或同步 Understanding | 是 | 至少完成解析和落盘后返回 |
-
-Git 是 Connector 与标准链共享的来源:未命中 Connector 或参数不受支持时可回退到标准链;一旦请求带有 Connector 专用凭证则禁止回退,避免凭证进入持久化队列。`tos://` 没有标准 Accessor,不能回退,否则只会在更深处得到误导性的解析错误。
-
-## Accessor:先把“数据在哪”变成“本地是什么”
-
-`AccessorRegistry` 按优先级选择数据访问器,当前内置顺序是:
-
-```text
-FeishuAccessor (100)
-GitAccessor (80)
-WebFeedAccessor (60)
-HTTPAccessor (50)
-LocalAccessor (1)
-```
-
-Accessor 的产物统一是 `LocalResource`,包含本地文件或目录路径、`source_type`、原始来源、是否需要清理,以及检测元数据。标准 Parser 不再负责 clone 或下载;只有明确开启的飞书 Understanding 直达链会在 Accessor 前消费原始 URL。
-
-### 飞书资源
-
-飞书是“远程私有数据源”,不是一种本地文件格式。默认使用 `FeishuAccessor` 获取并归一化:
-
-```text
-飞书 URL
- |
- v
-FeishuAccessor --调用飞书 OpenAPI--> Markdown + 下载后的图片
- |
- v
-LocalResource(document.md)
- |
- v
-ParserRouter --> MarkdownParser --> ParseResult --> TreeBuilder
-```
-
-当 `parser_api.enable=true`、`parser_api.enable_feishu_url=true`,并且本次请求有 `args.feishu_access_token` 或服务端已配置飞书应用凭证时,原始飞书 URL 会在 Accessor 前进入统一的 Understanding 链。否则进入上面的 FeishuAccessor 路径。
-
-`enable_feishu_url` 默认是 `false`。Understanding 一旦被选中,提交、轮询或解析失败会直接返回错误,不会在运行时自动重试 FeishuAccessor。
-
-`FeishuAccessor` 预期支持范围如下:
-
-| URL 类型 | Accessor 行为 | 当前边界 |
-|---|---|---|
-| `docx/{token}` | 拉取文档 block,转换标题、列表、代码、表格、图片和内嵌 sheet | 图片下载受 `download_images` 控制;内嵌 sheet 最多读取 100 行、A-Z 列 |
-| `sheets/{token}` | 枚举所有 sheet;普通网格读取单元格,内嵌多维表格根据 `blockInfo` 转走 Bitable API,统一输出 Markdown 表格 | 普通网格最多读取 `max_rows_per_sheet` 行、A-Z 列;内嵌多维表格继承 Base 的记录和图片处理能力 |
-| `base/{app_token}` | 无查询参数时枚举全部数据表;`table` 限定数据表,`table` + `view` 限定视图 | 表和字段完整翻页;每张表最多读取 `max_records_per_table` 条记录;附件字段中的图片会下载,其他附件保留文件名 |
-| `wiki/{token}` | 先解析 wiki 节点的实际类型和 token,再进入上述 `docx`、`sheets` 或 `base` 处理器 | wiki 指向其他飞书对象类型时明确报不支持 |
-
-四类入口都支持应用凭证获取的 tenant token;显式传入 `args.feishu_access_token` 时,同一 user token 会用于本次选中的飞书链路。Accessor 路径中,它用于 wiki 解析、正文、sheet/base 和图片请求;Understanding 直达路径中,它作为 `lark_file.user_access_token` 提交,随后从后台队列参数中删除。
-
-飞书专有的本地归一化逻辑到 `FeishuAccessor` 为止,后面只处理 Markdown,因此不再保留并行的本地 `FeishuParser` 入口。即使 `parser_api.extensions` 包含 `md`,`SourceType.FEISHU` 的 `LocalResource` 也固定使用内置 Markdown Parser,不会把已经拉取的数据再次送 Understanding。传给 Understanding 的本地文件同样优先上传本地内容,`original_source` 只作为来源元数据,不会导致二次抓取原 URL。
-
-Accessor 路径中的文档图片和 Base 附件字段图片使用同一条素材下载链路:先生成内部 `feishu://image/{file_token}` 引用;`download_images` 开启时,再通过飞书 Drive 素材接口下载到 `images/` 并改写 Markdown 相对路径。应用还必须具备 `docs:document.media:download` 权限;关闭下载、权限不足(例如 HTTP 403)或素材请求失败时,不会伪造本地图片文件,也不会把引用改成不存在的本地路径。Understanding 直达路径不调用这套素材接口,而是接收结果 ZIP 中已经包含的图片,并生成 artifact 图片映射供后续 URI 改写。
-
-`UnifiedResourceProcessor.prepare` 随后冻结两个字段:
-
-- `resolved_extension`:本次 Parser 路由唯一使用的扩展名。
-- `resolved_name`:用于展示、默认资源命名和 Understanding 上传文件名,不参与 HTTP 资源的类型覆盖。
-
-HTTP 资源以 HTTPAccessor 检出的 `meta.extension` 为准;本地文件或上传的临时文件可优先使用显式 `source_name` 的扩展名。这样既不会拿随机临时文件名选 Parser,也不会让用户提供的 URL 名称覆盖实际下载内容类型。
-
-本地文件进入 Understanding 时,ParserRouter 将冻结的 `resolved_name` 和 `resolved_extension` 一起传给上传层。上传层使用来源名称的 basename;如果末尾没有已识别的扩展名(忽略大小写),则追加该扩展名,保留名称中的编号和版本信息。例如无后缀 URL `/export?id=123` 返回 `Content-Type: application/pdf` 时,上传文件名为 `export.pdf`;`2601.00014` 会补成 `2601.00014.pdf`,`report.PDF` 保持原样。内部的 MPEG-TS 路由标记转换为真实的 `.ts` 后缀。
-
-普通上传、分片上传和 MIME 类型推断统一使用补全后的上传文件名,本地路径用于读取文件。同步解析、提前提交解析和仅上传获取 `file_id` 使用相同规则。`resource_name` 只控制外层资源目录,例如 `README.md` 下载为 `/tmp/tmpABC.md` 后,上传文件名仍为 `README.md`。
-
-## 无后缀 URL 怎么判断类型
-
-HTTPAccessor 按以下顺序收集和修正类型:
-
-1. URL path 中受支持的显式扩展名。
-2. HEAD 响应的 `Content-Disposition` 文件名。
-3. HEAD 响应的 `Content-Type`。
-4. GET 响应的 `Content-Disposition` 和 `Content-Type`,用于修正之前的模糊网页判断。
-5. GET 内容的 magic bytes,例如 PDF、图片、音视频、Office/EPUB/ZIP 签名。
-6. 仍无法识别时按网页处理。
-
-最终扩展名写入 `LocalResource.meta.extension`,然后冻结为 `resolved_extension`。`ParserRouter` 只读取这个结果。URL 上已有明确扩展名时,不用 magic bytes 擅自覆盖它。
-
-因此,`wait=false` 不等于“完全不碰源站就返回”。HTTP 服务收到无后缀远程 URL、且 Understanding 已启用时,必须先下载或探测一次,才能知道应进入外部解析队列还是内置 Parser。命中 Understanding 后,生产端直接上传这份已检测的本地文件并取得 `response_id`,然后才清理临时文件;Worker 只恢复该 response,不会重新下载可能已过期或内容已变化的 URL。
-
-## Parser:只回答“本地内容怎么解析”
-
-标准执行链分四类:
-
-- 原始文本:直接进入内置 `ParserRegistry`。
-- 可由 Understanding 直接接收的原始 URL:在 Accessor 前进入 `ParserRouter`。
-- 本地目录:直接进入 `DirectoryParser`;Git 仓库由目录链委派给代码仓库 Parser。
-- 本地文件:进入 `ParserRouter`,根据 `resolved_extension` 在内置 `ParserRegistry` 与 Understanding 之间选一次。
-
-ParserRegistry 只注册项目内置 Parser,不再提供自定义 Parser 类、回调注册或可选模块注册入口。新增数据源优先实现 Accessor;新增文件格式则直接增加内置 Parser 和对应测试。
-
-目录、网站和由内置 ZipParser 展开的压缩包,其“子文件遍历”仍属于当前内置
-Parser 的内部实现,不回到顶层 `ResourceService`。`DirectoryParser` 会递归扫描
-每个叶子文件,并通过 `ParserRouter` 重新检查 `parser_api.extensions`:命中的文件
-交给 Understanding,未命中的文件继续使用内置 Parser 或直接写入。该过程在当前
-目录任务内执行,不会把每个子文件拆成独立的 `ExternalParse` 队列任务。顶层压缩
-文件本身是否直接进入 Understanding,仍由其冻结扩展名和
-`parser_api.extensions` 决定。
-
-启用 Understanding 目录路由后,每次 `DirectoryParser` 扫描在发起该层远程请求前执行
-预检,默认限制为 1000 个入选文件和 10 层目录深度;关闭 Understanding 时,
-OpenViking 原生目录解析不应用这两个限制。内置 `ZipParser` 递归展开压缩包时会创建新的
-目录扫描,嵌套 ZIP 不与外层共享文件数量和深度预算。
-客户端导入本地目录时,会先将整个目录压缩为 ZIP,再由
-`/resources/temp_upload` 对整个 ZIP 执行上传大小限制。ZIP 解压后的叶子文件不再由
-`DirectoryParser` 设置统一大小限制,而是交给对应内置 Parser 或 Understanding,遵循
-各自的格式和上传限制。这些文件使用固定 worker 池,默认并发为 4;远程解析可以并发,
-但向目录临时树的合并始终按扫描顺序串行执行。目录限制可通过
-`parsers.directory` 配置调整。目录内部分文件失败时仍提交成功文件并通过
-`meta.failed_files` 返回失败详情;嵌套 ZIP 的叶子失败使用 `bundle.zip/path/to/file`
-形式的路径并保留远端任务 ID。如果没有任何文件成功,则在 TreeBuilder 持久化前
-终止任务,并清理本次请求新预占的空目标目录。
-
-## Understanding 链路
-
-Understanding 是“外部解析器”,不是“外部落盘器”:
-
-```text
-LocalResource / 远程源
- |
- v
-Understanding API
- |
- v
-解析结果 ZIP
- |
- v
-解压到临时 Viking 目录
- |
- v
-ParseResult
- |
- v
-TreeBuilder + 标准摘要/索引链
-```
-
-同步路径中,Accessor 已下载的本地文件会直接上传给 Understanding,`original_source` 只保留作来源元数据。普通 HTTP 文件的异步路径也先上传已检测文件,再通过统一的 `AddResourceMsg` 持久化 `understanding_response_id`、冻结的 `resolved_extension` 和 `parser_backend="understanding"`;Worker 直接恢复 response,既不重新下载源 URL,也不因配置变化重新选择后端。这些冻结字段是内部任务字段,公共 `args` 不能指定,避免调用方绕过外部解析开关和扩展名白名单。
-
-飞书直达的异步路径也冻结 `parser_backend="understanding"`。生产端统一调用 Understanding 提交:显式 user token 直接转换为 `lark_file`,应用凭证则在 UnderstandingAPI 内获取 tenant token。QueueFS 只持久化 `understanding_response_id`,不保存 token;Worker 从该 response 继续轮询,不重复提交也不重新判断配置。未显式指定资源名的飞书 artifact 会从 ZIP 单一根目录恢复真实标题,目标 URI 因而延迟到解析完成后确定。
-
-Understanding 返回 ZIP 时,本地适配器会安全解压,并根据 Markdown 的相对图片引用生成受控的图片映射 sidecar。TreeBuilder 后续仍使用统一的图片 URI 改写链,不依赖飞书 Accessor 的 `feishu://` 占位符。
-
-这条链的关键特征是:Understanding 只替代 Parser,后面的 `ParseResult`、URI 规划、TreeBuilder 落盘、摘要和索引仍属于 OpenViking。
-
-## Connector 链路
-
-Connector 是另一套端到端导入服务:
-
-```text
-ResourceService
- |
- +--> Connector doc/add
- |
- +--> Connector 获取源数据
- +--> Connector 解析
- +--> Connector 写入目标资源树
- |
- +--> 后台轮询 Connector task/info
- |
- +--> 更新 OpenViking TaskRecord
-```
-
-Connector 不返回本地 `ParseResult`,也不调用当前进程的 `TreeBuilder`。OpenViking 只负责校验这次请求能否无损委派、提交任务、返回 OpenViking `task_id`,再把 Connector 的终态同步到任务记录。
-
-Connector 当前要求提供精确 `to`,不接受 `parent`;也不支持 `wait=true`、watch、instruction、关闭建索引、摘要、strict、include/exclude 等。无凭证的 Git 请求可回退到标准链;带 Connector 专用凭证的 Git 和 Connector-only 来源会立即报错,避免凭证落入本地持久化任务。
-
-## `wait` 的准确含义
-
-| 路径 | `wait=false` | `wait=true` |
-|---|---|---|
-| Connector | 提交外部任务后返回 | 不支持;不会假装同步等待 |
-| Git | 预检并预占 URI 后启动后台标准链 | 当前请求内完成标准链并等待队列 |
-| 飞书直达 Understanding | 生产端提交后只将 response ID 放入 `ExternalParse`;无显式资源名时可延迟返回 `root_uri` | 当前请求内调用 Understanding,再等待后续队列 |
-| HTTP 服务 + 异步 Understanding | 先识别类型,再预占 URI、入 `ExternalParse` 后返回 | 当前请求内调用 Understanding,再等待后续队列 |
-| 普通标准链 | 解析和落盘完成后返回;摘要/语义处理由任务监控 | 解析和落盘完成后继续等待语义队列 |
-
-所以普通 `wait=false` 不是“所有工作后台化”,而是“资源树已落盘,但不阻塞等待后续语义任务”。Git 与异步 Understanding 是两个明确的例外分支。
-
-## 目标 URI、锁和失败边界
-
-- 需要后台执行的 Git 与普通文件 Understanding 任务会先规划并预占目标 URI,避免返回的 URI 随后台竞态变化。未指定名称的飞书直达任务会延迟目标 URI 解析,以 artifact 的真实根标题作为最终名称,并在完成时回写 TaskRecord。
-- 锁通过 handoff 交给后台任务或队列 Worker;入队失败时立即释放,并把任务标为失败。
-- 临时 `LocalResource` 由拥有它的调用层清理;交给标准处理器后,清理责任随之转移。
-- Parser 产生 `ParseResult` 后才进入 TreeBuilder。没有临时解析产物时标准链返回解析错误;目录允许带 warnings 的部分成功,`strict` 决定是否暴露这些警告。
-- Connector 的失败边界在外部任务终态,OpenViking 不对其内部文件逐个回滚。
-
-## 代码定位
-
-| 职责 | 入口 |
-|---|---|
-| 公开入口、新请求分流与内部执行 | `openviking/service/resource_service.py`:`ResourceService.add_resource`、`_submit_resource_ingestion`、`_execute_resource_ingestion` |
-| Watch 刷新入口 | `openviking/service/resource_service.py`:`ResourceService.refresh_resource`;`openviking/resource/watch_scheduler.py` |
-| 标准解析与落盘编排 | `openviking/utils/resource_processor.py`:`ResourceProcessor.process_resource` |
-| Accessor 与 Parser 两层衔接 | `openviking/utils/media_processor.py`:`UnifiedResourceProcessor` |
-| 文件 Parser 单次选择 | `openviking/parse/parser_router.py`:`ParserRouter` |
-| 内置 Parser 注册 | `openviking/parse/registry.py`:`ParserRegistry` |
-| HTTP 类型识别 | `openviking/parse/accessors/http_accessor.py`:`HTTPAccessor`、`URLTypeDetector` |
-| Understanding 同步适配 | `openviking/parse/understanding_api.py`:`UnderstandingAPI` |
-| 飞书直达开关 | `openviking_cli/utils/config/open_viking_config.py`:`ParserApiConfig.enable_feishu_url` |
-| 可恢复的后台资源消息与双队列 Worker | `openviking/storage/queuefs/add_resource_msg.py`、`add_resource_processor.py`、`queue_manager.py` |
-| Connector 客户端 | `openviking/connector/client.py`:`ConnectorClient` |
-
-## 快速自检
-
-- 无后缀 PDF URL:HTTPAccessor 从响应头或 PDF 签名得到 `.pdf`,ParserRouter 再决定是否使用 Understanding。
-- 飞书默认配置:走 FeishuAccessor;仅开启 `enable_feishu_url` 且有凭证时才绕过 Accessor。
-- 飞书 user token 直达:队列中只有 response ID 和强制后端标记,不出现 token 明文。
-- 已归一化飞书 Markdown:无论 `extensions` 是否包含 `md`,都走内置 Markdown Parser。
-- Understanding 返回结果:先转成 `ParseResult`,仍由本地 TreeBuilder 落盘。
-- Connector 返回结果:只返回任务标识,不经过本地 `ParseResult`。
-- 普通 Markdown 且 `wait=false`:返回前 Markdown 已解析并落盘,只是不等待后续语义队列。
-- 网站抓取出的目录:进入 DirectoryParser,页面子文件不会逐个调用 Understanding。
diff --git a/docs/design/runtime-configuration-design.md b/docs/design/runtime-configuration-design.md
deleted file mode 100644
index 2be477c25..000000000
--- a/docs/design/runtime-configuration-design.md
+++ /dev/null
@@ -1,217 +0,0 @@
-# Runtime Configuration Design
-
-## 1. Scope and goals
-
-OpenViking has two configuration planes:
-
-- `ov.conf` is the startup configuration. It defines the process baseline and the runtime-config source selection. It is read during startup and is never rewritten by the runtime configuration API.
-- Runtime settings are persisted independently for Cluster and each Account by a `ConfigSource`. They can be published without rebuilding the process.
-
-The runtime configuration layer is narrower than the complete `OpenVikingConfig` model. A field must be declared with `RuntimeField` to be exposed through the generic configuration API. Plain Pydantic fields remain startup-only.
-
-The design goals are:
-
-1. Keep the startup baseline immutable while rebuilding published Cluster configuration from its runtime settings.
-2. Keep Account configuration independent from Cluster configuration.
-3. Use one PATCH and validation contract for Cluster and Account scopes.
-4. Separate persistence, publication, cache invalidation, and consumer notification.
-5. Allow storage providers to be replaced without coupling the manager to AGFS or a concrete database.
-6. Keep business defaults and Account/Cluster composition outside the generic configuration manager.
-
-## 2. Configuration model
-
-`OpenVikingConfig` is the Cluster model. `AccountConfig` is the Account model.
-An optional Account field set to `None` means only that the Account has not
-configured that value. The consuming business decides what absence means.
-`RuntimeField` records lifecycle metadata:
-
-- `dynamic`: whether the field can be modified after creation;
-- `fallback`: a deprecated compatibility-only Cluster field path.
-
-Legacy `fallback` applies only to a completely unset top-level Account section
-and returns the complete Cluster section. It does not recursively merge fields.
-New configuration must not use it; business resolvers should explicitly combine
-the independently published Account and Cluster models when that is the desired
-behavior.
-
-Runtime fallback in the current VLM and vector resolvers also keeps existing
-Account documents usable when those documents predate complete Account settings.
-This is a migration compatibility path, not the target lifecycle for new
-configuration. New Account provisioning and new Account-scoped features should
-use Cluster configuration only as a creation template: materialize a complete
-Account-owned configuration during create, persist it with create-if-absent
-semantics, and thereafter change it only through that Account's API. Later
-Cluster changes then define defaults for future Accounts and do not implicitly
-change existing Accounts. Until existing Account documents are migrated or
-materialized, their missing sections continue to use the current resolver
-fallback behavior.
-
-Cluster-versus-Account scope comes from the model declaring the field, not from `RuntimeField` itself. A plain `Field` is outside the runtime API surface.
-
-Current runtime field declarations:
-
-| Scope | Field | Lifecycle | Fallback / consumer status |
-| --- | --- | --- | --- |
-| Cluster | `agent_evolution` | Dynamic | Cluster default; consumed by session and Agent Evolution paths |
-| Account | `agent_evolution` | Dynamic | Uses deprecated whole-section fallback to Cluster `agent_evolution` for compatibility |
-| Account | `feishu` | Dynamic | No declarative fallback; an unset section uses Cluster `feishu`, while a set section uses Account values/defaults for every field except the Cluster-owned `domain`. Used by Feishu imports, preflight, and watch token refresh |
-| Account | `github`, `acl` | Dynamic | No Cluster fallback; GitHub and ACL consumers read the Account value through the manager |
-| Account | `vlm`, `query_planner` | Dynamic | ROOT-only; the VLM resolver combines Account-owned model identity and credentials with selected Cluster runtime behavior |
-| Account | `embedding` | Mixed | ROOT-only; credentials and runtime policy are dynamic, while model identity, vector-space fields, text source and input token limit are create-only |
-| Account | `vectordb` | Create-only | ROOT-only; an explicit Account section owns the remote connection and authentication; an absent section selects the Cluster backend |
-
-Account `memory` is not declared on the current Account runtime model and is rejected by both creation-time settings validation and later PATCH requests. ADMIN responses omit `vlm`, `query_planner`, `embedding`, and `vectordb`; only ROOT can read or write these sections. Cluster `embedding`, `vlm`, `query_planner`, `memory`, `feishu`, and the other plain Cluster configuration sections are not writable through the runtime configuration API.
-
-An Account VLM or Query Planner section requires `model` and a non-empty
-`credentials` array. Model-service identity, endpoints and credentials come from
-that Account section. Selected runtime behavior comes from Cluster; Account
-`timeout`, when set, overrides Cluster `timeout`, and an unset or reset value
-uses Cluster `timeout`. Query Planner selection is Account `query_planner`,
-Account `vlm`, Cluster `query_planner`, then Cluster `vlm`.
-
-The vector resolver resolves and validates Embedding and VectorDB together.
-Account embedding may contain only runtime policy or an explicit empty object;
-without an Account model mode, it uses Cluster model bindings. Declared Account
-model modes replace the Cluster mode set, and their credential arrays provide
-complete provider bindings without borrowing Cluster connection or authentication
-fields. An explicit Account VectorDB section similarly owns its complete
-connection and authentication, even when it uses the same backend type as Cluster.
-Account backends support `http`, `volcengine`, and `vikingdb`; their remote
-collections, indexes and authorization must already be provisioned externally.
-See the [Admin API](../en/api/08-admin.md#runtime-configuration) for the field
-surface and compatibility requirements.
-
-## 3. RuntimeConfigManager
-
-`RuntimeConfigManager` owns storage-independent behavior:
-
-- three-state PATCH merging within one scope;
-- scope-local read/merge/write serialization;
-- model construction and validation through caller-provided hooks;
-- copy-on-write publication;
-- changed-section calculation;
-- consumer notification;
-- Account lazy loading, caching, refresh, and idle eviction.
-
-The manager does not import concrete Cluster or Account models. The service supplies hooks for reading and replacing the Cluster singleton, building a validated Cluster model, and building an `AccountConfig` model.
-
-Cluster runtime settings are always applied to the immutable startup baseline.
-They are not merged into the previously published Cluster object, which prevents
-removed values from remaining accidentally materialized. Account settings are
-constructed and published independently. The manager retains whole-section
-fallback only for existing compatibility fields; domain-specific defaults are
-resolved by business code.
-
-## 4. PATCH and validation
-
-Both scopes use the same request shape:
-
-```json
-{
- "settings": {
- "agent_evolution": {
- "enabled": true
- }
- }
-}
-```
-
-The PATCH has three states:
-
-- an absent field keeps its current value;
-- a concrete value sets or replaces the value;
-- `null` removes the value at the addressed scope.
-
-Objects merge recursively and arrays replace as a whole. A nested `null` removes only that leaf. It does not create a missing parent or remove an existing parent that becomes empty. Removing a parent requires an explicit parent-level `null`; `{}` remains an explicit empty object.
-
-Validation has three stages:
-
-1. Structural validation checks that every path is on the target model's `RuntimeField` surface, rejects unknown paths, and rejects `dynamic=False` paths on a non-creating PATCH.
-2. The merged result is constructed into the target Pydantic model for type validation and cross-field constraints.
-3. Registered Account candidate validators check the business-effective configuration before persistence. Vector validation checks the complete Embedding/VectorDB pair on creation, loading, refresh and PATCH; an embedding update also checks that an existing Account's mode and dimension remain unchanged.
-
-A `dynamic=False` field can be supplied in Account creation `settings`, but later additions, changes and resets are rejected, including ROOT requests. This applies to the whole `vectordb` section and to embedding model identity, dimension, input, query/document parameters, version, `text_source` and `max_input_tokens`. Removing a parent object cannot bypass the restrictions on its stored create-only fields.
-
-The API returns settings from the addressed scope, not a business-effective
-Account/Cluster composition. Declarative fallback is deprecated compatibility
-behavior, applies only to a whole section, and is currently used by Account
-`agent_evolution`. Feishu demonstrates the preferred design: its business
-resolver receives Account and Cluster configuration and applies Feishu-specific
-defaulting without extending the generic manager.
-
-## 5. Publication and consumers
-
-A successful update follows this order:
-
-1. Read the current settings for the addressed scope.
-2. Apply and validate the patch.
-3. Persist the new override.
-4. Publish the new Cluster object or Account cache entry.
-5. Release configuration update locks.
-6. Run matching consumers in registration order and wait for them.
-
-Consumer exceptions are logged and swallowed. They do not roll back persistence or publication, so a successful PATCH confirms that the configuration layer was updated, not that every derived client has applied it. Consumers may update in-memory state or invalidate derived clients, but must not write configuration or recursively publish another configuration update.
-
-Cluster publication uses atomic pointer replacement. The new object is built and validated before the singleton is swapped, so concurrent readers see either the old or new object. Account consumers are notified of eviction independently of section filters so they can drop account-local derived state.
-
-All currently declared Account sections have business consumers. GitHub, ACL,
-and Agent Evolution read through the manager; Feishu is resolved for resource
-imports, source preflight, and watch token refresh. Account VLM and Query Planner
-configuration is resolved for model work and retrieval planning. Account
-Embedding and VectorDB configuration is used by queries, queue writes, reindexing,
-OVPack and account-scoped observers. Configuration consumers invalidate derived
-model and vector resources after relevant updates or Account eviction. Account
-`memory` remains outside the runtime configuration API.
-
-Embedding and vector backend resources track active operations so retirement
-waits for in-flight work. Account VLM callers retain an account-bound proxy
-rather than a model client. Each asynchronous model call borrows the current
-client; configuration invalidation retires the old client and closes it after
-that call completes. No task-wide configuration lease is used.
-
-## 6. Persistence
-
-The built-in file source is selected by the startup configuration:
-
-```json
-{"runtime_config": {"source": "file"}}
-```
-
-It stores Account overrides at `/local/{account_id}/_system/setting.json` and Cluster overrides at `/local/_system/runtime_config/cluster.json`. Before replacing an existing file, it writes the previously read AGFS-visible bytes to the corresponding backup file. Reads recover from a valid backup when the primary is missing or invalid; if neither file is valid JSON, the read fails closed instead of treating corruption as an empty override.
-
-The file source relies on exact-path AGFS locks and lease-bound writes. Keeping the historical path and JSON format does not make concurrent old and new writers safe by itself. The source does not interpret provider parameters such as `namespace`; deployment isolation is provided by the mounted storage.
-
-`memory` is an explicitly volatile source. External sources implement the `ConfigSource` contract, register a factory, own their `params` interpretation, protect credentials, and provide idempotent scope deletion.
-
-## 7. Refresh and failure behavior
-
-The manager refreshes the Cluster scope and loaded Account scopes every 30 seconds. Accounts unused for 24 hours are evicted from the process cache.
-
-- A refresh failure retains the last valid published configuration and retries later.
-- A first load failure is returned to the caller.
-- An administrative read reads the explicit persisted override rather than an inherited effective value.
-
-This distinction prevents a transient storage failure from replacing a known-good in-memory configuration with defaults.
-
-## 8. Compatibility and verification
-
-The old Account `settings` endpoints, the Agent Evolution endpoint, and
-declarative whole-section fallback remain compatibility adapters. New Account
-features should read complete Account-owned configuration directly. Cluster
-defaults should be materialized by Account provisioning rather than introduced
-as new runtime fallback dependencies. Existing resolver fallback remains until
-pre-materialization Account documents have been migrated.
-
-Extended Account sections should not be written while old replicas share the same Account directory if those replicas reject unknown fields in `setting.json`.
-
-The focused mechanism tests are:
-
-```bash
-.venv/bin/python -m pytest tests/config --no-cov
-```
-
-They cover field discovery, three-state merging, runtime-surface validation,
-lazy Account loading, publication isolation, consumer notification, idle
-eviction, legacy whole-section fallback, Feishu business resolution, and
-file-source backup behavior, together with Account vector compatibility,
-credential isolation, cache invalidation and embedding resource lifecycle.
diff --git a/docs/design/session-memory-extraction-flow.md b/docs/design/session-memory-extraction-flow.md
deleted file mode 100644
index e663c0201..000000000
--- a/docs/design/session-memory-extraction-flow.md
+++ /dev/null
@@ -1,109 +0,0 @@
-# Session Memory Extraction Flow
-
-This document records the current implementation. It is meant to be used as a
-code-modification reference, so it avoids proposed or removed flows.
-
-## Policy
-
-`memory_policy` carries target switches plus an optional global memory type
-whitelist, and can disable per-archive Working Memory summaries:
-
-```json
-{
- "self": { "enabled": true },
- "peer": { "enabled": false },
- "working_memory": { "enabled": false },
- "memory_types": ["profile", "preferences"]
-}
-```
-
-When `memory_types` is omitted or `null`, all enabled schemas from
-`MemoryTypeRegistry` are allowed, including custom prompt/schema types. When it
-is set, extraction is limited to those names for both self and peer writes.
-When `working_memory.enabled` is `false`, commit still archives messages and
-runs configured memory extraction, but skips the archive summary.
-
-## Memory Type Groups
-
-| Group | Types | Target |
-| --- | --- | --- |
-| User-memory extraction | Enabled registry schemas with `stage: user`, including `cases` | Self and peer, subject to schema policy |
-| Case-driven training | `trajectories`, `experiences` | Self only |
-| Executable session skills | Optional output of case-driven training | Self only |
-
-Memory schemas default to `stage: user` and `peer_enabled: true`. Set
-`peer_enabled: false` for user-stage schemas that should ignore `peer_id` and
-`ranges` peer targets and remain under the current user space (for example
-`cases`). Execution-derived types are not exposed to the ordinary user-memory
-extractor.
-
-`SessionCompressorV3.extract_long_term_memories` is the only public extraction
-entry. It trains trajectories, experiences, and optional executable session
-skills only when ordinary extraction produces at least one case. An explicit
-execution-only `memory_types` policy does not invoke ordinary extraction, so it
-cannot create a case and does not trigger training.
-
-## Commit Flow
-
-Implemented in `openviking/session/session.py`:
-
-1. Load the session-level policy from session metadata.
-2. Archive the current message batch.
-3. Hydrate tool outputs for extraction.
-4. If peer memory is enabled, collect safe `message.peer_id` values from the
- archived batch into `allowed_peer_ids`.
-5. Start archive summary generation.
-6. Remove execution-derived types from the schema whitelist passed to ordinary
- extraction. If enabled user-memory types remain, call
- `SessionCompressorV3.extract_long_term_memories` once with the full archived
- batch, `allow_self_memory`, and `allowed_peer_ids`.
-7. V3 applies ordinary memory operations and collects extracted `cases`. When
- at least one case exists, V3 runs streaming training for trajectories and
- experiences and, when enabled, an executable session skill. With no case,
- all three training outputs are skipped.
-
-The current flow does not build separate buckets such as
-`self_identity_messages`, `self_experience_messages`,
-`peer_user_message_groups`, or `peer_assistant_message_groups`.
-
-## Long-Term Routing
-
-Implemented in `openviking/session/memory/memory_isolation_handler.py`.
-
-`MemoryIsolationHandler.calculate_memory_uris` resolves each extracted operation
-independently:
-
-| Operation fields | Result |
-| --- | --- |
-| No `peer_id`, no `ranges` | Write self if self memory is enabled |
-| Safe `peer_id` in `allowed_peer_ids` | Write that peer |
-| Unsafe `peer_id` | Skip |
-| Safe but unallowed `peer_id` | Skip |
-| `ranges` present | Read the message range; no-peer messages route to self, allowed peer messages route to peer |
-| Schema has `peer_enabled: false` | Ignore `peer_id` and `ranges` peer targets; write self if self memory is enabled |
-| Only disabled targets found | Skip |
-
-The router does not rewrite message roles. A `role=user` message remains user
-content, a `role=assistant` message remains assistant content, and tool parts
-stay on the message where they were recorded.
-
-## Storage Targets
-
-For current user space `viking://user/<user_id>`:
-
-| Target | Storage space |
-| --- | --- |
-| Self | `viking://user/<user_id>/...` |
-| Peer | `viking://user/<user_id>/peers/<peer_id>/...` |
-
-Peer-only extraction does not initialize self default files. Default self files
-are initialized only when `allow_self_memory` is true.
-
-## Practical Invariants
-
-- V3 user-memory extraction sees the full archived batch once.
-- The extractor may emit self and peer operations in the same response.
-- Final write targets are decided per operation by the isolation handler.
-- Peer writes require safe peer IDs observed in the archived batch.
-- `trajectories`, `experiences`, and executable session skills are trained only
- from an extracted case and never write peer memory.
diff --git a/docs/design/tool-stub-design.md b/docs/design/tool-stub-design.md
deleted file mode 100644
index 23c54de98..000000000
--- a/docs/design/tool-stub-design.md
+++ /dev/null
@@ -1,346 +0,0 @@
-# Tool Stub 设计文档
-
-**范围**: OpenViking 当前 `tool stub` 能力的实现说明,覆盖类型识别、规则化摘要、原文外置、回溯读取与测试边界。
-**状态**: 已实现,本文档描述当前代码行为,不额外引入新需求。
-
----
-
-## 概述
-
-OpenViking 原生已经支持 tool result preview。原有链路能够在 session 写入阶段把过大的 tool output externalize,并在 `ToolPart` 中留下一个 preview stub,同时保留 ref 供后续回溯。
-
-这次工作的重点不是新建 externalize 机制,而是在现有能力上优化 preview 的生成方式:从偏 `head + tail` 的直接截断,升级为按内容类型输出更稳定、更可读的规则化摘要。
-
-换句话说,本次改动保持下面这些基础能力不变:
-
-1. 哪些 tool output 需要 externalize,仍由 session 写入阶段决定。
-2. 原始内容仍写入 `ToolResultStore`。
-3. `ToolPart` 仍保留 stub 和 `tool_output_ref`。
-4. 原文回溯方式仍是 `read/search/list`。
-
-这次变化主要集中在 preview 生成层:
-
-1. 在 session 写入阶段识别哪些 tool output 需要 externalize。
-2. 原始输出写入 session 下的 tool result store。
-3. preview 从简单截断优化为基于内容和 MIME 的 deterministic synopsis。
-4. 把原始 `ToolPart.tool_output` 替换成 stub 文本,并保留 `tool_output_ref`。
-5. 后续通过 `read/search/list` 工具按 ref 回溯原文。
-
-`text` 类型只做规则化摘要,不接 LLM。
-
----
-
-## 设计目标
-
-1. 在保留 OV 原生 externalize 和 ref 回溯链路的前提下,优化 preview 的可读性。
-2. 减少大 tool output 对上下文窗口的占用。
-3. 把原有偏 `head + tail` 的截断 preview,升级为按类型输出的规则化摘要。
-4. 对常见文本型输出给出稳定、可读的 deterministic synopsis。
-5. 保留原始输出,支持按 ref 精确回溯。
-6. 当前版本不做 LLM 摘要,只做 deterministic 的规则化摘要。
-
----
-
-## 端到端流程
-
-### 1. 选择哪些输出需要 externalize
-
-入口在 [tool_output_externalizer.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/tool_output_externalizer.py) 的 `ToolOutputExternalizer.externalize_group()`。
-
-当前按两类条件触发:
-
-1. 单个 tool output 超过 `threshold_chars`。
-2. 同一个 assistant turn 中多个 tool output 的总 inline 体积超过 `assistant_turn_inline_budget_chars`。
-
-命中后会进入 externalization 流程。触发阈值仍沿用 OV 原有配置;规则化摘要本身不改变“什么时候 externalize”。
-
-### 2. 外置原始结果并替换 ToolPart
-
-入口在 [tool_output_externalizer.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/tool_output_externalizer.py) 的 `ToolOutputExternalizer._externalize_tool_part()`。
-
-这一步会:
-
-1. 把原始 `tool_output` 写入 `ToolResultStore`。
-2. 调用 preview 生成逻辑产出 stub 文本。
-3. 用 stub 替换 `ToolPart.tool_output`。
-4. 把原始结果的 ref 写入 `ToolPart.tool_output_ref`。
-
-因此被 stub 后,消息里保留的是 preview,不再是完整原始 tool result;原始结果仍在外置存储里。
-
-### 3. 生成 synopsis 和 stub
-
-入口在 [tool_result_store.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/tool_result_store.py#L38) 的 `make_preview()`:
-
-1. 原生 preview/stub 能力保留,但内容生成逻辑从简单截断演进为 typed synopsis。
-2. `generate_tool_result_synopsis()` 负责类型识别和摘要生成。
-3. `render_tool_result_stub()` 负责把摘要渲染成最终 stub 文本。
-
-核心实现位于 [tool_result_synopsis.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/tool_result_synopsis.py#L363)。
-
-当前原则:
-
-1. externalize 触发阈值沿用 OV 原有配置。
-2. 常见类型使用固定规则上限生成 synopsis,不依赖 `preview_chars` 控制摘要长度。
-3. `preview_chars` 只作为无法规则化时的 fallback head/tail 采样预算,并作为兼容字段保留在 stub header / metadata 中。
-
-### 4. 原文回溯
-
-当前回溯能力由 session 暴露三类工具:
-
-1. [session.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/session.py#L932) `read_tool_result()`:按 `offset/limit` 读取原始内容片段。
-2. [session.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/session.py#L952) `search_tool_result()`:在原始内容中做关键字搜索。
-3. [session.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/session.py#L972) `list_tool_results()`:列出当前 session 已 externalize 的结果。
-
-对应存储层实现位于 [tool_result_store.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/tool_result_store.py#L77)。
-
----
-
-## 支持的数据类型
-
-当前支持的 synopsis kind 定义在 [tool_result_synopsis.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/tool_result_synopsis.py#L18):
-
-`json` / `csv` / `tsv` / `yaml` / `xml` / `code` / `text` / `unknown`
-
-### 类型对照表
-
-| 类型 | 识别方式 | 处理办法 | stub 中保留内容 |
-|---|---|---|---|
-| `json` | MIME 含 `json`,或内容以 `{` / `[` 开头且能被 JSON decoder 解析 | 解析 top-level shape,提取 keys、array length、标量示例 | `summary + structure + notable_items` |
-| `csv` | 含逗号,且能按 CSV 读成规则表格 | 统计行列数、列名,保留首条数据样例 | `summary + structure` |
-| `tsv` | 含制表符,且能按 TSV 读成规则表格 | 统计行列数、列名,保留首条数据样例 | `summary + structure` |
-| `yaml` | 满足 YAML 启发式并能 `yaml.safe_load()` 成 dict/list | 提取 top-level keys 和 child type | `summary + structure` |
-| `xml` | MIME 含 `xml`,或内容以 `<` 开头且可解析 | 提取 root tag、属性数、子标签计数 | `summary + structure` |
-| `code` | 命中代码模式正则 | 提取 imports、symbols、line_count | `summary + structure + notable_items` |
-| `text` | 作为最终 fallback | 规则化文本摘要,不保留全文 sample | `summary` |
-| `unknown` | 空内容、binary-like 内容,或带明确 MIME 但解析失败的结构化内容 | 无法规则化时使用 fallback head/tail sample | `summary + sample` |
-
----
-
-## 类型识别顺序
-
-识别顺序定义在 [tool_result_synopsis.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/tool_result_synopsis.py#L363)。
-
-当前顺序如下:
-
-1. 空内容:直接标为 `unknown`。
-2. binary-like 内容:如果出现 NUL 或控制字符比例过高,标为 `unknown`。
-3. `json`
-4. `xml`
-5. `tsv`
-6. `csv`
-7. `yaml`
-8. `code`
-9. 最终 fallback 为 `text`
-
-这个顺序的目的是优先识别结构化格式,再识别代码,最后才把剩余内容视作普通文本。日志样式输出不再作为独立类型处理,会走 `text`,与 lossless-claw 的 large-file exploration 行为保持一致。
-
----
-
-## 各类型处理策略
-
-### JSON
-
-实现位于 [tool_result_synopsis.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/tool_result_synopsis.py#L150)。
-
-输出重点:
-
-1. 顶层类型是 object 还是 array。
-2. top-level keys,最多 10 个。
-3. 子字段是 object / array / scalar。
-4. 最多若干条标量示例。
-5. 若第一个 JSON value 后还有额外字符,会记入 `trailing_chars_after_first_json_value`。
-6. 不额外保留原始 JSON sample。
-
-### CSV / TSV
-
-实现位于 [tool_result_synopsis.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/tool_result_synopsis.py#L218)。
-
-输出重点:
-
-1. 列数与数据行数。
-2. 首行列名。
-3. 首条数据样例,最多 180 字符。
-
-只接受“列数基本一致”的表格;不规则分隔文本不会被误判成表格。
-
-### YAML
-
-实现位于 [tool_result_synopsis.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/tool_result_synopsis.py#L184) 与 [tool_result_synopsis.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/tool_result_synopsis.py#L268)。
-
-输出重点:
-
-1. 顶层是 object 还是 array。
-2. top-level keys,最多 30 个。
-3. 每个 key 对应的 child type。
-4. 不额外保留 YAML sample。
-
-### XML
-
-实现位于 [tool_result_synopsis.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/tool_result_synopsis.py#L204)。
-
-输出重点:
-
-1. 根标签名。
-2. 根节点属性数量。
-3. 一级子标签频次,最多 30 个。
-4. 不额外保留 XML sample。
-
-### Code
-
-实现位于 [tool_result_synopsis.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/tool_result_synopsis.py#L280)。
-
-输出重点:
-
-1. 总行数。
-2. import 语句,最多 12 条,单条最多 180 字符。
-3. 顶层 symbol,如 `class Foo`、`def bar`、`fn baz`,最多 24 条,单条最多 200 字符。
-4. 不额外保留 head/tail sample。
-
-当前是轻量规则识别,不做 AST 级代码摘要。
-
-### Text
-
-实现位于 [tool_result_synopsis.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/tool_result_synopsis.py#L319)。
-
-`text` 类型明确不接 LLM,只做 deterministic fallback。摘录采用固定上限,不受 `preview_chars` 影响。
-
-日志样式输出也归入 `text`。如果需要定位错误/警告行,优先通过 stub 中的 ref 使用 `openviking_tool_result_search` 搜索原始 payload,避免仅靠关键字把普通文档误判成日志。
-
-输出重点:
-
-1. `Characters`
-2. `Words`
-3. `Lines`
-4. `Detected section headers`
-5. `Opening excerpt`
-6. `Closing excerpt`
-
-标题提取规则:
-
-1. Markdown 标题,如 `# Heading`
-2. 全大写风格标题行,如 `SYSTEM STATUS`
-
-摘录规则:
-
-1. opening excerpt 固定最多取前 500 字符。
-2. closing excerpt 固定最多取后 500 字符。
-3. 先压缩空白,再写入摘要。
-4. 不额外保留 `sample` 字段,避免把完整原文重新带回上下文。
-
-### Unknown
-
-`unknown` 是当前实现里的保守分类,不是富类型支持。
-
-当前会落到 `unknown` 的场景包括:
-
-1. 输出为空。
-2. 文本中存在明显二进制控制字符。
-3. MIME 明确标成 JSON/XML,但内容解析失败。
-
-对这些内容,stub 保留基础说明;非空内容会使用 `preview_chars` 生成 head/tail fallback sample。原始 payload 仍通过 ref 回溯。
-
----
-
-## Stub 文本结构
-
-渲染逻辑位于 [tool_result_synopsis.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/tool_result_synopsis.py#L436)。
-
-当前 stub 由两部分组成:
-
-### Header
-
-包含:
-
-1. `tool_name`
-2. `kind`
-3. `original_chars`
-4. `preview_chars`
-5. `ref`
-6. `sha256`
-7. `reason`
-
-### Body
-
-按 synopsis 内容选择性渲染:
-
-1. `Synopsis`
-2. `Structure`
-3. `Notable items`
-4. `Sample`
-5. `Explore`
-
-其中 `Explore` 会提示模型使用:
-
-1. `openviking_tool_result_search`
-2. `openviking_tool_result_read`
-3. `openviking_tool_result_list`
-
----
-
-## 原始内容存储与回溯
-
-实现位于 [tool_result_store.py](https://github.com/volcengine/OpenViking/blob/main/openviking/session/tool_result_store.py#L101)。
-
-每个 externalized tool result 会写入两类文件:
-
-1. `output.txt`:原始输出内容。
-2. `metadata.json`:元数据和 synopsis。
-
-元数据包括:
-
-1. `tool_result_id`
-2. `session_id`
-3. `message_id`
-4. `tool_id`
-5. `tool_name`
-6. `created_at`
-7. `original_chars`
-8. `preview_chars`
-9. `sha256`
-10. `mime_type`
-11. `synopsis_kind`
-12. `synopsis`
-13. `storage_uri`
-14. `output_uri`
-16. `offset_unit=unicode_code_point`
-
-### 读取方式
-
-1. `read()`:按 `offset/limit` 读取原始文本片段,适合长文本逐段展开。
-2. `search()`:在原始文本中查关键词,并返回带 offset 的 snippet。
-3. `list()`:按 session 列出已有外置结果,便于发现 ref。
-
-当前读取模型是“面向长文本”的;它适合回看日志、代码、表格文本、普通文本。
-
----
-
-## 当前边界与取舍
-
-1. `text` 不接 LLM,原因是我们当前只需要稳定、低成本、可测试的规则化 stub。
-2. 当前回溯接口是 `read/search/list`,更适合大文本原文回看。
-3. `offset/limit` 对“顺序文本展开”很合适,但对图片、二进制、复杂多模态结果并不理想。
-
----
-
-## 测试覆盖
-
-当前相关测试包括:
-
-1. [test_tool_result_synopsis.py](https://github.com/volcengine/OpenViking/blob/main/tests/session/test_tool_result_synopsis.py#L1):覆盖类型识别和 synopsis 生成,包括固定 caps、text 的 500/500 deterministic fallback,以及 unknown 的 head/tail fallback。
-2. [test_tool_result_externalization.py](https://github.com/volcengine/OpenViking/blob/main/tests/session/test_tool_result_externalization.py#L1):覆盖 externalization、stub 替换、阈值边界、aggregate budget、ref 回溯等端到端流程。
-3. [test_api_sessions.py](https://github.com/volcengine/OpenViking/blob/main/tests/server/test_api_sessions.py#L190):覆盖 HTTP API 层的 tool result externalization、stub 文案、`read/list/search` 回溯,以及 `synopsis_kind` / `synopsis.kind` 元数据透出。
-
-当前相关测试共 29 个用例通过,可作为后续继续补齐真实输出回归用例的基础。
-
----
-
-## 结论
-
-OpenViking 当前的 `tool stub` 已经具备一版完整闭环:
-
-1. OV 原生的 externalize、preview stub、ref 回溯链路继续保留。
-2. preview 生成方式已从偏 `head + tail` 的截断,升级为按类型的规则化摘要。
-3. `text` 类型采用 deterministic 规则摘要,不接 LLM。
-4. 能通过 `read/search/list` 对外置原文进行回溯。
-
-后续优先级应放在更深的回归测试、更多真实输出样本,以及是否需要继续优化 `read/search/list` 的原文回溯体验,而不是先扩展 LLM 摘要或媒体解析。
diff --git a/docs/design/traj-exp-experience-learning-redesign.md b/docs/design/traj-exp-experience-learning-redesign.md
deleted file mode 100644
index 19637571b..000000000
--- a/docs/design/traj-exp-experience-learning-redesign.md
+++ /dev/null
@@ -1,1292 +0,0 @@
-# Trajectory / Experience 经验学习框架重构
->
-> 目标:把真实或离线环境中的 agent rollout 转换为 trajectory,再从 trajectory 估计 experience 更新信号,最终通过可审查、可合并、可并发安全的 policy update 机制更新 `experiences` 目录。
-
-## 1. 总体定位
-
-当前框架把 `experiences` 目录视为一个可优化的 **Experience Policy Set**:
-
-```text
-viking://user/<user>/memories/experiences/
-```
-
-目录中的每个 experience 文件是一个 `Experience`,整个目录共同构成 agent 的经验策略。训练框架不直接绑定某个 agent loop;它只约束以下抽象链路:
-
-```text
-CaseLoader
- -> RolloutExecutor
- -> PolicyTrainer
- -> RolloutAnalyzer
- -> GradientEstimator
- -> PolicyOptimizer
- -> PolicyUpdater
-```
-
-其中 `PolicyTrainer` 是训练入口。默认本地实现会在进程内执行 `analyze -> estimate -> plan -> apply`;远程实现可以把 rollout 通过 `session.commit` 提交给 OpenViking 服务端,由服务端完成分析和训练。
-
-### 1.1 训练执行细节图
-
-<img src="https://gist.githubusercontent.com/chenjw/c2de3083d0e1dac3a192c74f98c020c7/raw/502e01c5e207ce8b2b4076a6cd84b8fe9dc06543/train-execution-details.svg" alt="OpenViking session.train 训练执行细节" width="100%">
-
-这张图强调三个实现边界:
-
-- **并行边界**:case rollout、rollout analysis、gradient estimation 可以并行。
-- **串行边界**:`ExperienceSet.lock()` 内的 `reload -> PolicyOptimizer.plan -> PolicyUpdater.apply` 必须串行。
-- **存储边界**:trajectory 写入发生在 `RolloutAnalyzer`;experience 读取/合并/写入发生在 optimizer/updater;session archive 和 `memory_diff.json` 只出现在 `session.commit` 路径。
-- **LLM 边界**:红色特殊框表示该模块会调用 LLM / `ExtractLoop`,包括 trajectory 抽取、experience gradient 估计和 patch merge。
-
-
-## 2. 代码结构
-
-当前模块结构:
-
-```text
-openviking/session/train/
- context.py # PipelineContext / ExecutionContext
- domain.py # domain dataclass
- engine.py # PolicyTrainingEngine:共享 analyze/estimate/plan/apply 内核
- gradients.py # PatchSemanticGradient
- interfaces.py # Protocol 接口
- pipeline.py # OfflinePolicyOptimizationPipeline
-
- components/ # 可替换组件实现
- case_loader.py
- gradient_estimator.py
- memory_store.py
- policy_optimizer.py
- policy_trainer.py
- policy_updater.py
- remote.py
- rollout_executor.py
- session_commit.py
- snapshotter.py
- trajectory_analyzer.py
-```
-
-设计边界:
-
-- 根目录保留框架内核、domain、接口和编排。
-- `components/` 放所有具体实现。
-- `openviking.session.train` 顶层继续导出常用类,便于外部使用。
-
-## 3. 核心 Domain Model
-
-### 3.1 Experience / ExperienceSet
-
-`Experience` 对应 experiences 目录下的一个 experience 文件。
-
-```python
-@dataclass(slots=True)
-class Experience:
- name: str
- uri: str
- version: int
- status: PolicyStatus
- content: str
- metadata: dict[str, Any] = field(default_factory=dict)
- links: list[dict[str, Any]] = field(default_factory=list)
- backlinks: list[dict[str, Any]] = field(default_factory=list)
-```
-
-`ExperienceSet` 是某个 experiences 根目录的快照:
-
-```python
-@dataclass(slots=True)
-class ExperienceSet:
- root_uri: str
- policies: list[Experience]
- metadata: dict[str, Any] = field(default_factory=dict)
- viking_fs: Any | None = field(default=None, repr=False, compare=False)
- request_context: Any | None = field(default=None, repr=False, compare=False)
-```
-
-当前实现中,`ExperienceSet` 还负责提供并发安全能力:
-
-```python
-async with policy_set.lock():
- latest_policy_set = await policy_set.reload()
-```
-
-约定:
-
-- `root_uri` 是 experiences 目录 URI。
-- `links/backlinks` 对应 memory file 中的 `MEMORY_FIELDS.links/backlinks`,用于在 train 域快照内保留 v2 link 协议数据。
-- `policies` 是当前目录下所有 experience 文件解析后的快照。
-- `viking_fs` / `request_context` 是运行时依赖,用于 `lock()` 和 `reload()`,不参与 equality/repr。
-- `PolicyTrainingEngine.plan_and_apply(...)` 会先加 policy tree lock,再 reload 最新 policy set,然后 plan/apply。
-
-### 3.2 Trajectory
-
-`Trajectory` 是从 rollout 中抽取并持久化的可训练轨迹样本,对应 trajectories 目录下的 memory 文件。
-
-```python
-@dataclass(slots=True)
-class Trajectory:
- name: str
- uri: str
- content: str
- outcome: TrajectoryOutcome | str
- retrieval_anchor: str
- metadata: dict[str, Any] = field(default_factory=dict)
-```
-
-约定:
-
-- `Rollout` 是原始执行记录。
-- `Trajectory` 是从 rollout messages 中抽取出的训练样本。
-- trajectory 文件由 `TrajectoryRolloutAnalyzer` 通过 `ExtractLoop + MemoryUpdater` 写入 `memories/trajectories`。
-
-### 3.3 Case / Rubric
-
-`Case` 是可执行、可复现、可评估的训练/评测样例。
-
-```python
-@dataclass(slots=True)
-class Case:
- name: str
- task_signature: str
- input: dict[str, Any]
- rubric: Rubric
- metadata: dict[str, Any] = field(default_factory=dict)
-```
-
-`Rubric` 定义“什么叫做好”和“怎么检查”。当前不再保留独立 `Outcome` 概念。
-
-```python
-@dataclass(slots=True)
-class Rubric:
- name: str
- description: str
- criteria: list[RubricCriterion]
- metadata: dict[str, Any] = field(default_factory=dict)
-
-@dataclass(slots=True)
-class RubricCriterion:
- name: str
- description: str
- required: bool
- weight: float
- metadata: dict[str, Any] = field(default_factory=dict)
-```
-
-### 3.4 Rollout
-
-`Rollout` 是某个 policy snapshot 在某个 case 上执行后的记录。
-
-```python
-@dataclass(slots=True)
-class Rollout:
- case: Case
- messages: list[Message]
- policy_snapshot_id: str
- evaluation: RubricEvaluation | None = None
- metadata: dict[str, Any] = field(default_factory=dict)
-```
-
-当前关键变化:`Rollout.evaluation` 是一等可选字段。
-
-- 如果环境本身能给 reward / evaluation,`RolloutExecutor` 应直接填入 `rollout.evaluation`。
-- 训练时 `TrajectoryRolloutAnalyzer` 优先沿用 `rollout.evaluation`;没有时才通过注入的 `RolloutEvaluator` 评估;再没有时用“是否抽取到 trajectory”作为 fallback evaluation。
-- `pipeline.eval(...)` 不再调用 `RolloutAnalyzer`,只依赖 `RolloutExecutor` 返回的 `rollout.evaluation`;如果 eval rollout 缺 evaluation,会直接报错。
-
-### 3.5 RubricEvaluation
-
-```python
-@dataclass(slots=True)
-class RubricEvaluation:
- passed: bool
- score: float
- criterion_results: list[CriterionResult]
- feedback: list[str]
- metadata: dict[str, Any] = field(default_factory=dict)
-
-@dataclass(slots=True)
-class CriterionResult:
- criterion_name: str
- passed: bool
- score: float
- feedback: list[str]
- evidence: list[str]
- metadata: dict[str, Any] = field(default_factory=dict)
-```
-
-在 tau2 集成中:
-
-- `passed = reward >= 1.0`
-- `score = reward`
-- report 展示以 `accuracy = passed_count / case_count` 为主,`average_reward` 为辅助指标。
-
-## 4. SemanticGradient
-
-`SemanticGradient` 是针对一个目标 experience 的语义更新信号。当前接口以 `MemoryFile` before/after 表达,而不是文本 patch 对象。
-
-```python
-class SemanticGradient(Protocol):
- @property
- def before_file(self) -> MemoryFile | None: ...
-
- @property
- def after_file(self) -> MemoryFile: ...
-
- @property
- def target_experience_name(self) -> str: ...
- @property
- def target_experience_uri(self) -> str | None: ...
- @property
- def base_version(self) -> int | None: ...
- @property
- def rationale(self) -> str: ...
- @property
- def links(self) -> list[StoredLink]: ...
- @property
- def confidence(self) -> float: ...
- @property
- def metadata(self) -> dict[str, Any]: ...
-```
-
-当前具体实现:
-
-```python
-@dataclass(slots=True)
-class PatchSemanticGradient:
- before_file: MemoryFile | None
- after_file: MemoryFile
- base_version: int | None
- rationale: str
- links: list[StoredLink]
- confidence: float
- metadata: dict[str, Any] = field(default_factory=dict)
-```
-
-约定:
-
-- `before_file is None` 表示建议新建。
-- `after_file` 是建议的目标 memory file 状态。
-- `links` 承载 exp→traj 的 provenance,沿用 v2 `MEMORY_FIELDS.links/backlinks` 协议;来源轨迹关系使用 `StoredLink(from_uri=exp_uri, to_uri=traj_uri, link_type="derived_from", weight=1.0)`,不再引入单独的轨迹 URI 列表字段。
-- patch 文本不是 gradient 自身字段,而是由 `PatchMergeContextProvider` 在 merge 阶段把 before/after memory file 渲染为字段级 unified diff。
-
-## 5. PolicyUpdatePlan / PolicyUpdater
-
-`PolicyOptimizer.plan(...)` 输出 `PolicyUpdatePlan`,`PolicyUpdater.apply(...)` 负责真正写文件。
-
-```python
-PolicyPlanItemKind = Literal["upsert_experience", "delete_experience"]
-
-@dataclass(slots=True)
-class PolicyPlanItem:
- kind: PolicyPlanItemKind
- target_experience_name: str
- target_experience_uri: str | None
- before_content: str | None
- after_content: str | None
- base_version: int | None = None
- confidence: float | None = None
- links: list[StoredLink] = field(default_factory=list)
- metadata: dict[str, Any] = field(default_factory=dict)
-
-@dataclass(slots=True)
-class PolicyUpdatePlan:
- items: list[PolicyPlanItem] = field(default_factory=list)
- metadata: dict[str, Any] = field(default_factory=dict)
-
-@dataclass(slots=True)
-class PolicyApplyResult:
- updated_policy_set: ExperienceSet
- written_uris: list[str] = field(default_factory=list)
- deleted_uris: list[str] = field(default_factory=list)
- errors: list[str] = field(default_factory=list)
- metadata: dict[str, Any] = field(default_factory=dict)
-```
-
-当前 `MemoryFilePolicyUpdater` 支持:
-
-- `upsert_experience`
-- `delete_experience`
-- 基于 `before_content` 的轻量 base-content guard,避免覆盖已发散内容。
-
-## 6. 接口定义
-
-### 6.1 CaseLoader
-
-```python
-class CaseLoader(Protocol):
- async def batches(self, context: Any) -> AsyncIterator[list[Case]]: ...
-```
-
-实现:
-
-- `ListCaseLoader`
-- `RemoteCaseLoader`:通过 HTTP 服务拉取 cases。
-
-### 6.2 RolloutExecutor
-
-```python
-class RolloutExecutor(Protocol):
- async def execute(
- self,
- cases: list[Case],
- policy_set: ExperienceSet,
- context: ExecutionContext,
- ) -> list[Rollout]: ...
-```
-
-实现:
-
-- `SingleTurnLLMRolloutExecutor`
-- `RemoteRolloutExecutor`
-- `Tau2RolloutExecutor`(benchmark/tau2 内部实现,通过 tau2 service 暴露给训练流程)
-
-### 6.3 RolloutEvaluator
-
-```python
-class RolloutEvaluator(Protocol):
- async def evaluate(self, rollout: Rollout, context: Any) -> RubricEvaluation: ...
-```
-
-用途:环境不能直接提供 `rollout.evaluation` 时,`RolloutAnalyzer` 可注入 evaluator 进行评估。
-
-### 6.4 RolloutAnalyzer
-
-```python
-class RolloutAnalyzer(Protocol):
- async def analyze(self, rollout: Rollout, context: Any) -> RolloutAnalysis: ...
-```
-
-当前实现:`TrajectoryRolloutAnalyzer`。
-
-职责:
-
-1. 确定 rollout evaluation:
- - 优先使用 `rollout.evaluation`
- - 否则使用注入的 `RolloutEvaluator`
- - 否则基于是否抽取到 trajectory 生成默认 evaluation
-2. 将 evaluation feedback 追加到 trajectory extraction messages。
-3. 通过 `AgentTrajectoryContextProvider + ExtractLoop` 只抽取 `trajectories` memory type。
-4. 通过 `MemoryUpdater.apply_operations(...)` 写入 trajectory memory。
-5. 读取写入的 trajectory 文件并返回 `RolloutAnalysis`。
-
-### 6.5 GradientEstimator
-
-```python
-class GradientEstimator(Protocol):
- async def estimate(
- self,
- analysis: RolloutAnalysis,
- experience_set: ExperienceSet,
- context: Any,
- ) -> list[SemanticGradient]: ...
-```
-
-当前实现:`ExperienceGradientEstimator`。
-
-它复用:
-
-- `AgentExperienceContextProvider`
-- `ExtractLoop`
-- `MemoryIsolationHandler(allowed_memory_types={"experiences"})`
-
-但不调用 `MemoryUpdater.apply_operations(...)`。它把 ExtractLoop 产生的 upsert operations 转成 `PatchSemanticGradient`。
-
-### 6.6 PolicyOptimizer
-
-```python
-class PolicyOptimizer(Protocol):
- async def plan(
- self,
- gradients: list[SemanticGradient],
- policy_set: ExperienceSet,
- context: Any,
- ) -> PolicyUpdatePlan: ...
-```
-
-当前实现:`PatchMergePolicyOptimizer`。
-
-它不按 target 分组限制输出,而是把一批 gradients 一次性交给 `PatchMergeContextProvider + ExtractLoop` 进行全局 merge。LLM 可以:
-
-- 合并多个 patch 到一个 experience。
-- 把一个臃肿 patch 拆成多个 experience。
-- 合并相似新文件。
-- 主动输出删除操作。
-
-### 6.7 PolicyUpdater
-
-```python
-class PolicyUpdater(Protocol):
- async def apply(
- self,
- plan: PolicyUpdatePlan,
- policy_set: ExperienceSet,
- context: Any,
- ) -> PolicyApplyResult: ...
-```
-
-实现:
-
-- `DryRunPolicyUpdater`
-- `MemoryFilePolicyUpdater`
-
-### 6.8 PolicyTrainer
-
-```python
-class PolicyTrainer(Protocol):
- async def train_rollouts(
- self,
- rollouts: list[Rollout],
- policy_set: ExperienceSet,
- context: Any,
- analyses: list[RolloutAnalysis] | None = None,
- ) -> RolloutTrainingResult: ...
-```
-
-实现:
-
-- `BatchPolicyTrainer`:显式 batch,本地执行 analyze/estimate/plan/apply。
-- `StreamingPolicyTrainer`:实时 rollout 输入,先 analyze/estimate,再按梯度数量和时间窗口攒批,批量 plan/apply。
-- `SessionCommitPolicyTrainer`:把 rollout 写入远端 OpenViking session,通过 `session.commit` 让服务端完成训练。
-
-### 6.9 PolicyOptimizationPipeline
-
-```python
-class PolicyOptimizationPipeline(Protocol):
- async def train(...) -> PipelineResult: ...
- async def eval(...) -> PipelineEvaluationResult: ...
- async def train_from_rollouts(...) -> RolloutTrainingResult: ...
-```
-
-当前实现:`OfflinePolicyOptimizationPipeline`。
-
-## 7. PipelineContext / ExecutionContext
-
-```python
-@dataclass(slots=True)
-class PipelineContext:
- case_load_context: Any = None
- snapshot_context: Any = None
- analysis_context: Any = None
- gradient_context: Any = None
- optimization_context: Any = None
- apply_context: Any = None
- execution_metadata: dict[str, Any] = field(default_factory=dict)
- max_epochs: int = 1
-
-@dataclass(slots=True)
-class ExecutionContext:
- policy_snapshot_id: str
- metadata: dict[str, Any] = field(default_factory=dict)
-```
-
-`max_epochs` 是训练迭代次数。之前文档中的 `max_iterations` 已改为 epoch 概念。
-
-## 8. 训练流程
-
-### 8.1 OfflinePolicyOptimizationPipeline.train
-
-```text
-for epoch in range(ctx.max_epochs):
- for cases in case_loader.batches(...):
- snapshot_id = snapshotter.snapshot(policy_set)
- rollouts = rollout_executor.execute(cases, policy_set, ExecutionContext(snapshot_id))
- training_result = policy_trainer.train_rollouts(rollouts, policy_set, ctx)
- policy_set = training_result.apply_result.updated_policy_set
-```
-
-默认 `policy_trainer` 是 `BatchPolicyTrainer`,因此本地训练链路为:
-
-```text
-Rollout[]
- -> RolloutAnalyzer.analyze(...)
- -> GradientEstimator.estimate(...)
- -> PolicyTrainingEngine.plan_and_apply(...)
- -> async with ExperienceSet.lock()
- -> ExperienceSet.reload()
- -> PolicyOptimizer.plan(...)
- -> PolicyUpdater.apply(...)
-```
-
-### 8.2 OfflinePolicyOptimizationPipeline.eval
-
-```text
-CaseLoader -> RolloutExecutor -> Rollout.evaluation -> PipelineEvaluationResult
-```
-
-eval 阶段不会调用 `RolloutAnalyzer`,不会抽 trajectory,也不会写 policy。它要求 `RolloutExecutor` 返回带 `evaluation` 的 rollout。
-
-### 8.3 train_from_rollouts
-
-实时场景或外部系统已经产生 rollout 时,可以绕过 `CaseLoader / PolicySnapshotter / RolloutExecutor`:
-
-```text
-Rollout[] -> policy_trainer.train_rollouts(...)
-```
-
-约束:每个 rollout 必须包含 `case`。
-
-## 9. Batch 与 Streaming
-
-### 9.1 BatchPolicyTrainer
-
-适合离线训练,输入一批 rollout 后直接完成一次:
-
-```text
-analyze -> estimate -> plan -> apply
-```
-
-### 9.2 StreamingPolicyTrainer
-
-适合实时 commit / 并发 rollout 场景。
-
-流程:
-
-```text
-submit_rollout(rollout)
- -> analyze rollout
- -> estimate gradients
- -> submit gradients to StreamingBatcher
- -> 等待该 rollout 所在 batch 被 flush 并 apply
-```
-
-flush 触发条件:
-
-- `max_gradients_per_update` 达到阈值
-- 最老 gradient 等待超过 `max_wait_seconds`
-- `close()` 时 flush 剩余内容
-
-默认配置:
-
-```python
-@dataclass(slots=True)
-class StreamingPolicyTrainerConfig:
- max_gradients_per_update: int = 8
- max_wait_seconds: float = 10.0
- timer_check_interval_seconds: float = 1.0
- trace_console: bool = False
-```
-
-进程内全局共享:
-
-```python
-get_streaming_policy_trainer(...)
-make_streaming_policy_trainer_key(policy_root_uri, request_context)
-```
-
-并发安全由 `PolicyTrainingEngine.plan_and_apply(...)` 中的 `ExperienceSet.lock()` 保证。
-
-## 10. Patch Merge 机制
-
-### 10.1 PatchSemanticGradient 到 PatchMergePatch
-
-`PatchMergePolicyOptimizer` 会把每个 `SemanticGradient` 转为:
-
-```python
-@dataclass(slots=True)
-class PatchMergePatch:
- before_file: MemoryFile | None
- after_file: MemoryFile
- metadata: dict[str, Any]
-```
-
-### 10.2 PatchMergeContextProvider
-
-位置:`openviking/session/memory/patch_merge_context_provider.py`
-
-职责:
-
-- 给 LLM 提供待合并 patch 相关的原始 memory 文件。
-- 将 `MemoryFile` before/after 渲染为字段级 unified diff。
-- 用 embedding 检索额外候选文件,帮助发现相似/重复 memory。
-- 暴露指定 memory type 的 schema,让 ExtractLoop 输出合法 memory operations。
-
-输入文件选择:
-
-```text
-required_file_uris = patch target uri / superseded policy uri
-extra_candidate_files = embedding search 当前 memory_type 下的相似文件
-max_extra_candidate_files = max(5, len(required_file_uris))
-search_limit = max_extra_candidate_files * 2
-```
-
-字段 diff 规则:
-
-- 只展示发生变化的字段。
-- 字符串按行 diff。
-- dict/list 先 JSON 格式化再 diff。
-- `content` 已在 `Field Diff: content` 中展示,因此不会额外在 metadata 中重复塞完整 content。
-
-### 10.3 PatchMergePolicyOptimizer
-
-```text
-SemanticGradient[]
- -> PatchMergeContextProvider.prefetch()
- -> ExtractLoop(max_iterations=1)
- -> ResolvedOperations
- -> PolicyPlanItem[]
-```
-
-输出支持:
-
-- upsert experience
-- delete experience
-
-merge 输入/输出日志通过 `tracer.info(..., console=False)` 记录,避免默认污染 console。
-
-## 11. session.commit 实时训练接入
-
-`SessionCompressorV3` 已把用户记忆抽取和实时训练接起来。
-
-### 11.1 用户记忆抽取
-
-`SessionCompressorV3._extract_user_memories(...)`:
-
-1. 通过原用户记忆 `ExtractLoop` 抽取用户记忆。
-2. case 不再额外单独调用 LLM,而是作为一种普通 memory type:`cases`。
-3. 抽取结果交给 `StreamingMemoryUpdater` 做 patch merge 写入用户记忆。
-4. 如有 `archive_uri`,写入 `memory_diff.json`,其中包含顶层 `trace_id`。
-
-`memory_diff.json` 顶层结构包含:
-
-```json
-{
- "archive_uri": "...",
- "trace_id": "...",
- "extracted_at": "...",
- "operations": {...},
- "skipped_operations": [...],
- "summary": {...}
-}
-```
-
-### 11.2 从 cases 触发 streaming train
-
-`SessionCompressorV3.train_from_extracted_cases(...)`:
-
-```text
-extracted Case[] + original commit messages
- -> Rollout(case, messages, policy_snapshot_id=session-commit:...)
- -> StreamingPolicyTrainer.submit_rollout(...)
-```
-
-即真实 session.commit 产生的对话可以被转为 rollout 输入训练框架。
-
-## 12. SessionCommitPolicyTrainer:远程服务端训练
-
-`SessionCommitPolicyTrainer` 是一个 `PolicyTrainer` 实现,用于“训练框架在外部,OpenViking 服务端负责训练”的场景。
-
-它会把 rollout 写成一个临时 session:
-
-```text
-[CaseSpec message]
-[Rollout messages]
-[OutcomeEvaluation message]
-```
-
-其中:
-
-- `CaseSpec` 放在开头,只含 case/rubric/task context,不含 evaluation。
-- `OutcomeEvaluation` 放在最后,只含 evaluation,作为训练信号。
-- rollout 的工具结果会通过 `ToolPart` 的 `tool_output` 上传,而不是普通 text。
-
-然后执行:
-
-```text
-client.create_session(...)
-client.batch_add_messages(...)
-client.commit_session(...)
-client.get_task(...) until completed/failed/timeout
-```
-
-CaseSpec 会做精简,避免传入巨大或重复字段:
-
-- 不传 `policy`
-- 不传 `data_root`
-- 不传 `rollout_metadata`
-- 不传 `policy_snapshot_id`
-- 保留 `domain/split/data_split/task_id/task_no/user_query/ground_truth/rubric`
-
-## 13. Remote HTTP 组件
-
-`components/remote.py` 提供通用 HTTP 组件:
-
-- `RemoteCaseLoader`
-- `RemoteRolloutExecutor`
-
-它们面向一个环境/benchmark service:
-
-```text
-POST /v1/cases/query
-POST /v1/rollouts/execute
-GET /v1/rollouts/executions/{execution_id}
-```
-
-其中 `/v1/rollouts/execute` 只负责提交单个 case 的 rollout execution,返回
-`execution_id`;`RemoteRolloutExecutor` 会并发提交多个 case,并通过
-`/v1/rollouts/executions/{execution_id}` 轮询状态。这样长耗时 rollout 不会占用
-一个超长 HTTP request,也便于未来 benchmark service 做多机部署和负载均衡。
-
-这样训练框架不需要直接依赖 tau2 或其他 benchmark 的代码,只依赖通用
-Case/Rollout JSON 协议。
-
-## 14. tau2 集成
-
-### 14.1 架构
-
-当前 tau2 训练分为两个进程:
-
-```text
-tau2 service
- - 依赖 tau2 / vikingbot
- - 暴露 case query 和 rollout execute HTTP API
-
-train/eval runner
- - 使用 RemoteCaseLoader / RemoteRolloutExecutor
- - 使用 SessionCommitPolicyTrainer 提交 OpenViking session.commit
- - 本身不直接依赖 tau2 runtime
-```
-
-### 14.2 tau2 service
-
-位置:
-
-```text
-benchmark/tau2/train/service_app.py
-benchmark/tau2/train/run_service.sh
-```
-
-启动:
-
-```bash
-benchmark/tau2/train/run_service.sh \
- --host 127.0.0.1 \
- --port 1944
-```
-
-### 14.3 remote train/eval
-
-位置:
-
-```text
-benchmark/tau2/train/run_batch_train_eval.sh
-openviking/session/train/run_batch_train_eval.py
-openviking/session/train/batch_runner.py
-```
-
-预先只跑 test 分数(不训练):
-
-```bash
-benchmark/tau2/train/run_batch_train_eval.sh \
- --epochs 0 \
- --eval-index 24 \
- --trials 8
-```
-
-训练前先跑一次 test baseline,再训练并跑最终 test:
-
-```bash
-benchmark/tau2/train/run_batch_train_eval.sh \
- --baseline-eval \
- --epochs 4 \
- --trials 8
-```
-
-输出以 accuracy 为主,阶段日志由 session/train lifecycle hooks 统一输出:
-
-```text
-[baseline_rollout] epoch=-1 trials=8 cases_per_trial=25 total_rollouts=200 accuracy=... ± ... avg_reward=... ± ...
-================= epoch 0 =================
-[train_rollout] epoch=0 cases=25 accuracy=... passed=... avg_reward=...
-[train] epoch=0 commits=25 errors=0
-[final_test_rollout] epoch=4 trials=8 cases_per_trial=25 total_rollouts=200 accuracy=... ± ... avg_reward=... ± ...
-```
-
-### 14.4 tau2 rollout messages
-
-`Tau2RolloutExecutor` 会把工具结果转成真正的 `ToolPart`:
-
-```json
-{
- "type": "tool",
- "tool_id": "tau2-tool-0",
- "tool_name": "get_reservation_details",
- "tool_input": {...},
- "tool_output": "...",
- "tool_status": "completed"
-}
-```
-
-这样上传到 `session.commit` 后,服务端可以复用已有 tool output 外部化和 memory extraction 逻辑。
-
-
-## 15. tau2 接入新评测框架示意图
-
-tau2 的接入方式体现了推荐的 benchmark 集成模式:benchmark runtime 独立成 HTTP service,训练框架只通过通用 `RemoteCaseLoader` / `RemoteRolloutExecutor` 接入。
-
-<img src="https://gist.githubusercontent.com/chenjw/5c8f05a10f2c3f1913eb6c9d4293f0a4/raw/d9151bc8bbceccf3e56486897061c76a5d6f0cfa/tau2-train-eval-architecture.svg" alt="tau2 接入 OpenViking 新训练评测框架" width="100%">
-
-
-图中需要特别注意:tau2 runtime service 虽然不负责训练写入,但它执行 rollout 时会通过 VikingBot / OpenViking tools 读取当前 OpenViking memories。因此 final_eval 能看到 train epoch 后写入的最新 experiences。
-
-### 15.1 接入分层
-
-```text
-tau2 service
- - 依赖 tau2 / vikingbot
- - 负责 case 查询、rollout 执行、环境 reward 评估
- - 输出通用 Case / Rollout / RubricEvaluation JSON
-
-train/eval runner
- - 不直接依赖 tau2 runtime
- - 使用 RemoteCaseLoader 查询 case
- - 使用 RemoteRolloutExecutor 执行 rollout
- - 使用 SessionCommitPolicyTrainer 把训练 rollout 提交给 OpenViking 服务端
-
-OpenViking server
- - 通过 session.commit 接收 rollout messages
- - 服务端内部执行 trajectory extraction / gradient estimation / patch merge / policy update
-```
-
-### 15.2 train/eval 时序
-
-```text
-baseline_eval:
- RemoteCaseLoader(test)
- -> RemoteRolloutExecutor
- -> Tau2RolloutExecutor
- -> rollout.evaluation
- -> accuracy / avg_reward report
-
-train epoch:
- RemoteCaseLoader(train)
- -> RemoteRolloutExecutor
- -> Tau2RolloutExecutor
- -> SessionCommitPolicyTrainer
- -> session.commit
- -> SessionCompressorV3
- -> StreamingPolicyTrainer
- -> experiences update
-
-final_eval:
- RemoteCaseLoader(test)
- -> RemoteRolloutExecutor
- -> Tau2RolloutExecutor reads latest OpenViking experiences
- -> rollout.evaluation
- -> accuracy delta report
-```
-
-### 15.3 为什么 eval 不走 RolloutAnalyzer
-
-在 tau2 场景中,环境执行完 rollout 后可以直接给出 reward,因此 `Tau2RolloutExecutor` 会返回:
-
-```python
-Rollout(
- case=case,
- messages=messages,
- policy_snapshot_id=snapshot_id,
- evaluation=RubricEvaluation(...),
-)
-```
-
-所以 `OfflinePolicyOptimizationPipeline.eval(...)` 只统计 `rollout.evaluation`:
-
-```text
-accuracy = passed_count / case_count
-average_reward = mean(evaluation.score)
-```
-
-eval 不抽 trajectory、不估计 gradient、不写 experience。
-
-### 15.4 训练如何通过 session.commit 进入服务端
-
-`SessionCommitPolicyTrainer` 会把 rollout 转成临时 session messages:
-
-```text
-[OpenViking Training CaseSpec]
-[Rollout messages: user / assistant / ToolPart]
-[OpenViking OutcomeEvaluation]
-```
-
-其中:
-
-- `CaseSpec` 放在开头,只描述任务和 rubric,不包含 evaluation。
-- `OutcomeEvaluation` 放在最后,作为训练信号。
-- tau2 工具结果使用 `ToolPart.tool_output` 上传,服务端可以复用已有 tool output 外部化和 memory extraction 逻辑。
-
-### 15.5 指标展示
-
-tau2 runner 的报告以正确率为主:
-
-```text
-[baseline_eval] epoch=-1 cases=10 accuracy=20.00% passed=2/10 avg_reward=0.200000
-[train_epoch] epoch=0 cases=50 accuracy=18.00% passed=9/50 avg_reward=0.180000 commits=50 errors=0
-[final_eval] epoch=1 cases=10 accuracy=30.00% passed=3/10 avg_reward=0.300000
-
-baseline accuracy: 20.00% (2/10)
-final accuracy: 30.00% (3/10)
-accuracy delta: +10.00pp
-```
-
-`average_reward` 保留为辅助指标;主指标是 `accuracy`。
-
-### 15.6 以 tau2 为例:新场景接入需要实现的接口
-
-一个新的 benchmark / domain / environment 接入训练评测框架时,推荐复用 tau2
-的分层方式:把场景 runtime 独立成一个 HTTP service,训练进程继续使用通用
-`RemoteCaseLoader` / `RemoteRolloutExecutor`。训练框架不关心场景内部怎么启动
-agent、怎么调用工具、怎么计算 reward,只要求 service 实现下面这些协议。
-
-#### 15.6.1 Case 查询接口
-
-```text
-POST /v1/cases/query
-```
-
-请求:
-
-```json
-{
- "dataset": "tau2",
- "domain": "airline",
- "split": "train",
- "cursor": null,
- "limit": 100,
- "filters": {}
-}
-```
-
-响应:
-
-```json
-{
- "cases": [
- {
- "name": "tau2_airline_train_0",
- "task_signature": "tau2:airline:train:0",
- "input": {
- "domain": "airline",
- "split": "train",
- "task_id": "0",
- "task_no": 0,
- "user_query": "...",
- "ground_truth": "..."
- },
- "rubric": {
- "name": "tau2_airline_train_0_rubric",
- "description": "...",
- "criteria": [
- {
- "name": "tau2_reward",
- "description": "The tau2 environment reward is 1.0.",
- "required": true,
- "weight": 1.0,
- "metadata": {}
- }
- ],
- "metadata": {}
- },
- "metadata": {
- "dataset": "tau2",
- "domain": "airline",
- "source": "tau2",
- "split": "train"
- }
- }
- ],
- "next_cursor": "100"
-}
-```
-
-接入要求:
-
-- `dataset/domain/split` 用于定位数据集切片。
-- `cursor/limit` 用于分页;没有下一页时 `next_cursor = null`。
-- `Case.input` 只放 rollout 必需的任务输入和场景元信息,不要塞训练框架已经能从
- 上下文拿到的内容,例如完整 system prompt、完整 rollout metadata、evaluation
- 结果或 policy snapshot。
-- `Case.rubric` 必须能描述评测目标;如果环境能直接给 reward,也仍然要提供
- rubric,便于训练侧把 reward 转成统一的 `RubricEvaluation`。
-
-tau2 中对应实现是:
-
-```text
-benchmark/tau2/train/service_app.py::query_cases
-benchmark/tau2/train/case_loader.py::Tau2CaseLoader
-```
-
-#### 15.6.2 Rollout 提交接口
-
-```text
-POST /v1/rollouts/execute
-```
-
-请求:
-
-```json
-{
- "case": { "...": "Case JSON" },
- "policy_set": {
- "root_uri": "viking://user/default/memories/experiences",
- "policies": [],
- "metadata": {}
- },
- "execution_context": {
- "policy_snapshot_id": "tau2-policy-snapshot:...",
- "metadata": {
- "epoch": 0,
- "training": true
- }
- },
- "options": {
- "config_path": "/path/to/ov.conf",
- "max_iterations": 30,
- "keep_default_tools": true,
- "rollout_language": "default"
- }
-}
-```
-
-响应:
-
-```json
-{
- "execution_id": "rollout_exec_...",
- "status": "running",
- "case_name": "tau2_airline_train_0",
- "created_at": 1781097747.0,
- "updated_at": 1781097747.0,
- "error": null
-}
-```
-
-接入要求:
-
-- 该接口只提交一个 case 的 rollout execution,不需要同步等待 rollout 完成。
-- 客户端会对多个 case 发起多个请求,service 端可以自行排队、限流、调度到不同
- worker 或机器。
-- `policy_set.root_uri` 告诉 runtime 当前 experiences 根目录;tau2 rollout 期间
- VikingBot 会通过 OpenViking recall 读取这里的最新经验。
-- `execution_context.policy_snapshot_id` 必须原样写入返回的 `Rollout.policy_snapshot_id`,
- 用于追踪这次 rollout 使用的是哪次 policy snapshot。
-
-tau2 中对应实现是:
-
-```text
-benchmark/tau2/train/service_app.py::execute_rollout
-benchmark/tau2/train/service_app.py::_run_rollout_execution
-benchmark/tau2/train/rollout_executor.py::Tau2RolloutExecutor
-```
-
-#### 15.6.3 Rollout 状态轮询接口
-
-```text
-GET /v1/rollouts/executions/{execution_id}
-```
-
-运行中响应:
-
-```json
-{
- "execution_id": "rollout_exec_...",
- "status": "running",
- "case_name": "tau2_airline_train_0",
- "created_at": 1781097747.0,
- "updated_at": 1781097750.0,
- "error": null
-}
-```
-
-完成响应:
-
-```json
-{
- "execution_id": "rollout_exec_...",
- "status": "completed",
- "case_name": "tau2_airline_train_0",
- "created_at": 1781097747.0,
- "updated_at": 1781097760.0,
- "error": null,
- "rollout": {
- "case": { "...": "Case JSON" },
- "messages": [
- {
- "role": "user",
- "parts": [
- {
- "type": "text",
- "text": "..."
- }
- ]
- },
- {
- "role": "assistant",
- "parts": [
- {
- "type": "tool",
- "tool_id": "tau2-tool-0",
- "tool_name": "get_reservation_details",
- "tool_input": {"reservation_id": "EHGLP3"},
- "tool_output": "...",
- "tool_status": "completed"
- }
- ]
- }
- ],
- "policy_snapshot_id": "tau2-policy-snapshot:...",
- "evaluation": {
- "passed": false,
- "score": 0.0,
- "criterion_results": [
- {
- "criterion_name": "tau2_reward",
- "passed": false,
- "score": 0.0,
- "feedback": ["tau2 environment reward is below 1.0."],
- "evidence": [],
- "metadata": {"reward": 0.0}
- }
- ],
- "feedback": ["tau2 environment reward is below 1.0."],
- "metadata": {
- "source": "tau2_executor",
- "reward": 0.0
- }
- },
- "metadata": {
- "memory": "...",
- "tools_used": [],
- "iterations": 6
- }
- }
-}
-```
-
-失败响应:
-
-```json
-{
- "execution_id": "rollout_exec_...",
- "status": "failed",
- "case_name": "tau2_airline_train_0",
- "created_at": 1781097747.0,
- "updated_at": 1781097752.0,
- "error": "..."
-}
-```
-
-接入要求:
-
-- `status` 至少支持 `running/completed/failed`。
-- `completed` 时必须返回完整 `rollout`。
-- `failed` 时必须返回可读 `error`,训练侧会把它归入该 case 的 rollout 失败。
-- `Rollout.messages` 应使用 OpenViking `Message` / `Part` 结构;工具调用和工具结果
- 用 `ToolPart`,不要把 `tool-call:\nname: ...` 塞进普通 text content。
-- `Rollout.evaluation` 在 eval 阶段是必需字段;如果没有 evaluation,
- `OfflinePolicyOptimizationPipeline.eval(...)` 会失败。
-
-#### 15.6.4 RolloutExecutor 内部职责
-
-新场景自己的 rollout executor 需要完成这些事情:
-
-1. 根据 `Case.input` 初始化环境和用户模拟器。
-2. 根据 `policy_set.root_uri` / OpenViking 配置让 agent 读取当前 experiences。
-3. 执行 agent loop,记录 user/assistant/tool messages。
-4. 把环境 reward 或 judge 结果转成 `RubricEvaluation`。
-5. 返回统一 `Rollout`:
-
-```python
-Rollout(
- case=case,
- messages=messages,
- policy_snapshot_id=context.policy_snapshot_id,
- evaluation=RubricEvaluation(...),
- metadata={
- "tools_used": [...],
- "iterations": ...,
- "memory": "...",
- },
-)
-```
-
-tau2 的 `Tau2RolloutExecutor` 就是这个适配层:它一侧依赖 tau2/VikingBot runtime,
-另一侧只输出训练框架理解的 `Rollout`。
-
-#### 15.6.5 最小接入清单
-
-接入一个新场景,最少需要实现:
-
-| 接口/组件 | 必需 | 作用 |
-|---|---:|---|
-| `POST /v1/cases/query` | 是 | 分页返回 `Case[]` |
-| `POST /v1/rollouts/execute` | 是 | 提交单个 rollout execution |
-| `GET /v1/rollouts/executions/{execution_id}` | 是 | 轮询 rollout 状态并取回 `Rollout` |
-| `RubricEvaluation` 转换 | eval 必需 | 把场景 reward/judge 结果转成统一 evaluation |
-| `Message` / `ToolPart` 转换 | 训练必需 | 保留 agent 行为和工具证据,供 session.commit 抽取 trajectory/experience |
-| `GET /health` | 建议 | 方便 runner 或部署系统做 preflight |
-
-如果新场景不想提供 HTTP service,也可以在同进程内直接实现
-`CaseLoader` / `RolloutExecutor` Protocol;但跨进程、多机或重 runtime 依赖的场景,
-推荐采用 tau2 这种 service 方式。
-
-## 16. 当前主要组件清单
-
-| 组件 | 文件 | 说明 |
-|---|---|---|
-| `OfflinePolicyOptimizationPipeline` | `pipeline.py` | 离线 train/eval 编排 |
-| `PolicyTrainingEngine` | `engine.py` | 共享 analyze/estimate/plan/apply 内核 |
-| `ListCaseLoader` | `components/case_loader.py` | 内存 case loader |
-| `RemoteCaseLoader` | `components/remote.py` | HTTP case loader |
-| `RemoteRolloutExecutor` | `components/remote.py` | HTTP rollout executor |
-| `SingleTurnLLMRolloutExecutor` | `components/rollout_executor.py` | 简单单轮 LLM rollout |
-| `TrajectoryRolloutAnalyzer` | `components/trajectory_analyzer.py` | 抽取 trajectory memory |
-| `ExperienceGradientEstimator` | `components/gradient_estimator.py` | trajectory -> PatchSemanticGradient |
-| `PatchMergePolicyOptimizer` | `components/policy_optimizer.py` | 多 gradient 全局 merge |
-| `DryRunPolicyUpdater` | `components/policy_updater.py` | dry-run apply |
-| `MemoryFilePolicyUpdater` | `components/policy_updater.py` | VikingFS 写回 experiences |
-| `BatchPolicyTrainer` | `components/policy_trainer.py` | batch rollout 训练 |
-| `StreamingPolicyTrainer` | `components/policy_trainer.py` | 实时攒批训练 |
-| `SessionCommitPolicyTrainer` | `components/session_commit.py` | 通过 session.commit 远程训练 |
-| `ContentHashPolicySnapshotter` | `components/snapshotter.py` | 内容 hash snapshot id |
-| `ExperienceSetLoader` | `components/memory_store.py` | 从 experiences 目录加载 policy set |
-
-## 17. 端到端本地训练伪代码
-
-```python
-policy_set = await ExperienceSetLoader(viking_fs).load(
- "viking://user/default/memories/experiences",
- ctx=request_context,
-)
-
-pipeline = OfflinePolicyOptimizationPipeline(
- snapshotter=ContentHashPolicySnapshotter(),
- rollout_executor=SomeRolloutExecutor(),
- rollout_analyzer=TrajectoryRolloutAnalyzer(viking_fs=viking_fs, vikingdb=vikingdb),
- gradient_estimator=ExperienceGradientEstimator(viking_fs=viking_fs),
- policy_optimizer=PatchMergePolicyOptimizer(viking_fs=viking_fs),
- policy_updater=MemoryFilePolicyUpdater(viking_fs=viking_fs),
-)
-
-result = await pipeline.train(
- case_loader=ListCaseLoader(cases, batch_size=8),
- policy_set=policy_set,
- context=PipelineContext(
- max_epochs=1,
- analysis_context=TrajectoryAnalyzerContext(request_context=request_context),
- gradient_context=ExperienceGradientContext(
- request_context=request_context,
- messages=[],
- ),
- optimization_context=PatchMergePolicyOptimizerContext(
- request_context=request_context,
- ),
- apply_context=request_context,
- ),
-)
-```
-
-## 18. 设计原则
-
-- `Case` 是训练/评测样本,不再使用 `Outcome` 概念。
-- `Rubric` 定义验收标准;`RubricEvaluation` 是一次 rollout 的评估结果。
-- `Rollout` 保留原始执行消息和可选 evaluation;`Trajectory` 是从 rollout 中抽取的可训练样本。
-- `SemanticGradient` 是 memory-file before/after 级别的语义更新信号。
-- `PolicyOptimizer` 只规划,不写文件;`PolicyUpdater` 才是写入边界。
-- batch 和 streaming 共用同一个 `PolicyTrainingEngine`。
-- 并发写入通过 `ExperienceSet.lock() + reload()` 串行化 optimizer/apply 阶段。
-- 远程 benchmark 集成应走 `RemoteCaseLoader / RemoteRolloutExecutor`,不要让训练框架直接依赖 benchmark runtime。
diff --git a/docs/design/web-studio-compile-interaction-design.md b/docs/design/web-studio-compile-interaction-design.md
deleted file mode 100644
index 5b03e2ee0..000000000
--- a/docs/design/web-studio-compile-interaction-design.md
+++ /dev/null
@@ -1,521 +0,0 @@
-# Web Studio Compile 交互与实现设计
-
-| 项目 | 内容 |
-| --- | --- |
-| 状态 | 待实现设计 |
-| 更新日期 | 2026-09-16 |
-| 适用范围 | Web Studio Compile 独立导航页、Playground 终端、通用任务联动 |
-| 核心流程 | 选择 Skill → 选择素材 → 设置输出 → 提交 → 查看执行 → 打开产物 |
-
-## 1. 目标与边界
-
-Compile 使用一个指定 Skill,加工一个或多个 OpenViking 素材目录,并将结果写入目标目录。用户应能理解“用什么方法、处理什么内容、结果放在哪里”,无需先学习 API 或 Runtime 配置。
-
-提供两个平等入口:
-
-1. **Compile 独立 Tab**:在 Studio 左侧工作区导航中增加 Compile,紧邻 Skills。提供任务列表、新建页、详情页。
-2. **Playground 终端**:支持 compile 和 task 命令,适合熟悉 CLI 的用户;提交后可进入同一详情页。
-
-本文的 Tab 指独立导航模块,不是 Playground 内部新面板。资源页、Skills 页第一版不增加额外创建入口。
-
-第一版包含完整的创建、查询、取消、参数回填、再次运行和结果查看闭环,并补齐服务端分页。暂不包含定时执行、批量取消、任务删除、任务重命名、产物差异比较、运行中修改参数及通用 Skill 参数表单生成。
-
-## 2. 当前能力与设计依赖
-
-以下现状以本地源码为依据,不代表部署环境已验证。
-
-| 能力 | 当前实现 | 本方案处理 |
-| --- | --- | --- |
-| 创建 | `POST /api/v1/compile`,202,返回 TaskRecord | 复用 |
-| 必填参数 | `from`、`to`、`skill` | 映射三个表单区块 |
-| 可选参数 | `instruction`、`args` | 补充要求、折叠高级参数 |
-| 查询详情 | `GET /api/v1/tasks/{task_id}` | 复用,携带 `include_events=true` |
-| 查询列表 | `GET /api/v1/tasks`,默认 50、最多 200,无游标 | 增加兼容的分页模式 |
-| 取消 | `POST /api/v1/tasks/{task_id}/cancel`,ROOT 禁止取消 | 复用并明确权限和状态 |
-| 原始输入 | `meta.request` 保存公开请求字段 | 用于详情及回填;敏感参数不回显 |
-| 执行事件 | 详情可返回 `execution_events` | 复用已有事件展示,缺失时不伪造 |
-| 执行后端 | 外部 `compile_api` 或 `--with-bot` 本地执行服务 | 新增能力状态用于入口反馈 |
-| Studio 终端 | 自有命令解释器,不是操作系统 Shell | 增加命令解析与 API 调用 |
-| 原生 CLI | 已支持 `ov compile` 和 `ov task status/cancel/list` | Studio 对齐对应语法 |
-
-`docs/design/ov-compile-design.md` 保留了历史 Bot 直连方案。本文以现行 OpenViking 托管任务的接口为准;浏览器不直接调用 Runtime 或旧 Bot compile 接口。
-
-## 3. 页面和路由
-
-| 页面 | 路由 | 主要动作 |
-| --- | --- | --- |
-| 编译列表 | `/compile` | 筛选、加载更多、新建、点击任务 |
-| 新建编译 | `/compile/new` | 选择 Skill/素材/输出、提交、保存草稿 |
-| 编译详情 | `/compile/tasks/$taskId` | 查看执行、取消、打开结果、再次运行 |
-| 基于任务新建 | `/compile/new?fromTask=$taskId` | 获取公开配置后回填,不立即提交 |
-| 终端 | 现有 Playground terminal 面板 | 命令补全、提交、查询、取消、跳转详情 |
-
-列表筛选放入 URL,例如 `?status=running&q=wiki`。草稿、指令、args 不放入 URL。详情页面的任务 ID 只定位任务,权限仍由服务端验证。
-
-导航规则:
-
-- 点击左侧 Compile 默认进入列表;不自动跳到上次任务。
-- 点击列表行进入完整详情页,不用抽屉承载主要流程。
-- 返回列表恢复筛选、已加载页面及滚动位置;刷新详情可直接重新获取任务。
-- 外部直接进入详情时,“返回列表”落到默认列表。
-- 列表行支持键盘 Enter、链接新标签打开;行内复制按钮不触发行跳转。
-- 通用 Tasks 页面保留 compile 记录,并提供进入 Compile 详情的链接。
-
-```mermaid
-flowchart LR
- L[Compile 列表] --> N[新建编译]
- L --> D[任务详情]
- N -->|创建成功| D
- T[Playground 终端] -->|compile 提交| A[任务回执]
- A -->|查看任务| D
- T -->|打开表单| N
- D -->|修改后重新运行| N
- D -->|查看输出| R[资源或 Skill 浏览页面]
- D -->|返回| L
-```
-
-## 4. 页面一:Compile 列表
-
-### 4.1 布局
-
-```text
-Compile [新建编译]
-使用 Skill 将素材整理为新的内容
-
-[搜索 Skill、路径或任务 ID…] [全部状态 ▾] [刷新]
-
-任务 / Skill 素材 状态 创建时间
-monthly_wiki → 团队知识库 周报 等 2 个目录 运行中 今天 14:20
-guide_builder → 操作指南 产品文档 已完成 今天 13:10
-monthly_wiki → 月报 周报 失败 昨天 18:00
-
- [加载更多]
-```
-
-### 4.2 列表字段与操作
-
-| 字段 | 展示规则 |
-| --- | --- |
-| 任务标题 | 从请求派生“Skill 名称 → 输出目录名”;无请求信息时显示任务 ID |
-| Skill | 显示名称;完整 URI 可通过详情查看,不依赖 Skill 当前仍存在 |
-| 素材 | 第一个目录名及“等 N 个目录”;详情展示完整集合 |
-| 状态 | 图标与文字共同表达,不只使用颜色 |
-| 创建时间 | 本地时区,相对日期;悬停显示完整时间和时区 |
-| 任务 ID | 行次要信息,支持复制 |
-
-排序固定为 `created_at DESC, task_id DESC`。同一素材或同一目标的多次执行分别保留,不应用通用 Tasks 页面按资源去重的逻辑。
-
-行点击只负责打开详情。第一版不在行内堆叠取消、重跑和输出等按钮,这些操作集中在详情。
-
-### 4.3 筛选与分页
-
-- 状态选项:全部、排队中、运行中、取消中、已完成、失败、已取消。
-- 搜索覆盖当前用户可见的全部历史任务,范围为任务 ID、公开请求中的 Skill URI、来源 URI、目标 URI;不搜索 instruction 和 args。
-- 搜索输入防抖 300 ms;更改筛选时回到第一页,清除旧游标并取消过时请求。
-- 每页 30 条,“加载更多”追加结果;失败在按钮位置重试,不清空已加载内容。
-- 无下一页时显示“已显示全部可用记录”,不显示未经计算的任务总数。
-- 初次查询失败显示错误和重试,不能显示为“暂无任务”。
-- 新任务提示为“有新任务,点击刷新”;浏览历史时不自动插入并推动列表。
-- 列表可见时每 10 秒刷新第一页;仅更新已显示 ID 的状态,新 ID 先显示提示。详情页拥有更及时的单任务刷新。
-- 分页是实时记录浏览,不是严格快照。状态筛选期间任务可能移入或移出集合;刷新后重新建立游标链,不承诺固定总数。
-
-### 4.4 空状态与服务状态
-
-| 场景 | 文案与操作 |
-| --- | --- |
-| 无历史任务 | “使用 Skill,把已有素材整理成新的内容。”+“新建编译” |
-| 筛选无结果 | “没有符合条件的任务。”+“清除筛选” |
-| 加载失败 | “任务列表加载失败。”+“重试” |
-| 执行服务未配置 | 顶部说明“当前连接尚未启用编译服务”;历史记录仍可查看,创建入口禁用并提供原因 |
-| 能力状态获取失败 | 显示“暂时无法确认编译服务状态”及重试;不误报为未配置,可进入表单并由提交接口最终判定 |
-
-## 5. 页面二:新建编译
-
-### 5.1 表单布局
-
-采用单页分组表单,不使用多步弹窗。Skill 在最前面,帮助用户先理解加工方式,再选择输入和输出。
-
-```text
-[返回列表] 新建编译 草稿已保存
-
-1 使用哪个 Skill? *
- [搜索并选择 Skill ▾]
- 按月汇总周报,生成主题知识页 [查看 Skill]
-
-2 处理哪些素材? *
- [选择目录] [粘贴 URI]
- 周报 viking://resources/weekly [移除]
- 项目记录 viking://resources/projects [移除]
-
-3 将结果保存到哪里? *
- [viking://resources/team-wiki ] [浏览]
- 目标目录尚不存在,执行时按后端能力创建
-
-补充要求
-[例如:按主题整理,保留引用来源,优先使用最近一个月的材料]
-
-▸ 高级参数(可选)
-
-使用 monthly_wiki,处理 2 个目录,输出到 team-wiki
-[复制命令] [取消] [开始编译]
-```
-
-底部操作区在长表单中保持可见,但不遮挡字段错误或屏幕键盘。窄屏取消横向摘要,将完整路径换行显示。
-
-### 5.2 Skill 选择
-
-点击后打开可搜索选择面板。每项显示名称、简短描述、所属范围和 URI;同名 Skill 依靠范围、URI 区分。
-
-- 只列当前身份可见的 Skill,不通过 URI 文本推断权限。
-- 搜索结果缺少描述时显示 URI,不生成未经验证的用途说明。
-- 首次打开不自动选中任意 Skill;只有草稿或复制任务时预选。
-- “查看 Skill”打开侧边预览,显示实际 `SKILL.md`,保留主表单上下文。
-- 预览读取失败不丢失选择,提供重试;提交时仍由后端验证其有效性。
-- 无 Skill 时显示“还没有可用的 Skill”,提供“前往 Skills”;离开前保存公开草稿。
-- 切换 Skill 保留素材、输出和指令。args 非空时提示“已更换 Skill,请检查高级参数”;不静默删除参数。
-- 不假设 Skill 描述能可靠推导输出类型或参数 schema,第一版不自动生成专属表单。
-
-### 5.3 素材目录选择
-
-“选择目录”打开带面包屑的目录选择器,支持进入目录、多选目录及跨目录保留选择。
-
-- 文件可见时置灰并解释“请选择所在目录”;禁止直接选文件作为 from。
-- 已选项以完整 URI 去重,保留选择顺序;后端最终 canonicalize。
-- 手动粘贴支持每行一个 URI,逐条校验并展示错误;无效项可编辑,不清空其它内容。
-- 选择父目录后再选择其子目录时提示可能存在重叠,不静默删除用户选择。
-- 目录不存在、不可读、连接失败使用不同文案;检查中显示局部 loading。
-- 不递归扫描所有内容来估算 token、价格或执行时间。
-
-### 5.4 输出位置
-
-复用目录浏览交互,支持直接输入新路径。字段下持续显示完整 URI,避免同名目录混淆。
-
-- 支持后端允许的 resource、memory 和 skills 目标;具体合法位置以后端校验为准。
-- 技能产物目标必须符合支持的 skills 命名空间,不能按普通目录规则任意嵌套。
-- 来源和目标重叠时提示“结果将写入素材范围,后续执行可能读取这些结果”,不强制替用户更改路径。
-- 已有目标提示“此目录已有内容,执行可能更新其中内容”。不展示尚未支持的“只新增”“自动覆盖”等策略选项。
-- 新目录提示仅表示路径未存在,不在填写表单时提前创建远端目录。
-- 目标为文件、无写权限或命名空间根不合法时就地报错。
-- 可做轻量存在性检查;写权限和业务合法性必须由创建接口最终确认,不将 stat 成功当作可写证明。
-
-### 5.5 补充要求与高级参数
-
-instruction 可留空,空字符串归一化为未设置。输入框示例不作为默认提交值。
-
-args 使用折叠的 JSON 编辑区,默认空;支持格式化、错误定位,只接受 JSON 对象。解析失败时禁用提交并将错误定位到编辑器。
-
-第一版高级参数仅保留于当前页面内存,不写入本地草稿或终端持久历史。复制命令默认省略 args,并明确提示;用户显式选择“包含高级参数”后才纳入剪贴板。服务端公开请求可能脱敏,不能将脱敏占位值作为真实参数再次提交。
-
-### 5.6 草稿、离开与恢复
-
-- 一个身份范围保存一份公开草稿:Skill、from、to、instruction;键包含连接、账号、用户,禁止跨身份复用。
-- 字段变更后防抖保存,显示“草稿已保存”;存储失败显示“草稿未保存”,不阻断编辑。
-- 再次进入新建页提示“已恢复上次草稿”,提供“清空”。
-- 返回列表或点击取消保留公开草稿;“取消”不创建任务。
-- 有未保存输入或内存中的 args 时,离开弹出“继续编辑 / 离开并丢弃未保存内容”。正常已保存草稿不反复确认。
-- 成功提交后清除本次草稿;提交失败保留全部输入。
-- `fromTask` 回填前若已有草稿,提供“继续现有草稿 / 使用任务配置”;不得静默覆盖。
-- 页面刷新无法恢复 args,在高级参数附近明确提示其不自动保存。
-
-### 5.7 提交交互
-
-1. 点击“开始编译”,检查必填项、URI 基本格式和 args;聚焦首个错误字段。
-2. 校验通过后生成本次提交标识,按钮改为“正在提交”,禁止重复提交;保留可见摘要。
-3. 创建成功后跳转任务详情,提示“任务已创建,离开页面不会中断执行”。
-4. 请求参数、权限或配置错误就地展示;有可定位字段时关联字段,否则显示表单顶部错误。
-5. 请求超时或断连时提示“尚未确认是否创建成功”,不宣称创建失败,不直接发起全新任务。
-6. 在服务端幂等能力支持下,“重试确认”复用同一提交标识;参数改变则必须先解决原请求状态或明确新建另一任务。
-
-正常提交不增加确认弹窗。取消正在提交的页面导航只停止前端等待,不承诺撤销服务端创建。
-
-## 6. 页面三:任务详情
-
-### 6.1 布局
-
-```text
-[返回列表] monthly_wiki → 团队知识库 [修改后重新运行]
-cmp_... [复制] 运行中 已运行 2 分 18 秒 [取消任务]
-当前阶段:后端报告的阶段名称 最后更新:14:22:18
-可以离开页面,任务会继续执行
-
-[概览] [执行记录] [结果]
-
-概览
-Skill monthly_wiki [查看 Skill]
-素材 周报、项目记录 [展开路径]
-输出 viking://resources/team-wiki [打开目录]
-补充要求 按主题整理,保留来源
-创建时间 / 更新时间 / 完成时间(有可靠数据时)
-▸ 高级参数(仅公开、脱敏后的内容)
-```
-
-顶部生命周期状态由 `status` 决定,`stage` 只补充当前阶段,不用字符串猜测覆盖 status。未知状态显示“未知状态”及原始值,不自动当作完成。
-
-### 6.2 概览
-
-- 全量展示本次请求的公开配置;超长来源列表默认显示前三项,可展开全部。
-- Skill 链接读取的是当前版本,标注“查看当前 Skill”;后端无快照信息时不声称这是运行时版本。
-- “打开目录”可以查看运行中的已有内容,但标注“执行中,内容可能继续变化”。目标不存在时显示“输出尚未生成”,不当作任务失败。
-- 没有可靠完成时间时不将任意 `updated_at` 标为完成时间;结束耗时仅在后端提供可确认时间时展示。
-- 旧任务缺少 `meta.request` 时显示“该任务未记录完整创建参数”,不从 resource_id 拼凑可执行请求。
-
-### 6.3 执行记录
-
-- 按后端事件顺序展示时间、事件名称、说明及可展开详情;复用现有事件组件。
-- 没有事件时显示“暂未提供执行记录”,仍显示任务状态和 stage。
-- 不展示模拟日志、虚构的阶段完成勾选或百分比。
-- 用户停留底部时自动跟随;向上滚动后暂停跟随,显示“有新记录 / 回到底部”。
-- 原始结构化信息默认折叠,敏感字段应在服务端脱敏,前端不负责恢复。
-- 若事件历史被截断,展示后端提供的截断提示;没有事件分页能力时不承诺完整日志。
-
-### 6.4 结果
-
-| 状态 | 结果区 |
-| --- | --- |
-| 未结束 | “任务完成后将在此展示结果”;可查看已有目标目录 |
-| 已完成且有标准产物 | 结果摘要、产物链接、主要按钮“打开输出目录” |
-| 已完成但 result 为空或格式未知 | “任务已完成”,提供输出目录;未知结构放入“原始结果” |
-| 失败 | 错误原因、可展开技术信息、“修改后重新运行”;可能存在部分产物时允许查看目标 |
-| 已取消 | “任务已停止;已写入的内容可能保留”,可查看目标和基于参数新建 |
-
-产物链接必须来自明确 URI,不能仅凭 result 中任意字符串生成跳转。resource、memory、skills 使用对应浏览能力;暂不能直接定位的 URI 提供复制及可用的目录浏览入口。
-
-第一版不假设存在统一的 created/updated 文件列表,不显示未经后端确认的文件数量、覆盖差异或“全部成功写入”结论。
-
-### 6.5 取消与再次运行
-
-取消按钮仅在后端可取消状态及身份下启用。ROOT 显示禁用原因“当前 ROOT 身份不能取消任务”,不能仅隐藏后使用户误认为不支持。
-
-点击取消打开轻量确认框:“停止此任务?已经写入的内容可能保留。”按钮为“继续执行 / 停止任务”。请求成功后依据返回状态显示取消中或实际终态,不立即伪造 cancelled。
-
-- 请求失败保留真实状态并允许重试。
-- 取消期间任务已经完成时,展示最终完成状态并说明结果已更新。
-- “修改后重新运行”只打开预填表单,不隐式创建任务;原任务不受影响。
-- 缺少敏感参数或公开参数被脱敏时提示需要重新填写,不提交脱敏占位符。
-- 当前 Skill 已删除或权限变化时回填 URI 并标为待重新选择;不阻止用户查看旧任务。
-
-### 6.6 刷新、恢复与通知
-
-- 活跃任务详情可见时每 5 秒查询;浏览器隐藏时暂停,重新聚焦立即刷新。
-- 终态停止自动轮询,保留手动刷新;未知状态使用低频刷新并允许重试。
-- 后端 provider 可能以更长间隔刷新状态,前端查询频率不等于执行进度更新频率。
-- 连续请求失败采用有上限的退避;显示“暂时无法更新,以下为最近状态”,不将任务改为 failed。
-- 返回列表、刷新浏览器、关闭终端都不取消任务;恢复后重新查询服务端。
-- 当前页面观察到完成时显示一次带“查看结果”的通知,不主动切换用户正在查看的子页。
-- 不承诺浏览器关闭后的系统通知;第一版不请求浏览器通知权限。
-- 404 统一显示“任务不存在、已过期或当前身份不可访问”,提供返回列表;不泄露其他用户任务。
-
-## 7. Playground 终端交互
-
-### 7.1 命令集
-
-```bash
-compile --from viking://resources/weekly --to viking://resources/wiki --skill viking://agent/skills/monthly_wiki --instruction "按主题整理,保留来源"
-task status cmp_example
-task list --task-type compile --status running
-task cancel cmp_example
-```
-
-同时接受可选的 `ov` 前缀。from 支持重复参数和逗号分隔,与原生 CLI 对齐。compile 成功后立即返回回执,不阻塞用户输入下一条命令。
-
-这是 Studio 命令语法,不能执行 Shell 的管道、重定向、命令替换或环境变量展开。明确拒绝不支持的语法,不传给系统 Shell。
-
-### 7.2 提示与补全
-
-- 输入 `compile` 显示用途、必填参数、一个可运行结构的示例及“打开可视化表单”。单独回车显示帮助,不创建空任务。
-- 参数补全区分 `--from` 的可读目录、`--skill` 的 Skill 和 `--to` 的目标路径。
-- 缺参时展示准确字段,如“缺少 --skill”,并允许将已解析值带入表单。
-- 无效 JSON 指出 `--args` 必须是对象,不输出完整可能含凭证的输入。
-- 支持单引号、双引号、转义及 JSON 字符串;共享专门的解析模块,不继续使用空格 split。
-- 终端到表单通过身份隔离的内存交接保存参数,地址栏不携带参数;不能恢复的高级参数明确提示。
-
-### 7.3 提交回执与后续操作
-
-```text
-任务已创建
-任务:cmp_example
-状态:排队中
-输出:viking://resources/wiki
-[查看任务] [复制任务 ID]
-```
-
-回执卡片可在可见时刷新状态,复用同一任务查询缓存;不为历史每张卡片分别长期轮询。点击“查看任务”进入 Compile 详情。
-
-task status 展示状态、阶段、错误或结果摘要及详情链接。task list 展示分页结果及“加载更多”,明确范围是当前连接与身份。task cancel 属于用户明确取消指令,不再弹二次确认,返回“正在取消”或真实终态,并说明已有写入可能保留。
-
-历史只持久化经过处理的命令摘要及任务 ID,args 不落盘;含高级参数的原始命令不得进入现有命令历史、entry title 或错误文本。重用历史时提示补齐参数。
-
-表单“复制命令”采用统一转义生成器,并与解析器做往返验证。正常公开字段可复制,默认省略 args;复制内容必须与当前表单实际值一致。
-
-## 8. 接口补充设计
-
-本节均为拟新增契约,不能当作当前接口已支持。
-
-### 8.1 创建及公开请求
-
-现有请求保持兼容:
-
-```json
-{
- "from": ["viking://resources/weekly"],
- "to": "viking://resources/wiki",
- "skill": "viking://agent/skills/monthly_wiki",
- "instruction": "按主题整理,保留来源"
-}
-```
-
-前端通过适配层读取 `meta.request`,不要让页面散落依赖任意 meta 字段。无参数快照时禁用自动回填并解释原因。
-
-### 8.2 创建幂等
-
-为 `POST /api/v1/compile` 增加可选 `Idempotency-Key`。幂等范围为连接对应服务内的 account、user、操作类型及 key。
-
-- 同 key、同规范化请求返回同一 task_id;同 key、不同请求返回明确冲突。
-- 请求校验失败不产生任务;校验通过后的幂等登记与任务创建必须具备原子保证。
-- 并发请求和服务重启不能产生重复任务,需持久化幂等关联。
-- 建议幂等映射至少保留 24 小时,并在契约中说明保留期;超出保留期不自动重发。
-- 浏览器仅保存 key 与确认状态,不持久化 args。页面恢复后可通过下述 lookup 找回已创建任务。
-- 拟增加 `GET /api/v1/compile/submissions/{key}`:在相同身份下返回已关联任务或明确的未找到;不得返回私有请求。
-- lookup 未找到但原请求可能仍在途时,同 key 重试仍由原子幂等处理,不能改用新 key。
-
-现有 provider 的内部幂等 key 以已生成的 OV task_id 为基础,不能替代浏览器重复创建请求的幂等保护。
-
-### 8.3 任务分页与搜索
-
-为通用列表增加显式分页模式,避免破坏当前数组返回值:
-
-```http
-GET /api/v1/tasks?pagination=cursor&task_type=compile&limit=30&status=running&q=wiki
-GET /api/v1/tasks?pagination=cursor&task_type=compile&limit=30&status=running&q=wiki&cursor=opaque-token
-```
-
-```json
-{
- "status": "ok",
- "result": {
- "items": [],
- "next_cursor": null,
- "has_more": false
- }
-}
-```
-
-- 未传 `pagination=cursor` 时保持现有数组返回,现有 CLI 和 Tasks 调用不受影响。
-- 服务端使用 `created_at DESC, task_id DESC` 的键集分页,过滤先于分页;读取 `limit + 1` 判断 has_more。
-- cursor 是服务端生成的不可随意篡改标识,绑定排序版本、过滤条件和身份范围。过期或条件不匹配返回明确错误,前端提示重新加载。
-- `q` 只对明确的公开字段搜索,不读取私有 args;新 Compile 页固定 `task_type=compile`。
-- 从持久化存储层实现分页,不能延续“全部读入内存再截取”的做法来声称完成服务端分页。
-- ROOT 的可见范围、系统任务及普通身份隔离沿用现有权限规则;分页、搜索不得扩大可见范围。
-- 列表按 task_id 去重;状态变化导致筛选集合变化时,以刷新重新建立列表为准。
-- total 暂不返回,避免额外计数和不稳定总数产生误导。
-
-### 8.4 能力查询
-
-拟增加 `GET /api/v1/compile/capabilities`,用于当前身份的入口提示,至少返回:
-
-```json
-{
- "status": "ok",
- "result": {
- "configured": true,
- "can_create": true,
- "reason_code": null
- }
-}
-```
-
-configured 仅表示已配置执行后端,不承诺 Runtime 此刻健康。can_create 表示静态配置与身份允许尝试创建,不替代 URI 权限检查。不得返回 gateway token、API Key 或内部地址。网络故障作为查询失败处理,不能返回 configured=false。
-
-取消能力依旧按角色、任务状态和后端响应判断。若后续统一任务接口提供 allowed_actions,前端再迁移使用,第一版不依赖尚不存在字段。
-
-## 9. 状态、数据隔离与组件复用
-
-所有 Query key、草稿和内存交接包含当前连接及 identityScopeKey;切换身份时中止旧请求、清空可见旧数据。每个任务 ID 在同一身份下共享缓存,避免终端、详情和列表互相显示过期状态。
-
-建议模块边界:
-
-| 模块 | 职责 |
-| --- | --- |
-| Compile API 适配层 | 创建、能力、幂等恢复、分页、详情、取消 |
-| Compile 列表页 | 筛选、分页、列表状态及导航 |
-| Compile 新建页 | 草稿、字段编排、提交状态 |
-| Compile 详情页 | 状态、配置、执行记录、结果、操作 |
-| Skill 选择器 | 搜索、选择和当前内容预览 |
-| Viking 目录选择器 | 浏览、单选/多选、粘贴 URI、局部错误 |
-| Compile 表单模型 | 参数归一化、校验、公开回填、命令生成 |
-| 终端命令模块 | tokenize、compile/task 解析、回执、历史脱敏 |
-
-复用 Studio 的按钮、表单、目录浏览、任务状态和事件组件,不复制一套任务生命周期实现。业务文件保持职责单一,单文件不超过 800 行。
-
-## 10. 视觉、可访问性与文案
-
-- 沿用现有 Studio 主题、排版、间距和 Lucide 图标,不为 Compile 引入另一套设计语言。
-- 每页只有一个突出主动作:列表“新建编译”、表单“开始编译”、完成详情“打开输出目录”。
-- loading、空数据、错误和无权限必须是可区分状态。
-- 字段有真实 label、必填标识和关联错误;目录选择器支持键盘操作,弹层关闭后焦点返回触发按钮。
-- 状态变化采用适度的 aria-live 提示,不每次轮询朗读整页。
-- URI 可复制、可换行;截断只用于列表,详情始终可查看完整值。
-- 所有文案通过中英文 i18n 管理;错误原文保留在技术详情中。
-- 移动端表格退化为紧凑列表,表单保持单列;主要按钮满足可触达尺寸。
-
-## 11. 关键流程验收
-
-| 场景 | 验收标准 |
-| --- | --- |
-| 首次创建 | 空列表 → 新建 → 选 Skill、两个素材目录、输出 → 提交 → 详情,可打开结果 |
-| 查看历史 | 进入列表、筛选、加载更多、点击详情、返回,筛选和位置不丢失 |
-| 超过 200 条 | 能通过服务端游标访问更早记录,不局限于内存中的 200 条 |
-| Skill 不可用 | 清楚显示缺失或权限问题,保留其它表单值,可替换 Skill |
-| 参数错误 | 定位具体字段;非法 JSON 不发送请求;含空格指令完整保留 |
-| 双击与网络超时 | 双击只产生一个任务;超时使用相同 key 恢复到同一个 task_id |
-| 刷新页面 | 详情恢复服务端状态;公开草稿恢复;args 不泄露或静默回填占位值 |
-| 取消竞争 | 运行中取消、取消请求失败、同时完成等情况均显示服务端最终状态 |
-| 再次运行 | 回填公开参数,可修改;原任务保留,新提交产生新 task_id |
-| 执行失败 | 显示可读错误和技术详情,可调整参数再次提交,可查看已有目标 |
-| 状态断连 | 保留最后状态并提示更新时间,不将网络错误映射为任务失败 |
-| 终端互通 | 带引号、重复 from、JSON args 正确解析,提交回执可打开同一详情 |
-| 身份切换 | 列表、详情缓存和草稿不串号;旧请求不能覆盖新身份页面 |
-| 结果不完整 | result 为空、未知结构、无事件时页面仍可操作,不显示虚构统计 |
-| 历史与敏感参数 | 终端命令历史、草稿、URL、错误提示不保存原始 args |
-| 可访问性 | 键盘完成创建与查看,错误可聚焦,状态不只依赖颜色 |
-
-验证分三层:参数解析和状态模型的单元验证;真实 API 契约与分页/幂等/权限验证;浏览器端到端验证。构建或类型检查通过不能替代真实创建、取消和结果浏览的验证。
-
-## 12. 实施顺序与完成条件
-
-1. **后端契约**:完成分页与公开字段搜索、创建幂等及恢复、能力查询;保持旧任务列表返回兼容,更新 OpenAPI。
-2. **基础模块**:同步 Studio SDK,完成 API 适配层、目录/Skill 选择器、表单模型和身份隔离。
-3. **独立页面**:交付列表、新建、详情三页及公开草稿、状态刷新、结果入口。
-4. **终端接入**:完成语法解析、补全、回执、task 操作、命令复制及持久历史处理。
-5. **联动与验收**:通用 Tasks 添加 compile 类型和详情链接,跑通上述关键流程。
-
-完成标准是两个入口使用相同任务模型,用户能够创建、追踪、取消、恢复、再次运行并找到结果,历史浏览具备真实分页。接口增强未完成时可开发页面,但不能把模拟数据或本地分页作为完整交付。
-
-## 13. 源码依据
-
-- `openviking/server/routers/compile.py`:创建路由。
-- `openviking/service/compile_service.py`:请求模型、URI 校验、执行后端配置、结果快照。
-- `openviking/service/external_task_service.py`:公开请求保存、外部执行任务生命周期。
-- `openviking/server/routers/tasks.py`:任务详情、列表和取消。
-- `openviking/service/task_tracker.py`:TaskRecord 与现有列表读取逻辑。
-- `web-studio/src/components/app-shell.tsx`:导航结构。
-- `web-studio/src/routes/tasks/route.tsx`:现有通用任务页。
-- `web-studio/src/routes/tasks/-components/task-detail-sheet.tsx`:任务查询、事件展示与刷新基础。
-- `web-studio/src/routes/playground/-components/terminal-panel.tsx`:现有终端解析、历史和回执。
-- `crates/ov_cli/src/commands/compile.rs`、`crates/ov_cli/src/main.rs`:原生 CLI 参数和 task 命令。
-
-## 14. 本分支实现说明(2026-09-16)
-
-`feat/studio-compile` 实现独立列表、新建与详情页面,以及 Playground 终端的 `compile` / `task` 命令。支持 Skill 查询与内容预览、目录浏览与多来源输入、公开草稿、参数回填、取消、结果目录跳转、中英文文案和终端到表单的内存参数交接。
-
-服务端增加可选游标分页、公开字段搜索、Compile 能力查询、`Idempotency-Key` 创建去重及提交结果查询;未启用游标模式的任务列表保持数组返回。
-
-实现边界:
-
-- AGFS 当前没有任务索引查询,分页逐条扫描持久化记录,通过有界堆保留当前页,不把所有任务载入 TaskTracker。记录对象内存受页大小约束,目录枚举和读取成本仍随历史记录数量增长;不是索引级查询。
-- 游标包含身份、角色和筛选范围,并使用当前服务进程的密钥签名。服务重启后旧游标失效,刷新列表可恢复。多实例部署需要共享游标签名配置。
-- 幂等标识派生为稳定任务 ID,参数摘要保存在任务记录中但不通过公共 API 回显;同标识的并发创建与恢复在当前实例内串行。已创建请求先按身份及规范化请求摘要恢复,不重新依赖素材、Skill 或执行后端仍然可用;新请求仍执行完整资源与权限校验。保障建立在现有单 TaskTracker 写入者模型上,多写入者部署仍需存储级 CAS。
-- 幂等恢复与任务记录共用保留周期。当前 tracker 对完成/取消任务保留 24 小时,对失败任务保留 7 天;此功能不新增永久历史。页面对超过 24 小时的持久提交标识停止自动重发。分页扫描会清理当前身份目录中的过期记录,清理前在任务锁内复查状态;不将全量历史载入缓存。
-- 公开高级参数可从历史任务回填,但不保存到浏览器草稿。复制命令默认不包含高级参数;没有“一键复制私有参数”的入口。
-- 结果页面提供输出目录入口及后端原始结果;不假设不同 Runtime 已统一产物清单、进度百分比和完成时间字段。
-- 本地验证包含后端 HTTP/持久化测试、前端单元测试及浏览器可控 API 场景。真实执行服务与模型产物需要部署环境联调验证。
diff --git a/docs/design/web-studio-vikingbot.md b/docs/design/web-studio-vikingbot.md
deleted file mode 100644
index c3d2c81f0..000000000
--- a/docs/design/web-studio-vikingbot.md
+++ /dev/null
@@ -1,304 +0,0 @@
-# Web Studio VikingBot 产品与实现方案
-
-状态:设计与首期实现说明。首期支持网页对话与飞书接入,其他 IM 在 Studio 中标注“开发中”。
-
-## 当前分支实现说明
-
-- 页面入口 `/vikingbot`;新增管理接口集中在 `/api/v1/admin`,网页聊天继续复用原有接口。
-- 飞书连接和收发时间线持久化到 Bot 数据目录的 `studio.sqlite3`,文件权限 0600。它含应用与专用用户凭证,备份需按服务端配置处理。
-- Studio 管理的飞书会话仅开放带绑定身份的 OpenViking 查询与记忆工具;Shell、本地文件、定时任务及未显式批准的 MCP 工具默认不可用。
-- 首期仅服务管理员可管理渠道;按当前 account 隔离连接及飞书历史。接入时选择同账户普通用户,由服务端绑定现有凭证;浏览器无需接收或输入用户 API Key。管理员身份不可选,仅存储哈希而无法自动绑定凭证的用户显示不可用。
-- 受管启动时自动为父子进程生成内部管理令牌,不写回配置文件。独立 Gateway 需要额外的管理部署支持。
-- 默认使用三步扫码接入:选择运行用户 → 飞书扫码自动建应用、配权限事件并提交发布 → 添加到群验证。保留单表单手动配置作为已有应用和故障恢复入口。支持凭证更新、暂停/恢复、重启恢复连接、群内短期验证码与独立收发验证。
-- 飞书时间线展示 Studio 连接建立后捕获的消息,不自动接管原 ov.conf 渠道或补录它们的旧历史。既有渠道的迁移需要后续显式绑定与身份确认。
-- 支持暂停连接并保留历史,也支持确认后删除连接及其本地收发记录。删除不会删除飞书应用或飞书中的消息。飞书会话首期只读。
-- 受管 Agent 会话以连接 ID 隔离;删除重建后不继承旧连接上下文,也不发送旧连接未完成的回复。同一连接暂停恢复或重启后仍可续接。此前未按连接隔离的 Agent 历史不自动迁移,Studio 已捕获的只读消息记录不受影响。
-- 自动化和模拟接口浏览器验证不等同真实飞书群验收;真实收发仍需部署后使用应用凭证与测试群验证。
-
-
-## 接口范围与复用依据
-
-路由遵循仓库管理接口约定:`/api/v1/admin` 为管理前缀,账号在 URL 中指定,router 自身声明 prefix/tags,并由 `routers/__init__.py` 导出、`app.py` 统一挂载。业务管理仍仅允许 ROOT,不能因挂入 admin 前缀而放宽为账号 ADMIN。
-
-以下表格用 `B` 代表 `/api/v1/admin/accounts/{account_id}/bot`:
-
-| HTTP 路由 | 调用场景与契约 |
-| --- | --- |
-| `GET /api/v1/admin/bot/capabilities` | 判断 Bot 启用及 ROOT 管理能力;与运行健康检查职责不同。 |
-| `GET /api/v1/admin/accounts/{account_id}/users?role=user&include_credentials=false` | **复用现有接口**。返回 `user_id`、`role`、`api_key_available`,不返回密钥或前缀。默认参数保持原有接口行为。 |
-| `GET B/connections` | 渠道列表、混合会话来源、扫码完成后加载连接。 |
-| `POST B/connections` | 手动连接;请求包含 `type`、`user_id`、平台自有的 `credentials` 对象。 |
-| `PATCH B/connections/{id}` | 更新 `enabled`;提交 `revision` 保留并发保护。 |
-| `DELETE B/connections/{id}?revision=N` | 删除连接及其本地记录;不删除外部平台应用。 |
-| `POST B/connections/{id}/credentials` | 更新平台凭证,包含 `credentials`、`user_id`、`revision`;服务端重新绑定身份。 |
-| `POST B/connections/{id}/verifications` | 发起可选群验证,提交 `revision`。 |
-| `GET B/connections/{id}/conversations` | 连接下的收发会话列表。 |
-| `GET B/connections/{id}/messages?conversation=...&before=...` | 捕获消息及发送状态;平台会话标识保留在查询参数中。 |
-| `POST B/onboarding-runs` | 创建自动接入任务,显式传 `type`、`user_id`、`request_id` 和可选 `name`。 |
-| `GET B/onboarding-runs/current?type=...` | 查询指定平台当前未完成任务;没有任务时返回 null。不是全量任务列表。 |
-| `GET B/onboarding-runs/{id}` | 轮询指定任务。 |
-| `POST B/onboarding-runs/{id}/actions` | 请求体 `action` 严格限定为 `retry`、`cancel`、`manual`,保留各操作的状态校验。 |
-
-浏览器管理接口共 13 个,加上复用的用户列表接口。扫码任务的重试、取消和转手动共用一个 actions 接口,连接生命周期保持独立方法。Studio 管理路由及 Gateway 内部 dispatch 均不进入 OpenAPI schema;接口仍正常注册并保留原鉴权。旧的 `PATCH {action: ...}` 和 `X-OpenViking-Studio-Account` 已移除。该变更调整当前未发布 PR 内的接口,前后端需一起更新;不为旧的临时浏览器接口保留兼容入口。
-
-网页会话创建、列表、历史、删除、Bot 聊天流式响应和健康状态继续复用既有 API。平台收发记录按连接归属并保存发送状态,不能直接替换为 OpenViking 上下文会话历史。
-
-`POST /bot/v1/studio/dispatch` 仅在 Bot Gateway 内部保留,用内部令牌及 loopback 限制服务端调用。浏览器不直接调用;账号和绑定用户仍在 OpenViking 服务端校验。
-
-### 后续接入钉钉等平台
-
-- URL 按连接和接入任务组织,不含飞书或钉钉名称。平台由显式 `type` 决定;未知平台由 provider registry 拒绝,不能默认为飞书。
-- 平台凭证放入 `credentials` 对象,例如飞书使用 `app_id/app_secret`,后续平台可以使用自己的字段。具体校验、连接运行、凭证更新及公开配置字段由 provider 负责;浏览器不能借凭证字段替换服务端身份。
-- 暂停、恢复、删除、收发记录和任务查询共享资源接口。各平台的授权实现与前端表单放入 provider 目录;平台特有能力不应直接加入全局路径或假设所有平台支持扫码/群验证。
-- 当前仍只注册飞书 provider。新增钉钉需要实现它的鉴权、连接、消息转换和 UI,并验证其接入状态流;通用路由不是钉钉功能已完成的证明。
-
-未使用的定时任务接口及 UI、旧独立飞书会话列表、旧 `step` 操作已删除,既有 CLI/Agent 定时任务功能不受影响。
-
-## 1. 用户目标与首期范围
-
-用户可以在 Web Studio 中直接与 VikingBot 对话、查阅历史,并通过完整引导将同一个 Bot 接入飞书群。网页和各个群的对话上下文独立;共用 Bot 不代表共享所有会话或个人记忆。
-
-首期交付:
-
-- 一级导航新增 **VikingBot**,包含“对话”和“渠道”两个页面。
-- 网页新建对话、流式回复、停止生成、继续历史对话。
-- 查看有权限访问的网页、飞书单聊、普通群、话题群历史。
-- 飞书接入向导、连接检查、群内验证、暂停和恢复连接。
-- Slack、钉钉、Discord、Telegram 等展示“开发中”,无配置表单、无可点击的接入按钮。文案说明“Studio 接入管理开发中”,避免误称底层完全不支持。
-
-首期不提供从 Studio 代发群消息、导入机器人入群前的飞书历史、跨群共享上下文。网页聊天不依赖飞书配置完成。
-
-## 2. 页面结构
-
-```text
-VikingBot Bot 运行正常
- 对话 | 渠道
-
-对话页
-┌──────────────────┬──────────────────────────────────┐
-│ 新建对话 │ 项目讨论群 · 飞书 │
-│ 搜索对话 │ 机器人收到的消息与回复 │
-│ 全部 / 网页 / 飞书 │ 姓名、时间、正文、发送状态 │
-│ │ │
-│ 今天 │ 工具调用默认折叠 │
-│ 需求分析 · 网页 │ │
-│ 项目讨论群 · 飞书 │ 此会话来自飞书,请前往飞书继续对话 │
-└──────────────────┴──────────────────────────────────┘
-```
-
-“对话”默认选中最近一次打开且仍有权限的会话,否则显示欢迎页。窄屏先显示列表,选择后进入详情,提供返回列表操作。
-
-列表显示标题、来源、最后消息摘要和时间;飞书话题显示“群名 / 话题摘要”。不向普通用户暴露群 ID、消息 ID 或内部 SessionKey。名称暂不可用时显示“飞书群聊(名称待同步)”,技术 ID 仅在管理员诊断详情中展示。
-
-“渠道”页包含网页渠道、已连接的飞书应用、添加飞书应用按钮,以及其他 IM 的开发中卡片。一个应用可以服务多个群;应用连接和群会话分别展示,不把一个群建成一个渠道。
-
-## 3. 首次启用与网页对话
-
-### 3.1 进入页面
-
-页面分别检测 Bot 服务、模型配置和当前身份权限:
-
-| 状态 | 页面文案与操作 |
-|---|---|
-| Bot 未启用 | “先启用 VikingBot”;管理员看到 `openviking-server --with-bot` 与部署说明,普通用户看到“请联系管理员启用” |
-| 服务不可达 | “暂时无法连接 VikingBot”;显示重试与管理员诊断入口,不清除已有历史 |
-| 模型未配置 | “配置对话模型后即可开始”;链接现有模型配置说明,说明默认继承根级 `vlm` |
-| 可以使用 | “开始与 VikingBot 对话”;主按钮“新建对话”,次按钮“连接飞书” |
-
-读取配置只代表模型已配置,不代表调用成功。首次正常对话成功后记录模型可用;模型调用失败保留输入并提供重试。
-
-### 3.2 开始与继续对话
-
-1. 点击“新建对话”,输入问题。
-2. 首次发送时建立持久会话;提交接受前保留输入、阻止重复发送。
-3. 流式展示回答,工具调用折叠展示,支持停止生成。
-4. 左侧立即出现新会话,标题取首条问题,可重命名。
-5. 刷新、重新登录或服务重启后,可重新打开历史继续对话。
-
-切换会话、取消或卸载页面时,旧请求不能覆盖新会话内容。停止浏览器流不自动表示服务端任务已取消;产品只有在服务端确认取消后才显示“已停止”,否则显示“已停止接收,任务可能仍在运行”。
-
-## 4. 飞书接入流程
-
-### 默认:扫码自动配置
-
-1. 选择当前账户的普通用户,填写机器人名称(默认 VikingBot),点击生成二维码。页面事先说明将创建应用及申请的权限。
-2. 用飞书扫码并在手机确认。服务端用该次登录会话创建应用、开启机器人和长连接,申请 `im:message.group_at_msg:readonly`、`im:message:send_as_bot`、`im:chat:readonly`,订阅 `im.message.receive_v1`,创建并提交首个版本。
-3. 读取版本状态:已上线后展示加群指引;审核中则等待管理员审批。添加到群后生成测试消息,分别确认收到消息、飞书接受回复以及用户在群内看到回复。
-
-初始应用可用范围仅包含扫码创建者。扩大群成员可用范围需要在开放平台调整并发布。
-
-扫码登录参考 Botmux 的 Web 会话路径,使用飞书开放平台控制台接口,不是第三方 OAuth 安装接口。平台契约集中在飞书适配器,变更时可回退手动接入。不会使用开发机已有 Botmux 或浏览器登录凭证。
-
-任务和创建/发布检查点保存在 SQLite;Cookie、二维码 token 和 flow key 仅存在服务端任务内存中。二维码两分钟过期,等待审批最长保留会话十分钟。超时、服务重启后重新扫码,必须匹配原账号和企业。创建、创建版本与发布请求不自动重放;结果未知时引导检查开放平台。页面刷新恢复原任务,不重复创建应用。
-
-### 备用:已有应用或手动恢复
-
-以下六步仅用于手动接入。
-
-
-入口:“渠道 → 添加飞书应用”。采用独立页面式向导,左侧步骤,右侧操作与说明。每步可返回;退出后保留服务端草稿并支持“继续配置”。密钥不写入浏览器本地存储。
-
-首次说明:“将 VikingBot 加入飞书群,在群里 @机器人即可对话。你需要飞书企业自建应用的管理权限,以及目标群添加机器人的权限。”首期引导面向企业内部群,外部群不承诺支持。
-
-### 第一步:创建应用
-
-1. 点击“打开飞书开放平台”:https://open.feishu.cn/app 。
-2. 创建企业自建应用,设置名称和头像。
-3. 在应用能力中添加“机器人”。
-4. 返回 Studio,点击“下一步:连接应用”。
-
-说明这是支持接收消息的应用机器人;仅有群 Webhook 地址不能完成此流程。
-
-### 第二步:连接应用
-
-填写 App ID 与 App Secret,提供“在哪里找到?”说明:进入应用的“凭证与基础信息”。Secret 默认隐藏,保存后仅显示“已配置”,支持替换。
-
-点击“验证并建立连接”:服务端验证凭证,尝试获取机器人名称和身份,保存草稿并启动长连接。成功后展示机器人名称及头像;无法自动获取时说明缺失条件,名称允许补填,但不能用名称匹配替代可靠的机器人身份识别。
-
-状态依次展示“验证凭证 → 建立长连接”。凭证通过但连接失败时分别显示结果。SDK 初始化成功不算连接成功,需要实际连接证据。
-
-建立长连接后再引导配置事件,避免用户在飞书选择长连接时因为服务尚未启动而无法继续。
-
-### 第三步:配置权限与事件
-
-提供逐条可复制的权限/事件说明及官方链接,默认只配置“群内 @机器人回复”所需能力:接收群 @消息、以机器人身份发送消息;启用单聊时增加接收单聊消息能力。群名称、成员名称、图片相关权限按使用功能补充。
-
-实现时维护经过官方核验的权限清单及批量导入内容,不能直接把旧文档中的笼统 `im:message` 当成完整权限模板。平台权限标识与展示名称应同时列出。
-
-事件订阅选择“使用长连接接收事件”,添加 `im.message.receive_v1`。首期不要求填写公网回调 URL、Encrypt Key 或 Verification Token。
-
-提供“检查配置”按钮。可由 API 检测的项目显示结果;无法读取的订阅/发布状态显示“待群内验证”,用户勾选只表示已完成操作,不显示自动检测通过。
-
-### 第四步:发布应用
-
-引导前往“版本管理与发布”,创建版本,设置适当的可用范围并提交发布。需审批时显示“等待管理员审批”,允许保存退出。权限或事件调整后,提示检查是否需要重新发布。
-
-“我已发布,继续”进入下一步,但不改变技术验证结果。
-
-### 第五步:添加到群并验证
-
-1. 在飞书打开目标群,通过群设置中的机器人入口添加刚创建的应用机器人。
-2. Studio 生成一条带短期随机验证码的测试消息,例如 `@VikingBot 连接测试 7K2P`,提供复制按钮;提示在飞书使用真正的 @ 选择机器人,复制的纯文本不等于 mention。
-3. 用户在目标群发送测试消息,Studio 等待该应用收到匹配验证码的事件。
-4. Bot 返回固定测试确认,不调用模型、不执行工具、不写入长期记忆。随后更新验证状态。
-
-验证拆成三项:“收到群消息”“回复已被飞书接受”“群内可见”。前两项使用入站事件与发送 API 回执验证,最后一项由用户确认或后续已验证的平台能力确认。发送 API 成功不声称消息已读。
-
-只把当前草稿应用、有效期内、匹配验证码的事件绑定为本次验证;重复事件不重复建群、不重复回复。超时后可生成新验证码重试。
-
-完成页显示群名、机器人名、“仅 @时回复”,操作为“查看该群会话”“再连接一个群”“完成”。增加其他群复用当前应用,从本步骤开始。
-
-未收到消息时提供按顺序排查:应用是否已发布且可用范围正确、机器人是否已入群、是否使用真正的 @、事件与权限是否生效、长连接是否正常。收到消息但发不出去时,定位发送权限、机器人是否仍在群中及飞书返回错误。
-
-### 第六步:正常使用
-
-提示用户在群里 @机器人提出一个真实问题。该步骤验证模型对话链路;固定测试通过但模型失败时显示“飞书已接通,对话模型调用失败”,不要求用户重做渠道配置。
-
-## 5. 飞书历史与日常管理
-
-飞书历史展示 VikingBot 实际收到、持久化的消息以及自身回复。首次显示提示:“仅展示机器人接入后收到的消息,不包含完整群历史。”未授权接收的非 @消息不会凭空出现在列表里。
-
-普通群按群组织,话题群按话题组织。飞书单聊独立展示。消息包含发送人、时间、正文及已支持的附件;不支持的消息类型显示明确占位,不丢弃整条记录。生成失败、发送失败和发送成功分开标识。
-
-飞书会话详情首期只读,底部固定提示“请前往飞书继续对话”。有可靠平台链接时提供“在飞书打开”;没有时展示群名和操作说明,不拼造跳转链接。
-
-应用详情展示:连接状态、最近收消息时间、最近成功回复时间、最近错误、已发现的群、接入向导进度。明确“已发现的群”为收到过消息的群,不声称枚举了全部已加入群。
-
-支持更新凭证、重新检测、暂停与恢复;暂停停止接收新任务,已有任务按明确的排空策略结束,保留历史。删除连接需要二次确认,并说明不会自动删除飞书应用或历史。凭证更新失败保留原连接,不能破坏其他渠道。
-
-首期固定推荐“仅 @机器人时回复”。不开放“所有群消息自动回复”,避免额外权限、消息量和话题规则使首次引导复杂化。
-
-## 6. 身份、权限和上下文
-
-- 渠道配置及密钥修改仅管理员可用;服务端逐接口鉴权,不能仅隐藏按钮。
-- 首期群历史仅对该连接所属管理范围内的管理员开放。普通 Studio 用户只查看自己的网页会话;后续另行实现飞书成员身份绑定与按群授权。
-- 外部应用必须绑定明确的 OpenViking account/workspace 与运行身份;无绑定或无权限时拒绝启用,不回退 root 身份。
-- 群会话不得继承管理员私人网页会话或个人记忆。群可访问资源与记忆范围使用受限的渠道身份配置。
-- 列表、搜索、详情、附件、流事件均使用同一服务端权限过滤;禁止先全量返回再由前端过滤。
-- 群历史中的文字只是消息内容,不作为 Studio 管理指令执行。
-
-## 7. 当前可复用能力与需要补齐的能力
-
-基于当前仓库代码核对:
-
-| 能力 | 现状 | 实现工作 |
-|---|---|---|
-| 网页聊天 | Studio 已有 `useChat`、Composer、MessageList,Server 代理 Bot 流式接口 | 复用组件与请求生命周期,增加独立入口 |
-| 网页历史 | Studio 当前读取 OpenViking Session 与归档 | 复用持久历史,避免另建重复会话 |
-| Bot 历史 | Bot SessionManager 持久化并可列举;OpenAPI `/sessions` 使用运行时内存索引 | 新增持久化的统一会话索引和权限过滤 |
-| 飞书群 | 已有长连接、普通群与话题群处理 | 增加向导、配置 API、身份检测、验证回执 |
-| @识别 | 当前基于 `bot_name` 匹配 mention 名称 | 改为机器人稳定身份匹配,兼容已配置名称 |
-| 渠道生命周期 | 配置加载与启动已有;文档要求修改配置后重启 | 新增单渠道受控应用配置、替换、暂停、恢复与回滚 |
-| 运行状态 | `_running` 与启动日志不能证明连接和消息收发正常 | 增加实际连接、入站、出站的独立状态与时间戳 |
-
-## 8. 建议接口与数据契约
-
-以下均为拟新增能力,不代表现有 API 已提供。Studio 统一访问 OpenViking Server,由 Server 进行鉴权并调用受管 Bot。
-
-| 接口 | 用途 |
-|---|---|
-| `GET /bot/v1/capabilities` | 当前用户权限、Bot 状态、支持的渠道与管理能力 |
-| `GET /bot/v1/conversations` | 按来源、关键词及游标列出有权限的持久会话 |
-| `GET /bot/v1/conversations/{id}/messages` | 分页读取统一时间线 |
-| 当前管理接口 | 以本文“接口范围与复用依据”的表格为准;不存在独立的 validate/apply/status HTTP 接口。 |
-
-网页发送继续复用现有 chat/stream 接口;统一 conversation ID 必须能映射到原 Session ID。飞书会话不提供网页发送接口。
-
-Conversation 索引保存:权限作用域、来源、连接、原始会话引用、群/话题显示信息、最近活动时间。原始身份标识仅服务端保存。历史正文沿用现有存储,索引不复制两份消息;同一 Bot 会话关联的 OpenViking 会话必须去重映射。
-
-历史消息区分 generated、send_failed、sent 等状态;不能把模型输出视为已发送。旧历史缺少发送证据时标注“发送状态未知”。已有会话迁移时不能推测拥有者;无法确定权限归属的记录暂不对普通用户开放。
-
-连接使用 draft、connecting、connected、degraded、paused、error 等运行状态;配置验证、群内测试另设独立结果。刷新页面和服务重启不丢失引导步骤,但运行状态须重新探测。
-
-首期管理能力限定为 Server 受管 Bot。外置 Gateway 未实现管理协议时显示“当前部署暂不支持在 Studio 配置渠道”,仍可使用已授权的网页聊天,并提供配置文件说明;不显示注定失败的表单。
-
-密钥只在写请求中提交,响应、日志及诊断导出均不回显。沿用服务端配置位置,采用严格文件权限、原子写入与版本校验,保留不相关配置。只读配置部署返回明确原因与管理员操作指引。
-
-## 9. 实施顺序与验收
-
-第一阶段:独立入口和网页闭环。复用聊天组件、完成可持久的会话索引与身份契约。验证首条发送失败可恢复、切换无串话、重启后历史可读、多身份隔离。
-
-第二阶段:飞书向导和连接管理。完成配置草稿、凭证校验、单渠道应用、身份匹配、真实连接状态、群内验证码收发。验证错误密钥、未发布、未订阅、断网、重复事件、配置失败回滚与刷新续接。
-
-第三阶段:飞书历史与完整验收。展示群名、成员名、话题、附件占位、回复结果;新增其他 IM 开发中卡片。通过真实飞书群完成一次正常 @问答,核对 Studio 历史和平台回复一致。
-
-首期发布必须同时满足:
-
-1. 新用户能从服务未启用状态沿引导走到一次网页成功对话。
-2. 管理员可从零完成飞书应用连接、发布、入群和真实问答;中断后可继续。
-3. 改名后的机器人仍可正确识别 @;普通群与不同话题不串上下文。
-4. 页面重载及 Bot 重启后历史和配置仍可恢复;无内存索引依赖导致的历史消失。
-5. 群消息发送失败不会显示成功;凭证正确不会直接显示“接入完成”。
-6. 无权限用户无法通过接口枚举群历史或读取密钥;群问答无法读取管理员私人记忆。
-7. 其他渠道清楚显示“Studio 接入管理开发中”,不提供虚假可用入口。
-
-## 10. 依据
-
-- 仓库:`web-studio/src/lib/sessions/api.ts`、`web-studio/src/routes/playground/-components/agent-panel.tsx`。
-- 仓库:`bot/vikingbot/channels/openapi.py`、`bot/vikingbot/session/manager.py`、`openviking/server/routers/bot.py`。
-- 仓库:`bot/vikingbot/channels/feishu.py`、`bot/vikingbot/channels/manager.py`、`bot/vikingbot/config/schema.py`、`bot/docs/zh/concepts/05-channel.md`。
-- [飞书开放平台:事件订阅方式](https://open.feishu.cn/document/server-docs/event-subscription-guide/event-subscription-configure-/request-url-configuration-case)与[接收消息事件](https://open.feishu.cn/document/server-docs/im-v1/message/events/receive):实现时核对最新权限与事件要求;本次抓取页面未返回正文,不据此宣称精确权限模板已验证。
-- [飞书官方:配置机器人能力与发布应用](https://www.feishu.cn/content/425524486655):用于机器人能力和发布步骤参考。
-
-
-## 多 IM 目录边界
-
-- `bot/vikingbot/studio/service.py`:账号隔离、持久化、版本冲突和连接生命周期。
-- `bot/vikingbot/studio/providers/registry.py`:按连接 `type` 选择平台适配器;旧记录默认飞书,未知类型拒绝接入。
-- `bot/vikingbot/studio/providers/feishu/`:凭证校验、引导动作、消息接收和长连接协议。扫码会话、控制台协议和自动配置也集中在此目录。
-- `web-studio/src/routes/vikingbot/-providers/registry.ts`:注册各平台的引导和凭证组件。
-- `web-studio/src/routes/vikingbot/-providers/feishu/`:飞书专属界面和测试。
-- 公共会话、历史记录和渠道列表保留在 `-components/`。
-
-新增 Slack 等平台时,新增对应 provider 目录并注册,复用连接生命周期和历史存储。平台特有权限、扫码或 OAuth 状态不进入公共服务。当前仅飞书可接入,其他平台保持“开发中”。扫码初始化已通过真实飞书接口验证;登录后建应用、审批和群收发仍需真实账号验收。
-
-
-### 扫码任务与回复配置
-
-浏览器使用 `/api/v1/admin/accounts/{account_id}/bot` 下的 `onboarding-runs` 创建任务,`onboarding-runs/current?type=feishu` 恢复任务,`onboarding-runs/{id}` 查询状态,以及 `POST onboarding-runs/{id}/actions`(`action` 为 `retry`、`cancel`、`manual`)。所有接口复用 root 管理认证和 account 隔离;返回状态白名单不含凭证、Cookie 或原始上游错误。
-
-扫码和手动创建均提供“群聊回复方式”,通过已有创建接口的 `settings.thread_require_mention` 保存,默认为 `true`。已创建连接通过已有 `PATCH connections/{id}` 提交 `settings` 和 `revision` 修改;一次请求只能修改 `enabled` 或 `settings` 之一。设置立即更新运行中的渠道,并持久化供重启或恢复时加载,旧记录保持原默认行为。
-
-关闭该设置后,普通群消息无需 @;话题首条消息无需 @,后续话题回复仍需 @(DEBUG 模式例外),私聊不受影响。扫码创建按选项申请 `im:message.group_msg` 权限;手动接入或创建后切换时,用户需在飞书开放平台补充接收未 @ 群消息的权限并发布应用。保存本地设置不代表飞书权限已生效。
-
-`settings` 由对应平台 provider 校验和应用,飞书仅接受布尔型 `thread_require_mention`。未来钉钉等平台可扩展自己的设置而无需增加平台专属路由。
diff --git a/docs/design/workspace-config-and-peer-source-rfc.md b/docs/design/workspace-config-and-peer-source-rfc.md
deleted file mode 100644
index ee31c4f08..000000000
--- a/docs/design/workspace-config-and-peer-source-rfc.md
+++ /dev/null
@@ -1,327 +0,0 @@
-# RFC: Workspace 分层配置与可配置 Peer 来源
-
-## TL;DR
-
-**问题**:目前 OpenViking 使用「当前工作目录(CWD)」作为项目身份(peer)。这导致工作目录一旦改变,项目身份也会随之改变,之前积累的项目记忆便会失效——无论是更换设备、移动仓库位置、从子目录启动会话,还是使用 git worktree,都会触发此问题。此外,目前无法将「项目级配置」固化到项目中:用户只能设置环境变量,这些配置既不落盘持久化,也无法通过 Git 与团队成员共享。
-
-**提案**:
-
-1. **项目身份改为基于 Git 推导**。使用归一化后的 origin remote(如 `github.com-volcengine-openviking`)作为 peer id。如此一来,同一个仓库无论在何台设备、哪个克隆副本、哪个子目录或哪个 worktree 下运行,其项目身份均保持一致。
-2. **非 Git 仓库目录默认不再分配 peer**,其记忆将写入用户级空间——恢复到 peer 功能引入前的默认行为。此举主要是为了应对 Codex desktop 等场景:该类工具会为每个临时任务新建一个日期目录,若按原有规则,每个一次性任务都会生成一个全新的空 peer,既无法检索历史记忆,又会在服务端堆积大量仅含零星记忆的命名空间。若需让某个非 Git 目录拥有独立记忆,只需在其中创建 `.openviking/config.json` 并指定 `peer.id` 即可。
-3. **peer 来源调整为可配置项** `peer.source`:内置 `git`(新默认值)、`cwd`(旧行为,保持逐字节兼容)、`none`(彻底禁用)三种模式,同时支持诸如 `"{git_remote}-{harness}"` 的自定义模板。
-4. **引入三层配置架构**:包括 `<仓库根>/.openviking/config.json`(提交至 Git,供团队共享)、`config.local.json`(供个人覆盖,不提交)、以及 `~/.openviking/workspaces/`(本机私有,用户对任何仓库均有最终覆盖权)。这三层配置共用同一套 Schema 与合并规则,其优先级高于全局的 `ovcli.conf`,但始终低于环境变量。
-
-**旧记忆处理方案**:无需进行任何数据迁移。旧的 cwd 身份随时可在本地重新计算,recall 检索时会自动将其带入进行双向读取(dual-read),且不设截止期限。此外,默认的跨 peer 广度扫描同样会召回旧记忆,仅在结果排序时相对靠后。
-
-**边界界定**:服务端协议保持不变,peer 依旧作为用户边界内的视图过滤,而非租户级隔离;对提交至仓库的配置采取「直接信任」原则,仅保留结构性底线(如禁止包含凭证类字段、不进行变量展开),不设置复杂的授权门槛。
-
-## 概述
-
-OpenViking 客户端目前仅依赖一份全局配置(`~/.openviking/ovcli.conf` 结合环境变量),项目身份(actor peer)由进程工作目录动态推导:`cwd.replace(/[^A-Za-z0-9]/g, "-")`。这一机制带来了三个长期存在的问题:
-
-1. **Peer 身份脆弱易变**。更换机器、移动目录、在仓库子目录中启动会话或使用 Git worktree,都会推导出截然不同的 Peer,导致此前积累的项目记忆随之“消失”。插件文档已将“仓库移动或重命名后 recall 内容为空”列为已知故障模式。
-2. **缺乏对单个 Workspace 的持久化配置能力**。如果想固定 Peer 或调整某个项目的行为,目前只能设置环境变量,这些配置无法随项目落盘,更无法通过 Git 在团队间共享。
-3. **配置体系缺乏分层机制**。既没有项目级配置,也没有团队共享配置,更缺少诸如“某个目录应用哪份连接配置”的用户级映射能力。
-
-本 RFC 旨在提出一套统一的解决方案,核心是建立**配置分层体系**,而 Peer 身份机制的改造则是该体系落地的首个核心功能:
-
-- **引入三层配置架构**:包括提交到仓库的 `<root>/.openviking/config.json`(团队共享)、不提交到仓库的 `<root>/.openviking/config.local.json`(个人覆盖),以及用户级注册表 `~/.openviking/workspaces/`(机器本地,按 Workspace 分布为单文件)。这三层配置采用统一的 Schema 和合并引擎。
-- **将 Peer 来源重构为可配置规则**:引入 `peer.source` 键,内置 `git`、`cwd`、`none` 预设,支持变量模板与按序回退。该规则可在任意配置层进行设置,也支持完全禁用 Peer。
-- **默认策略切换为基于 Git,且只基于 Git**:以归一化的 origin remote URL 作为项目身份,确保跨机器、跨克隆、跨子目录、跨 worktree 的稳定性。不在 Git 仓库里的目录默认**不再派生 peer**,其记忆进入用户级空间——这正是 peer 功能出现之前的基线;按目录路径派生 peer 改为显式 opt-in。旧有基于 cwd 推导的记忆,将由默认的 broad recall 扫描与 dual-read 机制兜底(具体覆盖范围与边界详见「迁移与数据连续性」)。
-- **对仓库提交的配置采取“直接信任”策略**:不设复杂的授权门槛,仅保留零摩擦的结构性安全底线(如结构性禁止凭证类键、不做变量展开)。相关风险评估与未来可选的授权机制详见「风险与信任取舍」一节。
-
-## 背景与现状
-
-### Peer 的当前机制
-
-客户端将 Peer ID 放置在 `X-OpenViking-Actor-Peer` 请求头(读路径)和 Session 消息体的 `peer_id` 字段(写路径)中。服务端将 Peer 视为**用户边界内的路径前缀**:`viking://user/<user>/peers/<peer_id>/{memories,resources}`。目前服务端没有 Peer 注册表,也没有 Rename、Alias 或 Merge 机制(参考 `openviking/core/retrieval_targets.py:142`)。因此,变更 Peer ID 意味着开启一个全新的空命名空间;旧的命名空间只能通过默认的 broad recall(`peer_scope: "all"`)扫回,且仅覆盖 memory 分类桶,并因 `other_peer_penalty` 被降分垫底;在 `peer_scope: "actor"` 模式下,旧命名空间完全不可见。
-
-当前的推导逻辑集中在共享库 `examples/memory-plugin-shared/lib/workspace-peer.mjs`(15 行代码)中,并通过 `sync.mjs` 复制到 7 个 Harness 目标。显式指定 Peer 的优先级链已经存在:`OPENVIKING_PEER_ID` 环境变量 → `ovcli.conf` 中的 `actor_peer_id` / `peer_id` → 各 Harness 的遗留配置块 → cwd 推导。
-
-### 配置读取的当前机制
-
-`ovcli.conf` 在仓库中存在多个独立的 Reader(Rust CLI、Python 侧有四处、JS 侧有五处),其行为已出现细微分歧。例如,`/etc` 回退与 `${VAR}` 展开仅存在于 `openviking_cli` 的 Reader,而 SDK 遇到 BOM 头会直接报错。Python 侧的 Schema 守门人拒绝未知的顶层键:Pydantic 模型设置了 `extra: "forbid"`(`ovcli_config.py:60`),SDK 也有白名单机制。唯一开放的扩展点是 `plugin` 字典(`ovcli_config.py:52`),这也顺理成章地成为本方案中所有 `ovcli.conf` 侧新键的落点——**实现零 Schema 变更**。
-
-但在此之前,必须修复一个前置 Bug:Rust 的 `Config` 结构体缺少 `plugin` 字段(`crates/ov_cli/src/config.rs:39`),导致 `ov config add|edit` 与交互向导在重写文件时会**整段丢弃 `plugin` 配置**(包括现有的 `plugin.claude_code` / `plugin.codex`)。这是一个当前已存在的数据丢失问题,其修复(Rust 写路径改用 `serde_json::Value` 级合并以保留未知键)需列入 P0 阶段。
-
-`${VAR}` 展开目前由 `load_json_config` 对整个文件文本执行(`openviking_cli/utils/config/config_loader.py:88`)。这种行为对用户自有文件固然便利,但对任何可通过仓库提交的文件而言,却是一个可能泄露密钥的危险机制(参考 pnpm GHSA-3qhv-2rgh-x77r 漏洞:提交的 `.npmrc` 中的 `${CI_JOB_TOKEN}` 在安装时被展开并外发)。因此,Workspace 文件必须走独立的、不涉及变量展开的解析路径。
-
-## 目标与非目标
-
-目标:
-
-- 建立一套三层、统一 Schema、可扩展的 per-workspace 配置体系,支持团队通过 Git 共享项目级设置。
-- 实现 Peer 来源可配置、可禁用;默认切换为 Git 推导机制;避免现有记忆成为“孤儿”数据。
-- 产出一份附带 per-consumer 适配标注的规范优先级表,以及通过 doctor 输出 per-key 的解析链路,终结“配置到底从哪里来”的排障黑洞。
-
-非目标:
-
-- 暂不更改服务端协议与鉴权模型(Peer 依然是用户边界内的视图过滤,而非租户边界)。
-- 暂不实现复杂的授权/信任(Trust)门槛(仅在风险一节预留设计空间)。
-- Python SDK 与 VikingBot 不读取 Workspace 文件(库或服务进程的 cwd 没有意义,详见适配矩阵)。
-- 不涉及 Monorepo 子目录级的 Peer 细分(留待 v2 议题)。
-
-## 设计:配置分层
-
-### 文件布局
-
-| 文件 | 位置 | 提交到 Git | 用途 |
-| --- | --- | --- | --- |
-| `config.json` | `<workspace-root>/.openviking/` | 是 | 团队共享的项目级设置 |
-| `config.local.json` | `<workspace-root>/.openviking/` | 否(gitignore) | 个人对当前项目的覆盖配置 |
-| `<slot>.json` | `~/.openviking/workspaces/` | 机器本地 | 用户级的 per-workspace 注册表;本次没有 CLI 写入器,按插件 doctor 打印的路径手工创建 |
-| `ovcli.conf` | `~/.openviking/` | 机器本地 | 连接与凭证(维持不变);新键存入 `plugin` 字典 |
-
-Workspace 根目录的确定规则:从生效的 cwd 向上查找,最近的一个持有 `.git`(文件或目录)**或** `.openviking/config.json` / `config.local.json` 的目录即为根目录。`.git` 与标记文件同在一个目录时按 Git 处理;标记文件在仓库内部的子目录先被命中时,该子目录是配置层的根,但 Git 身份仍继续向上取自外层仓库(`{git_remote}` / `{git_root}` 不变,因此默认 peer 不会因为子目录多了一份配置文件而分裂)。对于 linked worktree,通过 `commondir` 收敛**身份**(因此两个 worktree 共用同一个 peer 与同一条注册表记录),但各自的 `.openviking/config.json` 仍跟随所在 checkout——那是分支上的文件;Submodule 被视为独立仓库,不并入父仓库。既无 `.git` 也无标记文件的目录**不是 Workspace**:没有根目录、没有配置层、没有注册表条目,默认也不派生 peer。`$HOME` 与 `/` 不能作为 Workspace 根目录。
-
-用户级注册表设计采用**目录制**而非单一 JSON 文件:每个 Workspace 对应一个权限为 0600、支持原子写入的小文件,以避免多个短生命周期的 Hook 进程对同一文件执行 read-modify-write 时造成更新丢失。定位条目时以 Workspace 根目录路径为依据,条目内部记录 Git 身份键作为**负证据(Negative Evidence)**——当路径命中但记录的 Git 身份与当前仓库冲突时,视为未命中,系统将开启新的条目,绝不继承旧条目的 Peer 绑定与设置。这能有效防止“同一路径先后放置了两个不同仓库”时发生身份串台。
-
-注册表条目内容包括:per-workspace settings(与 Workspace 文件共用 Schema)、`peer` 显式绑定(手工写入,CLI 写入器为后续)、`previous_peer_ids`、`cli_config_profile`(详见安全底线),以及首次/最近可见时间。
-
-同时需一并处理已知的命名冲突问题:`.openviking` 目前也是解析器的机器本地临时目录(`StoragePath.BASE_DIR`,`openviking_cli/utils/storage.py:37`),并且本仓库的 `.gitignore` 也忽略了整个 `.openviking` 目录。解决方案:将仓库自身与文档示例的 `.gitignore` 规则缩小为具体的临时子路径(如 `.openviking/media/`、`.openviking/downloads/` 等)而非整个目录;doctor 增加“存在 `config.json` 但被 Git 忽略”的检查项。
-
-### 优先级
-
-针对同一个配置键,优先级从高到低排列如下:
-
-| 层级 | 说明 |
-| --- | --- |
-| 1. 环境变量 `OPENVIKING_*` | 用于部署期覆盖,遵循项目惯例,优先级永远最高 |
-| 2. CLI 标志参数 | 仅 Rust CLI 存在(如 `--actor-peer-id`) |
-| 3. 用户注册表 `~/.openviking/workspaces/<slot>.json` | 用户针对该 Workspace 的私有最终覆盖 |
-| 4. `<root>/.openviking/config.local.json` | 个人项目层 |
-| 5. `<root>/.openviking/config.json` | 团队项目层(需经过安全底线过滤) |
-| 6. `ovcli.conf` 的 `plugin.<harness>` → `plugin` | 现有全局机制保持不变 |
-| 7. `ov.conf` 的 `<harness>` 遗留块 | 仅作向后兼容读取 |
-| 8. 内置默认值 | — |
-
-项目层(4、5)优先级高于全局层(6)的原因在于:项目声明的约定应当对该项目直接生效,这与 VS Code(workspace > user)和 Claude Code(project > user)的逻辑保持一致;而第 3 层则保证了用户对任何本地仓库始终拥有最终否决权。
-
-必须显式声明本机制与现有 `OPENVIKING_CREDENTIAL_SOURCE` 开关的关系:该开关对凭证字段起全有全无的控制作用——在 `cli` 模式下,连 `OPENVIKING_PEER_ID` 都会被忽略(`credentials.mjs:183`),在 `auto` 模式下,只要出现任一凭证类环境变量,整个链路就会切换到环境变量优先(`credentials.mjs:119`)。本方案规定:Workspace 身份与行为设置(`peer.source`、注册表、两个 Workspace 文件中的各个键)**不属于凭证链**,不受 credential source 模式的影响。上表优先级仅约束这些新键,凭证与连接键继续维持既有的链路与开关语义。
-
-各消费者的适配状态需在文档中逐列标注(已实现 / 计划中 / 不适用),避免规范与实现脱节:
-
-| 层级 | JS Hooks | MCP Proxy | Rust CLI | Python SDK |
-| --- | --- | --- | --- | --- |
-| 环境变量 | 已有 | 已有 | 部分(无 `OPENVIKING_PEER_ID`) | 已有 |
-| 注册表 | 新增 | 经父进程注入 | 后续(本次不含 Rust CLI) | 不适配 |
-| Workspace 文件 | 新增 | 不直读(见 Proxy 章节) | 后续 | 不适配 |
-| `ovcli.conf` | 已有 | 已有 | 已有 | 已有 |
-
-### 合并语义
-
-- **标量与对象**:高层级覆盖低层级,对象类型按键进行深度合并。
-- **列表**:默认跨层做 Union(并集);若列表首元素为字面量 `"!reset"`,则清空所有低层继承(参考 EditorConfig 的 `unset` 与 Git 对 `safe.directory` 的空值重置逻辑)。
-- **未知键**:保留并忽略,永不报错(保障前向兼容性;老版本客户端不能因遇到新版文件而崩溃,反之亦然)。已知键若出现非法枚举值,则回退到默认值并抛出一次警告。
-- **`version`**:必填整数,当前固定为 1;缺失或遇到不认识的主版本号(Major)时,忽略整个文件并警告。
-- **`$schema`**:可选字段,供编辑器自动补全与校验使用;仓库在 `examples/schemas/workspace-config-v1.json` 提供预留的 JSON Schema(随 P2 的键集一起落地),示例中的 URL 指向其 GitHub raw 地址。客户端在解析时会忽略该键。
-- **`min_client_version`**:仅触发软警告,不阻断执行——否则仓库文件将获得对用户插件进行拒绝服务攻击(DoS)的能力。
-
-### Schema (v1)
-
-```jsonc
-{
- "$schema": "https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/schemas/workspace-config-v1.json",
- "version": 1,
- "min_client_version": "0.9.0",
- "notes": "本项目的 OpenViking 约定,自由文本,仅展示",
-
- "peer": {
- "source": "git", // 预设或模板,见「Peer 来源」
- "id": "openviking-core" // 显式指定,优先于 source 推导
- },
-
- "recall": {
- "enabled": true,
- "peer_scope": "all", // "all" | "actor"
- "dedup_turns": 5,
- "max_items": 12
- },
-
- "capture": {
- "enabled": true,
- "commit_token_threshold": 20000
- },
-
- "bypass": {
- "session_patterns": ["*-scratch", "**/tmp/**"] // union 合并;沿用 isBypassed 语义:对 session id 与 cwd 都匹配,`*` 不跨 `/`,跨层级用 `**`
- },
-
- "labels": { "project": "OpenViking" }
-}
-```
-
-`config.local.json` 与注册表的 `settings` 使用同一个 Schema;注册表条目则额外增加 `cli_config_profile` 与 `previous_peer_ids` 等内部登记字段。数值类配置键会在客户端进行区间钳制(例如 `commit_token_threshold` 限制在 1000..1000000,`dedup_turns` 限制在 0..20),非法枚举值直接回退为默认值。
-
-对于来自代码仓库的“关闭”类设置(如 `capture.enabled: false` 或 bypass 模式命中),系统将在 Session-start 注入的上下文块中播报一行提示,并在 doctor 输出中明确标注其来源——确保行为可见,但不做硬性拦截。
-
-### 结构性安全底线
-
-虽然不设复杂的授权门槛,但以下安全规则必须无条件成立,以确保对日常使用零摩擦:
-
-1. **结构性禁止凭证与连接键**。`url`、`mcp_url`、`api_key`、`bearer_token`、`root_api_key`、`gateway_token`、`account`、`user`、`auth_mode`、`extra_headers`、`credential_source`,以及任何指向其他配置文件的路径键,一律**不允许**出现在两个 Workspace 文件中;解析时将直接剔除并触发警告(非静默)。连接与凭证信息唯一的归宿是:`ovcli.conf` + 环境变量。这是回答“我的数据究竟发往哪台服务器”时,不需要去翻阅仓库文件的唯一保证,逻辑上对应 Git 的 `protected configuration` 不变式。
-2. **变量展开是配置层的属性,而非解析器的属性**。Workspace 文件与新的注册表文件由同一个引擎解析,一律使用原生的 `JSON.parse`,永不经过 `load_json_config` 或任何包含 `${VAR}` 的展开路径;将在单元测试中断言 `${HOME}` 在这些文件中保持字符串字面量。“维持现有的展开行为”仅针对旧有的 `ov.conf` / `ovcli.conf`(实际上现状本身也不统一:Python Reader 会展开,JS Reader 不展开,统一与否不属于本 RFC 的范畴)。
-3. **限制 `cli_config_profile` 仅能作为名称标识**。它只能从注册表(用户侧)选择 `~/.openviking/ovcli.conf.<name>`(复用 Rust CLI 现有的命名 Profile 布局),字符集限制为 `^[a-z0-9][a-z0-9._-]{0,63}$`,不允许包含路径分隔符;如果 Profile 不存在,则触发硬错误而不是静默回退。此键**禁止**出现在仓库提交文件中——因为“选择哪份凭证发往哪台服务器”,等价于直接篡改 `url` 的攻击。
-4. Workspace 文件在解析前的常规防御机制:必须是常规文件、realpath 不能逃逸出 Workspace 根目录、设定文件大小上限(64 KiB)、顶级节点必须是对象;解析若发生错误,则进入 Hook 的 fail-open 路径(插件自身的错误不应阻塞用户的会话)。
-
-### Provenance 与诊断
-
-两个插件的 doctor 输出将展示 per-key 的完整解析链路:包括生效值、来源文件、被更高层遮蔽的值,以及因安全底线被剔除的键——功能对标 `git config --show-origin --show-scope`。(注:现有的 `ov doctor` 实际上是 Python 侧面向服务端环境的诊断工具,不承载此项输出功能。)在当前三语言技术栈、多 Reader 并存的现状下,这一诊断输出与配置体系本身同等重要,并将其作为各 Reader 行为一致性的日常验收手段。
-
-## 设计:Peer 来源规则
-
-### `peer.source`
-
-这是新增的配置键,可出现在任意配置层级中(环境变量形式为 `OPENVIKING_PEER_SOURCE`;`ovcli.conf` 侧为 `plugin.peerSource` / `plugin.<harness>.peerSource`):
-
-- 内置预设 `"git"`:启用 Git 身份推导(这是新的默认行为),推导链路见下文;不在 Git 仓库里则不派生。
-- 内置预设 `"cwd"`:保持旧行为,做到字节级一致;这是按目录路径派生 peer 的唯一预设,需显式选择。
-- 内置预设 `"none"`:完全不发送 Peer 头,也不写入 `peer_id`。
-- 支持模板字符串:例如 `"git-{git_remote}"`、`"{git_root}"`、`"team-{dir}"`。
-- 支持模板数组:按序尝试,如果某条模板中的变量解析为空,则整条直接落空并尝试下一条;全部落空则等价于 `"none"`。
-
-`{harness}` 让「同一仓库下不同 agent 各存各的记忆」成为可写得出来的配置,但**没有任何预设使用它**:跨 agent 共享一份项目记忆通常才是用户想要的那一侧,所以拆分是 opt-in。此外 MCP proxy 不参与 peer 推导(其 cwd 不是可靠身份,见「实现落点」),因此模板里用了 `{harness}` 时,只经由 proxy 的读路径解析不出该变量。
-
-v1 支持的变量集:
-
-| 变量 | 含义 | 空值条件 |
-| --- | --- | --- |
-| `{git_remote}` | 归一化后的 origin URL(`github.com/org/repo` 形式,已清理特殊字符) | 非 Git 仓库或不存在 origin remote |
-| `{git_root}` | 仓库根路径(按照 legacy 规则进行字符清理);标记文件在仓库内部命中时仍是仓库根 | 非 Git 仓库 |
-| `{cwd}` | 生效的 cwd(按照 legacy 规则进行字符清理);默认链路不再使用,仅供 `cwd` 预设与自定义模板 | 无 |
-| `{dir}` | Workspace 根目录的目录名(已清理特殊字符) | 不是 Workspace |
-| `{harness}` | 当前 agent 的名字,与 User-Agent 携带的一致(`claude-code`、`codex`、`dsh`、`opencode`、`pi`、`cursor`、`trae`、`trae-cn`、`zcode`) | 从不为空 |
-
-预设 `"git"` 实际上等价于模板数组 `["{git_remote}", "{git_root}"]`:优先使用 remote,若无 remote 则退回到仓库根路径(至少修复了子目录分裂的问题),若不是 Git 仓库则**落空**——不发送 peer 头,也不写入 `peer_id`,记忆进入用户级空间 `viking://user/<u>/memories`。默认情况下不添加任何前缀——因为路径类 ID(`{git_root}` / `{cwd}`)在 POSIX 系统下必然以 `-` 开头,与 remote 的表现形态天然不冲突;如果用户需要前缀,可以自定义模板(如 `"git-{git_remote}"`)。
-
-### 非 Git 目录:默认不派生,按路径派生需 opt-in
-
-初稿的 `"git"` 预设末尾还挂着 `{cwd}` 回退,实测证明这一档必须去掉。Codex desktop 为每个不属于任何项目的对话(其状态文件里称为 projectless thread)新建一个 `~/Documents/Codex/<日期>/<slug>/` 目录作为 cwd,这些目录没有一个是 Git 仓库;按 cwd 回退,每个一次性任务都会铸造一个全新的空 peer,既召回不到上一次的东西,又在服务端留下一堆只有几条记忆的命名空间。这不是 Codex 独有的形态——下载解包出来的目录、临时目录、其他 agent 应用生成的任务目录都一样。通用的信号只有一个:它不是 Git 仓库,也没有任何东西声明它是一个项目。
-
-因此规则是:**默认只有 Git 仓库有 peer**。既不是仓库、也没有标记文件的目录,走 peer 功能出现之前的基线——不带 `X-OpenViking-Actor-Peer`,记忆写进用户级空间。想让一个非 Git 目录拥有自己的记忆,需要用户主动开启,三种方式按推荐顺序:
-
-1. 在该目录放 `.openviking/config.json`,写 `{"version": 1, "peer": {"id": "<名字>"}}`。显式名字不含路径,换机器、改目录名都不变;标记文件让任意子目录向上都能找到这个根。
-2. 同一文件里改写 `peer.source`(如 `"cwd"` 或 `"team-{dir}"`),适合想按路径或目录名派生的场景;注意 `"cwd"` 在子目录里会得到不同的 id,这是它的旧语义。
-3. 全局 `plugin.peerSource: "cwd"`(或 `OPENVIKING_PEER_SOURCE=cwd`)恢复旧行为,适合明知自己的项目多数不是 Git 仓库、且总是从项目根启动的用户。
-
-"这里不是 Workspace"的说明只出现在 doctor,不进入注入模型的上下文——否则 Codex 每个新任务都会吃一行噪音。
-
-已评估并放弃的其他做法见「备选方案」;简言之,读 Codex 的私有状态文件、按 app 路径设黑名单、为一次性目录发固定的 `scratch` peer,都或者不通用,或者只是把问题换了个地方。
-
-### 按场景标注 peer
-
-| 场景 | 建议 |
-| --- | --- |
-| 有 origin 的仓库 | 默认即可:所有 clone、worktree、子目录共用一个 peer |
-| Fork | 默认按 origin 与上游分开;要合并记忆,在两边的 `config.json` 里写同一个 `peer.id` |
-| 无 remote 的本地仓库 | 默认按仓库根路径;换机器会变,长期项目建议在 `config.json` 里写 `peer.id` |
-| 非 Git 的长期项目目录 | 放 `.openviking/config.json` 写 `peer.id` |
-| Monorepo 里某个子项目要单独记忆 | 子目录放 `config.json`,`peer.source: "{git_remote}-{dir}"`;不写则沿用仓库 peer |
-| 一次性任务目录(Codex desktop 的日期目录、临时解包目录) | 什么都不做,记忆进用户级空间 |
-| 几个目录共享一份记忆 | 各处 `peer.id` 写同一个值 |
-| 同一仓库下各个 agent 要各存各的 | `peer.source: "{git_remote}-{harness}"` |
-| 不想按项目分 | `peer.source: "none"`(等价 `OPENVIKING_WORKSPACE_PEER=0`) |
-
-### 更进一步的自定义(记录方向,不在本 RFC 范围)
-
-模板变量集与 `peer.source` 的候选链是可以继续加东西的,以下两条已经评估过可行性,但都不随本 RFC 交付:
-
-**更多现成变量。** `{git_branch}` 的读取成本很低:`resolveGitDir` 已经算出了 worktree 自己的 gitdir(linked worktree 的 `HEAD` 在自己的 gitdir 里而不是 commondir 里,因此必须用前者,否则读到的是主 worktree 的分支),只需多读一次 `HEAD` 并匹配 `ref: refs/heads/<name>`,detached HEAD 取不到名字就按既有的 all-or-nothing 规则整条落空。同理,`normalizeGitRemote` 产出的 `host/path` 再切一刀就能免费得到 `{git_host}` / `{git_owner}` / `{git_repo}`,让 `"{git_owner}-{git_repo}"` 这类更短的 id 写得出来。
-
-不做的理由不在实现,而在语义与缓存:分支是天天在换的,按分支拆 peer 意味着每开一个 feature 分支就进一个空的记忆命名空间、切回来才找得到,这与 Session pin「整个会话冻结同一个 peer」的初衷直接冲突;而 identity 结果有 60 秒磁盘缓存,`git checkout` 之后最多 60 秒内 peer 仍是旧分支的。若将来交付,应当与 `{harness}` 同级——提供变量,但不进任何预设,并在文档里写明这个代价。另需注意:旧客户端写下的缓存条目不含新键,升级后的 60 秒窗口内模板会静默判空并漂移到回退档,因此缓存读取需要在键集不匹配时视为未命中。
-
-**`peer.command`:由外部脚本决定 peer。** 做成又一个模板变量 `{command}` 而不是平行的解析路径,即可自动继承既有语义:能与别的变量拼接、能放进候选列表、脚本无输出就整条落空并试下一条。要点是懒执行(模板里没提到 `{command}` 就根本不启动进程)、定长 argv 不过 shell(沿用 `async-writer` / `doctor-core` / `host-compressor` 既有的执行姿势)、带超时且超时即落空、结果与 identity 同一套短 TTL 缓存以保证一个 turn 只付一次代价。
-
-它值不值得做,取决于 `peer.id`(显式命名)与用户级注册表(按 workspace 手工绑定)之外还剩多少诉求——脚本真正独有的场景是「对一批还没访问过的仓库自动套一条规则」。此外,该键不应从仓库提交的 `config.json` / `config.local.json` 读取,只认用户级来源,否则克隆一个仓库即等于执行任意代码,本 RFC「风险与信任取舍」中列出的三条结构性底线会被一次性拆掉。
-
-### 召回隔离
-
-peer 是路径前缀,不是租户边界;隔离程度由召回参数 `peer_scope` 决定,客户端键为 workspace 文件的 `recall.peer_scope`、`ovcli.conf` 的 `plugin.recallPeerScope` 或环境变量 `OPENVIKING_RECALL_PEER_SCOPE`:
-
-- `"all"`(默认):召回目标是用户级记忆 + 当前 peer 的记忆,再对 `viking://user/<u>/peers` 做一次广度扫描,其他 peer 命中的结果按类别降分(服务端 `other_peer_penalty` 默认 events / entities 0.1,preferences / experiences 0.02),只能垫底、不会抢占。旧 peer 下的记忆靠这一步自然回流。
-- `"actor"`:不扫描其他 peer,只看用户级记忆与当前 peer。客户端在这一档下会对 Legacy ID 额外发一次查询(见「迁移与数据连续性」)。
-- 用户级记忆在两档下都是全权重目标,这也是"非 Git 目录进用户级空间"的代价:一次性任务里提炼出的内容会在所有项目里参与召回。需要更强隔离的用户可以给一次性目录也放标记文件,或全局切到 `"actor"`。
-
-`peer_scope` 是逐请求参数,旧版服务端不认识时客户端会记录一次降级并告警,不会静默变成 `"all"`。
-
-显式指定的 `peer.id` 优先级始终高于 `source` 推导,其跨层优先级继续沿用现有的 explicit 语义:`OPENVIKING_PEER_ID` 环境变量 → CLI 标志参数(`ov --actor-peer-id`)→ 注册表条目(手工创建)→ `config.local.json` → `config.json` → `ovcli.conf` 中的 `actor_peer_id` / `peer_id` → 遗留的 `ov.conf` 块。出于向后兼容的考虑:`OPENVIKING_WORKSPACE_PEER=0` 将继续等价于 `peer.source: "none"`。
-
-### Git 身份推导(零子进程)
-
-基于热路径的性能约束:每个 Hook 都是新启动的 Node 进程,推导动作发生在每一次提示词级别的 Hook 路径上,而且各个 Hook 的超时预算差异极大(例如 Codex `hooks.json` 中,SessionEnd 仅 3 秒,SessionStart 为 70 秒,UserPromptSubmit 为 130 秒)。出于降低延迟、满足预算极紧场景(如 SessionEnd)的考量,同时保障健壮性(避免因环境缺少 Git 二进制文件或触发 dubious-ownership 告警而失效),推导过程仅执行纯文件系统操作,不启动 Git 子进程:
-
-1. 向上查找 `.git` 目录;若 `.git` 为文件,则读取 `gitdir:` 的指向,通过 `commondir` 将 linked worktree 收敛至主仓库;如果 `gitdir` 路径包含 `modules/` 则判定为 Submodule,按独立仓库处理。
-2. 从 `<commondir>/config` 执行纯 INI 解析,读取 `[remote "origin"] url`;不跟随 `include` / `includeIf` 指令(取不到就直接落空,进入下一级回退逻辑)。
-3. 结果写入 `~/.openviking/state/` 下基于 cwd 的短 TTL 缓存中,确保同一个 Turn 内的多个 Hook 进程只需付出一次推导代价(复用现成的 `readJsonState(name, { maxAgeMs })` 状态文件机制,见 `examples/claude-code-memory-plugin/scripts/lib/state.mjs:42`)。
-
-`{git_remote}` 的归一化规则:
-
-```text
-SCP 形式 [email protected]:volcengine/OpenViking.git
-URL 形式 https://user:[email protected]:8443/volcengine/OpenViking.git/
-处理步骤: → host 提取 hostname(丢弃 userinfo 与端口),转换为小写
- → path 移除首尾斜杠与 .git 后缀,转换为小写并折叠
-最终结果: "github.com/volcengine/openviking";若无法解析(如 file:// 或裸本地路径)则落空
-```
-
-由于 userinfo 在归一化过程中被丢弃,因此 remote URL 中内嵌 token 的情况不会泄露到 Peer ID 中。大小写折叠使得同一仓库的不同拼写方式(如 SSH 与 HTTPS、大小写差异)都能收敛到同一个身份;其代价是,在极少数区分大小写的 Forge 平台上,仅大小写不同的两个仓库会合并到同一个命名空间(原始的拼写会保留在注册表的 `label` 中)。
-
-字符清理(Sanitize)存在两套规则,严禁混用:`{git_root}` 与 `{cwd}` 遵循 **Legacy 规则进行逐字节替换**(即 `[^A-Za-z0-9]` → `-`,不折叠连续字符、保留前导 `-`),确保与 `peer.source: "cwd"` 在 Legacy ID 重算时达到字节级完全一致;而 `{git_remote}`、`{dir}` 与 `{harness}` 使用新规则(适配服务端字符集 `^[a-zA-Z0-9_.@-]+$`,详见 `openviking/core/identifiers.py:8`):非法字符替换为 `-`,折叠连续的 `-`,去除首尾的 `-.`,保留 `.` 使得类似 `github.com` 的域名具备可读性;规避 `__self` 与 `ext-`(实现期核实:二者在服务端校验层并非保留字——`__self` 只是 `session/memory/memory_isolation_handler.py` 的内部哨兵,`ext-` 只是 `ingest/peer.py` 的客户端编码约定;仍然规避,以免与它们撞名);超过 100 字符时进行截断,并在末尾追加原文哈希的前 12 位(远低于 AGFS 的 255 字节段上限)。
-
-示例:在 `/Users/x/Dev/OpenViking/examples/codex-memory-plugin` 目录下,且 origin 为 `[email protected]:volcengine/OpenViking.git` 时,推导出的 Peer 为 `github.com-volcengine-openviking`——无论是在任何子目录、任何 worktree、任何机器,还是任何一份克隆,身份都保持绝对一致。
-
-由此确立的身份语义:同一仓库的多个本地克隆**共享**同一个 Peer(项目记忆跟着项目走);Fork 仓库与上游仓库的 origin 不同,因此**默认分开**(通过 `gh pr checkout` 审查外部 PR 时,origin 依然是自己的仓库,身份不受影响;若需合并 Fork 与上游的记忆,在两边写同一个 `peer.id`)。
-
-### 实现落点
-
-- **推导与归一化**:新增共享模块 `workspace-identity.mjs`;`resolveEffectivePeerId` 函数保持 `source ∈ {explicit, workspace, none}` 三值枚举不变,但新增姊妹字段 `origin`(取值为实际产生该 id 的模板字符串,如 `{git_remote}` / `{git_root}` / `{cwd}`,或 `explicit` / `disabled` / `none` / `unresolved`)。因为现有代码中有 5 处针对 `source === "workspace"` 的字面量硬编码比较(Claude Code 的 session pin 两处、Codex 的 session-start 一处,以及两个 doctor),新增枚举会静默破坏 session pinning 逻辑。
-- **Session Pin**:Claude Code 的 `ws-peer-<sessionId>.json` 与 Codex 的 `state.workspacePeerId` 继续在 SessionStart 阶段冻结整个会话的 Peer;Pin 文件新增版本字段,读取时忽略旧版本条目(目前的现状是 pin 永不过期,读取时没有 `maxAgeMs` 限制)。
-- **身份解析一次、向下传递**:每个提示词级别的 Hook 优先读取 pin 文件,避免重复推导。
-
-## 迁移与数据连续性
-
-默认策略切换为 Git 后,已有用户积累的旧记忆仍然存放在由 cwd 推导的旧 Peer 之下。本方案不依赖用户执行任何一次性迁移动作:
-
-1. **永久的双向读取(Dual-read)兜底**。当前 cwd 对应的 Legacy ID 永远可以在本地重新计算得出(无需专门登记):当当前生效的 Peer 与 Legacy ID 不一致时——包括非 Git 目录如今根本没有 Peer 的情况——recall 操作会自动兼顾旧 Peer。在默认的 `peer_scope: "all"` 模式下,现有的 peers 目录扫描逻辑已自然覆盖旧 Peer 的 memory 数据,实现零额外成本;而在 `peer_scope: "actor"` 模式下,recall 会额外发起一次针对 `viking://user/<u>/peers/<legacy>/memories` 的 search 请求,但该请求必须**不带** `X-OpenViking-Actor-Peer` 头(带此请求头去读取他人的 Peer 路径会触发 403 硬错误,参考 `retrieval_targets.py:176`)。Dual-read 机制不设截止期限。需注意其覆盖范围:能在本地重算的仅限**当前路径**的 Legacy ID;若仓库已移动/改名,或历史上曾在多个子目录各自铸造过 Peer,旧 ID 将无法重算,此类情况由 broad 扫描机制兜底。
-2. **本次交付的保证只有第 1 条**:旧 Peer 下的记忆不搬家,recall 靠 `all` scope 的跨 Peer 扫描与 `actor` scope 的额外查询触达;显式绑定与 `cli_config_profile` 通过手工创建的注册表条目完成。
-
-已知边界(需如实写入文档):broad 扫描的配额路径仅覆盖 `/memories/<bucket>/` 这样的分类桶(而无配额的扁平路径可能会带回 `profile.md` 等非分类文件),此外,旧 Peer 下的 **resources 文件在两条路径下都不会被自动扫回**——Dual-read 的 actor 分支与手动 migrate 才是彻底的解决方案。服务端的 Alias 映射表(在 `normalize_actor_peer_header` 处做旧→新映射)作为远期的备选方案,不纳入本 RFC 实施范围;需注意,该函数目前仅覆盖了读路径的 Header,写路径中的消息体 `peer_id` 还需另行处理;并且,项目 Changelog 曾明确决定不对 Legacy 有损 Peer 目录进行自动回读(因为多个身份可能发生碰撞,归属权应当交由操作者人工裁决),任何自动 Alias 机制都必须在此先例基础上进行独立论证。
-
-## 风险与信任取舍
-
-仓库提交的 `config.json` 本质上是攻击者可控的输入(只需克隆一个仓库即可生效)。在采取“直接信任”策略的前提下,恶意仓库通过篡改该文件可能造成以下影响(如实列举):
-
-- **通过 `peer.id` 指向受害者的其他项目**:该仓库产生的会话记忆将被写入受害者其他项目的命名空间(构成记忆投毒——记忆本质上是持久化的 Prompt 注入面),同时,其他项目的记忆也会被 recall 进该恶意仓库控制的上下文中。
-- **配置 `peer.source: "none"`**:抑制客户端发送 Peer 头。请注意,发送 Peer 头是一个**收窄**默认检索范围的保护动作,去掉该 Header 后,默认的目标检索集将退化回整个 user root——这意味着该仓库内的会话能够窥探用户所有项目的记忆。
-- **配置 `capture.enabled: false` 或命中 bypass 模式**:使该仓库内的活动逃避系统记录(反取证行为)。
-- 放大数值类配置键的成本消耗(目前已通过客户端区间钳制予以缓解)。
-
-无法越权执行的操作(由结构性底线保障):恶意仓库无法篡改数据发往的服务器地址、无法读取或外发凭证、无法通过 `${VAR}` 展开来窃取环境变量、无法切换当前使用的 `ovcli.conf` 配置。
-
-接受上述残余风险的考量:由于 Hook 流程完全是非交互式的,任何设立授权门槛的做法最终都会退化为“要求用户在每个 Workspace 先执行一条前置命令”,这种纯粹的摩擦对于绝大多数良性开发场景是不可接受的。况且本项目目前的主要使用形态(个人开发者、处理自有仓库)中,发生攻击的前提条件较弱。相应的缓解措施为:来自代码仓库的身份配置与关闭类设置一律进行播报(Session-start 时提示一行 + doctor 诊断),绝不允许静默生效。
-
-未来扩展性预留(仅记录,不包含在本 RFC 实施范围内):若未来确需收紧安全策略,保留了两个互不冲突的演进方向。其一,引入类似 direnv 或 mise 的一次性内容哈希授权机制,但仅对 `peer.*` 等身份敏感键生效;其二,推行“Key, not authority”原则——仓库内的文件仅负责声明 Workspace 的逻辑名称,由用户级的注册表将该名称映射到实际的 Peer,从而剥夺仓库直接指挥写入目标的权力。这两个方向均能在现有分层体系上增量加装,且不会破坏本 RFC 设定的文件格式。
-
-## 实施阶段
-
-- **P0:基础卫生修复(可独立发版)**:`sync.mjs` 改为仅导出各目标清单,并将 `main()` 逻辑挡在入口判断之后(当前机制只要 import 就会触发全量同步);`sync.test.mjs` 改为导入这些清单(现有测试清单已过期,副本漂移可能会被 CI 静默放过);修复 Rust 配置写路径中丢弃 `plugin` 段的数据丢失 Bug(`ov config add|edit` 与交互向导改用 `serde_json::Value` 级别的合并机制,确保未知键在往返序列化时得以保留);为 Session pin 机制增加版本字段;当 `peer_scope: "actor"` 被旧版服务端响应 400/422 降级时,将静默失败改为抛出警告;将新编写的测试文件注册进 `.github/workflows/pr.yml`。
-- **P1:搭建配置引擎**:新增共享模块 `workspace-config.mjs`(负责发现、纯粹的 parse、安全底线过滤、合并以及 Provenance 溯源)、`workspace-registry.mjs`(负责目录制注册表读写、负证据查找机制)、`workspace-identity.mjs`(负责 Git 身份推导、归一化、Sanitize 字符清理及缓存);将上述模块加入 `HARNESS_SHARED_FILES` 以同步至 7 个目标端,同时手工同步 `agent-plugins/servers/` 下的副本;接入 `loadPluginSettings`(函数签名增加 cwd 参数;由于 Hook 顶层调用的 `loadConfig()` 早于 stdin 的解析,Workspace 层的配置必须延迟懒加载),并串联各 Harness 的 cfg 组装点;实现插件 doctor 的 Provenance 诊断输出。此阶段系统行为保持不变(因为新层级默认均为空)。
-- **P2:Peer 来源规则与默认策略切换**:确保 `peer.source` 在全链路生效(环境变量 / ovcli 的 `plugin` 字典 / Workspace 文件;为 doctor 增加对 `plugin.*` 内部已知键的拼写检查支持——现有的 `KNOWN_OVCLI_KEYS` 仅校验顶层键,而 `plugin` 自身已经在白名单内);将默认策略正式切换为 `git` 推导,非 Git 目录默认不派生(根目录查找同时识别 `.openviking/config.json` 标记文件);上线 Dual-read 兜底机制;在 doctor 中增加对旧 Peer 的检测逻辑;同步更新引用了旧推导规则的 5 处 README 文件、`docs/en/agent-integrations/16-capability-reference.md`、`docs/en/configuration/02-client.md` 以及全部的中文镜像文档,并在 Changelog 中详细说明默认行为的变化与兜底恢复机制。
-- **P3:CLI 命令(后续,本次 PR 不含)**:CLI 面整体推迟,本次以纯插件改动合入;Rust 侧保留的只有 `ov config add|edit` 丢 `plugin` 段的修复(`serde_json::Value` 级合并)。
-- **独立 PR(涉及行为变更,需附带 Release Note)**:Claude Code、OpenCode 及 agent-plugins 这三个 MCP Proxy 停止使用 `process.cwd()` 推导 Peer(此举违反了其共享模块自身的约定,Codex 侧已有测试禁止此行为),改为由父进程在启动时(Launch-time)注入 `OPENVIKING_PEER_ID` 环境变量(仓库内部已有先例:dsh 父进程就是如此注入的,见 `examples/dsh-memory-plugin/mcp.mjs:27`;若父进程未注入,其 Proxy 仍会回退到 `process.cwd()`,本次将一并修正);当 Actor 作用域下缺乏显式 Peer 时,触发警告并降级处理,而不是在启动时直接抛出异常。
-
-## 备选方案(已否决)
-
-- **使用 Root-commit SHA 作为 Git 身份**:在本仓库实测中被证伪——`git rev-list --max-parents=0 --all` 会返回 29 个根节点(结果取决于 Fetch 过哪些引用),执行 Fetch 操作会导致身份发生漂移;Shallow clone 根本没有根节点;Fork 仓库继承了上游的 root commit,在常规的审查外部 PR 流程中,会导致完全零配置的身份串台。
-- **在提交的文件中随机生成并记录 Workspace ID 作为唯一身份**:稳定性极佳,但严重依赖于该提交文件必须存在(如果仓库未采纳或未提交该文件则彻底无效),并且将该文件作为“权威”来源时,等于暴露了投毒攻击面;其“作为键”的设计思想已部分被未来的“Key, not authority”可选方向收录。
-- **设立授权门槛(Direnv 式的 Trust Gate 或 Key-not-authority)**:基于产品决策否决——在完全非交互的 Hook 场景下,任何授权机制都必然退化为要求用户对每个 Workspace 单独执行一条前置审批命令,带来的日常操作摩擦是不可接受的;其设计要点已归档在「风险与信任取舍」中备用。
-- **扩展 `ovcli.conf` 的顶层 Schema**:由于存在三个不同机制的 Schema 守门人(Pydantic 设置的 `extra:"forbid"`、SDK 的硬编码白名单、Rust 重写文件时的静默丢键行为),引入任何顶层新键对于旧版客户端都是致命的硬错误;而 `plugin` 字典是目前唯一可行的零变更安全通道。
-- **非 Git 目录继续按 cwd 派生(初稿的 `{cwd}` 回退档)**:被 Codex desktop 的 projectless 目录证伪——每个一次性任务铸造一个 peer。为此评估过的补救都没有采纳:读 `~/.codex/.codex-global-state.json` 里的 `projectless-thread-ids`(Electron 私有格式、1.25 MB、仅桌面版存在,SessionEnd 只有 3 秒预算);按 app 路径设黑名单或在 codex 插件内置 `~/Documents/Codex`(依赖具体应用与操作系统的目录布局,`~/Documents/trae_projects` 之类的目录立刻又要补一条);用户级"容器根"规则如 `~/Dev/*`(要求每个用户描述自己机器的目录布局,不是通用产品该有的默认值);为非 Workspace 目录统一发固定的 `scratch` peer(在项目里降分、在 `actor` 下不可见的行为其实更好,但引入一个约定保留 id,且松散目录里学到的偏好也被降分;P2 若需要可在现有规则上加一条)。最终选择最朴素的一条:不是仓库就没有项目记忆,回到 peer 出现前的基线。
-- **Remote 查找时支持从 origin 回退到 upstream**:由于执行 `git remote add upstream` 的瞬间会导致身份发生突变,这种不确定性不可接受;因此固定仅使用 origin,如需合并命名空间,统一走显式的 `peer.id`。
-
-## 开放问题
-
-1. Rust `ov` CLI 发起的数据面请求是否也应该按照 Workspace 来推导 Peer(目前它仅响应显式的 `actor_peer_id` 或 flag 参数)?若决定采纳,则需要实现 `serde_json::Value` 级别的 Overlay 覆盖合并,建议在 P3 阶段完成后再行单独评估。
-2. 模板变量集是否需要引入诸如 `{git_branch}` 这类在会话生命周期内可能发生改变的变量,以及是否开放 `peer.command` 这样的脚本扩展点?两者的可行性与代价见「更进一步的自定义」,本 RFC 均不交付。
-3. Monorepo 的子目录级别 Peer 划分:根目录查找已经采用"就近文件优先",子目录里的 `.openviking/config.json` 会成为该子树的配置层根,但 Git 身份仍取自外层仓库,因此默认依旧是"一个仓库对应一个 Peer";想拆分的子项目自己在文件里改 `peer.source`(见「按场景标注 peer」)。根级别的子路径映射表不做。
-4. 目前已经可以通过不带 actor-peer 头的 `ov ls viking://user/<u>/peers` 来枚举既有 Peers 目录;对于 doctor 而言,是否值得专门开发一个带有额外元信息(如内部条目数量、最近写入时间戳)的专属清单 API?此问题留待实际实现期再做评估。
\ No newline at end of file
diff --git a/docs/en/agent-integrations/03-openclaw.md b/docs/en/agent-integrations/03-openclaw.md
index 02a49983a..6ac8c76c4 100644
--- a/docs/en/agent-integrations/03-openclaw.md
+++ b/docs/en/agent-integrations/03-openclaw.md
@@ -118,6 +118,26 @@ The history branch falls back to host messages when OV has no data, has fewer me
A **session commit** archives conversation and processes memory. It is separate from a [snapshot commit](../guides/15-snapshot.md), which versions resource files.
+## Agent experience recall configuration
+
+The plugin still accepts `agentExperience` in its plugin configuration with these defaults:
+
+```json
+{
+ "agentExperience": {
+ "enabled": false,
+ "recallLimit": 3,
+ "scoreThreshold": 0.35,
+ "maxInjectedChars": 6000,
+ "minQueryChars": 12
+ }
+}
+```
+
+These fields remain in the configuration schema, but the current assemble path does not consume them. Recall uses the shared `searchContext` path and the general `autoRecall`, `recallLimit`, `recallScoreThreshold`, and `recallMaxInjectedChars` settings. Setting `agentExperience.enabled` does not enable a separate experience search or a separate experience section.
+
+The retained `shouldRecallAgentExperience` helper scores execution, write, failure, and engineering terms, plus intent words such as “经验”, “踩坑”, “best practice”, and “pitfall”. It has no caller in the current recall path. Its keyword rules and `minQueryChars` must not be treated as active recall controls. Injected context uses `<openviking-context>`; capture strips that wrapper and its content before saving user text, so recalled material is not captured again as user input.
+
## Verify
```bash
diff --git a/docs/en/api/02-resources.md b/docs/en/api/02-resources.md
index 6017b382f..2964d892e 100644
--- a/docs/en/api/02-resources.md
+++ b/docs/en/api/02-resources.md
@@ -79,6 +79,12 @@ Source Input -> Parse -> Resource Tree Build -> Persistence -> Semantic Processi
URL/File Parser TreeBuilder AGFS Summarizer/Vector
```
+#### Routing and waiting
+
+OpenViking first checks whether the source and request parameters qualify for Connector ingestion. Connector runs ingestion outside the standard pipeline. Otherwise, formats selected by [`parser_api`](../guides/01-configuration.md#parser-api) use the external Understanding parser; remaining formats use built-in parsers. External parsing replaces only the Parse stage and returns to TreeBuilder and the standard storage/semantic pipeline. Feishu documents already normalized to Markdown by an accessor bypass external parsing.
+
+Connector requires an exact `to` target and does not support `wait=true`. A `tos://` source cannot fall back to a built-in accessor. Git may fall back when Connector does not apply, except when Connector-only credentials were supplied. For supported standard-pipeline requests, `wait=true` waits for work belonging to this import, not unrelated work in the global queues; a timeout does not imply that the import was cancelled.
+
#### Stage 1: Parse
- Uses `UnifiedResourceProcessor` to parse content based on resource type
- Supports multiple formats: documents (PDF/Markdown/Word), spreadsheets (Excel/PPT), code, media files, etc.
@@ -106,7 +112,8 @@ Source Input -> Parse -> Resource Tree Build -> Persistence -> Semantic Processi
- For Git repository sources with `wait=false`, OpenViking validates the repository, resolves the target URI, reserves the final `root_uri`, and returns before clone/parse/finalize completes.
- The immediate response contains `status`, `root_uri`, and `task_id`; fetching, parsing, finalizing, and queue waiting continue in a persistent background task.
- Poll `GET /api/v1/tasks/{task_id}` to inspect task state. Git resource import tasks use stages such as `queued`, `fetching`, `parsing`, `finalizing`, and `processing_queue`.
-- Other resource sources with `wait=false` finish fetching/parsing/finalizing before the response; their returned `task_id` tracks semantic and embedding queue completion only.
+- External Understanding imports can also return before parsing finishes: direct Feishu ingestion submits the URL, while HTTP file ingestion identifies and uploads the file before queueing the external response for follow-up. Poll the returned `task_id`; a direct Feishu import may not have a `root_uri` until the parsed title is known.
+- Ordinary imports through built-in parsers with `wait=false` finish fetching/parsing/finalizing before responding; their `task_id` tracks the remaining semantic and embedding work.
### Incremental Updates for Resources
diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.md
index e73673263..e3de7d3c4 100644
--- a/docs/en/api/08-admin.md
+++ b/docs/en/api/08-admin.md
@@ -532,8 +532,7 @@ not return business-resolved defaults. After persistence, the new
configuration is published and matching in-process consumers are awaited.
Consumer failures are logged without rolling back the persisted override, so
a successful response confirms the configuration update but does not certify
-that every derived client has applied it. The current business integrations
-are documented in the [runtime configuration design](../../design/runtime-configuration-design.md).
+that every derived client has applied it. See [runtime configuration source and reload behavior](../guides/01-configuration.md#runtime-configuration-source).
#### Account Configuration Reference
diff --git a/docs/en/concepts/08-session.md b/docs/en/concepts/08-session.md
index 4816ca8c1..84b3f78a2 100644
--- a/docs/en/concepts/08-session.md
+++ b/docs/en/concepts/08-session.md
@@ -146,6 +146,8 @@ OpenViking includes memory types such as `profile`, `preferences`, `entities`, `
Within `memory_policy.memory_types`, `experiences` enables the complete Agent Evolution pipeline and automatically activates `cases` and `trajectories`. If `experiences` is absent, explicitly supplied `cases` and `trajectories` entries are ignored without an error.
+Agent Evolution also requires the effective `agent_evolution.enabled` switch. With `experiences` selected, the flow organizes the task as a case, records its execution as a trajectory, and derives reusable experiences. Query experience usage and execution outcome distributions through the [Agent Evolution API](../api/19-agent-evolution.md). The offline training framework under `openviking/session/train/` is an internal implementation, not a public training API.
+
### Extraction Flow
<MemoryExtractionDiagram />
diff --git a/docs/en/concepts/12-metrics.md b/docs/en/concepts/12-metrics.md
index c6fc7920d..b6da7c6bb 100644
--- a/docs/en/concepts/12-metrics.md
+++ b/docs/en/concepts/12-metrics.md
@@ -569,4 +569,3 @@ Example:
- [Data Encryption](./10-encryption.md) - storage-layer encryption and isolation
- [Metrics API](../api/09-metrics.md) - `/metrics` endpoint usage
- [VikingBot Feedback Observability Design](https://github.com/volcengine/OpenViking/blob/main/bot/docs/zh/design/vikingbot-feedback-observability-design.md) - feedback observability design background and rollout plan (Chinese)
-- [Metrics Design](../../design/metric-design.md) - metrics system design details
diff --git a/docs/en/configuration/02-client.md b/docs/en/configuration/02-client.md
index bee2d0866..3f6a4d6dc 100644
--- a/docs/en/configuration/02-client.md
+++ b/docs/en/configuration/02-client.md
@@ -221,6 +221,8 @@ A peer is a path prefix under your own user space — `viking://user/<you>/peers
`peer.source` decides the rule. The same setting is spelled `OPENVIKING_PEER_SOURCE` in the environment and `plugin.peerSource` or `plugin.<harness>.peerSource` in `ovcli.conf`.
+Remote identity comes only from `origin`; there is no fallback to `upstream`, because adding an upstream remote must not silently change the memory namespace. Root-commit hashes are not used either: forks share ancestry, and shallow clones or newly fetched histories can change which roots are visible. Without `origin`, a Git repository uses its root path. Use an explicit `peer.id` when repositories should share memories or when path-based identity must survive a move. Non-Git directories still have no derived peer by default.
+
#### Give a Directory Its Own Peer
Create `.openviking/config.json` in the directory:
diff --git a/docs/en/context-compilation/01-overview.md b/docs/en/context-compilation/01-overview.md
index afaf044f0..aaa256b0d 100644
--- a/docs/en/context-compilation/01-overview.md
+++ b/docs/en/context-compilation/01-overview.md
@@ -28,6 +28,14 @@ ov compile \
The command returns a `cmp_...` task ID immediately. Use `ov task status <id>` to check progress and `ov task cancel <id>` to stop it. The full field reference, task lifecycle, and HTTP API are in the [Agent Runtime API](../api/23-agent-runtime.md).
+## Use Web Studio
+
+Studio provides a Compile list at `/compile`, a form at `/compile/new`, and task details at `/compile/tasks/<task_id>`. Select and preview a Skill, browse source directories, submit multiple sources, inspect or cancel a task, and open its output directory. Playground's terminal also supports `compile` and `task`; it can hand parameters to the form.
+
+Task-list cursors are signed with a process-local key and bound to the caller and filters. Restarting the service invalidates old cursors; refresh the list to start again. A cursor from one replica is not portable to another. Pagination scans stored task records rather than using an index, so read cost grows with retained history.
+
+For HTTP submission retries, reuse the same `Idempotency-Key` and request parameters; a changed request with the same key returns `409`. Recovery lasts only as long as the task record: completed/cancelled records expire 24 hours after their last update, failed records after 7 days. This is not permanent submission history or a cross-instance exactly-once guarantee. See [Agent Runtime](../api/23-agent-runtime.md) for submission recovery and [Tasks](../api/17-tasks.md) for task operations.
+
## Swap the Skill, get a different output
The Skill defines the output. The repository includes these examples; LLM Wiki and Knowledge Graph also include visualization scripts:
diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.md
index 655afce0e..39b402000 100644
--- a/docs/en/guides/01-configuration.md
+++ b/docs/en/guides/01-configuration.md
@@ -620,6 +620,18 @@ Get your API key at https://dashscope.console.aliyun.com/api-key
Supported task types: `RETRIEVAL_QUERY`, `RETRIEVAL_DOCUMENT`, `SEMANTIC_SIMILARITY`, `CLASSIFICATION`, `CLUSTERING`, `CODE_RETRIEVAL_QUERY`, `QUESTION_ANSWERING`, `FACT_VERIFICATION`.
+#### Local provider (`local`)
+
+When no `dense`, `sparse`, or `hybrid` embedding is configured (including when `embedding` is omitted), OpenViking selects `dense: {"provider": "local", "model": "bge-small-zh-v1.5-f16"}`. This GGUF model produces 512-dimensional vectors and requires no API key.
+
+Install the local inference dependency:
+
+```bash
+pip install "openviking[local-embed]"
+```
+
+On first use, OpenViking downloads the model to `~/.cache/openviking/models` unless the file is already cached. Set `embedding.dense.cache_dir` to change the cache directory, or `embedding.dense.model_path` to use an existing GGUF file without downloading it. A missing explicit `model_path` is an error; it does not trigger a download. This model's dimension is fixed at 512.
+
#### Sparse Embedding
> This example uses `doubao-embedding-vision-251215`. Check sparse text-output support for your selected model in the Ark [embedding documentation](https://docs.volcengine.com/docs/ark/vectorization?lang=zh&redirect=1).
@@ -989,6 +1001,26 @@ PDF parsing configuration. Three strategies are supported: `local` (local pdfplu
**MinerU protocol**: a synchronous `POST {mineru_endpoint}/file_parse` request with the PDF as the multipart `files` field; form parameters are passed through from `mineru_bodys`.
+### External parser API (`parser_api`) {#parser-api}
+
+The top-level `parser_api` section routes selected formats to the external Understanding files/responses API. It replaces the Parser stage; TreeBuilder, persistence, and semantic processing remain in OpenViking. See [Resource processing](../api/02-resources.md#resource-processing-pipeline) for routing and asynchronous behavior.
+
+| Field | Default | Meaning |
+| --- | --- | --- |
+| `enable` | `false` | Enable external parsing. |
+| `extensions` | `[]` | File extensions to route externally; normalized to lowercase without the leading dot. |
+| `host` | `""` | API host including scheme, such as `https://parser.example.com`; required when enabled. |
+| `api_key` | `""` | External API credential; required when enabled. |
+| `enable_feishu_url` | `false` | Allow direct Feishu URL parsing when credentials are available. Feishu documents already normalized to Markdown by the accessor bypass external parsing; file attachments still use extension routing. |
+| `enable_resumable_upload` | `false` | Enable resumable uploads. |
+| `upload_simple_max_bytes` | `536870912` (512 MiB) | Simple-upload size threshold. |
+| `upload_part_size_bytes` | `8388608` (8 MiB) | Resumable-upload part size. |
+| `http_timeout_seconds` | `10.0` | Timeout for an individual HTTP request. |
+| `response_timeout_seconds` | `1800` | Timeout while waiting for the parsing response. |
+| `poll_interval_ms` | `3000` | Response polling interval. |
+
+All size, timeout, and polling values must be greater than zero.
+
### rerank
Reranking model for search result refinement. Supports VikingDB (Volcengine), Cohere,
@@ -1681,7 +1713,13 @@ For memory-related settings, add a `memory` section in `ov.conf`:
| `extraction_enabled` | Whether session commit runs long-term memory extraction. | `true` |
| `session_skill_extraction_enabled` | Whether session commit also extracts reusable skills into the current user's skill directory. | `false` |
| `link_enabled` | Whether memory extraction writes and resolves memory links. | `false` |
-| `session_auto_commit` | Server-wide automatic session commit controls. This belongs under `memory`, not under `server`; see [Session Auto Commit Configuration](#session-auto-commit-configuration). | See section above |
+| `session_auto_commit` | Server-wide automatic session commit controls. This belongs under `memory`, not under `server`; see [Session Auto Commit Configuration](#session-auto-commit-configuration). | See section below |
+
+#### Memory links (`memory.link_enabled`)
+
+`memory.link_enabled` defaults to `false`. When enabled, extraction resolves temporary page IDs into URIs and stores links in memory metadata. Each link contains `from_uri`, `to_uri`, `link_type` (default `related_to`), `weight` (default `0.5`, extraction clamps it to 0–1), `match_text` (a word from the conversation, or `null`), `description`, and `created_at`.
+
+`link_type` is a relation label rather than a closed enum. Extraction normalizes it to lowercase snake_case with one to three alphabetic words; invalid labels fall back to `related_to`. These links describe relationships between memories; the current retrieval pipeline does not traverse them or use their weights for ranking.
#### Session Auto Commit Configuration
@@ -1851,6 +1889,39 @@ Supported add target URIs:
- `skill_uri` is used as the default `add_skill` target root. In v1, only `viking://~/skills` and `viking://agent/skills` are accepted; explicit `viking://user/{user_id}/skills` is not accepted.
- Legacy spellings: `viking://user/resources` and `viking://user/skills` written in earlier configs are auto-normalized to `viking://~/resources` and `viking://~/skills` when the config is loaded, and the server logs an info message. Prefer the `viking://~/...` form in new configs — outside `add_targets`, the uid-less spelling is rejected at the request boundary.
+### Runtime configuration source {#runtime-configuration-source}
+
+The top-level `runtime_config` section selects the source of runtime settings at startup; it is not nested under `server`.
+
+| Field | Default | Meaning |
+| --- | --- | --- |
+| `source` | `"file"` | `file` stores settings through AGFS; `memory` keeps them only in this process; a registered source name selects a custom implementation. |
+| `module` | `null` | Optional Python module imported to register a custom source. Sources can also register through the `openviking.config_source` entry-point group. |
+| `params` | `{}` | Parameters passed to the custom source factory as `ConfigSourceContext.params`. |
+
+A custom source implements `ConfigSource.load(scope)`, `update(scope, mutate)`, and `delete(scope)`. It must guard read-modify-write against concurrent updates, including calls from different threads or event loops. The mutation callback can be retried and must have no side effects.
+
+The file source stores Account settings at `/local/{account_id}/_system/setting.json` and Cluster settings at `/local/_system/runtime_config/cluster.json` in AGFS. It retains the previous bytes as `setting.backup.json` and `cluster.backup.json` beside those files and can read the backup if the primary file is missing or invalid. Existing Account settings keep their original path.
+
+The manager polls the Cluster and cached Accounts every 30 seconds. Accounts unused for 24 hours are evicted from the cache and stop being polled; their persisted settings remain. A refresh failure keeps the last valid configuration. Admin settings GET returns the stored override, not a merged effective configuration or proof that every derived client has switched. Use the [Admin API](../api/08-admin.md) to update settings; see [Reload boundary](#reload-boundary) for consumer behavior.
+
+### Tool output externalization {#tool-output-externalization}
+
+`server.tool_output_externalization` moves oversized session tool outputs to the session's `tool-results/` store and leaves a preview stub plus `tool_output_ref`. Retrieve the full output through the session tool-result read, search, and list APIs in [Session management](../api/05-sessions.md).
+
+| Field | Default | Meaning |
+| --- | --- | --- |
+| `enabled` | `true` | Enable externalization. |
+| `threshold_chars` | `20000` | Externalize an individual output above this character count. |
+| `preview_chars` | `2000` | Preview character target for one output. |
+| `assistant_turn_inline_budget_chars` | `100000` | Inline budget across tool outputs in one assistant turn. |
+| `assistant_turn_preview_budget_chars` | `10000` | Budget used to allocate previews across the turn. |
+| `min_preview_chars` | `1000` | Lower bound when allocating per-output previews. |
+| `aggregate_selection_strategy` | `"largest_first"` | Only supported strategy: select larger outputs first when reducing the turn's inline size. |
+| `failure_mode` | `"preserve_raw"` | On storage failure: `preserve_raw` keeps the original output, `reject` raises an error, and `preview_only` keeps only a preview without a recoverable reference. |
+
+The budgets guide output selection and preview allocation; preview metadata and the minimum preview size can prevent a strict cap. With `preserve_raw`, failed writes can also leave the turn above its budget.
+
### Usage Reporter
The optional Usage Reporter extracts memory usage events from committed session tool parts. The built-in file log sink writes each event as one flat JSON object to a dedicated hourly rotating file:
@@ -1892,6 +1963,18 @@ Each line has the following form:
`event_time` is UTC. `tenant_id` combines the deployment resource ID, event account, user, and Experience URI. `memory.recalled` maps to `experience.recall.count`, while `memory.injected` maps to `experience.inject.count`. `object_id` is the stable Usage Event ID. Downstream consumers must deduplicate by the composite `(tenant_id, object_id)` key rather than by `object_id` globally. Aggregate usage with `sum(count)` after filtering by `tenant_id`, `event_name`, and the desired `event_time` range. File collection and downstream delivery remain best-effort.
+#### Custom sink
+
+Add a sink entry under `server.usage_reporter.sinks`:
+
+```json
+{"type": "custom", "class_path": "my_app.usage.MySink", "config": {}}
+```
+
+The class must be importable by the server. `config` is passed as keyword arguments to its constructor. Implement `async def write(self, *, events: list[UsageEvent]) -> None`; `UsageEvent` is defined in `openviking.usage_reporter.models` and exposes `event_id` and `to_dict()`. The input is a list of events, not the flat `file_log` JSON rows.
+
+Delivery is best-effort: sink errors and timeouts are logged, and phase-2 replay can send an event again. A custom sink must define its own retry and deduplication policy. If it emits the file-log schema, use `object_id = event.event_id` and deduplicate by `(tenant_id, object_id)` within the deployment/account/user/resource scope described above. This is not an exactly-once delivery contract.
+
For startup and deployment details see [Deployment](./03-deployment.md), for authentication see [Authentication](./04-authentication.md).
## storage.transaction Section
diff --git a/docs/en/guides/16-cuvs.md b/docs/en/guides/16-cuvs.md
index 5e9e8f23b..870e094ac 100644
--- a/docs/en/guides/16-cuvs.md
+++ b/docs/en/guides/16-cuvs.md
@@ -347,3 +347,5 @@ collection.close()
## Current limits
The native prefilter preserves scalar DSL, `date_time`, `geo_point`, and path-depth semantics. cuVS only handles pure dense queries; sparse/hybrid fallback and snapshot maintenance follow the behavior described above. Treat brute-force as the functional baseline. Tune CAGRA graph and search parameters against recall, throughput, latency, and GPU memory for your workload.
+
+The GPU index itself is not persisted. After a restart, OpenViking reconstructs it from locally stored vectors; inserts, updates, and deletes mark it dirty. By default, the next dense search rebuilds it. In memory-aware auto mode, `auto_background_rebuild` moves rebuilding to a background worker while queries use the native fallback until a usable GPU index is ready. Budget for rebuild latency after restarts and writes, even when the local vector store is persisted.
diff --git a/docs/en/guides/17-vikingbot.md b/docs/en/guides/17-vikingbot.md
index f4ec32f70..f2120054f 100644
--- a/docs/en/guides/17-vikingbot.md
+++ b/docs/en/guides/17-vikingbot.md
@@ -261,6 +261,20 @@ The Gateway listens on `127.0.0.1` by default. If you change it to `0.0.0.0` or
For credentials and permissions required by each chat platform, see [VikingBot Channel Configuration](https://github.com/volcengine/OpenViking/blob/main/bot/docs/en/concepts/05-channel.md).
+## Manage through Web Studio
+
+Open Web Studio's `/vikingbot` page to chat on the web or manage Feishu connections for a Server-managed Bot. Connection management and Feishu history require ROOT access and are isolated by the account selected in Studio; an account ADMIN key is not sufficient. Studio calls `GET /api/v1/admin/bot/capabilities` and the connection, conversation, verification, and onboarding endpoints under `/api/v1/admin/accounts/{account_id}/bot`.
+
+The Feishu QR setup has three steps:
+
+1. Select a regular user in the same account as the connection's runtime identity. The server binds an available credential; the browser does not need that user's API key.
+2. Scan the Feishu QR code to create the application, configure permissions/events, and submit it for publication. Existing applications can use manual credential setup instead.
+3. Add the bot to a group and verify message receipt and reply. API acceptance of a reply does not prove that it is visible in the group; check the group as part of setup.
+
+Connections and captured messages are stored in `studio.sqlite3` under the Bot data directory with mode `0600`. The database contains application and bound-user credentials, so handle its backups like server configuration. Studio-managed Feishu sessions use only the OpenViking query and memory tools allowed for the bound identity; shell, local-file, scheduling, and unapproved MCP tools are unavailable.
+
+Pause stops the connection and keeps history. Deleting a connection removes its local records, not the Feishu application or messages in Feishu. Feishu history is read-only in Studio and starts with messages captured by that Studio connection; channels already configured in `ov.conf` and their old history are not migrated automatically. Resuming or restarting a connection preserves its context; deleting and recreating it creates a new context.
+
## More Documentation
- [Complete VikingBot documentation](https://github.com/volcengine/OpenViking/blob/main/bot/README.md)
diff --git a/docs/images/agents/skills/sales-opportunity-order-builder.md b/docs/images/agents/skills/sales-opportunity-order-builder.md
index 67e624435..c261f5d6a 100644
--- a/docs/images/agents/skills/sales-opportunity-order-builder.md
+++ b/docs/images/agents/skills/sales-opportunity-order-builder.md
@@ -33,7 +33,7 @@ OpenViking 相关操作分属**两个不同的面**,各用各的 Key,混用
## 总体原则
- 按顺序完成前置检查:AgentPlan APIKey → 控制面能力 → 创建/选择 OV 库 →
- 获取并记录库的 OpenViking APIKey 与 user 身份 → 飞书 CLI。
+ 配置库的 OpenViking APIKey 并记录 user 身份 → 飞书 CLI。
- 不在对话中展示、复述、记录 APIKey、Token、Cookie 等敏感凭据明文;配置凭据
优先走环境变量或配置文件,不要求用户把 Key 粘贴进聊天。
- **建库是计费动作**,且每账号最多 20 个库:创建前必须向用户确认。
@@ -67,7 +67,8 @@ CLI 在同一个包里),境内网络给 uv 配 PyPI 镜像即可,不依赖
```bash
# 境内网络可加:export UV_DEFAULT_INDEX=https://pypi.tuna.tsinghua.edu.cn/simple
- AGENTPLAN_API_KEY=<已配置的key> uvx --from mcp-server-openviking-controlplane ov-cp list
+ # 先通过凭据管理工具或环境配置设置 AGENTPLAN_API_KEY
+ uvx --from mcp-server-openviking-controlplane ov-cp list
```
2. **安装为 MCP(适合长期使用)**:向用户展示将写入 `.mcp.json` 的内容,
@@ -105,15 +106,14 @@ CLI 在同一个包里),境内网络给 uv 配 PyPI 镜像即可,不依赖
## Step 4:等库就绪,获取并记录 OpenViking APIKey 与 user 身份
库创建后处于 `INIT` 状态,需要轮询到 `READY` 才能取凭据(INIT 阶段取
-api-key 会超时,不是故障,等一会重试即可):
+api-key 可能超时,先查状态再决定是否重试):
1. 用 `get_collection`(或 `ov-cp get <ResourceID>`)轮询 `Status`,
直到 `READY`(通常几分钟内)。
2. 调 `get_collection_api_key`(或 `ov-cp api-key <ResourceID>`),返回
`{UserID, Role, ApiKey}` —— 这里的 `ApiKey` 就是该库的
**OpenViking APIKey**,`UserID` 就是 user 身份。
-3. 安全记录:库名、`ResourceID`、`UserID`、OpenViking APIKey。回复中只说明
- "已安全记录",不展示明文。
+3. 记录库名、`ResourceID`、`UserID`;OpenViking APIKey 仅写入凭据管理器或受保护的本地配置,不写入普通记忆、文档或日志。确认写入成功后再回复凭据已配置,不展示明文。
4. 之后数据面 MCP 读写该库(上传、查询、沉淀)一律用这把 Key。
**控制台兜底路径**(MCP 不可用、api-key 调用被拦、或用户已有存量库时同样适用):
@@ -143,7 +143,7 @@ APIKey。让用户把 Key 配置到数据面工具的环境变量/配置中,
已完成:
1. AgentPlan APIKey 可用(用于建库、联网、数据集查询)。
2. OpenViking 个人库「[库名]」已就绪(READY)。
-3. 该库的 OpenViking APIKey 与 user 身份已安全记录(用于读写库数据)。
+3. 该库的 OpenViking APIKey 与 user 身份已配置(用于读写库数据)。
4. 飞书 CLI 已就绪。
你可以直接这样说:
@@ -196,7 +196,7 @@ APIKey。让用户把 Key 配置到数据面工具的环境变量/配置中,
1. 询问同步范围(当前会话 / 指定项目 / 最近 N 天 / 关键词)和频率
(每天、每周、会话结束后、指定时间)。
-2. 用定时任务能力创建任务;执行时用 OpenViking APIKey 上传摘要或全文。
+2. 检查宿主是否提供持久化定时任务能力,再创建任务并返回任务标识。未提供时说明只能手动触发,不宣称已设置自动同步。执行时用 OpenViking APIKey 上传摘要或全文。
3. 上传内容带元信息:时间、主题、关联商机、来源会话、摘要、待办。
4. 不上传无关闲聊、敏感凭据或用户明确排除的内容。
5. 告知用户定时任务可暂停、可删除、可改频率。
@@ -218,13 +218,13 @@ APIKey。让用户把 Key 配置到数据面工具的环境变量/配置中,
|---|---|---|
| 无 AgentPlan APIKey | 未购买/未配置 | 给控制台链接,暂停建库 |
| create 返回 `ProductUnordered` | 未开通 AgentPlan 抵扣 | 引导控制台开通抵扣,不要重试 |
-| create 返回超限 | 已达 20 库上限 | 让用户删除闲置库或复用现有库 |
-| api-key 调用超时 | 库还在 INIT | 轮询 `get_collection` 到 READY 再取 |
+| create 返回超限 | 已达 20 库上限 | 先检查并复用合适的现有库;删除库需单独确认数据备份和删除范围 |
+| api-key 调用超时 | 库可能未就绪,也可能是网络或服务异常 | 查询库状态;INIT 时等待,READY 后仍超时则检查端点和服务错误 |
| 控制面 MCP / `ov-cp` 不可用 | 缺控制面能力 | 走 Step 2 征求安装同意,或控制台手工建库 |
| 拿不到 OpenViking APIKey | — | 控制台「鉴权管理 → 显示鉴权凭证」兜底 |
| 数据面读写鉴权失败 | 可能 Key 用混了 | 确认用的是该库的 OpenViking APIKey |
| 飞书 CLI 不可用 | — | 给官方安装链接,等待安装/授权 |
-| 查询无结果 | 库里没有相关内容 | 说明未找到,建议上传哪些文档 |
+| 查询无结果 | 本次检索未命中 | 检查库、身份、检索范围和索引任务状态,再调整查询或补充资料 |
## 安全与合规
diff --git a/docs/zh/agent-integrations/03-openclaw.md b/docs/zh/agent-integrations/03-openclaw.md
index 2f3d635ca..250337680 100644
--- a/docs/zh/agent-integrations/03-openclaw.md
+++ b/docs/zh/agent-integrations/03-openclaw.md
@@ -118,6 +118,26 @@ OV 无数据、无归档且消息数少于宿主输入、转换后为空或读
这里的 **session commit** 负责会话归档和记忆处理,与保存资源文件版本的 [snapshot commit](../guides/15-snapshot.md) 是不同操作。
+## Agent experience 召回配置
+
+插件配置仍接受 `agentExperience`,默认值如下:
+
+```json
+{
+ "agentExperience": {
+ "enabled": false,
+ "recallLimit": 3,
+ "scoreThreshold": 0.35,
+ "maxInjectedChars": 6000,
+ "minQueryChars": 12
+ }
+}
+```
+
+这些字段仍在配置 Schema 中,但当前 assemble 链路不读取它们。召回使用统一的 `searchContext` 路径,以及通用的 `autoRecall`、`recallLimit`、`recallScoreThreshold` 和 `recallMaxInjectedChars` 配置。设置 `agentExperience.enabled` 不会启用独立的经验检索,也不会生成单独的经验区块。
+
+代码保留的 `shouldRecallAgentExperience` 函数会对执行、写操作、失败、工程对象等词,以及“经验”“踩坑”“best practice”“pitfall”等意图词打分,但当前召回链路没有调用它。不能把这些关键词规则和 `minQueryChars` 当作生效的召回控制项。注入内容使用 `<openviking-context>` 包裹;捕获用户文本时会剥离该标记及其内容,避免把召回材料再次当作用户输入保存。
+
## 验证
```bash
diff --git a/docs/zh/api/02-resources.md b/docs/zh/api/02-resources.md
index a386fe06c..55b96a3e5 100644
--- a/docs/zh/api/02-resources.md
+++ b/docs/zh/api/02-resources.md
@@ -79,6 +79,12 @@ OpenViking 支持多种资源类型,按照功能分类如下:
URL/文件 Parser TreeBuilder AGFS Summarizer/Vector
```
+#### 路由与等待
+
+OpenViking 先检查来源和请求参数是否满足 Connector 接入条件。Connector 在标准流水线之外完成导入。其余请求中,[`parser_api`](../guides/01-configuration.md#parser-api) 选中的格式交给外部 Understanding 解析,剩余格式使用内置 Parser。外部解析只替换 Parse 阶段,结果仍进入 TreeBuilder 和后续存储、语义处理。已经由 Accessor 归一化为 Markdown 的飞书文档跳过外部解析。
+
+Connector 要求精确的 `to` 目标,不支持 `wait=true`。`tos://` 来源不能回退到内置 Accessor。Git 未命中 Connector 时可以回退,但携带 Connector 专用凭证时禁止回退。对于支持等待的标准流水线请求,`wait=true` 只等待本次导入的工作,不等待全局队列中的无关任务;等待超时不代表导入已取消。
+
#### 阶段 1:源解析 (Parse)
- 使用 `UnifiedResourceProcessor` 根据资源类型解析内容
- 支持多种格式:文档(PDF/Markdown/Word)、表格(Excel/PPT)、代码、媒体文件等
@@ -106,7 +112,8 @@ URL/文件 Parser TreeBuilder AGFS Summarizer/Vector
- 对 Git 仓库来源使用 `wait=false` 时,OpenViking 会先校验仓库、解析目标 URI、预占最终 `root_uri`,然后在 clone/parse/finalize 完成前返回。
- 立即响应包含 `status`、`root_uri` 和 `task_id`;抓取、解析、finalize 以及队列等待会在持久化后台任务中继续执行。
- 可通过 `GET /api/v1/tasks/{task_id}` 查询任务状态。Git 资源导入任务的阶段包括 `queued`、`fetching`、`parsing`、`finalizing`、`processing_queue`。
-- 其他资源来源使用 `wait=false` 时,会在响应前完成抓取/解析/finalize;返回的 `task_id` 只用于跟踪 semantic 和 embedding 队列完成情况。
+- 外部 Understanding 导入也可能在解析完成前返回:飞书直达路径提交 URL;HTTP 文件路径先识别类型并上传文件,再将外部响应交给后台处理。通过返回的 `task_id` 查询进度;飞书直达导入可能要等解析标题确定后才有 `root_uri`。
+- 使用内置 Parser 的普通导入在 `wait=false` 时仍会先完成抓取、解析和 finalize,再返回响应;其 `task_id` 跟踪剩余的语义和 embedding 工作。
### 资源的增量更新
diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.md
index 0ab72eb83..1e3e6a373 100644
--- a/docs/zh/api/08-admin.md
+++ b/docs/zh/api/08-admin.md
@@ -443,7 +443,7 @@ PATCH 会先做结构校验,再构造合并后的配置:未知路径和运
两个 GET 接口只返回目标作用域持久化的配置,不返回业务解析后的默认值。配置持久化后会发布新配置并等待
匹配的进程内 Consumer;Consumer 失败会记录日志但不会回滚已持久化的配置,因此接口成功只表示
-配置层更新成功,不保证所有派生客户端都已完成切换。当前业务接入状态见[运行时配置设计](../../design/runtime-configuration-design.md)。
+配置层更新成功,不保证所有派生客户端都已完成切换。配置存储和重载行为见[运行时配置来源与重载行为](../guides/01-configuration.md#runtime-configuration-source)。
#### Account Configuration 接口参考
diff --git a/docs/zh/concepts/08-session.md b/docs/zh/concepts/08-session.md
index 129fe637a..5949e9674 100644
--- a/docs/zh/concepts/08-session.md
+++ b/docs/zh/concepts/08-session.md
@@ -146,6 +146,8 @@ OpenViking 内置 `profile`、`preferences`、`entities`、`events`、`identity`
在 `memory_policy.memory_types` 中,`experiences` 会启用完整的 Agent Evolution 流程,并自动激活 `cases` 和 `trajectories`。如果没有 `experiences`,显式传入的 `cases` 和 `trajectories` 会被静默忽略,不会报错。
+Agent Evolution 还要求生效的 `agent_evolution.enabled` 开关已开启。选择 `experiences` 后,流程将任务组织为 case,将执行记录为 trajectory,再提炼可复用的 experiences。经验使用情况和执行结果分布通过 [Agent Evolution API](../api/19-agent-evolution.md) 查询。`openviking/session/train/` 中的离线训练框架属于内部实现,不是公开训练 API。
+
### 提取流程
<MemoryExtractionDiagram />
diff --git a/docs/zh/concepts/12-metrics.md b/docs/zh/concepts/12-metrics.md
index ad6375199..0ccd621fa 100644
--- a/docs/zh/concepts/12-metrics.md
+++ b/docs/zh/concepts/12-metrics.md
@@ -569,4 +569,3 @@ max by (job) (openviking_feedback_events_total{valid="0"})
- [数据加密](./10-encryption.md) - 存储层加密与隔离
- [Metrics API](../api/09-metrics.md) - `/metrics` 端点用法
- [VikingBot 问答效果反馈观测方案设计](https://github.com/volcengine/OpenViking/blob/main/bot/docs/zh/design/vikingbot-feedback-observability-design.md) - feedback 指标与阶段性落地背景
-- [指标体系设计](../../design/metric-design.md) - 指标体系设计细节
diff --git a/docs/zh/configuration/02-client.md b/docs/zh/configuration/02-client.md
index fe5214b5b..79cdfee4b 100644
--- a/docs/zh/configuration/02-client.md
+++ b/docs/zh/configuration/02-client.md
@@ -218,6 +218,8 @@ peer 是用户空间下的一段路径前缀——`viking://user/<you>/peers/<pe
规则由 `peer.source` 决定。同一项配置在环境变量中写作 `OPENVIKING_PEER_SOURCE`,在 `ovcli.conf` 中写作 `plugin.peerSource` 或 `plugin.<harness>.peerSource`。
+远端身份只取 `origin`,不回退到 `upstream`,避免添加 upstream 时悄悄改变记忆空间。也不使用 root-commit SHA:Fork 共享祖先,浅克隆或新拉取的历史又会改变可见的根提交。Git 仓库没有 `origin` 时使用仓库根路径。需要多个仓库共享记忆,或希望移动目录后身份不变时,应显式配置 `peer.id`。非 Git 目录默认仍不派生 peer。
+
#### 让一个目录拥有独立记忆
在该目录下创建 `.openviking/config.json`:
diff --git a/docs/zh/context-compilation/01-overview.md b/docs/zh/context-compilation/01-overview.md
index 331765cc5..39f6ea743 100644
--- a/docs/zh/context-compilation/01-overview.md
+++ b/docs/zh/context-compilation/01-overview.md
@@ -28,6 +28,14 @@ ov compile \
命令会立即返回一个 `cmp_...` 任务 ID,之后用 `ov task status <id>` 查看进度、用 `ov task cancel <id>` 取消。完整的字段说明、任务生命周期和 HTTP 接口见 [Agent Runtime API](../api/23-agent-runtime.md)。
+## 使用 Web Studio
+
+Studio 提供 `/compile` 列表、`/compile/new` 新建表单和 `/compile/tasks/<task_id>` 任务详情页。可以选择并预览 Skill、浏览来源目录、提交多个来源、查看或取消任务,以及打开产物目录。Playground 终端也支持 `compile` 和 `task`,并可将参数带入表单。
+
+任务列表游标使用进程内密钥签名,并绑定调用者和筛选条件。服务重启后旧游标失效,刷新列表即可重新开始。一个副本签发的游标不能直接用于另一个副本。分页扫描已存储的任务记录,不依赖索引,读取成本仍随保留的历史数量增长。
+
+重试 HTTP 提交时,复用相同的 `Idempotency-Key` 和请求参数;同一 Key 对应的参数变化时返回 `409`。提交恢复只在任务记录保留期间有效:完成或取消的记录在最后一次更新后保留 24 小时,失败记录保留 7 天。这不是永久提交历史,也不保证跨实例 exactly-once。提交恢复见 [Agent Runtime](../api/23-agent-runtime.md),任务操作见[任务管理](../api/17-tasks.md)。
+
## 换个 Skill,就换一种产物
Skill 决定输出内容和结构。仓库提供以下示例,其中 LLM Wiki 和 Knowledge Graph 还包含可视化脚本:
diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.md
index 416afd834..345c0763b 100644
--- a/docs/zh/guides/01-configuration.md
+++ b/docs/zh/guides/01-configuration.md
@@ -618,6 +618,18 @@ SDK 1.39.0 起提供所需的客户端上下文管理器和关闭方法,用于
支持的 task type: `RETRIEVAL_QUERY`、`RETRIEVAL_DOCUMENT`、`SEMANTIC_SIMILARITY`、`CLASSIFICATION`、`CLUSTERING`、`CODE_RETRIEVAL_QUERY`、`QUESTION_ANSWERING`、`FACT_VERIFICATION`。
+#### 本地 provider(`local`)
+
+未配置 `dense`、`sparse` 或 `hybrid` embedding 时(包括省略 `embedding`),OpenViking 默认选择 `dense: {"provider": "local", "model": "bge-small-zh-v1.5-f16"}`。该 GGUF 模型输出 512 维向量,无需 API Key。
+
+安装本地推理依赖:
+
+```bash
+pip install "openviking[local-embed]"
+```
+
+首次使用时,OpenViking 将模型下载到 `~/.cache/openviking/models`;已有缓存则复用。通过 `embedding.dense.cache_dir` 修改缓存目录,或用 `embedding.dense.model_path` 指定已有 GGUF 文件以跳过下载。显式指定的文件不存在时会报错,不会转为下载。该模型的维度固定为 512。
+
#### Sparse Embedding
> 以下示例使用 `doubao-embedding-vision-251215`。所选模型是否支持文本 sparse 输出,请核对方舟[向量化文档](https://docs.volcengine.com/docs/ark/vectorization?lang=zh&redirect=1)。
@@ -984,6 +996,26 @@ PDF 解析配置。支持三种策略:`local`(本地 pdfplumber)、`mineru
**MinerU 协议**:同步调用 `POST {mineru_endpoint}/file_parse`,multipart 文件字段为 `files`,form 参数由 `mineru_bodys` 透传。
+### 外部解析 API(`parser_api`) {#parser-api}
+
+顶层 `parser_api` 配置将指定格式交给外部 Understanding files/responses API。它只替换 Parser 阶段;TreeBuilder、持久化和语义处理仍由 OpenViking 完成。路由与异步行为见[资源处理流程](../api/02-resources.md#资源处理流程)。
+
+| 字段 | 默认值 | 含义 |
+| --- | --- | --- |
+| `enable` | `false` | 启用外部解析。 |
+| `extensions` | `[]` | 交给外部解析的扩展名;转为小写并去掉开头的点。 |
+| `host` | `""` | 带协议的 API 地址,如 `https://parser.example.com`;启用时必填。 |
+| `api_key` | `""` | 外部 API 凭证;启用时必填。 |
+| `enable_feishu_url` | `false` | 有可用凭证时允许直接解析飞书 URL。已由 Accessor 归一化为 Markdown 的飞书文档跳过外部解析;文件附件仍按扩展名路由。 |
+| `enable_resumable_upload` | `false` | 启用断点续传。 |
+| `upload_simple_max_bytes` | `536870912`(512 MiB) | 简单上传的大小阈值。 |
+| `upload_part_size_bytes` | `8388608`(8 MiB) | 分片上传的分片大小。 |
+| `http_timeout_seconds` | `10.0` | 单次 HTTP 请求超时秒数。 |
+| `response_timeout_seconds` | `1800` | 等待解析结果的超时秒数。 |
+| `poll_interval_ms` | `3000` | 结果轮询间隔,单位毫秒。 |
+
+大小、超时和轮询参数都必须大于零。
+
### rerank
用于搜索结果精排的 Rerank 模型。支持 VikingDB(火山引擎)、Cohere、OpenAI
@@ -1671,7 +1703,13 @@ openviking-server --config /path/to/ov.conf
| `extraction_enabled` | session commit 时是否执行长期记忆抽取。 | `true` |
| `session_skill_extraction_enabled` | session commit 时是否同时抽取可复用 skill 到当前用户的 skill 目录。 | `false` |
| `link_enabled` | 记忆抽取是否写入和解析 memory links。 | `false` |
-| `session_auto_commit` | 服务端 session 自动 commit 的全局控制项。该配置属于 `memory` 段,不属于 `server` 段;详见 [Session Auto Commit 配置](#session-auto-commit-配置)。 | 见上文 |
+| `session_auto_commit` | 服务端 session 自动 commit 的全局控制项。该配置属于 `memory` 段,不属于 `server` 段;详见 [Session Auto Commit 配置](#session-auto-commit-配置)。 | 见下文 |
+
+#### 记忆链接(`memory.link_enabled`)
+
+`memory.link_enabled` 默认为 `false`。启用后,抽取流程将临时 page ID 解析为 URI,并把链接存入记忆元数据。每条链接包含 `from_uri`、`to_uri`、`link_type`(默认 `related_to`)、`weight`(默认 `0.5`,抽取时限制在 0–1)、`match_text`(对话中的一个词或 `null`)、`description` 和 `created_at`。
+
+`link_type` 是关系标签,不是封闭枚举。抽取时将其归一化为小写 snake_case,允许一到三个字母单词;无效标签回退为 `related_to`。这些链接描述记忆间的关系;当前检索流程不遍历链接,也不使用链接权重排序。
#### Session Auto Commit 配置
@@ -1841,6 +1879,39 @@ ov add-resource ./docs --exclude "*.tmp"
- `skill_uri` 作为 `add_skill` 的默认目标根目录使用。v1 只允许 `viking://~/skills` 和 `viking://agent/skills`;不支持显式写成 `viking://user/{user_id}/skills`。
- 旧写法兼容:早期配置中的 `viking://user/resources` 和 `viking://user/skills` 会在配置加载时自动归一化为 `viking://~/resources` 和 `viking://~/skills`,并打印一条 info 日志。新配置请直接使用 `viking://~/...`;在 `add_targets` 之外,无 uid 的写法会在请求入口被拒绝。
+### 运行时配置来源 {#runtime-configuration-source}
+
+顶层 `runtime_config` 在启动时选择运行时配置来源,不放在 `server` 内。
+
+| 字段 | 默认值 | 含义 |
+| --- | --- | --- |
+| `source` | `"file"` | `file` 通过 AGFS 存储配置;`memory` 只保存在当前进程中;也可填写已注册的自定义来源名称。 |
+| `module` | `null` | 用于注册自定义来源的 Python 模块。来源也可通过 `openviking.config_source` entry-point group 注册。 |
+| `params` | `{}` | 通过 `ConfigSourceContext.params` 传给自定义来源工厂的参数。 |
+
+自定义来源实现 `ConfigSource.load(scope)`、`update(scope, mutate)` 和 `delete(scope)`。来源必须防止并发读改写丢失更新,包括跨线程和事件循环的调用。更新回调可能被重试,因此不能有副作用。
+
+文件来源在 AGFS 中把 Account 配置写入 `/local/{account_id}/_system/setting.json`,把 Cluster 配置写入 `/local/_system/runtime_config/cluster.json`。前一版本的字节保存在同目录的 `setting.backup.json` 和 `cluster.backup.json`;主文件丢失或无效时可读取备份。原有 Account 配置继续使用原路径。
+
+管理器每 30 秒刷新 Cluster 和已缓存的 Account。24 小时未使用的 Account 从缓存移除并停止轮询,已存储的配置仍保留。刷新失败时继续使用上一次有效配置。Admin settings GET 返回已存储的覆盖值,不是合并后的生效配置,也不能证明所有派生客户端都已切换。修改配置使用 [Admin API](../api/08-admin.md),各消费者的行为见[配置重载边界](#配置重载边界)。
+
+### 工具输出外置 {#tool-output-externalization}
+
+`server.tool_output_externalization` 将会话中过大的工具输出存入该会话的 `tool-results/`,消息保留预览 stub 和 `tool_output_ref`。完整输出可通过[会话管理](../api/05-sessions.md)中的 tool-result read、search、list API 回读。
+
+| 字段 | 默认值 | 含义 |
+| --- | --- | --- |
+| `enabled` | `true` | 启用工具输出外置。 |
+| `threshold_chars` | `20000` | 单条输出超过此字符数时外置。 |
+| `preview_chars` | `2000` | 单条输出的预览字符目标。 |
+| `assistant_turn_inline_budget_chars` | `100000` | 同一 assistant turn 中工具输出的内联预算。 |
+| `assistant_turn_preview_budget_chars` | `10000` | 在该轮各输出之间分配的预览预算。 |
+| `min_preview_chars` | `1000` | 分配单条预览时的下限。 |
+| `aggregate_selection_strategy` | `"largest_first"` | 目前唯一支持的策略:需要缩减该轮内联大小时优先外置较大输出。 |
+| `failure_mode` | `"preserve_raw"` | 存储失败时:`preserve_raw` 保留原文;`reject` 抛出错误;`preview_only` 只保留预览,不提供可恢复原文的引用。 |
+
+这些预算用于选择外置输出和分配预览。预览元数据和最小预览大小可能使结果超出预算;`preserve_raw` 在写入失败时也可能使该轮超出预算。
+
### Usage Reporter
可选的 Usage Reporter 从已 commit session 的 tool parts 中抽取记忆使用事件。内置文件日志 Sink 将每个事件写成一行扁平 JSON,并按小时滚动专用日志文件:
@@ -1881,6 +1952,18 @@ ov add-resource ./docs --exclude "*.tmp"
`event_time` 使用 UTC 时间。`tenant_id` 由部署 resource ID、事件所属的 account、user 和 Experience URI 拼接。`memory.recalled` 映射为 `experience.recall.count`,`memory.injected` 映射为 `experience.inject.count`。`object_id` 是稳定的 Usage Event ID。下游必须使用 `(tenant_id, object_id)` 复合键去重,不能跨 tenant 仅按 `object_id` 全局去重。查询时按 `tenant_id`、`event_name` 和 `event_time` 范围过滤,再通过 `sum(count)` 汇总。文件采集和下游投递仍为 best-effort。
+#### 自定义 Sink
+
+在 `server.usage_reporter.sinks` 中添加:
+
+```json
+{"type": "custom", "class_path": "my_app.usage.MySink", "config": {}}
+```
+
+该类必须能被服务端导入。`config` 作为关键字参数传给构造函数。类需实现 `async def write(self, *, events: list[UsageEvent]) -> None`;`UsageEvent` 定义于 `openviking.usage_reporter.models`,提供 `event_id` 和 `to_dict()`。输入是事件对象列表,不是 `file_log` 输出的扁平 JSON 行。
+
+投递采用 best-effort:Sink 错误和超时会记录到日志,phase-2 重放可能再次发送同一事件。自定义 Sink 需定义重试和去重策略。若输出文件日志格式,应设置 `object_id = event.event_id`,并按上述部署/account/user/resource 范围内的 `(tenant_id, object_id)` 去重。这不是 exactly-once 投递协议。
+
启动方式和部署详情见 [服务部署](./03-deployment.md),认证详情见 [认证](./04-authentication.md)。
<a id="encryption"></a>
diff --git a/docs/zh/guides/16-cuvs.md b/docs/zh/guides/16-cuvs.md
index 97a37d8ad..1d42a2ac7 100644
--- a/docs/zh/guides/16-cuvs.md
+++ b/docs/zh/guides/16-cuvs.md
@@ -319,3 +319,5 @@ collection.close()
- 默认情况下,每次 upsert/delete 后仍由下一次查询同步重建;开启 `auto_background_rebuild` 后,dirty 期间查询走 native,连续写被合并为后台重建。
- cuVS 索引不作为权威持久化数据;进程重启时会从 OpenViking 本地 store 重建,因此不受 cuVS 跨版本序列化格式变化影响。
- `brute_force` 适合功能对齐和 ground truth;CAGRA 的 graph/search 参数需要在后续结合召回率、QPS、延迟和显存进行调优。
+
+GPU 索引本身不持久化。重启后,OpenViking 从本地存储的向量重新构建索引;插入、更新和删除会将其标记为 dirty。默认由下一次 dense 检索触发重建。显存感知自动模式下,`auto_background_rebuild` 将重建交给后台线程,可用的 GPU 索引就绪前使用 native 回退。即使本地向量存储已持久化,也需要计入重启和写入后的重建耗时。
diff --git a/docs/zh/guides/17-vikingbot.md b/docs/zh/guides/17-vikingbot.md
index 7c9d216e9..ea368648f 100644
--- a/docs/zh/guides/17-vikingbot.md
+++ b/docs/zh/guides/17-vikingbot.md
@@ -260,6 +260,20 @@ Gateway 默认只监听 `127.0.0.1`。如果改为 `0.0.0.0` 或其他非 localh
聊天平台的凭证和权限配置见 [VikingBot 渠道配置](https://github.com/volcengine/OpenViking/blob/main/bot/docs/zh/concepts/05-channel.md)。
+## 通过 Web Studio 管理
+
+打开 Web Studio 的 `/vikingbot` 页面,可使用网页对话或管理 Server 受管 Bot 的飞书连接。渠道管理和飞书历史仅允许 ROOT 访问,并按 Studio 当前选择的 account 隔离;Account ADMIN Key 不具备该权限。Studio 使用 `GET /api/v1/admin/bot/capabilities`,以及 `/api/v1/admin/accounts/{account_id}/bot` 下的连接、会话、验证和接入任务接口。
+
+飞书扫码接入分三步:
+
+1. 选择同账户普通用户作为连接的运行身份。服务端绑定可用凭证,浏览器无需接收该用户的 API Key。
+2. 飞书扫码,创建应用、配置权限和事件并提交发布。已有应用可改用手动凭证配置。
+3. 将机器人加入群,验证消息接收和回复。发送 API 接受回复不代表群内可见,接入时仍需在群里确认。
+
+连接和捕获的消息保存在 Bot 数据目录的 `studio.sqlite3`,文件权限为 `0600`。数据库含应用和绑定用户的凭证,备份需按服务端配置处理。Studio 管理的飞书会话只开放绑定身份允许的 OpenViking 查询和记忆工具;Shell、本地文件、定时任务和未批准的 MCP 工具不可用。
+
+暂停连接保留历史。删除连接会移除本地记录,不会删除飞书应用或飞书中的消息。飞书历史在 Studio 中只读,从该 Studio 连接捕获的消息开始;不会自动迁入 `ov.conf` 中已有的渠道及其旧历史。同一连接暂停恢复或重启后保留上下文;删除并重建连接会创建新的上下文。
+
## 更多文档
- [VikingBot 完整使用说明](https://github.com/volcengine/OpenViking/blob/main/bot/README_CN.md)
diff --git a/examples/openclaw-plugin/README.md b/examples/openclaw-plugin/README.md
index 7dfe99b04..a2c047b1b 100644
--- a/examples/openclaw-plugin/README.md
+++ b/examples/openclaw-plugin/README.md
@@ -319,17 +319,9 @@ The plugin operates exclusively in remote mode as a pure HTTP client:
The OpenViking service must be deployed and running independently before the plugin can connect to it.
-## Relationship to the Older Design Draft
+## Context lifecycle reference
-The repo also contains a more future-looking design draft at `docs/design/openclaw-context-engine-refactor.md`. It is important not to conflate the two:
-
-- this README describes current implemented behavior
-- the older draft discusses a stronger future move into context-engine-owned lifecycle control
-- in the current version, the main automatic recall path lives in `assemble()`: preflight rebuilds history, transformContext injects long-term memories
-- in the current version, `afterTurn()` already appends to the OpenViking session, but commit remains threshold-triggered and asynchronous on that path
-- in the current version, `compact()` already uses `commit(wait=true)`, but it is still focused on synchronous commit plus readback rather than owning every orchestration concern
-
-That distinction matters, otherwise the future design draft is easy to misread as already shipped behavior.
+For the current assemble, recall, capture, and compaction behavior, see the [OpenClaw integration guide](../../docs/en/agent-integrations/03-openclaw.md#how-assemble-builds-context). The guide also explains the retained `agentExperience` settings and their current limits.
## Operator and Debugging Surfaces
diff --git a/examples/openclaw-plugin/README_CN.md b/examples/openclaw-plugin/README_CN.md
index 3c3a42a9b..b896a37d0 100644
--- a/examples/openclaw-plugin/README_CN.md
+++ b/examples/openclaw-plugin/README_CN.md
@@ -360,17 +360,9 @@ Recall trace 默认关闭。可通过插件配置 `traceRecall`、`traceRecallPe
OpenViking 服务需要独立部署并运行,插件才能连接到它。
-## 与旧设计稿的关系
+## 上下文生命周期参考
-仓库里还有一份更偏"未来演进方向"的设计稿:`docs/design/openclaw-context-engine-refactor.md`。阅读时需要区分两者的口径:
-
-- 本文描述的是当前实现已经落地的行为。
-- 旧设计稿讨论的是"进一步把更多主链路迁入 context-engine 生命周期"的目标态。
-- 当前版本里,自动 recall 的主入口已经迁到 `assemble()`:preflight 重建历史,transformContext 注入长期记忆。
-- 当前版本里,`afterTurn()` 已经负责增量写入 OpenViking session,但它仍然依赖阈值触发异步 commit。
-- 当前版本里,`compact()` 已经走 `commit(wait=true)`,但它的职责仍以"同步提交 + 结果回读"为主,而不是承载一切上层编排。
-
-这段区分很重要,否则很容易把未来设计误读成现状。
+当前 assemble、召回、捕获和压缩行为见 [OpenClaw 接入指南](../../docs/zh/agent-integrations/03-openclaw.md#assemble-如何组装上下文)。指南也说明了保留的 `agentExperience` 配置及其当前限制。
## 运维与调试入口
diff --git a/openviking/parse/parsers/README.md b/openviking/parse/parsers/README.md
index 935181e75..03bf4bfbd 100644
--- a/openviking/parse/parsers/README.md
+++ b/openviking/parse/parsers/README.md
@@ -1,10 +1,10 @@
# Built-in parsers
-OpenViking only routes resources to built-in parsers. Applications add resources through
+OpenViking routes resources to built-in parsers or the configured external parser API. Applications add resources through
`add_resource`; parser registries are internal implementation details.
For the complete Accessor, Parser, Understanding, Connector, and asynchronous execution
-flow, see [Resource ingestion routing](../../../docs/design/resource-ingestion-routing.md).
+flow, see [Resource processing](../../../docs/en/api/02-resources.md#resource-processing-pipeline).
Each built-in parser implements `BaseParser` and returns a `ParseResult`. New formats are
added to the repository as built-in parsers and registered in `openviking/parse/registry.py`.