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
feat(gateway): let operators add to or remove from the packaged client rules (#6333)
t0saki8640600f4a86
diff --git a/docs/en/gateway/10-overview-and-requests.md b/docs/en/gateway/10-overview-and-requests.mdindex 7a46ca74e..417a6eb5f 100644--- a/docs/en/gateway/10-overview-and-requests.md+++ b/docs/en/gateway/10-overview-and-requests.md@@ -100,7 +100,7 @@ Every record has one type. The type decides whether the request searches memory| --- | --- | --- || New message | A request whose last message is a new user message | Searched once, earlier memory replayed; the turn is saved || Tool step | The same turn continuing, for example with tool results | Earlier memory replayed; saved with its turn |-| Housekeeping | Title, summary, compaction, suggestion and permission-check requests; once a conversation has sent client tools, a separate request in it with neither tools nor earlier replies, such as Claude Code summarizing a fetched page | Earlier memory replayed; never saved |+| Housekeeping | Title, summary, compaction, suggestion and permission-check requests; once a conversation has sent client tools, a separate request in it with neither tools nor earlier replies, such as Claude Code summarizing a fetched page. Operators can add a client's own requests in [Client rules](13-configuration.md#client-rules) | Earlier memory replayed; never saved || Sub-agent | Requests from a client's sub-agents | Earlier memory replayed; never saved || Token count | Token-counting requests (`/gateway/v1/messages/count_tokens`) | Earlier memory replayed, so the count matches what is actually sent || Forwarded | Requests passed through unchanged, without memory: other endpoints, Responses requests that rely on provider-side state, compressed or unreadable bodies | None |diff --git a/docs/en/gateway/13-configuration.md b/docs/en/gateway/13-configuration.mdindex f8ac395ce..ca2630e2c 100644--- a/docs/en/gateway/13-configuration.md+++ b/docs/en/gateway/13-configuration.md@@ -40,6 +40,7 @@ An embedded and a standalone gateway share most fields; they differ in which fil| `max_body_bytes` | Both | `33554432` (32 MiB) | 1,024 or more | Size limit for requests and uploads, in bytes || `upstream_timeout_seconds` | Both | `600` | More than 0 | Timeout for provider requests || `health_interval_seconds` | Both | `60` | 1 or more | Seconds between OpenViking status checks |+| `client_rules` | Both | `{}` (packaged rules only) | See [Client rules](#client-rules) | Text added to or removed from what the gateway recognizes as housekeeping requests and client-inserted messages |## Environment variables {#environment-variables}@@ -54,6 +55,7 @@ OPENVIKING_GATEWAY_MANAGEMENT_KEY='<management-key>'- Values that start with `tcp://` or `udp://` are ignored, so the variables Kubernetes sets for a Service named `openviking-gateway` (such as `OPENVIKING_GATEWAY_PORT=tcp://…`) do not override the file.- A value in the file can also be a `"$VAR"` reference, resolved from the environment.- The `encryption` block can only be set in the file.+- `client_rules` takes the whole section as JSON: `OPENVIKING_GATEWAY_CLIENT_RULES='{"auxiliary_patterns":{"add":["You are the Acme title writer"]}}'`.- Containers usually need no file: set the fields they need as variables.## Validation {#validation}@@ -63,9 +65,42 @@ OPENVIKING_GATEWAY_MANAGEMENT_KEY='<management-key>'| `openviking_url` and `public_url` | HTTP(S), with no credentials, query or fragment || Upstream `base_url` | Its own rules; see [Endpoint](07-upstreams.md#endpoint) || `management_key` | At least 32 characters once `$VAR` references are resolved; an unresolved `$VAR` fails |+| `client_rules` | Every added pattern must be a valid Python regular expression; added tag names start with an ASCII letter and use only ASCII letters, digits, `_`, `.`, `:` and `-` || Unknown fields | Fail validation || Removed fields | Ignored, with a startup warning: `encryption_key_env`, and in `ov.conf` also the v0.5 fields listed in [Migration](../guides/22-gateway-operations.md#migration) |+## Client rules {#client-rules}++The gateway tells [housekeeping requests](10-overview-and-requests.md#request-types) and the messages clients insert on the user's behalf apart from real user messages by fixed text, listed in the packaged [`client-rules.json`](https://github.com/volcengine/OpenViking/blob/main/openviking_gateway/client-rules.json). When a client's title or summary requests show up as **New message** in the request log, or a real message is treated as housekeeping, add or remove entries in `client_rules`:++```json+{+ "gateway": {+ "enabled": true,+ "client_rules": {+ "auxiliary_patterns": {+ "add": ["You are the Acme title writer"],+ "remove": ["Create a short.{0,40}title"]+ },+ "noise_tags": { "add": ["acme-context"] }+ }+ }+}+```++In `gateway.conf`, `client_rules` sits at the root, without the `gateway` wrapper.++| List | Entries | What a match does |+| --- | --- | --- |+| `auxiliary_patterns` | Regular expressions, ignoring case | Each is matched separately against the Messages `system` field, the Responses `instructions` and the latest user message. A match makes the request **Housekeeping**. System and developer messages inside Chat Completions `messages` or Responses `input` are not checked, so for those clients match text in the user message. |+| `noise_patterns` | Regular expressions, case-sensitive | Ignored when the gateway reads the conversation: left out of request classification, the memory search and saved messages and tool results, but still sent to the model unchanged. A user message left empty is not a new user message, so the request continues the turn. |+| `noise_tags` | Tag names | `<tag …>…</tag>` blocks, in any letter case, handled the same way as `noise_patterns`. |+| `plugin_tags` | Tag names | `<tag` in the system prompt or a client message marks an OpenViking memory plugin in the client. For the rest of that conversation the gateway only forwards requests: no memory, no OpenViking tools, nothing saved (see [When both are in use](../guides/15-gateway.md#when-both-are-in-use)). Add only a tag the plugin itself writes. |++- **`add` appends to the packaged list and `remove` takes entries out of it.** Write a removal exactly as it appears in `client-rules.json`. A removal that matches nothing, for example after an upgrade changed the entry, is ignored with a startup warning. The packaged list cannot be replaced as a whole, so entries added in later releases keep working.+- **Match text only the client writes.** Use a full sentence from the client's own prompt rather than a short phrase. A user message that matches makes its whole turn housekeeping, so none of it is searched for or saved; a pattern that also matches the main conversation's system prompt does this to every request. Anchor a noise pattern to the whole message (`"\\A…\\Z"` in JSON) so it never cuts text out of a real message.+- **Changes take effect at startup.** Restart the server or the standalone gateway after editing.+## Context profile settings {#context-profile-settings}In Studio: **Profiles** → a profile. The tables follow the editor's sections, with the Studio label first and then the name in the management API, which calls context profiles `policies`. **Name** (`name`, default `Default`) is the profile's display name; what each section does is explained in [Context profiles](08-context-profiles.md#context-profiles).diff --git a/docs/zh/gateway/10-overview-and-requests.md b/docs/zh/gateway/10-overview-and-requests.mdindex 3b8e9dbd4..a24476a9c 100644--- a/docs/zh/gateway/10-overview-and-requests.md+++ b/docs/zh/gateway/10-overview-and-requests.md@@ -100,7 +100,7 @@ description: 读懂 Studio 中 OpenViking 网关的“概览”和“请求日| --- | --- | --- || 新消息 | 最后一条是新用户消息的请求 | 检索一次,并放回之前的记忆;这一轮会被保存 || 工具步骤 | 同一轮的延续,例如带着工具结果继续 | 放回之前的记忆;随所在轮次一起保存 |-| 辅助请求 | 生成标题、摘要、压缩、建议和权限检查的请求;对话带过客户端工具后,同一对话里不带工具、也不带之前回复的单独请求,例如 Claude Code 汇总抓取的网页 | 放回之前的记忆;从不保存 |+| 辅助请求 | 生成标题、摘要、压缩、建议和权限检查的请求;对话带过客户端工具后,同一对话里不带工具、也不带之前回复的单独请求,例如 Claude Code 汇总抓取的网页。运维可以在[客户端规则](13-configuration.md#client-rules)里补充某个客户端自己的请求 | 放回之前的记忆;从不保存 || 子 Agent | 客户端的子 Agent 发出的请求 | 放回之前的记忆;从不保存 || Token 计数 | token 计数请求(`/gateway/v1/messages/count_tokens`) | 放回之前的记忆,计数才和实际发送的内容一致 || 直接转发 | 原样转发、不带记忆的请求:其他接口、依赖服务商端状态的 Responses 请求、压缩过或无法解析的请求体 | 无 |diff --git a/docs/zh/gateway/13-configuration.md b/docs/zh/gateway/13-configuration.mdindex c2516feaa..c18df95fc 100644--- a/docs/zh/gateway/13-configuration.md+++ b/docs/zh/gateway/13-configuration.md@@ -40,6 +40,7 @@ description: 查询 OpenViking 网关的配置字段、环境变量、上下文| `max_body_bytes` | 两者 | `33554432`(32 MiB) | 1,024 及以上 | 请求和上传的大小上限,单位为字节 || `upstream_timeout_seconds` | 两者 | `600` | 大于 0 | 服务商请求超时 || `health_interval_seconds` | 两者 | `60` | 1 及以上 | 检查 OpenViking 状态的间隔秒数 |+| `client_rules` | 两者 | `{}`(只用内置规则) | 见[客户端规则](#client-rules) | 在网关内置的辅助请求和客户端插入消息识别规则上增删条目 |## 环境变量 {#environment-variables}@@ -54,6 +55,7 @@ OPENVIKING_GATEWAY_MANAGEMENT_KEY='<management-key>'- 以 `tcp://` 或 `udp://` 开头的值会被忽略。这样,Kubernetes 为名为 `openviking-gateway` 的 Service 自动注入的变量(例如 `OPENVIKING_GATEWAY_PORT=tcp://…`)不会覆盖文件。- 文件中的值也可以写成 `"$VAR"`,从环境变量中取值。- `encryption` 块只能写在文件里。+- `client_rules` 用 JSON 传整段配置:`OPENVIKING_GATEWAY_CLIENT_RULES='{"auxiliary_patterns":{"add":["You are the Acme title writer"]}}'`。- 容器通常不需要配置文件,用环境变量设置需要的字段即可。## 校验 {#validation}@@ -63,9 +65,42 @@ OPENVIKING_GATEWAY_MANAGEMENT_KEY='<management-key>'| `openviking_url` 和 `public_url` | 必须是 HTTP(S),不能含凭证、查询参数或 fragment || 上游的 `base_url` | 规则不同,见[接口](07-upstreams.md#endpoint) || `management_key` | 解析 `$VAR` 引用后至少 32 个字符;`$VAR` 没能解析时校验失败 |+| `client_rules` | 新增的模式必须是合法的 Python 正则表达式;新增的标签名以英文字母开头,只能包含英文字母、数字、`_`、`.`、`:` 和 `-` || 未知字段 | 校验失败 || 已删除的字段 | 忽略,启动时打印警告:`encryption_key_env`,以及 `ov.conf` 中[迁移](../guides/22-gateway-operations.md#migration)列出的 v0.5 字段 |+## 客户端规则 {#client-rules}++网关靠固定文本区分[辅助请求](10-overview-and-requests.md#request-types)、客户端代用户插入的消息和真正的用户消息,这些文本列在内置的 [`client-rules.json`](https://github.com/volcengine/OpenViking/blob/main/openviking_gateway/client-rules.json) 里。如果某个客户端的标题、摘要请求在请求日志里显示为**新消息**,或者真实消息被当成了辅助请求,可以在 `client_rules` 里增删条目:++```json+{+ "gateway": {+ "enabled": true,+ "client_rules": {+ "auxiliary_patterns": {+ "add": ["You are the Acme title writer"],+ "remove": ["Create a short.{0,40}title"]+ },+ "noise_tags": { "add": ["acme-context"] }+ }+ }+}+```++在 `gateway.conf` 里,`client_rules` 直接写在根层级,不需要外面的 `gateway`。++| 列表 | 条目 | 命中后的效果 |+| --- | --- | --- |+| `auxiliary_patterns` | 正则表达式,不区分大小写 | 分别与 Messages 的 `system` 字段、Responses 的 `instructions` 和最后一条用户消息匹配,命中的请求算作**辅助请求**。Chat Completions `messages` 和 Responses `input` 里的 system、developer 消息不参与匹配,这类客户端要匹配用户消息里的文本。 |+| `noise_patterns` | 正则表达式,区分大小写 | 网关读取对话时忽略这些文本:不参与请求分类和记忆检索,也不写入保存的消息和工具结果,但仍原样发给模型。删完为空的用户消息不算新用户消息,请求按同一轮的延续处理。 |+| `noise_tags` | 标签名 | `<tag …>…</tag>` 块(不区分大小写),处理方式同 `noise_patterns`。 |+| `plugin_tags` | 标签名 | 系统提示词或客户端消息中出现 `<tag`,表示客户端里运行着 OpenViking 记忆插件。该对话此后网关只做转发:不加记忆、不提供 OpenViking 工具、不保存(见[两者同时使用时](../guides/15-gateway.md#when-both-are-in-use))。只添加插件自己写入的标签。 |++- **`add` 追加到内置列表,`remove` 从内置列表中去掉条目。** `remove` 的条目要和 `client-rules.json` 里的写法完全一致。没有匹配到任何条目的 `remove`(例如升级后内置条目改了写法)会被忽略,启动时打印警告。内置列表不能整体替换,这样后续版本新增的条目仍然生效。+- **只匹配客户端自己写的文本。** 用客户端自己提示词里的整句,不要用短语。用户消息一旦命中,这一整轮都算辅助请求,不检索也不保存;如果模式还能命中主对话的系统提示词,对话里的每个请求都会这样。噪声模式要锚定整条消息(JSON 里写作 `"\\A…\\Z"`),避免从真实消息里删掉文字。+- **修改在启动时生效。** 改完后重启 Server 或独立网关。+## 上下文配置的设置 {#context-profile-settings}在 Studio 中:**上下文配置** → 打开一份配置。下面几张表按编辑器的分区排列,先写 Studio 中的名称,再写管理 API 中的名称(管理 API 把上下文配置称为 `policies`)。**名称**(`name`,默认 `Default`)是配置的显示名称;各分区的作用见[上下文配置](08-context-profiles.md#context-profiles)。diff --git a/openviking_gateway/app.py b/openviking_gateway/app.pyindex 2602c0b2a..a87479640 100644--- a/openviking_gateway/app.py+++ b/openviking_gateway/app.py@@ -25,6 +25,7 @@ from .config import PUBLIC_OPENVIKING_URLS, GatewayConfig, normalize_urlfrom .kernel import MemoryKernelfrom .management import import_vlm_objects, register_management, request_credentialfrom .models import Policy+from .protocols import configure_rulesfrom .proxy import ProxyRequest, filtered_headersfrom .storage import ManagementStore, SQLiteKernelStore, delete_account_data, delete_user_data@@ -45,6 +46,12 @@ def create_app(config: GatewayConfig, *, openviking_url: str, vlm_source=None, e``encryptor`` is an OpenViking ``FileEncryptor``; without one, values are stored as plaintext."""+ if unknown := configure_rules(config.client_rules):+ # An upgrade may rename a packaged rule; a stale removal must not stop the host.+ logger.warning(+ "gateway.client_rules removes entries the packaged rules do not have: %s",+ "; ".join(unknown),+ )store = SQLiteKernelStore(config.directory / "kernel.sqlite3", encryptor)management = ManagementStore(config.directory / "management.sqlite3", encryptor)diff --git a/openviking_gateway/config.py b/openviking_gateway/config.pyindex ac23d425a..caeb6eabf 100644--- a/openviking_gateway/config.py+++ b/openviking_gateway/config.py@@ -2,8 +2,10 @@# SPDX-License-Identifier: AGPL-3.0"""Configuration for embedded and standalone gateway hosts."""+import jsonimport loggingimport os+import refrom pathlib import Pathfrom typing import ClassVar, Literalfrom urllib.parse import urlsplit, urlunsplit@@ -34,6 +36,41 @@ def normalize_url(value: str) -> str:return urlunsplit((parsed.scheme, parsed.netloc.lower(), parsed.path.rstrip("/"), "", ""))+class RuleChanges(BaseModel):+ model_config = ConfigDict(extra="forbid")+ add: list[str] = Field(default_factory=list)+ # Entries of the packaged list, written exactly as there.+ remove: list[str] = Field(default_factory=list)+++class ClientRules(BaseModel):+ """Changes to the packaged ``client-rules.json``, applied when the gateway starts."""++ model_config = ConfigDict(extra="forbid")+ plugin_tags: RuleChanges = Field(default_factory=RuleChanges)+ noise_tags: RuleChanges = Field(default_factory=RuleChanges)+ noise_patterns: RuleChanges = Field(default_factory=RuleChanges)+ auxiliary_patterns: RuleChanges = Field(default_factory=RuleChanges)++ @field_validator("plugin_tags", "noise_tags")+ @classmethod+ def validate_tags(cls, value: RuleChanges) -> RuleChanges:+ # Element names, as clients write them in <name ...>.+ if bad := [tag for tag in value.add if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_.:-]*", tag)]:+ raise ValueError(f"tag names must be ASCII letters, digits, _ . : or -: {bad}")+ return value++ @field_validator("noise_patterns", "auxiliary_patterns")+ @classmethod+ def validate_patterns(cls, value: RuleChanges) -> RuleChanges:+ for pattern in value.add:+ try:+ re.compile(pattern)+ except re.error as error:+ raise ValueError(f"invalid regex {pattern!r}: {error}") from None+ return value++class GatewayConfig(BaseModel):model_config = ConfigDict(extra="forbid")# Settings an upgraded configuration may still carry; rejecting them would stop the host.@@ -50,6 +87,7 @@ class GatewayConfig(BaseModel):max_body_bytes: int = Field(default=32 * 1024 * 1024, ge=1024)upstream_timeout_seconds: float = Field(default=600, gt=0)health_interval_seconds: float = Field(default=60, ge=1)+ client_rules: ClientRules = Field(default_factory=ClientRules)@model_validator(mode="before")@classmethod@@ -71,6 +109,12 @@ class GatewayConfig(BaseModel):value[field] = overridereturn value+ @field_validator("client_rules", mode="before")+ @classmethod+ def parse_client_rules(cls, value):+ # OPENVIKING_GATEWAY_CLIENT_RULES carries the section as JSON.+ return json.loads(value) if isinstance(value, str) else value+@field_validator("public_url")@classmethoddef validate_url(cls, value: str) -> str:diff --git a/openviking_gateway/protocols.py b/openviking_gateway/protocols.pyindex 348e412de..f652427d2 100644--- a/openviking_gateway/protocols.py+++ b/openviking_gateway/protocols.py@@ -16,32 +16,63 @@ from typing import Anyimport orjson+from .config import ClientRules+NORMALIZATION_VERSION = "v1"-_RULES = json.loads(files("openviking_gateway").joinpath("client-rules.json").read_text())-PLUGIN_TAGS = tuple(_RULES["plugin_tags"])-NOISE_TAGS = tuple(_RULES["noise_tags"])-AUXILIARY_PATTERNS = tuple(_RULES["auxiliary_patterns"])-# Whole messages clients write on the user's behalf: pi-ai's label for a tool result's-# images, which it sends as a user message after the tool result, and DSH's runtime and-# time snapshots, which DSH can append mid-turn. Each is a message of its own, so a-# snapshot pattern takes the rest of the text. Anchored, so other text fails at once.-NOISE_PATTERNS = tuple(re.compile(p) for p in _RULES["noise_patterns"])+PACKAGED_RULES = json.loads(files("openviking_gateway").joinpath("client-rules.json").read_text())# re.I tries a pattern at every offset; plain ASCII patterns (no escapes, sets or flags),# lowercased, get re's literal search instead, the same match unless the text has one of# the only letters where lower() and re.I differ against ASCII (checked in the tests).REI_CASE_EXCEPTIONS = "İıſ"-LOWERED_AUXILIARY = (- tuple(re.compile(p.lower()) for p in AUXILIARY_PATTERNS)- if all(p.isascii() and not re.search(r"[\\\[]|\(\?", p) for p in AUXILIARY_PATTERNS)- else ()-)+++def lowered(pattern: str) -> re.Pattern | None:+ plain = pattern.isascii() and not re.search(r"[\\\[]|\(\?", pattern)+ return re.compile(pattern.lower()) if plain else None+++def configure_rules(changes: ClientRules | None = None) -> list[str]:+ """Apply ``GatewayConfig.client_rules`` to the packaged rules, for the whole process.++ Returns the removals that name no packaged entry. Each call starts from the packaged+ rules, so calling it again with other changes replaces the earlier ones.+ """+ global PLUGIN_TAGS, NOISE_TAGS, NOISE_BLOCKS, AUXILIARY_PATTERNS, NOISE_PATTERNS, AUXILIARY+ changes = changes or ClientRules()+ rules, unknown = {}, []+ for name, packaged in PACKAGED_RULES.items():+ change = getattr(changes, name)+ removed = set(change.remove)+ unknown += [f"{name}: {entry}" for entry in sorted(removed.difference(packaged))]+ kept = [entry for entry in packaged if entry not in removed]+ rules[name] = tuple(dict.fromkeys([*kept, *change.add]))+ PLUGIN_TAGS = rules["plugin_tags"]+ NOISE_TAGS = rules["noise_tags"]+ NOISE_BLOCKS = tuple(+ re.compile(rf"<{re.escape(tag)}(?=[\s>])[^>]*>[\s\S]*?</{re.escape(tag)}>", re.I)+ for tag in NOISE_TAGS+ )+ AUXILIARY_PATTERNS = rules["auxiliary_patterns"]+ # Whole messages clients write on the user's behalf: pi-ai's label for a tool result's+ # images, which it sends as a user message after the tool result, and DSH's runtime and+ # time snapshots, which DSH can append mid-turn. Each is a message of its own, so a+ # snapshot pattern takes the rest of the text. Anchored, so other text fails at once.+ NOISE_PATTERNS = tuple(re.compile(p) for p in rules["noise_patterns"])+ # Each pattern keeps its lowercase form when it has one, so one configured regex does+ # not move the others off the fast path.+ AUXILIARY = tuple((lowered(p), re.compile(p, re.I)) for p in AUXILIARY_PATTERNS)+ return unknown+++configure_rules()+# Vendors whose models expect their reasoning back in later turns.REASONING_VENDORS = {"deepseek", "ark", "byteplus"}def clean_text(text: str) -> str:- for tag in NOISE_TAGS:- text = re.sub(rf"<{tag}\b[^>]*>[\s\S]*?</{tag}>", " ", text, flags=re.I)+ for block in NOISE_BLOCKS:+ text = block.sub(" ", text)text = re.sub(r"^\s*\[Subagent Context\][^\n]*", "", text, flags=re.M)for pattern in NOISE_PATTERNS:text = pattern.sub("", text)@@ -323,10 +354,11 @@ def is_user(message):def auxiliary(text: str) -> bool:"""Whether ``text`` matches an auxiliary pattern, ignoring case."""- if LOWERED_AUXILIARY and not any(c in text for c in REI_CASE_EXCEPTIONS):- text = text.lower()- return any(pattern.search(text) for pattern in LOWERED_AUXILIARY)- return any(re.search(pattern, text, re.I) for pattern in AUXILIARY_PATTERNS)+ lower = None if any(c in text for c in REI_CASE_EXCEPTIONS) else text.lower()+ return any(+ fast.search(lower) if fast and lower is not None else pattern.search(text)+ for fast, pattern in AUXILIARY+ )def classify(body: dict, headers: dict, messages: list[dict]) -> tuple[str, int]:@@ -353,10 +385,11 @@ def classify(body: dict, headers: dict, messages: list[dict]) -> tuple[str, int])if re.search(r"compact|summar|title|classif|heartbeat|suggest|permission", hints, re.I):return "auxiliary", anchor- probe = str(body.get("system", "")) + str(body.get("instructions", ""))+ # Each part on its own and as plain text, so a pattern's anchors and line breaks hold.+ parts = [text_content({"content": body.get(key, "")}) for key in ("system", "instructions")]if anchor >= 0:- probe += text_content(messages[anchor])- if auxiliary(probe):+ parts.append(text_content(messages[anchor]))+ if any(auxiliary(part) for part in parts if part):return "auxiliary", anchorif anchor < 0:return "continuation", anchordiff --git a/tests/gateway/test_gateway_config.py b/tests/gateway/test_gateway_config.pyindex ffe43afb9..31f055379 100644--- a/tests/gateway/test_gateway_config.py+++ b/tests/gateway/test_gateway_config.py@@ -7,7 +7,8 @@ import pytestfrom pydantic import ValidationErrorfrom openviking.crypto import FileEncryptor-from openviking_gateway import cli+from openviking_gateway import cli, protocols+from openviking_gateway.app import create_appfrom openviking_gateway.cli import load_configfrom openviking_gateway.client import VikingErrorfrom openviking_gateway.config import (@@ -106,6 +107,34 @@ def test_embedded_environment_overrides_ov_conf(monkeypatch):assert EmbeddedGatewayConfig().management_key == "e" * 32+def test_client_rules_validation_and_environment(monkeypatch):+ with pytest.raises(ValidationError, match="invalid regex"):+ GatewayConfig(client_rules={"auxiliary_patterns": {"add": ["Summarize (this"]}})+ with pytest.raises(ValidationError, match="tag names"):+ GatewayConfig(client_rules={"noise_tags": {"add": ["a>b"]}})+ with pytest.raises(ValidationError):+ GatewayConfig(client_rules={"auxiliary_patterns": ["replaces the list"]})+ rules = {"auxiliary_patterns": {"add": ["You are the Acme title writer"]}}+ monkeypatch.setenv("OPENVIKING_GATEWAY_CLIENT_RULES", json.dumps(rules))+ config = EmbeddedGatewayConfig.model_validate({"enabled": True})+ assert config.client_rules.auxiliary_patterns.add == ["You are the Acme title writer"]+++def test_app_applies_client_rules_and_warns_about_stale_removals(tmp_path, caplog):+ config = GatewayConfig(+ storage_path=str(tmp_path),+ client_rules={+ "auxiliary_patterns": {"add": ["Acme title writer"], "remove": ["Old packaged rule"]}+ },+ )+ try:+ create_app(config, openviking_url="http://ov.test")+ assert "Acme title writer" in protocols.AUXILIARY_PATTERNS+ assert "auxiliary_patterns: Old packaged rule" in caplog.text+ finally:+ protocols.configure_rules()++def test_standalone_config_file_and_env_precedence(tmp_path, monkeypatch):monkeypatch.setenv("OPENVIKING_CONFIG_FILE", str(tmp_path / "ignored-ov.conf"))(tmp_path / "ignored-ov.conf").write_text('{"gateway":{"enabled":true}}')diff --git a/tests/gateway/test_kernel.py b/tests/gateway/test_kernel.pyindex 53188e8cd..88a8d39f3 100644--- a/tests/gateway/test_kernel.py+++ b/tests/gateway/test_kernel.py@@ -7,20 +7,24 @@ import timeimport pytestfrom conftest import replay_records+from openviking_gateway import protocolsfrom openviking_gateway.blocks import gateway_notefrom openviking_gateway.capture import CaptureWorker, capture_messagesfrom openviking_gateway.capture_store import Documentfrom openviking_gateway.client import VikingError+from openviking_gateway.config import ClientRulesfrom openviking_gateway.kernel import token_estimatefrom openviking_gateway.models import Policyfrom openviking_gateway.protocols import (+ AUXILIARY,AUXILIARY_PATTERNS,- LOWERED_AUXILIARY,REI_CASE_EXCEPTIONS,auxiliary,canonical_arguments,classify,+ clean_text,client_openviking_tools,+ configure_rules,normalize,parse_body,plugin_present,@@ -587,7 +591,8 @@ def test_classification_and_plugin_namespaces():def test_lowercase_agrees_with_case_insensitive_matching():- assert LOWERED_AUXILIARY+ # Every packaged pattern stays on the literal-search fast path.+ assert all(fast for fast, _ in AUXILIARY)ascii_any_case = re.compile(r"[\x00-\x7f]", re.I)differing = set()for code in range(sys.maxunicode + 1):@@ -625,6 +630,58 @@ def test_auxiliary_matches_patterns_ignoring_case(text, expected):assert auxiliary(text) == expected+def client_rules():+ yield lambda changes: configure_rules(ClientRules.model_validate(changes))+ configure_rules()+++def test_client_rules_add_to_and_remove_from_the_packaged_rules(client_rules):+ user = {"role": "user", "content": "Write the Acme release title for v2"}+ side = [{"role": "user", "content": "You are the ACME title writer.\n\nv2 notes"}]+ assert classify({}, {}, side)[0] == "user"+ unknown = client_rules(+ {+ "auxiliary_patterns": {+ "add": ["You are the Acme title writer", r"\Aacme \d+\Z"],+ "remove": ["Create a short.{0,40}title", "not packaged"],+ },+ "noise_tags": {"add": ["acme-context", "acme.note"], "remove": ["system-reminder"]},+ "noise_patterns": {"add": [r"\A\[Acme: keep going\]\Z"]},+ "plugin_tags": {"add": ["acme-memory"]},+ }+ )+ assert unknown == ["auxiliary_patterns: not packaged"]+ assert classify({}, {}, side)[0] == "auxiliary"+ assert classify({"system": "Create a short release title"}, {}, [user])[0] == "user"+ assert auxiliary("ACME 12") and not auxiliary("acme 12 fixes")+ # Each part is matched on its own and as text, so anchors and line breaks hold.+ numbered = [{"role": "user", "content": "acme 12"}]+ assert classify({"system": "You are helpful"}, {}, numbered)[0] == "auxiliary"+ assert classify({"instructions": "Be brief"}, {}, numbered)[0] == "auxiliary"+ blocks = [{"type": "text", "text": "Intro\nYou are the Acme title writer"}]+ assert classify({"system": blocks}, {}, [user])[0] == "auxiliary"+ # A configured regex leaves every packaged pattern on the fast path.+ assert [fast is None for fast, _ in protocols.AUXILIARY].count(True) == 1+ assert clean_text("<acme-context>cwd</acme-context> fix it") == "fix it"+ assert clean_text("<acme.note a='1'>x</acme.note> fix it") == "fix it"+ assert clean_text("<acmeXnote>x</acmeXnote> fix it") == "<acmeXnote>x</acmeXnote> fix it"+ assert "<system-reminder>" in clean_text("<system-reminder>x</system-reminder> fix it")+ loop = [+ user,+ {"role": "assistant", "content": "On it"},+ {"role": "user", "content": "[Acme: keep going]"},+ ]+ assert classify({}, {}, loop) == ("continuation", 0)+ assert plugin_present(+ {"messages": [{"role": "user", "content": "<acme-memory>m</acme-memory>"}]}, {}+ )+ # Each call starts again from the packaged rules.+ assert client_rules({}) == []+ assert classify({}, {}, side)[0] == "user"+ assert protocols.AUXILIARY_PATTERNS == AUXILIARY_PATTERNS++OV_NAMES = ["read", "ls", "glob", "find", "search", "add_resource"]