Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
docs: add Rules (Beta) guides and API reference (#6613)
Caucher Wangc81e4e123fdc
diff --git a/bot/docs/en/concepts/02-agent-capabilities.md b/bot/docs/en/concepts/02-agent-capabilities.mdindex 13b08db97..cf80a4e6c 100644--- a/bot/docs/en/concepts/02-agent-capabilities.md+++ b/bot/docs/en/concepts/02-agent-capabilities.md@@ -38,7 +38,7 @@ A Skill may orchestrate several tools, but it does not receive additional permis| Commands | `exec` | Execute shell commands through the sandbox backend || Web | `web_search`, `web_fetch` | Search and read web pages || OpenViking | `openviking_list/search/grep/glob/multi_read` | Browse, retrieve, and read context |-| OpenViking | `openviking_rule_search` | Retrieve compiled constraints applicable to a concrete task |+| OpenViking | `openviking_rule_search` (Beta) | Retrieve compiled constraints applicable to a concrete task || OpenViking | `openviking_add_resource`, `openviking_memory_commit` | Add resources and commit memory || Delivery | `message`, `generate_image` | Send messages proactively or generate images || Automation | `cron` | Manage scheduled Agent tasks; disabled by default |diff --git a/bot/docs/en/concepts/04-openviking-integration.md b/bot/docs/en/concepts/04-openviking-integration.mdindex 951bf62bf..a91752617 100644--- a/bot/docs/en/concepts/04-openviking-integration.md+++ b/bot/docs/en/concepts/04-openviking-integration.md@@ -145,7 +145,7 @@ When a channel enables `ov_tools_enable`, the Agent can use:|------|------------|| `openviking_list` | Browse a Viking URI directory || `openviking_search` | Semantically search Resources, Memories, and Skills |-| `openviking_rule_search` | Retrieve compiled Rules applicable to a concrete task context |+| `openviking_rule_search` (Beta) | Retrieve compiled Rules applicable to a concrete task context || `openviking_grep` | Run regular-expression searches over OpenViking content || `openviking_glob` | Search URI paths with glob patterns || `openviking_multi_read` | Read the full content of multiple URIs concurrently |diff --git a/bot/docs/zh/concepts/02-agent-capabilities.md b/bot/docs/zh/concepts/02-agent-capabilities.mdindex e7a329e40..6ed18f7ab 100644--- a/bot/docs/zh/concepts/02-agent-capabilities.md+++ b/bot/docs/zh/concepts/02-agent-capabilities.md@@ -38,7 +38,7 @@ Skill 可以编排多个工具,但不会自动获得额外权限。工具是| 命令 | `exec` | 在沙箱后端执行 shell 命令 || 网络 | `web_search`、`web_fetch` | 搜索和读取网页 || OpenViking | `openviking_list/search/grep/glob/multi_read` | 浏览、检索和读取上下文 |-| OpenViking | `openviking_rule_search` | 检索适用于具体任务的已编译约束 |+| OpenViking | `openviking_rule_search`(Beta) | 检索适用于具体任务的已编译约束 || OpenViking | `openviking_add_resource`、`openviking_memory_commit` | 添加资源和提交记忆 || 对外操作 | `message`、`generate_image` | 主动发送消息或生成图片 || 自动化 | `cron` | 管理定时 Agent 任务,默认关闭 |diff --git a/bot/docs/zh/concepts/04-openviking-integration.md b/bot/docs/zh/concepts/04-openviking-integration.mdindex f99dffcda..7e239b94e 100644--- a/bot/docs/zh/concepts/04-openviking-integration.md+++ b/bot/docs/zh/concepts/04-openviking-integration.md@@ -145,7 +145,7 @@ Experience 保存 Agent 过去完成任务时形成的可复用方法。VikingBo|------|------|| `openviking_list` | 浏览 Viking URI 目录 || `openviking_search` | 对资源、记忆和 Skill 做语义检索 |-| `openviking_rule_search` | 检索适用于具体任务上下文的已编译 Rules |+| `openviking_rule_search`(Beta) | 检索适用于具体任务上下文的已编译 Rules || `openviking_grep` | 在 OpenViking 内容中做正则搜索 || `openviking_glob` | 按 URI 路径模式搜索 || `openviking_multi_read` | 并发读取多个 URI 的完整内容 |diff --git a/docs/.vitepress/theme/docs-sections.ts b/docs/.vitepress/theme/docs-sections.tsindex f03bcbbbc..d8dd3bceb 100644--- a/docs/.vitepress/theme/docs-sections.ts+++ b/docs/.vitepress/theme/docs-sections.ts@@ -177,6 +177,9 @@ export const sections: DocSection[] = [g('Choose a workflow', '选择开发任务', [p('workflows/01-overview')]),+ g('Rule validation (Beta)', '规则校验(Beta)', [+ p('workflows/02-rule-validation')+ ]),g('Manage context', '组织与维护上下文', [p('guides/23-data-organize'),p('guides/18-openviking-assets'),@@ -255,6 +258,9 @@ export const sections: DocSection[] = [p('api/04-skills'),p('api/19-agent-evolution')]),+ g('Rules (Beta)', '规则(Beta)', [+ p('api/26-rules')+ ]),g('Data and extension APIs', '数据与扩展 API', [p('api/11-snapshot'),p('api/14-ovpack'),diff --git a/docs/en/agent-integrations/01-overview.md b/docs/en/agent-integrations/01-overview.mdindex 0e619a9b2..4197ab69e 100644--- a/docs/en/agent-integrations/01-overview.md+++ b/docs/en/agent-integrations/01-overview.md@@ -16,6 +16,7 @@ OpenViking can act as the long-term memory and context backend for many agent ru| **OpenCode** | [OpenCode Plugin](./10-opencode.md) — MCP tools plus lifecycle hooks for repo context, auto-recall, and capture || **pi** | [pi Coding Agent Extension](./11-pi.md) — native extension with auto-recall, turn capture, threshold commit, and the server's MCP tools registered as native pi tools || **LangChain / LangGraph** | [LangChain and LangGraph](./07-langchain-langgraph.md) — retriever, tools, context backend, store, and middleware |+| **VikingBot** | [VikingBot Installation and Configuration](../guides/17-vikingbot.md) — built-in Agent with the `openviking_rule_search` tool (Beta) || **Multiple local coding agents / a desktop UI** | [OpenViking Helper](./14-openviking-helper.md) — visual agent setup, session inspection, and memory management || **Any Agent Plugins 1.0 client** | [Agent Plugins 1.0 Package](./15-agent-plugins.md) — one portable package: `openviking-memory` skill plus the OpenViking MCP tools || **Manus / Claude Desktop / ChatGPT / other MCP clients** | [MCP Clients](./06-mcp-clients.md) — point any MCP-compatible client at the built-in `/mcp` endpoint |diff --git a/docs/en/api/01-overview.md b/docs/en/api/01-overview.mdindex e4d170eb2..5d1f9e383 100644--- a/docs/en/api/01-overview.md+++ b/docs/en/api/01-overview.md@@ -432,6 +432,13 @@ This catalog follows the routes actually mounted by the server. Each group headi| GET | `/api/v1/agent-evolution/experiences/trajectories` | List trajectories that consumed an Experience || GET | `/api/v1/agent-evolution/experiences/outcomes` | Aggregate outcomes of trajectories that consumed an Experience |+### [Rules (Beta)](26-rules.md)++| Method | Path | Description |+|--------|------|-------------|+| POST | `/api/v1/rules/compile` | Submit a background rule compilation task |+| POST | `/api/v1/rules/search` | Retrieve applicable active rules for task context |+### [Retrieval](06-retrieval.md)| Method | Path | Description |diff --git a/docs/en/api/26-rules.md b/docs/en/api/26-rules.mdnew file mode 100644index 000000000..58f13617d--- /dev/null+++ b/docs/en/api/26-rules.md@@ -0,0 +1,238 @@+# Rules (Beta)++The Rules API compiles user-provided mandatory constraints into durable Rules and retrieves applicable rules using task context. The current interfaces are the Python HTTP SDK and HTTP API; there are no dedicated CLI, TypeScript SDK, or Go SDK methods. VikingBot includes a [rule search tool (Beta)](../guides/17-vikingbot.md).++Compilation and search use the authenticated user's library at `viking://user/<user_id>/memories/rules/`. See [Rules (Beta)](../concepts/17-rule-scenarios.md) for concepts and [Rule validation (Beta)](../workflows/02-rule-validation.md) for the complete workflow.++## API Reference++### rule_compile()++#### 1. Purpose and prerequisites++Submit rule text or source material for background compilation, creating or updating rules or changing their status on explicit user instructions. A working Compiler model is required; it defaults to the server VLM and can be overridden with `rules.compiler`.++Sources can be ingested resources or new files, directories, or URLs. New sources go through resource ingestion before constraint extraction. Ordinary session commits do not trigger compilation.++#### 2. Interface and parameters++```text+POST /api/v1/rules/compile+```++| Parameter | Type | Required | Default | Description |+| --- | --- | --- | --- | --- |+| `instruction` | string | At least one of this or `sources` | `null` | Rule text or explicit change instructions; at most 64,000 characters. Without sources, it must remain non-empty after trimming |+| `sources` | array | At least one of this or `instruction` | `[]` | At most 16 sources; use `options["sources"]` in the Python SDK |++Each HTTP source uses one of these forms:++| Source | Format | Description |+| --- | --- | --- |+| Existing resource | `{"resource_uri": "viking://resources/standards"}` | Read resource content without importing it again |+| New remote source | `{"path": "https://example.com/standards.md"}` | Reuse the resource ingestion request; see the [Resources API](./02-resources.md) for fields |+| New local source | `{"temp_file_id": "upload-id", "source_name": "standards.md"}` | Upload through the resource temporary upload endpoint first; package directories as ZIP files |++The Python SDK also accepts source strings: local file or directory paths, URLs, and `viking://` resource URIs. It uploads local sources and converts them into HTTP objects.++The Compiler generates mutations; callers do not submit them directly:++| Operation | Behavior |+| --- | --- |+| `NEW` | Create an active Rule and reuse or create a Scenario |+| `UPDATE` | Update one rule, keeping its identity and active/paused status |+| `REPLACE` | On explicit full replacement of one old rule, create a new identity and archive the old rule |+| `NOOP` | An active Rule fully covers the input; no write |+| `UNCERTAIN` / `REJECT` | Record ambiguity or rejection reasons without writing a Rule |+| `PAUSE` | Explicitly pause or disable an active Rule |+| `RESTORE` | Explicitly reactivate a paused Rule |+| `ARCHIVE` | Explicit deletion, discard, or recycle-bin intent; authorization must come from `instruction` |++Compilation candidates include only active and paused rules. There is no public path to restore archived rules or a dedicated interface for submitting lifecycle operations directly by ID.++#### 3. Examples++**Python SDK (HTTP)**++```python+from openviking_sdk import SyncHTTPClient++client = SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+task = client.rule_compile(+ instruction="When a repository declares itself open source, it must provide a complete project license text.",+)+print(task["task_id"])++# One status query; see the workflow for polling and index checks.+print(client.get_task(task["task_id"]))+```++**HTTP API**++```bash+curl -X POST http://localhost:1933/api/v1/rules/compile \+ -H "X-API-Key: your-key" \+ -H "Content-Type: application/json" \+ -d '{+ "instruction": "When a repository declares itself open source, it must provide a complete project license text."+ }'+```++#### 4. Response contract and errors++HTTP returns **202 Accepted** with a background task record. The Python SDK returns the task object inside the outer `result`. This example omits timestamps and metadata:++```json+{+ "status": "ok",+ "result": {+ "task_id": "rule_compile_example",+ "task_type": "rule_compile",+ "status": "pending",+ "resource_id": "viking://user/alice/memories/rules",+ "stage": "queued",+ "result": null,+ "error": null+ }+}+```++Receiving a task does not mean compilation has completed. Poll the [Tasks API](./17-tasks.md) until `completed`, handling `failed` and `cancelled`. A newly returned task may already be `running`. On completion, `task.result` includes:++| Field | Type | Description |+| --- | --- | --- |+| `rules_root` | string | Current user's rule library URI |+| `source_uris` | array | Source resource URIs; can be empty for inline text |+| `plan_reason` | string | Explanation of the compilation plan |+| `batch_count` | integer | Number of input compilation batches |+| `operations` | array | Actual mutations or reasons for no write; fields depend on operation type |+| `written_uris` | array | Rule and Scenario URIs written |+| `write_result` | object | Batch write result; writes can include a separate `task_id` for index processing |++Example completed task result, omitting other task fields and write statistics:++```json+{+ "status": "ok",+ "result": {+ "task_id": "rule_compile_example",+ "task_type": "rule_compile",+ "status": "completed",+ "result": {+ "rules_root": "viking://user/alice/memories/rules",+ "source_uris": [],+ "plan_reason": "Create the project license requirement.",+ "batch_count": 1,+ "operations": [+ {+ "operation": "NEW",+ "atomic_id": "project-license",+ "uri": "viking://user/alice/memories/rules/repository-license/project-license.md"+ }+ ],+ "written_uris": [+ "viking://user/alice/memories/rules/repository-license/abstract.md",+ "viking://user/alice/memories/rules/repository-license/project-license.md"+ ],+ "write_result": {"task_id": "write_example"}+ },+ "error": null+ }+}+```++Inspect the actual operations and generated content, then wait for `write_result.task_id` before searching. Invalid request structures or lengths return HTTP 422. Background parsing, model, or validation failures appear in the task's `error`; compilation failures carry `RULE_COMPILE_FAILED`.++---++### rule_search()++#### 1. Purpose and prerequisites++Retrieve active rules for the current task, with complete constraints and applicability information. Confirm that compilation and associated index tasks have completed, and search as the same user.++Task context should include the goal, object, planned actions, and known facts. Search judges applicability; the Agent checks evidence and whether rules are violated.++#### 2. Interface and parameters++```text+POST /api/v1/rules/search+```++| Parameter | Type | Required | Default | Description |+| --- | --- | --- | --- | --- |+| `task_context` | string | Yes | — | Non-empty task context, at most 64,000 characters |+| `rule_probability_threshold` | number | No | `0.65` | `0`–`1`, inclusive; return rules scoring at least this value. Pass in SDK `options` |++The public interface has no `limit`, `scenario_limit`, or `target_uri`. Search semantically recalls Scenarios, filters unrelated situations, then reads their active Rules.++#### 3. Examples++**Python SDK (HTTP)**++```python+from openviking_sdk import SyncHTTPClient++client = SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+result = client.rule_search(+ task_context="Read-only license review: README declares the repository open source; next, inspect LICENSE text.",+ options={"rule_probability_threshold": 0.65},+)+print(result["rendered"])+print(result.get("warning"))+```++**HTTP API**++```bash+curl -X POST http://localhost:1933/api/v1/rules/search \+ -H "X-API-Key: your-key" \+ -H "Content-Type: application/json" \+ -d '{+ "task_context": "Read-only license review: README declares the repository open source; next, inspect LICENSE text.",+ "rule_probability_threshold": 0.65+ }'+```++#### 4. Response contract and errors++HTTP returns **200 OK** with a result envelope. The Python SDK returns the outer `result` directly.++| Field | Type | Description |+| --- | --- | --- |+| `rules` | array | Matches, each with `atomic_id`, `revision`, `scenario_id`, `probability`, `uri`, and `content` |+| `rules[].content` | string | Complete stored Rule Markdown, including metadata and the constraint, not just its constraint sentence |+| `scenarios` | array | Scenario identities passed to the rule loading stage |+| `rendered` | string | Application protocol and complete rule blocks for the Agent |+| `delivery` | object | `complete`, `rule_count`, and `rendered_chars`; delivery completeness for matched rules |+| `scenario_selection` | object / null | Scenario filtering information, including backend, passed or filtered details, and possible warnings |+| `judge` | string, optional | `jev_noul` or `pass`; may be absent with no candidates |+| `warning` | string, optional | Pass-through explanation when Rule judgment is unavailable |++Example response with no Scenario candidates:++```json+{+ "status": "ok",+ "result": {+ "rules": [],+ "scenarios": [],+ "rendered": "# Applicable OpenViking Rules\n\nThese Rules are behavioral constraints.\n\nApplication protocol:\n1. Evaluate every Rule independently against concrete facts from the current task.\n2. Check the applicability boundary and exception before applying a Rule. An empty\n applies_when means the Rule applies in every situation except its exception.\n For a non-empty applies_when, topic similarity alone does not establish applicability.\n3. Do not infer facts that are absent.\n4. Before acting or answering, validate the planned action or answer against every\n returned Rule. Returned Rules are mandatory when their applicability conditions hold.\n\nMatched 0 active Rule(s).\n\nNo active compiled Rule met the current retrieval thresholds.",+ "scenario_selection": null,+ "delivery": {"complete": true, "rule_count": 0, "rendered_chars": 730}+ }+}+```++Even with no matches, `rendered` contains the application protocol and an empty-match message. `delivery.complete=true` means selected rules were not truncated, not that the entire library was recalled. Empty results are not a compliance verdict.++When Jev is unconfigured or judgment fails, affected candidates pass through. Failed Rule judgment returns `judge="pass"`, `probability=1.0`, and `warning`; the score is not an estimated probability. Scenario judgment warnings appear in `scenario_selection`. Agents must check every rule's conditions and exceptions.++Blank context, overlong text, an out-of-range threshold, or extra parameters return HTTP 422. Failures reading Rule files can fail the request; handle interface errors without treating them as an empty rule set. See [API conventions](./01-overview.md) for authentication and general error formats.++## Related documentation++- [Rules (Beta)](../concepts/17-rule-scenarios.md)+- [Rule validation (Beta)](../workflows/02-rule-validation.md)+- [Background Tasks](./17-tasks.md)+- [Server Rules configuration](../configuration/01-server.md#rules)diff --git a/docs/en/concepts/00-overview.md b/docs/en/concepts/00-overview.mdindex 07b101955..13458e473 100644--- a/docs/en/concepts/00-overview.md+++ b/docs/en/concepts/00-overview.md@@ -17,6 +17,7 @@ Trace the paths from source ingestion and recorded conversations:- [Context Extraction](06-extraction.md): how sources are parsed, organized and processed semantically.- [Retrieval Mechanism](07-retrieval.md): how relevant context is found and how `find` differs from `search`.- [Session Management](08-session.md): how messages, session commits and memory extraction connect.+- [Rules (Beta)](17-rule-scenarios.md): how durable constraints are compiled and recalled for Agent checks.When you are ready to build, choose an [application workflow](../workflows/01-overview.md). Look up parameters and responses in the [reference](../reference/01-overview.md).diff --git a/docs/en/concepts/02-context-types.md b/docs/en/concepts/02-context-types.mdindex c799d1e13..92606eb2e 100644--- a/docs/en/concepts/02-context-types.md+++ b/docs/en/concepts/02-context-types.md@@ -1,14 +1,15 @@# Context Types-OpenViking manages three types of context: resources provide reference material, memories retain information from interactions, and skills describe how to carry out tasks.+OpenViking resources provide reference material, memories retain information from interactions, and skills describe how to carry out tasks. [Rules (Beta)](./17-rule-scenarios.md) are a separate type of mandatory constraint that an Agent must follow when its conditions hold.## Overview| Type | Purpose | Lifecycle | Initiative ||------|---------|-----------|------------|-| **Resource** | Knowledge and rules | Retained until updated or deleted | User adds |+| **Resource** | Source knowledge and reference material | Retained until updated or deleted | User adds || **Memory** | Preferences, facts, and task experience | Long-term, dynamically updated | Extracted from sessions or recorded explicitly || **Skill** | Task instructions and supporting resources | Long-term, updatable | User or system adds |+| **Rule (Beta)** | Durable, executable mandatory constraints | active / paused / archived | Explicit compilation and on-demand recall |## Example Setupdiff --git a/docs/en/concepts/17-rule-scenarios.md b/docs/en/concepts/17-rule-scenarios.mdindex 603be6ec4..f8b5b268a 100644--- a/docs/en/concepts/17-rule-scenarios.md+++ b/docs/en/concepts/17-rule-scenarios.md@@ -1,60 +1,101 @@-# Rule Scenarios+# Rules (Beta)-Rules are grouped by **Scenario**, the situations in which their constraints may matter.-The compiler uses `scenario` for NEW mutations and `scenario_id` for Scenario identity.-Rule search returns `scenarios`, each Rule's `scenario_id`, and `scenario_selection`.+A Rule is a durable constraint an Agent must follow when its conditions hold, such as an obligation, prohibition, or boundary. OpenViking compiles source material in batches into self-contained rules, then retrieves applicable rules for the current task so the Agent can check them before acting or answering.-Each Scenario is a directory directly under the user's Rule library:+The current Beta supports explicit imports and on-demand recall. Ordinary session commits do not automatically compile rules, and there is no built-in flow that forcibly injects them on every user message or at the start of every session.++## How rules differ from other context types++| Type | Question it answers | Example |+| --- | --- | --- |+| Resource | What source material can I consult? | An agreement, code repository, or technical specification |+| Memory | What facts, preferences, and experience are known? | A user prefers concise answers; a project uses a particular framework |+| Skill | How do I carry out this kind of task? | Repository review steps or a report generation method |+| Rule | Under which conditions must I do something, or refrain from doing it? | A repository declaring itself open source must provide a locatable license text |++Rules take priority over ordinary Memory. They are a separate context type with dedicated compilation and search interfaces, even though they live under the user's `memories/rules/`. Importing an agreement or standard as a Resource stores the material; its mandatory constraints still need explicit compilation.++Preferences, suggestions, facts, examples, and one-off tasks should not become Rules. Compilation must not turn “should” into “must” or weaken “must” and “must not.”++## Use cases++| Scenario | Rule sources | How the Agent uses them |+| --- | --- | --- |+| Legal agreement review | Obligations, prohibitions, and exceptions in user-provided agreements | Retrieve constraints using the review object and known facts, then check the text or planned actions |+| Coding standards checks | Team development standards and review requirements | Retrieve rules using the repository, changes, and execution stage, then check the proposed changes |+| Open-source license checks | User-provided license requirements | Read repository declarations and license files, verify triggering conditions, and record evidence |++For example, “When a repository declares itself open source, it must provide an explicit, complete, and locatable project license text” can produce:++| Field | Example |+| --- | --- |+| `content` | When a repository declares itself open source, it must provide an explicit, complete, and locatable project license text. |+| `applies_when` | The repository declares itself open source. |+| `exception` | Empty string: the source specifies no exception. |+| Scenario | Project license review |++Topic similarity does not establish applicability. Agents must verify conditions using readable evidence. A rule still applies when its requirement is already satisfied.++## How rules are organized++Each Rule holds one complete constraint that can be updated or withdrawn independently. It includes `content`, applicability conditions in `applies_when`, an `exception`, sources and exact evidence, a stable `atomic_id`, a `revision`, and a `status`. Empty `applies_when` means the rule applies everywhere except its exception.++A Scenario describes situations in which rules may apply, such as “Project license review,” and groups rules for retrieval. It is not a source document title: one document can produce multiple Scenarios, and several sources can share a Scenario.```textviking://user/<user_id>/memories/rules/-└── file-operations/- ├── abstract.md- ├── confirm-delete.md- └── preserve-backups.md+└── repository-license/+ ├── abstract.md # Scenario description+ └── project-license.md # Complete Rule record```-`abstract.md` contains Scenario metadata and a short description:+## Compilation flow-```markdown-----schema: openviking.rule.scenario/v1-scenario_id: file-operations-name: File operations-description: Constraints for creating, modifying, and deleting files.-updated_at: "2026-10-21T00:00:00+00:00"----+```text+Rule text, files, directories, or URLs+ → Read existing resources, or parse and ingest new sources+ → Recall existing active / paused rules+ → Compiler extracts constraints and proposes mutations+ → Validate structure, targets, exact evidence, and retained requirements+ → Write Rules / Scenarios and refresh indexes asynchronously+```++The Compiler preserves obligation strength, conditions, exceptions, thresholds, and units, separating rules that can be maintained independently. An evolving rule updates its existing record; an explicit full replacement creates a new identity and archives the old record. Fully covered input needs no duplicate write. Material ambiguity or rejected input is recorded with reasons and creates no Rule.++The compilation interface first returns a background task. Inspect the actual mutations after completion. The index task associated with the writes may still be processing; confirm it completes before use as well. See [Rule validation (Beta)](../workflows/02-rule-validation.md) for the steps.-# File operations+## Search and execution flow-Constraints for creating, modifying, and deleting files.+```text+Agent submits the task goal, object, planned actions, and known facts+ → Semantically recall potentially relevant Scenarios+ → Jev filters Scenarios judged unrelated with high confidence+ → Read their active rules and judge conditions and exceptions+ → Return structured rules and complete constraint text+ → Agent checks every rule and constrains its actions or answer```-The other Markdown files contain complete Rule records, including `atomic_id`,-`scenario_id`, revision, status, content, applicability, exceptions, and evidence.-`abstract` is reserved as a file name. The storage system's generated `.abstract.md`-and `.overview.md` are separate internal summaries.--Scenario retrieval searches only `*/abstract.md`; Rule files cannot occupy the-Scenario candidate limit. After selecting Scenarios, the service reads their direct-Rule files. Membership comes from the directory, so no `rule_uris` list is needed.-Paused and archived Rules remain in their Scenario until lifecycle cleanup removes-expired archived Rules. Rule search uses active Rules; compilation considers active-and paused Rules. Archived Rules are logically deleted and appear in neither path.--Rule status is `active`, `paused`, or `archived`. `PAUSE` suspends an active Rule-without scheduling removal. `ARCHIVE` marks a Rule for cleanup after 30 days by-default, using `archived_at`; repeating it does not reset that timestamp.-`RESTORE` reactivates a paused Rule. Archived Rules cannot be restored through Rule-compilation.-Updating a Rule preserves its current lifecycle status. Replaced Rules become archived.-Lifecycle actions require explicit user instructions. `ARCHIVE` specifically requires-explicit deletion, discard, or recycle-bin intent in the user's instruction. Requests-to pause, disable, deactivate, retire, stop applying, or stop using a Rule use `PAUSE`.--Jev judges Scenario irrelevance and Rule applicability. When Jev is unconfigured,-unavailable, fails, or returns invalid results, the affected candidates pass without-VLM judgment. A failed Rule judgment passes all candidate Rules with score `1.0`,-`judge=pass`, and a warning; this is a pass score, not an estimated probability.-Agents still check applicability and exceptions before enforcing a Rule. Rule-compilation continues to use the compiler VLM; the VLM `rule_matcher` setting is removed.+Search returns rules scoring at least `0.65` by default, with no fixed Top-K in the public interface. For non-empty conditions, an exception vetoes a rule only if its score reaches the threshold and strictly exceeds the applicability score. With empty conditions, an exception reaching the threshold is sufficient to veto.++If Jev is unconfigured, unavailable, or returns invalid results, affected candidates pass through. Failed Rule judgment returns `judge="pass"`, `probability=1.0`, and a warning; this score means pass-through, not an estimated probability. Agents must still check conditions and exceptions.++`rendered` supplies an application protocol and complete rule blocks for the Agent. Search determines whether rules apply; the Agent uses task evidence to decide whether they are satisfied, violated, or undetermined. Empty results do not prove the library contains no relevant constraints. `delivery.complete` only means matched rules were delivered in full, not that the entire library was recalled.++## Lifecycle++| Status | Compilation candidate | Search candidate | Meaning |+| --- | --- | --- | --- |+| `active` | Yes | Yes | Enabled |+| `paused` | Yes | No | Suspended and retained without expiry cleanup |+| `archived` | No | No | Logically deleted; eligible for cleanup after retention |++Explicit requests to pause or disable use `PAUSE`; reactivation of paused rules uses `RESTORE`. Deletion, discard, or moving to the recycle bin uses `ARCHIVE`. `UPDATE` preserves the current status. The compilation interface cannot restore archived rules.++Archived records store `archived_at`; repeated archival does not reset it. Periodic cleanup is enabled by default with 30-day retention. Physical removal occurs during a scan after retention expires; see [server Rules configuration](../configuration/01-server.md#rules).++## Related documentation++- [Rule validation (Beta)](../workflows/02-rule-validation.md): batch compilation, recall, and Agent checks+- [Rules API (Beta)](../api/26-rules.md): parameters, responses, and failures+- [VikingBot Installation and Configuration](../guides/17-vikingbot.md): the rule search tool+- [Context Types](./02-context-types.md): resources, memory, and skillsdiff --git a/docs/en/configuration/01-server.md b/docs/en/configuration/01-server.mdindex 31f21f62c..3c6923dae 100644--- a/docs/en/configuration/01-server.md+++ b/docs/en/configuration/01-server.md@@ -222,7 +222,7 @@ instruction; non-deletion deactivation requests use `PAUSE`.Rules live directly in `memories/rules/<scenario_id>/`: `abstract.md` stores Scenariometadata and `<atomic_id>.md` stores each Rule. See-[Rule Scenarios](../concepts/17-rule-scenarios.md) for the storage format.+[Rules (Beta)](../concepts/17-rule-scenarios.md) for the storage format.When `jev_rule_matcher` is unconfigured, unavailable, fails, or returns invalidresults, Scenario and Rule judgments pass the candidates without calling a VLM.diff --git a/docs/en/reference/01-overview.md b/docs/en/reference/01-overview.mdindex ec023b2af..3c36ad960 100644--- a/docs/en/reference/01-overview.md+++ b/docs/en/reference/01-overview.md@@ -9,6 +9,7 @@ Use this section to look up interface contracts, protocols and configuration fie| MCP tools, parameters and upload protocol | [MCP tools and protocol](../guides/06-mcp-integration.md); for client installation, see [Connect an MCP client](../agent-integrations/06-mcp-clients.md) || Resources, files and retrieval interfaces | [Resources](../api/02-resources.md), [file system](../api/03-filesystem.md), [content](../api/12-content.md), [retrieval](../api/06-retrieval.md) || Sessions, memory and skills interfaces | [Sessions](../api/05-sessions.md), [memory](../api/16-memory.md), [skills](../api/04-skills.md) |+| Rule compilation and applicability recall (Beta) | [Rules API (Beta)](../api/26-rules.md) || Administration, permissions and background state | [Admin](../api/08-admin.md), [ACL](../api/12-acl.md), [background tasks](../api/17-tasks.md), [Observer](../api/18-observer.md) || Consistency, isolation and processing completion | [Architecture](../concepts/01-architecture.md), [transactions and recovery](../concepts/09-transaction.md), [multi-tenancy](../concepts/11-multi-tenant.md), [queue state](../concepts/16-queue-lifecycle.md) |diff --git a/docs/en/workflows/01-overview.md b/docs/en/workflows/01-overview.mdindex 3e1f57a9b..80d410026 100644--- a/docs/en/workflows/01-overview.md+++ b/docs/en/workflows/01-overview.md@@ -7,6 +7,7 @@ Complete your [first import and retrieval](../getting-started/02-quickstart.md),| Retrieve documents or code in an application | [Import resources](../api/02-resources.md) → [Retrieve](../api/06-retrieval.md) → [Read content](../api/12-content.md) | Ask a question with a known answer, read the returned URI and compare it with the source || Reuse memory across sessions | [Session and memory model](../concepts/08-session.md) → [Session API](../api/05-sessions.md) → [Memory API](../api/16-memory.md) | Commit a session, confirm background completion, then inspect the memories and their ownership || Reuse agent skills | [Skills API](../api/04-skills.md) → [Privacy model](../concepts/13-privacy.md) | Inspect the installed skill, its visibility and how it is invoked |+| Rule validation (Beta) | [Rule concepts](../concepts/17-rule-scenarios.md) → [Compile, recall, and check](./02-rule-validation.md) → [Rules API](../api/26-rules.md) | Check compilation and index tasks and source evidence, then have the Agent verify each rule's conditions, exceptions, and planned actions || Produce a wiki, graph or report from sources | [Context compilation](../context-compilation/01-overview.md) → choose an output tutorial | Check task status, output files and how the output relates to the input sources || Sync or migrate existing context | [Project asset sync](../guides/18-openviking-assets.md), [OVPack](../guides/09-ovpack.md) or [version recovery](../guides/15-snapshot.md) | Follow the relevant guide to verify sync state, imported data or restored content |diff --git a/docs/en/workflows/02-rule-validation.md b/docs/en/workflows/02-rule-validation.mdnew file mode 100644index 000000000..f1731026d--- /dev/null+++ b/docs/en/workflows/02-rule-validation.md@@ -0,0 +1,122 @@+# Rule validation (Beta)++Compile mandatory constraints from agreements or coding standards in batches, then let an Agent recall rules for a concrete task, check evidence, and adjust its actions. This tutorial uses user-provided open-source license requirements.++OpenViking compiles rules and retrieves applicable candidates. The Agent decides whether requirements are satisfied or violated; search itself returns no compliance verdict. See [Rules (Beta)](../concepts/17-rule-scenarios.md) for concepts and lifecycle.++## Prerequisites++- Run an OpenViking Server that includes Rule support, with working Compiler and Embedding models. The Compiler defaults to the server VLM; `rules.compiler` can override it.+- Use a Python HTTP SDK with `rule_compile()` and `rule_search()`, configured with the current user's identity. Compile and search as the same user.+- Prepare mandatory constraints confirmed by the user, preserving conditions, exceptions, and thresholds. Do not treat ordinary suggestions or preferences as rules.++See [server Rules configuration](../configuration/01-server.md#rules) and [API conventions](../api/01-overview.md). Run the following snippets in order, replacing the URL and API key with your configuration.++## Step 1: Submit rule material++```python+from openviking_sdk import SyncHTTPClient++client = SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+task = client.rule_compile(+ instruction=(+ "When a repository declares itself open source, "+ "it must provide an explicit, complete, and locatable project license text."+ ),+)+print(task["task_id"])+```++To import files or a directory in a batch, replace the call above with:++```python+task = client.rule_compile(options={"sources": ["./compliance-rules/"]})+```++The SDK uploads local sources. Use `{"sources": ["viking://resources/compliance-rules"]}` for an already ingested resource to avoid importing it again. See the [Rules API](../api/26-rules.md) for HTTP source formats.++## Step 2: Wait and inspect the output++```python+import time+++def wait_for_task(task_id, timeout=300):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ current = client.get_task(task_id)+ if current is None:+ raise RuntimeError(f"Task not found: {task_id}")+ if current["status"] == "completed":+ return current+ if current["status"] in {"failed", "cancelled"}:+ raise RuntimeError(current)+ time.sleep(1)+ raise TimeoutError(f"Task still running: {task_id}")+++completed = wait_for_task(task["task_id"])+result = completed["result"]+print(result["operations"])+print(result["written_uris"])++# Compilation and subsequent index processing may have separate tasks.+write_task_id = result.get("write_result", {}).get("task_id")+if write_task_id:+ wait_for_task(write_task_id)++for uri in result["written_uris"]:+ print(client.read(uri))+```++Check that generated rules retain the subject, obligations, conditions, exceptions, and exact source evidence. `UNCERTAIN` and `REJECT` only record reasons; `NOOP` means an existing rule covers the input. A timeout stops local polling without cancelling the server task.++## Step 3: Search for a concrete task++Read the object under review first, then put the goal, object, planned actions, and available evidence into `task_context`. These are example facts; replace them with observations from your task:++```python+matches = client.rule_search(+ task_context=(+ "Perform a read-only open-source license review of a repository. "+ "README.md has been read and declares the project open source. "+ "A LICENSE file exists at the root, but its text has not been checked. "+ "Next, read the license text and check its completeness."+ ),+)+print(matches["rendered"])+print(matches.get("warning"))+```++Give the complete `rendered` text to the Agent. Applications using the API directly should also inspect `judge`, `warning`, and `scenario_selection`. When Jev is unavailable, candidates may pass through; their pass scores are not confirmed applicability probabilities.++## Step 4: Have the Agent check every rule++For each returned rule, the Agent should:++1. Check `applies_when` against concrete evidence without inventing missing facts. Empty conditions mean the rule applies except for its exception.+2. Check explicit exceptions, then validate planned actions or answers against `content`.+3. For reviews, record rule identities, sources, and evidence from the reviewed object, distinguishing satisfied, violated, and undetermined requirements. Already satisfied rules still belong in the applicable set.+4. Search again when new facts materially change the applicable situation.++In this example, the README declaration triggers the rule. The existence of LICENSE does not establish that its text is complete, so further reading is needed. Empty search results neither establish the absence of relevant rules nor constitute a passed check.++## Connect an existing Agent++[VikingBot](../guides/17-vikingbot.md) includes the `openviking_rule_search` tool (Beta), available on demand after connecting to OpenViking.++Other Agents can use the Python HTTP SDK or HTTP API and install the companion Skills. Copy each complete directory to the Agent's configured Skills directory, then load it:++| Task | Companion Skill |+| --- | --- |+| Prepare sources, compile, and inspect results | [add-rules](https://github.com/volcengine/OpenViking/tree/main/examples/skills/add-rules) |+| Build task context, recall, and check rules | [openviking-rule-search](https://github.com/volcengine/OpenViking/tree/main/examples/skills/openviking-rule-search) |++Skills provide operational and behavioral instructions; the Agent still needs callable interfaces. The current Beta is invoked explicitly by the user or Agent.++## Related documentation++- [Rules (Beta)](../concepts/17-rule-scenarios.md)+- [Rules API (Beta)](../api/26-rules.md)+- [Background Tasks](../api/17-tasks.md)+- [Application workflows](./01-overview.md)diff --git a/docs/zh/agent-integrations/01-overview.md b/docs/zh/agent-integrations/01-overview.mdindex 048515bdb..241adc4e7 100644--- a/docs/zh/agent-integrations/01-overview.md+++ b/docs/zh/agent-integrations/01-overview.md@@ -16,6 +16,7 @@ OpenViking 可以作为多种 Agent 运行时的长期记忆与上下文后端| **OpenCode** | [OpenCode 插件](./10-opencode.md) — MCP 工具 + 生命周期 hooks,覆盖仓库上下文、自动召回与捕获 || **pi** | [pi Coding Agent 扩展](./11-pi.md) — 原生扩展,自动召回、逐轮捕获、阈值 commit,并把服务端的 MCP 工具注册为 pi 原生工具 || **LangChain / LangGraph** | [LangChain 和 LangGraph](./07-langchain-langgraph.md) — retriever、tools、context backend、store 和 middleware |+| **VikingBot** | [VikingBot 安装与配置](../guides/17-vikingbot.md) — 内置 Agent,提供 `openviking_rule_search` 规则搜索工具(Beta) || **多个本地开发 Agent / 希望使用桌面界面** | [OpenViking Helper](./14-openviking-helper.md) — 可视化完成 Agent 接入、会话分析和记忆管理 || **任意支持 Agent Plugins 1.0 的客户端** | [Agent Plugins 1.0 插件包](./15-agent-plugins.md) — 一个可移植的包:`openviking-memory` 技能 + OpenViking MCP 工具 || **Manus / Claude Desktop / ChatGPT / 其他 MCP 客户端** | [MCP 客户端](./06-mcp-clients.md) — 任何兼容 MCP 的客户端直接对接内置 `/mcp` 端点 |diff --git a/docs/zh/api/01-overview.md b/docs/zh/api/01-overview.mdindex dc86d6942..14e4ff08d 100644--- a/docs/zh/api/01-overview.md+++ b/docs/zh/api/01-overview.md@@ -427,6 +427,13 @@ JSON 输出 - 错误:| GET | `/api/v1/agent-evolution/experiences/trajectories` | 分页查询应用过指定 Experience 的 Trajectory || GET | `/api/v1/agent-evolution/experiences/outcomes` | 聚合应用过指定 Experience 的 Trajectory 结果分布 |+### [规则(Beta)](26-rules.md)++| 方法 | 路径 | 说明 |+|------|------|------|+| POST | `/api/v1/rules/compile` | 提交规则编译后台任务 |+| POST | `/api/v1/rules/search` | 按任务上下文召回适用的 active 规则 |+### [检索](06-retrieval.md)| 方法 | 路径 | 说明 |diff --git a/docs/zh/api/26-rules.md b/docs/zh/api/26-rules.mdnew file mode 100644index 000000000..749197bbf--- /dev/null+++ b/docs/zh/api/26-rules.md@@ -0,0 +1,238 @@+# 规则(Beta)++规则 API 将用户提供的强约束编译为持久 Rule,并按任务上下文召回适用规则。当前提供 Python HTTP SDK 和 HTTP 接口;没有对应的专用 CLI、TypeScript SDK 或 Go SDK 方法。VikingBot 提供[规则搜索工具(Beta)](../guides/17-vikingbot.md)。++编译和搜索使用当前认证用户的规则库 `viking://user/<user_id>/memories/rules/`。规则概念见[规则(Beta)](../concepts/17-rule-scenarios.md),完整操作流程见[规则校验(Beta)](../workflows/02-rule-validation.md)。++## API 参考++### rule_compile()++#### 1. 用途与前置条件++提交规则文本或来源材料,后台编译后新增、更新或按用户明确指令变更规则状态。需配置可用的 Compiler 模型;默认复用服务端 VLM,也可设置 `rules.compiler`。++来源可以是已导入的资源,也可以是待导入的文件、目录或 URL。新来源先走资源导入流程,再提炼约束。编译不会从普通会话提交中自动触发。++#### 2. 接口和参数说明++```text+POST /api/v1/rules/compile+```++| 参数 | 类型 | 必填 | 默认值 | 说明 |+| --- | --- | --- | --- | --- |+| `instruction` | string | 与 `sources` 至少提供一项 | `null` | 规则文本或明确的变更要求;最多 64,000 字符。没有来源时,去除首尾空白后必须非空 |+| `sources` | array | 与 `instruction` 至少提供一项 | `[]` | 最多 16 个来源;Python SDK 放在 `options["sources"]` 中 |++每个 HTTP 来源只能使用以下一种形式:++| 来源 | 格式 | 说明 |+| --- | --- | --- |+| 已有资源 | `{"resource_uri": "viking://resources/standards"}` | 直接读取资源正文,不重复导入 |+| 新远程来源 | `{"path": "https://example.com/standards.md"}` | 复用资源导入请求;可用字段见[资源 API](./02-resources.md) |+| 新本地来源 | `{"temp_file_id": "upload-id", "source_name": "standards.md"}` | 先通过资源临时上传接口上传;目录先打包为 ZIP |++Python SDK 还支持来源字符串:本地文件或目录路径、URL、`viking://` 资源 URI;会自动上传本地来源并转换为 HTTP 对象。++编译器生成变更计划,调用者不直接提交 Mutation:++| 操作 | 行为 |+| --- | --- |+| `NEW` | 创建 active Rule,复用或新建 Scenario |+| `UPDATE` | 更新单条规则,保留标识和 active/paused 状态 |+| `REPLACE` | 用户明确完整替代单条旧规则时,创建新标识并归档旧规则 |+| `NOOP` | 已有 active Rule 完整覆盖输入,不写入 |+| `UNCERTAIN` / `REJECT` | 记录歧义或拒绝原因,不写入 Rule |+| `PAUSE` | 用户明确暂停或禁用 active Rule |+| `RESTORE` | 用户明确恢复 paused Rule |+| `ARCHIVE` | 用户明确删除、丢弃或移入回收站;授权必须来自 `instruction` |++当前编译候选只包含 active 和 paused;没有恢复 archived 的公开入口,也没有按 ID 直接提交生命周期操作的专用接口。++#### 3. 使用示例++**Python SDK (HTTP)**++```python+from openviking_sdk import SyncHTTPClient++client = SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+task = client.rule_compile(+ instruction="仓库声明自己是开源项目时,必须提供完整的项目许可证文本。",+)+print(task["task_id"])++# 单次查询;完整等待与索引检查见规则校验教程。+print(client.get_task(task["task_id"]))+```++**HTTP API**++```bash+curl -X POST http://localhost:1933/api/v1/rules/compile \+ -H "X-API-Key: your-key" \+ -H "Content-Type: application/json" \+ -d '{+ "instruction": "仓库声明自己是开源项目时,必须提供完整的项目许可证文本。"+ }'+```++#### 4. 响应契约与错误处理++HTTP 返回 **202 Accepted** 和后台任务记录。Python SDK 返回外层 `result` 中的任务对象。以下示例省略时间和元数据:++```json+{+ "status": "ok",+ "result": {+ "task_id": "rule_compile_example",+ "task_type": "rule_compile",+ "status": "pending",+ "resource_id": "viking://user/alice/memories/rules",+ "stage": "queued",+ "result": null,+ "error": null+ }+}+```++收到任务不表示编译完成。通过[后台任务 API](./17-tasks.md)查询至 `completed`,处理 `failed`、`cancelled`;任务刚返回时也可能已进入 `running`。完成后的 `task.result` 包含:++| 字段 | 类型 | 说明 |+| --- | --- | --- |+| `rules_root` | string | 当前用户规则库 URI |+| `source_uris` | array | 本次来源资源 URI;纯文本输入时可为空 |+| `plan_reason` | string | 编译计划说明 |+| `batch_count` | integer | 输入编译批次数 |+| `operations` | array | 实际变更或未写入原因;字段随操作类型变化 |+| `written_uris` | array | 本次写入的 Rule 和 Scenario URI |+| `write_result` | object | 批量写入结果;有写入时可包含独立 `task_id`,用于跟踪索引处理 |++任务完成结果示例(省略任务对象的其他字段及写入统计):++```json+{+ "status": "ok",+ "result": {+ "task_id": "rule_compile_example",+ "task_type": "rule_compile",+ "status": "completed",+ "result": {+ "rules_root": "viking://user/alice/memories/rules",+ "source_uris": [],+ "plan_reason": "创建项目许可证要求。",+ "batch_count": 1,+ "operations": [+ {+ "operation": "NEW",+ "atomic_id": "project-license",+ "uri": "viking://user/alice/memories/rules/repository-license/project-license.md"+ }+ ],+ "written_uris": [+ "viking://user/alice/memories/rules/repository-license/abstract.md",+ "viking://user/alice/memories/rules/repository-license/project-license.md"+ ],+ "write_result": {"task_id": "write_example"}+ },+ "error": null+ }+}+```++先检查实际操作和生成内容,再等待 `write_result.task_id` 对应任务完成后检索。请求结构或长度不合法返回 HTTP 422;后台解析、模型或校验失败记录在任务 `error` 中,规则编译失败以 `RULE_COMPILE_FAILED` 标识。++---++### rule_search()++#### 1. 用途与前置条件++根据当前任务召回 active 规则,返回完整约束及适用性信息。应先确认规则编译和关联索引任务完成,并以相同用户身份搜索。++任务上下文应包含目标、对象、计划动作和已知事实。搜索判定适用性,Agent 负责核验事实和是否违反规则。++#### 2. 接口和参数说明++```text+POST /api/v1/rules/search+```++| 参数 | 类型 | 必填 | 默认值 | 说明 |+| --- | --- | --- | --- | --- |+| `task_context` | string | 是 | — | 非空任务上下文,最多 64,000 字符 |+| `rule_probability_threshold` | number | 否 | `0.65` | `0`–`1`,包含边界;返回分数大于等于该值的规则。SDK 放在 `options` 中 |++公开接口没有 `limit`、`scenario_limit` 或 `target_uri` 参数。搜索先语义召回 Scenario,再过滤无关场景并读取其中的 active Rule。++#### 3. 使用示例++**Python SDK (HTTP)**++```python+from openviking_sdk import SyncHTTPClient++client = SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+result = client.rule_search(+ task_context="只读核查仓库许可证;README 声明开源,计划检查 LICENSE 正文。",+ options={"rule_probability_threshold": 0.65},+)+print(result["rendered"])+print(result.get("warning"))+```++**HTTP API**++```bash+curl -X POST http://localhost:1933/api/v1/rules/search \+ -H "X-API-Key: your-key" \+ -H "Content-Type: application/json" \+ -d '{+ "task_context": "只读核查仓库许可证;README 声明开源,计划检查 LICENSE 正文。",+ "rule_probability_threshold": 0.65+ }'+```++#### 4. 响应契约与错误处理++HTTP 返回 **200 OK** 和结果包;Python SDK 直接返回外层 `result`。++| 字段 | 类型 | 说明 |+| --- | --- | --- |+| `rules` | array | 命中规则;每项包含 `atomic_id`、`revision`、`scenario_id`、`probability`、`uri`、`content` |+| `rules[].content` | string | 完整的存储 Rule Markdown,含元数据和约束;不是只有约束句子 |+| `scenarios` | array | 进入规则读取阶段的 Scenario 标识 |+| `rendered` | string | 应用步骤和完整规则块,供 Agent 使用 |+| `delivery` | object | `complete`、`rule_count`、`rendered_chars`;描述命中规则的交付完整性 |+| `scenario_selection` | object / null | Scenario 筛选信息,包括后端、放行或过滤详情及可能的 warning |+| `judge` | string,可选 | `jev_noul` 或 `pass`;无候选时可省略 |+| `warning` | string,可选 | Rule 判断不可用时的放行说明 |++无 Scenario 候选时的响应示例:++```json+{+ "status": "ok",+ "result": {+ "rules": [],+ "scenarios": [],+ "rendered": "# Applicable OpenViking Rules\n\nThese Rules are behavioral constraints.\n\nApplication protocol:\n1. Evaluate every Rule independently against concrete facts from the current task.\n2. Check the applicability boundary and exception before applying a Rule. An empty\n applies_when means the Rule applies in every situation except its exception.\n For a non-empty applies_when, topic similarity alone does not establish applicability.\n3. Do not infer facts that are absent.\n4. Before acting or answering, validate the planned action or answer against every\n returned Rule. Returned Rules are mandatory when their applicability conditions hold.\n\nMatched 0 active Rule(s).\n\nNo active compiled Rule met the current retrieval thresholds.",+ "scenario_selection": null,+ "delivery": {"complete": true, "rule_count": 0, "rendered_chars": 730}+ }+}+```++即使没有命中,`rendered` 仍包含应用步骤和空匹配提示。`delivery.complete=true` 表示选中规则未被截断,不证明全库召回;空结果不能当作合规结论。++Jev 未配置或判断失败时,受影响候选放行。Rule 判断失败返回 `judge="pass"`、`probability=1.0` 和 `warning`;分数不是估算概率。Scenario 判断异常的提示位于 `scenario_selection`。Agent 必须逐条检查适用条件与例外。++空白上下文、超长文本、阈值越界或多余参数返回 HTTP 422。Rule 文件读取失败可能使请求失败;调用方应处理接口错误,不能视为无规则。通用认证和错误格式见[API 总览](./01-overview.md)。++## 相关文档++- [规则(Beta)](../concepts/17-rule-scenarios.md)+- [规则校验(Beta)](../workflows/02-rule-validation.md)+- [后台任务](./17-tasks.md)+- [服务端 Rules 配置](../configuration/01-server.md#rules)diff --git a/docs/zh/concepts/00-overview.md b/docs/zh/concepts/00-overview.mdindex 1a9417145..3c3f7a606 100644--- a/docs/zh/concepts/00-overview.md+++ b/docs/zh/concepts/00-overview.md@@ -17,6 +17,7 @@- [上下文提取](06-extraction.md):原始资料如何经过解析、组织与语义处理。- [检索机制](07-retrieval.md):如何查找相关上下文,`find` 与 `search` 有什么区别。- [会话管理](08-session.md):消息、会话提交与记忆提取如何衔接。+- [规则(Beta)](17-rule-scenarios.md):如何编译持久强约束,并按任务召回供 Agent 核验。准备写应用时,回到[应用开发路径](../workflows/01-overview.md)选择操作流程;参数和响应查[参考文档](../reference/01-overview.md)。diff --git a/docs/zh/concepts/02-context-types.md b/docs/zh/concepts/02-context-types.mdindex 33831dc5e..0a38afda7 100644--- a/docs/zh/concepts/02-context-types.md+++ b/docs/zh/concepts/02-context-types.md@@ -1,14 +1,15 @@# 上下文类型-OpenViking 管理三类上下文:资源提供参考资料,记忆保存交互中提取的信息,技能描述完成任务的方法。+OpenViking 的资源提供参考资料,记忆保存交互中提取的信息,技能描述完成任务的方法。[规则(Beta)](./17-rule-scenarios.md)是独立的强约束类型,表达 Agent 在特定条件下必须遵守的要求。## 概览| 类型 | 用途 | 生命周期 | 主动性 ||------|------|----------|--------|-| **Resource** | 知识和规则 | 保留至更新或删除 | 用户添加 |+| **Resource** | 原始知识与参考资料 | 保留至更新或删除 | 用户添加 || **Memory** | 偏好、事实和任务经验 | 长期,动态更新 | 从会话提取或主动记录 || **Skill** | 任务指令和配套资源 | 长期,可更新 | 用户或系统添加 |+| **Rule(Beta)** | 持久、可执行的强约束 | active / paused / archived | 主动编译,按需召回 |## 示例准备diff --git a/docs/zh/concepts/17-rule-scenarios.md b/docs/zh/concepts/17-rule-scenarios.mdindex 001d079a5..f3864528b 100644--- a/docs/zh/concepts/17-rule-scenarios.md+++ b/docs/zh/concepts/17-rule-scenarios.md@@ -1,56 +1,101 @@-# Rule Scenario+# 规则(Beta)-Rule 按 **Scenario** 分组;Scenario 表示约束可能相关的一类实际情况。-Compiler 在 NEW mutation 中使用 `scenario`,并使用 `scenario_id` 标识 Scenario。-Rule 搜索结果包含 `scenarios`、每条 Rule 的 `scenario_id` 以及-`scenario_selection`。+Rule 是 Agent 在特定条件下必须遵守的持久强约束,例如行动义务、禁止项和边界。OpenViking 将规则材料批量编译为可独立理解的规则,再根据当前任务召回适用规则,供 Agent 在行动或回答前核验。-每个 Scenario 都是用户 Rule 库下的一个直接子目录:+当前 Beta 面向主动导入和按需召回。普通会话提交不会自动触发规则编译,也没有在每条用户消息或新会话开始时强制注入规则的内置流程。++## 与其他上下文类型的区别++| 类型 | 回答的问题 | 示例 |+| --- | --- | --- |+| Resource(资源) | 有哪些原始资料可查阅? | 协议原文、代码仓库、技术规范 |+| Memory(记忆) | 已知哪些事实、偏好和经验? | 用户偏好简洁回答、项目采用某个框架 |+| Skill(技能) | 如何完成这类任务? | 仓库审查步骤、报告生成方法 |+| Rule(规则) | 在什么条件下必须做什么或禁止做什么? | 声明开源的仓库必须提供可定位的许可证文本 |++Rule 的优先级高于普通 Memory。它是一种独立的上下文类型;虽然存储在用户的 `memories/rules/` 下,但使用专门的编译和搜索接口。把协议或规范作为 Resource 导入,只保存了资料,还需显式编译其中的强约束。++偏好、建议、事实、示例和单次任务不应提升为 Rule。编译也不能把原文的“建议”改成“必须”,或弱化“必须”“禁止”。++## 适用场景++| 场景 | 规则来源 | Agent 如何使用 |+| --- | --- | --- |+| 法律协议核查 | 用户提供的协议义务、禁止事项与例外 | 根据具体审查对象和已知事实召回约束,再核对文本或计划动作 |+| 代码规范检查 | 团队开发规范、代码审查要求 | 根据当前仓库、修改内容和执行阶段召回规则,检查拟提交的变更 |+| 开源许可证核查 | 用户提供的许可证要求 | 读取仓库声明和许可证文件,核对触发条件并记录证据 |++例如,输入“仓库声明自己是开源项目时,必须提供明确、完整且可定位的项目许可证文本”,可以形成:++| 字段 | 示例 |+| --- | --- |+| `content` | 仓库声明自己是开源项目时,必须提供明确、完整且可定位的项目许可证文本。 |+| `applies_when` | 仓库声明自己是开源项目。 |+| `exception` | 空字符串:原文没有明确例外。 |+| Scenario | 项目许可证核查 |++主题相似不等于条件成立。Agent 必须依据可读取的材料核验条件;规则已经满足时,它仍然适用。++## 规则如何组织++一条 Rule 保存一个可独立更新或撤销的完整约束,包含 `content`、适用条件 `applies_when`、例外 `exception`、来源与原文证据,以及稳定标识 `atomic_id`、版本 `revision` 和状态 `status`。空 `applies_when` 表示除例外外均适用。++Scenario 描述规则可能适用的实际情况,用于分组和召回,例如“项目许可证核查”。它不是来源文档的标题:同一份文档可以产生多个 Scenario,多份资料也可以复用同一 Scenario。```textviking://user/<user_id>/memories/rules/-└── file-operations/- ├── abstract.md- ├── confirm-delete.md- └── preserve-backups.md+└── repository-license/+ ├── abstract.md # Scenario 描述+ └── project-license.md # 完整 Rule 记录```-`abstract.md` 保存 Scenario 元数据和简短描述:+## 编译流程-```markdown-----schema: openviking.rule.scenario/v1-scenario_id: file-operations-name: File operations-description: Constraints for creating, modifying, and deleting files.-updated_at: "2026-10-21T00:00:00+00:00"----+```text+规则文本、文件、目录或 URL+ → 读取已有资源,或解析并导入新来源+ → 召回已有 active / paused 规则+ → Compiler 提炼约束并生成变更计划+ → 校验结构、目标、原文证据和旧要求保留情况+ → 写入 Rule / Scenario,异步刷新索引+```++Compiler 保留约束强度、条件、例外、阈值和单位,并拆分可独立维护的规则。同一规则的演进更新原记录,完整替代会创建新标识并归档旧记录;已有规则完整覆盖输入时无需重复写入。关键歧义或被拒绝的输入会记录原因,不写入 Rule。++编译接口先返回后台任务。任务完成后检查实际变更;规则写入对应的索引任务可能仍在处理,使用前也要确认该任务完成。具体步骤见[规则校验(Beta)](../workflows/02-rule-validation.md)。-# File operations+## 搜索与执行流程-Constraints for creating, modifying, and deleting files.+```text+Agent 提交任务目标、对象、计划动作和已知事实+ → 语义召回可能相关的 Scenario+ → Jev 过滤高置信度无关的 Scenario+ → 读取其中的 active 规则,判断适用条件与例外+ → 返回结构化规则和完整的约束文本+ → Agent 逐条核验并约束行动或回答```-其他 Markdown 文件保存完整的 Rule 记录,包括 `atomic_id`、`scenario_id`、-revision、status、content、适用条件、例外和证据。`abstract` 是保留文件名。-存储系统生成的 `.abstract.md` 和 `.overview.md` 是另外两种内部摘要。--Scenario 检索仅搜索 `*/abstract.md`,因此 Rule 文件不会占用 Scenario 候选数量。-选中 Scenario 后,服务会读取其直属 Rule 文件。成员关系由目录决定,无需维护-`rule_uris` 列表。暂停和归档的 Rule 会保留在所属 Scenario 中,直到生命周期清理-移除超过保留期的归档 Rule。Rule 搜索使用 active Rule;编译考虑 active 和 paused-Rule。archived Rule 视为逻辑删除,不会出现在这两条路径中。--Rule 状态包括 `active`、`paused` 和 `archived`。`PAUSE` 暂停 active Rule,-但不安排清理;`ARCHIVE` 标记 Rule,使其在默认 30 天保留期后被清理,并记录-`archived_at`,重复归档不会重置该时间。`RESTORE` 重新激活 paused Rule;archived-Rule 无法通过 Rule 编译恢复。更新 Rule 会保留其当前生命周期状态。被替换的-Rule 会转为 archived。生命周期操作必须由用户明确要求。其中 `ARCHIVE` 必须由-用户指令明确表达删除、丢弃或移入回收站;暂停、禁用、停用、停止生效或暂不-使用 Rule 的请求统一使用 `PAUSE`。--Jev 判断 Scenario 是否无关以及 Rule 是否适用。当 Jev 未配置、不可用、调用失败-或返回无效结果时,受影响候选会直接通过,不再进行 VLM 判断。Rule 判断失败时,-所有候选 Rule 以 `score=1.0`、`judge=pass` 和 warning 放行;该分数是放行值,-不是估算概率。Agent 仍需在执行 Rule 前检查适用条件和例外。Rule 编译继续使用-Compiler VLM;VLM `rule_matcher` 配置已移除。+搜索默认返回适用分数达到 `0.65` 的规则,公开接口不设置固定 Top-K。非空适用条件下,例外分数达到阈值且严格高于适用条件分数时才否决;空适用条件下,例外达到阈值即否决。++Jev 未配置、不可用或返回无效结果时,受影响候选会放行。Rule 判断失败时返回 `judge="pass"`、`probability=1.0` 和 warning;这个分数表示放行,不是估算概率。Agent 仍需核验条件和例外。++`rendered` 提供应用步骤和完整规则块,可交给 Agent。搜索判断的是“规则是否适用”;是否满足、违反或证据不足,由 Agent 对照任务事实判断。空搜索结果不能证明规则库没有相关约束;`delivery.complete` 也只表示命中规则完整交付,不保证全库召回。++## 生命周期++| 状态 | 编译候选 | 搜索候选 | 含义 |+| --- | --- | --- | --- |+| `active` | 是 | 是 | 启用 |+| `paused` | 是 | 否 | 暂停,保留规则,不安排到期清理 |+| `archived` | 否 | 否 | 逻辑删除,保留期结束后可被清理 |++用户明确要求暂停或禁用时使用 `PAUSE`;恢复暂停规则使用 `RESTORE`。删除、丢弃或移入回收站才使用 `ARCHIVE`。`UPDATE` 保留原有状态。当前编译接口不能恢复 archived 规则。++归档记录保存 `archived_at`,重复归档不重置时间。默认启用定期清理,保留期为 30 天;实际物理清理发生在保留期结束后的扫描中,配置见[服务端 Rules 配置](../configuration/01-server.md#rules)。++## 相关文档++- [规则校验(Beta)](../workflows/02-rule-validation.md):批量编译、召回与 Agent 核验+- [规则 API(Beta)](../api/26-rules.md):参数、响应和失败处理+- [VikingBot 安装与配置](../guides/17-vikingbot.md):使用规则搜索工具+- [上下文类型](./02-context-types.md):资源、记忆与技能diff --git a/docs/zh/configuration/01-server.md b/docs/zh/configuration/01-server.mdindex ac727ec8e..e064f4db1 100644--- a/docs/zh/configuration/01-server.md+++ b/docs/zh/configuration/01-server.md@@ -218,7 +218,7 @@ active。编译候选只包含 active 和 paused Rule;archived Rule 视为逻Rule 按 Scenario 直接存放在 `memories/rules/<scenario_id>/`:`abstract.md`保存场景元信息,`<atomic_id>.md` 保存规则。存储格式见-[Rule Scenario](../concepts/17-rule-scenarios.md)。+[规则(Beta)](../concepts/17-rule-scenarios.md)。`jev_rule_matcher` 未配置、不可用、调用失败或返回无效结果时,Scenario 和 Rule 判断直接放行,不调用 VLM。Scenario 诊断记录 `decision=pass`;Rule 返回 `judge=pass`diff --git a/docs/zh/reference/01-overview.md b/docs/zh/reference/01-overview.mdindex 682601d3b..07c4ce146 100644--- a/docs/zh/reference/01-overview.md+++ b/docs/zh/reference/01-overview.md@@ -9,6 +9,7 @@| MCP 工具、参数与上传协议 | [MCP 工具与协议](../guides/06-mcp-integration.md);安装客户端看[连接 MCP 客户端](../agent-integrations/06-mcp-clients.md) || 资源、文件和检索接口 | [资源](../api/02-resources.md)、[文件系统](../api/03-filesystem.md)、[内容](../api/12-content.md)、[检索](../api/06-retrieval.md) || 会话、记忆与技能接口 | [会话](../api/05-sessions.md)、[记忆](../api/16-memory.md)、[技能](../api/04-skills.md) |+| 规则编译与适用性召回(Beta) | [规则 API(Beta)](../api/26-rules.md) || 管理、权限与后台状态 | [Admin](../api/08-admin.md)、[ACL](../api/12-acl.md)、[后台任务](../api/17-tasks.md)、[Observer](../api/18-observer.md) || 数据一致性、隔离和处理完成的含义 | [系统架构](../concepts/01-architecture.md)、[事务与恢复](../concepts/09-transaction.md)、[多租户](../concepts/11-multi-tenant.md)、[任务状态](../concepts/16-queue-lifecycle.md) |diff --git a/docs/zh/workflows/01-overview.md b/docs/zh/workflows/01-overview.mdindex f2557f4a6..5e7b3b703 100644--- a/docs/zh/workflows/01-overview.md+++ b/docs/zh/workflows/01-overview.md@@ -7,6 +7,7 @@| 让应用检索文档或代码 | [导入资源](../api/02-resources.md) → [检索](../api/06-retrieval.md) → [读取内容](../api/12-content.md) | 用已知答案的问题查询,读取命中 URI,核对原文 || 跨会话复用记忆 | [会话与记忆模型](../concepts/08-session.md) → [会话 API](../api/05-sessions.md) → [记忆 API](../api/16-memory.md) | 提交会话并确认后台任务完成,再检查记忆内容和归属 || 让 Agent 复用技能 | [技能 API](../api/04-skills.md) → [隐私模型](../concepts/13-privacy.md) | 检查安装后的技能内容、可见范围和调用方式 |+| 规则校验(Beta) | [规则概念](../concepts/17-rule-scenarios.md) → [编译、召回与核验](./02-rule-validation.md) → [规则 API](../api/26-rules.md) | 检查编译与索引任务、原文证据,再由 Agent 逐条核验适用条件、例外及计划动作 || 从已有资料产出 Wiki、图谱或日报 | [上下文编译](../context-compilation/01-overview.md) → 选择产物教程 | 检查任务状态、产物目录,以及产物与输入来源的对应关系 || 同步或迁移已有上下文 | [项目资源同步](../guides/18-openviking-assets.md)、[OVPack](../guides/09-ovpack.md)或[版本恢复](../guides/15-snapshot.md) | 按对应指南核对同步状态、导入结果或恢复后的内容 |diff --git a/docs/zh/workflows/02-rule-validation.md b/docs/zh/workflows/02-rule-validation.mdnew file mode 100644index 000000000..aacac0792--- /dev/null+++ b/docs/zh/workflows/02-rule-validation.md@@ -0,0 +1,122 @@+# 规则校验(Beta)++把协议、代码规范等材料中的强约束批量编译为 Rule,再让 Agent 根据具体任务召回规则、核对证据并调整行动。本教程以用户提供的开源许可证要求为例。++OpenViking 负责规则编译和适用性召回。是否满足或违反规则由 Agent 判断,搜索接口本身不返回合规结论。概念和生命周期见[规则(Beta)](../concepts/17-rule-scenarios.md)。++## 前置条件++- 运行包含 Rule 功能的 OpenViking Server,配置可用的 Compiler 模型和 Embedding 模型。Compiler 默认复用服务端 VLM,也可以通过 `rules.compiler` 指定。+- 使用包含 `rule_compile()` 和 `rule_search()` 的 Python HTTP SDK,并配置当前用户的认证身份。编译和搜索应使用同一用户。+- 准备用户确认的强约束材料,保留原文的条件、例外和阈值。不要把普通建议或偏好当作规则。++模型配置见[服务端 Rules 配置](../configuration/01-server.md#rules),连接约定见[API 总览](../api/01-overview.md)。以下代码按顺序运行,URL 和 API Key 替换为自己的配置。++## 第一步:提交规则材料++```python+from openviking_sdk import SyncHTTPClient++client = SyncHTTPClient(url="http://localhost:1933", api_key="your-key")+task = client.rule_compile(+ instruction=(+ "仓库声明自己是开源项目时,"+ "必须提供明确、完整且可定位的项目许可证文本。"+ ),+)+print(task["task_id"])+```++批量导入文件或目录时,将上面的调用替换为:++```python+task = client.rule_compile(options={"sources": ["./compliance-rules/"]})+```++SDK 会上传本地来源。已导入的资源可以直接使用 `{"sources": ["viking://resources/compliance-rules"]}`,避免重复导入。HTTP 来源格式见[规则 API](../api/26-rules.md)。++## 第二步:等待完成并检查产物++```python+import time+++def wait_for_task(task_id, timeout=300):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ current = client.get_task(task_id)+ if current is None:+ raise RuntimeError(f"Task not found: {task_id}")+ if current["status"] == "completed":+ return current+ if current["status"] in {"failed", "cancelled"}:+ raise RuntimeError(current)+ time.sleep(1)+ raise TimeoutError(f"Task still running: {task_id}")+++completed = wait_for_task(task["task_id"])+result = completed["result"]+print(result["operations"])+print(result["written_uris"])++# 编译完成与写入后的索引处理可能属于不同任务。+write_task_id = result.get("write_result", {}).get("task_id")+if write_task_id:+ wait_for_task(write_task_id)++for uri in result["written_uris"]:+ print(client.read(uri))+```++检查生成规则是否保留了主体、义务、条件和例外,以及原文证据。`UNCERTAIN` 和 `REJECT` 只记录原因;`NOOP` 表示已有规则覆盖输入。超时只停止本地等待,不取消服务端任务。++## 第三步:按具体任务搜索++先读取审查对象,再把目标、对象、计划动作和已有证据组织为 `task_context`。以下内容是示例事实,使用时替换为实际读取的内容:++```python+matches = client.rule_search(+ task_context=(+ "只读检查一个仓库的开源许可证。"+ "已读取 README.md,其中声明项目开源;"+ "根目录存在 LICENSE,尚未检查其正文。"+ "接下来计划读取许可证文本并核对完整性。"+ ),+)+print(matches["rendered"])+print(matches.get("warning"))+```++把完整的 `rendered` 交给 Agent;直接对接 API 的应用还应检查 `judge`、`warning` 和 `scenario_selection`。Jev 不可用时可能放行候选,不能把放行分数当作已确认适用的概率。++## 第四步:Agent 逐条核验++Agent 对每条返回规则执行以下步骤:++1. 用当前任务证据检查 `applies_when`,不推断缺失的事实;空条件表示除例外外均适用。+2. 检查明确例外,再对照 `content` 核验拟执行动作或回答。+3. 对于审查任务,记录规则标识、来源与对象证据,区分已满足、违反和证据不足。规则已满足也应纳入适用规则。+4. 新事实实质改变适用场景时,再次搜索。++本例中,README 的声明触发规则;LICENSE 文件存在还不足以确认文本完整,应继续读取。空结果不代表没有相关规则,也不构成“校验通过”。++## 接入已有 Agent++[VikingBot](../guides/17-vikingbot.md) 已提供 `openviking_rule_search` 工具(Beta),连接 OpenViking 后可按需调用。++其他 Agent 可以使用 Python HTTP SDK 或 HTTP API,并安装配套 Skill。将完整目录放入 Agent 配置的 Skills 目录,再让 Agent 加载:++| 任务 | 配套 Skill |+| --- | --- |+| 准备来源、编译并检查结果 | [add-rules](https://github.com/volcengine/OpenViking/tree/main/examples/skills/add-rules) |+| 组织任务上下文、召回并核验规则 | [openviking-rule-search](https://github.com/volcengine/OpenViking/tree/main/examples/skills/openviking-rule-search) |++Skill 提供操作与行为要求;Agent 仍需具备可调用的接口。当前 Beta 通过用户或 Agent 主动调用使用。++## 相关文档++- [规则(Beta)](../concepts/17-rule-scenarios.md)+- [规则 API(Beta)](../api/26-rules.md)+- [后台任务](../api/17-tasks.md)+- [应用开发路径](./01-overview.md)