JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat:删除旧的三层匹配策略
wangxine9b20f84b816
diff --git a/jiuwenswarm/gateway/config/enterprise/__init__.py b/jiuwenswarm/gateway/config/enterprise/__init__.pyindex e5e5de583f..a0d684b261 100644--- a/jiuwenswarm/gateway/config/enterprise/__init__.py+++ b/jiuwenswarm/gateway/config/enterprise/__init__.py@@ -1,5 +1,5 @@# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-"""企业专属表(config_effective_* / *_template / 密钥等)→ PersistentStore。+"""企业专属表(instance_agent_resource / *_template / 密钥等)→ PersistentStore。仅 DB;企业版启动时由 storage_assembly 注入 ``EnterpriseRecordRepository``。"""diff --git a/jiuwenswarm/gateway/config/enterprise/catalog.py b/jiuwenswarm/gateway/config/enterprise/catalog.pyindex 02bf3fa741..a11f9a55bf 100644--- a/jiuwenswarm/gateway/config/enterprise/catalog.py+++ b/jiuwenswarm/gateway/config/enterprise/catalog.py@@ -24,10 +24,6 @@ class EnterpriseRecordSpec:# store name == DB 表名;与 layouts / EE TableDefinition 对齐。# ``cron_job`` 另有 personal JSON 布局(见 ``layouts._legacy_gateway_cron_job_layout``)。ENTERPRISE_RECORD_SPECS: dict[str, EnterpriseRecordSpec] = {- "config_effective_global_policy": EnterpriseRecordSpec(key_fields=("policy_id",)),- "config_effective_service_policy": EnterpriseRecordSpec(key_fields=("policy_id",)),- "config_effective_agent_policy": EnterpriseRecordSpec(key_fields=("policy_id",)),- "config_default_template_mapping": EnterpriseRecordSpec(key_fields=("policy_id",)),"model_template": EnterpriseRecordSpec(key_fields=("template_id",)),"embedding_template": EnterpriseRecordSpec(key_fields=("template_id",)),"extension_config_template": EnterpriseRecordSpec(key_fields=("template_id",)),diff --git a/jiuwenswarm/server/runtime/enterprise_config/loader.py b/jiuwenswarm/server/runtime/enterprise_config/loader.pyindex 940d697fcf..6dad3eb807 100644--- a/jiuwenswarm/server/runtime/enterprise_config/loader.py+++ b/jiuwenswarm/server/runtime/enterprise_config/loader.py@@ -1,17 +1,15 @@-"""从 Gateway DB 加载企业级生效配置(Service → Agent → Global 三级匹配)。"""+"""从 Gateway DB 按实例 Agent 资源加载企业级生效配置。"""from __future__ import annotations-from jiuwenswarm.common.local_env_config import is_enterprise-import osfrom collections.abc import Collection-from dataclasses import dataclassfrom typing import Any+from jiuwenswarm.common.local_env_config import is_enterprisefrom jiuwenswarm.common.schema.agent import AgentRequestfrom jiuwenswarm.common.utils import logger-from . import expressions, gateway_db+from . import gateway_dbfrom .schemas import (DEFAULT_AGENT_LOAD_SLOTS,MODEL_SLOT_KEYS,@@ -22,94 +20,6 @@ from .schemas import ()-def merge_template_ref(*layers: dict[str, list[str]]) -> dict[str, list[str]]:- """按参数顺序从左到右合并 ``template_ref``;后出现的槽位整组覆盖先前的同名槽位。"""- merged: dict[str, list[str]] = {}- for layer in layers:- merged.update(layer)- return merged---def fill_missing_template_ref_slots(- merged: dict[str, list[str]],- fallback: dict[str, list[str]],-) -> dict[str, list[str]]:- """将 ``fallback`` 中尚未出现在 ``merged`` 的槽位补入(用于全局兜底按槽位回填)。"""- if not fallback:- return merged- out = dict(merged)- for slot, refs in fallback.items():- if slot not in out:- out[slot] = refs- return out---async def _fetch_global_policy_refs() -> tuple[dict[str, Any] | None, dict[str, list[str]]]:- filters: dict[str, Any] = {"enabled": True}- global_rows = await gateway_db.list_records(- "config_effective_global_policy",- filters=filters,- order_by="priority DESC",- )- if not global_rows:- return None, {}- matched_global = global_rows[0]- return matched_global, normalize_template_ref(matched_global.get("template_ref"))---@dataclass-class _PolicyMatchResult:- merged_refs: dict[str, list[str]]- matched_service: dict[str, Any] | None- matched_agent: dict[str, Any] | None- matched_global: dict[str, Any] | None---async def _resolve_policy_match(ctx: RoutingContext) -> _PolicyMatchResult:- service_rules = await gateway_db.list_records(- "config_effective_service_policy",- filters={"enabled": True},- order_by="priority DESC",- )-- matched_service: dict[str, Any] | None = None- matched_agent: dict[str, Any] | None = None- matched_global, global_refs = await _fetch_global_policy_refs()- merged_refs: dict[str, list[str]] = {}-- for rule in service_rules:- if expressions.evaluate_match_expr(rule.get("match_expr"), ctx):- matched_service = rule- merged_refs = normalize_template_ref(rule.get("template_ref"))- break-- if matched_service is not None:- sp_id = int(matched_service["id"])- agent_rules = await gateway_db.list_records(- "config_effective_agent_policy",- filters={"enabled": True, "service_policy_id": sp_id},- order_by="priority DESC",- )- for rule in agent_rules:- if expressions.agent_rule_matches(rule, ctx):- matched_agent = rule- merged_refs = merge_template_ref(- merged_refs,- normalize_template_ref(rule.get("template_ref")),- )- break- merged_refs = fill_missing_template_ref_slots(merged_refs, global_refs)- else:- merged_refs = global_refs-- return _PolicyMatchResult(- merged_refs=merged_refs,- matched_service=matched_service,- matched_agent=matched_agent,- matched_global=matched_global,- )--def routing_context_from_request(request: AgentRequest | Any) -> RoutingContext:"""从 ``request.params`` 解析路由上下文(调用方保证字段格式正确)。"""p = getattr(request, "params", None) or {}@@ -192,71 +102,149 @@ async def _fetch_slot_entities(return entities+async def _fetch_instance_agent_resource(resource_id: str) -> dict[str, Any] | None:+ rid = str(resource_id or "").strip()+ if not rid:+ return None+ rows = await gateway_db.list_records(+ "instance_agent_resource",+ filters={"resource_id": rid},+ )+ return rows[0] if rows else None+++async def _fetch_agent_template_row(template_id: str) -> dict[str, Any] | None:+ tid = str(template_id or "").strip()+ if not tid:+ return None+ rows = await gateway_db.list_records(+ "agent_template",+ filters={"enabled": True, "template_id": tid},+ )+ return rows[0] if rows else None+++def _literal_slot_template_id_map(+ refs: dict[str, list[str]],+) -> dict[str, list[str]]:+ """仅接受字面 ``template_id``;跳过 ``${...}`` / ``or`` 等映射表达式。"""+ slot_template_id_map: dict[str, list[str]] = {}+ for slot, raw_list in refs.items():+ resolved: list[str] = []+ seen: set[str] = set()+ for raw in raw_list:+ text = str(raw or "").strip()+ if not text or text.startswith("${") or " or " in text.lower():+ continue+ if text not in seen:+ seen.add(text)+ resolved.append(text)+ if resolved:+ slot_template_id_map[slot] = resolved+ return slot_template_id_map++async def load_effective_enterprise_config(request: AgentRequest | Any,slots: Collection[TemplateRefSlot],) -> EffectiveEnterpriseConfig | None:- """按 Service → Agent → Global 三级匹配加载企业配置。+ """按 ``request.bot_id``(即 ``instance_agent_resource.resource_id``)加载 Agent 实例生效配置。- ``slots`` 指定要解析并加载的 ``template_ref`` 槽位。+ 读取实例 Agent 资源 → ``agent_template`` → 仅按字面 ``template_id`` 解析+ ``template_ref`` 并加载模型等模板实体。"""- # 企业版特性:仅企业版开启时生效if not is_enterprise():return Nonectx = routing_context_from_request(request)if not slots:raise ValueError("slots must not be empty")++ rid = str(ctx.bot_id or "").strip()+ if not rid:+ logger.warning(+ "[enterprise_config] bot_id(resource_id) missing in request context %s",+ ctx.as_dict(),+ )+ return None+load_slots = frozenset(slot.value for slot in slots)- match = await _resolve_policy_match(ctx)++ resource_row = await _fetch_instance_agent_resource(rid)+ if resource_row is None:+ logger.warning(+ "[enterprise_config] instance_agent_resource not found: resource_id=%r",+ rid,+ )+ return None++ ref_template_id = str(resource_row.get("ref_template_id") or "").strip()+ if not ref_template_id:+ logger.warning(+ "[enterprise_config] instance_agent_resource missing ref_template_id: resource_id=%r",+ rid,+ )+ return None++ agent_template_row = await _fetch_agent_template_row(ref_template_id)+ if agent_template_row is None:+ logger.warning(+ "[enterprise_config] agent_template not found or disabled: "+ "resource_id=%r ref_template_id=%r",+ rid,+ ref_template_id,+ )+ return None++ merged_refs = normalize_template_ref(agent_template_row.get("template_ref"))filtered_refs = {slot: refs- for slot, refs in match.merged_refs.items()+ for slot, refs in merged_refs.items()if slot in load_slots}if not filtered_refs:logger.warning(- "[enterprise_config] no template_ref resolved for context %s slots=%s",- ctx.as_dict(),+ "[enterprise_config] agent_template has no template_ref for resource_id=%r slots=%s",+ rid,sorted(load_slots),)return None- slot_template_id_map = await expressions.resolve_slot_template_id_map(- filtered_refs,- ctx,- )+ slot_template_id_map = _literal_slot_template_id_map(filtered_refs)if not slot_template_id_map:logger.warning(- "[enterprise_config] template_ref slots unresolved for context %s refs=%s",- ctx.as_dict(),+ "[enterprise_config] agent template_ref has no literal template_id "+ "for resource_id=%r refs=%s",+ rid,filtered_refs,)return None+ template_data = agent_template_row.get("data")+ workspace_dir = None+ if isinstance(template_data, dict):+ raw_ws = template_data.get("workspace_dir")+ if isinstance(raw_ws, str) and raw_ws.strip():+ workspace_dir = raw_ws.strip()+result = EffectiveEnterpriseConfig(routing=ctx,template_ref=slot_template_id_map,- service_policy_id=(- int(match.matched_service["id"]) if match.matched_service else None- ),- agent_policy_id=(- int(match.matched_agent["id"]) if match.matched_agent else None- ),- global_policy_id=(- int(match.matched_global["id"]) if match.matched_global else None- ),- service_policy=match.matched_service,- agent_policy=match.matched_agent,- global_policy=match.matched_global,+ agent_id=rid,+ workspace_dir=workspace_dir,+ resource_id=rid,+ ref_template_id=ref_template_id,+ agent_template=agent_template_row,+ instance_agent_resource=resource_row,debug={- "raw_template_ref": match.merged_refs,"jiuwenclaw_id": gateway_db.resolve_jiuwenclaw_id(),"group_id": ctx.group_id,"bot_id": ctx.bot_id,"user_id": ctx.user_id,"load_slots": sorted(load_slots),+ "resource_id": rid,+ "ref_template_id": ref_template_id,},)@@ -267,8 +255,9 @@ async def load_effective_enterprise_config(if not _any_requested_slot_loaded(result, load_slots):logger.warning(- "[enterprise_config] no template entities loaded "+ "[enterprise_config] no template entities loaded for resource_id=%r ""template_ref=%s ctx=%s slots=%s",+ rid,slot_template_id_map,ctx.as_dict(),sorted(load_slots),@@ -276,7 +265,8 @@ async def load_effective_enterprise_config(return Nonelogger.info(- "[enterprise_config] loaded enterprise config: slots=%s payload=%s",+ "[enterprise_config] loaded enterprise config by resource_id=%r slots=%s payload=%s",+ rid,sorted(load_slots),result.as_dict(),)@@ -287,8 +277,6 @@ __all__ = ("DEFAULT_AGENT_LOAD_SLOTS","EffectiveEnterpriseConfig","TemplateRefSlot",- "fill_missing_template_ref_slots","load_effective_enterprise_config",- "merge_template_ref","routing_context_from_request",)diff --git a/jiuwenswarm/server/runtime/enterprise_config/schemas.py b/jiuwenswarm/server/runtime/enterprise_config/schemas.pyindex 586fbfeca2..3d43517363 100644--- a/jiuwenswarm/server/runtime/enterprise_config/schemas.py+++ b/jiuwenswarm/server/runtime/enterprise_config/schemas.py@@ -11,7 +11,7 @@ SERVICE_CONFIG_TABLE = "service_config_template"class TemplateRefSlot(StrEnum):- """``template_ref`` JSON 键名,与 ``config_default_template_mapping.template_type`` 一致。"""+ """``template_ref`` JSON 键名(与 agent_template.template_ref 槽位一致)。"""DEFAULT_MODEL = "default_model"VIDEO_MODEL = "video_model"@@ -97,12 +97,14 @@ class EffectiveEnterpriseConfig:skill_whitelist: list[dict[str, Any]] | None = Noneextension_config: list[dict[str, Any]] | None = Noneservice_config: list[dict[str, Any]] | None = None- service_policy_id: int | None = None- agent_policy_id: int | None = None- global_policy_id: int | None = None- service_policy: dict[str, Any] | None = None- agent_policy: dict[str, Any] | None = None- global_policy: dict[str, Any] | None = None+ service_id: str | None = None+ agent_id: str | None = None+ workspace_dir: str | None = None+ send_file_allowed: bool = True+ resource_id: str | None = None+ ref_template_id: str | None = None+ agent_template: dict[str, Any] | None = None+ instance_agent_resource: dict[str, Any] | None = Nonedebug: dict[str, Any] = field(default_factory=dict)def as_dict(self) -> dict[str, Any]:@@ -114,9 +116,14 @@ class EffectiveEnterpriseConfig:"skill_whitelist": self.skill_whitelist,"extension_config": self.extension_config,"service_config": self.service_config,- "service_policy_id": self.service_policy_id,- "agent_policy_id": self.agent_policy_id,- "global_policy_id": self.global_policy_id,+ "service_id": self.service_id,+ "agent_id": self.agent_id,+ "workspace_dir": self.workspace_dir,+ "send_file_allowed": self.send_file_allowed,+ "resource_id": self.resource_id,+ "ref_template_id": self.ref_template_id,+ "agent_template": self.agent_template,+ "instance_agent_resource": self.instance_agent_resource,"debug": dict(self.debug),}diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/__init__.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/__init__.pydeleted file mode 100644index a518e49f44..0000000000--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/__init__.py+++ /dev/null@@ -1,11 +0,0 @@-from .config_default_template_mapping import ConfigDefaultTemplateMappingService-from .config_effective_agent_policy import ConfigEffectiveAgentPolicyService-from .config_effective_global_policy import ConfigEffectiveGlobalPolicyService-from .config_effective_service_policy import ConfigEffectiveServicePolicyService--__all__ = (- "ConfigDefaultTemplateMappingService",- "ConfigEffectiveAgentPolicyService",- "ConfigEffectiveGlobalPolicyService",- "ConfigEffectiveServicePolicyService",-)diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_default_template_mapping.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_default_template_mapping.pydeleted file mode 100644index e24ac969fd..0000000000--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_default_template_mapping.py+++ /dev/null@@ -1,183 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved--"""默认模板映射:将 Claw Manager 下发的 config_default_template_mappings 写入 Gateway 本地库。"""--from __future__ import annotations--import logging-from typing import Any--from jiuwenswarm.gateway.config.enterprise.repository import EnterpriseRecordRepository--from ...infrastructure.repository_access import require_enterprise_repository-from ...infrastructure.utils import parse_iso_datetime, utc_now-from ...models.config_effective_policy_models import (- CONFIG_DEFAULT_TEMPLATE_MAPPING_TABLE_DEF,-)-from ...schemas.config_effective_policy_schemas import (- ConfigDefaultTemplateMappingCreateRequest,- ConfigDefaultTemplateMappingUpdateRequest,-)-from .config_record_ops import (- apply_create_from_row_builder,- apply_delete_by_id,- apply_update_by_id,- get_row_for_instance,-)-from ..enterprise_config.schemas import MAPPING_SCOPE_TYPES--_TABLE = CONFIG_DEFAULT_TEMPLATE_MAPPING_TABLE_DEF.table_name-_SECTION = "config_default_template_mappings"-logger = logging.getLogger(__name__)--_ALLOWED_TEMPLATE_TYPES = frozenset({- "default_model",- "video_model",- "audio_model",- "vision_model",- "embedding_model",- "skill_whitelist",- "extension_config",- "service_config",-})---def _validate_template_type(template_type: str) -> str:- normalized = template_type.strip()- if normalized not in _ALLOWED_TEMPLATE_TYPES:- raise ValueError(- f"template_type must be one of {sorted(_ALLOWED_TEMPLATE_TYPES)}, got {template_type!r}"- )- return normalized---def _validate_scope(scope_type: str, scope_id: str) -> tuple[str, str]:- st = str(scope_type or "").strip().lower()- if st not in MAPPING_SCOPE_TYPES:- raise ValueError(- f"scope_type must be one of {sorted(MAPPING_SCOPE_TYPES)}, got {scope_type!r}"- )- sid = str(scope_id or "").strip()- if not sid:- raise ValueError("scope_id is required")- return st, sid---async def update_config_default_template_mapping_record(- repo: EnterpriseRecordRepository,- mapping_id: int,- updates: dict[str, Any],- jiuwenclaw_id: str,-) -> dict[str, Any] | None:- request = ConfigDefaultTemplateMappingUpdateRequest.model_validate(updates)- existing = await get_row_for_instance(repo, mapping_id)- if existing is None:- return None-- field_updates = request.model_dump(exclude_unset=True)- if "template_type" in field_updates and field_updates["template_type"] is not None:- field_updates["template_type"] = _validate_template_type(field_updates["template_type"])- if "template_id" in field_updates and field_updates["template_id"] is not None:- field_updates["template_id"] = field_updates["template_id"].strip()- if not field_updates["template_id"]:- raise ValueError("template_id cannot be empty")- if "scope_type" in field_updates and field_updates["scope_type"] is not None:- field_updates["scope_type"] = str(field_updates["scope_type"]).strip().lower()- if "scope_id" in field_updates and field_updates["scope_id"] is not None:- field_updates["scope_id"] = str(field_updates["scope_id"]).strip()-- merged_type = field_updates.get("scope_type", existing.get("scope_type"))- merged_id = field_updates.get("scope_id", existing.get("scope_id"))- _validate_scope(str(merged_type), str(merged_id))-- if not field_updates:- raise ValueError("请求未包含任何可更新的业务字段")-- field_updates["updated_at"] = utc_now()- updated = await repo.update_by_row_id(mapping_id, field_updates)- if updated is None:- return None- return {"id": updated.get("id")}---def _build_row_from_sync_mapping(- mapping: dict[str, Any],- jiuwenclaw_id: str,- now: Any,-) -> dict[str, Any]:- req = ConfigDefaultTemplateMappingCreateRequest.model_validate(mapping)- scope_type, scope_id = _validate_scope(req.scope_type, req.scope_id)- template_type = _validate_template_type(req.template_type)- return {- "jiuwenclaw_id": jiuwenclaw_id,- "policy_id": req.policy_id,- "policy_name": req.policy_name,- "policy_desc": req.policy_desc,- "scope_type": scope_type,- "scope_id": scope_id,- "priority": req.priority,- "template_id": req.template_id,- "template_type": template_type,- "enabled": req.enabled,- "data": req.data,- "created_at": parse_iso_datetime(mapping.get("created_at")) or now,- "updated_at": parse_iso_datetime(mapping.get("updated_at")) or now,- }---class ConfigDefaultTemplateMappingService:-- async def create(- self,- jiuwenclaw_id: str,- mapping: dict[str, Any],- ) -> dict[str, Any]:- repo = require_enterprise_repository(_TABLE)- result = await apply_create_from_row_builder(- repo,- section=_SECTION,- jiuwenclaw_id=jiuwenclaw_id,- record=mapping,- build_row=_build_row_from_sync_mapping,- record_label="mapping",- entity="mapping",- )- logger.info(- "[ManagerConfigReceiver] config_default_template_mappings create id=%s",- result.get("id"),- )- return result-- async def update(- self,- jiuwenclaw_id: str,- row_id: Any,- updates: dict[str, Any],- ) -> None:- repo = require_enterprise_repository(_TABLE)- await apply_update_by_id(- repo,- section=_SECTION,- jiuwenclaw_id=jiuwenclaw_id,- row_id=row_id,- updates=updates,- update_record=update_config_default_template_mapping_record,- not_found_message=f"config default template mapping id={row_id} not found",- )- logger.info(- "[ManagerConfigReceiver] config_default_template_mappings update id=%s",- row_id,- )-- async def delete(self, jiuwenclaw_id: str, row_id: Any) -> None:- _ = jiuwenclaw_id- repo = require_enterprise_repository(_TABLE)- await apply_delete_by_id(- repo,- section=_SECTION,- row_id=row_id,- )- logger.info(- "[ManagerConfigReceiver] config_default_template_mappings delete id=%s",- row_id,- )diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_effective_agent_policy.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_effective_agent_policy.pydeleted file mode 100644index f22d0ff032..0000000000--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_effective_agent_policy.py+++ /dev/null@@ -1,202 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved--"""Agent 层级配置生效策略:将 Claw Manager 下发的 config_effective_agent_policies 写入 Gateway 本地库。"""--from __future__ import annotations--import logging-from typing import Any--from jiuwenswarm.gateway.config.enterprise.repository import EnterpriseRecordRepository--from ...infrastructure.repository_access import require_enterprise_repository-from ...infrastructure.utils import (- apply_template_ref_to_updates,- normalize_template_ref,- parse_iso_datetime,- utc_now,-)-from ...models.config_effective_policy_models import (- CONFIG_EFFECTIVE_AGENT_POLICY_TABLE_DEF,- CONFIG_EFFECTIVE_SERVICE_POLICY_TABLE_DEF,-)-from ...schemas.config_effective_policy_schemas import (- ConfigEffectiveAgentPolicyCreateRequest,- ConfigEffectiveAgentPolicyUpdateRequest,-)-from ..enterprise_config.expressions import validate_match_expr-from .config_record_ops import (- apply_create_from_row_builder,- apply_delete_by_id,- apply_update_by_id,- get_row_for_instance,-)--_AGENT_TABLE = CONFIG_EFFECTIVE_AGENT_POLICY_TABLE_DEF.table_name-_SERVICE_TABLE = CONFIG_EFFECTIVE_SERVICE_POLICY_TABLE_DEF.table_name-_SECTION = "config_effective_agent_policies"-logger = logging.getLogger(__name__)---async def _validate_service_policy_ref(- service_repo: EnterpriseRecordRepository,- *,- service_policy_id: str,-) -> None:- normalized_id = str(service_policy_id).strip()- if not normalized_id:- raise ValueError("service_policy_id is required")- rows = await service_repo.list(- filters={"policy_id": normalized_id},- limit=1,- )- if not rows:- raise ValueError(f"unknown service_policy_id={normalized_id!r}")---async def _before_agent_policy_create(- repo: EnterpriseRecordRepository,- jiuwenclaw_id: str,- policy: dict[str, Any],-) -> None:- req = ConfigEffectiveAgentPolicyCreateRequest.model_validate(policy)- service_repo = require_enterprise_repository(_SERVICE_TABLE)- await _validate_service_policy_ref(- service_repo,- service_policy_id=req.service_policy_id,- )---async def update_config_effective_agent_policy_record(- repo: EnterpriseRecordRepository,- policy_id: int,- updates: dict[str, Any],- jiuwenclaw_id: str,-) -> dict[str, Any] | None:- request = ConfigEffectiveAgentPolicyUpdateRequest.model_validate(updates)- existing = await get_row_for_instance(repo, policy_id)- if existing is None:- return None-- field_updates = request.model_dump(exclude_unset=True)- if "agent_id" in field_updates and field_updates["agent_id"] is not None:- field_updates["agent_id"] = field_updates["agent_id"].strip()- if not field_updates["agent_id"]:- raise ValueError("agent_id cannot be empty")-- if "workspace_dir" in field_updates:- raw_ws = field_updates["workspace_dir"]- field_updates["workspace_dir"] = (- raw_ws.strip() if isinstance(raw_ws, str) and raw_ws.strip() else None- )-- if "service_policy_id" in field_updates and field_updates["service_policy_id"] is not None:- field_updates["service_policy_id"] = str(field_updates["service_policy_id"]).strip()- if not field_updates["service_policy_id"]:- raise ValueError("service_policy_id cannot be empty")-- if "match_expr" in field_updates:- validate_match_expr(field_updates["match_expr"])-- next_service_policy_id = field_updates.get(- "service_policy_id", existing.get("service_policy_id")- )- if "service_policy_id" in field_updates:- service_repo = require_enterprise_repository(_SERVICE_TABLE)- await _validate_service_policy_ref(- service_repo,- service_policy_id=str(next_service_policy_id),- )-- if not field_updates:- raise ValueError("请求未包含任何可更新的业务字段")-- field_updates = apply_template_ref_to_updates(field_updates, existing_row=existing)- field_updates["updated_at"] = utc_now()- updated = await repo.update_by_row_id(policy_id, field_updates)- if updated is None:- return None- return {"id": updated.get("id")}---def _build_row_from_sync_policy(- policy: dict[str, Any],- jiuwenclaw_id: str,- now: Any,-) -> dict[str, Any]:- req = ConfigEffectiveAgentPolicyCreateRequest.model_validate(policy)- validate_match_expr(req.match_expr)- return {- "jiuwenclaw_id": jiuwenclaw_id,- "policy_id": req.policy_id,- "policy_name": req.policy_name,- "policy_desc": req.policy_desc,- "agent_id": req.agent_id,- "workspace_dir": req.workspace_dir,- "service_policy_id": req.service_policy_id,- "priority": req.priority,- "match_expr": req.match_expr,- "template_ref": normalize_template_ref(req.template_ref),- "send_file_allowed": req.send_file_allowed,- "enabled": req.enabled,- "data": req.data,- "created_at": parse_iso_datetime(policy.get("created_at")) or now,- "updated_at": parse_iso_datetime(policy.get("updated_at")) or now,- }---class ConfigEffectiveAgentPolicyService:-- async def create(- self,- jiuwenclaw_id: str,- policy: dict[str, Any],- ) -> dict[str, Any]:- repo = require_enterprise_repository(_AGENT_TABLE)- result = await apply_create_from_row_builder(- repo,- section=_SECTION,- jiuwenclaw_id=jiuwenclaw_id,- record=policy,- build_row=_build_row_from_sync_policy,- before_create=_before_agent_policy_create,- )- logger.info(- "[ManagerConfigReceiver] config_effective_agent_policies create id=%s",- result.get("id"),- )- return result-- async def update(- self,- jiuwenclaw_id: str,- row_id: Any,- updates: dict[str, Any],- ) -> None:- repo = require_enterprise_repository(_AGENT_TABLE)- await apply_update_by_id(- repo,- section=_SECTION,- jiuwenclaw_id=jiuwenclaw_id,- row_id=row_id,- updates=updates,- update_record=update_config_effective_agent_policy_record,- not_found_message=f"config effective agent policy id={row_id} not found",- )- logger.info(- "[ManagerConfigReceiver] config_effective_agent_policies update id=%s",- row_id,- )-- async def delete(self, jiuwenclaw_id: str, row_id: Any) -> None:- _ = jiuwenclaw_id- repo = require_enterprise_repository(_AGENT_TABLE)- await apply_delete_by_id(- repo,- section=_SECTION,- row_id=row_id,- )- logger.info(- "[ManagerConfigReceiver] config_effective_agent_policies delete id=%s",- row_id,- )diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_effective_global_policy.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_effective_global_policy.pydeleted file mode 100644index 953dd4375e..0000000000--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_effective_global_policy.py+++ /dev/null@@ -1,135 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved--"""全局兜底配置生效策略:将 Claw Manager 下发的 config_effective_global_policies 写入 Gateway 本地库。"""--from __future__ import annotations--import logging-from typing import Any--from jiuwenswarm.gateway.config.enterprise.repository import EnterpriseRecordRepository--from ...infrastructure.repository_access import require_enterprise_repository-from ...infrastructure.utils import (- apply_template_ref_to_updates,- normalize_template_ref,- parse_iso_datetime,- utc_now,-)-from ...models.config_effective_policy_models import (- CONFIG_EFFECTIVE_GLOBAL_POLICY_TABLE_DEF,-)-from ...schemas.config_effective_policy_schemas import (- ConfigEffectiveGlobalPolicyCreateRequest,- ConfigEffectiveGlobalPolicyUpdateRequest,-)-from .config_record_ops import (- apply_create_from_row_builder,- apply_delete_by_id,- apply_update_by_id,- get_row_for_instance,-)--_TABLE = CONFIG_EFFECTIVE_GLOBAL_POLICY_TABLE_DEF.table_name-_SECTION = "config_effective_global_policies"-logger = logging.getLogger(__name__)---async def update_config_effective_global_policy_record(- repo: EnterpriseRecordRepository,- policy_id: int,- updates: dict[str, Any],- jiuwenclaw_id: str,-) -> dict[str, Any] | None:- request = ConfigEffectiveGlobalPolicyUpdateRequest.model_validate(updates)- existing = await get_row_for_instance(repo, policy_id)- if existing is None:- return None-- field_updates = request.model_dump(exclude_unset=True)-- if not field_updates:- raise ValueError("请求未包含任何可更新的业务字段")-- field_updates = apply_template_ref_to_updates(field_updates, existing_row=existing)- field_updates["updated_at"] = utc_now()- updated = await repo.update_by_row_id(policy_id, field_updates)- if updated is None:- return None- return {"id": updated.get("id")}---def _build_row_from_sync_policy(- policy: dict[str, Any],- jiuwenclaw_id: str,- now: Any,-) -> dict[str, Any]:- req = ConfigEffectiveGlobalPolicyCreateRequest.model_validate(policy)- return {- "jiuwenclaw_id": jiuwenclaw_id,- "policy_id": req.policy_id,- "policy_name": req.policy_name,- "policy_desc": req.policy_desc,- "priority": req.priority,- "template_ref": normalize_template_ref(req.template_ref),- "enabled": req.enabled,- "data": req.data,- "created_at": parse_iso_datetime(policy.get("created_at")) or now,- "updated_at": parse_iso_datetime(policy.get("updated_at")) or now,- }---class ConfigEffectiveGlobalPolicyService:-- async def create(- self,- jiuwenclaw_id: str,- policy: dict[str, Any],- ) -> dict[str, Any]:- repo = require_enterprise_repository(_TABLE)- result = await apply_create_from_row_builder(- repo,- section=_SECTION,- jiuwenclaw_id=jiuwenclaw_id,- record=policy,- build_row=_build_row_from_sync_policy,- )- logger.info(- "[ManagerConfigReceiver] config_effective_global_policies create id=%s",- result.get("id"),- )- return result-- async def update(- self,- jiuwenclaw_id: str,- row_id: Any,- updates: dict[str, Any],- ) -> None:- repo = require_enterprise_repository(_TABLE)- await apply_update_by_id(- repo,- section=_SECTION,- jiuwenclaw_id=jiuwenclaw_id,- row_id=row_id,- updates=updates,- update_record=update_config_effective_global_policy_record,- not_found_message=f"config effective global policy id={row_id} not found",- )- logger.info(- "[ManagerConfigReceiver] config_effective_global_policies update id=%s",- row_id,- )-- async def delete(self, jiuwenclaw_id: str, row_id: Any) -> None:- _ = jiuwenclaw_id- repo = require_enterprise_repository(_TABLE)- await apply_delete_by_id(- repo,- section=_SECTION,- row_id=row_id,- )- logger.info(- "[ManagerConfigReceiver] config_effective_global_policies delete id=%s",- row_id,- )diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_effective_service_policy.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_effective_service_policy.pydeleted file mode 100644index a1f9c70240..0000000000--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_effective_service_policy.py+++ /dev/null@@ -1,145 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved--"""Service 层级配置生效策略:将 Claw Manager 下发的 config_effective_service_policies 写入 Gateway 本地库。"""--from __future__ import annotations--import logging-from typing import Any--from jiuwenswarm.gateway.config.enterprise.repository import EnterpriseRecordRepository--from ...infrastructure.repository_access import require_enterprise_repository-from ...infrastructure.utils import (- apply_template_ref_to_updates,- normalize_template_ref,- parse_iso_datetime,- utc_now,-)-from ...models.config_effective_policy_models import (- CONFIG_EFFECTIVE_SERVICE_POLICY_TABLE_DEF,-)-from ...schemas.config_effective_policy_schemas import (- ConfigEffectiveServicePolicyCreateRequest,- ConfigEffectiveServicePolicyUpdateRequest,-)-from ..enterprise_config.expressions import validate_match_expr-from .config_record_ops import (- apply_create_from_row_builder,- apply_delete_by_id,- apply_update_by_id,- get_row_for_instance,-)--_TABLE = CONFIG_EFFECTIVE_SERVICE_POLICY_TABLE_DEF.table_name-_SECTION = "config_effective_service_policies"-logger = logging.getLogger(__name__)---async def update_config_effective_service_policy_record(- repo: EnterpriseRecordRepository,- policy_id: int,- updates: dict[str, Any],- jiuwenclaw_id: str,-) -> dict[str, Any] | None:- request = ConfigEffectiveServicePolicyUpdateRequest.model_validate(updates)- existing = await get_row_for_instance(repo, policy_id)- if existing is None:- return None-- field_updates = request.model_dump(exclude_unset=True)- if "service_id" in field_updates and field_updates["service_id"] is not None:- field_updates["service_id"] = field_updates["service_id"].strip()- if not field_updates["service_id"]:- raise ValueError("service_id cannot be empty")- if "match_expr" in field_updates:- validate_match_expr(field_updates["match_expr"])-- if not field_updates:- raise ValueError("请求未包含任何可更新的业务字段")-- field_updates = apply_template_ref_to_updates(field_updates, existing_row=existing)- field_updates["updated_at"] = utc_now()- updated = await repo.update_by_row_id(policy_id, field_updates)- if updated is None:- return None- return {"id": updated.get("id")}---def _build_row_from_sync_policy(- policy: dict[str, Any],- jiuwenclaw_id: str,- now: Any,-) -> dict[str, Any]:- req = ConfigEffectiveServicePolicyCreateRequest.model_validate(policy)- validate_match_expr(req.match_expr)- return {- "jiuwenclaw_id": jiuwenclaw_id,- "policy_id": req.policy_id,- "policy_name": req.policy_name,- "policy_desc": req.policy_desc,- "service_id": req.service_id,- "priority": req.priority,- "match_expr": req.match_expr,- "template_ref": normalize_template_ref(req.template_ref),- "enabled": req.enabled,- "data": req.data,- "created_at": parse_iso_datetime(policy.get("created_at")) or now,- "updated_at": parse_iso_datetime(policy.get("updated_at")) or now,- }---class ConfigEffectiveServicePolicyService:-- async def create(- self,- jiuwenclaw_id: str,- policy: dict[str, Any],- ) -> dict[str, Any]:- repo = require_enterprise_repository(_TABLE)- result = await apply_create_from_row_builder(- repo,- section=_SECTION,- jiuwenclaw_id=jiuwenclaw_id,- record=policy,- build_row=_build_row_from_sync_policy,- )- logger.info(- "[ManagerConfigReceiver] config_effective_service_policies create id=%s",- result.get("id"),- )- return result-- async def update(- self,- jiuwenclaw_id: str,- row_id: Any,- updates: dict[str, Any],- ) -> None:- repo = require_enterprise_repository(_TABLE)- await apply_update_by_id(- repo,- section=_SECTION,- jiuwenclaw_id=jiuwenclaw_id,- row_id=row_id,- updates=updates,- update_record=update_config_effective_service_policy_record,- not_found_message=f"config effective service policy id={row_id} not found",- )- logger.info(- "[ManagerConfigReceiver] config_effective_service_policies update id=%s",- row_id,- )-- async def delete(self, jiuwenclaw_id: str, row_id: Any) -> None:- _ = jiuwenclaw_id- repo = require_enterprise_repository(_TABLE)- await apply_delete_by_id(- repo,- section=_SECTION,- row_id=row_id,- )- logger.info(- "[ManagerConfigReceiver] config_effective_service_policies delete id=%s",- row_id,- )diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_record_ops.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_record_ops.pydeleted file mode 100644index bcb170e76f..0000000000--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/config_effective_policy/config_record_ops.py+++ /dev/null@@ -1,159 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved--"""配置生效策略 / 映射记录的 CRUD 与 bulk sync 公共逻辑(EnterpriseRecordRepository)。"""--from __future__ import annotations--from collections.abc import Awaitable, Callable-from typing import Any--from jiuwenswarm.gateway.config.enterprise.repository import EnterpriseRecordRepository--from ...infrastructure.utils import utc_now--_LIST_ALL_CAP = 10_000--BuildRowFn = Callable[[dict[str, Any], str, Any], dict[str, Any]]-BeforeCreateFn = Callable[- [EnterpriseRecordRepository, str, dict[str, Any]], Awaitable[None]-]-UpdateRecordFn = Callable[- [EnterpriseRecordRepository, int, Any, str], Awaitable[dict[str, Any] | None]-]---async def get_row_for_instance(- repo: EnterpriseRecordRepository,- row_id: int,-) -> dict[str, Any] | None:- return await repo.get_by_row_id(row_id)---async def delete_record_for_instance(- repo: EnterpriseRecordRepository,- row_id: int,-) -> bool:- return await repo.delete_by_row_id(row_id)---async def create_record(- repo: EnterpriseRecordRepository,- row_data: dict[str, Any],- *,- section: str,- entity: str = "policy",-) -> dict[str, Any]:- created = await repo.create(row_data)- new_id = int(created.get("id", 0) or 0)- if new_id < 1:- raise ValueError(f"{section}.create: database did not return {entity} id")- return {"id": new_id}---async def apply_create_from_row_builder(- repo: EnterpriseRecordRepository,- *,- section: str,- jiuwenclaw_id: str,- record: Any,- build_row: BuildRowFn,- record_label: str = "policy",- entity: str = "policy",- before_create: BeforeCreateFn | None = None,-) -> dict[str, Any]:- if not isinstance(record, dict):- raise ValueError(f"{section}.create requires {record_label} object")- if before_create is not None:- await before_create(repo, jiuwenclaw_id, record)- row_data = build_row(record, jiuwenclaw_id, utc_now())- return await create_record(- repo,- row_data,- section=section,- entity=entity,- )---async def apply_update_by_id(- repo: EnterpriseRecordRepository,- *,- section: str,- jiuwenclaw_id: str,- row_id: Any,- updates: Any,- update_record: UpdateRecordFn,- not_found_message: str,-) -> None:- if row_id is None:- raise ValueError(f"{section}.update requires id")- if not isinstance(updates, dict) or not updates:- raise ValueError(f"{section}.update requires non-empty updates")- row = await update_record(repo, int(row_id), updates, jiuwenclaw_id)- if row is None:- raise ValueError(not_found_message)---async def apply_delete_by_id(- repo: EnterpriseRecordRepository,- *,- section: str,- row_id: Any,-) -> None:- if row_id is None:- raise ValueError(f"{section}.delete requires id")- await delete_record_for_instance(repo, int(row_id))---async def sync_records_by_policy_id(- repo: EnterpriseRecordRepository,- records: list[dict[str, Any]],- *,- jiuwenclaw_id: str,- build_row: BuildRowFn,-) -> dict[str, int]:- """按 ``policy_id`` upsert,并删除本实例下不在 incoming 集合中的行。"""- incoming_ids: set[str] = set()- synced = 0- now = utc_now()- table = repo.store_name- for item in records:- if not isinstance(item, dict):- raise ValueError(f"{table}.sync records must be objects")- policy_id = str(item.get("policy_id") or "").strip()- if not policy_id:- raise ValueError(f"{table}.sync record missing policy_id")- incoming_ids.add(policy_id)-- existing_rows = await repo.list(- filters={"policy_id": policy_id},- limit=1,- )- existing = existing_rows[0] if existing_rows else None- row_data = build_row(item, jiuwenclaw_id, now)- if existing is None:- raw_id = item.get("id")- if raw_id is not None:- row_data["id"] = int(raw_id)- await repo.create(row_data)- else:- created_at = existing.get("created_at")- if created_at is not None:- row_data["created_at"] = created_at- updates = {- key: value- for key, value in row_data.items()- if key not in ("jiuwenclaw_id", "policy_id", "id")- }- updates["updated_at"] = utc_now()- await repo.update({"policy_id": policy_id}, updates)- synced += 1-- deleted = 0- existing_rows = await repo.list(limit=_LIST_ALL_CAP)- for row in existing_rows:- pid = str(row.get("policy_id") or "")- if pid and pid not in incoming_ids:- if await repo.delete(policy_id=pid):- deleted += 1-- return {"synced_count": synced, "deleted_count": deleted}diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/__init__.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/__init__.pyindex 34716157fb..b45eec9952 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/__init__.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/__init__.py@@ -1,12 +1,9 @@# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved-"""Gateway 侧企业配置三级策略只读加载。"""+"""Gateway 侧企业配置只读加载(按实例 Agent 资源)。"""from ...infrastructure.utils import normalize_template_ref-from .loader import (- load_effective_enterprise_config,- load_effective_enterprise_config_old,-)+from .loader import load_effective_enterprise_configfrom .schemas import (SERVICE_CONFIG_SLOT,SERVICE_CONFIG_TABLE,@@ -23,5 +20,4 @@ __all__ = ("TemplateRefSlot","normalize_template_ref","load_effective_enterprise_config",- "load_effective_enterprise_config_old",)diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/loader.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/loader.pyindex 5240671bd2..c39f8a0172 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/loader.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/loader.py@@ -1,21 +1,15 @@# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved-"""从 Gateway DB 加载企业级生效配置(Service → Agent → Global 三级匹配)。"""+"""从 Gateway DB 按实例 Agent 资源加载企业级生效配置。"""from __future__ import annotationsfrom collections.abc import Collection-from dataclasses import dataclassfrom typing import Anyfrom openjiuwen_runtime.foundation.log import get_logger-from ...infrastructure.utils import (- fill_missing_template_ref_slots,- merge_template_ref,- normalize_template_ref,-)-from . import expressions+from ...infrastructure.utils import normalize_template_reffrom .gateway_db import GatewayDbfrom .schemas import (MODEL_SLOT_KEYS,@@ -26,79 +20,6 @@ from .schemas import (logger = get_logger(__name__)-# 策略/映射选路排序:priority 降序;同 priority 时 updated_at 越新越优先。-# SQLAlchemyHandler.list_records 的 str 形式 order_by 仅支持单列;多列须用 list[tuple[field, is_desc]]。-POLICY_MATCH_ORDER_BY: list[tuple[str, bool]] = [- ("priority", True),- ("updated_at", True),-]---async def _fetch_global_policy_refs() -> tuple[dict[str, Any] | None, dict[str, list[str]]]:- filters: dict[str, Any] = {"enabled": True}- global_rows = await GatewayDb.current().list_records(- "config_effective_global_policy",- filters=filters,- order_by=POLICY_MATCH_ORDER_BY,- )- if not global_rows:- return None, {}- matched_global = global_rows[0]- return matched_global, normalize_template_ref(matched_global.get("template_ref"))---@dataclass-class _PolicyMatchResult:- merged_refs: dict[str, list[str]]- matched_service: dict[str, Any] | None- matched_agent: dict[str, Any] | None- matched_global: dict[str, Any] | None---async def _resolve_policy_match(ctx: RoutingContext) -> _PolicyMatchResult:- service_rules = await GatewayDb.current().list_records(- "config_effective_service_policy",- filters={"enabled": True},- order_by=POLICY_MATCH_ORDER_BY,- )-- matched_service: dict[str, Any] | None = None- matched_agent: dict[str, Any] | None = None- matched_global, global_refs = await _fetch_global_policy_refs()- merged_refs: dict[str, list[str]] = {}-- for rule in service_rules:- if expressions.evaluate_match_expr(rule.get("match_expr"), ctx):- matched_service = rule- merged_refs = normalize_template_ref(rule.get("template_ref"))- break-- if matched_service is not None:- sp_policy_id = str(matched_service["policy_id"])- agent_rules = await GatewayDb.current().list_records(- "config_effective_agent_policy",- filters={"enabled": True, "service_policy_id": sp_policy_id},- order_by=POLICY_MATCH_ORDER_BY,- )- for rule in agent_rules:- if expressions.evaluate_match_expr(rule.get("match_expr"), ctx):- matched_agent = rule- merged_refs = merge_template_ref(- merged_refs,- normalize_template_ref(rule.get("template_ref")),- )- break- merged_refs = fill_missing_template_ref_slots(merged_refs, global_refs)- else:- merged_refs = global_refs-- return _PolicyMatchResult(- merged_refs=merged_refs,- matched_service=matched_service,- matched_agent=matched_agent,- matched_global=matched_global,- )-def _coerce_routing_field(value: Any) -> str:"""将路由字段规范为字符串(兼容 WebChannel ``parse_qs`` 的列表值)。"""@@ -224,140 +145,6 @@ async def _fetch_slot_entities(return entities-def resolve_policy_field(- policy: dict[str, Any] | None,- field: str,- ctx: RoutingContext,-) -> str | None:- if not policy:- return None- raw = str(policy.get(field) or "").strip()- if not raw:- return None- if "${" in raw:- resolved = expressions.substitute_template(raw, ctx)- return resolved if resolved else raw- return raw---async def load_effective_enterprise_config_old(- request: Any,- slots: Collection[TemplateRefSlot],-) -> EffectiveEnterpriseConfig | None:- """按 Service → Agent → Global 三级匹配加载企业配置(旧路径,保留供对照)。-- ``slots`` 指定要解析并加载的 ``template_ref`` 槽位,例如模型槽位、- ``TemplateRefSlot.EMBEDDING_MODEL``、``TemplateRefSlot.SKILL_WHITELIST``、- ``TemplateRefSlot.EXTENSION_CONFIG``、``TemplateRefSlot.SERVICE_CONFIG`` 等。- """- ctx = routing_context_from_request(request)- if not slots:- raise ValueError("slots must not be empty")- load_slots = frozenset(slot.value for slot in slots)- match = await _resolve_policy_match(ctx)-- resolved_service_id: str | None = None- resolved_agent_id: str | None = None- resolved_workspace_dir: str | None = None- if TemplateRefSlot.SERVICE_CONFIG in load_slots:- resolved_service_id = resolve_policy_field(- match.matched_service,- "service_id",- ctx,- )- resolved_agent_id = resolve_policy_field(- match.matched_agent,- "agent_id",- ctx,- )- resolved_workspace_dir = resolve_policy_field(- match.matched_agent,- "workspace_dir",- ctx,- )-- send_file_allowed = bool((match.matched_agent or {}).get("send_file_allowed", True))- has_policy_outcome = bool(- resolved_service_id- or resolved_agent_id- or resolved_workspace_dir- or send_file_allowed- )-- filtered_refs = {- slot: refs- for slot, refs in match.merged_refs.items()- if slot in load_slots- }-- if not filtered_refs:- logger.warning(- "[enterprise_config] no template_ref resolved for context %s slots=%s",- ctx.as_dict(),- sorted(load_slots),- )- if not has_policy_outcome:- return None- slot_template_id_map: dict[str, list[str]] = {}- else:- slot_template_id_map = await expressions.resolve_slot_template_id_map(- filtered_refs,- ctx,- )- if not slot_template_id_map:- logger.warning(- "[enterprise_config] template_ref slots unresolved for context %s refs=%s",- ctx.as_dict(),- filtered_refs,- )- if not has_policy_outcome:- return None-- result = EffectiveEnterpriseConfig(- routing=ctx,- template_ref=slot_template_id_map,- service_policy_id=(- str(match.matched_service["policy_id"]) if match.matched_service else None- ),- agent_policy_id=(- int(match.matched_agent["id"]) if match.matched_agent else None- ),- global_policy_id=(- int(match.matched_global["id"]) if match.matched_global else None- ),- service_id=resolved_service_id,- agent_id=resolved_agent_id,- workspace_dir=resolved_workspace_dir,- send_file_allowed=send_file_allowed,- service_policy=match.matched_service,- agent_policy=match.matched_agent,- global_policy=match.matched_global,- )-- for slot, template_ids in slot_template_id_map.items():- entities = await _fetch_slot_entities(slot, template_ids)- if entities:- _apply_slot_entities(result, slot, entities)-- if not _any_requested_slot_loaded(result, load_slots):- logger.warning(- "[enterprise_config] no template entities loaded "- "template_ref=%s ctx=%s slots=%s",- slot_template_id_map,- ctx.as_dict(),- sorted(load_slots),- )- if not has_policy_outcome:- return None-- logger.info(- "[enterprise_config] loaded enterprise config (old): slots=%s payload=%s",- sorted(load_slots),- result.as_dict(),- )- return result--async def _fetch_instance_agent_resource(resource_id: str) -> dict[str, Any] | None:rid = str(resource_id or "").strip()if not rid:@@ -518,8 +305,6 @@ async def load_effective_enterprise_config(__all__ = (- "POLICY_MATCH_ORDER_BY","load_effective_enterprise_config",- "load_effective_enterprise_config_old","routing_context_from_request",)diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/routing_id.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/routing_id.pydeleted file mode 100644index d24b33f2b9..0000000000--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/routing_id.py+++ /dev/null@@ -1,40 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved--"""service_id / agent_id 路由标识校验(与 substitute_template 约定一致)。"""--from __future__ import annotations--import re--_ROUTING_PLACEHOLDER = re.compile(r"\$\{(user_id|group_id|bot_id)\}")--ROUTING_ID_VALIDATION_ERROR = (- "invalid routing id placeholder: only ${user_id}, ${group_id}, ${bot_id} "- "are allowed when $ is present"-)---def validate_routing_id(value: str | None) -> str:- if value is None:- raise ValueError("routing id is required")- text = str(value).strip()- if not text:- raise ValueError("routing id cannot be empty")- if "$" not in text:- return text- remainder = _ROUTING_PLACEHOLDER.sub("", text)- if "$" in remainder:- raise ValueError(ROUTING_ID_VALIDATION_ERROR)- return text---def coerce_routing_id(value: str | None) -> str:- return validate_routing_id(value)---def coerce_routing_id_optional(value: str | None) -> str | None:- if value is None:- return None- if not str(value).strip():- return None- return validate_routing_id(value)diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/schemas.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/schemas.pyindex 0efdbbd53e..2506f9c38a 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/schemas.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/schemas.py@@ -13,7 +13,7 @@ SERVICE_CONFIG_TABLE = "service_config_template"class TemplateRefSlot(StrEnum):- """``template_ref`` JSON 键名,与 ``config_default_template_mapping.template_type`` 一致。"""+ """``template_ref`` JSON 键名(与 agent_template.template_ref 槽位一致)。"""DEFAULT_MODEL = "default_model"VIDEO_MODEL = "video_model"@@ -79,16 +79,10 @@ class EffectiveEnterpriseConfig:skill_whitelist: list[dict[str, Any]] | None = Noneextension_config: list[dict[str, Any]] | None = Noneservice_config: list[dict[str, Any]] | None = None- service_policy_id: str | None = None- agent_policy_id: int | None = None- global_policy_id: int | None = Noneservice_id: str | None = Noneagent_id: str | None = Noneworkspace_dir: str | None = Nonesend_file_allowed: bool = True- service_policy: dict[str, Any] | None = None- agent_policy: dict[str, Any] | None = None- global_policy: dict[str, Any] | None = Noneresource_id: str | None = Noneref_template_id: str | None = Noneagent_template: dict[str, Any] | None = None@@ -103,16 +97,10 @@ class EffectiveEnterpriseConfig:"skill_whitelist": self.skill_whitelist,"extension_config": self.extension_config,"service_config": self.service_config,- "service_policy_id": self.service_policy_id,- "agent_policy_id": self.agent_policy_id,- "global_policy_id": self.global_policy_id,"service_id": self.service_id,"agent_id": self.agent_id,"workspace_dir": self.workspace_dir,"send_file_allowed": self.send_file_allowed,- "service_policy": self.service_policy,- "agent_policy": self.agent_policy,- "global_policy": self.global_policy,"resource_id": self.resource_id,"ref_template_id": self.ref_template_id,"agent_template": self.agent_template,diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_data_lifecycle.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_data_lifecycle.pyindex f058eaf101..dba5feaef2 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_data_lifecycle.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_data_lifecycle.py@@ -29,10 +29,6 @@ INSTANCE_PURGE_TABLES: tuple[str, ...] = ("service_config_template","agent_template","instance_agent_resource",- "config_effective_global_policy",- "config_effective_service_policy",- "config_effective_agent_policy",- "config_default_template_mapping","log_masking_rule","logging_config","task_memory_config",diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/http/app.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/http/app.pyindex 911026ae24..e36d89119f 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/http/app.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/http/app.py@@ -7,7 +7,6 @@ from starlette.middleware.base import BaseHTTPMiddlewarefrom ..infrastructure.ha import gateway_deployment_mode, is_gateway_primaryfrom ..routers.application_config_routers import application_config_router-from ..routers.config_effective_policy_routers import config_effective_policy_routersfrom ..routers.instance_resource_routers import instance_resource_routerfrom ..routers.instance_routers import instance_routerfrom ..routers.register_router import register_router@@ -64,8 +63,6 @@ def create_app() -> FastAPI:v1.include_router(instance_router, tags=["Instances"])v1.include_router(instance_resource_router, tags=["Instance Resources"])v1.include_router(application_config_router, tags=["Application Config"])- for policy_router in config_effective_policy_routers:- v1.include_router(policy_router, tags=["Config Effective Policy"])app.include_router(v1)return appdiff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/config_effective_policy_models.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/config_effective_policy_models.pydeleted file mode 100644index ea74f03c39..0000000000--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/config_effective_policy_models.py+++ /dev/null@@ -1,129 +0,0 @@-# coding: utf-8-# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved--"""配置生效策略与默认模板映射表(与 Claw Manager 企业级数据模型对齐)。"""--from __future__ import annotations--from openjiuwen_runtime.foundation.db.table_def import (- ColumnDefinition,- IndexDefinition,- TableDefinition,-)--CONFIG_EFFECTIVE_GLOBAL_POLICY_TABLE_DEF = TableDefinition(- table_name="config_effective_global_policy",- columns=[- ColumnDefinition(- "id",- "integer",- primary_key=True,- autoincrement=True,- nullable=False,- ),- ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),- ColumnDefinition("policy_id", "string", length=100, nullable=False),- ColumnDefinition("policy_name", "string", length=128, nullable=False),- ColumnDefinition("policy_desc", "string", length=512, nullable=True),- ColumnDefinition("priority", "integer", nullable=False),- ColumnDefinition("template_ref", "json", nullable=False),- ColumnDefinition("enabled", "boolean", nullable=False, default=True),- ColumnDefinition("data", "json", nullable=True),- ColumnDefinition("created_at", "datetime", nullable=False),- ColumnDefinition("updated_at", "datetime", nullable=False),- ],- indexes=[- IndexDefinition(["jiuwenclaw_id", "policy_id"], unique=True),- ],-)---CONFIG_EFFECTIVE_SERVICE_POLICY_TABLE_DEF = TableDefinition(- table_name="config_effective_service_policy",- columns=[- ColumnDefinition(- "id",- "integer",- primary_key=True,- autoincrement=True,- nullable=False,- ),- ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),- ColumnDefinition("policy_id", "string", length=100, nullable=False),- ColumnDefinition("policy_name", "string", length=128, nullable=False),- ColumnDefinition("policy_desc", "string", length=512, nullable=True),- ColumnDefinition("service_id", "string", length=512, nullable=False),- ColumnDefinition("priority", "integer", nullable=False),- ColumnDefinition("match_expr", "string", length=8192, nullable=True),- ColumnDefinition("template_ref", "json", nullable=False),- ColumnDefinition("enabled", "boolean", nullable=False, default=True),- ColumnDefinition("data", "json", nullable=True),- ColumnDefinition("created_at", "datetime", nullable=False),- ColumnDefinition("updated_at", "datetime", nullable=False),- ],- indexes=[- IndexDefinition(["jiuwenclaw_id", "policy_id"], unique=True),- ],-)---CONFIG_EFFECTIVE_AGENT_POLICY_TABLE_DEF = TableDefinition(- table_name="config_effective_agent_policy",- columns=[- ColumnDefinition(- "id",- "integer",- primary_key=True,- autoincrement=True,- nullable=False,- ),- ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),- ColumnDefinition("policy_id", "string", length=100, nullable=False),- ColumnDefinition("policy_name", "string", length=128, nullable=False),- ColumnDefinition("policy_desc", "string", length=512, nullable=True),- ColumnDefinition("agent_id", "string", length=512, nullable=False),- ColumnDefinition("workspace_dir", "string", length=512, nullable=True),- ColumnDefinition("service_policy_id", "string", length=100, nullable=False),- ColumnDefinition("priority", "integer", nullable=False, default=0),- ColumnDefinition("match_expr", "string", length=8192, nullable=True),- ColumnDefinition("template_ref", "json", nullable=False),- ColumnDefinition("send_file_allowed", "boolean", nullable=False, default=True),- ColumnDefinition("enabled", "boolean", nullable=False, default=True),- ColumnDefinition("data", "json", nullable=True),- ColumnDefinition("created_at", "datetime", nullable=False),- ColumnDefinition("updated_at", "datetime", nullable=False),- ],- indexes=[- IndexDefinition(["jiuwenclaw_id", "policy_id"], unique=True),- ],-)---CONFIG_DEFAULT_TEMPLATE_MAPPING_TABLE_DEF = TableDefinition(- table_name="config_default_template_mapping",- columns=[- ColumnDefinition(- "id",- "integer",- primary_key=True,- autoincrement=True,- nullable=False,- ),- ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),- ColumnDefinition("policy_id", "string", length=100, nullable=False),- ColumnDefinition("policy_name", "string", length=128, nullable=False),- ColumnDefinition("policy_desc", "string", length=512, nullable=True),- ColumnDefinition("scope_type", "string", length=32, nullable=False),- ColumnDefinition("scope_id", "string", length=512, nullable=False),- ColumnDefinition("priority", "integer", nullable=False),- ColumnDefinition("template_id", "string", length=100, nullable=False),- ColumnDefinition("template_type", "string", length=512, nullable=False),- ColumnDefinition("enabled", "boolean", nullable=False, default=True),- ColumnDefinition("data", "json", nullable=True),- ColumnDefinition("created_at", "datetime", nullable=False),- ColumnDefinition("updated_at", "datetime", nullable=False),- ],- indexes=[- IndexDefinition(["jiuwenclaw_id", "policy_id"], unique=True),- ],-)diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/table_init.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/table_init.pyindex ae2bb41ce8..c3f54de88c 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/table_init.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/models/table_init.py@@ -15,12 +15,6 @@ from .application_config_models import (PERMISSIONS_CONFIG_TABLE_DEF,MEMORY_CONFIG_TABLE_DEF,)-from .config_effective_policy_models import (- CONFIG_DEFAULT_TEMPLATE_MAPPING_TABLE_DEF,- CONFIG_EFFECTIVE_AGENT_POLICY_TABLE_DEF,- CONFIG_EFFECTIVE_GLOBAL_POLICY_TABLE_DEF,- CONFIG_EFFECTIVE_SERVICE_POLICY_TABLE_DEF,-)from .cron_job_models import CRON_JOB_TABLE_DEFfrom .session_map_models import SESSION_MAP_TABLE_DEFfrom .key_models import (@@ -54,10 +48,6 @@ ALL_TABLE_DEFINITIONS: tuple[TableDefinition, ...] = (TASK_MEMORY_CONFIG_TABLE_DEF,PERMISSIONS_CONFIG_TABLE_DEF,MEMORY_CONFIG_TABLE_DEF,- CONFIG_DEFAULT_TEMPLATE_MAPPING_TABLE_DEF,- CONFIG_EFFECTIVE_GLOBAL_POLICY_TABLE_DEF,- CONFIG_EFFECTIVE_SERVICE_POLICY_TABLE_DEF,- CONFIG_EFFECTIVE_AGENT_POLICY_TABLE_DEF,CRON_JOB_TABLE_DEF,SESSION_MAP_TABLE_DEF,)diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/__init__.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/__init__.pyindex 83026a1a3d..20852bdbbd 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/__init__.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/__init__.py@@ -1,14 +1,14 @@"""HTTP routers for Manager → Gateway config sync."""from .application_config_routers import application_config_router-from .config_effective_policy_routers import config_effective_policy_routers+from .instance_resource_routers import instance_resource_routerfrom .instance_routers import instance_routerfrom .register_router import register_routerfrom .template_routers import templates_router__all__ = ["application_config_router",- "config_effective_policy_routers",+ "instance_resource_router","instance_router","register_router","templates_router",diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/config_effective_policy_routers.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/config_effective_policy_routers.pydeleted file mode 100644index 50983e8e0f..0000000000--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/config_effective_policy_routers.py+++ /dev/null@@ -1,211 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-"""配置生效策略与默认模板映射同步 API(显式 Body schema,对齐 Manager)。"""--from __future__ import annotations--from collections.abc import Callable-from typing import Annotated, Any--from fastapi import APIRouter, Depends, HTTPException, Request--from ..core.config_effective_policy import (- ConfigDefaultTemplateMappingService,- ConfigEffectiveAgentPolicyService,- ConfigEffectiveGlobalPolicyService,- ConfigEffectiveServicePolicyService,-)-from ..schemas.common_schemas import ResponseModel-from ..schemas.config_effective_policy_schemas import (- ConfigDefaultTemplateMappingCreateRequest,- ConfigDefaultTemplateMappingUpdateRequest,- ConfigEffectiveAgentPolicyCreateRequest,- ConfigEffectiveAgentPolicyUpdateRequest,- ConfigEffectiveGlobalPolicyCreateRequest,- ConfigEffectiveGlobalPolicyUpdateRequest,- ConfigEffectiveServicePolicyCreateRequest,- ConfigEffectiveServicePolicyUpdateRequest,-)-from ..schemas.sync_schemas import SyncEnvelopeOnlyBody, make_sync_body-from .deps import (- SyncContext,- VerifySyncEnvelopeOnly,- build_sync_context,- sync_write_data,- verify_sync,-)-from .runtime_notify import trigger_runtime_config_update--mapping_router = APIRouter(prefix="/config-default-template-mappings")-agent_policy_router = APIRouter(prefix="/config-effective/agent-policies")-global_policy_router = APIRouter(prefix="/config-effective/global-policies")-service_policy_router = APIRouter(prefix="/config-effective/service-policies")--MappingCreateSyncBody = make_sync_body(- "MappingCreateSyncBody", ConfigDefaultTemplateMappingCreateRequest-)-MappingUpdateSyncBody = make_sync_body(- "MappingUpdateSyncBody", ConfigDefaultTemplateMappingUpdateRequest-)--_ServiceFactory = Callable[[], Any]---def _http_exc(exc: ValueError) -> HTTPException:- detail = str(exc)- status = 404 if "not found" in detail else 400- return HTTPException(status_code=status, detail=detail)---@mapping_router.post("/", response_model=ResponseModel)-async def create_template_mapping(- sync: Annotated[SyncContext, Depends(verify_sync(MappingCreateSyncBody))],-):- try:- result = await ConfigDefaultTemplateMappingService().create(- sync.jiuwenclaw_id, sync.business- )- except ValueError as exc:- raise _http_exc(exc) from exc- trigger_runtime_config_update()- return ResponseModel(code=200, message="success", data=sync_write_data(sync, result))---@mapping_router.patch("/{mapping_id}", response_model=ResponseModel)-async def update_template_mapping(- mapping_id: int,- sync: Annotated[SyncContext, Depends(verify_sync(MappingUpdateSyncBody))],-):- try:- await ConfigDefaultTemplateMappingService().update(- sync.jiuwenclaw_id, mapping_id, sync.business- )- except ValueError as exc:- raise _http_exc(exc) from exc- trigger_runtime_config_update()- return ResponseModel(code=200, message="success", data=sync_write_data(sync, None))---@mapping_router.delete("/{mapping_id}", response_model=ResponseModel)-async def delete_template_mapping(- mapping_id: int,- sync: VerifySyncEnvelopeOnly,-):- try:- await ConfigDefaultTemplateMappingService().delete(- sync.jiuwenclaw_id, mapping_id- )- except ValueError as exc:- raise _http_exc(exc) from exc- trigger_runtime_config_update()- return ResponseModel(code=200, message="success", data=sync_write_data(sync, None))---def _add_policy_crud(- router: APIRouter,- svc_factory: _ServiceFactory,- tag: str,- create_body: type,- update_body: type,-) -> None:- create_sync = make_sync_body(f"{tag.title()}PolicyCreateSyncBody", create_body)- update_sync = make_sync_body(f"{tag.title()}PolicyUpdateSyncBody", update_body)-- async def create_policy(- request: Request,- body: Any,- ):- sync = await build_sync_context(body, request.method)- try:- result = await svc_factory().create(- sync.jiuwenclaw_id, sync.business- )- except ValueError as exc:- raise _http_exc(exc) from exc- trigger_runtime_config_update()- return ResponseModel(- code=200, message="success", data=sync_write_data(sync, result)- )-- async def update_policy(- request: Request,- policy_id: int,- body: Any,- ):- sync = await build_sync_context(body, request.method)- try:- await svc_factory().update(- sync.jiuwenclaw_id, policy_id, sync.business- )- except ValueError as exc:- raise _http_exc(exc) from exc- trigger_runtime_config_update()- return ResponseModel(- code=200, message="success", data=sync_write_data(sync, None)- )-- async def delete_policy(- request: Request,- policy_id: int,- body: SyncEnvelopeOnlyBody,- ):- sync = await build_sync_context(body, request.method)- try:- await svc_factory().delete(sync.jiuwenclaw_id, policy_id)- except ValueError as exc:- raise _http_exc(exc) from exc- trigger_runtime_config_update()- return ResponseModel(- code=200, message="success", data=sync_write_data(sync, None)- )-- create_policy.__name__ = f"create_{tag}_policy"- update_policy.__name__ = f"update_{tag}_policy"- delete_policy.__name__ = f"delete_{tag}_policy"- create_policy.__annotations__["body"] = create_sync- update_policy.__annotations__["body"] = update_sync-- router.add_api_route(- "/", create_policy, methods=["POST"], response_model=ResponseModel- )- router.add_api_route(- "/{policy_id}",- update_policy,- methods=["PATCH"],- response_model=ResponseModel,- )- router.add_api_route(- "/{policy_id}",- delete_policy,- methods=["DELETE"],- response_model=ResponseModel,- )---_add_policy_crud(- agent_policy_router,- ConfigEffectiveAgentPolicyService,- "agent",- ConfigEffectiveAgentPolicyCreateRequest,- ConfigEffectiveAgentPolicyUpdateRequest,-)-_add_policy_crud(- global_policy_router,- ConfigEffectiveGlobalPolicyService,- "global",- ConfigEffectiveGlobalPolicyCreateRequest,- ConfigEffectiveGlobalPolicyUpdateRequest,-)-_add_policy_crud(- service_policy_router,- ConfigEffectiveServicePolicyService,- "service",- ConfigEffectiveServicePolicyCreateRequest,- ConfigEffectiveServicePolicyUpdateRequest,-)--config_effective_policy_routers: list[APIRouter] = [- mapping_router,- agent_policy_router,- global_policy_router,- service_policy_router,-]diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/__init__.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/__init__.pyindex 05d2ed2c4e..abf841f55c 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/__init__.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/__init__.py@@ -1,27 +1,9 @@-from .config_effective_policy_schemas import (- ConfigDefaultTemplateMappingCreateRequest,- ConfigDefaultTemplateMappingUpdateRequest,- ConfigEffectiveAgentPolicyCreateRequest,- ConfigEffectiveAgentPolicyUpdateRequest,- ConfigEffectiveGlobalPolicyCreateRequest,- ConfigEffectiveGlobalPolicyUpdateRequest,- ConfigEffectiveServicePolicyCreateRequest,- ConfigEffectiveServicePolicyUpdateRequest,-)from .template_schemas import (ExtensionConfigTemplateUpdateRequest,ModelTemplateUpdateRequest,)__all__ = (- "ConfigDefaultTemplateMappingCreateRequest",- "ConfigDefaultTemplateMappingUpdateRequest",- "ConfigEffectiveAgentPolicyCreateRequest",- "ConfigEffectiveAgentPolicyUpdateRequest",- "ConfigEffectiveGlobalPolicyCreateRequest",- "ConfigEffectiveGlobalPolicyUpdateRequest",- "ConfigEffectiveServicePolicyCreateRequest",- "ConfigEffectiveServicePolicyUpdateRequest","ModelTemplateUpdateRequest","ExtensionConfigTemplateUpdateRequest",)diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/config_effective_policy_schemas.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/config_effective_policy_schemas.pydeleted file mode 100644index b52be8f80f..0000000000--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/config_effective_policy_schemas.py+++ /dev/null@@ -1,136 +0,0 @@-from __future__ import annotations--from typing import Annotated, Any--from pydantic import BaseModel, ConfigDict, Field, BeforeValidator--from ..core.enterprise_config.routing_id import (- coerce_routing_id,- coerce_routing_id_optional,-)-from ..infrastructure.utils import normalize_template_ref--TemplateRefField = Annotated[- dict[str, list[str]],- BeforeValidator(lambda value: {} if value is None else normalize_template_ref(value)),-]-OptionalTemplateRefField = Annotated[- dict[str, list[str]] | None,- BeforeValidator(- lambda value: None if value is None else normalize_template_ref(value)- ),-]-RoutingIdField = Annotated[str, BeforeValidator(coerce_routing_id)]-OptionalRoutingIdField = Annotated[str | None, BeforeValidator(coerce_routing_id_optional)]---class ConfigEffectiveServicePolicyUpdateRequest(BaseModel):- policy_name: str | None = Field(default=None, max_length=128, min_length=1)- policy_desc: str | None = Field(default=None, max_length=512)- service_id: OptionalRoutingIdField = Field(default=None, max_length=512)- priority: int | None = None- match_expr: str | None = None- template_ref: OptionalTemplateRefField = None- enabled: bool | None = None- data: dict[str, Any] | None = None---class ConfigEffectiveServicePolicyCreateRequest(BaseModel):- """创建 Service 层级配置生效策略(WebSocket 同步用)。"""-- model_config = ConfigDict(str_strip_whitespace=True)-- policy_id: str = Field(..., max_length=100, min_length=1)- policy_name: str = Field(..., max_length=128, min_length=1)- policy_desc: str | None = Field(default=None, max_length=512)- service_id: RoutingIdField = Field(..., max_length=512, min_length=1)- priority: int- match_expr: str | None = None- template_ref: TemplateRefField = Field(default_factory=dict)- enabled: bool = True- data: dict[str, Any] | None = None---class ConfigEffectiveGlobalPolicyUpdateRequest(BaseModel):- policy_name: str | None = Field(default=None, max_length=128, min_length=1)- policy_desc: str | None = Field(default=None, max_length=512)- priority: int | None = None- template_ref: OptionalTemplateRefField = None- enabled: bool | None = None- data: dict[str, Any] | None = None---class ConfigEffectiveGlobalPolicyCreateRequest(BaseModel):- """创建全局兜底配置生效策略(WebSocket 同步用,每实例至多一条)。"""-- model_config = ConfigDict(str_strip_whitespace=True)-- policy_id: str = Field(..., max_length=100, min_length=1)- policy_name: str = Field(..., max_length=128, min_length=1)- policy_desc: str | None = Field(default=None, max_length=512)- priority: int = 0- template_ref: TemplateRefField = Field(default_factory=dict)- enabled: bool = True- data: dict[str, Any] | None = None---class ConfigDefaultTemplateMappingUpdateRequest(BaseModel):- policy_name: str | None = Field(default=None, max_length=128, min_length=1)- policy_desc: str | None = Field(default=None, max_length=512)- scope_type: str | None = Field(default=None, max_length=32)- scope_id: str | None = Field(default=None, max_length=512)- priority: int | None = None- template_id: str | None = Field(default=None, max_length=512)- template_type: str | None = Field(default=None, max_length=512)- enabled: bool | None = None- data: dict[str, Any] | None = None---class ConfigEffectiveAgentPolicyUpdateRequest(BaseModel):- policy_name: str | None = Field(default=None, max_length=128, min_length=1)- policy_desc: str | None = Field(default=None, max_length=512)- agent_id: OptionalRoutingIdField = Field(default=None, max_length=512)- workspace_dir: OptionalRoutingIdField = Field(default=None, max_length=512)- service_policy_id: str | None = Field(default=None, max_length=100, min_length=1)- priority: int | None = None- match_expr: str | None = None- template_ref: OptionalTemplateRefField = None- send_file_allowed: bool | None = None- enabled: bool | None = None- data: dict[str, Any] | None = None---class ConfigEffectiveAgentPolicyCreateRequest(BaseModel):- """创建 Agent 层级配置生效策略(WebSocket 同步用)。"""-- model_config = ConfigDict(str_strip_whitespace=True)-- policy_id: str = Field(..., max_length=100, min_length=1)- policy_name: str = Field(..., max_length=128, min_length=1)- policy_desc: str | None = Field(default=None, max_length=512)- agent_id: RoutingIdField = Field(..., max_length=512, min_length=1)- workspace_dir: OptionalRoutingIdField = Field(default=None, max_length=512)- service_policy_id: str = Field(..., max_length=100, min_length=1)- priority: int = 0- match_expr: str | None = None- template_ref: TemplateRefField = Field(default_factory=dict)- send_file_allowed: bool = True- enabled: bool = True- data: dict[str, Any] | None = None---class ConfigDefaultTemplateMappingCreateRequest(BaseModel):- """创建作用域默认模板映射(WebSocket 同步用)。"""-- model_config = ConfigDict(str_strip_whitespace=True)-- policy_id: str = Field(..., max_length=100, min_length=1)- policy_name: str = Field(..., max_length=128, min_length=1)- policy_desc: str | None = Field(default=None, max_length=512)- scope_type: str = Field(..., max_length=32, min_length=1)- scope_id: str = Field(..., max_length=512, min_length=1)- priority: int = 0- template_id: str = Field(..., max_length=512, min_length=1)- template_type: str = Field(..., max_length=512, min_length=1)- enabled: bool = True- data: dict[str, Any] | None = Nonediff --git a/tests/unit_tests/agentserver/test_enterprise_policy.py b/tests/unit_tests/agentserver/test_enterprise_policy.pyindex 8338a9811d..f0634ad115 100644--- a/tests/unit_tests/agentserver/test_enterprise_policy.py+++ b/tests/unit_tests/agentserver/test_enterprise_policy.py@@ -291,33 +291,8 @@ async def test_resolve_template_slot_ref_or_literal_when_no_mapping(assert ref == _FALLBACK_TEMPLATE_ID-def test_fill_missing_template_ref_slots() -> None:- from jiuwenswarm.server.runtime.enterprise_config.loader import (- fill_missing_template_ref_slots,- )-- merged = {- "default_model": ["m3"],- "vision_model": ["m2"],- }- global_refs = {- "default_model": ["m1"],- "video_model": ["m1"],- "audio_model": ["m1"],- "skill_whitelist": ["w3"],- }- out = fill_missing_template_ref_slots(merged, global_refs)- assert out == {- "default_model": ["m3"],- "vision_model": ["m2"],- "video_model": ["m1"],- "audio_model": ["m1"],- "skill_whitelist": ["w3"],- }--@pytest.mark.asyncio-async def test_load_effective_config_fills_missing_slots_from_global(+async def test_load_effective_config_by_instance_agent_resource(monkeypatch: pytest.MonkeyPatch,) -> None:from jiuwenswarm.server.runtime.enterprise_config import gateway_db@@ -331,11 +306,12 @@ async def test_load_effective_config_fills_missing_slots_from_global(monkeypatch.setenv("JIUWENCLAW_ID", "sp-demo")m2 = "22222222-2222-4222-8222-222222222222"- m5 = "55555555-5555-4555-8555-555555555555"m1 = "11111111-1111-4111-8111-111111111111"- w1, w2, w3 = "w1", "w2", "w3"- e1, e2, e4 = "e1", "e2", "e4"+ w1, w2 = "w1", "w2"+ e1, e2 = "e1", "e2"jid = "sp-demo"+ resource_id = "bot_main"+ ref_template_id = "agent-tmpl-1"async def _list_records(table: str,@@ -344,64 +320,37 @@ async def test_load_effective_config_fills_missing_slots_from_global(order_by: str = "",) -> list[dict]:scoped = gateway_db.apply_instance_scope(table, dict(filters or {}))- if table == "config_effective_service_policy":- if scoped.get("jiuwenclaw_id") not in (None, jid):+ if table == "instance_agent_resource":+ if scoped.get("resource_id") != resource_id:return []return [{- "id": 1,"jiuwenclaw_id": jid,- "match_expr": "group_id == 'g_demo_sales'",- "template_ref": {- "default_model": [m2],- "vision_model": [m2],- "skill_whitelist": [w1, w2],- "extension_config": [e1, e2],- },+ "resource_id": resource_id,+ "resource_name": "main",+ "ref_template_id": ref_template_id,+ "grants": [{"match_expr": "", "enabled": True}],}]- if table == "config_effective_agent_policy":- if scoped.get("jiuwenclaw_id") not in (None, jid):+ if table == "agent_template":+ if scoped.get("template_id") != ref_template_id:return []return [{- "id": 10,"jiuwenclaw_id": jid,- "agent_id": "${user_id}",- "match_expr": "",+ "template_id": ref_template_id,+ "enabled": True,"template_ref": {- "default_model": [f"${{group::g_demo_sales}} or {m1}"],+ "default_model": [m2],+ "vision_model": [m2],+ "video_model": [m1],+ "audio_model": [m1],+ "skill_whitelist": [w1, w2],+ "extension_config": [e1, e2],},+ "data": {"workspace_dir": "/ws/bot_main"},}]- if table == "config_effective_global_policy":- if scoped.get("jiuwenclaw_id") == jid:- return [- {- "id": 99,- "jiuwenclaw_id": jid,- "template_ref": {- "default_model": [m1],- "vision_model": [m1],- "video_model": [m1],- "audio_model": [m1],- "skill_whitelist": [w3],- "extension_config": [e4],- },- }- ]- if scoped.get("jiuwenclaw_id") == "sp-other":- return [- {- "id": 1,- "jiuwenclaw_id": "sp-other",- "template_ref": {"extension_config": ["e3-old"]},- }- ]- return []- if table == "config_default_template_mapping":- if scoped.get("group_id") == "g_demo_sales":- return [{"template_id": m5}]return []async def _fetch_template_by_slot(slot: str, template_id: str) -> dict | None:@@ -414,7 +363,7 @@ async def test_load_effective_config_fills_missing_slots_from_global(request_id="req-test-bob",params={"group_id": "g_demo_sales",- "bot_id": "bot_main",+ "bot_id": resource_id,"user_id": "bob",},)@@ -423,17 +372,20 @@ async def test_load_effective_config_fills_missing_slots_from_global(DEFAULT_AGENT_LOAD_SLOTS,)assert loaded is not None- assert loaded.template_ref["default_model"] == [m5]+ assert loaded.resource_id == resource_id+ assert loaded.ref_template_id == ref_template_id+ assert loaded.agent_id == resource_id+ assert loaded.workspace_dir == "/ws/bot_main"+ assert loaded.template_ref["default_model"] == [m2]assert loaded.template_ref["vision_model"] == [m2]assert loaded.template_ref["video_model"] == [m1]assert loaded.template_ref["audio_model"] == [m1]assert loaded.template_ref["skill_whitelist"] == [w1, w2]assert loaded.template_ref["extension_config"] == [e1, e2]- assert loaded.global_policy_id == 99@pytest.mark.asyncio-async def test_load_effective_config_scopes_global_policy_by_jiuwenclaw_id(+async def test_load_effective_config_skips_mapping_expr_in_template_ref(monkeypatch: pytest.MonkeyPatch,) -> None:from jiuwenswarm.server.runtime.enterprise_config import gateway_db@@ -446,9 +398,9 @@ async def test_load_effective_config_scopes_global_policy_by_jiuwenclaw_id(monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")monkeypatch.setenv("JIUWENCLAW_ID", "sp-current")e4 = "44444444-4444-4444-8444-444444444444"- e3_old = "33333333-3333-4333-8333-333333333333"m1 = "11111111-1111-4111-8111-111111111111"- w3 = "w3"+ resource_id = "bot_main"+ ref_template_id = "agent-tmpl-ext"async def _list_records(table: str,@@ -457,32 +409,37 @@ async def test_load_effective_config_scopes_global_policy_by_jiuwenclaw_id(order_by: str = "",) -> list[dict]:scoped = gateway_db.apply_instance_scope(table, dict(filters or {}))- if table == "config_effective_service_policy":- return []- if table == "config_effective_global_policy":- jid = scoped.get("jiuwenclaw_id")- if jid == "sp-current":- return [- {- "id": 4,- "jiuwenclaw_id": "sp-current",- "template_ref": {- "default_model": [m1],- "vision_model": [m1],- "video_model": [m1],- "audio_model": [m1],- "skill_whitelist": [w3],- "extension_config": [e4],- },- }- ]- return []+ if table == "instance_agent_resource":+ if scoped.get("resource_id") != resource_id:+ return []+ return [+ {+ "jiuwenclaw_id": "sp-current",+ "resource_id": resource_id,+ "ref_template_id": ref_template_id,+ "grants": [{"match_expr": "", "enabled": True}],+ }+ ]+ if table == "agent_template":+ if scoped.get("template_id") != ref_template_id:+ return []+ return [+ {+ "jiuwenclaw_id": "sp-current",+ "template_id": ref_template_id,+ "enabled": True,+ "template_ref": {+ "default_model": [f"${{group::g_demo_sales}} or {m1}"],+ "extension_config": [e4],+ },+ }+ ]return []async def _fetch_template_by_slot(slot: str, template_id: str) -> dict | None:return {"template_id": template_id,- "template_name": "Gateway 定时清理" if template_id == e4 else "Agent Server 错误恢复",+ "template_name": "Gateway 定时清理" if template_id == e4 else "other","component": "gateway" if template_id == e4 else "agent_server","slot": slot,}@@ -494,7 +451,7 @@ async def test_load_effective_config_scopes_global_policy_by_jiuwenclaw_id(request_id="req-test-unknown",params={"group_id": "g_unknown",- "bot_id": "bot_main",+ "bot_id": resource_id,"user_id": "bob",},)@@ -503,7 +460,7 @@ async def test_load_effective_config_scopes_global_policy_by_jiuwenclaw_id(DEFAULT_AGENT_LOAD_SLOTS,)assert loaded is not None- assert loaded.global_policy_id == 4+ assert "default_model" not in loaded.template_refassert loaded.template_ref["extension_config"] == [e4]assert loaded.extension_config is not Noneassert loaded.extension_config[0]["template_name"] == "Gateway 定时清理"@@ -614,6 +571,8 @@ async def test_load_effective_config_loads_embedding_template(jid = "embedding-demo"monkeypatch.setenv("JIUWENCLAW_ID", jid)embedding_id = "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"+ resource_id = "bot_embed"+ ref_template_id = "agent-tmpl-embed"async def _list_records(table: str,@@ -622,16 +581,25 @@ async def test_load_effective_config_loads_embedding_template(order_by: str = "",) -> list[dict]:scoped = gateway_db.apply_instance_scope(table, dict(filters or {}))- if table == "config_effective_service_policy":- return []- if (- table == "config_effective_global_policy"- and scoped.get("jiuwenclaw_id") == jid- ):+ if table == "instance_agent_resource":+ if scoped.get("resource_id") != resource_id:+ return []+ return [+ {+ "jiuwenclaw_id": jid,+ "resource_id": resource_id,+ "ref_template_id": ref_template_id,+ "grants": [{"match_expr": "", "enabled": True}],+ }+ ]+ if table == "agent_template":+ if scoped.get("template_id") != ref_template_id:+ return []return [{- "id": 8,"jiuwenclaw_id": jid,+ "template_id": ref_template_id,+ "enabled": True,"template_ref": {"embedding_model": [embedding_id]},}]@@ -651,7 +619,10 @@ async def test_load_effective_config_loads_embedding_template(monkeypatch.setattr(gateway_db, "fetch_template_by_slot", _fetch_template_by_slot)loaded = await load_effective_enterprise_config(- AgentRequest(request_id="req-embedding"),+ AgentRequest(+ request_id="req-embedding",+ params={"bot_id": resource_id},+ ),DEFAULT_AGENT_LOAD_SLOTS,)diff --git a/tests/unit_tests/gateway/test_enterprise_record_repository.py b/tests/unit_tests/gateway/test_enterprise_record_repository.pyindex abc2d9c03e..9f5dd3d7f1 100644--- a/tests/unit_tests/gateway/test_enterprise_record_repository.py+++ b/tests/unit_tests/gateway/test_enterprise_record_repository.py@@ -21,41 +21,43 @@ from jiuwenswarm.gateway.storage_assembly.setup import (@pytest.mark.asyncio-async def test_policy_crud_and_scope() -> None:+async def test_instance_agent_resource_crud_and_scope() -> None:store = InMemoryPersistentBackend()repo = EnterpriseRecordRepository(store,- "config_effective_global_policy",+ "instance_agent_resource",instance_id="inst-1",)created = await repo.create({- "policy_id": "p1",- "policy_name": "global",- "priority": 10,- "template_ref": {"model": "t1"},- "enabled": True,+ "resource_id": "bot-main",+ "resource_name": "main agent",+ "ref_template_id": "tmpl-1",+ "grants": [{"match_expr": "", "enabled": True}],})assert created["jiuwenclaw_id"] == "inst-1"- assert created["policy_id"] == "p1"+ assert created["resource_id"] == "bot-main"- got = await repo.get(policy_id="p1")+ got = await repo.get(resource_id="bot-main")assert got is not None- assert got["policy_name"] == "global"+ assert got["resource_name"] == "main agent"- updated = await repo.update({"policy_id": "p1"}, {"priority": 20})+ updated = await repo.update(+ {"resource_id": "bot-main"},+ {"resource_name": "main agent v2"},+ )assert updated is not None- assert updated["priority"] == 20+ assert updated["resource_name"] == "main agent v2"other = EnterpriseRecordRepository(store,- "config_effective_global_policy",+ "instance_agent_resource",instance_id="inst-2",)assert await other.list() == []- assert await repo.delete(policy_id="p1") is True- assert await repo.get(policy_id="p1") is None+ assert await repo.delete(resource_id="bot-main") is True+ assert await repo.get(resource_id="bot-main") is None@pytest.mark.asyncio