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(config): add runtime configuration system (#5140)
runyunzhoue6433bd86c54
diff --git a/docs/design/runtime-configuration-design.md b/docs/design/runtime-configuration-design.mdnew file mode 100644index 000000000..8dd34e324--- /dev/null+++ b/docs/design/runtime-configuration-design.md@@ -0,0 +1,140 @@+# 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 overrides are sparse values persisted by a `ConfigSource`. They can be published without rebuilding the process and are resolved independently at Cluster and Account scopes.++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 sparse overrides.+2. Keep Account overrides sparse and resolve fallback at read time instead of materializing inherited values.+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.++## 2. Configuration model++`OpenVikingConfig` is the Cluster model. `AccountConfig` is a sparse Account model; every Account field defaults to `None`, which means that the account has no explicit override. `RuntimeField` records two independent properties:++- `dynamic`: whether the field can be modified after creation;+- `fallback`: an optional Cluster field path used when an Account field is unset.++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 | `vlm`, `memory`, `feishu`, `agent_evolution` | Dynamic | All four declare Cluster fallback; Agent Evolution is consumed through the manager, while the complete VLM, memory, and Feishu consumer paths are not yet wired |+| Account | `github`, `acl` | Dynamic | No Cluster fallback; GitHub and ACL consumers read the Account value through the manager |+| Account | `embedding`, `vectordb` | Create-only | Fallback to Cluster `embedding` and `storage.vectordb`; both fields must be set together when explicitly configured |++`query_planner`, Cluster `embedding`, Cluster `vlm`, Cluster `memory`, and the other plain configuration sections are not currently writable through the runtime configuration API.++## 3. RuntimeConfigManager++`RuntimeConfigManager` owns storage-independent behavior:++- sparse three-state PATCH merging;+- 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 overrides are always applied to the immutable startup baseline. They are not merged into the previously published effective object, which prevents removed overrides from remaining accidentally materialized. Account overrides remain sparse; fallback is resolved only when an Account field is read.++## 4. PATCH and validation++Both scopes use the same request shape:++```json+{+ "settings": {+ "agent_evolution": {+ "enabled": true+ }+ }+}+```++The stored override 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 two 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.++A `dynamic=False` field can be supplied while an Account is created, but any later PATCH touching that field is rejected. `embedding` and `vectordb` are validated as a pair, including their dimensions.++The API returns the explicit override at the addressed scope. It does not return inherited or effective values. Fallback is a whole-section operation: if an Account supplies `vlm`, omitted properties use the VLM model defaults rather than being merged property-by-property from the Cluster VLM.++## 5. Publication and consumers++A successful update follows this order:++1. Read the current sparse override.+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.++The current implementation only wires a subset of declared fields into business consumers. Account GitHub, ACL, and Agent Evolution reads use the manager. Account `vlm`, `memory`, `feishu`, `embedding`, and `vectordb` can be validated and persisted, but their complete business read paths remain follow-up work.++## 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 and the Agent Evolution endpoint remain compatibility adapters. They translate writes into `RuntimeConfigManager` operations and do not maintain a second persistence path.++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+pytest tests/config/test_runtime_config.py+```++They cover field discovery, three-state merging, dynamic/create-only validation, lazy Account loading, publication isolation, consumer notification, idle eviction, fallback, and file-source backup behavior.diff --git a/docs/en/api/01-overview.md b/docs/en/api/01-overview.mdindex 0419cbf45..6618a8772 100644--- a/docs/en/api/01-overview.md+++ b/docs/en/api/01-overview.md@@ -499,10 +499,14 @@ This catalog follows the routes actually mounted by the server. Each group headi| Method | Path | Description ||--------|------|-------------|-| GET | `/api/v1/admin/agent-evolution` | Get the caller account's Agent Evolution status |-| PUT | `/api/v1/admin/agent-evolution` | Update the caller account's Agent Evolution status |-| GET | `/api/v1/admin/accounts/{account_id}/settings` | Get effective account settings |-| PATCH | `/api/v1/admin/accounts/{account_id}/settings` | Update allowlisted account settings |+| GET | `/api/v1/admin/configuration` | Get explicit Cluster runtime configuration |+| PATCH | `/api/v1/admin/configuration` | Update Cluster runtime configuration |+| GET | `/api/v1/admin/accounts/{account_id}/configuration` | Get explicit Account runtime configuration |+| PATCH | `/api/v1/admin/accounts/{account_id}/configuration` | Update Account runtime configuration |+| GET | `/api/v1/admin/agent-evolution` | Get Agent Evolution status (deprecated) |+| PUT | `/api/v1/admin/agent-evolution` | Update Agent Evolution status (deprecated) |+| GET | `/api/v1/admin/accounts/{account_id}/settings` | Get legacy account settings (deprecated) |+| PATCH | `/api/v1/admin/accounts/{account_id}/settings` | Update legacy account settings (deprecated) || GET | `/api/v1/admin/accounts/{account_id}/memory-templates` | List editable memory templates, defaults and effective values || GET | `/api/v1/admin/accounts/{account_id}/memory-templates/{memory_type}` | Read one memory template || PUT | `/api/v1/admin/accounts/{account_id}/memory-templates/{memory_type}` | Complete and publish one memory template |diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.mdindex 905a30618..c6206f564 100644--- a/docs/en/api/08-admin.md+++ b/docs/en/api/08-admin.md@@ -113,12 +113,10 @@ curl http://localhost:1933/api/v1/admin/agent-evolution \}```-`enabled` is the account override from-`/local/{account_id}/_system/setting.json`, or-`server.agent_evolution.enabled` when no override exists. Session commits read-this effective value without restarting the server.+`enabled` resolves the Account runtime override, Cluster runtime override, then+the startup value from `server.agent_evolution.enabled`.-The existing update endpoint name is unchanged:+The existing endpoint remains as a deprecated compatibility adapter:```httpPUT /api/v1/admin/agent-evolution@@ -129,9 +127,9 @@ Content-Type: application/json### account_settings-ROOT can manage any account and ADMIN can manage only its own account. The-generic settings endpoint accepts only explicitly allowlisted fields. It currently-allows `agent_evolution.enabled` and `acl.enabled`.+This endpoint is deprecated. ROOT can manage any account and ADMIN can manage+only its own account. It preserves the original ACL and Agent Evolution request+and response semantics:```httpGET /api/v1/admin/accounts/{account_id}/settings@@ -144,6 +142,10 @@ Content-Type: application/json}```+Missing and `null` sections are no-ops. A present object replaces that legacy+section; an empty ACL object means `enabled=false`. New integrations should use+the configuration endpoints below.+`acl.enabled` defaults to `false`. While disabled, shared resources use theoriginal public behavior and ACL authorization is skipped. When enabled, newlycreated shared resources receive ACL fields and ACL-protected shared resources@@ -419,6 +421,55 @@ active configuration remains unchanged. Structurally valid older overrides usingunsupported Jinja can still be read, replaced or reset, but extraction refuses toexecute them unchecked. Corrupt YAML remains an explicit error.+### runtime_configuration++ROOT can manage Cluster configuration and any Account configuration. ADMIN can+manage only its own Account layer.++```http+GET /api/v1/admin/configuration+PATCH /api/v1/admin/configuration++GET /api/v1/admin/accounts/{account_id}/configuration+PATCH /api/v1/admin/accounts/{account_id}/configuration+Content-Type: application/json++{"settings": {"agent_evolution": {"enabled": true}}}+```++`settings` always means explicit values at the addressed layer. PATCH is+three-state: an absent key is unchanged, `null` deletes that layer's value, and+a concrete value updates it.++The Cluster runtime surface currently contains agent_evolution. The Account+surface contains vlm, memory, feishu, agent_evolution, github, and acl as+dynamic fields, plus embedding and vectordb as create-only fields. Cluster+embedding, vlm, query_planner, memory, storage, parser, and retrieval fields+are startup-only because they are not declared as runtime fields.++dynamic=True fields may be set when an Account is created and changed by a+later PATCH. dynamic=False fields may be set only during Account creation;+later PATCH requests that touch them are rejected. embedding and vectordb must+be supplied together when explicitly configured, and their dimensions must+match. Account fields may declare a whole-section Cluster fallback. An Account+section that is explicitly set does not merge individual omitted properties+from the Cluster section; omitted properties use the model defaults.++The PATCH is validated structurally before the merged configuration is built:+unknown paths and fields outside the runtime surface are rejected, and+create-only fields are rejected on ordinary PATCH. Objects merge recursively;+arrays replace wholesale. A nested null removes only that leaf. To remove a+whole object override, send null at the parent path; an empty object remains an+explicit empty object.++Both GET endpoints return only the explicit values persisted at the addressed+layer. They do not expand fallback values. 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).+### user_settingsROOT can manage any User and ADMIN can manage Users in its own account. Thediff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.mdindex f8c16fd1a..be58323e2 100644--- a/docs/en/guides/01-configuration.md+++ b/docs/en/guides/01-configuration.md@@ -47,6 +47,48 @@ Create `~/.openviking/ov.conf` in your home configuration directory:For `provider: "openai-codex"`, `vlm.api_key` is optional when Codex OAuth is already available.+## Configuration Scope and Update Lifecycle++OpenViking configuration has two layers:++- **Startup configuration** is read from `ov.conf`. It defines the process baseline and the runtime configuration source. Changing it requires a service restart; the runtime configuration API never rewrites `ov.conf`.+- **Runtime overrides** are sparse values stored by the configured runtime configuration source. They can be read and updated through the Admin API at Cluster or Account scope.++Only fields explicitly declared as runtime fields are exposed by the runtime configuration API. The current update surface is:++| Scope | Configuration | Lifecycle | Effective behavior |+| --- | --- | --- | --- |+| Cluster | `agent_evolution` | Dynamic | ROOT can update it through the Admin API; it is used as the cluster default. |+| Account | `vlm`, `memory`, `feishu`, `agent_evolution` | Dynamic | ROOT or the Account ADMIN can update it. The first four sections declare Cluster fallback; currently Agent Evolution is consumed through the runtime manager. |+| Account | `github`, `acl` | Dynamic | ROOT or the Account ADMIN can update it. These sections have no Cluster fallback. |+| Account | `embedding`, `vectordb` | Create-only | Can be supplied when creating an Account, but cannot be changed by a later configuration PATCH. They must be configured together when explicitly set. |++Cluster `embedding`, Cluster `vlm`, `query_planner`, Cluster `memory`, storage, parser, retrieval, and other ordinary configuration sections remain startup-only. Account `vlm`, `memory`, `feishu`, `embedding`, and `vectordb` values can currently be validated and persisted, but their complete business consumer integrations are still being rolled out; do not interpret persistence alone as proof that every component has switched.++For runtime changes, use the following endpoints:++```http+GET /api/v1/admin/configuration+PATCH /api/v1/admin/configuration++GET /api/v1/admin/accounts/{account_id}/configuration+PATCH /api/v1/admin/accounts/{account_id}/configuration+```++The request body wraps a sparse patch in `settings`:++```json+{+ "settings": {+ "agent_evolution": {+ "enabled": true+ }+ }+}+```++PATCH uses three states: an omitted field is unchanged, a concrete value sets or replaces the value, and `null` removes the override at that layer. Objects merge recursively and arrays replace as a whole. The response contains explicit values at the addressed layer, not inherited or effective values. See [Admin API - Runtime Configuration](../api/08-admin.md#runtime_configuration) for permissions, validation, fallback, and compatibility details. The implementation design is documented in [Runtime Configuration Design](../../design/runtime-configuration-design.md).+## Configuration Examples<details>@@ -1688,13 +1730,13 @@ When running OpenViking as an HTTP service, add a `server` section to `ov.conf`:| `user_config_defaults.add_targets.resource_uri` | str | Deployment default resource add directory used when `add_resource` omits both `to` and `parent`. `viking://~/...` resolves per request user. | `null` || `user_config_defaults.add_targets.skill_uri` | str | Deployment default skill add root used when `add_skill` omits `target_uri`. Only `viking://~/skills` and `viking://agent/skills` are accepted. | `null` || `user_config_defaults.memory_policy` | object | Deployment default memory extraction policy used when neither the Session nor the User has an explicit policy. | `null` |-| `agent_evolution.enabled` | bool | Instance-wide Agent Evolution switch. When enabled, session commits may generate or update cases, trajectories, and experiences according to the session `memory_policy`. When disabled, production of these memory types stops for every account and user. Existing memories remain readable and searchable. | `false` |+| `agent_evolution.enabled` | bool | Startup cluster default for Agent Evolution. Account and Cluster Admin settings may override it at runtime. When enabled, session commits may generate or update cases, trajectories, and experiences according to the session `memory_policy`. Existing memories remain readable and searchable when disabled. | `false` |Omitting `auth_mode` (or setting it to `null`) selects `api_key` when a non-empty `root_api_key` is configured, and `dev` otherwise. `dev` is allowed only on localhost and accepts requests without authentication. An empty-string `root_api_key` is invalid.Explicit `auth_mode: "api_key"` requires a non-empty `root_api_key`, including on localhost; without it, startup fails instead of falling back to development mode. Use the root key with the Admin API to create accounts and user/admin keys; use those tenant-bound keys for data access. `trusted` mode accepts account/user identity headers from a trusted gateway and does not require user-key provisioning first. Its root key is optional only on localhost and required for non-localhost binds. For role resolution, OIDC/LDAP setup, and gateway requirements, see [Authentication](04-authentication.md).-`user_config_defaults` provides deployment defaults for add targets and memory extraction. For add operations, explicit request targets still win: `add_resource.to` / `add_resource.parent` take precedence over user defaults, and `add_skill.target_uri` takes precedence over user defaults. Memory policy precedence is Session policy > User `settings/user_config.json` policy > `server.user_config_defaults.memory_policy` > kernel default. `agent_evolution.enabled` is shared by the entire OpenViking instance and has no per-user override. Running HTTP server workers read the current Agent Evolution value from the resolved `ov.conf` when a session commits, so a valid file update applies without restarting the server.+`user_config_defaults` provides deployment defaults for add targets and memory extraction. For add operations, explicit request targets still win: `add_resource.to` / `add_resource.parent` take precedence over user defaults, and `add_skill.target_uri` takes precedence over user defaults. Memory policy precedence is Session policy > User `settings/user_config.json` policy > `server.user_config_defaults.memory_policy` > kernel default. `server.agent_evolution.enabled` supplies the startup default. Runtime resolution is Account override > Cluster runtime override > that startup value. Use the Admin settings APIs for changes without restarting; editing `ov.conf` directly takes effect after restart.### Usage Reporterdiff --git a/docs/zh/api/01-overview.md b/docs/zh/api/01-overview.mdindex ceee36682..b79246069 100644--- a/docs/zh/api/01-overview.md+++ b/docs/zh/api/01-overview.md@@ -494,10 +494,14 @@ JSON 输出 - 错误:| 方法 | 路径 | 说明 ||------|------|------|-| GET | `/api/v1/admin/agent-evolution` | 获取调用方 account 的 Agent 进化状态 |-| PUT | `/api/v1/admin/agent-evolution` | 更新调用方 account 的 Agent 进化状态 |-| GET | `/api/v1/admin/accounts/{account_id}/settings` | 获取 account 生效配置 |-| PATCH | `/api/v1/admin/accounts/{account_id}/settings` | 更新白名单内的 account 配置 |+| GET | `/api/v1/admin/configuration` | 获取 Cluster 层显式运行时配置 |+| PATCH | `/api/v1/admin/configuration` | 更新 Cluster 层运行时配置 |+| GET | `/api/v1/admin/accounts/{account_id}/configuration` | 获取 Account 层显式运行时配置 |+| PATCH | `/api/v1/admin/accounts/{account_id}/configuration` | 更新 Account 层运行时配置 |+| GET | `/api/v1/admin/agent-evolution` | 获取 Agent 进化状态(deprecated) |+| PUT | `/api/v1/admin/agent-evolution` | 更新 Agent 进化状态(deprecated) |+| GET | `/api/v1/admin/accounts/{account_id}/settings` | 获取存量账号配置(deprecated) |+| PATCH | `/api/v1/admin/accounts/{account_id}/settings` | 更新存量账号配置(deprecated) || GET | `/api/v1/admin/accounts/{account_id}/memory-templates` | 列出可编辑记忆模板、默认值及生效值 || GET | `/api/v1/admin/accounts/{account_id}/memory-templates/{memory_type}` | 查询单个记忆模板 || PUT | `/api/v1/admin/accounts/{account_id}/memory-templates/{memory_type}` | 补齐并发布单个记忆模板 |diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.mdindex 90fa8d979..447cf06ba 100644--- a/docs/zh/api/08-admin.md+++ b/docs/zh/api/08-admin.md@@ -113,11 +113,10 @@ curl http://localhost:1933/api/v1/admin/agent-evolution \}```-`enabled` 优先读取-`/local/{account_id}/_system/setting.json` 中的 account 级覆盖值;未配置时使用-`server.agent_evolution.enabled`。Session commit 会实时读取生效值,无需重启。+`enabled` 依次解析 Account 运行时覆盖、Cluster 运行时覆盖,以及+`server.agent_evolution.enabled` 提供的启动值。-现有更新接口名保持不变:+现有接口作为 deprecated 兼容适配器保留:```httpPUT /api/v1/admin/agent-evolution@@ -128,9 +127,8 @@ Content-Type: application/json### account_settings-ROOT 可管理任意 account,ADMIN 仅可管理自己所属的 account。通用配置接口仅允许-显式列入白名单的字段;当前允许修改 `agent_evolution.enabled` 和-`acl.enabled`。+该接口已 deprecated。ROOT 可管理任意 account,ADMIN 仅可管理自己所属的 account。+接口保留原有 ACL 与 Agent Evolution 请求和响应语义:```httpGET /api/v1/admin/accounts/{account_id}/settings@@ -143,6 +141,9 @@ Content-Type: application/json}```+字段缺失或为 `null` 都表示不修改;传入对象则整体设置对应存量配置段,+空 ACL 对象表示 `enabled=false`。新接入方应使用下述 configuration 接口。+`acl.enabled` 默认为 `false`。关闭时,共享资源按原有规则完全共享,不执行 ACL鉴权。开启后,账号内新增共享资源会写入 ACL,并对带 ACL 的共享资源执行鉴权;已有且未设置 ACL 的内容不会迁移或改权。重新关闭后,已有 ACL 也不再参与访问判断。@@ -352,6 +353,44 @@ Events 的默认 embedding 模板引用正文,因此正文变化也可能影{% endfor %}```+### runtime_configuration++ROOT 可管理 Cluster 配置和任意 Account 配置;ADMIN 只能管理所属账号的 Account 层。++```http+GET /api/v1/admin/configuration+PATCH /api/v1/admin/configuration++GET /api/v1/admin/accounts/{account_id}/configuration+PATCH /api/v1/admin/accounts/{account_id}/configuration+Content-Type: application/json++{"settings": {"agent_evolution": {"enabled": true}}}+```++`settings` 始终表示目标层的显式设置值。PATCH 为三态语义:字段缺失表示不修改,+`null` 表示删除当前层配置,具体值表示更新。++当前 Cluster 运行时配置面仅包含 agent_evolution。Account 配置面包含+vlm、memory、feishu、agent_evolution、github、acl 这些动态字段,以及+embedding、vectordb 这两个仅创建时可设置的字段。Cluster 的 embedding、vlm、+query_planner、memory、存储、解析器和检索配置没有声明为运行时字段,因此仍然+只能在启动配置中修改。++dynamic=True 的字段可以在创建 Account 时设置,也可以通过后续 PATCH 修改;+dynamic=False 的字段只能在创建 Account 时设置,后续 PATCH 触及时会被拒绝。+显式配置 embedding 和 vectordb 时必须成对提供,并且维度必须一致。Account+字段可以声明整个配置段的 Cluster fallback。Account 一旦显式设置某个配置段,+其中省略的属性不会逐项从 Cluster 配置合并,而是使用该模型的默认值。++PATCH 会先做结构校验,再构造合并后的配置:未知路径、运行时配置面之外的字段会被拒绝,+普通 PATCH 触及仅创建字段时也会被拒绝。对象递归合并,数组整体替换;嵌套 null+只删除对应叶子。删除整个对象覆盖需要在父路径传 null,传空对象仍表示显式空对象。++两个 GET 接口只返回目标层持久化的显式值,不展开 fallback。配置持久化后会发布新配置并等待+匹配的进程内 Consumer;Consumer 失败会记录日志但不会回滚已持久化的覆盖,因此接口成功只表示+配置层更新成功,不保证所有派生客户端都已完成切换。当前业务接入状态见[运行时配置设计](../../design/runtime-configuration-design.md)。+### user_settingsROOT 可管理任意 User,ADMIN 仅可管理所属 account 内的 User。User 配置接口当前diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.mdindex 88ada4f4e..8feb3fb77 100644--- a/docs/zh/guides/01-configuration.md+++ b/docs/zh/guides/01-configuration.md@@ -48,6 +48,48 @@ openviking-server doctor如果 `provider` 是 `openai-codex`,并且 Codex OAuth 已经就绪,则 `vlm.api_key` 可以省略。+## 配置范围与生效方式++OpenViking 的配置分为两个层级:++- **启动配置**从 `ov.conf` 读取,用于定义进程基线和运行时配置源。修改后需要重启服务;运行时配置接口不会改写 `ov.conf`。+- **运行时覆盖配置**由配置源持久化保存,可以通过 Admin API 在 Cluster 或 Account 层修改。++只有显式声明为运行时字段的配置,才会暴露在运行时配置 API 中。当前可修改范围如下:++| 范围 | 配置 | 生命周期 | 生效说明 |+| --- | --- | --- | --- |+| Cluster | `agent_evolution` | 动态配置 | ROOT 可通过 Admin API 修改,作为集群默认值使用。 |+| Account | `vlm`、`memory`、`feishu`、`agent_evolution` | 动态配置 | ROOT 或该 Account 的 ADMIN 可修改;这些配置段声明了 Cluster fallback。目前只有 Agent Evolution 已通过运行时管理器接入业务读取。 |+| Account | `github`、`acl` | 动态配置 | ROOT 或该 Account 的 ADMIN 可修改;没有 Cluster fallback。 |+| Account | `embedding`、`vectordb` | 仅创建时配置 | 创建 Account 时可以设置,后续不能通过配置 PATCH 修改;显式设置时必须成对配置。 |++Cluster 的 `embedding`、Cluster 的 `vlm`、`query_planner`、Cluster 的 `memory`、存储、解析器、检索等普通配置仍然是启动配置。Account 的 `vlm`、`memory`、`feishu`、`embedding` 和 `vectordb` 当前可以完成校验和持久化,但业务消费方尚未全部接入;配置成功保存不代表所有组件都已经切换。++修改运行时配置使用以下接口:++```http+GET /api/v1/admin/configuration+PATCH /api/v1/admin/configuration++GET /api/v1/admin/accounts/{account_id}/configuration+PATCH /api/v1/admin/accounts/{account_id}/configuration+```++请求体使用 `settings` 包装稀疏补丁:++```json+{+ "settings": {+ "agent_evolution": {+ "enabled": true+ }+ }+}+```++PATCH 采用三态语义:字段缺失表示不修改,具体值表示设置或替换,`null` 表示删除当前层的覆盖。对象递归合并,数组整体替换。响应返回目标层的显式值,不返回继承值或最终生效值。权限、校验、fallback 和兼容接口详见 [Admin API - 运行时配置](../api/08-admin.md#runtime_configuration);实现设计见 [运行时配置设计](../../design/runtime-configuration-design.md)。+## 配置示例<details>@@ -1660,13 +1702,13 @@ ov add-resource ./docs --exclude "*.tmp"| `user_config_defaults.add_targets.resource_uri` | str | `add_resource` 未传 `to` 和 `parent` 时使用的部署级默认资源添加目录。`viking://~/...` 会按请求用户解析。 | `null` || `user_config_defaults.add_targets.skill_uri` | str | `add_skill` 未传 `target_uri` 时使用的部署级默认技能添加根目录。仅允许 `viking://~/skills` 和 `viking://agent/skills`。 | `null` || `user_config_defaults.memory_policy` | object | Session 和 User 都未显式配置策略时使用的部署级默认记忆抽取策略。 | `null` |-| `agent_evolution.enabled` | bool | 实例级 Agent 进化开关。开启时,session commit 可按 session `memory_policy` 生成或更新 cases、trajectories 和 experiences;关闭时,所有账号和用户均停止生产这三类记忆。已有记忆仍可读取和检索。 | `false` |+| `agent_evolution.enabled` | bool | Agent 进化的集群启动默认值,运行时可由 Account 或 Cluster Admin settings 覆盖。开启时,session commit 可按 session `memory_policy` 生成或更新 cases、trajectories 和 experiences;关闭后已有记忆仍可读取和检索。 | `false` |省略 `auth_mode`(或设为 `null`)时,配置了非空 `root_api_key` 则选择 `api_key`,否则选择 `dev`。`dev` 仅允许监听 localhost,不进行身份认证。`root_api_key` 不能配置为空字符串。显式设置 `auth_mode: "api_key"` 时,包括 localhost 在内都必须提供非空 `root_api_key`;缺少该 key 会导致启动失败,不会回退到开发模式。使用 root key 调用 Admin API 创建 account 和 user/admin key,数据访问使用这些绑定租户身份的 key。`trusted` 模式接受可信网关注入的 account/user 身份头,无需预先创建 user key;其 root key 仅在 localhost 可省略,监听非 localhost 地址时必填。角色解析、OIDC/LDAP 配置与网关要求参见 [身份认证](04-authentication.md)。-`user_config_defaults` 提供添加目标和记忆抽取的部署级默认配置。添加操作中,显式请求目标仍然优先:`add_resource.to` / `add_resource.parent` 优先于用户默认值,`add_skill.target_uri` 优先于用户默认值。记忆策略优先级为 Session 策略 > User `settings/user_config.json` 策略 > `server.user_config_defaults.memory_policy` > 内核默认策略。`agent_evolution.enabled` 是当前 OpenViking 实例的统一开关,不支持用户级覆盖。HTTP Server 的 worker 会在 session commit 时从解析后的 `ov.conf` 读取当前 Agent 进化配置,因此合法的文件更新无需重启服务即可生效。+`user_config_defaults` 提供添加目标和记忆抽取的部署级默认配置。添加操作中,显式请求目标仍然优先:`add_resource.to` / `add_resource.parent` 优先于用户默认值,`add_skill.target_uri` 优先于用户默认值。记忆策略优先级为 Session 策略 > User `settings/user_config.json` 策略 > `server.user_config_defaults.memory_policy` > 内核默认策略。`server.agent_evolution.enabled` 提供启动默认值,运行时优先级为 Account 覆盖 > Cluster 运行时覆盖 > 启动值。无需重启的修改应使用 Admin settings 接口;直接编辑 `ov.conf` 需要重启后生效。### Usage Reporterdiff --git a/openviking/config/__init__.py b/openviking/config/__init__.pynew file mode 100644index 000000000..703db6882--- /dev/null+++ b/openviking/config/__init__.py@@ -0,0 +1,59 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Runtime configuration system.++Separates configuration *storage/awareness* (:mod:`openviking.config.source`)+from configuration *merge/publish/invalidation* (:class:`RuntimeConfigManager`).++Cluster and account are two independent Pydantic models: cluster fields live on+``OpenVikingConfig`` and account fields on :class:`AccountConfig`. A field's+scope is decided by which model declares it. Account reads go through+``RuntimeConfigManager.get_account(account_id, field)``, which loads on demand+and resolves the field's declared cluster fallback.+"""++from openviking.config.account_config import AccountConfig+from openviking.config.assembly import build_config_source, resolve_config_source_settings+from openviking.config.manager import (+ ConfigChangeConsumer,+ ConfigChangeEvent,+ ConfigChangeReason,+ RuntimeConfigManager,+)+from openviking.config.merge import apply_three_state_patch, diff_sections+from openviking.config.scope import ConfigScope, ScopeKind+from openviking.config.source import (+ ConfigSource,+ ConfigSourceContext,+ FileConfigSource,+ MemoryConfigSource,+ Mutate,+ create_config_source,+ register_config_source,+)+from openviking.config.validate import ConfigPatchError, validate_patch+from openviking_cli.utils.config.open_viking_config import RuntimeConfigSettings++__all__ = [+ "AccountConfig",+ "ConfigChangeConsumer",+ "ConfigChangeEvent",+ "ConfigChangeReason",+ "ConfigPatchError",+ "ConfigScope",+ "ConfigSource",+ "ConfigSourceContext",+ "FileConfigSource",+ "MemoryConfigSource",+ "Mutate",+ "RuntimeConfigManager",+ "RuntimeConfigSettings",+ "ScopeKind",+ "apply_three_state_patch",+ "build_config_source",+ "create_config_source",+ "diff_sections",+ "register_config_source",+ "resolve_config_source_settings",+ "validate_patch",+]diff --git a/openviking/config/account_config.py b/openviking/config/account_config.pynew file mode 100644index 000000000..7dcf97f87--- /dev/null+++ b/openviking/config/account_config.py@@ -0,0 +1,47 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Account-scoped runtime configuration model.++``AccountConfig`` declares account overrides; ``OpenVikingConfig`` declares+cluster configuration. ``RuntimeField`` specifies write permissions and optional+cluster fallback. The manager resolves fallback for a whole unset section,+without merging cluster values into an explicitly configured account section.+"""++from __future__ import annotations++from typing import Optional++from pydantic import BaseModel++from openviking_cli.utils.config.agent_evolution_config import AgentEvolutionConfig+from openviking_cli.utils.config.github_config import GitHubConfig+from openviking_cli.utils.config.runtime_field import RuntimeField+++class AccountAclSettings(BaseModel):+ """Account-scoped ACL switch."""++ enabled: bool = False+++class AccountConfig(BaseModel):+ """Sparse per-account override model.++ Every field is ``Optional`` and defaults to ``None`` (= "account did not+ override this"). ``fallback`` fields resolve to the named cluster field when+ unset.+ """++ # These are the only account-level settings with active business consumers.+ github: Optional[GitHubConfig] = RuntimeField(default=None)+ agent_evolution: Optional[AgentEvolutionConfig] = RuntimeField(+ default=None,+ fallback="agent_evolution",+ )+ acl: Optional[AccountAclSettings] = RuntimeField(default=None)++ # Deferred account-level sections (vlm, memory, feishu, embedding, vectordb)+ # have no active consumers. Ignore historical or newer persisted sections;+ # validate_patch() still keeps API writes limited to the fields above.+ model_config = {"arbitrary_types_allowed": True, "extra": "ignore"}diff --git a/openviking/config/assembly.py b/openviking/config/assembly.pynew file mode 100644index 000000000..5b571b0f4--- /dev/null+++ b/openviking/config/assembly.py@@ -0,0 +1,55 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Startup assembly for the runtime config system.++Service startup calls the binding layer, which constructs a source through this+module and injects it into the manager. Source selection is read from ``ov.conf``+and cannot be changed through the runtime PATCH API::++ {+ "runtime_config": {+ "source": "file"+ }+ }++``params`` is passed unchanged to external providers. The built-in ``file``+source is constructed only by the kernel binding layer, which owns its AGFS+client and never exposes it to plugin factories.+"""++from __future__ import annotations++from openviking.config.source.base import ConfigSource, ConfigSourceContext+from openviking.config.source.registry import create_config_source, load_config_source_module+from openviking_cli.utils.config.open_viking_config import RuntimeConfigSettings+++def build_config_source(+ settings: RuntimeConfigSettings | dict | None,+) -> ConfigSource:+ """Construct an external configured :class:`ConfigSource`.++ ``settings`` may be a :class:`RuntimeConfigSettings`, a plain dict from+ ``ov.conf``, or ``None`` (which resolves to the kernel-owned ``file``+ source). External providers receive only ``params``.+ """+ resolved = resolve_config_source_settings(settings)+ if resolved.source.strip().lower() == "file":+ raise ValueError("The built-in 'file' config source is kernel-owned")+ if resolved.module:+ load_config_source_module(resolved.module)+ ctx = ConfigSourceContext(params=dict(resolved.params))+ return create_config_source(resolved.source, ctx)+++def resolve_config_source_settings(+ settings: RuntimeConfigSettings | dict | None,+) -> RuntimeConfigSettings:+ """Normalize boot configuration before selecting a kernel or plugin source."""+ if settings is None:+ return RuntimeConfigSettings()+ if isinstance(settings, RuntimeConfigSettings):+ return settings+ if isinstance(settings, dict):+ return RuntimeConfigSettings(**settings)+ raise TypeError(f"unsupported runtime_config settings type: {type(settings)!r}")diff --git a/openviking/config/binding.py b/openviking/config/binding.pynew file mode 100644index 000000000..4d4dbe016--- /dev/null+++ b/openviking/config/binding.py@@ -0,0 +1,103 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Bind the generic runtime-config machinery to concrete OpenViking models.++The manager receives hooks for cluster publication, model construction and+request validation. This module binds those hooks to ``OpenVikingConfig`` and+``AccountConfig``; service startup supplies the source selection and only the+kernel-owned file source receives its AGFS client.+"""++from __future__ import annotations++from typing import Optional++from openviking.config.account_config import AccountConfig+from openviking.config.assembly import build_config_source, resolve_config_source_settings+from openviking.config.manager import RuntimeConfigManager+from openviking.config.merge import apply_three_state_patch+from openviking.config.source.base import ConfigSource+from openviking.config.source.file_source import FileConfigSource+from openviking.config.validate import validate_patch+from openviking.pyagfs import AsyncAGFSClient+from openviking_cli.utils.config import get_openviking_config, set_openviking_config+from openviking_cli.utils.config.open_viking_config import OpenVikingConfig, RuntimeConfigSettings++# The concrete manager type this module hands back.+OpenVikingRuntimeConfigManager = RuntimeConfigManager[OpenVikingConfig, AccountConfig]+++def _build_cluster(old: OpenVikingConfig, override: dict) -> OpenVikingConfig:+ """Rebuild the cluster config from its startup baseline plus an override.++ Apply the complete stored override to the immutable startup model, then run+ ``from_dict`` validation. Reusing the previously published effective model+ would retain values after their override is deleted.++ ``by_alias=True`` is required for the dump→``from_dict`` round-trip: several+ fields (e.g. ``storage.vectordb.project_name`` aliased to ``project``) are+ only accepted by ``from_dict`` under their alias, while the bare+ ``model_dump()`` emits the field name and would be rejected as unknown. A+ stored override may contain top-level fields from a newer binary, so that+ runtime-only rebuild intentionally ignores those fields.+ """+ merged = apply_three_state_patch(+ old.model_dump(by_alias=True, exclude_unset=True),+ override or {},+ )+ return OpenVikingConfig.from_dict(merged)+++def _build_account(override: Optional[dict]) -> AccountConfig:+ """Construct (and thereby validate) an account config from its sparse override."""+ return AccountConfig.model_validate(override or {})+++def _validate_request(patch: dict, is_account: bool, creating: bool) -> None:+ """Structural gate: which model's RuntimeField surface a patch may touch."""+ model = AccountConfig if is_account else OpenVikingConfig+ validate_patch(model, patch, creating=creating)+++def build_runtime_config_manager(+ agfs_client: AsyncAGFSClient,+ *,+ settings: RuntimeConfigSettings | dict | None = None,+ base_config: OpenVikingConfig | None = None,+) -> OpenVikingRuntimeConfigManager:+ """Construct a fully-wired manager over the selected config source.++ The built-in ``file`` source receives the service-owned ``agfs_client`` in+ this kernel-only branch. Every other source is built by the plugin registry+ with its configured ``params`` only, so plugins never receive AGFS.+ """+ resolved = resolve_config_source_settings(settings)+ if resolved.source.strip().lower() == "file":+ source = FileConfigSource(agfs_client)+ else:+ source = build_config_source(resolved)+ return manager_over_source(source, base_config=base_config)+++def manager_over_source(+ source: ConfigSource,+ *,+ base_config: OpenVikingConfig | None = None,+) -> OpenVikingRuntimeConfigManager:+ """Wire the concrete OpenViking hooks onto an arbitrary :class:`ConfigSource`.++ Split out from :func:`build_runtime_config_manager` so callers that already+ hold a source (e.g. tests using an in-memory source) reuse the same+ cluster/account binding instead of duplicating the hook set. When omitted,+ ``base_config`` is captured from the current singleton at construction time.+ """+ base = base_config or get_openviking_config()+ return RuntimeConfigManager(+ source,+ base_config=base,+ get_config=get_openviking_config,+ set_config=set_openviking_config,+ build_config=_build_cluster,+ build_account=_build_account,+ validate_request=_validate_request,+ )diff --git a/openviking/config/manager.py b/openviking/config/manager.pynew file mode 100644index 000000000..b3304bbd6--- /dev/null+++ b/openviking/config/manager.py@@ -0,0 +1,513 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Runtime config manager: merge, publish, invalidation.++The manager owns everything that is storage-independent: three-state PATCH+merge, per-scope copy-on-write publish, old/new diff, and consumer notification.+It depends only on the :class:`ConfigSource` abstraction and never imports a+concrete source implementation.++Two scopes are managed side by side, mirroring the two independent config models+(the cluster ``OpenVikingConfig`` and the per-account ``AccountConfig``):++- **cluster** — a single process-wide config object, bridged through the+ ``get_config`` / ``set_config`` / ``build_config`` hooks so the manager stays+ agnostic to the concrete cluster model.+- **account** — a per-account cache of ``(sparse override, constructed account+ config, last-access time)``. ``get_account(account_id, field)`` loads the+ account on demand and resolves the field's declared cluster fallback.++Both models are built and validated by caller-supplied hooks, so the manager+imports neither ``OpenVikingConfig`` nor ``AccountConfig`` directly.+"""++from __future__ import annotations++import asyncio+import time+import weakref+from dataclasses import dataclass+from enum import Enum+from typing import Any, Awaitable, Callable, Generic, Optional, TypeVar++from openviking.config.merge import apply_three_state_patch, diff_sections+from openviking.config.scope import ConfigScope, ScopeKind+from openviking.config.source.base import ConfigSource+from openviking.service.task_tracker_concurrency import OwnerLoopDispatcher, run_to_completion+from openviking_cli.utils.config.runtime_field import fallback_of, resolve_fallback+from openviking_cli.utils.logger import get_logger++logger = get_logger(__name__)++# C = cluster config type; A = per-account config type.+C = TypeVar("C")+A = TypeVar("A")++REFRESH_INTERVAL_SECS = 30.0+# Accounts unused for this long are evicted and stop being polled.+ACCOUNT_IDLE_TTL_SECS = 24 * 60 * 60.0+++@dataclass(frozen=True)+class ConfigChangeEvent:+ """Emitted after a new config is published.++ ``scope`` names the changed override (cluster-wide or one account).+ ``old_config`` / ``new_config`` are the objects for that scope (the cluster+ config, or that account's :class:`AccountConfig`; ``None`` when the account+ scope was cleared or evicted). ``reason`` distinguishes ordinary config+ publication from manager-owned account lifecycle events.+ """++ scope: ConfigScope+ changed_sections: frozenset[str]+ old_config: Any+ new_config: Any+ reason: "ConfigChangeReason"+++class ConfigChangeReason(str, Enum):+ UPDATE = "update"+ EVICT = "evict"+++ConfigChangeConsumer = Callable[[ConfigChangeEvent], Awaitable[None]]+++@dataclass(frozen=True)+class _ConsumerRegistration:+ scope: ScopeKind+ sections: frozenset[str]+ consumer: ConfigChangeConsumer+++@dataclass+class _AccountEntry(Generic[A]):+ """One account's cached state under the manager's owner loop.++ ``config`` is the constructed, already-validated account model;+ ``last_access`` drives idle eviction.+ """++ config: A+ last_access: float+++class RuntimeConfigManager(Generic[C, A]):+ """Coordinate override merge/publish/invalidation over a :class:`ConfigSource`.++ ``base_config`` is the caller-owned immutable startup baseline.+ ``get_config`` / ``set_config`` bridge to the process-wide cluster singleton;+ ``build_config`` rebuilds the cluster model from the baseline plus a complete+ cluster override; ``build_account`` constructs an account model from its+ sparse override. Supplying these as hooks keeps the manager free of any+ concrete config-model import.+ """++ def __init__(+ self,+ source: ConfigSource,+ *,+ base_config: C,+ get_config: Callable[[], C],+ set_config: Callable[[C], None],+ build_config: Callable[[C, dict], C],+ build_account: Callable[[Optional[dict]], A],+ validate_request: Optional[Callable[[dict, bool, bool], None]] = None,+ ) -> None:+ self._source = source+ self._dispatcher = OwnerLoopDispatcher()+ # Immutable startup baseline. Cluster overrides are always rebuilt from+ # this object, never from the previously published effective config.+ self._base_config = base_config+ self._get_config = get_config+ self._set_config = set_config+ # build_config(old_cluster, cluster_override) -> new validated cluster config.+ self._build_config = build_config+ # build_account(sparse_override) -> constructed & validated account config.+ # The manager persists and builds from the *sparse* override only; fallback+ # is never materialized. AccountConfig's own @model_validator(after) runs at+ # construction, but it only cross-checks fields the account set explicitly+ # (see _check_embedding_vectordb_dim), so it never needs the cluster here.+ self._build_account = build_account+ # validate_request(patch, is_account_scope, creating) -> None (structural gate).+ self._validate_request = validate_request+ # Per-account cache; only touched on the owner loop.+ self._accounts: dict[str, _AccountEntry[A]] = {}+ self._overrides: dict[ConfigScope, Optional[dict]] = {}+ self._consumers: list[_ConsumerRegistration] = []+ # Per-scope local locks serialize same-node concurrent PATCHes so two+ # requests mutating the same scope can't interleave read-merge-write.+ self._scope_locks: weakref.WeakValueDictionary[tuple, asyncio.Lock] = (+ weakref.WeakValueDictionary()+ )+ self._publish_lock = asyncio.Lock()+ self._notification_lock = asyncio.Lock()+ self._refresh_task: Optional[asyncio.Task] = None++ # -- consumers ------------------------------------------------------------++ def add_update_consumer(+ self,+ *,+ scope: ScopeKind,+ sections: set[str] | frozenset[str],+ consumer: ConfigChangeConsumer,+ ) -> None:+ """Register a consumer for one scope kind and one or more sections."""+ if not sections:+ raise ValueError("config consumer must register at least one section")+ self._consumers.append(+ _ConsumerRegistration(+ scope=scope,+ sections=frozenset(sections),+ consumer=consumer,+ )+ )++ # -- cluster loading -----------------------------------------------------++ async def initialize(self) -> None:+ """Load cluster defaults before serving requests."""+ self._dispatcher.bind_current_loop()+ await self._refresh_scope(ConfigScope.cluster(), reason=ConfigChangeReason.UPDATE)++ async def replace_base_config(self, base_config: C) -> ConfigChangeEvent:+ """Replace the startup baseline without persisting a runtime override."""+ return await self._dispatcher.run(+ lambda: run_to_completion(lambda: self._replace_base_config(base_config))+ )++ async def _replace_base_config(self, base_config: C) -> ConfigChangeEvent:+ scope = ConfigScope.cluster()+ async with self._lock_for(scope):+ async with self._publish_lock:+ self._base_config = base_config+ event = self._publish(+ scope,+ self._overrides.get(scope),+ reason=ConfigChangeReason.UPDATE,+ )+ await self._notify(event)+ return event++ # -- account loading -----------------------------------------------------++ async def _ensure_loaded(self, account_id: str) -> None:+ """Load one account's override and construct its config, once.++ Idempotent and concurrency-safe per account. Absence of a file records+ "loaded, no override"; a read/decrypt/validate failure raises and does+ not fall back to another account's config.+ """+ entry = self._accounts.get(account_id)+ if entry is not None:+ entry.last_access = time.monotonic()+ return+ scope = ConfigScope.account(account_id)+ async with self._lock_for(scope):+ if account_id in self._accounts:+ self._accounts[account_id].last_access = time.monotonic()+ return+ override = await self._source.load(scope)+ async with self._publish_lock:+ self._accounts[account_id] = _AccountEntry(+ config=self._build_account(override),+ last_access=time.monotonic(),+ )+ self._overrides[scope] = override++ async def get_account(self, account_id: str, field: str) -> Any:+ """Load an account on demand and return one effective config field."""+ return await self._dispatcher.run(+ lambda: run_to_completion(lambda: self._get_account(account_id, field))+ )++ async def _get_account(self, account_id: str, field: str) -> Any:+ await self._ensure_loaded(account_id)+ entry = self._accounts[account_id]+ model_fields = getattr(type(entry.config), "model_fields", {})+ if field not in model_fields:+ raise AttributeError(field)+ value = getattr(entry.config, field)+ if value is not None:+ return value+ target = fallback_of(model_fields[field])+ if target is None:+ return None+ return resolve_fallback(self._get_config(), target)++ async def get_settings(self, scope: ConfigScope) -> dict:+ """Read explicit overrides, never the merged configuration."""+ import copy++ return copy.deepcopy(await self._dispatcher.run(lambda: self._source.load(scope)) or {})++ def validate_initial_settings(self, account_id: str, settings: dict) -> None:+ """Validate creation-time settings without persisting them."""+ ConfigScope.account(account_id)+ if self._validate_request is not None:+ self._validate_request(settings, True, True)+ # Construct-to-validate: section-internal and cross-section validators run.+ self._build_account(settings)++ # -- PATCH ---------------------------------------------------------------++ async def patch_cluster(self, patch: dict) -> ConfigChangeEvent:+ """Apply a three-state PATCH to the cluster override and publish."""+ scope = ConfigScope.cluster()+ return await self._dispatcher.run(+ lambda: run_to_completion(lambda: self._patch(scope, patch))+ )++ async def patch_account(+ self, account_id: str, patch: dict, *, creating: bool = False+ ) -> ConfigChangeEvent:+ """Apply a three-state PATCH to one account override and publish."""+ scope = ConfigScope.account(account_id)+ return await self._dispatcher.run(+ lambda: run_to_completion(lambda: self._patch(scope, patch, creating=creating))+ )++ async def delete_account(self, account_id: str) -> ConfigChangeEvent:+ """Delete one account override and evict all manager-owned state."""+ scope = ConfigScope.account(account_id)+ return await self._dispatcher.run(+ lambda: run_to_completion(lambda: self._delete_account(scope))+ )++ async def _delete_account(self, scope: ConfigScope) -> ConfigChangeEvent:+ assert scope.key is not None+ async with self._lock_for(scope):+ await self._source.delete(scope)+ async with self._publish_lock:+ entry = self._accounts.pop(scope.key, None)+ self._overrides.pop(scope, None)+ event = self._account_event(+ scope.key,+ entry.config if entry is not None else None,+ None,+ reason=ConfigChangeReason.EVICT,+ )+ await self._notify(event)+ return event++ async def _patch(+ self, scope: ConfigScope, patch: dict, *, creating: bool = False+ ) -> ConfigChangeEvent:+ is_account = scope.kind is ScopeKind.ACCOUNT+ if self._validate_request is not None:+ self._validate_request(patch, is_account, creating)+ async with self._lock_for(scope):++ def mutate(current: Optional[dict]) -> dict:+ override = apply_three_state_patch(current, patch)+ if self._validate_request is not None and not creating:+ self._validate_resets(current or {}, patch, is_account)+ # Construct-to-validate before persisting.+ self._build_candidate(scope, override)+ return override++ override = await self._source.update(scope, mutate)+ async with self._publish_lock:+ event = self._publish(scope, override, reason=ConfigChangeReason.UPDATE)+ await self._notify(event)+ return event++ def _validate_resets(self, current: dict, patch: dict, is_account: bool) -> None:+ """A parent reset must not erase creation-only overrides beneath it."""++ def removed(node: dict, changes: dict) -> dict:+ result = {}+ for key, value in changes.items():+ if value is None and key in node:+ result[key] = node[key]+ elif isinstance(value, dict) and isinstance(node.get(key), dict):+ nested = removed(node[key], value)+ if nested:+ result[key] = nested+ return result++ assert self._validate_request is not None+ self._validate_request(removed(current, patch), is_account, False)++ # -- copy-on-write publish -----------------------------------------------++ def _build_candidate(self, scope: ConfigScope, override: Optional[dict]) -> Any:+ """Build (and thereby validate) the new object for a scope's override."""+ if scope.kind is ScopeKind.CLUSTER:+ return self._build_config(self._base_config, override or {})+ return self._build_account(override)++ def _publish(+ self,+ scope: ConfigScope,+ override: Optional[dict],+ *,+ reason: ConfigChangeReason,+ ) -> ConfigChangeEvent:+ """Swap in the new object for a scope and return the change event.++ Cluster publish swaps the singleton pointer; account publish replaces the+ cache entry. Either way business code only ever sees a fully-built object,+ never a partially-mutated one.+ """+ if scope.kind is ScopeKind.CLUSTER:+ old = self._get_config()+ new = self._build_config(self._base_config, override or {})+ self._set_config(new)+ self._overrides[scope] = override+ return ConfigChangeEvent(+ scope=scope,+ changed_sections=diff_sections(old, new),+ old_config=old,+ new_config=new,+ reason=reason,+ )+ assert scope.key is not None+ account_id = scope.key+ old_entry = self._accounts.get(account_id)+ old_config = old_entry.config if old_entry is not None else None+ new_config = self._build_account(override)+ self._accounts[account_id] = _AccountEntry(+ config=new_config,+ last_access=(old_entry.last_access if old_entry else time.monotonic()),+ )+ self._overrides[scope] = override+ return self._account_event(account_id, old_config, new_config, reason=reason)++ def _account_event(+ self,+ account_id: str,+ old_config: Any,+ new_config: Any,+ *,+ reason: ConfigChangeReason,+ ) -> ConfigChangeEvent:+ return ConfigChangeEvent(+ scope=ConfigScope.account(account_id),+ changed_sections=diff_sections(old_config, new_config),+ old_config=old_config,+ new_config=new_config,+ reason=reason,+ )++ async def _notify(self, event: ConfigChangeEvent) -> None:+ """Await matching consumers in registration order after publication."""+ is_evict = event.reason is ConfigChangeReason.EVICT+ if not event.changed_sections and not is_evict:+ return+ async with self._notification_lock:+ for registration in self._consumers:+ if registration.scope is not event.scope.kind:+ continue+ if not is_evict and registration.sections.isdisjoint(event.changed_sections):+ continue+ try:+ await registration.consumer(event)+ except Exception:+ logger.exception("Config change consumer failed")++ def _lock_for(self, scope: ConfigScope) -> asyncio.Lock:+ key = (scope.kind.value, scope.key)+ lock = self._scope_locks.get(key)+ if lock is None:+ lock = asyncio.Lock()+ self._scope_locks[key] = lock+ return lock++ # -- periodic refresh ----------------------------------------------------++ def start_refresh_loop(self, interval_secs: float = REFRESH_INTERVAL_SECS) -> None:+ if self._refresh_task is None or self._refresh_task.done():+ self._refresh_task = asyncio.create_task(self._refresh_loop(interval_secs))++ async def stop_refresh_loop(self) -> None:+ task = self._refresh_task+ self._refresh_task = None+ if task is not None:+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass++ async def _refresh_loop(self, interval_secs: float) -> None:+ while True:+ try:+ await asyncio.sleep(interval_secs)+ await self.refresh_once()+ except asyncio.CancelledError:+ raise+ except Exception:+ logger.exception("Runtime config refresh iteration failed")++ async def refresh_once(self) -> None:+ """Run one refresh on the configuration owner's loop."""+ await self._dispatcher.run(self._refresh_once)++ async def _refresh_once(self) -> None:+ """Reload cluster + hot accounts once, publishing any observed change.++ Every active scope is reloaded and diffed against the last published+ override (``_refresh_scope``); the manager owns change detection, so the+ source stays stateless. Cold accounts (idle > TTL) are evicted and stop+ being reloaded. On load or publish failure the last effective value is+ kept, and the next refresh retries the active scope.+ """+ async with self._publish_lock:+ evictions = self._evict_cold_accounts()+ for event in evictions:+ await self._notify(event)+ scopes = [ConfigScope.cluster()] + [+ ConfigScope.account(account_id) for account_id in list(self._accounts)+ ]+ for scope in scopes:+ try:+ await self._refresh_scope(scope, reason=ConfigChangeReason.UPDATE)+ except Exception:+ logger.warning(+ "Runtime config refresh for %s failed; keeping last value",+ scope,+ exc_info=True,+ )++ async def _refresh_scope(+ self,+ scope: ConfigScope,+ *,+ reason: ConfigChangeReason,+ ) -> None:+ async with self._lock_for(scope):+ override = await self._source.load(scope)+ if scope in self._overrides and self._overrides[scope] == override:+ return+ async with self._publish_lock:+ if scope.kind is ScopeKind.ACCOUNT:+ assert scope.key is not None+ if scope.key not in self._accounts:+ # A refresh must not resurrect an evicted/never-loaded account.+ return+ event = self._publish(scope, override, reason=reason)+ await self._notify(event)++ def _evict_cold_accounts(self) -> list[ConfigChangeEvent]:+ now = time.monotonic()+ cold = [+ account_id+ for account_id, entry in self._accounts.items()+ if now - entry.last_access > ACCOUNT_IDLE_TTL_SECS+ ]+ events: list[ConfigChangeEvent] = []+ for account_id in cold:+ entry = self._accounts.pop(account_id)+ self._overrides.pop(ConfigScope.account(account_id), None)+ events.append(+ self._account_event(+ account_id,+ entry.config,+ None,+ reason=ConfigChangeReason.EVICT,+ )+ )+ return eventsdiff --git a/openviking/config/merge.py b/openviking/config/merge.pynew file mode 100644index 000000000..b3020baad--- /dev/null+++ b/openviking/config/merge.py@@ -0,0 +1,73 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Three-state PATCH merge and copy-on-write helpers.++The same three-state semantics apply to every config layer (cluster and account):++- field absent: keep current value.+- field is a concrete value: set/replace.+- field is ``None``: delete this layer's override, inheriting the next layer.++Objects merge recursively, arrays replace wholesale.+"""++from __future__ import annotations++import copy+from typing import Any, Optional+++def apply_three_state_patch(current: Optional[dict], patch: dict) -> dict:+ """Return a new sparse override with ``patch`` applied to ``current``.++ Never mutates the inputs (pure function; safe for conflict retries).+ """+ result: dict = copy.deepcopy(current) if current else {}+ _merge_into(result, patch)+ return result+++def _merge_into(base: dict, patch: dict) -> None:+ for key, value in patch.items():+ if value is None:+ # Delete this layer's override, restoring inheritance.+ base.pop(key, None)+ continue+ if isinstance(value, dict):+ existing = base.get(key)+ if isinstance(existing, dict):+ _merge_into(existing, value)+ else:+ nested: dict = {}+ _merge_into(nested, value)+ # A delete-only child patch against a missing parent is a no-op.+ # An explicitly empty object still creates an explicit parent.+ if nested or not value:+ base[key] = nested+ continue+ # Concrete scalar or list: replace wholesale.+ base[key] = copy.deepcopy(value)+++def diff_sections(old: Any, new: Any) -> frozenset[str]:+ """Return the set of top-level sections whose value changed.++ Accepts either dicts or pydantic models; models are dumped first. Used to+ build :class:`~openviking.config.manager.ConfigChangeEvent`.+ """+ old_dict = _as_dict(old)+ new_dict = _as_dict(new)+ changed: set[str] = set()+ for key in set(old_dict) | set(new_dict):+ if old_dict.get(key) != new_dict.get(key):+ changed.add(key)+ return frozenset(changed)+++def _as_dict(value: Any) -> dict:+ if isinstance(value, dict):+ return value+ dump = getattr(value, "model_dump", None)+ if callable(dump):+ return dump()+ return {}diff --git a/openviking/config/scope.py b/openviking/config/scope.pynew file mode 100644index 000000000..d39ffb637--- /dev/null+++ b/openviking/config/scope.py@@ -0,0 +1,51 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Logical address of a single config override.++``ConfigScope`` names *one* override (cluster-wide or one account). It does not+express inheritance layers and does not prescribe storage layout; that is a+``ConfigSource`` implementation detail.+"""++from __future__ import annotations++from dataclasses import dataclass+from enum import Enum+from typing import Optional++from openviking.core.identifiers import validate_account_id+++class ScopeKind(str, Enum):+ CLUSTER = "cluster"+ ACCOUNT = "account"+++@dataclass(frozen=True)+class ConfigScope:+ """A logical address for one override; validated on construction."""++ kind: ScopeKind+ key: Optional[str] = None++ def __post_init__(self) -> None:+ if self.kind is ScopeKind.CLUSTER:+ if self.key is not None:+ raise ValueError("cluster scope has no key")+ elif self.kind is ScopeKind.ACCOUNT:+ if not self.key:+ raise ValueError("account scope requires key")+ error = validate_account_id(self.key)+ if error:+ # Fail closed on path-traversal and other identifier abuse.+ raise ValueError(error)+ else:+ raise ValueError(f"unknown scope kind: {self.kind}")++ @classmethod+ def cluster(cls) -> "ConfigScope":+ return cls(ScopeKind.CLUSTER)++ @classmethod+ def account(cls, account_id: str) -> "ConfigScope":+ return cls(ScopeKind.ACCOUNT, account_id)diff --git a/openviking/config/source/__init__.py b/openviking/config/source/__init__.pynew file mode 100644index 000000000..a8ea0ba1e--- /dev/null+++ b/openviking/config/source/__init__.py@@ -0,0 +1,41 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Config source abstraction, registry, and built-in implementations.++A :class:`ConfigSource` owns *where an override comes from, how it is written+back, how change is detected, and whether/how it is encrypted*. The+:class:`~openviking.config.manager.RuntimeConfigManager` owns merge, publish and+invalidation and depends only on this abstraction.+"""++from openviking.config.source.base import (+ ConfigSource,+ ConfigSourceContext,+ Mutate,+)+from openviking.config.source.registry import (+ create_config_source,+ register_config_source,+)++__all__ = [+ "ConfigSource",+ "ConfigSourceContext",+ "Mutate",+ "FileConfigSource",+ "MemoryConfigSource",+ "create_config_source",+ "register_config_source",+]+++def __getattr__(name):+ if name == "FileConfigSource":+ from openviking.config.source.file_source import FileConfigSource++ return FileConfigSource+ if name == "MemoryConfigSource":+ from openviking.config.source.memory_source import MemoryConfigSource++ return MemoryConfigSource+ raise AttributeError(name)diff --git a/openviking/config/source/base.py b/openviking/config/source/base.pynew file mode 100644index 000000000..60d707331--- /dev/null+++ b/openviking/config/source/base.py@@ -0,0 +1,64 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Stable ``ConfigSource`` contract.++External source implementations depend only on this module and+:mod:`openviking.config.source.registry`; they must not import other private+kernel modules. These two modules are maintained as a stable API.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any, Callable, Optional, Protocol, runtime_checkable++from openviking.config.scope import ConfigScope, ScopeKind++__all__ = ["ConfigScope", "ScopeKind", "ConfigSource", "ConfigSourceContext", "Mutate"]++# A pure, repeatable function producing the full new override from the current+# one. It must have no side effects and must not send consumer notifications;+# a conflict retry may run it again.+Mutate = Callable[[Optional[dict]], dict]+++@dataclass+class ConfigSourceContext:+ """Configuration passed to an external source factory at construction time.++ ``params`` is opaque to the manager; its meaning and connection lifecycle+ belong to the provider. The context intentionally contains no kernel+ dependencies, so plugins cannot receive AGFS or other service objects.+ """++ params: dict[str, Any] = field(default_factory=dict)+++@runtime_checkable+class ConfigSource(Protocol):+ """Storage/awareness of config overrides for individual scopes."""++ async def load(self, scope: ConfigScope) -> Optional[dict]:+ """Read the sparse override (plaintext dict) for one scope.++ Returns ``None`` when no override exists for the scope.+ """+ ...++ async def update(self, scope: ConfigScope, mutate: "Mutate") -> dict:+ """Perform a read-modify-write within the source's own concurrency guard.++ Reads the current override, calls ``mutate`` to get the full new+ override, writes it back. ``mutate`` is guaranteed to run against the+ latest value and the write must not drop updates; lock vs. CAS is an+ implementation choice.+ """+ ...++ async def delete(self, scope: ConfigScope) -> None:+ """Delete the persisted override for one scope.++ Missing state is treated as success. Implementations must provide the+ same concurrency guarantees as :meth:`update`.+ """+ ...diff --git a/openviking/config/source/file_source.py b/openviking/config/source/file_source.pynew file mode 100644index 000000000..2687ebf92--- /dev/null+++ b/openviking/config/source/file_source.py@@ -0,0 +1,217 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Built-in file-backed config source.++Paths are specific to this provider. The account override retains the legacy+``setting.json`` location:++============ ==========================================================+override path+============ ==========================================================+account ``/local/{account_id}/_system/setting.json``+account backup ``/local/{account_id}/_system/setting.backup.json``+cluster ``/local/_system/runtime_config/cluster.json``+============ ==========================================================++Only sparse overrides are stored. This source exchanges JSON bytes with AGFS;+encryption at rest follows the mount's configuration. Backups preserve the+previous bytes returned by AGFS so readers can recover if the destination is+left truncated by an interrupted write.+"""++from __future__ import annotations++import json+from typing import Any, Optional++from openviking.config.scope import ConfigScope, ScopeKind+from openviking.config.source.base import Mutate+from openviking.pyagfs import AGFSAlreadyExistsError, AGFSNotFoundError, AsyncAGFSClient+from openviking.pyagfs.async_client import fs_ctx_from_agfs_path+from openviking.storage.errors import LockAcquisitionError, ResourceBusyError+from openviking_cli.utils.logger import get_logger++logger = get_logger(__name__)++ACCOUNT_SETTINGS_PATH = "/local/{account_id}/_system/setting.json"+ACCOUNT_BACKUP_PATH = "/local/{account_id}/_system/setting.backup.json"+CLUSTER_SETTINGS_PATH = "/local/_system/runtime_config/cluster.json"+++class FileConfigSource:+ """Store sparse JSON overrides using AGFS locks, backups and rollback."""++ def __init__(+ self,+ agfs_client: AsyncAGFSClient,+ *,+ lock_timeout_secs: float = 10.0,+ ) -> None:+ self._client = agfs_client+ self._lock_timeout_secs = lock_timeout_secs++ # -- path / account resolution -------------------------------------------++ def _path(self, scope: ConfigScope) -> str:+ if scope.kind is ScopeKind.CLUSTER:+ return CLUSTER_SETTINGS_PATH+ return ACCOUNT_SETTINGS_PATH.format(account_id=scope.key)++ def _backup_path(self, scope: ConfigScope) -> Optional[str]:+ if scope.kind is ScopeKind.ACCOUNT:+ return ACCOUNT_BACKUP_PATH.format(account_id=scope.key)+ return "/local/_system/runtime_config/cluster.backup.json"++ # -- codec ----------------------------------------------------------------++ def _decode(self, raw: bytes) -> dict:+ payload = json.loads(raw.decode("utf-8"))+ if not isinstance(payload, dict):+ raise ValueError("config override must be a JSON object")+ return payload++ def _encode(self, override: dict) -> bytes:+ return json.dumps(override, ensure_ascii=False, indent=2, sort_keys=True).encode("utf-8")++ async def _read_raw(self, path: str) -> Optional[bytes]:+ try:+ fs_ctx = fs_ctx_from_agfs_path(path)+ fs_ctx["bypass_cache"] = "true"+ result = await self._client.read(path, fs_ctx=fs_ctx)+ except AGFSNotFoundError:+ return None+ return _decode_read_result(result)++ async def _read_override(self, scope: ConfigScope) -> tuple[Optional[bytes], Optional[dict]]:+ """Read a valid override, recovering from the previous version when needed."""+ path = self._path(scope)+ decode_error: Exception | None = None+ for candidate in (path, self._backup_path(scope)):+ if candidate is None:+ continue+ raw = await self._read_raw(candidate)+ if raw is None:+ continue+ try:+ override = self._decode(raw)+ except (UnicodeDecodeError, json.JSONDecodeError, ValueError) as exc:+ decode_error = decode_error or exc+ continue+ if candidate != path:+ logger.warning(+ "Recovered runtime config for %s from %s after the primary was unavailable "+ "or invalid",+ scope,+ candidate,+ )+ return raw, override+ if decode_error is not None:+ logger.error(+ "Runtime config for %s is invalid and no valid backup exists",+ scope,+ exc_info=decode_error,+ )+ raise RuntimeError(+ f"Runtime config for {scope} is invalid and no valid backup exists"+ ) from decode_error+ return None, None++ # -- ConfigSource contract ------------------------------------------------++ async def load(self, scope: ConfigScope) -> Optional[dict]:+ _, override = await self._read_override(scope)+ return override++ async def update(self, scope: ConfigScope, mutate: Mutate) -> dict:+ path = self._path(scope)+ try:+ lease = await self._client.pathlock_acquire_exact(+ path, timeout_secs=self._lock_timeout_secs+ )+ except LockAcquisitionError as exc:+ raise ResourceBusyError(+ "Another configuration update is in progress. Please retry.",+ uri=path,+ conflict_type="runtime_config_busy",+ ) from exc+ fs_ctx = _lease_fs_ctx(path, lease)+ try:+ current_raw, current = await self._read_override(scope)+ new_override = mutate(current)+ encoded = self._encode(new_override)++ try:+ await self._client.ensure_parent_dirs(path)+ except AGFSAlreadyExistsError:+ pass++ backup_path = self._backup_path(scope)+ if backup_path is not None and current_raw is not None:+ await self._client.write(backup_path, current_raw)++ try:+ await self._client.write(path, encoded, fs_ctx=fs_ctx)+ except Exception:+ try:+ if current_raw is None:+ await self._client.rm(path, fs_ctx=fs_ctx)+ else:+ await self._client.write(path, current_raw, fs_ctx=fs_ctx)+ except AGFSNotFoundError:+ pass+ except Exception:+ logger.exception("Failed to roll back runtime config at %s", path)+ raise+ return new_override+ finally:+ await self._client.pathlock_release(lease)++ async def delete(self, scope: ConfigScope) -> None:+ path = self._path(scope)+ try:+ lease = await self._client.pathlock_acquire_exact(+ path, timeout_secs=self._lock_timeout_secs+ )+ except LockAcquisitionError as exc:+ raise ResourceBusyError(+ "Another configuration update is in progress. Please retry.",+ uri=path,+ conflict_type="runtime_config_busy",+ ) from exc+ fs_ctx = _lease_fs_ctx(path, lease)+ try:+ for target in (path, self._backup_path(scope)):+ if target is None:+ continue+ try:+ if target == path:+ await self._client.rm(target, fs_ctx=fs_ctx)+ else:+ await self._client.rm(target)+ except AGFSNotFoundError:+ pass+ finally:+ await self._client.pathlock_release(lease)+++def _decode_read_result(result: Any) -> bytes:+ if isinstance(result, bytes):+ return result+ content = getattr(result, "content", None)+ if isinstance(content, bytes):+ return content+ if isinstance(content, str):+ return content.encode("utf-8")+ if isinstance(result, str):+ return result.encode("utf-8")+ raise ValueError("config override content must be bytes or JSON text")+++def _lease_fs_ctx(path: str, lease: Any) -> dict[str, str]:+ fs_ctx = fs_ctx_from_agfs_path(path)+ lease_ref = getattr(lease, "lease_ref", None) or getattr(lease, "id", None)+ if isinstance(lease, dict):+ lease_ref = lease.get("lease_ref", lease_ref)+ if isinstance(lease_ref, str) and lease_ref:+ fs_ctx["lease_ref"] = lease_ref+ return fs_ctxdiff --git a/openviking/config/source/memory_source.py b/openviking/config/source/memory_source.pynew file mode 100644index 000000000..435da313a--- /dev/null+++ b/openviking/config/source/memory_source.py@@ -0,0 +1,46 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""In-memory config source for tests and explicit volatile mode."""++from __future__ import annotations++import asyncio+import copy+from typing import Optional++from openviking.config.scope import ConfigScope+from openviking.config.source.base import ConfigSourceContext, Mutate+from openviking.config.source.registry import register_config_source+++class MemoryConfigSource:+ """Volatile source keeping overrides in a process-local dict."""++ def __init__(self, ctx: Optional[ConfigSourceContext] = None) -> None:+ self._namespace = ctx.params.get("namespace", "") if ctx else ""+ self._store: dict[tuple, Optional[dict]] = {}+ self._lock = asyncio.Lock()++ def _key(self, scope: ConfigScope) -> tuple:+ return (self._namespace, scope.kind.value, scope.key)++ async def load(self, scope: ConfigScope) -> Optional[dict]:+ override = self._store.get(self._key(scope))+ return copy.deepcopy(override) if override is not None else None++ async def update(self, scope: ConfigScope, mutate: Mutate) -> dict:+ async with self._lock:+ key = self._key(scope)+ current = self._store.get(key)+ new_override = mutate(copy.deepcopy(current) if current else None)+ self._store[key] = copy.deepcopy(new_override)+ return copy.deepcopy(new_override)++ async def delete(self, scope: ConfigScope) -> None:+ async with self._lock:+ self._store.pop(self._key(scope), None)+++@register_config_source("memory")+def _build_memory_source(ctx: ConfigSourceContext) -> MemoryConfigSource:+ return MemoryConfigSource(ctx)diff --git a/openviking/config/source/registry.py b/openviking/config/source/registry.pynew file mode 100644index 000000000..41df22c3f--- /dev/null+++ b/openviking/config/source/registry.py@@ -0,0 +1,84 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""External config source registry.++Plugins register by name through the ``openviking.config_source`` entry-point+group or an ``ov.conf`` module path. Kernel-owned sources, such as the AGFS+file source, are deliberately not registrable here.+"""++from __future__ import annotations++import importlib+from typing import Callable++from openviking.config.source.base import ConfigSource, ConfigSourceContext+from openviking_cli.utils.logger import get_logger++logger = get_logger(__name__)++ConfigSourceFactory = Callable[[ConfigSourceContext], ConfigSource]++_FACTORIES: dict[str, ConfigSourceFactory] = {}++ENTRY_POINT_GROUP = "openviking.config_source"+++def register_config_source(name: str) -> Callable[[ConfigSourceFactory], ConfigSourceFactory]:+ """Decorator registering a source factory under ``name``."""+ normalized = _normalize(name)++ def deco(factory: ConfigSourceFactory) -> ConfigSourceFactory:+ if normalized in _FACTORIES:+ existing = getattr(_FACTORIES[normalized], "__name__", "?")+ raise ValueError(f"config source {normalized!r} is already registered by {existing}")+ _FACTORIES[normalized] = factory+ logger.debug("Registered config source: %s", normalized)+ return factory++ return deco+++def create_config_source(name: str, ctx: ConfigSourceContext) -> ConfigSource:+ """Construct a source by name, importing plugins on demand.++ Unknown names raise ``ValueError`` after trying entry points.+ """+ normalized = _normalize(name)+ if normalized == "memory":+ importlib.import_module(f"openviking.config.source.{normalized}_source")+ if normalized not in _FACTORIES:+ _load_from_entry_points(normalized)+ factory = _FACTORIES.get(normalized)+ if factory is None:+ available = ", ".join(sorted(_FACTORIES)) or "<none>"+ raise ValueError(+ f"Unknown config source {name!r}. Available: {available}. "+ "Install a plugin exposing it via the 'openviking.config_source' "+ "entry point or set runtime_config.module."+ )+ return factory(ctx)+++def load_config_source_module(module_path: str) -> None:+ """Import an ``ov.conf``-specified module so it can self-register."""+ importlib.import_module(module_path)+++def _load_from_entry_points(name: str) -> None:+ from importlib.metadata import entry_points++ eps = entry_points(group=ENTRY_POINT_GROUP)+ for ep in eps:+ if _normalize(ep.name) == name:+ factory = ep.load()+ if name not in _FACTORIES:+ register_config_source(name)(factory)+ return+++def _normalize(name: str) -> str:+ normalized = name.strip().lower()+ if not normalized:+ raise ValueError("config source name must not be empty")+ return normalizeddiff --git a/openviking/config/validate.py b/openviking/config/validate.pynew file mode 100644index 000000000..0317b1ff3--- /dev/null+++ b/openviking/config/validate.py@@ -0,0 +1,180 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Model-agnostic PATCH request validation.++The admin PATCH endpoints accept a nested dict and must reject anything the+runtime config surface does not allow *before* any merge or persistence. This+module enforces the structural rules that do not depend on the concrete config+model, so a single generic router can serve every section without per-field+branches:++1. top-level sections must be declared with :func:`RuntimeField`. If a section+ has marked descendants, input paths are restricted to those declarations;+ otherwise the whole section is accepted for subsequent model validation;+2. cluster-vs-account scope is confined by *which model is validated against*+ (``OpenVikingConfig`` for a cluster PATCH, ``AccountConfig`` for an account+ PATCH) — there is no per-field scope flag;+3. objects merge recursively, arrays replace wholesale (a list value is a leaf);+4. ``None`` is the three-state "delete this override" and is allowed on any+ surface leaf path, except a ``dynamic=False`` field on a non-creating PATCH.++Type and cross-field validation of the *merged* result still happens later when+the merged dict is parsed back into the real config model; this layer only gates+the request shape, not the semantic validity of individual values.+"""++from __future__ import annotations++import types+import typing+from typing import Any++from pydantic import BaseModel++from openviking_cli.utils.config.runtime_field import (+ collect_frozen_paths,+ collect_runtime_field_paths,+)+++class ConfigPatchError(ValueError):+ """Raised when a PATCH request references a field the API may not modify."""++ def __init__(self, message: str, *, path: tuple[str, ...] | None = None) -> None:+ self.path = path+ if path:+ message = f"{message} (at '{'.'.join(path)}')"+ super().__init__(message)+++def validate_patch(+ model: type[BaseModel],+ patch: dict[str, Any],+ *,+ creating: bool = False,+) -> None:+ """Validate a three-state PATCH request against ``model``.++ ``model`` is the scope's config model: pass ``OpenVikingConfig`` for a+ cluster PATCH and ``AccountConfig`` for an account PATCH. Only that model's+ ``RuntimeField`` surface paths are accepted, so scope isolation falls out of+ the model choice with no per-field flag.++ ``creating=False`` (the default, i.e. an update to an existing object) also+ rejects any path under a ``dynamic=False`` field: those may only be set at+ creation time and are immutable afterwards. ``creating=True`` skips that gate+ so initial-settings validation can accept them.++ Raises :class:`ConfigPatchError` on the first offending path. A valid patch+ returns ``None``.+ """+ if not isinstance(patch, dict):+ raise ConfigPatchError("patch must be a JSON object")+ allowed = collect_runtime_field_paths(model)+ _walk(patch, (), allowed, model)+ if not creating:+ _reject_frozen(patch, (), collect_frozen_paths(model))+++def _reject_frozen(+ node: dict[str, Any],+ prefix: tuple[str, ...],+ frozen: set[tuple[str, ...]],+) -> None:+ """Reject any PATCH path that touches (or nests under) a create-only field."""+ if not frozen:+ return+ for key, value in node.items():+ path = prefix + (key,)+ if path in frozen:+ raise ConfigPatchError(+ "field is create-only and cannot be changed after creation", path=path+ )+ if isinstance(value, dict):+ _reject_frozen(value, path, frozen)+++def _walk(+ node: dict[str, Any],+ prefix: tuple[str, ...],+ allowed: set[tuple[str, ...]],+ root_model: type[BaseModel],+) -> None:+ for key, value in node.items():+ if not isinstance(key, str):+ raise ConfigPatchError("patch keys must be strings", path=prefix)+ path = prefix + (key,)+ if path not in allowed:+ raise ConfigPatchError("field is not modifiable by the config API", path=path)+ # None (delete) and non-dict values (scalar / list-replace) are leaves.+ if value is None or not isinstance(value, dict):+ continue+ # Sections with no marked descendants are validated as a whole by the+ # model constructor. Keep API input strict even though persisted config+ # models intentionally ignore unknown fields for version compatibility.+ if _has_children(path, allowed):+ _walk(value, path, allowed, root_model)+ else:+ nested_model = _model_at_path(root_model, path)+ if nested_model is not None:+ _reject_unknown_model_fields(value, path, nested_model)+++def _has_children(prefix: tuple[str, ...], allowed: set[tuple[str, ...]]) -> bool:+ plen = len(prefix)+ return any(len(p) > plen and p[:plen] == prefix for p in allowed)+++def _model_at_path(+ root_model: type[BaseModel],+ path: tuple[str, ...],+) -> type[BaseModel] | None:+ model = root_model+ for part in path:+ field = model.model_fields.get(part)+ if field is None:+ return None+ nested = _unwrap_model(field.annotation)+ if nested is None:+ return None+ model = nested+ return model+++def _reject_unknown_model_fields(+ node: dict[str, Any],+ prefix: tuple[str, ...],+ model: type[BaseModel],+) -> None:+ accepted: dict[str, str] = {}+ for field_name, field in model.model_fields.items():+ accepted[field_name] = field_name+ for alias in (field.alias, field.validation_alias):+ if isinstance(alias, str):+ accepted[alias] = field_name++ for key, value in node.items():+ field_name = accepted.get(key)+ path = prefix + (key,)+ if field_name is None:+ raise ConfigPatchError("field is not recognized", path=path)+ if not isinstance(value, dict):+ continue+ nested = _unwrap_model(model.model_fields[field_name].annotation)+ if nested is not None:+ _reject_unknown_model_fields(value, path, nested)+++def _unwrap_model(annotation: Any) -> type[BaseModel] | None:+ origin = typing.get_origin(annotation)+ if origin in (typing.Union, types.UnionType):+ for arg in typing.get_args(annotation):+ if arg is type(None):+ continue+ nested = _unwrap_model(arg)+ if nested is not None:+ return nested+ return None+ if isinstance(annotation, type) and issubclass(annotation, BaseModel):+ return annotation+ return Nonediff --git a/openviking/parse/accessors/git_accessor.py b/openviking/parse/accessors/git_accessor.pyindex 8b049fe61..6e34599e2 100644--- a/openviking/parse/accessors/git_accessor.py+++ b/openviking/parse/accessors/git_accessor.py@@ -31,6 +31,7 @@ from openviking.utils.code_hosting_utils import ()from openviking.utils.git_auth import (build_git_http_auth_env,+ is_git_https_url,parse_git_http_auth_config,raise_git_auth_error,)@@ -133,10 +134,21 @@ class GitAccessor(DataAccessor):if auth_config is not None:git_env = build_git_http_auth_env(auth_config, repo_url)if self._is_github_url(repo_url) and auth_config is None:+ github_token = kwargs.get("github_token") or os.environ.get("GITHUB_TOKEN")+ if github_token and is_git_https_url(repo_url):+ github_auth = parse_git_http_auth_config(+ {"token": github_token},+ repo_url,+ )+ assert github_auth is not None+ git_env = build_git_http_auth_env(github_auth, repo_url)# Try GitHub ZIP API first, fall back to git clonetry:local_dir, repo_name = await self._github_zip_download(- repo_url, branch or commit, temp_local_dir+ repo_url,+ branch or commit,+ temp_local_dir,+ github_token=github_token,)except Exception as zip_exc:logger.warning(@@ -444,6 +456,8 @@ class GitAccessor(DataAccessor):repo_url: str,branch: Optional[str],target_dir: str,+ *,+ github_token: Optional[str] = None,) -> Tuple[Path, str]:"""Download a GitHub repo as a ZIP archive and extract it."""repo_name = self._get_repo_name(repo_url)@@ -465,10 +479,11 @@ class GitAccessor(DataAccessor):extract_dir = os.path.join(target_dir, "_extracted")os.makedirs(extract_dir, exist_ok=True)+ github_token = github_token or os.environ.get("GITHUB_TOKEN")+# Download (blocking HTTP; run in thread pool)def _download() -> None:headers = {"User-Agent": "OpenViking"}- github_token = os.environ.get("GITHUB_TOKEN")if github_token:headers["Authorization"] = f"token {github_token}"diff --git a/openviking/retrieve/hierarchical_retriever.py b/openviking/retrieve/hierarchical_retriever.pyindex 65bc2ed1f..1ec3c0111 100644--- a/openviking/retrieve/hierarchical_retriever.py+++ b/openviking/retrieve/hierarchical_retriever.py@@ -232,7 +232,7 @@ class HierarchicalRetriever:telemetry.count("vector.scanned", len(global_results))leaf_results: List[Dict[str, Any]] = []- if self.vector_store._acl_enabled(ctx) and (level is None or 2 in level):+ if await self.vector_store._acl_enabled(ctx) and (level is None or 2 in level):leaf_results = await vector_proxy.search_in_tenant(query_vector=query_vector,sparse_query_vector=sparse_query_vector,diff --git a/openviking/server/account_settings.py b/openviking/server/account_settings.pydeleted file mode 100644index 2d20fab5a..000000000--- a/openviking/server/account_settings.py+++ /dev/null@@ -1,205 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: AGPL-3.0-"""Persistent, account-scoped runtime settings."""--from __future__ import annotations--import json-from typing import Any, Optional--from pydantic import BaseModel--from openviking.pyagfs import AGFSAlreadyExistsError, AGFSNotFoundError, AsyncAGFSClient-from openviking.pyagfs.async_client import fs_ctx_from_agfs_path-from openviking.storage.errors import LockAcquisitionError, ResourceBusyError-from openviking.storage.viking_fs import VikingFS-from openviking_cli.exceptions import InvalidArgumentError-from openviking_cli.session.user_id import validate_account_id-from openviking_cli.utils.logger import get_logger--ACCOUNT_SETTINGS_PATH_TEMPLATE = "/local/{account_id}/_system/setting.json"-ACCOUNT_SETTINGS_BACKUP_PATH_TEMPLATE = "/local/{account_id}/_system/setting.backup.json"--logger = get_logger(__name__)---class AccountAgentEvolutionSettings(BaseModel):- """Account-scoped Agent Evolution override."""-- enabled: bool---class AccountAclSettings(BaseModel):- """Account-scoped ACL switch."""-- enabled: bool = False---class AccountSettings(BaseModel):- """Persisted account overrides.-- Unknown persisted fields are ignored for upgrade compatibility.- """-- agent_evolution: Optional[AccountAgentEvolutionSettings] = None- acl: Optional[AccountAclSettings] = None---class AccountSettingsPatch(BaseModel):- """Allowlisted account settings accepted by the update API."""-- agent_evolution: Optional[AccountAgentEvolutionSettings] = None- acl: Optional[AccountAclSettings] = None-- model_config = {"extra": "forbid"}---def account_settings_path(account_id: str) -> str:- _validate_account_id(account_id)- return ACCOUNT_SETTINGS_PATH_TEMPLATE.format(account_id=account_id)---def account_settings_backup_path(account_id: str) -> str:- _validate_account_id(account_id)- return ACCOUNT_SETTINGS_BACKUP_PATH_TEMPLATE.format(account_id=account_id)---def _validate_account_id(account_id: str) -> None:- error = validate_account_id(account_id)- if error:- raise InvalidArgumentError(error)---def _decode_read_result(result: Any) -> bytes:- if isinstance(result, bytes):- return result- content = getattr(result, "content", None)- if isinstance(content, bytes):- return content- if isinstance(content, str):- return content.encode("utf-8")- if isinstance(result, str):- return result.encode("utf-8")- raise InvalidArgumentError("account settings content must be JSON text")---def _parse_account_settings(raw: bytes) -> AccountSettings:- try:- payload = json.loads(raw.decode("utf-8"))- except (UnicodeDecodeError, json.JSONDecodeError) as exc:- raise InvalidArgumentError(f"Invalid account settings JSON: {exc}") from exc- if not isinstance(payload, dict):- raise InvalidArgumentError("account settings must be an object")- try:- return AccountSettings.model_validate(payload)- except Exception as exc:- raise InvalidArgumentError(str(exc)) from exc---async def _read_raw(client: AsyncAGFSClient, path: str) -> Optional[bytes]:- try:- return _decode_read_result(await client.read(path))- except AGFSNotFoundError:- return None---async def read_account_settings(viking_fs: VikingFS, account_id: str) -> AccountSettings:- """Read the persisted overrides for one account."""- path = account_settings_path(account_id)- raw = await _read_raw(AsyncAGFSClient(viking_fs.agfs), path)- return AccountSettings() if raw is None else _parse_account_settings(raw)---def effective_agent_evolution_enabled(- settings: AccountSettings,- *,- default_enabled: bool,-) -> bool:- if settings.agent_evolution is None:- return bool(default_enabled)- return settings.agent_evolution.enabled---def effective_acl_enabled(settings: AccountSettings) -> bool:- if settings.acl is None:- return False- return settings.acl.enabled---async def update_account_settings(- viking_fs: VikingFS,- account_id: str,- patch: AccountSettingsPatch,-) -> AccountSettings:- """Apply a locked, backed-up update to one account's settings."""- path = account_settings_path(account_id)- backup_path = account_settings_backup_path(account_id)- client = AsyncAGFSClient(viking_fs.agfs)- try:- lease = await client.pathlock_acquire_exact(path, timeout_secs=10.0)- except LockAcquisitionError as exc:- raise ResourceBusyError(- "Another account settings update is in progress. Please retry.",- uri=path,- conflict_type="account_settings_busy",- ) from exc-- fs_ctx = fs_ctx_from_agfs_path(path)- lease_ref = getattr(lease, "lease_ref", None) or getattr(lease, "id", None)- if isinstance(lease, dict):- lease_ref = lease.get("lease_ref", lease_ref)- if isinstance(lease_ref, str) and lease_ref:- fs_ctx["lease_ref"] = lease_ref-- try:- current_raw = await _read_raw(client, path)- current = AccountSettings() if current_raw is None else _parse_account_settings(current_raw)- updated = current.model_copy(deep=True)- if patch.agent_evolution is not None:- updated.agent_evolution = patch.agent_evolution.model_copy(deep=True)- if patch.acl is not None:- updated.acl = patch.acl.model_copy(deep=True)- if updated == current:- if patch.acl is not None:- if viking_fs.acl_manager is None:- raise RuntimeError("ACL is not initialized")- viking_fs.acl_manager.set_enabled(account_id, updated.acl.enabled)- return current-- encoded = json.dumps(- updated.model_dump(exclude_none=True),- ensure_ascii=False,- indent=2,- sort_keys=True,- ).encode("utf-8")- try:- await client.ensure_parent_dirs(path)- except AGFSAlreadyExistsError:- pass-- if current_raw is not None:- await client.write(backup_path, current_raw)-- try:- await client.write(path, encoded, fs_ctx=fs_ctx)- except Exception:- try:- if current_raw is not None:- await client.write(path, current_raw, fs_ctx=fs_ctx)- else:- await client.rm(path, fs_ctx=fs_ctx)- except AGFSNotFoundError:- pass- except Exception:- logger.exception(- "Failed to roll back account settings for account %s",- account_id,- )- raise- if patch.acl is not None:- if viking_fs.acl_manager is None:- raise RuntimeError("ACL is not initialized")- viking_fs.acl_manager.set_enabled(account_id, updated.acl.enabled)- return updated- finally:- await client.pathlock_release(lease)diff --git a/openviking/server/agent_evolution_config.py b/openviking/server/agent_evolution_config.pydeleted file mode 100644index 0c2c33ab1..000000000--- a/openviking/server/agent_evolution_config.py+++ /dev/null@@ -1,103 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: AGPL-3.0-"""Live access to account-scoped Agent Evolution settings."""--from __future__ import annotations--from pathlib import Path-from threading import Lock-from typing import Optional--from openviking.server.account_settings import (- effective_agent_evolution_enabled,- read_account_settings,-)-from openviking.server.config import ServerConfig-from openviking.storage.viking_fs import VikingFS-from openviking_cli.utils.config import load_json_config-from openviking_cli.utils.logger import get_logger--logger = get_logger(__name__)---class AgentEvolutionConfigProvider:- """Resolve ov.conf defaults with persistent account overrides."""-- def __init__(- self,- *,- default_enabled: bool,- viking_fs: VikingFS,- config_path: Optional[str | Path] = None,- ) -> None:- self._last_valid_enabled = bool(default_enabled)- self._last_valid_account_overrides: dict[str, Optional[bool]] = {}- self._viking_fs = viking_fs- self._config_path = Path(config_path).expanduser() if config_path else None- self._lock = Lock()-- def set_default_enabled(self, enabled: bool) -> None:- with self._lock:- self._last_valid_enabled = bool(enabled)-- def _default_enabled(self) -> bool:- with self._lock:- fallback = self._last_valid_enabled-- config_path = self._config_path- if config_path is None:- return fallback-- try:- payload = load_json_config(config_path)- if not isinstance(payload, dict):- raise ValueError("config root must be an object")- server_config = payload.get("server", {})- if server_config is None:- server_config = {}- if not isinstance(server_config, dict):- raise ValueError("server must be an object")- agent_evolution = ServerConfig.model_validate(server_config).agent_evolution- enabled = agent_evolution.enabled- except OSError as exc:- logger.warning(- "Failed to access Agent Evolution config file %s, using last valid value: %s",- config_path,- exc,- )- return fallback- except (KeyError, TypeError, ValueError) as exc:- logger.warning(- "Failed to read Agent Evolution config from %s, using last valid value: %s",- config_path,- exc,- )- return fallback-- with self._lock:- self._last_valid_enabled = enabled- return enabled-- async def is_enabled(self, account_id: str) -> bool:- default_enabled = self._default_enabled()- try:- settings = await read_account_settings(self._viking_fs, account_id)- enabled = effective_agent_evolution_enabled(- settings,- default_enabled=default_enabled,- )- override = (- settings.agent_evolution.enabled if settings.agent_evolution is not None else None- )- with self._lock:- self._last_valid_account_overrides[account_id] = override- return enabled- except Exception as exc:- logger.warning(- "Failed to read Agent Evolution settings for account %s, using last valid value: %s",- account_id,- exc,- )- with self._lock:- override = self._last_valid_account_overrides.get(account_id)- return default_enabled if override is None else overridediff --git a/openviking/server/app.py b/openviking/server/app.pyindex 01d020d45..e99cfd3e4 100644--- a/openviking/server/app.py+++ b/openviking/server/app.py@@ -160,16 +160,8 @@ async def _initialize_runtime_state() -> None:"""Initialize service and auth dependencies before traffic is accepted."""await service.initialize()+ await service.apply_agent_evolution_config()await _initialize_auth_plugin(app, service, config)- manager = app.state.api_key_manager- if manager is not None:- await service.load_acl_settings(- [- item["account_id"]- for item in manager.get_accounts()- if item["account_id"] != service.user.account_id- ]- )from openviking.service.deletion import setup_deletionapp.state.deletion_service = await setup_deletion(@@ -261,7 +253,7 @@ def create_app(Args:config: Server configuration. If None, loads from default location.service: Pre-initialized OpenVikingService (optional).- config_path: Resolved ov.conf path used for live configuration reload.+ config_path: Resolved ov.conf path used for startup configuration.Returns:FastAPI application instance@@ -299,7 +291,9 @@ def create_app(if callable(usage_reporter_setter):usage_reporter_setter(_get_usage_reporter())- agent_evolution_setter = getattr(sessions, "set_agent_evolution_config", None)+ agent_evolution_setter = getattr(service_obj, "set_agent_evolution_config", None)+ if not callable(agent_evolution_setter):+ agent_evolution_setter = getattr(sessions, "set_agent_evolution_config", None)if callable(agent_evolution_setter):agent_evolution_setter(config.agent_evolution)@@ -311,16 +305,6 @@ def create_app(if callable(user_memory_policy_setter):user_memory_policy_setter(config.user_config_defaults.memory_policy)- agent_evolution_path_setter = getattr(- sessions,- "set_agent_evolution_config_path",- None,- )- if callable(agent_evolution_path_setter):- agent_evolution_path_setter(- str(resolved_config_path) if resolved_config_path is not None else None- )-if service is not None:_configure_session_runtime(service)diff --git a/openviking/server/config.py b/openviking/server/config.pyindex 2e4033d68..55495160f 100644--- a/openviking/server/config.py+++ b/openviking/server/config.py@@ -13,6 +13,7 @@ from openviking.server.auth.oidc_config import OIDCConfigfrom openviking.server.auth.registry import get_registryfrom openviking.server.identity import AuthModefrom openviking_cli.utils import get_logger+from openviking_cli.utils.config.agent_evolution_config import AgentEvolutionConfigfrom openviking_cli.utils.config.config_loader import (load_json_config,resolve_config_path,@@ -124,12 +125,6 @@ class AddTargetsConfig(BaseModel):)-class AgentEvolutionConfig(BaseModel):- """Default Agent Evolution setting for accounts without an override."""-- enabled: bool = False--class DeprecatedUserAgentEvolutionConfig(BaseModel):"""Parse-only compatibility for legacy per-user configuration files."""diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.pyindex 3ed9444be..5d3003bee 100644--- a/openviking/server/routers/admin.py+++ b/openviking/server/routers/admin.py@@ -3,19 +3,13 @@"""Admin endpoints for OpenViking multi-tenant HTTP Server."""import asyncio-from typing import Optional+from typing import Any, Optionalfrom fastapi import APIRouter, Body, Depends, Path, Query, Request-from pydantic import BaseModel--from openviking.server.account_settings import (- AccountAgentEvolutionSettings,- AccountSettings,- AccountSettingsPatch,- effective_acl_enabled,- read_account_settings,- update_account_settings,-)+from pydantic import BaseModel, Field++from openviking.config.scope import ConfigScope+from openviking.config.validate import ConfigPatchErrorfrom openviking.server.api_keys.models import validate_account_user_rolefrom openviking.server.auth import (get_api_key_manager_or_raise,@@ -71,6 +65,9 @@ class CreateAccountRequest(BaseModel):admin_user_id: strseed: str | None = Noneuser_config: UserConfig | None = None+ # Optional initial AccountConfig override, validated against the active+ # account-level runtime field surface before the account is created.+ settings: dict[str, Any] | None = Noneclass RegisterUserRequest(BaseModel):@@ -102,6 +99,44 @@ class SetAgentEvolutionRequest(BaseModel):enabled: bool+class LegacyAccountAgentEvolutionSettings(BaseModel):+ """Legacy Agent Evolution request shape; enabled was required."""++ enabled: bool++ model_config = {"extra": "forbid"}+++class LegacyAccountAclSettings(BaseModel):+ """Legacy ACL request shape; an empty object meant disabled."""++ enabled: bool = False++ model_config = {"extra": "forbid"}+++class LegacyAccountSettingsPatch(BaseModel):+ """Compatibility parser for the original account settings endpoint."""++ agent_evolution: Optional[LegacyAccountAgentEvolutionSettings] = None+ acl: Optional[LegacyAccountAclSettings] = None++ model_config = {"extra": "forbid"}+++class ConfigPatchRequest(BaseModel):+ """A three-state sparse PATCH over a config scope's ``RuntimeField`` surface.++ The body is an arbitrary nested object; structural validity (which paths may+ be touched, create-only gating) is enforced by the runtime config manager's+ ``validate_request`` hook, and semantic validity by re-parsing the merged+ config. ``extra`` is intentionally permissive here because the allowlist is+ the model surface, not this envelope.+ """++ settings: dict[str, Any] = Field(default_factory=dict)++class UserSettingsPatch(BaseModel):memory_policy: Optional[dict]@@ -114,7 +149,7 @@ def _agent_evolution_account_id(ctx: RequestContext) -> str:return ctx.account_id[email protected]("/agent-evolution")[email protected]("/agent-evolution", deprecated=True)@require_auth_root_or_adminasync def get_agent_evolution_status(request: Request,@@ -130,7 +165,7 @@ async def get_agent_evolution_status()[email protected]("/agent-evolution")[email protected]("/agent-evolution", deprecated=True)@require_auth_root_or_adminasync def set_agent_evolution_status(body: SetAgentEvolutionRequest,@@ -143,11 +178,13 @@ async def set_agent_evolution_status(service = get_service()if service.viking_fs is None:raise FailedPreconditionError("OpenViking service is not initialized.")- await update_account_settings(- service.viking_fs,- account_id,- AccountSettingsPatch(agent_evolution=AccountAgentEvolutionSettings(enabled=body.enabled)),- )+ runtime_config = _get_runtime_config_manager()+ try:+ await runtime_config.patch_account(+ account_id, {"agent_evolution": {"enabled": body.enabled}}+ )+ except (ConfigPatchError, ValueError) as exc:+ raise InvalidArgumentError(str(exc)) from excenabled = await service.sessions.get_agent_evolution_enabled(account_id)return Response(status="ok",@@ -160,6 +197,15 @@ def _get_api_key_manager(request: Request):return get_api_key_manager_or_raise(request)+def _get_runtime_config_manager():+ """Return the live runtime config manager, or fail with a clear precondition."""+ service = get_service()+ manager = service.runtime_config_manager+ if manager is None:+ raise FailedPreconditionError("Runtime config manager is not initialized.")+ return manager++def _should_expose_user_key(request: Request) -> bool:config = getattr(request.app.state, "config", None)if not isinstance(config, ServerConfig):@@ -199,9 +245,20 @@ async def _check_account_exists(async def _account_settings_result(account_id: str,- settings: AccountSettings,+ acl_setting: Any,+ overrides: dict,) -> dict:+ """Build the account settings response.++ ``settings`` is the effective view of the two legacy switches; ``overrides``+ projects only their explicit account values to preserve the original response.+ """enabled = await get_service().sessions.get_agent_evolution_enabled(account_id)+ legacy_overrides = {+ key: overrides[key]+ for key in ("agent_evolution", "acl")+ if key in overrides+ }return {"account_id": account_id,"settings": {@@ -209,10 +266,10 @@ async def _account_settings_result("enabled": enabled,},"acl": {- "enabled": effective_acl_enabled(settings),+ "enabled": acl_setting.enabled if acl_setting is not None else False,},},- "overrides": settings.model_dump(exclude_none=True),+ "overrides": legacy_overrides,}@@ -255,7 +312,65 @@ async def _write_initial_user_config(await write_user_config(service.viking_fs, user_ctx, user_config)-async def _check_user_exists(request: Request, account_id: str, user_id: str, manager=None) -> None:+async def _rollback_account_creation(+ service,+ manager,+ account_id: str,+ runtime_config,+ deletion_service=None,+ actor: RequestContext | None = None,+) -> None:+ """Compensate resources created after the account registry entry.++ ``APIKeyManager.create_account`` already rolls back its own registry writes.+ This covers the later workspace, user-config and runtime-config steps when+ one of them fails.+ """+ if deletion_service is not None and actor is not None:+ try:+ await deletion_service.delete_now(account_id, actor=actor)+ return+ except Exception:+ logger.exception(+ "Synchronous account cleanup failed for %s; durable deletion remains queued",+ account_id,+ )+ return++ rollback_errors: list[Exception] = []+ if runtime_config is not None:+ try:+ await runtime_config.delete_account(account_id)+ except Exception as exc:+ rollback_errors.append(exc)+ logger.exception("Failed to roll back runtime config for account %s", account_id)++ viking_fs = getattr(service, "viking_fs", None)+ agfs = getattr(viking_fs, "_async_agfs", None)+ if agfs is not None:+ try:+ await agfs.rm(f"/local/{account_id}", recursive=True)+ except Exception as exc:+ rollback_errors.append(exc)+ logger.exception("Failed to roll back workspace for account %s", account_id)++ try:+ await manager.delete_account(account_id)+ except Exception as exc:+ rollback_errors.append(exc)+ logger.exception("Failed to roll back account registry entry for %s", account_id)++ if rollback_errors:+ logger.error(+ "Account creation rollback for %s completed with %d error(s)",+ account_id,+ len(rollback_errors),+ )+++async def _check_user_exists(+ request: Request, account_id: str, user_id: str, manager=None+) -> None:manager = manager or _get_api_key_manager(request)if not manager.has_user(account_id, user_id):raise NotFoundError(user_id, "user")@@ -324,14 +439,42 @@ async def create_account(role=Role.ADMIN,)await _validate_initial_user_config(service, account_ctx, body.user_config)+ # Reject bad initial config before any storage is created, so a failed+ # create leaves nothing behind. This validates the active account runtime+ # field surface without persisting. Only needed when initial settings exist.+ runtime_config = None+ if body.settings:+ runtime_config = _get_runtime_config_manager()+ try:+ runtime_config.validate_initial_settings(body.account_id, body.settings)+ except (ConfigPatchError, ValueError) as exc:+ raise InvalidArgumentError(str(exc)) from excmanager = _get_api_key_manager(request)user_key = await manager.create_account(body.account_id,body.admin_user_id,seed=body.seed,)- await service.initialize_account_workspace(account_ctx)- await _write_initial_user_config(service, account_ctx, body.user_config)+ try:+ await service.initialize_account_workspace(account_ctx)+ await _write_initial_user_config(service, account_ctx, body.user_config)+ if body.settings and runtime_config is not None:+ # Persist the pre-validated override.+ await runtime_config.patch_account(+ body.account_id,+ body.settings,+ creating=True,+ )+ except BaseException:+ await _rollback_account_creation(+ service,+ manager,+ body.account_id,+ runtime_config,+ deletion_service=getattr(request.app.state, "deletion_service", None),+ actor=ctx,+ )+ raiseresult = {"account_id": body.account_id,"admin_user_id": body.admin_user_id,@@ -423,44 +566,77 @@ async def delete_account(return Response(status="ok", result=result)[email protected]("/accounts/{account_id}/settings")[email protected]("/accounts/{account_id}/settings", deprecated=True)@require_auth_root_or_adminasync def get_account_settings(request: Request,account_id: str = Path(..., description="Account ID"),ctx: RequestContext = Depends(get_request_context),):- """Return effective and explicitly overridden settings for one account."""+ """Return the original effective-switch and override response shape."""_check_account_access(ctx, account_id)await _check_account_exists(request, account_id)- service = get_service()- if service.viking_fs is None:- raise FailedPreconditionError("OpenViking service is not initialized.")- settings = await read_account_settings(service.viking_fs, account_id)+ runtime_config = _get_runtime_config_manager()+ acl_setting = await runtime_config.get_account(account_id, "acl")+ overrides = await runtime_config.get_settings(ConfigScope.account(account_id))return Response(status="ok",- result=await _account_settings_result(account_id, settings),+ result=await _account_settings_result(account_id, acl_setting, overrides),)[email protected]("/accounts/{account_id}/settings")[email protected]("/accounts/{account_id}/settings", deprecated=True)@require_auth_root_or_adminasync def patch_account_settings(- body: AccountSettingsPatch,request: Request,+ body: LegacyAccountSettingsPatch,account_id: str = Path(..., description="Account ID"),ctx: RequestContext = Depends(get_request_context),):- """Update allowlisted hot-reloadable settings for one account."""+ """Apply the original account settings semantics through the new manager.++ Missing and null fields are both no-ops. Present objects replace the legacy+ section after model validation; notably an empty ACL object means disabled.+ """_check_account_access(ctx, account_id)await _check_account_exists(request, account_id)service = get_service()if service.viking_fs is None:raise FailedPreconditionError("OpenViking service is not initialized.")- settings = await update_account_settings(service.viking_fs, account_id, body)+ runtime_config = _get_runtime_config_manager()+ patch = body.model_dump(exclude_none=True)+ try:+ if patch:+ await runtime_config.patch_account(account_id, patch)+ except (ConfigPatchError, ValueError) as exc:+ raise InvalidArgumentError(str(exc)) from exc+ acl_setting = await runtime_config.get_account(account_id, "acl")+ overrides = await runtime_config.get_settings(ConfigScope.account(account_id))+ return Response(+ status="ok",+ result=await _account_settings_result(account_id, acl_setting, overrides),+ )+++# ---- Runtime configuration -------------------------------------------------++[email protected]("/accounts/{account_id}/configuration")+@require_auth_root_or_admin+async def get_account_configuration(+ request: Request,+ account_id: str = Path(..., description="Account ID"),+ ctx: RequestContext = Depends(get_request_context),+):+ """Return this account layer's explicit runtime configuration."""+ _check_account_access(ctx, account_id)+ await _check_account_exists(request, account_id)+ settings = await _get_runtime_config_manager().get_settings(+ ConfigScope.account(account_id)+ )return Response(status="ok",- result=await _account_settings_result(account_id, settings),+ result={"account_id": account_id, "settings": settings},)@@ -571,6 +747,59 @@ async def reset_memory_template()[email protected]("/accounts/{account_id}/configuration")+@require_auth_root_or_admin+async def patch_account_configuration(+ body: ConfigPatchRequest,+ request: Request,+ account_id: str = Path(..., description="Account ID"),+ ctx: RequestContext = Depends(get_request_context),+):+ """Apply a three-state PATCH to the account configuration layer."""+ _check_account_access(ctx, account_id)+ await _check_account_exists(request, account_id)+ try:+ await _get_runtime_config_manager().patch_account(account_id, body.settings)+ except (ConfigPatchError, ValueError) as exc:+ raise InvalidArgumentError(str(exc)) from exc+ settings = await _get_runtime_config_manager().get_settings(+ ConfigScope.account(account_id)+ )+ return Response(+ status="ok",+ result={"account_id": account_id, "settings": settings},+ )++[email protected]("/configuration")+@require_auth_root+async def get_cluster_configuration(+ request: Request,+ ctx: RequestContext = Depends(get_request_context),+):+ """Return the cluster layer's explicit runtime configuration."""+ runtime_config = _get_runtime_config_manager()+ settings = await runtime_config.get_settings(ConfigScope.cluster())+ return Response(status="ok", result={"settings": settings})++[email protected]("/configuration")+@require_auth_root+async def patch_cluster_configuration(+ body: ConfigPatchRequest,+ request: Request,+ ctx: RequestContext = Depends(get_request_context),+):+ """Apply a three-state PATCH to the cluster configuration layer."""+ runtime_config = _get_runtime_config_manager()+ try:+ await runtime_config.patch_cluster(body.settings)+ except (ConfigPatchError, ValueError) as exc:+ raise InvalidArgumentError(str(exc)) from exc+ settings = await runtime_config.get_settings(ConfigScope.cluster())+ return Response(status="ok", result={"settings": settings})++# ---- User endpoints ----diff --git a/openviking/service/core.py b/openviking/service/core.pyindex 455833441..ee9fb37e2 100644--- a/openviking/service/core.py+++ b/openviking/service/core.py@@ -14,10 +14,6 @@ from openviking.core.directories import DirectoryInitializerfrom openviking.privacy import UserPrivacyConfigServicefrom openviking.resource.uri_mutation_coordinator import UriMutationCoordinatorfrom openviking.resource.watch_scheduler import WatchScheduler-from openviking.server.account_settings import (- effective_acl_enabled,- read_account_settings,-)from openviking.server.identity import RequestContext, Rolefrom openviking.service.agent_evolution_service import AgentEvolutionServicefrom openviking.service.compile_service import CompileService@@ -52,6 +48,7 @@ from openviking_cli.exceptions import InvalidArgumentError, NotInitializedErrorfrom openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils import get_loggerfrom openviking_cli.utils.config import OPENVIKING_ENABLE_RECORDER_ENV, get_openviking_config+from openviking_cli.utils.config.agent_evolution_config import AgentEvolutionConfigfrom openviking_cli.utils.config.git_config import GitConfigfrom openviking_cli.utils.config.memory_config import SessionAutoCommitConfigfrom openviking_cli.utils.config.open_viking_config import initialize_openviking_config@@ -87,6 +84,7 @@ class OpenVikingService:path=path,)self._config = config+ self._agent_evolution_base_config = config.agent_evolution.model_copy(deep=True)self._user = user or UserIdentifier(config.default_account, config.default_user)# Infrastructure@@ -104,6 +102,7 @@ class OpenVikingService:self._session_auto_commit_scheduler: Optional[SessionAutoCommitScheduler] = Noneself._encryptor: Optional[Any] = Noneself._privacy_config_service: Optional[UserPrivacyConfigService] = None+ self._runtime_config_manager: Optional[Any] = Noneself._data_dir_lock_acquired = Falseself._data_dir_lock_path: Optional[str] = None@@ -213,17 +212,61 @@ class OpenVikingService:binding_config, self._encryptor = build_runtime_ragfs_binding_config(self._config)return binding_config- async def load_acl_settings(self, account_ids: list[str]) -> None:- if self._viking_fs is None:- raise NotInitializedError("VikingFS")+ @property+ def runtime_config_manager(self) -> Optional[Any]:+ """The runtime config manager bound to the cluster + account models."""+ return self._runtime_config_manager++ def set_agent_evolution_config(self, config: AgentEvolutionConfig) -> None:+ """Set the legacy server value used as the cluster startup baseline."""+ self._agent_evolution_base_config = config.model_copy(deep=True)+ self._session_service.set_agent_evolution_config(config)++ async def apply_agent_evolution_config(self) -> None:+ """Apply the legacy server value to an already initialized manager."""+ manager = self._runtime_config_manager+ if manager is None:+ return+ base_config = self._config.model_copy(+ update={+ "agent_evolution": self._agent_evolution_base_config.model_copy(+ deep=True+ )+ }+ )+ await manager.replace_base_config(base_config)++ async def _init_runtime_config_manager(self) -> None:+ """Build and start the runtime config manager over the AGFS config source.++ Publishing a cluster override swaps the global ``OpenVikingConfig``+ singleton, so it is available process-wide through+ ``get_openviking_config`` exactly as before; account overrides are cached+ per account and loaded on demand by field.+ """+ from openviking.config.binding import build_runtime_config_manager+ from openviking.pyagfs import AsyncAGFSClient++ if self._agfs_client is None:+ raise RuntimeError("AGFS client not initialized")+ base_config = self._config.model_copy(+ update={+ "agent_evolution": self._agent_evolution_base_config.model_copy(+ deep=True+ )+ },+ )+ manager = build_runtime_config_manager(+ AsyncAGFSClient(self._agfs_client),+ settings=self._config.runtime_config,+ base_config=base_config,+ )+ await manager.initialize()+ self._runtime_config_manager = managerif self._vikingdb_manager is None or self._vikingdb_manager.acl_manager is None:raise NotInitializedError("ACL")- for account_id in dict.fromkeys(account_ids):- settings = await read_account_settings(self._viking_fs, account_id)- self._vikingdb_manager.acl_manager.set_enabled(- account_id,- effective_acl_enabled(settings),- )+ self._vikingdb_manager.acl_manager.set_runtime_config_manager(manager)+ self._session_service.set_runtime_config_manager(manager)def _ensure_data_dir_lock_acquired(self) -> None:"""Protect embedded vector storage from concurrent processes in one workspace."""@@ -397,10 +440,11 @@ class OpenVikingService:)if enable_recorder:logger.info("VikingFS IO Recorder enabled")- await self.load_acl_settings([self._user.account_id])+ await self._init_runtime_config_manager()self._resource_processor = ResourceProcessor(vikingdb=self._vikingdb_manager,+ runtime_config_manager=self._runtime_config_manager,)# Initialize directories@@ -556,6 +600,8 @@ class OpenVikingService:"MinerU preflight failed (fallback will retry on first parse): %s", exc)+ if self._runtime_config_manager is not None:+ self._runtime_config_manager.start_refresh_loop()self._initialized = Truelogger.info("OpenVikingService initialized")@@ -563,6 +609,11 @@ class OpenVikingService:"""Close OpenViking and release resources."""await self._resource_service.close_background_tasks()+ if self._runtime_config_manager:+ await self._runtime_config_manager.stop_refresh_loop()+ self._runtime_config_manager = None+ logger.info("Runtime config manager stopped")+if self._watch_scheduler:await self._watch_scheduler.stop()self._watch_scheduler = Nonediff --git a/openviking/service/deletion.py b/openviking/service/deletion.pyindex 5971d77a7..d372cc190 100644--- a/openviking/service/deletion.py+++ b/openviking/service/deletion.py@@ -135,8 +135,44 @@ class DeletionService:# Request cancellation must not interrupt the fence/task/queue handoff.return await run_to_completion(lambda: self._submit(account_id, user_id, actor=actor))+ async def delete_now(+ self,+ account_id: str,+ *,+ actor: RequestContext,+ ) -> dict[str, str]:+ """Run the normal account deletion pipeline synchronously.++ Creation rollback needs the same vector, config, filesystem and identity+ cleanup as DELETE, but must settle it before returning the original+ creation error. If immediate cleanup fails, enqueue the same deletion+ message so the existing durable cleanup path can continue later.+ """+ result = await run_to_completion(+ lambda: self._submit(account_id, None, actor=actor, enqueue=False)+ )+ message = _deletion_message(+ task_id=result["task_id"],+ owner_account_id=SYSTEM_TASK_ACCOUNT_ID,+ owner_user_id=SYSTEM_TASK_USER_ID,+ target_account_id=account_id,+ target_user_id=None,+ )+ error = await run_to_completion(lambda: self._process(message))+ if error is not None:+ # _process has already marked this task failed. Submit again so+ # _submit replaces the terminal fence with a fresh queued task.+ await self.delete(account_id, actor=actor)+ raise RuntimeError(error)+ return result+async def _submit(- self, account_id: str, user_id: str | None, *, actor: RequestContext+ self,+ account_id: str,+ user_id: str | None,+ *,+ actor: RequestContext,+ enqueue: bool = True,) -> dict[str, str]:if (user_id is None@@ -189,13 +225,14 @@ class DeletionService:account_id=owner_account_id,user_id=owner_user_id,)- await self._enqueue_if_missing(- task_id=task_id,- owner_account_id=owner_account_id,- owner_user_id=owner_user_id,- target_account_id=account_id,- target_user_id=user_id,- )+ if enqueue:+ await self._enqueue_if_missing(+ task_id=task_id,+ owner_account_id=owner_account_id,+ owner_user_id=owner_user_id,+ target_account_id=account_id,+ target_user_id=user_id,+ )return {"account_id": account_id,@@ -295,6 +332,9 @@ class DeletionService:))if user_id is None:+ runtime_config = self._service.runtime_config_manager+ if runtime_config is not None:+ await run_to_completion(lambda: runtime_config.delete_account(account_id))await run_to_completion(lambda: self._delete_account_files(account_id))else:await run_to_completion(lambda: self._delete_uploads(ctx))diff --git a/openviking/service/resource_service.py b/openviking/service/resource_service.pyindex 14aeed694..886bd0f9b 100644--- a/openviking/service/resource_service.py+++ b/openviking/service/resource_service.py@@ -65,10 +65,11 @@ from openviking.telemetry.request_wait_tracker import get_request_wait_trackerfrom openviking.telemetry.resource_summary import (build_queue_status_payload,)-from openviking.utils import is_git_repo_url, parse_code_hosting_url+from openviking.utils import is_git_repo_url, is_github_url, parse_code_hosting_urlfrom openviking.utils.git_auth import (GitHttpAuthConfig,build_git_http_auth_env,+ is_git_https_url,parse_git_http_auth_config,raise_git_auth_error,reject_git_http_userinfo,@@ -948,10 +949,25 @@ class ResourceService:credential_args = credential_arg_names("git", processor_kwargs)if credential_args:raise InvalidArgumentError("Native Git credentials must use args.auth_config.")- git_auth = parse_git_http_auth_config(processor_kwargs.get("auth_config"), path)- if git_auth is not None:- task_auth = create_git_http_auth_state(git_auth, path)- source_info = await self._preflight_git_source(path, auth_config=git_auth)+ request_git_auth = parse_git_http_auth_config(processor_kwargs.get("auth_config"), path)+ if request_git_auth is not None:+ task_auth = create_git_http_auth_state(request_git_auth, path)+ preflight_git_auth = request_git_auth+ if (+ preflight_git_auth is None+ and is_git_https_url(path)+ and is_github_url(path)+ ):+ github_token = await self._resource_processor.github_token_for(path, ctx)+ if github_token:+ preflight_git_auth = GitHttpAuthConfig(+ username="oauth2",+ token=github_token,+ )+ source_info = await self._preflight_git_source(+ path,+ auth_config=preflight_git_auth,+ )source_name = source_name or source_info.source_namesource_info.source_name = source_nameelif feishu_source:diff --git a/openviking/service/session_service.py b/openviking/service/session_service.pyindex 5bd3f29f3..0be910e29 100644--- a/openviking/service/session_service.py+++ b/openviking/service/session_service.py@@ -12,8 +12,7 @@ from datetime import datetimefrom typing import TYPE_CHECKING, Any, Dict, List, Optionalfrom openviking.core.namespace import canonical_session_uri-from openviking.server.agent_evolution_config import AgentEvolutionConfigProvider-from openviking.server.config import AgentEvolutionConfig, ToolOutputExternalizationConfig+from openviking.server.config import ToolOutputExternalizationConfigfrom openviking.server.identity import RequestContextfrom openviking.server.user_config import read_user_memory_policyfrom openviking.service.session_auto_commit import (@@ -42,6 +41,7 @@ from openviking_cli.exceptions import (NotInitializedError,)from openviking_cli.utils import get_logger+from openviking_cli.utils.config.agent_evolution_config import AgentEvolutionConfigfrom openviking_cli.utils.config.memory_config import SessionAutoCommitConfiglogger = get_logger(__name__)@@ -64,11 +64,9 @@ class SessionService:self._viking_fs = viking_fsself._session_compressor = session_compressorself._tool_output_externalization_config = ToolOutputExternalizationConfig()- self._agent_evolution_enabled = AgentEvolutionConfig().enabled- self._agent_evolution_config_provider: Optional[AgentEvolutionConfigProvider] = None- self._agent_evolution_config_path: Optional[str] = None+ self._agent_evolution_default_enabled = AgentEvolutionConfig().enabled+ self._runtime_config_manager: Optional[Any] = Noneself._default_user_memory_policy: Optional[Dict[str, Any]] = None- self._configure_agent_evolution_provider()self._usage_reporter: Optional["UsageReporter"] = None# Server-wide controls remain disabled until configured during app setup.self._session_auto_commit_config = SessionAutoCommitConfig()@@ -89,7 +87,6 @@ class SessionService:self._vikingdb = vikingdbself._viking_fs = viking_fsself._session_compressor = session_compressor- self._configure_agent_evolution_provider()def set_tool_output_externalization_config(self, config: ToolOutputExternalizationConfig@@ -108,30 +105,21 @@ class SessionService:def set_agent_evolution_config(self, config: AgentEvolutionConfig) -> None:"""Set the default used when an account has no persisted override."""- self._agent_evolution_enabled = config.enabled- if self._agent_evolution_config_provider is not None:- self._agent_evolution_config_provider.set_default_enabled(config.enabled)-- def set_agent_evolution_config_path(self, config_path: Optional[str]) -> None:- """Enable account settings layered over the resolved ov.conf."""- self._agent_evolution_config_path = config_path- self._configure_agent_evolution_provider()-- def _configure_agent_evolution_provider(self) -> None:- if self._viking_fs is None:- self._agent_evolution_config_provider = None- return- self._agent_evolution_config_provider = AgentEvolutionConfigProvider(- default_enabled=self._agent_evolution_enabled,- viking_fs=self._viking_fs,- config_path=self._agent_evolution_config_path,- )+ self._agent_evolution_default_enabled = config.enabled++ def set_runtime_config_manager(self, manager: Any) -> None:+ """Bind the authoritative account runtime-config reader."""+ self._runtime_config_manager = managerasync def get_agent_evolution_enabled(self, account_id: str) -> bool:"""Return the effective Agent Evolution switch for one account."""- if self._agent_evolution_config_provider is None:- return self._agent_evolution_enabled- return await self._agent_evolution_config_provider.is_enabled(account_id)+ if self._runtime_config_manager is None:+ return self._agent_evolution_default_enabled+ setting = await self._runtime_config_manager.get_account(+ account_id,+ "agent_evolution",+ )+ return self._agent_evolution_default_enabled if setting is None else setting.enableddef set_usage_reporter(self, usage_reporter: Optional["UsageReporter"]) -> None:"""Set the usage reporter for newly created sessions."""@@ -207,7 +195,6 @@ class SessionService:session_id=session_id,session_uri=session_uri,tool_output_externalization_config=self._tool_output_externalization_config,- agent_evolution_enabled=self._agent_evolution_enabled,agent_evolution_enabled_provider=lambda: self.get_agent_evolution_enabled(ctx.account_id),diff --git a/openviking/storage/acl.py b/openviking/storage/acl.pyindex 5a1b36207..39f136484 100644--- a/openviking/storage/acl.py+++ b/openviking/storage/acl.py@@ -4,7 +4,7 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom enum import Enum-from typing import TYPE_CHECKING, Any, Iterable, Mapping, Sequence+from typing import TYPE_CHECKING, Any, Iterable, Mapping, Protocol, Sequencefrom openviking.core.identifiers import validate_identifier_part, validate_user_idfrom openviking.core.namespace import uri_parts@@ -16,6 +16,10 @@ if TYPE_CHECKING:from openviking.storage.viking_vector_index_backend import VikingVectorIndexBackend+class AccountConfigReader(Protocol):+ async def get_account(self, account_id: str, field: str) -> Any: ...++class AclLevel(str, Enum):READ = "read"WRITE = "write"@@ -251,18 +255,21 @@ class AclManager:def __init__(self,context_store: "VikingVectorIndexBackend",+ runtime_config: AccountConfigReader | None = None,) -> None:self._context_store = context_store- self._enabled_accounts: set[str] = set()+ self._runtime_config = runtime_config- def set_enabled(self, account_id: str, enabled: bool) -> None:- if enabled:- self._enabled_accounts.add(account_id)- else:- self._enabled_accounts.discard(account_id)+ def set_runtime_config_manager(self, runtime_config: AccountConfigReader) -> None:+ """Bind the authoritative account configuration reader."""+ self._runtime_config = runtime_config- def is_enabled(self, account_id: str) -> bool:- return account_id in self._enabled_accounts+ async def is_enabled(self, account_id: str) -> bool:+ """Resolve the account ACL switch, loading its config on cache miss."""+ if self._runtime_config is None:+ raise RuntimeError("Runtime config manager is not initialized")+ setting = await self._runtime_config.get_account(account_id, "acl")+ return False if setting is None else bool(setting.enabled)@staticmethoddef _effective_from_record(record: Mapping[str, Any]) -> EffectiveAcl:@@ -391,7 +398,7 @@ class AclManager:async def materialize_context_records(self, records: Sequence[dict[str, Any]], ctx: RequestContext) -> list[dict[str, Any]]:- if not self.is_enabled(ctx.account_id):+ if not await self.is_enabled(ctx.account_id):return [{key: value for key, value in record.items() if key != ACL_CREATOR_GRANT_FIELD}for record in recordsdiff --git a/openviking/storage/viking_fs/_access.py b/openviking/storage/viking_fs/_access.pyindex 4d7f46e74..126193b31 100644--- a/openviking/storage/viking_fs/_access.py+++ b/openviking/storage/viking_fs/_access.py@@ -176,7 +176,7 @@ class _AccessMixin:valid.append(uri)acl_manager = self.acl_manager- if acl_manager is None or not acl_manager.is_enabled(real_ctx.account_id):+ if acl_manager is None or not await acl_manager.is_enabled(real_ctx.account_id):result.update({uri: self._is_accessible(uri, real_ctx) for uri in valid})return result@@ -260,13 +260,15 @@ class _AccessMixin:async def _ensure_retrieval_scope(self, uri: str, ctx: Optional[RequestContext]) -> None:self._safe_uri_parts(uri)- if self._acl_enabled(ctx) and is_acl_uri(uri):+ if await self._acl_enabled(ctx) and is_acl_uri(uri):returnawait self._ensure_access(uri, ctx)- def _acl_enabled(self, ctx: Optional[RequestContext]) -> bool:+ async def _acl_enabled(self, ctx: Optional[RequestContext]) -> bool:real_ctx = self._ctx_or_default(ctx)- return self.acl_manager is not None and self.acl_manager.is_enabled(real_ctx.account_id)+ return self.acl_manager is not None and await self.acl_manager.is_enabled(+ real_ctx.account_id+ )async def _ensure_acl_manage(self, uri: str, ctx: Optional[RequestContext]) -> RequestContext:if self.acl_manager is None:@@ -463,7 +465,13 @@ class _AccessMixin:return Falsedef _is_path_entry_visible(- self, entry_path: str, name: str, base_path: str, ctx: RequestContext+ self,+ entry_path: str,+ name: str,+ base_path: str,+ ctx: RequestContext,+ *,+ acl_enabled: bool,) -> bool:"""Check visibility for one flattened path entry returned by Rust."""if self._ancestor_is_filtered(entry_path, base_path):@@ -476,7 +484,7 @@ class _AccessMixin:if not self._is_name_visible_at_path(name, parent_path):return False- if not self._acl_enabled(ctx):+ if not acl_enabled:uri = self._path_to_uri(entry_path, ctx=ctx)if not self._is_accessible(uri, ctx):return False@@ -484,13 +492,24 @@ class _AccessMixin:return Truedef _is_tree_entry_visible(- self, entry: Dict[str, Any], base_path: str, ctx: RequestContext+ self,+ entry: Dict[str, Any],+ base_path: str,+ ctx: RequestContext,+ *,+ acl_enabled: bool,) -> bool:"""Check visibility for a single TreeEntry returned by Rust tree_directory."""entry_path = entry["path"]entry_info = entry.get("info", {})name = entry_info.get("name") or entry_path.rstrip("/").rsplit("/", 1)[-1]- return self._is_path_entry_visible(entry_path, name, base_path, ctx)+ return self._is_path_entry_visible(+ entry_path,+ name,+ base_path,+ ctx,+ acl_enabled=acl_enabled,+ )def _glob_page_size(self, node_limit: Optional[int]) -> int:"""Return the backend page size used by glob_directory."""@@ -530,7 +549,7 @@ class _AccessMixin:raw_limit = None if node_limit is None else max(node_limit, 256)remaining_offset = offsetyielded = 0- acl_enabled = self._acl_enabled(real_ctx)+ acl_enabled = await self._acl_enabled(real_ctx)expose_resource_names = acl_enabled and is_acl_uri(uri)denied_directories: set[str] = set()@@ -549,7 +568,12 @@ class _AccessMixin:candidates: List[tuple] = []for entry in raw_entries:- if not self._is_tree_entry_visible(entry, path, real_ctx):+ if not self._is_tree_entry_visible(+ entry,+ path,+ real_ctx,+ acl_enabled=acl_enabled,+ ):continueif not await self._read_path_visible(uri, entry["path"], primary_path, real_ctx):continuediff --git a/openviking/storage/viking_fs/_ops.py b/openviking/storage/viking_fs/_ops.pyindex 961e45c98..6cde8f26c 100644--- a/openviking/storage/viking_fs/_ops.py+++ b/openviking/storage/viking_fs/_ops.py@@ -310,7 +310,7 @@ class _OpsMixin:path,recursive,ctx=ctx,- strict=is_dir and self._acl_enabled(ctx),+ strict=is_dir and await self._acl_enabled(ctx),)if is_direlse []@@ -695,7 +695,7 @@ class _OpsMixin:old_uri = self._normalize_transfer_uri(old_uri)new_uri = self._normalize_transfer_uri(new_uri)acl_manager = self.acl_manager- acl_enabled = self._acl_enabled(ctx)+ acl_enabled = await self._acl_enabled(ctx)guard_ctx = replace(self._ctx_or_default(ctx), bypass_acl=True)await self._ensure_access(old_uri, guard_ctx, action=AclAction.MANAGE)await self._ensure_access(old_uri, ctx, action=AclAction.WRITE)@@ -1230,6 +1230,7 @@ class _OpsMixin:# Tag filtering happens in FSService on the local fallback path. Fetch# all matches so an early filesystem limit cannot discard later tagged# entries. The remote path applies the same filter before its limit.+ acl_enabled = await self._acl_enabled(real_ctx)fs_node_limit = None if tag_filter else node_limitpage_size = self._glob_page_size(fs_node_limit)continuation_token: Optional[str] = None@@ -1253,6 +1254,7 @@ class _OpsMixin:entry.get("name") or entry["path"].rsplit("/", 1)[-1],path,real_ctx,+ acl_enabled=acl_enabled,):continueif not await self._read_path_visible(uri, entry["path"], primary_path, real_ctx):@@ -2393,7 +2395,8 @@ class _OpsMixin:remaining_offset = offsetmerge_paths = self._legacy_session_alias(uri) is not Nonebrowsable: List[tuple[Dict[str, Any], str]] = []- expose_resource_names = self._acl_enabled(ctx) and is_acl_uri(uri)+ acl_enabled = await self._acl_enabled(ctx)+ expose_resource_names = acl_enabled and is_acl_uri(uri)while True:entry_items, consumed, exhausted = await self._list_read_path_items(diff --git a/openviking/storage/viking_fs/_snapshot.py b/openviking/storage/viking_fs/_snapshot.pyindex 5d294cef4..736b61a1b 100644--- a/openviking/storage/viking_fs/_snapshot.py+++ b/openviking/storage/viking_fs/_snapshot.py@@ -49,6 +49,7 @@ class _SnapshotMixin:) -> List[str]:"""Return each requested snapshot scope and all current descendants."""result: List[str] = []+ acl_enabled = await self._acl_enabled(ctx)for uri in uris:path = self._uri_to_path(uri, ctx=ctx)try:@@ -67,7 +68,12 @@ class _SnapshotMixin:result.extend(self._path_to_uri(entry["path"], ctx=ctx)for entry in entries- if self._is_tree_entry_visible(entry, path, ctx)+ if self._is_tree_entry_visible(+ entry,+ path,+ ctx,+ acl_enabled=acl_enabled,+ ))result.append(uri)return list(dict.fromkeys(result))diff --git a/openviking/storage/viking_vector_index_backend.py b/openviking/storage/viking_vector_index_backend.pyindex c2bf91055..a74b89678 100644--- a/openviking/storage/viking_vector_index_backend.py+++ b/openviking/storage/viking_vector_index_backend.py@@ -1341,7 +1341,11 @@ class VikingVectorIndexBackend:ctx: RequestContext,) -> List[Dict[str, Any]]:backend = self._get_backend_for_context(ctx)- filter = self._merge_filters(filter, self._tenant_filter(ctx))+ acl_enabled = await self._acl_enabled(ctx)+ filter = self._merge_filters(+ filter,+ self._tenant_filter(ctx, acl_enabled=acl_enabled),+ )return await backend.search_by_random(filter=filter,limit=limit,@@ -1469,7 +1473,11 @@ class VikingVectorIndexBackend:) -> List[Dict[str, Any]]:if ctx:backend = self._get_backend_for_context(ctx)- filter = self._merge_filters(filter, self._tenant_filter(ctx))+ acl_enabled = await self._acl_enabled(ctx)+ filter = self._merge_filters(+ filter,+ self._tenant_filter(ctx, acl_enabled=acl_enabled),+ )else:backend = self._get_default_backend()return await backend.search_by_keywords(@@ -1536,12 +1544,14 @@ class VikingVectorIndexBackend:limit: int = 10,offset: int = 0,) -> List[Dict[str, Any]]:+ acl_enabled = await self._acl_enabled(ctx)scope_filter = self._build_scope_filter(ctx=ctx,context_type=context_type,target_directories=target_directories,extra_filter=extra_filter,level=level,+ acl_enabled=acl_enabled,)return await self.search(query_vector=query_vector,@@ -1571,12 +1581,14 @@ class VikingVectorIndexBackend:identical between the two — a separately hand-built filter would be onerefactor away from silently losing them."""+ acl_enabled = await self._acl_enabled(ctx)scope_filter = self._build_scope_filter(ctx=ctx,context_type=context_type,target_directories=target_directories,extra_filter=extra_filter,level=level,+ acl_enabled=acl_enabled,)if scope_filter is None:raise InvalidArgumentError(@@ -1617,6 +1629,7 @@ class VikingVectorIndexBackend:effective_target_directories = Nonebreak+ acl_enabled = await self._acl_enabled(ctx)merged_filter = self._merge_filters(PathScope("uri", parent_uri, depth=1),self._build_scope_filter(@@ -1624,6 +1637,7 @@ class VikingVectorIndexBackend:context_type=context_type,target_directories=effective_target_directories,extra_filter=extra_filter,+ acl_enabled=acl_enabled,),)return await self.search(@@ -1976,8 +1990,9 @@ class VikingVectorIndexBackend:)# A chunk cannot carry ACL for its base file URI. Keep the old main record# when copy has no main record to replace it, accepting its stale content.+ acl_enabled = await self._acl_enabled(ctx)preserved_acl_uris: set[str] = set()- if preserve_target_acl and self._acl_enabled(ctx):+ if preserve_target_acl and acl_enabled:written_uris = {rewrite_transfer_uri(str(record["uri"]), source_uri, target_uri)for record in source_records@@ -2009,7 +2024,7 @@ class VikingVectorIndexBackend:):affected_target_ids.append(str(record["id"]))target_acl_fields: Dict[str, Dict[str, Any]] = {}- if preserve_target_acl and self._acl_enabled(ctx) and replacement_target_uris:+ if preserve_target_acl and acl_enabled and replacement_target_uris:assert self.acl_manager is not Noneacl_target_uris = {uri for uri in replacement_target_uris if is_acl_uri(uri)}target_acl_fields = {@@ -2130,7 +2145,7 @@ class VikingVectorIndexBackend:return resulttimestamp = get_current_timestamp()- acl_enabled = self._acl_enabled(ctx)+ acl_enabled = await self._acl_enabled(ctx)moved_acl_by_uri: Dict[str, Dict[str, Any]] = {}target_payloads: List[Dict[str, Any]] = []for record in source_records:@@ -2252,16 +2267,18 @@ class VikingVectorIndexBackend:target_directories: Optional[List[str]],extra_filter: Optional[FilterExpr | Dict[str, Any]],level: Optional[List[int]] = None,+ *,+ acl_enabled: bool,) -> Optional[FilterExpr]:filters: List[FilterExpr] = []if context_type:filters.append(Eq("context_type", context_type))targets = [target_dir for target_dir in target_directories or [] if target_dir]- tenant_filter = self._tenant_filter(ctx)+ tenant_filter = self._tenant_filter(ctx, acl_enabled=acl_enabled)if (tenant_filter- and not self._acl_enabled(ctx)+ and not acl_enabledand self._targets_within_visible_roots(ctx, targets)):# The target scopes are already narrower than the tenant-visible@@ -2301,14 +2318,19 @@ class VikingVectorIndexBackend:for target_parts in (tuple(uri_parts(target)) for target in targets))- def _tenant_filter(self, ctx: RequestContext) -> Optional[FilterExpr]:+ def _tenant_filter(+ self,+ ctx: RequestContext,+ *,+ acl_enabled: bool,+ ) -> Optional[FilterExpr]:if ctx.bypass_acl:return Eq("account_id", ctx.account_id)if ctx.role == Role.ROOT:return Noneaccount_filter = Eq("account_id", ctx.account_id)- if not self._acl_enabled(ctx):+ if not acl_enabled:return And([account_filter,@@ -2357,8 +2379,8 @@ class VikingVectorIndexBackend:access_filters.append(PathScope("uri", "viking://resources", depth=-1))return And([account_filter, Or(access_filters)])- def _acl_enabled(self, ctx: RequestContext) -> bool:- return self.acl_manager is not None and self.acl_manager.is_enabled(ctx.account_id)+ async def _acl_enabled(self, ctx: RequestContext) -> bool:+ return self.acl_manager is not None and await self.acl_manager.is_enabled(ctx.account_id)@staticmethoddef _merge_filters(*filters: Optional[FilterExpr]) -> Optional[FilterExpr]:diff --git a/openviking/utils/git_auth.py b/openviking/utils/git_auth.pyindex 1932f210c..c2725369c 100644--- a/openviking/utils/git_auth.py+++ b/openviking/utils/git_auth.py@@ -47,6 +47,11 @@ class GitHttpAuthConfig:token: str = field(repr=False)+def is_git_https_url(repo_url: object) -> bool:+ """Return whether HTTP token authentication is valid for this Git URL."""+ return isinstance(repo_url, str) and repo_url.strip().lower().startswith("https://")++def reject_git_http_userinfo(repo_url: str) -> None:"""Require HTTP(S) Git credentials to travel through ``auth_config``."""parsed = urlparse(repo_url)@@ -60,7 +65,7 @@ def reject_git_http_userinfo(repo_url: str) -> None:def _validate_git_https_auth_url(repo_url: str) -> str:normalized = repo_url.strip() if isinstance(repo_url, str) else ""- if not normalized.lower().startswith("https://"):+ if not is_git_https_url(normalized):raise InvalidArgumentError("args.auth_config token authentication requires an HTTPS Git URL.")diff --git a/openviking/utils/media_processor.py b/openviking/utils/media_processor.pyindex 434804d4d..989775309 100644--- a/openviking/utils/media_processor.py+++ b/openviking/utils/media_processor.py@@ -363,6 +363,7 @@ class UnifiedResourceProcessor:# Source credentials are consumed by the accessor. Never forward# them into parser kwargs, parse results, or later queue payloads.parse_kwargs.pop("auth_config", None)+ parse_kwargs.pop("github_token", None)parse_kwargs.pop("tos_signature", None)parse_kwargs.pop("tos_access", None)parse_kwargs["instruction"] = instructiondiff --git a/openviking/utils/resource_processor.py b/openviking/utils/resource_processor.pyindex e87cecd7e..866c330b4 100644--- a/openviking/utils/resource_processor.py+++ b/openviking/utils/resource_processor.py@@ -9,6 +9,7 @@ as described in the OpenViking design document.import asyncioimport inspect+import osimport timefrom collections.abc import Callablefrom typing import TYPE_CHECKING, Any, Dict, List, Optional, Union@@ -33,7 +34,9 @@ from openviking.storage.queuefs.semantic_processor import SemanticProcessorfrom openviking.storage.viking_fs import LS_ALL_NODES, get_viking_fsfrom openviking.storage.vikingdb_manager import VikingDBManagerfrom openviking.telemetry import get_current_telemetry+from openviking.utils import is_github_urlfrom openviking.utils.embedding_utils import index_resource, vectorize_file+from openviking.utils.git_auth import is_git_https_urlfrom openviking.utils.ingest_options import IngestOptionsfrom openviking.utils.summarizer import Summarizerfrom openviking_cli.exceptions import OpenVikingError@@ -69,16 +72,46 @@ class ResourceProcessor:media_storage: Optional["StoragePath"] = None,max_context_size: int = 2000,max_split_depth: int = 3,+ runtime_config_manager: Optional[Any] = None,):"""Initialize coordinated writer."""self.vikingdb = vikingdbself.embedder = vikingdb.get_embedder()self.media_storage = media_storage+ self.runtime_config_manager = runtime_config_managerself.tree_builder = TreeBuilder()self._vlm_processor = Noneself._media_processor = Noneself._summarizer = None+ async def github_token_for(+ self,+ source: str,+ ctx: RequestContext,+ ) -> Optional[str]:+ """Resolve a GitHub token for one request without persisting it."""+ if not is_git_https_url(source) or not is_github_url(source):+ return None+ if self.runtime_config_manager is not None:+ account_github = await self.runtime_config_manager.get_account(ctx.account_id, "github")+ if account_github is not None and account_github.token:+ return account_github.token+ return os.environ.get("GITHUB_TOKEN") or None++ async def _source_config_kwargs(+ self,+ source: str,+ ctx: RequestContext,+ kwargs: dict[str, Any],+ ) -> dict[str, Any]:+ """Add account-scoped source credentials without persisting them."""+ github_token = await self.github_token_for(source, ctx)+ if not github_token:+ return kwargs+ result = dict(kwargs)+ result["github_token"] = github_token+ return result+def _get_summarizer(self) -> "Summarizer":"""Lazy initialization of Summarizer."""if self._summarizer is None:@@ -155,6 +188,7 @@ class ResourceProcessor:path, **kwargs):return None+ kwargs = await self._source_config_kwargs(path, ctx, kwargs)with get_viking_fs().bind_request_context(ctx):return await media_processor.prepare(path,@@ -263,6 +297,7 @@ class ResourceProcessor:await _set_stage("fetching")else:await _set_stage("parsing")+ kwargs = await self._source_config_kwargs(path, ctx, kwargs)with viking_fs.bind_request_context(ctx):parse_result = await media_processor.process(source=path,diff --git a/openviking_cli/utils/config/__init__.py b/openviking_cli/utils/config/__init__.pyindex 07bf7dac1..0b2d8bf56 100644--- a/openviking_cli/utils/config/__init__.py+++ b/openviking_cli/utils/config/__init__.py@@ -1,6 +1,7 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0from . import embedding_config+from .agent_evolution_config import AgentEvolutionConfigfrom .agfs_config import AGFSConfigfrom .cache_config import CacheConfigfrom .config_loader import (@@ -91,6 +92,7 @@ from .vlm_config import VLMConfig__all__ = ["AGFSConfig",+ "AgentEvolutionConfig","CacheConfig","SYSTEM_CONFIG_DIR","DEFAULT_OV_CONF",diff --git a/openviking_cli/utils/config/agent_evolution_config.py b/openviking_cli/utils/config/agent_evolution_config.pynew file mode 100644index 000000000..96f1c720c--- /dev/null+++ b/openviking_cli/utils/config/agent_evolution_config.py@@ -0,0 +1,11 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Agent Evolution runtime configuration."""++from pydantic import BaseModel+++class AgentEvolutionConfig(BaseModel):+ """Agent Evolution switch shared by cluster and account configuration."""++ enabled: bool = Falsediff --git a/openviking_cli/utils/config/github_config.py b/openviking_cli/utils/config/github_config.pynew file mode 100644index 000000000..ed3534baf--- /dev/null+++ b/openviking_cli/utils/config/github_config.py@@ -0,0 +1,11 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Account-scoped GitHub access configuration."""++from pydantic import BaseModel+++class GitHubConfig(BaseModel):+ """Configuration for GitHub access."""++ token: str = ""diff --git a/openviking_cli/utils/config/open_viking_config.py b/openviking_cli/utils/config/open_viking_config.pyindex e6b3f195d..e8dbf082d 100644--- a/openviking_cli/utils/config/open_viking_config.py+++ b/openviking_cli/utils/config/open_viking_config.py@@ -11,6 +11,7 @@ from pydantic import BaseModel, Field, ValidationError, model_validatorfrom openviking_cli.session.user_id import UserIdentifier+from .agent_evolution_config import AgentEvolutionConfigfrom .cache_config import CacheConfigfrom .config_loader import resolve_config_pathfrom .config_utils import format_validation_error@@ -49,6 +50,7 @@ from .queue_worker_config import QueueWorkersConfigfrom .reindex_config import ReindexConfigfrom .rerank_config import RerankConfigfrom .retrieval_config import RetrievalConfig+from .runtime_field import RuntimeFieldfrom .storage_config import StorageConfigfrom .telemetry_config import TelemetryConfigfrom .vlm_config import VLMConfig@@ -154,6 +156,14 @@ class CompileApiConfig(BaseModel):return self+class RuntimeConfigSettings(BaseModel):+ """Startup selection of the runtime config source."""++ source: str = "file"+ module: Optional[str] = None+ params: Dict[str, Any] = Field(default_factory=dict)++class OpenVikingConfig(BaseModel):"""Main configuration for OpenViking."""@@ -412,6 +422,11 @@ class OpenVikingConfig(BaseModel):memory: MemoryConfig = Field(default_factory=MemoryConfig, description="Memory configuration")+ agent_evolution: AgentEvolutionConfig = RuntimeField(+ default_factory=AgentEvolutionConfig,+ description="Dynamic cluster default for Agent Evolution.",+ )+oauth: OAuthConfig = Field(default_factory=OAuthConfig,description="OAuth 2.1 (MCP) configuration",@@ -430,6 +445,14 @@ class OpenVikingConfig(BaseModel):description="Conversation-log ingest (openviking-server ingest) configuration",)+ runtime_config: RuntimeConfigSettings = Field(+ default_factory=RuntimeConfigSettings,+ description=(+ "Boot-level selection of the runtime config source. "+ "Read once at startup and never mutated by the dynamic config API."+ ),+ )+model_config = {"arbitrary_types_allowed": True}@classmethod@@ -663,6 +686,12 @@ class OpenVikingConfigSingleton:except Exception as e:raise RuntimeError(f"Failed to load config file: {e}")+ @classmethod+ def set_instance(cls, config: "OpenVikingConfig") -> None:+ """Atomically publish an already-built validated configuration."""+ with cls._lock:+ cls._instance = config+@classmethoddef reset_instance(cls) -> None:"""Reset the singleton instance (mainly for testing)."""@@ -677,8 +706,8 @@ def get_openviking_config() -> OpenVikingConfig:def set_openviking_config(config: OpenVikingConfig) -> None:- """Set the global OpenVikingConfig instance."""- OpenVikingConfigSingleton.initialize(config_dict=config.to_dict())+ """Atomically publish an already-built OpenVikingConfig."""+ OpenVikingConfigSingleton.set_instance(config)def is_valid_openviking_config(config: OpenVikingConfig) -> bool:diff --git a/openviking_cli/utils/config/runtime_field.py b/openviking_cli/utils/config/runtime_field.pynew file mode 100644index 000000000..c62507078--- /dev/null+++ b/openviking_cli/utils/config/runtime_field.py@@ -0,0 +1,212 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Declarative marker for config fields the runtime config API may touch.++A plain top-level Pydantic ``Field`` is not on the config API surface: PATCH+requests targeting it are rejected. Declaring :func:`RuntimeField` opts it in+and records two orthogonal attributes so generic code can decide what the API+may do with it without any per-field branching:++- ``dynamic`` — the field's writable lifecycle, a single boolean covering all+ mutability. ``True`` (default): writable both at creation and by later PATCH.+ ``False``: writable only when the owning object is first created (account or+ cluster config); any later PATCH that touches it is rejected. When a+ ``dynamic=False`` field is not given at creation it is fixed to its default+ (which may be a ``fallback``, resolved at read time — never materialized).+- ``fallback`` — when an account leaves this field unset, which cluster-level+ field supplies the value. The value may be a dotted path (``storage.vectordb``)+ to reach a nested cluster field.++These attributes are stored on the field's ``json_schema_extra`` under the+``x-runtime-config`` key and read back through the helpers below. ``dynamic`` and+``fallback`` are orthogonal: a ``dynamic=False`` field may still carry a+``fallback`` (meaning "if not given at creation, fall back to the cluster default+forever").++Whether a field is cluster-wide or per-account is *not* one of these attributes:+it is decided by which model declares the field. Fields on ``OpenVikingConfig``+are cluster-wide; fields on ``AccountConfig`` are per-account. A field is never+made account-scoped by wrapping its type.+"""++from __future__ import annotations++import types+import typing+from dataclasses import is_dataclass+from typing import Any, Optional++from pydantic import BaseModel+from pydantic.fields import FieldInfo+from pydantic_core import PydanticUndefined++RUNTIME_CONFIG_KEY = "x-runtime-config"+++def RuntimeField( # noqa: N802+ *,+ dynamic: bool = True,+ fallback: Optional[str] = None,+ **kwargs: Any,+) -> Any:+ """Opt a config field into the runtime config API and declare its attributes.++ A single declaration carries both attributes below. Cluster-vs-account scope+ is not an argument here: it follows from which model declares the field+ (``OpenVikingConfig`` = cluster, ``AccountConfig`` = per-account).++ Args:+ dynamic: ``True`` (default) lets the field be set both at creation and by+ any later PATCH. ``False`` restricts writes to creation only; a later+ PATCH that touches it (or ``null``-deletes it via a parent) is+ rejected. A field declared with a plain ``Field`` — i.e. without+ ``RuntimeField`` — is never on the config surface at all.+ fallback: name of a cluster-level field, optionally dotted to reach a+ nested field (``storage.vectordb``). When an account has not set this+ field, its effective value is read from ``OpenVikingConfig.<fallback>``.+ ``None`` (default) means there is no cluster fallback; the manager+ returns ``None`` for an unset account field and the caller supplies+ any business default. Only meaningful on ``AccountConfig``.+ """+ from pydantic import Field++ extra = dict(kwargs.pop("json_schema_extra", {}) or {})+ extra[RUNTIME_CONFIG_KEY] = {+ "dynamic": dynamic,+ "fallback": fallback,+ }+ return Field(json_schema_extra=extra, **kwargs)+++def _runtime_meta(field: FieldInfo) -> Optional[dict]:+ extra = field.json_schema_extra+ if not isinstance(extra, dict):+ return None+ meta = extra.get(RUNTIME_CONFIG_KEY)+ return meta if isinstance(meta, dict) else None+++def is_runtime_field(field: FieldInfo) -> bool:+ """Whether the field was declared with :func:`RuntimeField` (on the surface)."""+ return _runtime_meta(field) is not None+++def is_dynamic(field: FieldInfo) -> bool:+ """Whether a RuntimeField is writable by PATCH after creation.++ ``False`` for a create-only field, and for any field not declared with+ :func:`RuntimeField` at all.+ """+ meta = _runtime_meta(field)+ return bool(meta and meta.get("dynamic"))+++def fallback_of(field: FieldInfo) -> Optional[str]:+ """Return the cluster field path this account field falls back to, else ``None``.++ The result may be dotted (``storage.vectordb``); resolution walks the path.+ """+ meta = _runtime_meta(field)+ return meta.get("fallback") if meta else None+++def resolve_fallback(cluster: Any, path: str) -> Any:+ """Read a (possibly dotted) fallback path off the cluster config object."""+ value = cluster+ for part in path.split("."):+ value = getattr(value, part)+ return value+++def _unwrap_model(annotation: Any) -> Optional[type[BaseModel]]:+ """Resolve the concrete ``BaseModel`` subclass an annotation points to.++ Handles ``Optional[...]``/``Union[...]`` wrappers so nested section fields+ can be traversed for validation; returns ``None`` for scalars and lists.+ """+ origin = typing.get_origin(annotation)+ if origin in (typing.Union, types.UnionType):+ for arg in typing.get_args(annotation):+ if arg is type(None):+ continue+ model = _unwrap_model(arg)+ if model is not None:+ return model+ return None+ if isinstance(annotation, type) and (+ issubclass(annotation, BaseModel) or is_dataclass(annotation)+ ):+ return annotation+ return None+++def collect_runtime_field_paths(model: type[BaseModel]) -> set[tuple[str, ...]]:+ """Collect dotted field paths that are on ``model``'s config surface.++ Collect explicitly marked paths, including their marked parent sections,+ regardless of ``dynamic``. A section with no marked descendants is treated+ by the validator as one configurable object; its ordinary model fields are+ accepted inside that object. Objects still merge recursively during PATCH.+ Sections with marked descendants restrict input to those declared paths.++ Whether a non-creating PATCH may write a path is further gated by+ ``dynamic`` (see :func:`collect_frozen_paths`). Cluster-vs-account scope is+ expressed by which model the field is declared on (``OpenVikingConfig`` vs+ ``AccountConfig``), so validating against the account model already confines+ the result to account fields.+ """+ paths: set[tuple[str, ...]] = set()++ def walk(cls: type[BaseModel], prefix: tuple[str, ...]) -> None:+ for name, field in model_fields(cls).items():+ if not is_runtime_field(field):+ continue+ path = prefix + (name,)+ nested = _unwrap_model(field.annotation)+ if nested is not None:+ walk(nested, path)+ paths.add(path)++ for name, field in model.model_fields.items():+ if not is_runtime_field(field):+ continue+ walk_root = _unwrap_model(field.annotation)+ path = (name,)+ if walk_root is not None:+ walk(walk_root, path)+ paths.add(path)+ return paths+++def collect_frozen_paths(model: type[BaseModel]) -> set[tuple[str, ...]]:+ """Collect all field paths marked ``dynamic=False`` on ``model``."""+ paths: set[tuple[str, ...]] = set()++ def walk(cls: type[BaseModel], prefix: tuple[str, ...], ancestors: set[type]) -> None:+ if cls in ancestors:+ return+ next_ancestors = ancestors | {cls}+ for name, field in model_fields(cls).items():+ if not is_runtime_field(field):+ continue+ path = prefix + (name,)+ if not is_dynamic(field):+ paths.add(path)+ nested = _unwrap_model(field.annotation)+ if nested is not None:+ walk(nested, path, next_ancestors)++ walk(model, (), set())+ return paths+++def model_fields(model: type) -> dict[str, FieldInfo]:+ """Expose declarations on both Pydantic and existing parser dataclasses."""+ if issubclass(model, BaseModel):+ return typing.cast(type[BaseModel], model).model_fields+ return {+ name: FieldInfo.from_annotated_attribute(+ annotation, getattr(model, name, PydanticUndefined)+ )+ for name, annotation in typing.get_type_hints(model, include_extras=True).items()+ }diff --git a/tests/config/__init__.py b/tests/config/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/config/test_runtime_config.py b/tests/config/test_runtime_config.pynew file mode 100644index 000000000..afe0a1937--- /dev/null+++ b/tests/config/test_runtime_config.py@@ -0,0 +1,1091 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Contract tests for the runtime configuration system.++Cluster and account are two independent config models. These tests exercise the+smallest meaningful public contracts across both:++- ``RuntimeField`` opt-in and path collection, cluster-vs-account scope by model.+- Three-state PATCH merge and structural validation (mutable / create-only /+ read-only).+- The manager's account loading, atomic multi-field publish, cluster/account+ publish isolation, consumer gating, and idle eviction.+- Account field lookup with automatic loading and cluster fallback.+- The file source's legacy-plaintext read / magic-write behaviour.+"""++from __future__ import annotations++import asyncio+from typing import Optional++import pytest+from pydantic import BaseModel, Field++from openviking.config import (+ AccountConfig,+ ConfigChangeReason,+ ConfigScope,+ RuntimeConfigManager,+ ScopeKind,+)+from openviking.config.merge import apply_three_state_patch+from openviking.config.source import FileConfigSource, MemoryConfigSource, create_config_source+from openviking.config.source.base import ConfigSourceContext+from openviking.config.validate import ConfigPatchError, validate_patch+from openviking_cli.utils.config.runtime_field import (+ RuntimeField,+ collect_frozen_paths,+ collect_runtime_field_paths,+ fallback_of,+ is_dynamic,+ is_runtime_field,+)++# -- test config models -------------------------------------------------------+++class VLMSection(BaseModel):+ model: Optional[str] = RuntimeField(default=None)+ temperature: float = Field(default=0.0) # plain Field -> immutable+ model_config = {"extra": "forbid"}+++class MemorySection(BaseModel):+ extraction_enabled: bool = RuntimeField(default=True)+ model_config = {"extra": "forbid"}+++class SwitchSection(BaseModel):+ enabled: bool+ model_config = {"extra": "forbid"}+++class ClusterConfig(BaseModel):+ """Stand-in cluster model: one mutable section, one locked section."""++ vlm: VLMSection = RuntimeField(default_factory=VLMSection)+ memory: MemorySection = RuntimeField(default_factory=MemorySection)+ server: VLMSection = Field(default_factory=VLMSection) # locked section+ model_config = {"extra": "forbid"}+++class AccountModel(BaseModel):+ """Stand-in sparse account model used by the manager tests."""++ vlm: Optional[VLMSection] = RuntimeField(default=None, fallback="vlm")+ memory: Optional[MemorySection] = RuntimeField(default=None, fallback="memory")+ switch: Optional[SwitchSection] = RuntimeField(default=None)+ model_config = {"extra": "forbid"}+++class NestedFrozenChild(BaseModel):+ frozen: str = RuntimeField(default="", dynamic=False)+++class NestedFrozenRoot(BaseModel):+ child: NestedFrozenChild = RuntimeField(default_factory=NestedFrozenChild)+++def _build_cluster(old: ClusterConfig, cluster_override: dict) -> ClusterConfig:+ """Rebuild the cluster config from its immutable base + sparse override."""+ return ClusterConfig(**apply_three_state_patch(old.model_dump(), cluster_override))+++def _build_account(override: Optional[dict]) -> AccountModel:+ """Construct (and validate) the sparse account model from its override."""+ return AccountModel(**(override or {}))+++def _make_manager(source) -> tuple[RuntimeConfigManager, dict]:+ holder = {"config": ClusterConfig()}+ manager = RuntimeConfigManager(+ source,+ base_config=holder["config"],+ get_config=lambda: holder["config"],+ set_config=lambda c: holder.__setitem__("config", c),+ build_config=_build_cluster,+ build_account=_build_account,+ validate_request=lambda patch, account, creating: validate_patch(+ AccountModel if account else ClusterConfig, patch, creating=creating+ ),+ )+ return manager, holder+++# -- RuntimeField / path collection -------------------------------------------+++def test_runtime_field_paths_scope_by_model():+ all_paths = collect_runtime_field_paths(ClusterConfig)+ assert ("vlm", "model") in all_paths+ assert ("memory", "extraction_enabled") in all_paths+ # plain Field leaf and plain Field section are never mutable+ assert ("vlm", "temperature") not in all_paths+ assert not any(p[0] == "server" for p in all_paths)++ assert is_dynamic(ClusterConfig.model_fields["vlm"])+ assert not is_runtime_field(ClusterConfig.model_fields["server"])+++def test_real_openviking_config_exposes_no_mutable_path():+ """Existing OpenVikingConfig fields opted into the surface are dynamic RuntimeFields."""+ from openviking_cli.utils.config.open_viking_config import OpenVikingConfig++ # Agent Evolution is the current cluster runtime surface. Other existing+ # cluster fields remain startup-only and use plain Field.+ surface = collect_runtime_field_paths(OpenVikingConfig)+ assert surface == {("agent_evolution",)}+ assert ("vlm",) not in surface+ assert not any(p[0] == "rerank" for p in surface)+ assert is_dynamic(OpenVikingConfig.model_fields["agent_evolution"])+ assert not is_runtime_field(OpenVikingConfig.model_fields["memory"])+ assert not is_runtime_field(OpenVikingConfig.model_fields["vlm"])+ assert not is_runtime_field(OpenVikingConfig.model_fields["rerank"])+ # Static cluster sections are rejected by the dynamic PATCH API.+ with pytest.raises(ConfigPatchError):+ validate_patch(OpenVikingConfig, {"vlm": {"model": "m"}})+ with pytest.raises(ConfigPatchError):+ validate_patch(OpenVikingConfig, {"rerank": {"enabled": True}})+++def test_cluster_rebuild_preserves_explicit_and_default_field_semantics():+ from openviking.config.binding import _build_cluster+ from openviking_cli.utils.config.open_viking_config import OpenVikingConfig++ base = OpenVikingConfig.from_dict(+ {+ "embedding": {+ "dense": {+ "provider": "openai",+ "model": "text-embedding-3-small",+ "api_key": "test-key",+ }+ }+ }+ )+ assert "input" not in base.embedding.dense.model_fields_set++ rebuilt = _build_cluster(base, {"agent_evolution": {"enabled": True}})+ assert rebuilt.embedding.dense.input == "multimodal"+ assert "input" not in rebuilt.embedding.dense.model_fields_set++ explicit = OpenVikingConfig.from_dict(+ {+ "embedding": {+ "dense": {+ "provider": "openai",+ "model": "text-embedding-3-small",+ "api_key": "test-key",+ "input": "multimodal",+ }+ }+ }+ )+ rebuilt_explicit = _build_cluster(+ explicit,+ {"agent_evolution": {"enabled": True}},+ )+ assert "input" in rebuilt_explicit.embedding.dense.model_fields_set+++def test_account_patch_keeps_sparse_explicit_field_semantics():+ async def run():+ manager, _ = _make_manager(MemoryConfigSource())+ await manager.patch_account("ov-a", {"vlm": {"model": "account-model"}})++ account = manager._accounts["ov-a"].config+ assert account.model_fields_set == {"vlm"}+ assert account.vlm.model_fields_set == {"model"}+ assert "temperature" not in account.vlm.model_fields_set++ asyncio.run(run())+++def test_collect_frozen_paths_includes_nested_create_only_fields():+ assert collect_frozen_paths(NestedFrozenRoot) == {("child", "frozen")}+ with pytest.raises(ConfigPatchError, match="child.frozen"):+ validate_patch(NestedFrozenRoot, {"child": {"frozen": "changed"}})+ validate_patch(NestedFrozenRoot, {"child": {"frozen": "initial"}}, creating=True)+++# -- PATCH request validation -------------------------------------------------+++def test_validate_patch_accepts_mutable_paths_and_none_delete():+ validate_patch(ClusterConfig, {"vlm": {"model": "m"}})+ validate_patch(ClusterConfig, {"vlm": {"model": None}})+ validate_patch(ClusterConfig, {"memory": {"extraction_enabled": False}})+++def test_validate_patch_rejects_locked_field_and_section():+ with pytest.raises(ConfigPatchError):+ validate_patch(ClusterConfig, {"vlm": {"temperature": 1.0}}) # locked leaf+ with pytest.raises(ConfigPatchError):+ validate_patch(ClusterConfig, {"server": {"model": "x"}}) # locked section+ with pytest.raises(ConfigPatchError):+ validate_patch(ClusterConfig, {"unknown": {}}) # unknown top-level+++def test_validate_patch_scope_confined_by_model():+ # AccountModel has no `server`; the same patch that is valid against a cluster+ # model with `memory` is rejected once fields aren't on the account model.+ validate_patch(AccountModel, {"vlm": {"model": "m"}})+ with pytest.raises(ConfigPatchError):+ validate_patch(AccountModel, {"server": {"model": "m"}})+++# -- three-state merge --------------------------------------------------------+++def test_three_state_patch_semantics():+ current = {"vlm": {"model": "old", "temperature": 1.0}, "memory": {"extraction_enabled": True}}+ patched = apply_three_state_patch(+ current,+ {"vlm": {"model": "new", "temperature": None}, "memory": None},+ )+ assert patched == {"vlm": {"model": "new"}}+ assert current["vlm"]["temperature"] == 1.0 # inputs untouched (pure function)+++def test_nested_delete_preserves_parent_existence():+ delete_leaf = {"memory": {"extraction_enabled": None}}++ # Deleting a missing child must not create its missing parent.+ assert apply_three_state_patch({}, delete_leaf) == {}++ # Deleting the final child preserves an already explicit parent.+ assert apply_three_state_patch(+ {"memory": {"extraction_enabled": False}},+ delete_leaf,+ ) == {"memory": {}}++ # Siblings remain, and only a parent-level null removes the parent.+ assert apply_three_state_patch(+ {"memory": {"extraction_enabled": False, "output_language": "zh"}},+ delete_leaf,+ ) == {"memory": {"output_language": "zh"}}+ assert apply_three_state_patch({"memory": {}}, {"memory": None}) == {}++ # An explicitly empty object is different from a delete-only child patch.+ assert apply_three_state_patch({}, {"memory": {}}) == {"memory": {}}+++# -- manager: cluster PATCH ---------------------------------------------------+++def test_cluster_patch_publishes_and_notifies_consumer():+ async def run():+ manager, holder = _make_manager(MemoryConfigSource())+ seen = []++ async def consumer(event):+ seen.append((event.scope.key, event.changed_sections, event.new_config.vlm.model))++ manager.add_update_consumer(+ scope=ScopeKind.CLUSTER,+ sections={"vlm"},+ consumer=consumer,+ )+ event = await manager.patch_cluster({"vlm": {"model": "gpt-x"}})++ assert seen == [(None, frozenset({"vlm"}), "gpt-x")]+ assert event.reason is ConfigChangeReason.UPDATE+ assert "vlm" in event.changed_sections+ assert holder["config"].vlm.model == "gpt-x"++ # patching a locked field is rejected and publishes nothing+ before = holder["config"]+ with pytest.raises(ConfigPatchError):+ await manager.patch_cluster({"server": {"model": "nope"}})+ assert holder["config"] is before+ assert len(seen) == 1++ asyncio.run(run())+++def test_cluster_patch_reset_rebuilds_from_startup_baseline():+ async def run():+ source = MemoryConfigSource()+ manager, holder = _make_manager(source)++ await manager.patch_cluster({"vlm": {"model": "temporary"}})+ assert holder["config"].vlm.model == "temporary"++ await manager.patch_cluster({"vlm": None})+ assert await source.load(ConfigScope.cluster()) == {}+ assert holder["config"].vlm.model is None++ asyncio.run(run())+++def test_multi_field_patch_publishes_atomically():+ async def run():+ manager, holder = _make_manager(MemoryConfigSource())+ seen = []++ async def consumer(event):+ cfg = event.new_config # fully published by the time a consumer runs+ seen.append((cfg.memory.extraction_enabled, cfg.vlm.model))++ manager.add_update_consumer(+ scope=ScopeKind.CLUSTER,+ sections={"vlm", "memory"},+ consumer=consumer,+ )+ await manager.patch_cluster({"vlm": {"model": "m2"}, "memory": {"extraction_enabled": False}})+ assert seen == [(False, "m2")]++ asyncio.run(run())+++def test_invalid_patch_does_not_persist_or_publish():+ async def run():+ source = MemoryConfigSource()+ manager, holder = _make_manager(source)+ before = holder["config"]+ with pytest.raises(ValueError):+ await manager.patch_cluster({"vlm": {"model": 123, "temperature": "bad"}})+ # temperature is locked -> ConfigPatchError before any persist+ assert holder["config"] is before+ assert await source.load(ConfigScope.cluster()) is None++ asyncio.run(run())+++# -- manager: account loading + PATCH -----------------------------------------+++def test_get_account_auto_loads_missing_override_and_resolves_fallback():+ async def run():+ manager, _ = _make_manager(MemoryConfigSource())+ vlm = await manager.get_account("ov-a", "vlm")+ assert "ov-a" in manager._accounts+ assert vlm.model is None++ asyncio.run(run())+++def test_get_account_rejects_unknown_field():+ async def run():+ manager, _ = _make_manager(MemoryConfigSource())+ with pytest.raises(AttributeError):+ await manager.get_account("ov-a", "unknown")++ asyncio.run(run())+++def test_account_patch_sets_override_and_publishes():+ async def run():+ manager, _ = _make_manager(MemoryConfigSource())+ event = await manager.patch_account("ov-a", {"vlm": {"model": "account-model"}})+ assert event.scope.key == "ov-a"+ assert (await manager.get_account("ov-a", "vlm")).model == "account-model"++ asyncio.run(run())+++def test_account_storage_wait_does_not_block_unrelated_account_load():+ class BlockingSource(MemoryConfigSource):+ def __init__(self):+ super().__init__()+ self.started = asyncio.Event()+ self.release = asyncio.Event()++ async def update(self, scope, mutate):+ if scope == ConfigScope.account("ov-a"):+ self.started.set()+ await self.release.wait()+ return await super().update(scope, mutate)++ async def run():+ source = BlockingSource()+ manager, _ = _make_manager(source)+ patch = asyncio.create_task(+ manager.patch_account("ov-a", {"vlm": {"model": "slow"}})+ )+ await source.started.wait()++ other = asyncio.create_task(manager.get_account("ov-b", "vlm"))+ assert (await asyncio.wait_for(other, timeout=1)).model is None++ source.release.set()+ await patch++ asyncio.run(run())+++def test_refresh_picks_up_out_of_band_write():+ async def run():+ source = MemoryConfigSource()+ manager, _ = _make_manager(source)+ reasons = []++ async def consumer(event):+ reasons.append(event.reason)++ manager.add_update_consumer(+ scope=ScopeKind.ACCOUNT,+ sections={"vlm"},+ consumer=consumer,+ )+ await manager.get_account("ov-a", "vlm")+ # A different writer mutates the same override file directly, bypassing+ # the manager; the periodic refresh re-reads and republishes.+ await source.update(ConfigScope.account("ov-a"), lambda _: {"vlm": {"model": "oob"}})+ await manager.refresh_once()+ assert reasons == [ConfigChangeReason.UPDATE]+ assert (await manager.get_account("ov-a", "vlm")).model == "oob"++ asyncio.run(run())+++def test_refresh_does_not_resurrect_unloaded_account():+ async def run():+ source = MemoryConfigSource()+ manager, _ = _make_manager(source)+ await source.update(ConfigScope.account("ov-x"), lambda _: {"vlm": {"model": "x"}})+ # Never loaded: refresh must not create the cache entry (no implicit load).+ await manager.refresh_once()+ assert "ov-x" not in manager._accounts++ asyncio.run(run())++++def test_patch_waits_for_matching_consumers_and_filters_registration():+ async def run():+ manager, _ = _make_manager(MemoryConfigSource())+ release = asyncio.Event()+ started = asyncio.Event()+ seen = []++ async def matching(event):+ started.set()+ await release.wait()+ seen.append(event.new_config.vlm.model)++ async def wrong_scope(event):+ seen.append("wrong-scope")++ async def wrong_section(event):+ seen.append("wrong-section")++ manager.add_update_consumer(+ scope=ScopeKind.CLUSTER,+ sections={"vlm"},+ consumer=matching,+ )+ manager.add_update_consumer(+ scope=ScopeKind.ACCOUNT,+ sections={"vlm"},+ consumer=wrong_scope,+ )+ manager.add_update_consumer(+ scope=ScopeKind.CLUSTER,+ sections={"memory"},+ consumer=wrong_section,+ )+ patch_task = asyncio.create_task(manager.patch_cluster({"vlm": {"model": "first"}}))+ await started.wait()+ assert not patch_task.done()+ release.set()+ await patch_task+ assert seen == ["first"]++ asyncio.run(run())+++def test_idle_evict_notifies_all_account_consumers(monkeypatch):+ import time++ clock = [100.0]+ monkeypatch.setattr(time, "monotonic", lambda: clock[0])++ async def run():+ source = MemoryConfigSource()+ manager, _ = _make_manager(source)+ reasons = []+ lifecycle_reasons = []++ async def consumer(event):+ reasons.append(event.reason)++ async def lifecycle_consumer(event):+ lifecycle_reasons.append(event.reason)++ manager.add_update_consumer(+ scope=ScopeKind.ACCOUNT,+ sections={"vlm"},+ consumer=consumer,+ )+ manager.add_update_consumer(+ scope=ScopeKind.ACCOUNT,+ sections={"switch"},+ consumer=lifecycle_consumer,+ )+ await manager.get_account("ov-a", "vlm")+ await manager.patch_account("ov-a", {"vlm": {"model": "a"}})+ clock[0] += 24 * 60 * 60 + 1+ await manager.refresh_once()++ assert reasons == [+ ConfigChangeReason.UPDATE,+ ConfigChangeReason.EVICT,+ ]+ assert lifecycle_reasons == [ConfigChangeReason.EVICT]+ assert (await manager.get_account("ov-a", "vlm")).model == "a"+ assert await source.load(ConfigScope.account("ov-a")) == {"vlm": {"model": "a"}}++ asyncio.run(run())+++def test_delete_account_clears_source_cache_and_notifies_consumers():+ async def run():+ source = MemoryConfigSource()+ manager, _ = _make_manager(source)+ reasons = []++ async def consumer(event):+ reasons.append(event.reason)++ manager.add_update_consumer(+ scope=ScopeKind.ACCOUNT,+ sections={"vlm"},+ consumer=consumer,+ )+ await manager.patch_account("ov-a", {"vlm": {"model": "old"}})+ assert (await manager.get_account("ov-a", "vlm")).model == "old"++ await manager.delete_account("ov-a")+ assert await source.load(ConfigScope.account("ov-a")) is None+ assert "ov-a" not in manager._accounts+ assert reasons == [ConfigChangeReason.UPDATE, ConfigChangeReason.EVICT]++ # Reusing the account ID starts from a clean scope.+ assert (await manager.get_account("ov-a", "vlm")).model is None++ asyncio.run(run())+++def test_refresh_does_not_keep_idle_accounts_alive(monkeypatch):+ import time++ clock = [100.0]+ monkeypatch.setattr(time, "monotonic", lambda: clock[0])++ async def run():+ manager, _ = _make_manager(MemoryConfigSource())+ await manager.get_account("ov-a", "vlm")+ clock[0] += 24 * 60 * 60 + 1 # idle past the eviction TTL+ await manager.refresh_once() # evicts the idle account+ assert "ov-a" not in manager._accounts+ assert (await manager.get_account("ov-a", "vlm")).model is None+ assert "ov-a" in manager._accounts++ asyncio.run(run())+++def test_refresh_retries_failed_load_without_another_storage_change():+ class FlakySource(MemoryConfigSource):+ fail_scope = None++ async def load(self, scope):+ if self.fail_scope is not None and scope == self.fail_scope:+ self.fail_scope = None+ raise OSError("temporary read failure")+ return await super().load(scope)++ async def run():+ source = FlakySource()+ manager, _ = _make_manager(source)+ await manager.get_account("ov-a", "vlm")+ await source.update(ConfigScope.account("ov-a"), lambda _: {"vlm": {"model": "new"}})+ source.fail_scope = ConfigScope.account("ov-a")+ await manager.refresh_once()+ assert (await manager.get_account("ov-a", "vlm")).model is None+ await manager.refresh_once()+ assert (await manager.get_account("ov-a", "vlm")).model == "new"++ asyncio.run(run())+++def test_refresh_does_not_resurrect_evicted_account():+ async def run():+ source = MemoryConfigSource()+ manager, _ = _make_manager(source)+ # never loaded; a stray storage change must not create the account+ await source.update(ConfigScope.account("ov-x"), lambda _: {"vlm": {"model": "x"}})+ await manager.refresh_once()+ assert "ov-x" not in manager._accounts++ asyncio.run(run())+++# -- AccountConfig field attributes + manager fallback ------------------------+++def test_account_config_field_attributes():+ fields = AccountConfig.model_fields+ assert set(fields) == {"acl", "agent_evolution", "github"}+ assert is_dynamic(fields["github"])+ assert fallback_of(fields["github"]) is None+ assert is_dynamic(fields["agent_evolution"])+ assert fallback_of(fields["agent_evolution"]) == "agent_evolution"+ assert collect_frozen_paths(AccountConfig) == set()+++def test_account_config_ignores_inactive_sections_during_known_patch():+ async def run():+ from openviking.config.binding import manager_over_source+ from openviking_cli.utils.config import set_openviking_config+ from openviking_cli.utils.config.open_viking_config import (+ OpenVikingConfig,+ OpenVikingConfigSingleton,+ )++ source = MemoryConfigSource()+ scope = ConfigScope.account("ov-a")+ inactive_section = {"model": "unused"}+ await source.update(scope, lambda _: {"vlm": inactive_section})++ base = OpenVikingConfig.from_dict({})+ set_openviking_config(base)+ manager = manager_over_source(source, base_config=base)+ await manager.initialize()+ try:+ assert await manager.get_account("ov-a", "acl") is None+ await manager.patch_account("ov-a", {"acl": {"enabled": True}})+ assert await source.load(scope) == {+ "vlm": inactive_section,+ "acl": {"enabled": True},+ }+ finally:+ OpenVikingConfigSingleton.reset_instance()++ asyncio.run(run())+++def test_account_patch_rejects_inactive_fields_and_allows_active_fields():+ validate_patch(AccountConfig, {"github": {"token": "t"}})+ with pytest.raises(ConfigPatchError, match="github.tokne"):+ validate_patch(AccountConfig, {"github": {"tokne": "t"}})+ with pytest.raises(ConfigPatchError):+ validate_patch(AccountConfig, {"vlm": {"model": "m"}})+ with pytest.raises(ConfigPatchError):+ validate_patch(AccountConfig, {"embedding": {"dense": {"model": "m"}}}, creating=True)+++def test_manager_resolves_account_override_fallback_and_no_fallback():+ async def run():+ manager, holder = _make_manager(MemoryConfigSource())+ holder["config"] = ClusterConfig(vlm=VLMSection(model="cluster-vlm"))++ assert (await manager.get_account("ov-a", "vlm")).model == "cluster-vlm"+ assert await manager.get_account("ov-a", "switch") is None++ await manager.patch_account(+ "ov-a",+ {+ "vlm": {"model": "account-vlm"},+ "switch": {"enabled": True},+ },+ )+ assert (await manager.get_account("ov-a", "vlm")).model == "account-vlm"+ assert (await manager.get_account("ov-a", "switch")).enabled is True++ asyncio.run(run())+++def test_account_config_acl_agent_evolution_are_dynamic_no_fallback():+ fields = AccountConfig.model_fields+ for name in ("acl", "github"):+ assert is_dynamic(fields[name]) # writable at create + PATCH+ assert fallback_of(fields[name]) is None # no cluster fallback+ assert fallback_of(fields["agent_evolution"]) == "agent_evolution"+ # dynamic => not frozen; a normal PATCH may set them.+ validate_patch(AccountConfig, {"acl": {"enabled": True}})+ validate_patch(AccountConfig, {"agent_evolution": {"enabled": False}})+++def test_runtime_cluster_ignores_future_top_level_override_and_preserves_it():+ async def run():+ from openviking.config.binding import manager_over_source+ from openviking_cli.utils.config import set_openviking_config+ from openviking_cli.utils.config.open_viking_config import (+ OpenVikingConfig,+ OpenVikingConfigSingleton,+ )++ source = MemoryConfigSource()+ future_section = {"enabled": True, "nested": {"version": 2}}+ await source.update(ConfigScope.cluster(), lambda _: {"future_section": future_section})+ base = OpenVikingConfig.from_dict({})+ set_openviking_config(base)+ manager = manager_over_source(source, base_config=base)+ await manager.initialize()+ try:+ await manager.patch_cluster({"agent_evolution": {"enabled": True}})+ assert (await source.load(ConfigScope.cluster())) == {+ "future_section": future_section,+ "agent_evolution": {"enabled": True},+ }+ finally:+ OpenVikingConfigSingleton.reset_instance()++ asyncio.run(run())+++def test_persisted_known_sections_ignore_future_nested_fields():+ from openviking.config.binding import _build_account, _build_cluster+ from openviking_cli.utils.config.open_viking_config import OpenVikingConfig++ cluster = _build_cluster(+ OpenVikingConfig.from_dict({}),+ {"agent_evolution": {"enabled": True, "future_option": 1}},+ )+ assert cluster.agent_evolution.enabled is True++ account = _build_account(+ {+ "github": {"token": "t", "future_option": True},+ "acl": {"enabled": True, "retired_field": False},+ }+ )+ assert account.github.token == "t"+ assert account.acl.enabled is True+++def test_openviking_config_ignores_unknown_top_level_field():+ from openviking_cli.utils.config.open_viking_config import OpenVikingConfig++ config = OpenVikingConfig.from_dict({"future_section": {"enabled": True}})++ assert "future_section" not in config.model_dump()+++def test_manager_fallback_reads_latest_cluster_snapshot():+ async def run():+ manager, _ = _make_manager(MemoryConfigSource())+ await manager.patch_cluster({"vlm": {"model": "v1"}})+ assert (await manager.get_account("ov-a", "vlm")).model == "v1"+ await manager.patch_cluster({"vlm": {"model": "v2"}})+ assert (await manager.get_account("ov-a", "vlm")).model == "v2"++ asyncio.run(run())+++def test_real_agent_evolution_precedence_and_fallback():+ async def run():+ from openviking.config.binding import manager_over_source+ from openviking_cli.utils.config import set_openviking_config+ from openviking_cli.utils.config.open_viking_config import (+ OpenVikingConfig,+ OpenVikingConfigSingleton,+ )++ base = OpenVikingConfig.from_dict(+ {"agent_evolution": {"enabled": False}}+ )+ set_openviking_config(base)+ manager = manager_over_source(MemoryConfigSource(), base_config=base)+ await manager.initialize()+ try:+ assert not (await manager.get_account("ov-a", "agent_evolution")).enabled++ await manager.patch_cluster({"agent_evolution": {"enabled": True}})+ assert (await manager.get_account("ov-a", "agent_evolution")).enabled++ await manager.patch_account(+ "ov-a", {"agent_evolution": {"enabled": False}}+ )+ assert not (await manager.get_account("ov-a", "agent_evolution")).enabled++ await manager.patch_account("ov-a", {"agent_evolution": None})+ assert (await manager.get_account("ov-a", "agent_evolution")).enabled+ finally:+ OpenVikingConfigSingleton.reset_instance()++ asyncio.run(run())+++# -- FileConfigSource plaintext read / magic write ----------------------------+++class _FakeAGFS:+ """Minimal in-memory AGFS stand-in for FileConfigSource tests."""++ def __init__(self):+ self.files: dict[str, bytes] = {}++ async def read(self, path, *a, **k):+ from openviking.pyagfs import AGFSNotFoundError++ if path not in self.files:+ raise AGFSNotFoundError(path)+ return self.files[path]++ async def write(self, path, data, *a, **k):+ self.files[path] = data if isinstance(data, bytes) else bytes(data)+ return path++ async def ensure_parent_dirs(self, path, *a, **k):+ return {}++ async def mv(self, old_path, new_path, **kwargs):+ self.files[new_path] = self.files.pop(old_path)++ async def rm(self, path, *a, **k):+ self.files.pop(path, None)+ return {}++ async def stat(self, path, *a, **k):+ from openviking.pyagfs import AGFSNotFoundError++ if path not in self.files:+ raise AGFSNotFoundError(path)+ return {"size": len(self.files[path]), "modTime": 1}++ async def pathlock_acquire_exact(self, path, *a, **k):+ return {"lease_ref": "lease-1"}++ async def pathlock_release(self, lease, *a, **k):+ return None+++def test_file_source_reads_and_writes_plaintext_json():+ async def run():+ import json++ agfs = _FakeAGFS()+ account_path = "/local/ov-a/_system/setting.json"+ agfs.files[account_path] = json.dumps({"vlm": {"model": "legacy"}}).encode("utf-8")++ source = FileConfigSource(agfs)+ scope = ConfigScope.account("ov-a")+ assert await source.load(scope) == {"vlm": {"model": "legacy"}}++ await source.update(scope, lambda cur: {**(cur or {}), "vlm": {"model": "new"}})+ # Written as plaintext JSON; AGFS applies transparent encryption at rest,+ # so this layer never adds an application-level codec.+ assert json.loads(agfs.files[account_path].decode("utf-8")) == {"vlm": {"model": "new"}}+ assert agfs.files["/local/ov-a/_system/setting.backup.json"] == json.dumps(+ {"vlm": {"model": "legacy"}}+ ).encode("utf-8")+ assert await source.load(scope) == {"vlm": {"model": "new"}}++ asyncio.run(run())+++def test_file_source_cluster_scope_path_and_load():+ async def run():+ agfs = _FakeAGFS()+ source = FileConfigSource(agfs)+ scope = ConfigScope.cluster()+ assert await source.load(scope) is None # no override yet+ await source.update(scope, lambda cur: {"memory": {"extraction_enabled": False}})+ assert "/local/_system/runtime_config/cluster.json" in agfs.files+ assert await source.load(scope) == {"memory": {"extraction_enabled": False}}++ asyncio.run(run())+++def test_file_source_failed_publish_preserves_previous_file():+ class FailingAGFS(_FakeAGFS):+ fail_next_target_write = True++ async def write(self, path, data, *args, **kwargs):+ if path.endswith("/setting.json") and self.fail_next_target_write:+ self.fail_next_target_write = False+ raise OSError("publish failed")+ return await super().write(path, data, *args, **kwargs)++ async def run():+ agfs = FailingAGFS()+ path = "/local/ov-a/_system/setting.json"+ agfs.files[path] = b'{"github":{"token":"old"}}'+ source = FileConfigSource(agfs)+ with pytest.raises(OSError, match="publish failed"):+ await source.update(ConfigScope.account("ov-a"), lambda _: {"github": {"token": "new"}})+ assert await source.load(ConfigScope.account("ov-a")) == {"github": {"token": "old"}}++ asyncio.run(run())+++def test_file_source_recovers_from_backup_when_publish_and_rollback_are_interrupted():+ class InterruptedAGFS(_FakeAGFS):+ async def write(self, path, data, *args, **kwargs):+ if path.endswith("/setting.json"):+ self.files[path] = b'{"github":'+ raise OSError("interrupted publish")+ return await super().write(path, data, *args, **kwargs)++ async def run():+ agfs = InterruptedAGFS()+ path = "/local/ov-a/_system/setting.json"+ agfs.files[path] = b'{"github":{"token":"old"}}'+ source = FileConfigSource(agfs)++ with pytest.raises(OSError, match="interrupted publish"):+ await source.update(+ ConfigScope.account("ov-a"),+ lambda _: {"github": {"token": "new"}},+ )++ assert agfs.files[path] == b'{"github":'+ assert await source.load(ConfigScope.account("ov-a")) == {"github": {"token": "old"}}++ asyncio.run(run())+++def test_file_source_rejects_invalid_config_without_backup():+ async def run():+ agfs = _FakeAGFS()+ path = "/local/ov-a/_system/setting.json"+ agfs.files[path] = b'{"github":'++ source = FileConfigSource(agfs)++ with pytest.raises(RuntimeError, match="no valid backup"):+ await source.load(ConfigScope.account("ov-a"))++ asyncio.run(run())+++def test_refresh_keeps_last_value_after_corruption_and_retries():+ async def run():+ import json++ agfs = _FakeAGFS()+ path = "/local/ov-a/_system/setting.json"+ agfs.files[path] = json.dumps({"vlm": {"model": "old"}}).encode()+ manager, _ = _make_manager(FileConfigSource(agfs))+ await manager.initialize()+ assert (await manager.get_account("ov-a", "vlm")).model == "old"++ agfs.files[path] = b'{"vlm":'+ await manager.refresh_once()+ assert (await manager.get_account("ov-a", "vlm")).model == "old"++ agfs.files[path] = json.dumps({"vlm": {"model": "new"}}).encode()+ await manager.refresh_once()+ assert (await manager.get_account("ov-a", "vlm")).model == "new"++ asyncio.run(run())+++def test_file_source_supports_repeated_update_and_idempotent_delete():+ async def run():+ agfs = _FakeAGFS()+ source = FileConfigSource(agfs)+ scope = ConfigScope.account("ov-a")++ await source.update(scope, lambda _: {"acl": {"enabled": True}})+ await source.update(scope, lambda _: {"acl": {"enabled": False}})+ assert await source.load(scope) == {"acl": {"enabled": False}}++ await source.delete(scope)+ await source.delete(scope)+ assert await source.load(scope) is None+ assert "/local/ov-a/_system/setting.backup.json" not in agfs.files++ asyncio.run(run())+++# -- registry / scope / startup assembly --------------------------------------+++def test_registry_create_known_and_unknown():+ src = create_config_source("memory", ConfigSourceContext())+ assert isinstance(src, MemoryConfigSource)+ with pytest.raises(ValueError):+ create_config_source("does-not-exist", ConfigSourceContext())+++def test_scope_rejects_bad_account_and_cluster_key():+ with pytest.raises(ValueError):+ ConfigScope(ScopeKind.ACCOUNT, "../etc")+ with pytest.raises(ValueError):+ ConfigScope(ScopeKind.CLUSTER, "unexpected-key")+++def test_build_config_source_rejects_kernel_owned_file_source():+ from openviking.config import build_config_source++ # ``file`` is kernel-owned because it is the only source allowed to see AGFS.+ with pytest.raises(ValueError, match="kernel-owned"):+ build_config_source(None)+++def test_plugin_source_receives_params_without_kernel_dependencies():+ from openviking.config import build_config_source, register_config_source++ captured = {}++ @register_config_source("params-only-test")+ def _build_plugin_source(ctx):+ captured["ctx"] = ctx+ return MemoryConfigSource(ctx)++ src = build_config_source(+ {"source": "params-only-test", "params": {"namespace": "ns-1"}}+ )+ assert isinstance(src, MemoryConfigSource)+ assert captured["ctx"].params == {"namespace": "ns-1"}+ assert not hasattr(captured["ctx"], "extras")+++def test_build_config_source_loads_configured_plugin_module(monkeypatch):+ from openviking.config import assembly, build_config_source, register_config_source++ loaded = []++ def load_module(module_path):+ loaded.append(module_path)++ @register_config_source("module-loaded-test")+ def _build_module_source(ctx):+ return MemoryConfigSource(ctx)++ monkeypatch.setattr(assembly, "load_config_source_module", load_module)+ source = build_config_source(+ {+ "source": "module-loaded-test",+ "module": "company.openviking.config_source",+ "params": {"namespace": "module"},+ }+ )++ assert isinstance(source, MemoryConfigSource)+ assert loaded == ["company.openviking.config_source"]+++def test_runtime_manager_constructs_file_source_inside_kernel():+ from openviking.config.binding import build_runtime_config_manager+ from openviking_cli.utils.config import set_openviking_config+ from openviking_cli.utils.config.open_viking_config import (+ OpenVikingConfig,+ OpenVikingConfigSingleton,+ )++ agfs = _FakeAGFS()+ base = OpenVikingConfig.from_dict({})+ set_openviking_config(base)+ try:+ manager = build_runtime_config_manager(+ agfs,+ settings={"source": "file"},+ base_config=base,+ )+ assert isinstance(manager._source, FileConfigSource)+ assert manager._source._client is agfs+ finally:+ OpenVikingConfigSingleton.reset_instance()+++def test_runtime_config_settings_ignores_unknown_field():+ from openviking.config import RuntimeConfigSettings++ settings = RuntimeConfigSettings(bogus=1)++ assert settings == RuntimeConfigSettings()diff --git a/tests/retrieve/test_hierarchical_retriever_rerank.py b/tests/retrieve/test_hierarchical_retriever_rerank.pyindex 56509e3c6..3dbeb8b98 100644--- a/tests/retrieve/test_hierarchical_retriever_rerank.py+++ b/tests/retrieve/test_hierarchical_retriever_rerank.py@@ -56,8 +56,8 @@ class DummyStorage:self.search_calls = []self.child_search_calls = []- def _acl_enabled(self, ctx: RequestContext) -> bool:- return self.acl_manager is not None and self.acl_manager.is_enabled(ctx.account_id)+ async def _acl_enabled(self, ctx: RequestContext) -> bool:+ return self.acl_manager is not None and await self.acl_manager.is_enabled(ctx.account_id)async def collection_exists_bound(self) -> bool:return True@@ -374,7 +374,10 @@ async def test_retrieve_falls_back_to_vector_scores_when_rerank_returns_none(mon_result("viking://resources/a/deep-a.md", 0.2, abstract="deep A"),_result("viking://resources/b/deep-b.md", 0.8, abstract="deep B"),])- storage.acl_manager = SimpleNamespace(is_enabled=lambda _account_id: True)+ async def acl_enabled(_account_id):+ return True++ storage.acl_manager = SimpleNamespace(is_enabled=acl_enabled)async def no_hierarchical_children(*_args, **_kwargs):return []diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.pyindex 7ff95c6f3..4ed841653 100644--- a/tests/server/test_admin_api.py+++ b/tests/server/test_admin_api.py@@ -1660,6 +1660,39 @@ async def test_create_account(admin_client: httpx.AsyncClient, admin_service: Opassert await admin_service.viking_fs.abstract("viking://user", ctx=ctx)+async def test_create_account_rolls_back_when_runtime_config_write_fails(+ admin_client: httpx.AsyncClient,+ admin_service: OpenVikingService,+ admin_app: FastAPI,+ monkeypatch: pytest.MonkeyPatch,+):+ """A post-registry initialization failure must not leave a half-created account."""+ acct = _uid()++ async def fail_patch(*args, **kwargs):+ raise OSError("runtime config unavailable")++ monkeypatch.setattr(+ admin_service.runtime_config_manager,+ "patch_account",+ fail_patch,+ )++ response = await admin_client.post(+ "/api/v1/admin/accounts",+ json={+ "account_id": acct,+ "admin_user_id": "alice",+ "settings": {"github": {"token": "account-token"}},+ },+ headers=root_headers(),+ )++ assert response.status_code == 500+ assert not any(item["account_id"] == acct for item in admin_app.state.api_key_manager.get_accounts())+ assert not await _agfs_exists(admin_service, f"/local/{acct}")++async def test_create_user_paths_accept_initial_user_config(lightweight_admin_client: httpx.AsyncClient,lightweight_admin_app: FastAPI,@@ -2226,6 +2259,57 @@ async def test_delete_account(assert manager.resolve(replacement_key).user_id == "bob"+async def test_delete_account_retries_when_runtime_config_cleanup_fails(+ admin_client: httpx.AsyncClient,+ admin_service: OpenVikingService,+ admin_app: FastAPI,+ monkeypatch: pytest.MonkeyPatch,+):+ """Config cleanup failure keeps the deletion fence and can be retried."""+ acct = _uid()+ resp = await admin_client.post(+ "/api/v1/admin/accounts",+ json={"account_id": acct, "admin_user_id": "alice"},+ headers=root_headers(),+ )+ user_key = resp.json()["result"]["user_key"]+ runtime_config = admin_service.runtime_config_manager+ delete_config = AsyncMock(side_effect=OSError("provider unavailable"))+ monkeypatch.setattr(runtime_config, "delete_account", delete_config)++ resp = await admin_client.delete(+ f"/api/v1/admin/accounts/{acct}",+ headers=root_headers(),+ )+ assert resp.status_code == 202+ failed = await _wait_for_task(admin_client, resp.json()["result"]["task_id"])+ assert failed["status"] == "failed"+ assert "provider unavailable" in failed["error"]+ denied = await admin_client.get(+ "/api/v1/fs/ls?uri=viking://",+ headers={"X-API-Key": user_key},+ )+ assert denied.status_code == 401+ assert admin_app.state.api_key_manager.get_deletion(acct) is not None++ conflict = await admin_client.post(+ "/api/v1/admin/accounts",+ json={"account_id": acct, "admin_user_id": "replacement"},+ headers=root_headers(),+ )+ assert conflict.status_code == 409++ delete_config.side_effect = None+ retry = await admin_client.delete(+ f"/api/v1/admin/accounts/{acct}",+ headers=root_headers(),+ )+ completed = await _wait_for_task(admin_client, retry.json()["result"]["task_id"])+ assert completed["status"] == "completed"+ assert admin_app.state.api_key_manager.get_deletion(acct) is None+ assert delete_config.await_count == 2++async def test_create_duplicate_account_fails(admin_client: httpx.AsyncClient):"""Creating duplicate account should fail."""acct = _uid()diff --git a/tests/server/test_agent_evolution_global_setting.py b/tests/server/test_agent_evolution_global_setting.pyindex 1fb7888a9..811622abc 100644--- a/tests/server/test_agent_evolution_global_setting.py+++ b/tests/server/test_agent_evolution_global_setting.py@@ -1,7 +1,6 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-import jsonfrom types import SimpleNamespacefrom unittest.mock import AsyncMock@@ -10,21 +9,12 @@ import pytestimport pytest_asynciofrom openviking.pyagfs import AGFSNotFoundError-from openviking.server.account_settings import (- AccountAclSettings,- AccountAgentEvolutionSettings,- AccountSettingsPatch,- account_settings_backup_path,- account_settings_path,- read_account_settings,- update_account_settings,-)-from openviking.server.agent_evolution_config import AgentEvolutionConfigProviderfrom openviking.server.app import create_appfrom openviking.server.auth.plugins import DevAuthPluginfrom openviking.server.config import AgentEvolutionConfig, ServerConfig, UserConfigfrom openviking.server.dependencies import set_servicefrom openviking.server.identity import RequestContext, Role+from openviking.service.core import OpenVikingServicefrom openviking.service.session_service import SessionServicefrom openviking.session import Sessionfrom openviking_cli.session.user_id import UserIdentifier@@ -45,6 +35,11 @@ class _FakeAGFS:self.files[path] = bytes(data)return path+ def mv(self, old_path, new_path, ctx=None):+ del ctx+ self.files[new_path] = self.files.pop(old_path)+ return {}+def ensure_parent_dirs(self, path, ctx=None):del pathdel ctx@@ -69,16 +64,42 @@ class _FakeAGFS:class _FakeAclManager:def __init__(self):- self.enabled_accounts: set[str] = set()+ self.runtime_config = None++ def set_runtime_config_manager(self, runtime_config) -> None:+ self.runtime_config = runtime_config++ async def is_enabled(self, account_id: str) -> bool:+ setting = await self.runtime_config.get_account(account_id, "acl")+ return setting.enabled if setting is not None else False+++class _FakeRuntimeConfig:+ def __init__(self):+ self.values = {}++ async def get_account(self, account_id: str, field: str):+ return self.values.get((account_id, field))+++class _FakeApiKeyManager:+ """Minimal admin-gate stand-in: account existence + user refresh no-ops."""++ def __init__(self, account_ids):+ self._account_ids = list(account_ids)++ async def refresh_accounts_from_store(self):+ return None++ async def refresh_account_users_from_store(self, account_id):+ return None- def set_enabled(self, account_id: str, enabled: bool) -> None:- if enabled:- self.enabled_accounts.add(account_id)- else:- self.enabled_accounts.discard(account_id)+ def ensure_account_active(self, account_id):+ if account_id not in self._account_ids:+ raise AssertionError(f"unexpected account: {account_id}")- def is_enabled(self, account_id: str) -> bool:- return account_id in self.enabled_accounts+ def get_accounts(self):+ return [{"account_id": aid} for aid in self._account_ids]@pytest.fixture@@ -92,18 +113,45 @@ async def settings_http(fake_viking_fs, monkeypatch):"openviking.server.routers.admin.get_openviking_config",lambda: SimpleNamespace(default_account="default"),)+ from openviking.config.binding import manager_over_source+ from openviking.config.source import MemoryConfigSource+ from openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingleton++ OpenVikingConfigSingleton.reset_instance()+ OpenVikingConfigSingleton.initialize(+ config_dict={+ "embedding": {+ "dense": {+ "provider": "openai",+ "model": "test-embedder",+ "api_key": "test-key",+ "dimension": 1024,+ }+ },+ }+ )++ source = MemoryConfigSource()+ runtime_config = manager_over_source(source)+ await runtime_config.initialize()sessions = SessionService(viking_fs=fake_viking_fs)- service = SimpleNamespace(sessions=sessions, viking_fs=fake_viking_fs)+ sessions.set_runtime_config_manager(runtime_config)+ fake_viking_fs.acl_manager.set_runtime_config_manager(runtime_config)+ service = SimpleNamespace(+ sessions=sessions,+ viking_fs=fake_viking_fs,+ runtime_config_manager=runtime_config,+ )app = create_app(config=ServerConfig(), service=service)set_service(service)app.state.auth_plugin = DevAuthPlugin()+ # Admin routes gate on a present APIKeyManager; DevAuthPlugin resolves ROOT+ # but leaves it None, so provide a stand-in that reports the default account.+ app.state.api_key_manager = _FakeApiKeyManager(["default"])transport = httpx.ASGITransport(app=app)async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:yield client, service---def _patch(enabled: bool) -> AccountSettingsPatch:- return AccountSettingsPatch(agent_evolution=AccountAgentEvolutionSettings(enabled=enabled))+ OpenVikingConfigSingleton.reset_instance()def test_agent_evolution_is_disabled_by_default():@@ -116,7 +164,49 @@ def test_agent_evolution_can_be_enabled_as_account_default():assert config.agent_evolution.enabled is True-def test_server_default_memory_policy_is_configured_on_session_service(fake_viking_fs):+def test_server_agent_evolution_seeds_runtime_cluster_baseline():+ sessions = SessionService()+ service = object.__new__(OpenVikingService)+ service._session_service = sessions++ service.set_agent_evolution_config(AgentEvolutionConfig(enabled=True))++ assert service._agent_evolution_base_config.enabled is True+ assert sessions._agent_evolution_default_enabled is True+++async def test_server_agent_evolution_updates_initialized_runtime_baseline():+ from openviking.config.binding import manager_over_source+ from openviking.config.source import MemoryConfigSource+ from openviking_cli.utils.config import set_openviking_config+ from openviking_cli.utils.config.open_viking_config import (+ OpenVikingConfig,+ OpenVikingConfigSingleton,+ )++ base = OpenVikingConfig.from_dict({})+ set_openviking_config(base)+ manager = manager_over_source(MemoryConfigSource(), base_config=base)+ await manager.initialize()+ service = object.__new__(OpenVikingService)+ service._config = base+ service._runtime_config_manager = manager+ service._session_service = SessionService()+ service.set_agent_evolution_config(AgentEvolutionConfig(enabled=True))+ try:+ await service.apply_agent_evolution_config()+ assert (await manager.get_account("default", "agent_evolution")).enabled+ finally:+ OpenVikingConfigSingleton.reset_instance()+++def test_server_default_memory_policy_is_configured_on_session_service(+ fake_viking_fs, monkeypatch+):+ monkeypatch.setattr(+ "openviking.service.session_service.get_default_registry",+ lambda: SimpleNamespace(list_names=lambda **_: ["profile"]),+ )sessions = SessionService(viking_fs=fake_viking_fs)service = SimpleNamespace(sessions=sessions)config = ServerConfig(@@ -133,14 +223,15 @@ def test_server_default_memory_policy_is_configured_on_session_service(fake_vikiasync def test_existing_session_observes_updated_account_value(fake_viking_fs):+ runtime_config = _FakeRuntimeConfig()service = SessionService(viking_fs=fake_viking_fs)service.set_agent_evolution_config(AgentEvolutionConfig(enabled=False))- service.set_agent_evolution_config_path(None)+ service.set_runtime_config_manager(runtime_config)session = service.session(RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT))- await update_account_settings(fake_viking_fs, "default", _patch(True))+ runtime_config.values[("default", "agent_evolution")] = SimpleNamespace(enabled=True)assert await session._agent_evolution_enabled_provider() is True@@ -166,72 +257,6 @@ def test_session_positional_usage_reporter_remains_compatible():assert session._agent_evolution_enabled_provider is None-async def test_provider_reloads_ov_conf_and_account_override(fake_viking_fs, tmp_path):- config_path = tmp_path / "ov.conf"- config_path.write_text(- json.dumps({"server": {"agent_evolution": {"enabled": False}}}),- encoding="utf-8",- )- provider = AgentEvolutionConfigProvider(- default_enabled=True,- viking_fs=fake_viking_fs,- config_path=config_path,- )-- assert await provider.is_enabled("default") is False-- config_path.write_text(- json.dumps({"server": {"agent_evolution": {"enabled": True}}}),- encoding="utf-8",- )- assert await provider.is_enabled("default") is True-- await update_account_settings(fake_viking_fs, "default", _patch(False))- assert await provider.is_enabled("default") is False---async def test_account_overrides_are_isolated(fake_viking_fs):- provider = AgentEvolutionConfigProvider(- default_enabled=False,- viking_fs=fake_viking_fs,- )- await update_account_settings(fake_viking_fs, "account-a", _patch(True))-- assert await provider.is_enabled("account-a") is True- assert await provider.is_enabled("account-b") is False---async def test_account_settings_update_backs_up_previous_file(fake_viking_fs):- legacy_settings = json.dumps(- {- "namespace": {- "isolate_user_scope_by_agent": True,- "isolate_agent_scope_by_user": False,- },- "agent_evolution": {"enabled": False},- "acl": {"enabled": True, "retired_field": False},- }- ).encode("utf-8")- fake_viking_fs.agfs.files[account_settings_path("default")] = legacy_settings-- settings = await read_account_settings(fake_viking_fs, "default")- assert settings.model_dump(exclude_none=True) == {- "agent_evolution": {"enabled": False},- "acl": {"enabled": True},- }- assert fake_viking_fs.agfs.files[account_settings_path("default")] == legacy_settings-- await update_account_settings(fake_viking_fs, "default", _patch(True))-- current = fake_viking_fs.agfs.files[account_settings_path("default")]- backup = fake_viking_fs.agfs.files[account_settings_backup_path("default")]- assert json.loads(current) == {- "agent_evolution": {"enabled": True},- "acl": {"enabled": True},- }- assert backup == legacy_settings--async def test_account_settings_admin_api_reads_and_updates_effective_value(settings_http,):@@ -263,10 +288,113 @@ async def test_account_settings_admin_api_reads_and_updates_effective_value("agent_evolution": {"enabled": True},"acl": {"enabled": True},}- settings = await read_account_settings(service.viking_fs, "default")- assert settings.agent_evolution.enabled- assert settings.acl == AccountAclSettings(enabled=True)- assert service.viking_fs.acl_manager.is_enabled("default")+ assert (+ await service.runtime_config_manager.get_account("default", "agent_evolution")+ ).enabled+ assert (await service.runtime_config_manager.get_account("default", "acl")).enabled+ assert await service.viking_fs.acl_manager.is_enabled("default")+++async def test_legacy_account_settings_preserves_null_and_empty_object_semantics(+ settings_http,+):+ client, _ = settings_http+ enabled = await client.patch(+ "/api/v1/admin/accounts/default/settings",+ json={+ "agent_evolution": {"enabled": True},+ "acl": {"enabled": True},+ },+ )+ assert enabled.status_code == 200, enabled.text++ unchanged = await client.patch(+ "/api/v1/admin/accounts/default/settings",+ json={"agent_evolution": None, "acl": None},+ )+ assert unchanged.status_code == 200, unchanged.text+ assert unchanged.json()["result"]["overrides"] == {+ "agent_evolution": {"enabled": True},+ "acl": {"enabled": True},+ }++ disabled = await client.patch(+ "/api/v1/admin/accounts/default/settings",+ json={"acl": {}},+ )+ assert disabled.status_code == 200, disabled.text+ assert disabled.json()["result"]["overrides"]["acl"] == {"enabled": False}+++async def test_account_configuration_exposes_three_state_layer(settings_http):+ client, _ = settings_http++ updated = await client.patch(+ "/api/v1/admin/accounts/default/configuration",+ json={+ "settings": {+ "github": {"token": "account-token"},+ "acl": {"enabled": True},+ }+ },+ )+ assert updated.status_code == 200, updated.text+ assert updated.json()["result"] == {+ "account_id": "default",+ "settings": {+ "github": {"token": "account-token"},+ "acl": {"enabled": True},+ },+ }++ removed = await client.patch(+ "/api/v1/admin/accounts/default/configuration",+ json={"settings": {"acl": None}},+ )+ assert removed.status_code == 200, removed.text+ assert removed.json()["result"]["settings"] == {+ "github": {"token": "account-token"}+ }+++async def test_cluster_agent_evolution_override_is_account_fallback(settings_http):+ client, service = settings_http++ updated = await client.patch(+ "/api/v1/admin/configuration",+ json={"settings": {"agent_evolution": {"enabled": True}}},+ )+ assert updated.status_code == 200, updated.text+ assert updated.json()["result"]["settings"] == {+ "agent_evolution": {"enabled": True}+ }+ assert await service.sessions.get_agent_evolution_enabled("default")++ await service.runtime_config_manager.patch_account(+ "default", {"agent_evolution": {"enabled": False}}+ )+ assert not await service.sessions.get_agent_evolution_enabled("default")++ await service.runtime_config_manager.patch_account(+ "default", {"agent_evolution": None}+ )+ assert await service.sessions.get_agent_evolution_enabled("default")+++async def test_legacy_admin_configuration_routes_are_deprecated(settings_http):+ client, _ = settings_http+ schema = client._transport.app.openapi()++ assert schema["paths"]["/api/v1/admin/agent-evolution"]["get"]["deprecated"]+ assert schema["paths"]["/api/v1/admin/agent-evolution"]["put"]["deprecated"]+ legacy = schema["paths"]["/api/v1/admin/accounts/{account_id}/settings"]+ assert legacy["get"]["deprecated"]+ assert legacy["patch"]["deprecated"]+ assert not schema["paths"][+ "/api/v1/admin/accounts/{account_id}/configuration"+ ]["patch"].get("deprecated", False)+ assert "/api/v1/admin/configuration" in schema["paths"]+ assert "/api/v1/admin/settings" not in schema["paths"]async def test_account_settings_admin_api_rejects_non_allowlisted_fields(@@ -299,7 +427,9 @@ async def test_agent_evolution_endpoint_keeps_name_and_uses_account_settings(assert response.status_code == 200, response.textassert response.json()["result"]["enabled"] is True- assert (await read_account_settings(service.viking_fs, "default")).agent_evolution.enabled+ assert (+ await service.runtime_config_manager.get_account("default", "agent_evolution")+ ).enableddef test_deprecated_user_agent_evolution_config_is_not_persisted():@@ -316,12 +446,14 @@ async def test_manual_extract_respects_account_setting(fake_viking_fs):viking_fs=fake_viking_fs,session_compressor=compressor,)+ runtime_config = _FakeRuntimeConfig()+ runtime_config.values[("default", "agent_evolution")] = SimpleNamespace(enabled=True)+ service.set_runtime_config_manager(runtime_config)session = SimpleNamespace(uri="viking://user/default/sessions/test-session",messages=[],)service.get = AsyncMock(return_value=session)- await update_account_settings(fake_viking_fs, "default", _patch(True))ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)await service.extract("test-session", ctx)diff --git a/tests/server/test_api_snapshot.py b/tests/server/test_api_snapshot.pyindex 5ed2699e6..295492b57 100644--- a/tests/server/test_api_snapshot.py+++ b/tests/server/test_api_snapshot.py@@ -11,11 +11,6 @@ import pytestimport pytest_asyncioimport openviking.service.reindex_executor as reindex_mod-from openviking.server.account_settings import (- AccountAclSettings,- AccountSettingsPatch,- update_account_settings,-)from openviking.server.app import create_appfrom openviking.server.auth import get_request_contextfrom openviking.server.config import ServerConfig@@ -200,10 +195,8 @@ async def client_with_resource_and_blob(client_with_resource, service):async def test_restore_acl_and_reindex_identity(client_with_resource, service, monkeypatch):_, _root = client_with_resourceadmin = RequestContext(user=service.user, role=Role.ADMIN)- await update_account_settings(- service.viking_fs,- admin.account_id,- AccountSettingsPatch(acl=AccountAclSettings(enabled=True)),+ await service.runtime_config_manager.patch_account(+ admin.account_id, {"acl": {"enabled": True}})writer = RequestContext(user=UserIdentifier(admin.account_id, "snapshot_writer"),diff --git a/tests/server/test_content_write_service.py b/tests/server/test_content_write_service.pyindex a2c093d31..9af29ab41 100644--- a/tests/server/test_content_write_service.py+++ b/tests/server/test_content_write_service.py@@ -8,11 +8,6 @@ from unittest.mock import AsyncMockimport pytest-from openviking.server.account_settings import (- AccountAclSettings,- AccountSettingsPatch,- update_account_settings,-)from openviking.server.identity import RequestContext, Rolefrom openviking.session.memory.dataclass import MemoryFilefrom openviking.session.memory.utils import MemoryFileUtils@@ -136,10 +131,8 @@ async def test_shared_resource_creation_inherits_acl_and_preserves_plain_append(auto_protected_dir = "viking://resources/auto_protected"uri = "viking://resources/append_plain/journal.md"- await update_account_settings(- service.viking_fs,- creator.account_id,- AccountSettingsPatch(acl=AccountAclSettings(enabled=True)),+ await service.runtime_config_manager.patch_account(+ creator.account_id, {"acl": {"enabled": True}})await service.fs.mkdir(auto_protected_dir, ctx=creator)await service.resources.wait_processed()@@ -271,10 +264,8 @@ async def test_shared_resource_creation_inherits_acl_and_preserves_plain_append(with pytest.raises(PermissionDeniedError):await service.viking_fs.read_file(uri, ctx=outsider)- await update_account_settings(- service.viking_fs,- creator.account_id,- AccountSettingsPatch(acl=AccountAclSettings(enabled=False)),+ await service.runtime_config_manager.patch_account(+ creator.account_id, {"acl": {"enabled": False}})assert await service.viking_fs.read_file(uri, ctx=outsider) == storeddiff --git a/tests/server/test_watch_task_acl.py b/tests/server/test_watch_task_acl.pyindex fa41798be..2312f4166 100644--- a/tests/server/test_watch_task_acl.py+++ b/tests/server/test_watch_task_acl.py@@ -53,7 +53,10 @@ class _NoWriteVikingFS:)@pytest.mark.asyncioasync def test_watch_task_control_files_are_root_only(bare_viking_fs, root_ctx, user_ctx, uri):- bare_viking_fs.acl_manager = SimpleNamespace(is_enabled=lambda _account_id: True)+ async def acl_enabled(_account_id):+ return True++ bare_viking_fs.acl_manager = SimpleNamespace(is_enabled=acl_enabled)await bare_viking_fs._ensure_access(uri, root_ctx)with pytest.raises(PermissionDeniedError):await bare_viking_fs._ensure_access(uri, user_ctx)@@ -63,7 +66,7 @@ async def test_watch_task_control_files_are_root_only(bare_viking_fs, root_ctx,async def test_hidden_listing_filters_watch_task_control_files_for_non_root(bare_viking_fs, root_ctx, user_ctx):- async def ls_entries(path, ctx=None):+ async def ls_entries(path, **_kwargs):return [{"name": ".watch_tasks.json",diff --git a/tests/service/test_resource_service_connector.py b/tests/service/test_resource_service_connector.pyindex 19f9b1676..7c641254e 100644--- a/tests/service/test_resource_service_connector.py+++ b/tests/service/test_resource_service_connector.py@@ -41,6 +41,11 @@ class _FakeEncryptor:return ciphertext[4:][::-1]+class _FakeResourceProcessor:+ async def github_token_for(self, *_args, **_kwargs):+ return None++@pytest.fixturedef connector_config(monkeypatch):import openviking_cli.utils.config.open_viking_config as config_module@@ -94,7 +99,7 @@ def service():return ResourceService(vikingdb=object(),viking_fs=SimpleNamespace(exists=AsyncMock(return_value=True)),- resource_processor=object(),+ resource_processor=_FakeResourceProcessor(),skill_processor=object(),)diff --git a/tests/service/test_resource_service_git_preflight.py b/tests/service/test_resource_service_git_preflight.pyindex 5fd8b8b4a..eb97ded11 100644--- a/tests/service/test_resource_service_git_preflight.py+++ b/tests/service/test_resource_service_git_preflight.py@@ -5,16 +5,96 @@import asyncioimport osimport signal+from types import SimpleNamespacefrom unittest.mock import AsyncMock, Mock, callimport pytest+from openviking.parse.mode import ParseMode+from openviking.server.identity import RequestContext, Role+from openviking.service import resource_service as resource_service_modulefrom openviking.service.resource_service import ResourceServicefrom openviking_cli.exceptions import InvalidArgumentError+from openviking_cli.session.user_id import UserIdentifierpytestmark = pytest.mark.skipif(os.name != "posix", reason="process groups are POSIX-only")+async def test_account_github_token_is_used_for_repository_preflight(monkeypatch):+ token_resolver = AsyncMock(return_value="account-token")+ processor = SimpleNamespace(github_token_for=token_resolver)+ service = ResourceService(resource_processor=processor)+ service._preflight_git_source = AsyncMock(+ return_value=SimpleNamespace(+ source_name="private",+ source_path="https://github.com/org/private",+ source_format="repository",+ )+ )+ monkeypatch.setattr(resource_service_module, "is_git_repo_url", lambda _path: True)+ monkeypatch.setattr(resource_service_module, "is_github_url", lambda _path: True)+ ctx = RequestContext(+ user=UserIdentifier("account-1", "user-1"),+ role=Role.USER,+ )++ plan = await service._prepare_standard_source_plan(+ path="https://github.com/org/private",+ ctx=ctx,+ mode=ParseMode.DEFAULT,+ allow_local_path_resolution=False,+ processor_kwargs={},+ watch_auth_state=None,+ )++ token_resolver.assert_awaited_once_with("https://github.com/org/private", ctx)+ preflight_auth = service._preflight_git_source.await_args.kwargs["auth_config"]+ assert preflight_auth.username == "oauth2"+ assert preflight_auth.token == "account-token"+ assert plan is not None+ assert plan.task_auth == {}+ assert "account-token" not in str(plan.processor_args)+++ "source",+ [+ "[email protected]:org/private.git",+ "ssh://[email protected]/org/private.git",+ ],+)+async def test_default_github_token_is_not_applied_to_ssh_preflight(monkeypatch, source):+ token_resolver = AsyncMock(return_value="account-token")+ processor = SimpleNamespace(github_token_for=token_resolver)+ service = ResourceService(resource_processor=processor)+ service._preflight_git_source = AsyncMock(+ return_value=SimpleNamespace(+ source_name="private",+ source_path=source,+ source_format="repository",+ )+ )+ monkeypatch.setattr(resource_service_module, "is_git_repo_url", lambda _path: True)+ monkeypatch.setattr(resource_service_module, "is_github_url", lambda _path: True)+ ctx = RequestContext(+ user=UserIdentifier("account-1", "user-1"),+ role=Role.USER,+ )++ plan = await service._prepare_standard_source_plan(+ path=source,+ ctx=ctx,+ mode=ParseMode.DEFAULT,+ allow_local_path_resolution=False,+ processor_kwargs={},+ watch_auth_state=None,+ )++ token_resolver.assert_not_awaited()+ service._preflight_git_source.assert_awaited_once_with(source, auth_config=None)+ assert plan is not None++async def test_git_preflight_timeout_kills_process_group_and_bounds_reap(monkeypatch):process = Mock(pid=43210)process.communicate = AsyncMock(return_value=(b"", b""))diff --git a/tests/service/test_resource_service_parse_mode.py b/tests/service/test_resource_service_parse_mode.pyindex bdb90ccae..033740832 100644--- a/tests/service/test_resource_service_parse_mode.py+++ b/tests/service/test_resource_service_parse_mode.py@@ -34,6 +34,9 @@ class _ResourceProcessor:async def prepare_durable_source(self, *_args, **_kwargs):return None+ async def github_token_for(self, *_args, **_kwargs):+ return None+async def finish_prepared_resource(self, *_args, **_kwargs):return {"status": "success"}diff --git a/tests/storage/test_transfer_merge_binding.py b/tests/storage/test_transfer_merge_binding.pyindex 9d4399e95..ee8b11241 100644--- a/tests/storage/test_transfer_merge_binding.py+++ b/tests/storage/test_transfer_merge_binding.py@@ -25,6 +25,12 @@ from openviking_cli.utils.config.agfs_config import AGFSConfigfrom openviking_cli.utils.config.vectordb_config import VectorDBBackendConfig+class _EnabledAclConfig:+ async def get_account(self, account_id: str, field: str):+ del account_id, field+ return SimpleNamespace(enabled=True)++@pytest.fixturedef binding_fs(tmp_path):client_type, _ = get_binding_client()@@ -360,8 +366,7 @@ async def test_overwrite_preserves_target_acl_with_real_storage(],ctx=ctx,)- acl = AclManager(backend)- acl.set_enabled(ctx.account_id, True)+ acl = AclManager(backend, _EnabledAclConfig())fs.acl_manager = backend.acl_manager = aclawait getattr(fs, operation)(source, target, ctx=ctx)@@ -402,8 +407,7 @@ async def test_chunk_only_copy_preserves_private_target_main_record(indexed_fs):"acl_inherited_grants": [],}await backend._upsert_many_raw([old_main], ctx=ctx)- acl = AclManager(backend)- acl.set_enabled(ctx.account_id, True)+ acl = AclManager(backend, _EnabledAclConfig())fs.acl_manager = backend.acl_manager = acloutsider = RequestContext(user=UserIdentifier(ctx.account_id, "outsider"), role=Role(Role.USER))with pytest.raises(PermissionDeniedError):@@ -486,8 +490,7 @@ async def test_transfer_protects_chunk_shaped_target_file(],ctx=ctx,)- acl = AclManager(backend)- acl.set_enabled(ctx.account_id, True)+ acl = AclManager(backend, _EnabledAclConfig())fs.acl_manager = backend.acl_manager = acloutsider = RequestContext(user=UserIdentifier(ctx.account_id, "outsider"), role=Role(Role.USER))with pytest.raises(PermissionDeniedError):@@ -623,11 +626,14 @@ async def test_acl_failure_restores_only_moved_vectors_after_directory_merge(await seed_vector(backend, f"{source}/file.txt", "new")await seed_vector(backend, f"{target}/only.txt", "keep")monkeypatch.setattr(fs, "_ensure_access", AsyncMock())+ async def acl_enabled(_account_id):+ return True+monkeypatch.setattr(fs,"acl_manager",SimpleNamespace(- is_enabled=lambda _: True,+ is_enabled=acl_enabled,refresh_context_subtree=AsyncMock(side_effect=RuntimeError("injected ACL failure")),),)diff --git a/tests/storage/test_vector_transfer.py b/tests/storage/test_vector_transfer.pyindex 2ba6654bf..9d221d076 100644--- a/tests/storage/test_vector_transfer.py+++ b/tests/storage/test_vector_transfer.py@@ -30,6 +30,12 @@ from openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils.config.vectordb_config import VectorDBBackendConfig+class _EnabledAclConfig:+ async def get_account(self, account_id: str, field: str):+ del account_id, field+ return SimpleNamespace(enabled=True)++def _ctx() -> RequestContext:return RequestContext(user=UserIdentifier("acct", "alice"), role=Role.USER)@@ -156,7 +162,7 @@ class _MemoryTransferBackend(VikingVectorIndexBackend):class _TransferAclManager:- def is_enabled(self, account_id: str) -> bool:+ async def is_enabled(self, account_id: str) -> bool:return account_id == "acct"async def materialize_context_records(self, records, ctx):@@ -223,8 +229,7 @@ class _RealAclMemoryTransferBackend(_MemoryTransferBackend):def __init__(self, records: list[dict[str, Any]]) -> None:super().__init__(records)- self.acl_manager = AclManager(self)- self.acl_manager.set_enabled("acct", True)+ self.acl_manager = AclManager(self, _EnabledAclConfig())async def scroll(self,diff --git a/tests/storage/test_viking_fs_cp.py b/tests/storage/test_viking_fs_cp.pyindex 2ead120b0..d8338c04e 100644--- a/tests/storage/test_viking_fs_cp.py+++ b/tests/storage/test_viking_fs_cp.py@@ -649,8 +649,11 @@ async def test_mv_restores_vectors_before_removing_target_when_acl_refresh_failsagfs.events.append(("move-vectors", old_uri, new_uri))return SimpleNamespace(scanned=1, written=1, deleted=1, restored=0, batches=1)+ async def acl_enabled(account_id):+ return account_id == "acct"+fs.acl_manager = SimpleNamespace(- is_enabled=lambda account_id: account_id == "acct",+ is_enabled=acl_enabled,refresh_context_subtree=AsyncMock(side_effect=RuntimeError("ACL refresh failed")),)monkeypatch.setattr(fs, "_update_vector_store_uris", move_vectors)@@ -686,8 +689,11 @@ async def test_mv_still_cleans_target_when_vector_restore_after_acl_refresh_failvector_uris.add(new_uri)return SimpleNamespace(scanned=1, written=1, deleted=1, restored=0, batches=1)+ async def acl_enabled(account_id):+ return account_id == "acct"+fs.acl_manager = SimpleNamespace(- is_enabled=lambda account_id: account_id == "acct",+ is_enabled=acl_enabled,refresh_context_subtree=AsyncMock(side_effect=RuntimeError("ACL refresh failed")),)monkeypatch.setattr(fs, "_update_vector_store_uris", move_vectors)diff --git a/tests/storage/test_viking_fs_tree.py b/tests/storage/test_viking_fs_tree.pyindex 8adcc3831..b45b9bd42 100644--- a/tests/storage/test_viking_fs_tree.py+++ b/tests/storage/test_viking_fs_tree.py@@ -255,28 +255,60 @@ def test_is_tree_entry_visible_visible(monkeypatch, fs):"""PY-FLT-005, PY-FLT-009: Normal visible entry."""patch_visibility(monkeypatch, fs, is_accessible=True)entry = make_entry("/local/test_account/resources/a", "a")- assert fs._is_tree_entry_visible(entry, "/local/test_account", _default_ctx()) is True+ assert (+ fs._is_tree_entry_visible(+ entry,+ "/local/test_account",+ _default_ctx(),+ acl_enabled=False,+ )+ is True+ )def test_is_tree_entry_visible_acl_filtered(monkeypatch, fs):"""PY-FLT-008: ACL filtering."""patch_visibility(monkeypatch, fs, is_accessible=False)entry = make_entry("/local/test_account/resources/secret", "secret")- assert fs._is_tree_entry_visible(entry, "/local/test_account", _default_ctx()) is False+ assert (+ fs._is_tree_entry_visible(+ entry,+ "/local/test_account",+ _default_ctx(),+ acl_enabled=False,+ )+ is False+ )def test_is_tree_entry_visible_hidden_scope_filtered(monkeypatch, fs):"""PY-FLT-007: tasks scope filtered at account root."""patch_visibility(monkeypatch, fs, is_accessible=True)entry = make_entry("/local/test_account/tasks/foo", "foo")- assert fs._is_tree_entry_visible(entry, "/local/test_account", _default_ctx()) is False+ assert (+ fs._is_tree_entry_visible(+ entry,+ "/local/test_account",+ _default_ctx(),+ acl_enabled=False,+ )+ is False+ )def test_is_tree_entry_visible_path_ovlock_filtered(monkeypatch, fs):"""PY-FLT-011: .path.ovlock is filtered."""patch_visibility(monkeypatch, fs, is_accessible=True)entry = make_entry("/local/test_account/resources/.path.ovlock", ".path.ovlock", is_dir=False)- assert fs._is_tree_entry_visible(entry, "/local/test_account", _default_ctx()) is False+ assert (+ fs._is_tree_entry_visible(+ entry,+ "/local/test_account",+ _default_ctx(),+ acl_enabled=False,+ )+ is False+ )def test_is_tree_entry_visible_multiwrite_meta_filtered(monkeypatch, fs):@@ -288,14 +320,30 @@ def test_is_tree_entry_visible_multiwrite_meta_filtered(monkeypatch, fs):hidden_name,is_dir=False,)- assert fs._is_tree_entry_visible(entry, "/local/test_account", _default_ctx()) is False+ assert (+ fs._is_tree_entry_visible(+ entry,+ "/local/test_account",+ _default_ctx(),+ acl_enabled=False,+ )+ is False+ )def test_is_tree_entry_visible_default_ctx(monkeypatch, fs):"""PY-FLT-010: ctx=None uses default context."""patch_visibility(monkeypatch, fs, is_accessible=True)entry = make_entry("/local/test_account/resources/a", "a")- assert fs._is_tree_entry_visible(entry, "/local/test_account", _default_ctx()) is True+ assert (+ fs._is_tree_entry_visible(+ entry,+ "/local/test_account",+ _default_ctx(),+ acl_enabled=False,+ )+ is True+ )# ── _iter_visible_tree_entries tests ──@@ -542,7 +590,10 @@ async def test_tree_original_dfs_order(monkeypatch, fs):),]patch_tree_env(monkeypatch, fs, entries)- fs.acl_manager = SimpleNamespace(is_enabled=lambda _account_id: True)+ async def acl_enabled(_account_id):+ return True++ fs.acl_manager = SimpleNamespace(is_enabled=acl_enabled)async def fake_can_access_many(uris, _ctx):return {uri: "/restricted" not in uri for uri in uris}@@ -669,7 +720,10 @@ async def test_ls_agent_modtime_is_raw_utc_iso(monkeypatch, fs):monkeypatch.setattr(fs, "_is_accessible", lambda _uri, _ctx: True)monkeypatch.setattr(fs, "_batch_fetch_abstracts", default_batch_fetch)monkeypatch.setattr(viking_fs_module, "datetime", _FixedDatetime)- fs.acl_manager = SimpleNamespace(is_enabled=lambda _account_id: True)+ async def acl_enabled(_account_id):+ return True++ fs.acl_manager = SimpleNamespace(is_enabled=acl_enabled)async def fake_can_access_many(uris, _ctx):return {uri: not uri.endswith("/restricted") for uri in uris}diff --git a/tests/storage/test_viking_vector_scope_filter.py b/tests/storage/test_viking_vector_scope_filter.pyindex 666790d01..3ae99afca 100644--- a/tests/storage/test_viking_vector_scope_filter.py+++ b/tests/storage/test_viking_vector_scope_filter.py@@ -1,6 +1,9 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: Apache-2.0+from types import SimpleNamespace+from unittest.mock import AsyncMock+import pytestfrom openviking.server.identity import RequestContext, Role@@ -30,6 +33,7 @@ def _build(context_type: str | None = "resource",extra_filter=None,level: list[int] | None = None,+ acl_enabled: bool = False,):backend = object.__new__(VikingVectorIndexBackend)backend.acl_manager = None@@ -39,13 +43,23 @@ def _build(target_directories=targets,extra_filter=extra_filter,level=level,+ acl_enabled=acl_enabled,)-def _tenant_filter(ctx: RequestContext):+def _tenant_filter(ctx: RequestContext, *, acl_enabled: bool = False):backend = object.__new__(VikingVectorIndexBackend)backend.acl_manager = None- return backend._tenant_filter(ctx)+ return backend._tenant_filter(ctx, acl_enabled=acl_enabled)+++class _AclConfigReader:+ def __init__(self, enabled: bool):+ self.enabled = enabled++ async def get_account(self, account_id: str, field: str):+ del account_id, field+ return SimpleNamespace(enabled=self.enabled)class _FailingAsyncAdapter:@@ -62,6 +76,20 @@ class _RecordingAsyncAdapter:return []+async def test_search_by_random_passes_runtime_acl_state_to_tenant_filter():+ ctx = _ctx()+ adapter = SimpleNamespace(search_by_random=AsyncMock(return_value=[]))+ acl_reader = _AclConfigReader(False)+ backend = object.__new__(VikingVectorIndexBackend)+ backend.acl_manager = AclManager(backend, acl_reader)+ backend._get_backend_for_context = lambda _ctx: adapter++ assert await backend.search_by_random(ctx=ctx) == []+ adapter.search_by_random.assert_awaited_once()+ assert adapter.search_by_random.await_args.kwargs["filter"] == _tenant_filter(ctx)++def test_descendant_target_elides_only_visible_root_path_filter():ctx = _ctx()target = "viking://resources/wiki/physics"@@ -225,8 +253,8 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl(tmp_path, leg"DefaultValue")assert await backend.create_collection("context", schema)- backend.acl_manager = AclManager(backend)- backend.acl_manager.set_enabled(ctx.account_id, True)+ acl_config = _AclConfigReader(True)+ backend.acl_manager = AclManager(backend, acl_config)for record in records:record_ctx = RequestContext(user=UserIdentifier(record["account_id"], ctx.user.user_id), role=Role.ADMIN@@ -279,7 +307,7 @@ async def test_tenant_search_enforces_visible_roots_and_shared_acl(tmp_path, leg])- backend.acl_manager.set_enabled(ctx.account_id, False)+ acl_config.enabled = Falseshared = await backend.search_in_tenant(ctx=ctx,query_vector=[1.0, 0.0, 0.0, 0.0],diff --git a/tests/unit/test_accessors_git.py b/tests/unit/test_accessors_git.pyindex f07d9c645..8c28258f6 100644--- a/tests/unit/test_accessors_git.py+++ b/tests/unit/test_accessors_git.py@@ -17,6 +17,7 @@ from openviking.utils import code_hosting_utilsfrom openviking.utils.git_auth import (build_git_http_auth_env,git_http_basic_auth_header,+ is_git_https_url,parse_git_http_auth_config,)from openviking_cli.exceptions import InvalidArgumentError@@ -77,6 +78,20 @@ def test_git_http_auth_config_defaults_username_and_builds_isolated_env() -> Nonassert env["GIT_CONFIG_KEY_4"] == f"http.{repo_url}.extraHeader"+ ("repo_url", "expected"),+ [+ ("https://github.com/org/repo.git", True),+ (" HTTPS://github.com/org/repo.git ", True),+ ("http://github.com/org/repo.git", False),+ ("[email protected]:org/repo.git", False),+ ("ssh://[email protected]/org/repo.git", False),+ ],+)+def test_git_https_url_detection(repo_url: str, expected: bool) -> None:+ assert is_git_https_url(repo_url) is expected++@pytest.mark.parametrize(("value", "repo_url", "message"),[@@ -485,6 +500,87 @@ class TestGitAccessor:assert resource.original_source == sourceassert token not in str(resource.meta)+ async def test_github_token_is_preserved_for_archive_fallback_clone(+ self,+ accessor: GitAccessor,+ tmp_path: Path,+ ) -> None:+ source = "https://github.com/org/private.git"+ token = "account-token"+ with (+ patch(+ "openviking.parse.accessors.git_accessor.tempfile.mkdtemp",+ return_value=str(tmp_path),+ ),+ patch.object(+ accessor,+ "_github_zip_download",+ new_callable=AsyncMock,+ side_effect=RuntimeError("archive unavailable"),+ ) as zip_download,+ patch.object(+ accessor,+ "_git_clone",+ new_callable=AsyncMock,+ return_value="org/private",+ ) as git_clone,+ ):+ await accessor.access(source, github_token=token)++ zip_download.assert_awaited_once_with(+ source,+ None,+ str(tmp_path),+ github_token=token,+ )+ clone_env = git_clone.await_args.kwargs["env"]+ assert _git_config_entries(clone_env)[f"http.{source}.extraHeader"] == (+ "Authorization: Basic "+ + base64.b64encode(f"oauth2:{token}".encode()).decode("ascii")+ )++ async def test_environment_github_token_does_not_replace_ssh_clone_auth(+ self,+ accessor: GitAccessor,+ tmp_path: Path,+ ) -> None:+ source = "ssh://[email protected]/org/private.git"+ token = "environment-token"+ with (+ patch.dict(os.environ, {"GITHUB_TOKEN": token}),+ patch(+ "openviking.parse.accessors.git_accessor.tempfile.mkdtemp",+ return_value=str(tmp_path),+ ),+ patch.object(+ accessor,+ "_github_zip_download",+ new_callable=AsyncMock,+ side_effect=RuntimeError("archive unavailable"),+ ) as zip_download,+ patch.object(+ accessor,+ "_git_clone",+ new_callable=AsyncMock,+ return_value="org/private",+ ) as git_clone,+ ):+ await accessor.access(source)++ zip_download.assert_awaited_once_with(+ source,+ None,+ str(tmp_path),+ github_token=token,+ )+ git_clone.assert_awaited_once_with(+ source,+ str(tmp_path),+ branch=None,+ commit=None,+ env=None,+ )+async def test_embedded_http_credentials_are_passed_through_unchanged(self,accessor: GitAccessor,diff --git a/tests/utils/test_resource_processor_processing_mode.py b/tests/utils/test_resource_processor_processing_mode.pyindex 1779bcc53..dec253fe3 100644--- a/tests/utils/test_resource_processor_processing_mode.py+++ b/tests/utils/test_resource_processor_processing_mode.py@@ -60,6 +60,55 @@ def ctx() -> RequestContext:)+async def test_github_token_prefers_account_config_over_environment(monkeypatch, ctx):+ monkeypatch.setenv("GITHUB_TOKEN", "environment-token")+ monkeypatch.setattr(+ "openviking.utils.resource_processor.is_github_url",+ lambda _source: True,+ )+ manager = SimpleNamespace(+ get_account=AsyncMock(return_value=SimpleNamespace(token="account-token"))+ )+ processor = ResourceProcessor(+ _FakeVikingDB(),+ runtime_config_manager=manager,+ )++ token = await processor.github_token_for("https://github.com/org/private", ctx)++ assert token == "account-token"+ manager.get_account.assert_awaited_once_with("account-1", "github")+++ "source",+ [+ "[email protected]:org/private.git",+ "ssh://[email protected]/org/private.git",+ ],+)+async def test_github_token_is_not_injected_into_ssh_sources(monkeypatch, ctx, source):+ monkeypatch.setenv("GITHUB_TOKEN", "environment-token")+ monkeypatch.setattr(+ "openviking.utils.resource_processor.is_github_url",+ lambda _source: True,+ )+ manager = SimpleNamespace(+ get_account=AsyncMock(return_value=SimpleNamespace(token="account-token"))+ )+ processor = ResourceProcessor(+ _FakeVikingDB(),+ runtime_config_manager=manager,+ )+ kwargs = {"branch": "main"}++ assert await processor.github_token_for(source, ctx) is None+ assert await processor._source_config_kwargs(source, ctx, kwargs) is kwargs+ manager.get_account.assert_not_awaited()++@pytest.mark.asyncioasync def test_flat_file_refreshes_parent_semantics_and_vectorizes_via_summary(monkeypatch,