Skip to content

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:gateway里去掉jiuwenclaw_id隔离

wangxina75a861275e8
diff --git a/jiuwenswarm/agents/harness/common/installed_skill.py b/jiuwenswarm/agents/harness/common/installed_skill.py
index e9f7ceecf1..554bfeabc9 100644
--- a/jiuwenswarm/agents/harness/common/installed_skill.py
+++ b/jiuwenswarm/agents/harness/common/installed_skill.py
@@ -101,7 +101,6 @@ def _row_to_dict(row: Any) -> dict[str, Any]:
return {k: getattr(row, k) for k in fields if not str(k).startswith("_")}
keys = (
"id",
- "jiuwenclaw_id",
"group_id",
"bot_id",
"user_id",
@@ -119,15 +118,6 @@ def _row_to_dict(row: Any) -> dict[str, Any]:
return {k: getattr(row, k) for k in keys if hasattr(row, k)}
-def _require_jiuwenclaw_id() -> str:
- from jiuwenswarm.gateway.cron.enterprise_gate import get_bound_jiuwenclaw_id
-
- jid = get_bound_jiuwenclaw_id()
- if not jid:
- raise RuntimeError("installed_skill requires bound jiuwenclaw_id")
- return jid
-
-
async def _handler() -> Any:
from jiuwenswarm.infrastructure.module_importer import import_manager_config_receiver_module
@@ -146,14 +136,8 @@ async def list_installed_skills(
aid = str(agent_id or "").strip()
if not sid or not aid:
return []
- try:
- jid = _require_jiuwenclaw_id()
- except RuntimeError:
- logger.warning("[InstalledSkill] list skipped: jiuwenclaw_id not bound")
- return []
filters: dict[str, Any] = {
- "jiuwenclaw_id": jid,
"service_id": sid,
"agent_id": aid,
}
@@ -200,15 +184,10 @@ async def get_installed_skill(
name = str(skill_name or "").strip()
if not sid or not aid or not name:
return None
- try:
- jid = _require_jiuwenclaw_id()
- except RuntimeError:
- return None
handler = await _handler()
row = await handler.get(
TABLE,
{
- "jiuwenclaw_id": jid,
"service_id": sid,
"agent_id": aid,
"skill_name": name,
@@ -241,21 +220,16 @@ async def upsert_installed_skill(
if st not in (SOURCE_PREBUILT, SOURCE_USER):
raise ValueError(f"invalid source_type: {source_type}")
- jid = _require_jiuwenclaw_id()
now = _utc_now()
handler = await _handler()
- existing = await handler.get(
- TABLE,
- {
- "jiuwenclaw_id": jid,
- "service_id": sid,
- "agent_id": aid,
- "skill_name": name,
- },
- )
+ identity = {
+ "service_id": sid,
+ "agent_id": aid,
+ "skill_name": name,
+ }
+ existing = await handler.get(TABLE, identity)
row_data: dict[str, Any] = {
- "jiuwenclaw_id": jid,
"service_id": sid,
"agent_id": aid,
"skill_name": name,
@@ -277,20 +251,10 @@ async def upsert_installed_skill(
if user_id is None and st == SOURCE_USER:
row_data["user_id"] = existing_map.get("user_id")
update_payload = dict(row_data)
- update_payload.pop("jiuwenclaw_id", None)
update_payload.pop("service_id", None)
update_payload.pop("agent_id", None)
update_payload.pop("skill_name", None)
- result = await handler.update(
- TABLE,
- {
- "jiuwenclaw_id": jid,
- "service_id": sid,
- "agent_id": aid,
- "skill_name": name,
- },
- update_payload,
- )
+ result = await handler.update(TABLE, identity, update_payload)
if result is None:
raise RuntimeError(f"failed to update installed_skill: {name}")
out = dict(row_data)
@@ -315,13 +279,11 @@ async def delete_installed_skill(
name = str(skill_name or "").strip()
if not sid or not aid or not name:
return False
- jid = _require_jiuwenclaw_id()
handler = await _handler()
return bool(
await handler.delete(
TABLE,
{
- "jiuwenclaw_id": jid,
"service_id": sid,
"agent_id": aid,
"skill_name": name,
diff --git a/jiuwenswarm/agents/harness/common/memory/config.py b/jiuwenswarm/agents/harness/common/memory/config.py
index f747fc4bf7..79f363ed66 100644
--- a/jiuwenswarm/agents/harness/common/memory/config.py
+++ b/jiuwenswarm/agents/harness/common/memory/config.py
@@ -167,14 +167,7 @@ async def reload_memory_config_from_gateway_db() -> dict[str, Any]:
try:
from jiuwenswarm.server.runtime.enterprise_config import gateway_db
- jid = gateway_db.resolve_jiuwenclaw_id()
- if not jid:
- return apply_memory_config_payload({"op": "delete"})
-
- rows = await gateway_db.list_records(
- MEMORY_CONFIG_TABLE,
- filters={"jiuwenclaw_id": jid},
- )
+ rows = await gateway_db.list_records(MEMORY_CONFIG_TABLE)
row = rows[0] if rows else None
body = row.get("body") if isinstance(row, dict) else None
if isinstance(body, dict) and body:
@@ -556,15 +549,7 @@ async def reload_task_memory_config_from_gateway_db() -> None:
try:
from jiuwenswarm.server.runtime.enterprise_config import gateway_db
- jid = gateway_db.resolve_jiuwenclaw_id()
- if not jid:
- _task_memory_config_db_cache = None
- return
-
- rows = await gateway_db.list_records(
- "task_memory_config",
- filters={"jiuwenclaw_id": jid},
- )
+ rows = await gateway_db.list_records("task_memory_config")
row = rows[0] if rows else None
if row is not None:
_task_memory_config_db_cache = {
diff --git a/jiuwenswarm/agents/harness/common/rails/permissions/config_loader.py b/jiuwenswarm/agents/harness/common/rails/permissions/config_loader.py
index e9eadff8c6..c4f88470d7 100644
--- a/jiuwenswarm/agents/harness/common/rails/permissions/config_loader.py
+++ b/jiuwenswarm/agents/harness/common/rails/permissions/config_loader.py
@@ -408,14 +408,7 @@ def _persist_permissions_to_yaml(permissions: dict[str, Any]) -> None:
async def _load_permissions_body_from_db() -> dict[str, Any] | None:
from jiuwenswarm.server.runtime.enterprise_config import gateway_db
- jid = gateway_db.resolve_jiuwenclaw_id()
- if not jid:
- return None
-
- rows = await gateway_db.list_records(
- PERMISSIONS_CONFIG_TABLE,
- filters={"jiuwenclaw_id": jid},
- )
+ rows = await gateway_db.list_records(PERMISSIONS_CONFIG_TABLE)
row = rows[0] if rows else None
if row is None:
return None
diff --git a/jiuwenswarm/agents/harness/common/tools/cron/cron_tools.py b/jiuwenswarm/agents/harness/common/tools/cron/cron_tools.py
index cb879440ff..08f31d0ffb 100644
--- a/jiuwenswarm/agents/harness/common/tools/cron/cron_tools.py
+++ b/jiuwenswarm/agents/harness/common/tools/cron/cron_tools.py
@@ -254,7 +254,6 @@ class CronTools:
from jiuwenswarm.gateway.cron.db_store import _row_to_job
from jiuwenswarm.gateway.cron.enterprise_gate import (
extract_routing_triple,
- get_bound_jiuwenclaw_id,
routing_triple_complete,
)
from jiuwenswarm.server.runtime.enterprise_config import gateway_db
@@ -264,9 +263,6 @@ class CronTools:
if not routing_triple_complete(g, b, u):
raise ValueError("enterprise cron list requires group_id, bot_id and user_id")
filters: dict[str, Any] = {"group_id": g, "bot_id": b, "user_id": u}
- jid = get_bound_jiuwenclaw_id()
- if jid:
- filters["jiuwenclaw_id"] = jid
rows = await gateway_db.list_records("cron_job", filters=filters, order_by="updated_at DESC")
out: list[dict[str, Any]] = []
for row in rows:
diff --git a/jiuwenswarm/common/utils.py b/jiuwenswarm/common/utils.py
index b16f6123b3..6bb7b7ff88 100644
--- a/jiuwenswarm/common/utils.py
+++ b/jiuwenswarm/common/utils.py
@@ -3319,15 +3319,7 @@ async def reload_logging_levels() -> None:
try:
from jiuwenswarm.server.runtime.enterprise_config import gateway_db
- jid = gateway_db.resolve_jiuwenclaw_id()
- if not jid:
- update_log_levels()
- return
-
- rows = await gateway_db.list_records(
- _LOGGING_CONFIG_TABLE,
- filters={"jiuwenclaw_id": jid},
- )
+ rows = await gateway_db.list_records(_LOGGING_CONFIG_TABLE)
row = rows[0] if rows else None
apply_logging_config_payload(
_logging_config_row_to_dict(row) if row is not None else None,
diff --git a/jiuwenswarm/gateway/config/channel/codec.py b/jiuwenswarm/gateway/config/channel/codec.py
index e2a7b33854..2fee10b41c 100644
--- a/jiuwenswarm/gateway/config/channel/codec.py
+++ b/jiuwenswarm/gateway/config/channel/codec.py
@@ -66,12 +66,11 @@ class YamlMapChannelCodec:
class DbRowChannelCodec:
"""enterprise:``channel_config`` 表行的编解码。
- 业务配置在 ``config`` JSON 列;``channel_id`` / ``jiuwenclaw_id`` 作主键。
+ 业务配置在 ``config`` JSON 列;主键为 ``channel_id``(每网关独立 DB)。
表行示例::
{
- "jiuwenclaw_id": "inst-1", # 由 instance_id 注入
"channel_id": "web",
"channel_name": "web",
"channel_type": "web",
@@ -82,13 +81,11 @@ class DbRowChannelCodec:
"""
def __init__(self, *, instance_id: str = "") -> None:
- self._instance_id = str(instance_id or "").strip()
+ _ = instance_id # 兼容旧构造参数;不再写入行键
- def identity(self, channel_id: str) -> dict[str, Any]:
- key: dict[str, Any] = {"channel_id": str(channel_id)}
- if self._instance_id:
- key["jiuwenclaw_id"] = self._instance_id
- return key
+ @staticmethod
+ def identity(channel_id: str) -> dict[str, Any]:
+ return {"channel_id": str(channel_id)}
@staticmethod
def from_record(record: dict[str, Any]) -> ChannelConfig:
@@ -103,9 +100,10 @@ class DbRowChannelCodec:
status=str(record.get("status") or "active"),
)
- def to_record(self, config: ChannelConfig) -> dict[str, Any]:
+ @staticmethod
+ def to_record(config: ChannelConfig) -> dict[str, Any]:
channel_id = config.channel_id
- row: dict[str, Any] = {
+ return {
"channel_id": channel_id,
"channel_name": config.channel_name or channel_id,
"channel_type": config.channel_type or channel_id,
@@ -113,14 +111,10 @@ class DbRowChannelCodec:
"config": dict(config.body),
"status": config.status or "active",
}
- if self._instance_id:
- row["jiuwenclaw_id"] = self._instance_id
- return row
def to_updates(self, config: ChannelConfig) -> dict[str, Any]:
record = self.to_record(config)
record.pop("channel_id", None)
- record.pop("jiuwenclaw_id", None)
return record
diff --git a/jiuwenswarm/gateway/config/enterprise/catalog.py b/jiuwenswarm/gateway/config/enterprise/catalog.py
index a11f9a55bf..c1d7981c97 100644
--- a/jiuwenswarm/gateway/config/enterprise/catalog.py
+++ b/jiuwenswarm/gateway/config/enterprise/catalog.py
@@ -1,7 +1,8 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-"""企业专属 PersistentStore name → 业务主键 / 实例作用域。
+"""企业专属 PersistentStore name → 业务主键。
仅 DB 布局(见 ``storage_assembly.layouts``);personal 无 file,调用应 fail-fast。
+每网关独立数据库,无实例隔离列。
"""
from __future__ import annotations
@@ -13,12 +14,12 @@ from dataclasses import dataclass
class EnterpriseRecordSpec:
"""一行企业表的定位方式。
- - ``key_fields``:业务主键(不含 ``jiuwenclaw_id``);空元组表示实例内至多一行。
- - ``scope_field``:实例隔离列;``None`` 表示全局单例表(如 gateway 密钥对)。
+ - ``key_fields``:业务主键;空元组表示库内至多一行。
+ - ``scope_field``:历史兼容字段;默认 ``None``(每网关独立 DB,不再做行级实例隔离)。
"""
key_fields: tuple[str, ...] = ()
- scope_field: str | None = "jiuwenclaw_id"
+ scope_field: str | None = None
# store name == DB 表名;与 layouts / EE TableDefinition 对齐。
@@ -34,7 +35,10 @@ ENTERPRISE_RECORD_SPECS: dict[str, EnterpriseRecordSpec] = {
"log_masking_rule": EnterpriseRecordSpec(key_fields=("rule_id",)),
"cron_job": EnterpriseRecordSpec(key_fields=("job_id",)),
"task_memory_config": EnterpriseRecordSpec(key_fields=()),
- "manager_sign_pubkey": EnterpriseRecordSpec(key_fields=()),
+ "manager_sign_pubkey": EnterpriseRecordSpec(
+ key_fields=("id",),
+ scope_field=None,
+ ),
"gateway_enc_keypair": EnterpriseRecordSpec(
key_fields=("id",),
scope_field=None,
diff --git a/jiuwenswarm/gateway/config/enterprise/instance_scope.py b/jiuwenswarm/gateway/config/enterprise/instance_scope.py
deleted file mode 100644
index 36910229d8..0000000000
--- a/jiuwenswarm/gateway/config/enterprise/instance_scope.py
+++ /dev/null
@@ -1,104 +0,0 @@
-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-"""企业 Gateway DB 实例隔离:catalog 推导 scoped 表 + 统一 instance id 解析。
-
-Gateway 写(``EnterpriseRecordRepository``)与 AgentServer 读(``gateway_db``)
-共用本模块,避免各维护一份 ``_INSTANCE_SCOPED_TABLES``。
-"""
-
-from __future__ import annotations
-
-import os
-from functools import lru_cache
-from typing import Any
-
-from jiuwenswarm.gateway.config.enterprise.catalog import ENTERPRISE_RECORD_SPECS
-
-
-@lru_cache(maxsize=1)
-def instance_scoped_store_names() -> frozenset[str]:
- """需自动附加 ``jiuwenclaw_id`` 的 store / 表名(与写侧 catalog 对齐)。"""
- return frozenset(
- name
- for name, spec in ENTERPRISE_RECORD_SPECS.items()
- if spec.scope_field == "jiuwenclaw_id"
- )
-
-
-def table_requires_instance_scope(table: str) -> bool:
- return table in instance_scoped_store_names()
-
-
-def list_records_requires_bound_instance(table: str, instance_id: str | None) -> bool:
- """scoped 表在未绑定实例 id 时不应查询(fail-closed)。"""
- return table_requires_instance_scope(table) and not instance_id
-
-
-def resolve_gateway_instance_id(cfg: dict[str, Any] | None = None) -> str | None:
- """读写共用的实例 ID 解析。
-
- 优先级(与 Gateway ``resolve_storage_instance_id`` 写路径对齐):
-
- 1. ``gateway.instance_id``(``config.yaml``)
- 2. Redis ``get_gateway_instance_id()``(若 extension 可用)
- 3. ``JIUWENCLAW_ID`` / ``JIUWENSWARM_ID``(Manager register.ack)
- 4. ``*_PROVISIONED_INSTANCE_ID``
- 5. ``GATEWAY_INSTANCE_ID``
- """
- if cfg is None:
- try:
- from jiuwenswarm.common.config import get_config
-
- cfg = get_config()
- except Exception:
- cfg = None
-
- if cfg:
- raw = (cfg.get("gateway") or {}).get("instance_id")
- if raw and str(raw).strip():
- return str(raw).strip()
-
- try:
- from jiuwenswarm.extensions.redis.redis_runtime import get_gateway_instance_id
-
- redis_id = get_gateway_instance_id()
- except Exception:
- # 模块缺失、初始化异常或未来实现变更均不应打断 instance id 解析;回退 env。
- redis_id = None
- if redis_id and str(redis_id).strip():
- return str(redis_id).strip()
-
- instance_id = (
- os.getenv("JIUWENCLAW_ID", "").strip()
- or os.getenv("JIUWENSWARM_ID", "").strip()
- or os.getenv("JIUWENSWARM_PROVISIONED_INSTANCE_ID", "").strip()
- or os.getenv("JIUWENCLAW_PROVISIONED_INSTANCE_ID", "").strip()
- or os.getenv("GATEWAY_INSTANCE_ID", "").strip()
- )
- return instance_id or None
-
-
-def apply_instance_scope(
- table: str,
- filters: dict[str, Any],
- *,
- instance_id: str | None = None,
-) -> dict[str, Any]:
- """为 scoped 表查询附加 ``jiuwenclaw_id``;显式 filter 优先。"""
- query = dict(filters)
- if not table_requires_instance_scope(table):
- return query
- resolved = instance_id
- if resolved is None:
- resolved = resolve_gateway_instance_id()
- if resolved and "jiuwenclaw_id" not in query:
- query["jiuwenclaw_id"] = resolved
- return query
-
-
-__all__ = [
- "apply_instance_scope",
- "instance_scoped_store_names",
- "list_records_requires_bound_instance",
- "resolve_gateway_instance_id",
- "table_requires_instance_scope",
-]
diff --git a/jiuwenswarm/gateway/config/enterprise/repository.py b/jiuwenswarm/gateway/config/enterprise/repository.py
index 1466f86d7c..d8f2d4b4ac 100644
--- a/jiuwenswarm/gateway/config/enterprise/repository.py
+++ b/jiuwenswarm/gateway/config/enterprise/repository.py
@@ -18,7 +18,7 @@ class EnterpriseRecordRepository:
"""企业配置 / 模板 / 密钥等表的通用 CRUD。
record 即业务 dict(与 EE ``DBHandler`` 行形状对齐);不引入领域 dataclass。
- 实例作用域由 ``instance_id`` + ``spec.scope_field`` 注入,调用方不必每次传。
+ ``instance_id`` / ``scope_field`` 保留兼容;默认无 scope(每网关独立 DB)。
"""
def __init__(
@@ -31,6 +31,7 @@ class EnterpriseRecordRepository:
) -> None:
self._store = store
self._store_name = store_name
+ # 保留构造参数以兼容旧调用方;scope_field 为 None 时不参与读写。
self._instance_id = str(instance_id or "").strip()
self._spec = spec if spec is not None else get_enterprise_record_spec(store_name)
@@ -160,7 +161,7 @@ class EnterpriseRecordRepository:
return await self._store.delete(self._store_name, self.identity(parts))
async def get_by_row_id(self, row_id: int) -> dict[str, Any] | None:
- """按自增 ``id`` 取行,并校验实例 scope(Manager WS update/delete)。"""
+ """按自增 ``id`` 取行(若有 scope_field 则校验,默认无)。"""
row = await self._store.get(self._store_name, {"id": int(row_id)})
if row is None:
return None
@@ -194,7 +195,7 @@ class EnterpriseRecordRepository:
*,
key_field: str | None = None,
) -> dict[str, int]:
- """按业务主键 upsert,并删除本实例下不在 incoming 集合中的行。
+ """按业务主键 upsert,并删除不在 incoming 集合中的行。
默认 ``key_field`` 取 ``spec.key_fields[0]``(如 ``policy_id`` / ``template_id``)。
无业务主键(单文档表)时只支持 0~1 条:有则 upsert,空列表则 delete。
diff --git a/jiuwenswarm/gateway/config/enterprise/tables/application_config_models.py b/jiuwenswarm/gateway/config/enterprise/tables/application_config_models.py
index 4dd162f136..5450eae014 100644
--- a/jiuwenswarm/gateway/config/enterprise/tables/application_config_models.py
+++ b/jiuwenswarm/gateway/config/enterprise/tables/application_config_models.py
@@ -17,7 +17,6 @@ LOG_MASKING_RULE_TABLE_DEF = TableDefinition(
autoincrement=True,
nullable=False,
),
- ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),
ColumnDefinition("rule_id", "string", length=64, nullable=False),
ColumnDefinition("rule_name", "string", length=128, nullable=False),
ColumnDefinition("description", "string", length=512, nullable=True),
@@ -37,7 +36,7 @@ LOG_MASKING_RULE_TABLE_DEF = TableDefinition(
ColumnDefinition("updated_at", "datetime", nullable=False),
],
indexes=[
- IndexDefinition(["jiuwenclaw_id", "rule_id"], unique=True),
+ IndexDefinition(["rule_id"], unique=True),
],
)
@@ -51,7 +50,6 @@ LOGGING_CONFIG_TABLE_DEF = TableDefinition(
autoincrement=True,
nullable=False,
),
- ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),
ColumnDefinition("level", "string", length=16, nullable=False, default="INFO"),
ColumnDefinition("console_level", "string", length=16, nullable=True),
ColumnDefinition("gateway", "string", length=16, nullable=True),
@@ -61,9 +59,7 @@ LOGGING_CONFIG_TABLE_DEF = TableDefinition(
ColumnDefinition("created_at", "datetime", nullable=False),
ColumnDefinition("updated_at", "datetime", nullable=False),
],
- indexes=[
- IndexDefinition(["jiuwenclaw_id"], unique=True),
- ],
+ indexes=[],
)
TASK_MEMORY_CONFIG_TABLE_DEF = TableDefinition(
@@ -76,7 +72,6 @@ TASK_MEMORY_CONFIG_TABLE_DEF = TableDefinition(
autoincrement=True,
nullable=False,
),
- ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),
ColumnDefinition("enabled", "boolean", nullable=False, default=False),
ColumnDefinition("llm_model", "string", length=256, nullable=True),
ColumnDefinition("embedding_model", "string", length=256, nullable=True),
@@ -87,9 +82,7 @@ TASK_MEMORY_CONFIG_TABLE_DEF = TableDefinition(
ColumnDefinition("created_at", "datetime", nullable=False),
ColumnDefinition("updated_at", "datetime", nullable=False),
],
- indexes=[
- IndexDefinition(["jiuwenclaw_id"], unique=False),
- ],
+ indexes=[],
)
PERMISSIONS_CONFIG_TABLE_DEF = TableDefinition(
@@ -102,16 +95,13 @@ PERMISSIONS_CONFIG_TABLE_DEF = TableDefinition(
autoincrement=True,
nullable=False,
),
- ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),
ColumnDefinition("body", "json", nullable=True),
ColumnDefinition("source", "string", length=16, nullable=False, default="manager"),
ColumnDefinition("revision", "integer", nullable=False, default=1),
ColumnDefinition("created_at", "datetime", nullable=False),
ColumnDefinition("updated_at", "datetime", nullable=False),
],
- indexes=[
- IndexDefinition(["jiuwenclaw_id"], unique=True),
- ],
+ indexes=[],
)
MEMORY_CONFIG_TABLE_DEF = TableDefinition(
@@ -124,14 +114,11 @@ MEMORY_CONFIG_TABLE_DEF = TableDefinition(
autoincrement=True,
nullable=False,
),
- ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),
ColumnDefinition("body", "json", nullable=True),
ColumnDefinition("source", "string", length=16, nullable=False, default="manager"),
ColumnDefinition("revision", "integer", nullable=False, default=1),
ColumnDefinition("created_at", "datetime", nullable=False),
ColumnDefinition("updated_at", "datetime", nullable=False),
],
- indexes=[
- IndexDefinition(["jiuwenclaw_id"], unique=True),
- ],
-)
\ No newline at end of file
+ indexes=[],
+)
diff --git a/jiuwenswarm/gateway/config/enterprise/tables/cron_job_models.py b/jiuwenswarm/gateway/config/enterprise/tables/cron_job_models.py
index 7ecdc2ac1a..23058df1fb 100644
--- a/jiuwenswarm/gateway/config/enterprise/tables/cron_job_models.py
+++ b/jiuwenswarm/gateway/config/enterprise/tables/cron_job_models.py
@@ -1,7 +1,7 @@
# coding: utf-8
# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved
-"""企业级定时任务表 ``cron_job``(按 ``jiuwenclaw_id`` 实例隔离)。"""
+"""企业级定时任务表 ``cron_job``(Gateway 本地库,按 job_id 唯一)。"""
from __future__ import annotations
@@ -21,9 +21,6 @@ CRON_JOB_TABLE_DEF = TableDefinition(
autoincrement=True,
nullable=False,
),
- ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),
- ColumnDefinition("service_id", "string", length=64, nullable=False, default="default"),
- ColumnDefinition("agent_id", "string", length=64, nullable=False, default="default"),
ColumnDefinition("job_id", "string", length=64, nullable=False),
ColumnDefinition(
"service_id", "string", length=256, nullable=False, default="default"
@@ -53,14 +50,14 @@ CRON_JOB_TABLE_DEF = TableDefinition(
ColumnDefinition("data", "json", nullable=True),
],
indexes=[
- IndexDefinition(["jiuwenclaw_id", "service_id", "agent_id", "job_id"], unique=True),
- # 该索引暂时注释掉:jiuwenclaw_id(64)+group_id(256)+bot_id(256)+user_id(256)
- # 在 utf8mb4 下共 3328 字节,超过 MySQL 索引键上限 3072 字节。
+ IndexDefinition(["job_id"], unique=True),
+ # 该索引暂时注释掉:group_id(256)+bot_id(256)+user_id(256)
+ # 在 utf8mb4 下共 3072 字节,接近 MySQL 索引键上限。
# 缩短 group_id/bot_id/user_id 列长度或改用前缀索引后再启用。
- # IndexDefinition(["jiuwenclaw_id", "group_id", "bot_id", "user_id"]),
- IndexDefinition(["jiuwenclaw_id", "group_id", "bot_id"]),
- IndexDefinition(["jiuwenclaw_id", "user_id"]),
- IndexDefinition(["jiuwenclaw_id", "enabled", "expired", "next_run_at"]),
+ # IndexDefinition(["group_id", "bot_id", "user_id"]),
+ IndexDefinition(["group_id", "bot_id"]),
+ IndexDefinition(["user_id"]),
+ IndexDefinition(["enabled", "expired", "next_run_at"]),
],
)
diff --git a/jiuwenswarm/gateway/config/enterprise/tables/instance_resource_models.py b/jiuwenswarm/gateway/config/enterprise/tables/instance_resource_models.py
index bf7baeee13..533e767c2c 100644
--- a/jiuwenswarm/gateway/config/enterprise/tables/instance_resource_models.py
+++ b/jiuwenswarm/gateway/config/enterprise/tables/instance_resource_models.py
@@ -1,7 +1,7 @@
# coding: utf-8
# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved
-"""实例资源表:instance_agent_resource(Gateway 本地副本;字段对齐 Manager,按 jiuwenclaw_id 隔离)。"""
+"""实例资源表:instance_agent_resource(Gateway 本地副本;字段对齐 Manager,每网关独立 DB)。"""
from __future__ import annotations
@@ -21,7 +21,6 @@ INSTANCE_AGENT_RESOURCE_TABLE_DEF = TableDefinition(
autoincrement=True,
nullable=False,
),
- ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),
ColumnDefinition("resource_id", "string", length=100, nullable=False),
ColumnDefinition("resource_name", "string", length=128, nullable=False),
ColumnDefinition("resource_desc", "string", length=512, nullable=True),
@@ -35,7 +34,7 @@ INSTANCE_AGENT_RESOURCE_TABLE_DEF = TableDefinition(
ColumnDefinition("updated_at", "datetime", nullable=False),
],
indexes=[
- IndexDefinition(["jiuwenclaw_id", "resource_id"], unique=True),
+ IndexDefinition(["resource_id"], unique=True),
],
)
diff --git a/jiuwenswarm/gateway/config/enterprise/tables/key_models.py b/jiuwenswarm/gateway/config/enterprise/tables/key_models.py
index 1dcac47ed5..ae1f56d4c1 100644
--- a/jiuwenswarm/gateway/config/enterprise/tables/key_models.py
+++ b/jiuwenswarm/gateway/config/enterprise/tables/key_models.py
@@ -5,7 +5,7 @@
- ``gateway_enc_keypair``:Gateway 自身 X25519 加密密钥对(单例,私钥本地受保护)。
- ``gateway_sign_keypair``:Gateway 自身 Ed25519 link-auth 签名密钥对(单例,握手出示令牌)。
-- ``manager_sign_pubkey``:握手分发的 Manager Ed25519 签名公钥,按 jiuwenclaw_id 关联。
+- ``manager_sign_pubkey``:握手分发的 Manager Ed25519 签名公钥(单例,id="default")。
"""
from __future__ import annotations
@@ -46,11 +46,11 @@ GATEWAY_SIGN_KEYPAIR_TABLE_DEF = TableDefinition(
indexes=[],
)
-# Manager 签名公钥(握手分发),按 jiuwenclaw_id 关联实例与对端 Manager。
+# Manager 签名公钥(握手分发),单例,固定主键 id="default"。
MANAGER_SIGN_PUBKEY_TABLE_DEF = TableDefinition(
table_name="manager_sign_pubkey",
columns=[
- ColumnDefinition("jiuwenclaw_id", "string", length=64, primary_key=True, nullable=False),
+ ColumnDefinition("id", "string", length=32, primary_key=True, nullable=False),
ColumnDefinition("manager_id", "string", length=64, nullable=False, default="default"),
ColumnDefinition("sign_alg", "string", length=32, nullable=False),
ColumnDefinition("public_key", "string", length=256, nullable=False),
diff --git a/jiuwenswarm/gateway/config/enterprise/tables/template_models.py b/jiuwenswarm/gateway/config/enterprise/tables/template_models.py
index 235f1f37f9..a16f6356b3 100644
--- a/jiuwenswarm/gateway/config/enterprise/tables/template_models.py
+++ b/jiuwenswarm/gateway/config/enterprise/tables/template_models.py
@@ -23,7 +23,6 @@ MODEL_TEMPLATE_TABLE_DEF = TableDefinition(
autoincrement=True,
nullable=False,
),
- ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),
ColumnDefinition("template_id", "string", length=100, nullable=False),
ColumnDefinition("template_name", "string", length=128, nullable=False),
ColumnDefinition("description", "string", length=512, nullable=True),
@@ -45,7 +44,7 @@ MODEL_TEMPLATE_TABLE_DEF = TableDefinition(
ColumnDefinition("updated_at", "datetime", nullable=False),
],
indexes=[
- IndexDefinition(["jiuwenclaw_id", "template_id"], unique=True),
+ IndexDefinition(["template_id"], unique=True),
],
)
@@ -59,7 +58,6 @@ EMBEDDING_TEMPLATE_TABLE_DEF = TableDefinition(
autoincrement=True,
nullable=False,
),
- ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),
ColumnDefinition("template_id", "string", length=100, nullable=False),
ColumnDefinition("template_name", "string", length=128, nullable=False),
ColumnDefinition("description", "string", length=512, nullable=True),
@@ -76,7 +74,7 @@ EMBEDDING_TEMPLATE_TABLE_DEF = TableDefinition(
ColumnDefinition("updated_at", "datetime", nullable=False),
],
indexes=[
- IndexDefinition(["jiuwenclaw_id", "template_id"], unique=True),
+ IndexDefinition(["template_id"], unique=True),
],
)
@@ -90,7 +88,6 @@ EXTENSION_CONFIG_TEMPLATE_TABLE_DEF = TableDefinition(
autoincrement=True,
nullable=False,
),
- ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),
ColumnDefinition("template_id", "string", length=100, nullable=False),
ColumnDefinition("template_name", "string", length=128, nullable=False),
ColumnDefinition("description", "string", length=512, nullable=True),
@@ -104,7 +101,7 @@ EXTENSION_CONFIG_TEMPLATE_TABLE_DEF = TableDefinition(
ColumnDefinition("updated_at", "datetime", nullable=False),
],
indexes=[
- IndexDefinition(["jiuwenclaw_id", "template_id"], unique=True),
+ IndexDefinition(["template_id"], unique=True),
],
)
@@ -118,7 +115,6 @@ SKILL_WHITELIST_TEMPLATE_TABLE_DEF = TableDefinition(
autoincrement=True,
nullable=False,
),
- ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),
ColumnDefinition("template_id", "string", length=100, nullable=False),
ColumnDefinition("template_name", "string", length=128, nullable=False),
ColumnDefinition("description", "string", length=512, nullable=True),
@@ -131,7 +127,7 @@ SKILL_WHITELIST_TEMPLATE_TABLE_DEF = TableDefinition(
ColumnDefinition("updated_at", "datetime", nullable=False),
],
indexes=[
- IndexDefinition(["jiuwenclaw_id", "template_id"], unique=True),
+ IndexDefinition(["template_id"], unique=True),
],
)
@@ -145,7 +141,6 @@ SERVICE_CONFIG_TEMPLATE_TABLE_DEF = TableDefinition(
autoincrement=True,
nullable=False,
),
- ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),
ColumnDefinition("template_id", "string", length=100, nullable=False),
ColumnDefinition("template_name", "string", length=128, nullable=False),
ColumnDefinition("description", "string", length=512, nullable=True),
@@ -199,7 +194,7 @@ SERVICE_CONFIG_TEMPLATE_TABLE_DEF = TableDefinition(
ColumnDefinition("updated_at", "datetime", nullable=False),
],
indexes=[
- IndexDefinition(["jiuwenclaw_id", "template_id"], unique=True),
+ IndexDefinition(["template_id"], unique=True),
],
)
@@ -213,7 +208,6 @@ AGENT_TEMPLATE_TABLE_DEF = TableDefinition(
autoincrement=True,
nullable=False,
),
- ColumnDefinition("jiuwenclaw_id", "string", length=64, nullable=False),
ColumnDefinition("template_id", "string", length=100, nullable=False),
ColumnDefinition("template_name", "string", length=128, nullable=False),
ColumnDefinition("description", "string", length=512, nullable=True),
@@ -225,6 +219,6 @@ AGENT_TEMPLATE_TABLE_DEF = TableDefinition(
ColumnDefinition("updated_at", "datetime", nullable=False),
],
indexes=[
- IndexDefinition(["jiuwenclaw_id", "template_id"], unique=True),
+ IndexDefinition(["template_id"], unique=True),
],
)
diff --git a/jiuwenswarm/gateway/config/section.py b/jiuwenswarm/gateway/config/section.py
index 5e18e39ac1..417eb12bd3 100644
--- a/jiuwenswarm/gateway/config/section.py
+++ b/jiuwenswarm/gateway/config/section.py
@@ -46,7 +46,7 @@ class YamlSectionCodec:
body = {
key: value
for key, value in dict(record).items()
- if key not in ("id", "jiuwenclaw_id", "source", "revision")
+ if key not in ("id", "source", "revision")
}
return SectionDocument(body=body)
@@ -66,8 +66,8 @@ class DbBodySectionCodec:
@staticmethod
def identity(instance_id: str = "") -> dict[str, Any]:
- iid = str(instance_id or "").strip()
- return {"jiuwenclaw_id": iid} if iid else {}
+ _ = instance_id
+ return {}
@staticmethod
def from_record(record: dict[str, Any]) -> SectionDocument:
@@ -83,15 +83,12 @@ class DbBodySectionCodec:
def to_record(
document: SectionDocument, *, instance_id: str = ""
) -> dict[str, Any]:
- row: dict[str, Any] = {
+ _ = instance_id
+ return {
"body": dict(document.body),
"source": document.source or "local",
"revision": int(document.revision or 1),
}
- iid = str(instance_id or "").strip()
- if iid:
- row["jiuwenclaw_id"] = iid
- return row
@staticmethod
def to_updates(document: SectionDocument) -> dict[str, Any]:
@@ -110,8 +107,8 @@ class DbFlatSectionCodec:
@staticmethod
def identity(instance_id: str = "") -> dict[str, Any]:
- iid = str(instance_id or "").strip()
- return {"jiuwenclaw_id": iid} if iid else {}
+ _ = instance_id
+ return {}
def from_record(self, record: dict[str, Any]) -> SectionDocument:
body = {
@@ -124,14 +121,12 @@ class DbFlatSectionCodec:
def to_record(
self, document: SectionDocument, *, instance_id: str = ""
) -> dict[str, Any]:
+ _ = instance_id
row: dict[str, Any] = {
key: document.body.get(key) for key in self._fields if key in document.body
}
if "level" not in row:
row["level"] = document.body.get("level") or "INFO"
- iid = str(instance_id or "").strip()
- if iid:
- row["jiuwenclaw_id"] = iid
return row
def to_updates(self, document: SectionDocument) -> dict[str, Any]:
@@ -220,13 +215,11 @@ class SectionDocumentRepository:
identity = self._identity()
existing_row = await self._load_row()
if existing_row is not None:
- # YAML 单文档用 {} 匹配;DB 优先用 instance_id,否则用已有行的 jiuwenclaw_id
+ # YAML 单文档用 {} 匹配;DB 单例按自增 id
key = identity
if not key:
key = {}
- if "jiuwenclaw_id" in existing_row:
- key = {"jiuwenclaw_id": existing_row["jiuwenclaw_id"]}
- elif "id" in existing_row:
+ if "id" in existing_row:
key = {"id": existing_row["id"]}
row = await self._store.update(
self._store_name,
@@ -249,9 +242,7 @@ class SectionDocumentRepository:
if row is None:
return False
key: dict[str, Any] = {}
- if "jiuwenclaw_id" in row:
- key = {"jiuwenclaw_id": row["jiuwenclaw_id"]}
- elif "id" in row:
+ if "id" in row:
key = {"id": row["id"]}
return await self._store.delete(self._store_name, key)
diff --git a/jiuwenswarm/gateway/config_poll/appliers.py b/jiuwenswarm/gateway/config_poll/appliers.py
index bb63eb6dd2..d8af294525 100644
--- a/jiuwenswarm/gateway/config_poll/appliers.py
+++ b/jiuwenswarm/gateway/config_poll/appliers.py
@@ -15,7 +15,7 @@ class TableApplyContext:
removed_channel_ids: frozenset[str] = frozenset()
-ApplyTableFn = Callable[[str, TableApplyContext], Awaitable[None]]
+ApplyTableFn = Callable[[TableApplyContext], Awaitable[None]]
def _enabled_log_masking_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
@@ -32,8 +32,7 @@ def _enabled_log_masking_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]
return enabled_rows
-async def apply_logging_config_table(jiuwenclaw_id: str, ctx: TableApplyContext) -> None:
- _ = jiuwenclaw_id
+async def apply_logging_config_table(ctx: TableApplyContext) -> None:
from jiuwenswarm.common.utils import (
_logging_config_row_to_dict,
apply_logging_config_payload,
@@ -51,8 +50,7 @@ async def apply_logging_config_table(jiuwenclaw_id: str, ctx: TableApplyContext)
logger.info("[ConfigPoll] logging_config applied rows=%d", len(ctx.rows))
-async def apply_log_masking_rule_table(jiuwenclaw_id: str, ctx: TableApplyContext) -> None:
- _ = jiuwenclaw_id
+async def apply_log_masking_rule_table(ctx: TableApplyContext) -> None:
from jiuwenswarm.infrastructure.log_masking.engine import LogMaskingEngine
rows = _enabled_log_masking_rows(ctx.rows)
@@ -60,8 +58,7 @@ async def apply_log_masking_rule_table(jiuwenclaw_id: str, ctx: TableApplyContex
logger.info("[ConfigPoll] log_masking_rule applied rows=%d", len(rows))
-async def apply_channel_config_table(jiuwenclaw_id: str, ctx: TableApplyContext) -> None:
- _ = jiuwenclaw_id
+async def apply_channel_config_table(ctx: TableApplyContext) -> None:
try:
from jiuwenswarm.gateway.channel_config_overlay import ChannelConfigChange
from jiuwenswarm.gateway.channel_config_reload import maybe_trigger_channel_config_reload
diff --git a/jiuwenswarm/gateway/config_poll/db.py b/jiuwenswarm/gateway/config_poll/db.py
index 390ee2a8d9..48c35964ed 100644
--- a/jiuwenswarm/gateway/config_poll/db.py
+++ b/jiuwenswarm/gateway/config_poll/db.py
@@ -40,7 +40,8 @@ def row_key(table: str, row: dict[str, Any]) -> str:
return str(row.get("channel_id") or "").strip()
if table == "log_masking_rule":
return str(row.get("rule_id") or "").strip()
- return str(row.get("jiuwenclaw_id") or row.get("id") or "default").strip()
+ # logging_config:单文档表
+ return str(row.get("id") or "default").strip()
def row_stamp(row: dict[str, Any]) -> str:
@@ -58,34 +59,20 @@ def row_snapshot(table: str, rows: list[dict[str, Any]]) -> dict[str, str]:
return snapshot
-def _poll_table_filters(table: str, jiuwenclaw_id: str) -> dict[str, Any]:
- """channel_config 为全局表(当前 MySQL 无 jiuwenclaw_id 列),不按实例过滤。"""
- if table == "channel_config":
- return {}
- jid = str(jiuwenclaw_id or "").strip()
- return {"jiuwenclaw_id": jid} if jid else {}
-
-
-async def list_table_records(table: str, jiuwenclaw_id: str) -> list[dict[str, Any]]:
- """拉取 poll 表行:优先 ``PersistentStore``,否则 ``gateway_db`` reader。"""
+async def list_table_records(table: str) -> list[dict[str, Any]]:
+ """拉取 poll 表全行:优先 ``PersistentStore``,否则 ``gateway_db`` reader。"""
if table not in _POLL_TABLES:
logger.warning("[ConfigPoll] unsupported table: %s", table)
return []
- jid = str(jiuwenclaw_id or "").strip()
- if table != "channel_config" and not jid:
- return []
from jiuwenswarm.gateway.storage.access import get_persistent_store
store = get_persistent_store()
if store is not None:
await store.ensure_ready()
- rows = await store.list(table, filters=_poll_table_filters(table, jid))
+ rows = await store.list(table)
return [dict(row) for row in rows or []]
from jiuwenswarm.server.runtime.enterprise_config import gateway_db
- return await gateway_db.list_records(
- table,
- filters=_poll_table_filters(table, jid),
- )
+ return await gateway_db.list_records(table)
diff --git a/jiuwenswarm/gateway/config_poll/syncer.py b/jiuwenswarm/gateway/config_poll/syncer.py
index 9aef2f531c..5b1383e2cc 100644
--- a/jiuwenswarm/gateway/config_poll/syncer.py
+++ b/jiuwenswarm/gateway/config_poll/syncer.py
@@ -4,8 +4,6 @@ from __future__ import annotations
import logging
-from jiuwenswarm.gateway.cron.enterprise_gate import get_bound_jiuwenclaw_id
-
from .appliers import TABLE_APPLIERS, TableApplyContext
from .db import POLL_TABLES, list_table_records, row_snapshot
@@ -25,32 +23,18 @@ class ConfigPollSyncer:
self._last_rows: dict[str, dict[str, str]] = {}
async def run_once(self) -> None:
- jiuwenclaw_id = get_bound_jiuwenclaw_id()
- if not jiuwenclaw_id:
- logger.debug("[ConfigPoll] skip: jiuwenclaw_id unset")
- return
-
for table in POLL_TABLES:
apply_fn = TABLE_APPLIERS.get(table)
if apply_fn is None:
logger.warning("[ConfigPoll] no applier registered for table=%s", table)
continue
try:
- await self._sync_table(table, jiuwenclaw_id, apply_fn)
+ await self._sync_table(table, apply_fn)
except Exception: # noqa: BLE001
- logger.exception(
- "[ConfigPoll] sync failed table=%s jiuwenclaw_id=%s",
- table,
- jiuwenclaw_id,
- )
+ logger.exception("[ConfigPoll] sync failed table=%s", table)
- async def _sync_table(
- self,
- table: str,
- jiuwenclaw_id: str,
- apply_fn,
- ) -> None:
- rows = await list_table_records(table, jiuwenclaw_id)
+ async def _sync_table(self, table: str, apply_fn) -> None:
+ rows = await list_table_records(table)
current = row_snapshot(table, rows)
previous = self._last_rows.get(table, {})
if current == previous:
@@ -61,13 +45,12 @@ class ConfigPollSyncer:
removed_channel_ids = frozenset(previous.keys()) - frozenset(current.keys())
ctx = TableApplyContext(rows=rows, removed_channel_ids=removed_channel_ids)
- await apply_fn(jiuwenclaw_id, ctx)
+ await apply_fn(ctx)
self._last_rows[table] = current
logger.info(
- "[ConfigPoll] table synced table=%s jiuwenclaw_id=%s rows=%d removed=%d",
+ "[ConfigPoll] table synced table=%s rows=%d removed=%d",
table,
- jiuwenclaw_id,
len(current),
len(removed_channel_ids),
)
diff --git a/jiuwenswarm/gateway/cron/controller.py b/jiuwenswarm/gateway/cron/controller.py
index 7f726f872e..8bd0e0e33f 100644
--- a/jiuwenswarm/gateway/cron/controller.py
+++ b/jiuwenswarm/gateway/cron/controller.py
@@ -163,7 +163,7 @@ class CronController:
def _require_enterprise_routing(params: dict[str, Any] | None) -> tuple[str, str, str]:
if is_enterprise() and not enterprise_cron_enabled():
raise PermissionError(
- "enterprise cron is not ready: jiuwenclaw_id not bound "
+ "enterprise cron is not ready: distributed deployment "
"(refuse write path; will not fall back to file store)"
)
g, b, u = extract_routing_triple(params or {})
@@ -394,7 +394,7 @@ class CronController:
) -> dict[str, Any]:
if is_enterprise() and not enterprise_cron_enabled():
raise PermissionError(
- "enterprise cron is not ready: jiuwenclaw_id not bound"
+ "enterprise cron is not ready: distributed deployment"
)
patch = strip_sticky_identity_fields(dict(patch or {}))
if "mode" in patch:
@@ -453,7 +453,7 @@ class CronController:
) -> bool:
if is_enterprise() and not enterprise_cron_enabled():
raise PermissionError(
- "enterprise cron is not ready: jiuwenclaw_id not bound"
+ "enterprise cron is not ready: distributed deployment"
)
existing = await self._store.get_job(job_id)
if existing is None:
diff --git a/jiuwenswarm/gateway/cron/db_store.py b/jiuwenswarm/gateway/cron/db_store.py
index 4c96e5b24a..4bce4fd0ed 100644
--- a/jiuwenswarm/gateway/cron/db_store.py
+++ b/jiuwenswarm/gateway/cron/db_store.py
@@ -18,7 +18,6 @@ from jiuwenswarm.gateway.cron.cron_job_mutations import (
build_new_cron_job,
sort_cron_jobs,
)
-from jiuwenswarm.gateway.cron.enterprise_gate import get_bound_jiuwenclaw_id
from jiuwenswarm.gateway.cron.models import CronJob
from jiuwenswarm.gateway.storage.protocols.persistent import PersistentStore
@@ -157,19 +156,12 @@ def _row_to_job(row: Any) -> CronJob | None:
class GatewayDbCronJobStore:
- """企业 cron 权威:``cron_job`` 表经 ``PersistentStore``。"""
+ """企业 cron 权威:``cron_job`` 表经 ``PersistentStore``(按 ``job_id`` 定位)。"""
def __init__(self) -> None:
self._lock = asyncio.Lock()
self._revision = 0
- @staticmethod
- def _require_jiuwenclaw_id() -> str:
- jid = get_bound_jiuwenclaw_id()
- if not jid:
- raise RuntimeError("enterprise cron requires bound jiuwenclaw_id")
- return jid
-
@staticmethod
async def _require_store() -> PersistentStore:
from jiuwenswarm.gateway.storage.access import require_persistent_store
@@ -177,8 +169,8 @@ class GatewayDbCronJobStore:
return await require_persistent_store()
@staticmethod
- def _job_identity(*, jiuwenclaw_id: str, job_id: str) -> dict[str, Any]:
- return {"jiuwenclaw_id": jiuwenclaw_id, "job_id": job_id}
+ def _job_identity(*, job_id: str) -> dict[str, Any]:
+ return {"job_id": job_id}
async def get_revision(self) -> int:
return int(self._revision)
@@ -187,9 +179,8 @@ class GatewayDbCronJobStore:
self._revision = int(time.time() * 1_000_000)
async def list_jobs(self, *, filters: dict[str, Any] | None = None) -> list[CronJob]:
- jid = self._require_jiuwenclaw_id()
store = await self._require_store()
- query: dict[str, Any] = {"jiuwenclaw_id": jid}
+ query: dict[str, Any] = {}
filters = dict(filters or {})
for key in ("group_id", "bot_id", "user_id"):
val = filters.get(key)
@@ -197,7 +188,7 @@ class GatewayDbCronJobStore:
query[key] = val.strip()
rows = await store.list(
_TABLE,
- filters=query,
+ filters=query or None,
order_by="updated_at DESC",
)
jobs: list[CronJob] = []
@@ -211,11 +202,10 @@ class GatewayDbCronJobStore:
job_id = str(job_id or "").strip()
if not job_id:
return None
- jid = self._require_jiuwenclaw_id()
store = await self._require_store()
rows = await store.list(
_TABLE,
- filters=self._job_identity(jiuwenclaw_id=jid, job_id=job_id),
+ filters=self._job_identity(job_id=job_id),
limit=1,
)
if not rows:
@@ -223,7 +213,7 @@ class GatewayDbCronJobStore:
return _row_to_job(rows[0])
@staticmethod
- def _job_to_row(job: CronJob, *, jiuwenclaw_id: str) -> dict[str, Any]:
+ def _job_to_row(job: CronJob) -> dict[str, Any]:
now_iso = _utc_now_iso()
created_iso = (
_epoch_to_dt(job.created_at).astimezone(dt_timezone.utc).isoformat()
@@ -232,7 +222,6 @@ class GatewayDbCronJobStore:
)
extra = _extra_from_job(job)
return {
- "jiuwenclaw_id": jiuwenclaw_id,
"job_id": job.id,
"group_id": job.group_id,
"bot_id": job.bot_id,
@@ -260,11 +249,10 @@ class GatewayDbCronJobStore:
}
async def create_job(self, **kwargs: Any) -> CronJob:
- jid = self._require_jiuwenclaw_id()
store = await self._require_store()
job = build_new_cron_job(**kwargs)
- row_data = self._job_to_row(job, jiuwenclaw_id=jid)
- identity = self._job_identity(jiuwenclaw_id=jid, job_id=job.id)
+ row_data = self._job_to_row(job)
+ identity = self._job_identity(job_id=job.id)
async with self._lock:
existing_rows = await store.list(_TABLE, filters=identity, limit=1)
if existing_rows:
@@ -277,16 +265,14 @@ class GatewayDbCronJobStore:
job_id = str(job_id or "").strip()
if not job_id:
raise ValueError("id is required")
- jid = self._require_jiuwenclaw_id()
store = await self._require_store()
- identity = self._job_identity(jiuwenclaw_id=jid, job_id=job_id)
+ identity = self._job_identity(job_id=job_id)
async with self._lock:
existing = await self.get_job(job_id)
if existing is None:
raise KeyError("job not found")
updated = apply_cron_job_patch(existing, patch)
- row_data = self._job_to_row(updated, jiuwenclaw_id=jid)
- row_data.pop("jiuwenclaw_id", None)
+ row_data = self._job_to_row(updated)
row_data.pop("job_id", None)
row_data.pop("created_at", None)
if "last_run_at" in patch:
@@ -301,9 +287,8 @@ class GatewayDbCronJobStore:
job_id = str(job_id or "").strip()
if not job_id:
return False
- jid = self._require_jiuwenclaw_id()
store = await self._require_store()
- identity = self._job_identity(jiuwenclaw_id=jid, job_id=job_id)
+ identity = self._job_identity(job_id=job_id)
async with self._lock:
deleted = await store.delete(_TABLE, identity)
if deleted:
diff --git a/jiuwenswarm/gateway/cron/enterprise_gate.py b/jiuwenswarm/gateway/cron/enterprise_gate.py
index 6b9d74aa4d..eae3aa4ea0 100644
--- a/jiuwenswarm/gateway/cron/enterprise_gate.py
+++ b/jiuwenswarm/gateway/cron/enterprise_gate.py
@@ -14,25 +14,10 @@ from jiuwenswarm.deployment_mode import MODE_DISTRIBUTED, normalize_deployment_m
logger = logging.getLogger(__name__)
STICKY_IDENTITY_FIELDS = frozenset(
- {"group_id", "bot_id", "user_id", "jiuwenclaw_id", "job_id", "created_at"}
+ {"group_id", "bot_id", "user_id", "job_id", "created_at"}
)
-def get_bound_jiuwenclaw_id() -> str | None:
- """读取当前绑定的实例 id。"""
- try:
- from jiuwenswarm.server.runtime.enterprise_config import gateway_db
-
- return gateway_db.resolve_jiuwenclaw_id()
- except Exception:
- logger.debug("Failed to read jiuwenclaw_id from gateway_db", exc_info=True)
- env = (
- os.getenv("JIUWENCLAW_ID", "").strip()
- or os.getenv("JIUWENSWARM_ID", "").strip()
- )
- return env or None
-
-
def _resolve_deployment_mode() -> str:
try:
from jiuwenswarm.common.config import get_config
@@ -46,8 +31,8 @@ def _resolve_deployment_mode() -> str:
def enterprise_cron_enabled(*, deployment_mode: str | None = None) -> bool:
- """企业 cron 真正开门:实例 id 已绑定,且非 distributed。"""
- if not get_bound_jiuwenclaw_id():
+ """企业 cron 真正开门:企业版且非 distributed(每网关独立 DB)。"""
+ if not is_enterprise():
return False
mode = deployment_mode if deployment_mode is not None else _resolve_deployment_mode()
return normalize_deployment_mode(mode) != MODE_DISTRIBUTED
@@ -159,7 +144,6 @@ __all__ = (
"coerce_routing_id",
"enterprise_cron_enabled",
"extract_routing_triple",
- "get_bound_jiuwenclaw_id",
"job_matches_routing",
"routing_triple_complete",
"strip_sticky_identity_fields",
diff --git a/jiuwenswarm/gateway/storage/backends/db/reader.py b/jiuwenswarm/gateway/storage/backends/db/reader.py
index 1b11d5281f..bfba28b528 100644
--- a/jiuwenswarm/gateway/storage/backends/db/reader.py
+++ b/jiuwenswarm/gateway/storage/backends/db/reader.py
@@ -2,7 +2,7 @@
"""Gateway DB 只读/轻量写(OSS):AgentServer 与 enterprise_config 共用。
不依赖 jiuwenclaw-ee。按 ``GATEWAY_*`` 连 sqlite 或 MySQL/PG,与 Gateway 写库同环境变量。
-业务隔离(``jiuwenclaw_id``)由调用方在 filters 中完成。
+每网关独立数据库,读写不加行级 ``jiuwenclaw_id`` 隔离。
"""
from __future__ import annotations
@@ -387,27 +387,21 @@ async def list_records(
async def upsert_permissions_config(
body: dict[str, Any],
*,
- jiuwenclaw_id: str,
source: str = "runtime_persist",
) -> None:
- """按 ``jiuwenclaw_id`` upsert ``permissions_config``。"""
+ """单例行 upsert ``permissions_config``(每网关独立 DB,无行级实例隔离)。"""
from datetime import datetime, timezone
- jid = str(jiuwenclaw_id or "").strip()
- if not jid:
- raise ValueError("JIUWENCLAW_ID is required for enterprise permissions persist")
-
now = datetime.now(timezone.utc).isoformat()
body_json = json.dumps(body, ensure_ascii=False)
if use_remote_gateway_db():
- await _upsert_permissions_remote(jid, body_json, source=source, now=now)
+ await _upsert_permissions_remote(body_json, source=source, now=now)
return
- await _upsert_permissions_sqlite(jid, body_json, source=source, now=now)
+ await _upsert_permissions_sqlite(body_json, source=source, now=now)
async def _upsert_permissions_remote(
- jid: str,
body_json: str,
*,
source: str,
@@ -422,11 +416,11 @@ async def _upsert_permissions_remote(
engine = await get_remote_engine()
async with engine.begin() as conn:
result = await conn.execute(
- text(f"SELECT id, revision FROM {table} WHERE jiuwenclaw_id = :jid"),
- {"jid": jid},
+ text(f"SELECT id, revision FROM {table} ORDER BY id ASC LIMIT 1"),
)
existing = result.fetchone()
if existing is not None:
+ row_id = int(existing[0])
revision = int(existing[1] or 1) + 1
await conn.execute(
text(
@@ -434,7 +428,7 @@ async def _upsert_permissions_remote(
UPDATE {table}
SET body = :body, source = :source, revision = :revision,
updated_at = :updated_at
- WHERE jiuwenclaw_id = :jid
+ WHERE id = :id
"""
),
{
@@ -442,7 +436,7 @@ async def _upsert_permissions_remote(
"source": source,
"revision": revision,
"updated_at": now,
- "jid": jid,
+ "id": row_id,
},
)
else:
@@ -450,12 +444,11 @@ async def _upsert_permissions_remote(
text(
f"""
INSERT INTO {table}
- (jiuwenclaw_id, body, source, revision, created_at, updated_at)
- VALUES (:jid, :body, :source, 1, :created_at, :updated_at)
+ (body, source, revision, created_at, updated_at)
+ VALUES (:body, :source, 1, :created_at, :updated_at)
"""
),
{
- "jid": jid,
"body": body_json,
"source": source,
"created_at": now,
@@ -465,7 +458,6 @@ async def _upsert_permissions_remote(
async def _upsert_permissions_sqlite(
- jid: str,
body_json: str,
*,
source: str,
@@ -478,32 +470,31 @@ async def _upsert_permissions_sqlite(
table = PERMISSIONS_CONFIG_TABLE
async with aiosqlite.connect(db_path) as conn:
async with conn.execute(
- f"SELECT id, revision FROM {table} WHERE jiuwenclaw_id = ?",
- (jid,),
+ f"SELECT id, revision FROM {table} ORDER BY id ASC LIMIT 1",
) as cursor:
existing = await cursor.fetchone()
if existing is not None:
+ row_id = int(existing[0])
revision = int(existing[1] or 1) + 1
await conn.execute(
f"""
UPDATE {table}
SET body = ?, source = ?, revision = ?, updated_at = ?
- WHERE jiuwenclaw_id = ?
+ WHERE id = ?
""",
- (body_json, source, revision, now, jid),
+ (body_json, source, revision, now, row_id),
)
else:
await conn.execute(
f"""
INSERT INTO {table}
- (jiuwenclaw_id, body, source, revision, created_at, updated_at)
- VALUES (?, ?, ?, 1, ?, ?)
+ (body, source, revision, created_at, updated_at)
+ VALUES (?, ?, 1, ?, ?)
""",
- (jid, body_json, source, now, now),
+ (body_json, source, now, now),
)
await conn.commit()
-
__all__ = [
"PERMISSIONS_CONFIG_TABLE",
"build_filter_clause",
diff --git a/jiuwenswarm/gateway/storage_assembly/db_connection.py b/jiuwenswarm/gateway/storage_assembly/db_connection.py
index 57cda54468..062765f516 100644
--- a/jiuwenswarm/gateway/storage_assembly/db_connection.py
+++ b/jiuwenswarm/gateway/storage_assembly/db_connection.py
@@ -44,7 +44,7 @@ def assert_replicas_db_compat() -> None:
class GatewayDbConnection:
- """绑定 EE GatewayDb;不注入 ``jiuwenclaw_id``。建表只在首次 ``ensure_ready`` 执行。"""
+ """绑定 EE GatewayDb 进程内单例。建表只在首次 ``ensure_ready`` 执行。"""
def __init__(self) -> None:
self._db_obj: Any | None = None
@@ -55,7 +55,7 @@ class GatewayDbConnection:
from jiuwenswarm.infrastructure.module_importer import import_manager_config_receiver_module
gateway_db_mod = import_manager_config_receiver_module("core.enterprise_config.gateway_db")
- db = gateway_db_mod.GatewayDb.bind(None)
+ db = gateway_db_mod.GatewayDb.current()
self._db_obj = db
return db
diff --git a/jiuwenswarm/gateway/storage_assembly/setup.py b/jiuwenswarm/gateway/storage_assembly/setup.py
index eaf880a192..7d0534ab33 100644
--- a/jiuwenswarm/gateway/storage_assembly/setup.py
+++ b/jiuwenswarm/gateway/storage_assembly/setup.py
@@ -104,13 +104,9 @@ def _create_ephemeral_factory():
def resolve_storage_instance_id(cfg: dict[str, Any] | None = None) -> str:
- """企业表 ``jiuwenclaw_id``(与 AgentServer 读库共用 ``resolve_gateway_instance_id``)。"""
- from jiuwenswarm.gateway.config.enterprise.instance_scope import (
- resolve_gateway_instance_id,
- )
-
- resolved = resolve_gateway_instance_id(cfg)
- return resolved or ""
+ """每网关独立 DB,装配层固定传空 ``instance_id``(不再解析 Manager/env 身份)。"""
+ _ = cfg
+ return ""
def _storage_flag(
@@ -211,7 +207,7 @@ def _wire_personal_yaml_section_repositories(
if is_enterprise():
return
- instance_id = resolve_storage_instance_id(cfg)
+ instance_id = ""
set_heartbeat_config_repository(
create_heartbeat_config_repository(store, instance_id=instance_id)
)
@@ -240,7 +236,7 @@ def _wire_config_and_cron_repositories(
from jiuwenswarm.gateway.cron.job_access import set_cron_persistent_store
from jiuwenswarm.gateway.storage.access import set_persistent_store
- instance_id = resolve_storage_instance_id(cfg)
+ instance_id = ""
set_channel_config_repository(
create_channel_config_repository(store, instance_id=instance_id)
)
@@ -334,7 +330,7 @@ async def setup_gateway_storage_repositories(
set_enterprise_record_repositories(
create_enterprise_record_repositories(
store,
- instance_id=resolve_storage_instance_id(cfg),
+ instance_id="",
)
)
@@ -420,7 +416,7 @@ async def wire_enterprise_manager_ws_store_async(
set_enterprise_record_repositories(
create_enterprise_record_repositories(
store,
- instance_id=resolve_storage_instance_id(cfg),
+ instance_id="",
)
)
if get_persistent_store() is None:
diff --git a/jiuwenswarm/infrastructure/log_masking/engine.py b/jiuwenswarm/infrastructure/log_masking/engine.py
index 6a6c167138..88df77fae4 100644
--- a/jiuwenswarm/infrastructure/log_masking/engine.py
+++ b/jiuwenswarm/infrastructure/log_masking/engine.py
@@ -269,7 +269,7 @@ class LogMaskingEngine:
"""从 Gateway 库加载 enabled 规则并刷新**本进程**单例引擎。
单机版(``JIUWENSWARM_EDITION`` 非企业版)不访问 GDB,直接使用内置规则。
- 企业版在 ``JIUWENCLAW_ID`` / ``JIUWENSWARM_ID`` 未就绪时保留内置规则。
+ 企业版直接读本网关 DB(每网关独立库,不依赖实例 id 绑定)。
读库走本地 ``enterprise_config.gateway_db``,不依赖 ``packages/jiuwenclaw-ee``。
``db_authoritative``:
@@ -281,29 +281,20 @@ class LogMaskingEngine:
if not enterprise:
cls.reload_from_rows([])
else:
- jid = (
- os.getenv("JIUWENCLAW_ID", "").strip()
- or os.getenv("JIUWENSWARM_ID", "").strip()
- )
- if not jid:
- _logger.debug(
- "[log_masking_db] skip GDB load: JIUWENCLAW_ID/JIUWENSWARM_ID not set yet"
+ try:
+ rows = await cls.list_enabled_log_masking_rule_rows()
+ authoritative = (
+ db_authoritative
+ if db_authoritative is not None
+ else bool(rows)
+ )
+ cls.reload_from_rows(rows, db_authoritative=authoritative)
+ except Exception as exc: # noqa: BLE001
+ _logger.warning(
+ "[log_masking_db] log_masking_rule read failed: %s",
+ exc,
+ exc_info=True,
)
- else:
- try:
- rows = await cls.list_enabled_log_masking_rule_rows()
- authoritative = (
- db_authoritative
- if db_authoritative is not None
- else bool(rows)
- )
- cls.reload_from_rows(rows, db_authoritative=authoritative)
- except Exception as exc: # noqa: BLE001
- _logger.warning(
- "[log_masking_db] log_masking_rule read failed: %s",
- exc,
- exc_info=True,
- )
from .probes import maybe_emit_log_masking_probe_samples
@@ -317,22 +308,13 @@ class LogMaskingEngine:
cls,
*,
table_name: str = _LOG_MASKING_RULE_TABLE,
- jiuwenclaw_id: str | None = None,
) -> list[dict[str, Any]]:
"""返回 ``enabled=true`` 的规则行(priority DESC)。"""
from jiuwenswarm.server.runtime.enterprise_config import gateway_db
- jid = (
- jiuwenclaw_id
- or gateway_db.resolve_jiuwenclaw_id()
- or os.getenv("JIUWENCLAW_ID", "").strip()
- or os.getenv("JIUWENSWARM_ID", "").strip()
- )
- if not jid:
- return []
rows = await gateway_db.list_records(
table_name,
- filters={"enabled": True, "jiuwenclaw_id": jid},
+ filters={"enabled": True},
order_by="priority DESC",
)
result: list[dict[str, Any]] = []
@@ -355,7 +337,6 @@ class LogMaskingEngine:
enabled = bool(enabled)
return {
"id": obj.get("id"),
- "jiuwenclaw_id": obj.get("jiuwenclaw_id"),
"rule_id": obj.get("rule_id"),
"rule_name": obj.get("rule_name"),
"description": obj.get("description"),
@@ -372,7 +353,6 @@ class LogMaskingEngine:
updated_at = getattr(obj, "updated_at", None)
return {
"id": getattr(obj, "id", None),
- "jiuwenclaw_id": getattr(obj, "jiuwenclaw_id", None),
"rule_id": getattr(obj, "rule_id", None),
"rule_name": getattr(obj, "rule_name", None),
"description": getattr(obj, "description", None),
diff --git a/jiuwenswarm/server/runtime/enterprise_config/gateway_db.py b/jiuwenswarm/server/runtime/enterprise_config/gateway_db.py
index cb921d5418..904e1e9473 100644
--- a/jiuwenswarm/server/runtime/enterprise_config/gateway_db.py
+++ b/jiuwenswarm/server/runtime/enterprise_config/gateway_db.py
@@ -2,7 +2,7 @@
"""Gateway 本地库:企业配置读库 facade(``GATEWAY_*``,不依赖 jiuwenclaw-ee)。
IO 实现见 ``gateway/storage/backends/db/reader``(与 Gateway 写库同环境变量)。
-本模块负责实例隔离(``jiuwenclaw_id``)与模板槽位等业务封装。
+每网关独立数据库,查询不加实例行级隔离。
"""
from __future__ import annotations
@@ -10,18 +10,10 @@ from __future__ import annotations
from typing import Any
from jiuwenswarm.common.utils import logger
-from jiuwenswarm.gateway.config.enterprise.instance_scope import (
- apply_instance_scope as _apply_instance_scope,
- instance_scoped_store_names,
- list_records_requires_bound_instance,
- resolve_gateway_instance_id,
-)
from jiuwenswarm.gateway.storage.backends.db import reader as _db_reader
from .schemas import SLOT_ENTITY_TABLE, TemplateRefSlot
-# 与 catalog + cron_job 对齐;供测试与文档引用
-INSTANCE_SCOPED_TABLES = instance_scoped_store_names()
PERMISSIONS_CONFIG_TABLE = _db_reader.PERMISSIONS_CONFIG_TABLE
resolve_gateway_db_path = _db_reader.resolve_gateway_db_path
@@ -33,34 +25,13 @@ _list_records_remote = _db_reader.list_records_remote
_list_records_sqlite = _db_reader.list_records_sqlite
-def resolve_jiuwenclaw_id() -> str | None:
- """当前实例 id(``resolve_gateway_instance_id`` 别名,供 AgentServer 调用方)。"""
- return resolve_gateway_instance_id()
-
-
-def apply_instance_scope(table: str, filters: dict[str, Any]) -> dict[str, Any]:
- """为 scoped 表查询附加 ``jiuwenclaw_id``(供读库与测试复用)。"""
- return _apply_instance_scope(
- table,
- filters,
- instance_id=resolve_gateway_instance_id(),
- )
-
-
async def upsert_permissions_config(
body: dict[str, Any],
*,
source: str = "runtime_persist",
) -> None:
- """按 ``jiuwenclaw_id`` upsert ``permissions_config``(远程或本地 sqlite)。"""
- jid = resolve_jiuwenclaw_id()
- if not jid:
- raise ValueError("JIUWENCLAW_ID is required for enterprise permissions persist")
- await _db_reader.upsert_permissions_config(
- body,
- jiuwenclaw_id=jid,
- source=source,
- )
+ """单例行 upsert ``permissions_config``(远程或本地 sqlite)。"""
+ await _db_reader.upsert_permissions_config(body, source=source)
async def fetch_template_by_slot(
@@ -90,7 +61,7 @@ async def list_records(
filters: dict[str, Any] | None = None,
order_by: str = "",
) -> list[dict[str, Any]]:
- """列表查询;scoped 表自动按 ``jiuwenclaw_id`` 隔离。
+ """列表查询(每网关独立 DB,不加实例隔离列)。
``is_enterprise()`` + ``GATEWAY_DB_HOST`` 时走远程 MySQL/PG;否则走本地 sqlite。
"""
@@ -98,29 +69,18 @@ async def list_records(
logger.warning("[enterprise_config] invalid table name: %r", table)
return []
- instance_id = resolve_gateway_instance_id()
- if list_records_requires_bound_instance(table, instance_id):
- logger.warning(
- "[enterprise_config] list_records skipped: jiuwenclaw_id not bound for table=%s",
- table,
- )
- return []
-
- query = apply_instance_scope(table, dict(filters or {}))
+ query = dict(filters or {})
if use_remote_gateway_db():
return await _list_records_remote(table, query, order_by)
return await _list_records_sqlite(table, query, order_by)
__all__ = (
- "INSTANCE_SCOPED_TABLES",
"PERMISSIONS_CONFIG_TABLE",
- "apply_instance_scope",
"fetch_template_by_slot",
"is_gateway_db_available",
"list_records",
"resolve_gateway_db_path",
- "resolve_jiuwenclaw_id",
"upsert_permissions_config",
"use_remote_gateway_db",
)
diff --git a/jiuwenswarm/server/runtime/enterprise_config/loader.py b/jiuwenswarm/server/runtime/enterprise_config/loader.py
index 6dad3eb807..4cc149830c 100644
--- a/jiuwenswarm/server/runtime/enterprise_config/loader.py
+++ b/jiuwenswarm/server/runtime/enterprise_config/loader.py
@@ -238,7 +238,6 @@ async def load_effective_enterprise_config(
agent_template=agent_template_row,
instance_agent_resource=resource_row,
debug={
- "jiuwenclaw_id": gateway_db.resolve_jiuwenclaw_id(),
"group_id": ctx.group_id,
"bot_id": ctx.bot_id,
"user_id": ctx.user_id,
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/log_masking_rule.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/log_masking_rule.py
index 6fd6f5ae09..22220f1d69 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/log_masking_rule.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/log_masking_rule.py
@@ -11,7 +11,7 @@ from jiuwenswarm.gateway.config.enterprise.repository import EnterpriseRecordRep
from jiuwenswarm.gateway.config.enterprise.tables.application_config_models import LOG_MASKING_RULE_TABLE_DEF
from jiuwenswarm.infrastructure.log_masking.engine import LogMaskingEngine
from ...infrastructure.repository_access import require_enterprise_repository
-from ...infrastructure.utils import assert_jiuwenclaw_id_matches, format_ts, utc_now
+from ...infrastructure.utils import format_ts, utc_now
from ...schemas.application_config_schemas import (
LogMaskingRuleCreateRequest,
LogMaskingRuleUpdateRequest,
@@ -24,7 +24,6 @@ logger = logging.getLogger(__name__)
def _rule_row_to_dict(row: dict[str, Any]) -> dict[str, Any]:
return {
"id": row.get("id"),
- "jiuwenclaw_id": row.get("jiuwenclaw_id"),
"rule_id": row.get("rule_id"),
"rule_name": row.get("rule_name"),
"description": row.get("description"),
@@ -42,8 +41,6 @@ def _rule_row_to_dict(row: dict[str, Any]) -> dict[str, Any]:
async def _create_log_masking_rule_record(
repo: EnterpriseRecordRepository,
request: LogMaskingRuleCreateRequest,
- *,
- jiuwenclaw_id: str,
) -> dict[str, Any]:
from jiuwenswarm.infrastructure.log_masking.engine import (
normalize_replacement,
@@ -60,7 +57,6 @@ async def _create_log_masking_rule_record(
source = normalize_source(request.source)
now = utc_now()
row_data: dict[str, Any] = {
- "jiuwenclaw_id": jiuwenclaw_id,
"rule_id": rule_id,
"rule_name": request.rule_name,
"description": request.description,
@@ -85,8 +81,6 @@ async def _update_log_masking_rule_record(
repo: EnterpriseRecordRepository,
rule_id: str,
request: LogMaskingRuleUpdateRequest,
- *,
- jiuwenclaw_id: str,
) -> dict[str, Any] | None:
from jiuwenswarm.infrastructure.log_masking.engine import (
normalize_replacement,
@@ -95,7 +89,6 @@ async def _update_log_masking_rule_record(
validate_pattern,
)
- _ = jiuwenclaw_id
rid = normalize_rule_id(rule_id)
existing = await repo.get(rule_id=rid)
if existing is None:
@@ -128,12 +121,9 @@ async def _update_log_masking_rule_record(
async def _delete_log_masking_rule_record(
repo: EnterpriseRecordRepository,
rule_id: str,
- *,
- jiuwenclaw_id: str,
) -> bool:
from jiuwenswarm.infrastructure.log_masking.engine import normalize_rule_id
- _ = jiuwenclaw_id
rid = normalize_rule_id(rule_id)
return await repo.delete(rule_id=rid)
@@ -142,16 +132,13 @@ class LogMaskingRuleService:
async def create(
self,
- jiuwenclaw_id: str,
rule: dict[str, Any],
) -> dict[str, Any]:
if not isinstance(rule, dict):
raise ValueError("log_masking_rule.create requires rule object")
req = LogMaskingRuleCreateRequest.model_validate(rule)
- jid = str(req.jiuwenclaw_id or jiuwenclaw_id).strip()
- assert_jiuwenclaw_id_matches(jid)
repo = require_enterprise_repository(_TABLE)
- row = await _create_log_masking_rule_record(repo, req, jiuwenclaw_id=jid)
+ row = await _create_log_masking_rule_record(repo, req)
await LogMaskingEngine.reload_log_masking_rule(db_authoritative=True)
result = {"rule_id": row["rule_id"]}
logger.info(
@@ -162,7 +149,6 @@ class LogMaskingRuleService:
async def update(
self,
- jiuwenclaw_id: str,
rule_id: str,
updates: dict[str, Any],
) -> dict[str, Any]:
@@ -173,9 +159,7 @@ class LogMaskingRuleService:
raise ValueError("log_masking_rule.update requires non-empty updates")
req = LogMaskingRuleUpdateRequest.model_validate(updates)
repo = require_enterprise_repository(_TABLE)
- row = await _update_log_masking_rule_record(
- repo, rid, req, jiuwenclaw_id=jiuwenclaw_id
- )
+ row = await _update_log_masking_rule_record(repo, rid, req)
if row is None:
raise ValueError(f"log masking rule id={rid!r} not found")
await LogMaskingEngine.reload_log_masking_rule(db_authoritative=True)
@@ -186,14 +170,12 @@ class LogMaskingRuleService:
)
return result
- async def delete(self, jiuwenclaw_id: str, rule_id: str) -> None:
+ async def delete(self, rule_id: str) -> None:
rid = str(rule_id or "").strip()
if not rid:
raise ValueError("log_masking_rule.delete requires rule_id")
repo = require_enterprise_repository(_TABLE)
- deleted = await _delete_log_masking_rule_record(
- repo, rid, jiuwenclaw_id=jiuwenclaw_id
- )
+ deleted = await _delete_log_masking_rule_record(repo, rid)
if not deleted:
raise ValueError(f"log masking rule id={rid!r} not found")
await LogMaskingEngine.reload_log_masking_rule(db_authoritative=True)
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/logging_config.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/logging_config.py
index 6f8daf69b5..39a824a490 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/logging_config.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/logging_config.py
@@ -32,7 +32,6 @@ class LoggingConfigService:
async def upsert(
self,
- jiuwenclaw_id: str,
*,
level: str = "INFO",
console_level: str | None = None,
@@ -42,7 +41,6 @@ class LoggingConfigService:
full: str | None = None,
**_extra: Any,
) -> dict[str, Any] | None:
- _ = jiuwenclaw_id
repo = require_logging_repository()
fields = {
"level": level,
@@ -63,12 +61,8 @@ class LoggingConfigService:
_apply_log_levels(fields)
return result
- async def delete(self, jiuwenclaw_id: str) -> None:
- _ = jiuwenclaw_id
+ async def delete(self) -> None:
repo = require_logging_repository()
await repo.delete()
apply_logging_config_payload({"op": "delete"})
- logger.info(
- "[ManagerConfigReceiver] logging_config deleted jiuwenclaw_id=%s",
- jiuwenclaw_id,
- )
+ logger.info("[ManagerConfigReceiver] logging_config deleted")
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/memory_config.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/memory_config.py
index 1067ee4be5..35952c3f8f 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/memory_config.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/memory_config.py
@@ -42,13 +42,11 @@ class MemoryConfigService:
async def upsert(
self,
- jiuwenclaw_id: str,
*,
body: dict[str, Any] | None = None,
source: str = "manager",
**_extra: Any,
) -> dict[str, Any] | None:
- _ = jiuwenclaw_id
if body is None and isinstance(_extra.get("body"), dict):
body = _extra["body"]
if body is None:
@@ -71,12 +69,8 @@ class MemoryConfigService:
)
return result
- async def delete(self, jiuwenclaw_id: str) -> None:
- _ = jiuwenclaw_id
+ async def delete(self) -> None:
repo = require_memory_repository()
await repo.delete()
_apply_memory(None, op="delete")
- logger.info(
- "[ManagerConfigReceiver] memory_config deleted jiuwenclaw_id=%s",
- jiuwenclaw_id,
- )
+ logger.info("[ManagerConfigReceiver] memory_config deleted")
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/permissions_config.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/permissions_config.py
index a190f44fcb..d3bd5fece6 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/permissions_config.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/permissions_config.py
@@ -36,13 +36,11 @@ class PermissionsConfigService:
async def upsert(
self,
- jiuwenclaw_id: str,
*,
body: dict[str, Any] | None = None,
source: str = "manager",
**_extra: Any,
) -> dict[str, Any] | None:
- _ = jiuwenclaw_id
if body is None and isinstance(_extra.get("body"), dict):
body = _extra["body"]
if body is None:
@@ -65,8 +63,7 @@ class PermissionsConfigService:
)
return result
- async def delete(self, jiuwenclaw_id: str) -> None:
- _ = jiuwenclaw_id
+ async def delete(self) -> None:
repo = require_permissions_repository()
await repo.delete()
_apply_permissions(None, op="delete")
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/task_memory_config.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/task_memory_config.py
index 428bdd3def..eebde1d958 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/task_memory_config.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/application_config/task_memory_config.py
@@ -18,7 +18,6 @@ logger = logging.getLogger(__name__)
def _row_to_dict(row: dict[str, Any]) -> dict[str, Any]:
return {
"id": row.get("id"),
- "jiuwenclaw_id": row.get("jiuwenclaw_id"),
"enabled": row.get("enabled", False),
"llm_model": row.get("llm_model", ""),
"embedding_model": row.get("embedding_model", ""),
@@ -77,11 +76,9 @@ class TaskMemoryConfigService:
async def upsert(
self,
- jiuwenclaw_id: str,
request: dict[str, Any] | None = None,
**fields: Any,
) -> dict[str, Any] | None:
- _ = jiuwenclaw_id
payload = dict(request or {})
payload.update({k: v for k, v in fields.items() if v is not None or k in fields})
# HTTP body 可能直接摊平字段,也可能嵌套 task_memory
@@ -89,11 +86,7 @@ class TaskMemoryConfigService:
payload = dict(payload["task_memory"])
return await _upsert_task_memory_config_record(payload)
- async def delete(self, jiuwenclaw_id: str) -> None:
- _ = jiuwenclaw_id
+ async def delete(self) -> None:
repo = require_enterprise_repository(_TABLE)
await repo.delete()
- logger.info(
- "[ManagerConfigReceiver] task_memory_config deleted jiuwenclaw_id=%s",
- jiuwenclaw_id,
- )
+ logger.info("[ManagerConfigReceiver] task_memory_config deleted")
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/gateway_db.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/gateway_db.py
index 87a6769674..91f7f6f2d7 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/gateway_db.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/enterprise_config/gateway_db.py
@@ -1,6 +1,9 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved
-"""Gateway 本地库:企业配置读库(继承 ``Database``,进程内单例 + ``jiuwenclaw_id`` 隔离)。"""
+"""Gateway 本地库:企业配置读库(继承 ``Database``,进程内单例)。
+
+每网关独立数据库,列表查询不再做实例行级隔离。
+"""
from __future__ import annotations
@@ -11,11 +14,6 @@ from typing import Any, ClassVar
from openjiuwen_runtime.foundation.log import get_logger
-from jiuwenswarm.gateway.config.enterprise.instance_scope import (
- apply_instance_scope as _apply_instance_scope,
- list_records_requires_bound_instance,
-)
-
from ...infrastructure.config import Settings
from ...infrastructure.db import Database
from ...infrastructure.utils import format_ts
@@ -27,13 +25,12 @@ _DEFAULT_RELATIVE_ROOT = Path(__file__).resolve().parents[2]
class GatewayDb(Database):
- """Gateway 企业配置读库;进程内仅一个实例持有连接池,``bind`` 只切换 ``jiuwenclaw_id``。"""
+ """Gateway 企业配置读库;进程内仅一个实例持有连接池。"""
_current: ClassVar[GatewayDb | None] = None
def __init__(
self,
- jiuwenclaw_id: str | None,
*,
cfg: Settings | None = None,
relative_root: Path | None = None,
@@ -41,41 +38,17 @@ class GatewayDb(Database):
) -> None:
if _with_connection:
super().__init__(cfg=cfg, relative_root=relative_root or _DEFAULT_RELATIVE_ROOT)
- self._jiuwenclaw_id = self._normalize_jiuwenclaw_id(jiuwenclaw_id)
-
- @staticmethod
- def _normalize_jiuwenclaw_id(jiuwenclaw_id: str | None) -> str | None:
- if jiuwenclaw_id is None:
- return None
- normalized = str(jiuwenclaw_id).strip()
- return normalized or None
@classmethod
def _ensure_singleton(cls) -> GatewayDb:
if cls._current is None:
- cls._current = cls(None, _with_connection=True)
+ cls._current = cls(_with_connection=True)
return cls._current
- @property
- def jiuwenclaw_id(self) -> str | None:
- return self._jiuwenclaw_id
-
- def set_jiuwenclaw_id(self, jiuwenclaw_id: str | None) -> None:
- """更新实例隔离 ID(不新建连接池)。"""
- normalized = self._normalize_jiuwenclaw_id(jiuwenclaw_id)
- if self._jiuwenclaw_id != normalized:
- self._jiuwenclaw_id = normalized
-
- def clear_jiuwenclaw_id(self) -> None:
- """清空实例隔离 ID。"""
- self._jiuwenclaw_id = None
-
@classmethod
- def bind(cls, jiuwenclaw_id: str | None) -> GatewayDb:
- """设置当前进程 ``jiuwenclaw_id``(不新建连接池)。"""
- db = cls._ensure_singleton()
- db.set_jiuwenclaw_id(jiuwenclaw_id)
- return db
+ def bind(cls, *_args: Any, **_kwargs: Any) -> GatewayDb:
+ """兼容旧调用:返回进程内单例(忽略历史实例 id 参数)。"""
+ return cls._ensure_singleton()
@classmethod
def current(cls) -> GatewayDb:
@@ -83,18 +56,10 @@ class GatewayDb(Database):
@classmethod
async def release(cls) -> None:
- """断连/注销时释放连接池,并清空 ``jiuwenclaw_id``。"""
+ """断连/注销时释放连接池。"""
if cls._current is not None:
await cls._current.close()
- cls._current.clear_jiuwenclaw_id()
-
- def apply_instance_scope(self, table: str, filters: dict[str, Any]) -> dict[str, Any]:
- """为 scoped 表查询附加 ``jiuwenclaw_id`` 隔离条件。"""
- return _apply_instance_scope(
- table,
- filters,
- instance_id=self._jiuwenclaw_id,
- )
+ cls._current = None
async def fetch_template_by_slot(
self,
@@ -124,15 +89,8 @@ class GatewayDb(Database):
filters: dict[str, Any] | None = None,
order_by: str | list[tuple[str, bool]] = "",
) -> list[dict[str, Any]]:
- """列表查询;策略/映射表自动按 ``jiuwenclaw_id`` 隔离。"""
- if list_records_requires_bound_instance(table, self._jiuwenclaw_id):
- logger.warning(
- "[enterprise_config] list_records skipped: jiuwenclaw_id not bound for table=%s",
- table,
- )
- return []
-
- query = self.apply_instance_scope(table, dict(filters or {}))
+ """列表查询(每网关独立 DB,不加实例隔离列)。"""
+ query = dict(filters or {})
try:
handler = await self.ensure_ready(log_prefix="enterprise_config")
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/__init__.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/__init__.py
index 3049f7cf77..dd7de30435 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/__init__.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/__init__.py
@@ -1,7 +1,7 @@
from .instance_data_lifecycle import (
INSTANCE_PURGE_TABLES,
InstanceDataLifecycleService,
- purge_jiuwenclaw_instance_data_on_handler,
+ purge_gateway_instance_data,
)
from .instance_service import (
InstanceService,
@@ -13,7 +13,7 @@ __all__ = (
"INSTANCE_PURGE_TABLES",
"InstanceDataLifecycleService",
"InstanceService",
- "purge_jiuwenclaw_instance_data_on_handler",
+ "purge_gateway_instance_data",
"resolve_manager_http_base",
"resolve_public_endpoint",
)
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.py
index dba5feaef2..5232d24dff 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
@@ -1,6 +1,6 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2026-2026. All rights reserved
-"""Gateway 实例生命周期:响应 Manager purge 指令并清理 GDB 实例级数据。"""
+"""Gateway 实例生命周期:响应 Manager purge 指令并清理本机库全部实例数据。"""
from __future__ import annotations
@@ -88,14 +88,14 @@ async def _purge_channel_config() -> int:
return deleted
-async def purge_jiuwenclaw_instance_data_on_handler(
- jiuwenclaw_id: str,
-) -> dict[str, int]:
- """删除 Gateway 本地库中指定 ``jiuwenclaw_id`` 的全部实例数据(幂等)。"""
- jid = str(jiuwenclaw_id or "").strip()
- if not jid:
- return {}
+async def purge_gateway_instance_data() -> dict[str, int]:
+ """清空本 Gateway 本地库中的全部实例级数据(幂等)。
+ 前提:每网关独立数据库,无跨实例行级隔离。此操作不可逆,将删除本库内
+ 模板 / 资源 / 应用配置 / channel / cron / Manager 公钥等实例数据,
+ 而非按 ``jiuwenclaw_id`` 过滤单实例。若未来改为多实例共享同一库,
+ 需重新引入按实例范围清理,否则会误删其它实例数据。
+ """
deleted_counts: dict[str, int] = {}
for table in _ENTERPRISE_PURGE_TABLES:
@@ -124,8 +124,7 @@ async def purge_jiuwenclaw_instance_data_on_handler(
deleted_counts[_MANAGER_SIGN_PUBKEY_TABLE] = 1
logger.info(
- "[instance_data_lifecycle] purged gateway instance data jiuwenclaw_id=%s counts=%s",
- jid,
+ "[instance_data_lifecycle] purged gateway instance data counts=%s",
deleted_counts,
)
return deleted_counts
@@ -133,11 +132,10 @@ async def purge_jiuwenclaw_instance_data_on_handler(
class InstanceDataLifecycleService:
- async def purge(self, jiuwenclaw_id: str) -> dict[str, Any]:
- counts = await purge_jiuwenclaw_instance_data_on_handler(jiuwenclaw_id)
+ async def purge(self) -> dict[str, Any]:
+ counts = await purge_gateway_instance_data()
logger.info(
- "[ManagerConfigReceiver] instance_data_lifecycle purge jiuwenclaw_id=%s counts=%s",
- jiuwenclaw_id,
+ "[ManagerConfigReceiver] instance_data_lifecycle purge counts=%s",
counts,
)
return {"purged": counts}
@@ -146,5 +144,5 @@ class InstanceDataLifecycleService:
__all__ = (
"INSTANCE_PURGE_TABLES",
"InstanceDataLifecycleService",
- "purge_jiuwenclaw_instance_data_on_handler",
+ "purge_gateway_instance_data",
)
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_service.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_service.py
index ed4818d752..47db42faab 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_service.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance/instance_service.py
@@ -1,17 +1,14 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-"""Gateway 实例身份绑定(无主动心跳)。
+"""Gateway 实例启动辅助(无主动心跳)。
-``JIUWENCLAW_ID`` 优先取自 env;未设置时启动时自动生成 UUID。
存活由 Manager 周期探活本机 ``/api/health`` 确认。
"""
from __future__ import annotations
import logging
-import os
from ...infrastructure.config import Settings, get_settings
-from ...infrastructure.utils import get_jiuwenclaw_id
logger = logging.getLogger(__name__)
@@ -34,30 +31,21 @@ def resolve_manager_http_base(cfg: Settings | None = None) -> str:
class InstanceService:
- """绑定 ``JIUWENCLAW_ID`` / GatewayDb;不再向 Manager 主动心跳。"""
+ """启动时确保 GatewayDb 连接可用。"""
def __init__(self, cfg: Settings | None = None) -> None:
self._cfg = cfg or get_settings()
async def start(self) -> None:
- from_env = bool(os.getenv("JIUWENCLAW_ID", "").strip())
- jid = get_jiuwenclaw_id()
- if not from_env:
- logger.info(
- "[InstanceService] JIUWENCLAW_ID unset; generated jiuwenclaw_id=%s",
- jid,
- )
try:
from ..enterprise_config.gateway_db import GatewayDb
- GatewayDb.bind(jid)
+ GatewayDb.current()
except Exception: # noqa: BLE001
- logger.debug("[InstanceService] GatewayDb.bind failed", exc_info=True)
+ logger.debug("[InstanceService] GatewayDb.current failed", exc_info=True)
return
logger.info(
- "[InstanceService] bound jiuwenclaw_id=%s endpoint=%s "
- "(Manager health-probes this Gateway)",
- jid,
+ "[InstanceService] endpoint=%s (Manager health-probes this Gateway)",
resolve_public_endpoint(self._cfg),
)
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance_resource/instance_agent_resource.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance_resource/instance_agent_resource.py
index adf0f16802..717f298000 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance_resource/instance_agent_resource.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/instance_resource/instance_agent_resource.py
@@ -37,12 +37,10 @@ async def _get_row_for_resource(
def _build_row_from_resource(
resource: dict[str, Any],
*,
- jiuwenclaw_id: str,
now: Any,
) -> dict[str, Any]:
req = InstanceAgentResourceUpsertRequest.model_validate(resource)
return {
- "jiuwenclaw_id": jiuwenclaw_id,
"resource_id": _normalize_resource_id(req.resource_id),
"resource_name": req.resource_name.strip(),
"resource_desc": req.resource_desc,
@@ -60,13 +58,11 @@ def _build_row_from_resource(
async def _upsert_instance_agent_resource(
repo: EnterpriseRecordRepository,
resource: dict[str, Any],
- *,
- jiuwenclaw_id: str,
) -> None:
now = utc_now()
rid = _normalize_resource_id(resource.get("resource_id"))
existing = await _get_row_for_resource(repo, rid)
- row_data = _build_row_from_resource(resource, jiuwenclaw_id=jiuwenclaw_id, now=now)
+ row_data = _build_row_from_resource(resource, now=now)
if existing is None:
await repo.create(row_data)
return
@@ -77,7 +73,7 @@ async def _upsert_instance_agent_resource(
updates = {
key: value
for key, value in row_data.items()
- if key not in ("jiuwenclaw_id", "resource_id")
+ if key not in ("resource_id",)
}
updates["updated_at"] = utc_now()
await repo.update({"resource_id": rid}, updates)
@@ -98,15 +94,12 @@ class InstanceAgentResourceService:
async def upsert(
self,
- jiuwenclaw_id: str,
resource: dict[str, Any],
) -> dict[str, Any]:
if not isinstance(resource, dict):
raise ValueError("instance_agent_resources.upsert requires resource object")
repo = require_enterprise_repository(_TABLE)
- await _upsert_instance_agent_resource(
- repo, resource, jiuwenclaw_id=jiuwenclaw_id
- )
+ await _upsert_instance_agent_resource(repo, resource)
result = {"resource_id": _normalize_resource_id(resource.get("resource_id"))}
logger.info(
"[ManagerConfigReceiver] instance_agent_resources upsert resource_id=%s",
@@ -114,7 +107,7 @@ class InstanceAgentResourceService:
)
return result
- async def delete(self, jiuwenclaw_id: str, resource_id: str) -> None:
+ async def delete(self, resource_id: str) -> None:
if resource_id is None:
raise ValueError("instance_agent_resources.delete requires resource_id")
rid = _normalize_resource_id(resource_id)
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/agent_template.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/agent_template.py
index 7470133164..f084bfca79 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/agent_template.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/agent_template.py
@@ -9,6 +9,7 @@ from typing import Any
from jiuwenswarm.gateway.config.enterprise.repository import EnterpriseRecordRepository
from jiuwenswarm.gateway.config.enterprise.tables.template_models import AGENT_TEMPLATE_TABLE_DEF
+
from ...infrastructure.repository_access import require_enterprise_repository
from ...infrastructure.utils import (
normalize_template_ref,
@@ -40,12 +41,10 @@ async def _get_row_for_instance(
def _build_row_from_template(
template: dict[str, Any],
*,
- jiuwenclaw_id: str,
now: Any,
) -> dict[str, Any]:
template_uuid = _normalize_template_id(template.get("template_id"))
return {
- "jiuwenclaw_id": jiuwenclaw_id,
"template_id": template_uuid,
"template_name": str(template["template_name"]).strip(),
"description": template.get("description"),
@@ -60,14 +59,12 @@ def _build_row_from_template(
async def _upsert_agent_template_from_sync(
repo: EnterpriseRecordRepository,
- template: dict[str, Any],
- *,
- jiuwenclaw_id: str,
+ template: dict[str, Any]
) -> None:
now = utc_now()
tid = _normalize_template_id(template.get("template_id"))
existing = await _get_row_for_instance(repo, tid)
- row_data = _build_row_from_template(template, jiuwenclaw_id=jiuwenclaw_id, now=now)
+ row_data = _build_row_from_template(template, now=now)
if existing is None:
await repo.create(row_data)
return
@@ -78,7 +75,7 @@ async def _upsert_agent_template_from_sync(
updates = {
key: value
for key, value in row_data.items()
- if key not in ("jiuwenclaw_id", "template_id")
+ if key not in ("template_id",)
}
updates["updated_at"] = utc_now()
await repo.update({"template_id": tid}, updates)
@@ -126,14 +123,13 @@ class AgentTemplateService:
async def create(
self,
- jiuwenclaw_id: str,
template: dict[str, Any],
) -> dict[str, Any]:
if not isinstance(template, dict):
raise ValueError("agent_templates.create requires template object")
repo = require_enterprise_repository(_TABLE)
await _upsert_agent_template_from_sync(
- repo, template, jiuwenclaw_id=jiuwenclaw_id
+ repo, template
)
result = {"template_id": _normalize_template_id(template.get("template_id"))}
logger.info(
@@ -144,7 +140,6 @@ class AgentTemplateService:
async def update(
self,
- jiuwenclaw_id: str,
template_id: str,
updates: dict[str, Any],
) -> None:
@@ -163,7 +158,7 @@ class AgentTemplateService:
tid,
)
- async def delete(self, jiuwenclaw_id: str, template_id: str) -> None:
+ async def delete(self, template_id: str) -> None:
if template_id is None:
raise ValueError("agent_templates.delete requires template_id")
tid = _normalize_template_id(template_id)
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/embedding_template.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/embedding_template.py
index 0c767fc60c..efea123c2c 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/embedding_template.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/embedding_template.py
@@ -9,6 +9,7 @@ from typing import Any
from jiuwenswarm.gateway.config.enterprise.repository import EnterpriseRecordRepository
from jiuwenswarm.gateway.config.enterprise.tables.template_models import EMBEDDING_TEMPLATE_TABLE_DEF
+
from ...infrastructure.repository_access import require_enterprise_repository
from ...infrastructure.utils import parse_iso_datetime, utc_now
from ...schemas.template_schemas import EmbeddingTemplateUpdateRequest
@@ -73,7 +74,6 @@ async def delete_embedding_template(
def _build_row_from_template(
template: dict[str, Any],
*,
- jiuwenclaw_id: str,
now: Any,
) -> dict[str, Any]:
template_uuid = _normalize_template_id(template.get("template_id"))
@@ -81,7 +81,6 @@ def _build_row_from_template(
template["template_name"] if "template_name" in template else template["name"]
)
return {
- "jiuwenclaw_id": jiuwenclaw_id,
"template_id": template_uuid,
"template_name": str(template_name).strip(),
"description": template.get("description"),
@@ -101,15 +100,13 @@ def _build_row_from_template(
async def _upsert_embedding_template_from_sync(
repo: EnterpriseRecordRepository,
- template: dict[str, Any],
- *,
- jiuwenclaw_id: str,
+ template: dict[str, Any]
) -> None:
now = utc_now()
tid = _normalize_template_id(template.get("template_id"))
existing = await _get_row_for_instance(repo, tid)
row_data = _build_row_from_template(
- template, jiuwenclaw_id=jiuwenclaw_id, now=now
+ template, now=now
)
if existing is None:
await repo.create(row_data)
@@ -121,7 +118,7 @@ async def _upsert_embedding_template_from_sync(
updates = {
key: value
for key, value in row_data.items()
- if key not in ("jiuwenclaw_id", "template_id")
+ if key not in ("template_id",)
}
updates["updated_at"] = utc_now()
await repo.update({"template_id": tid}, updates)
@@ -129,9 +126,7 @@ async def _upsert_embedding_template_from_sync(
async def _sync_embedding_templates_records(
repo: EnterpriseRecordRepository,
- templates: list[dict[str, Any]],
- *,
- jiuwenclaw_id: str,
+ templates: list[dict[str, Any]]
) -> dict[str, Any]:
incoming_ids: set[str] = set()
synced = 0
@@ -141,7 +136,7 @@ async def _sync_embedding_templates_records(
tid = _normalize_template_id(item.get("template_id"))
incoming_ids.add(tid)
await _upsert_embedding_template_from_sync(
- repo, item, jiuwenclaw_id=jiuwenclaw_id
+ repo, item
)
synced += 1
@@ -158,14 +153,13 @@ class EmbeddingTemplateService:
async def create(
self,
- jiuwenclaw_id: str,
template: dict[str, Any],
) -> dict[str, Any]:
if not isinstance(template, dict):
raise ValueError("embedding_templates.create requires template object")
repo = require_enterprise_repository(_TABLE)
await _upsert_embedding_template_from_sync(
- repo, template, jiuwenclaw_id=jiuwenclaw_id
+ repo, template
)
result = {
"template_id": _normalize_template_id(template.get("template_id")),
@@ -178,7 +172,6 @@ class EmbeddingTemplateService:
async def update(
self,
- jiuwenclaw_id: str,
template_id: str,
updates: dict[str, Any],
) -> None:
@@ -197,7 +190,7 @@ class EmbeddingTemplateService:
tid,
)
- async def delete(self, jiuwenclaw_id: str, template_id: str) -> None:
+ async def delete(self, template_id: str) -> None:
if template_id is None:
raise ValueError("embedding_templates.delete requires template_id")
tid = _normalize_template_id(template_id)
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/extension_config_template.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/extension_config_template.py
index 532618938c..b37715bfee 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/extension_config_template.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/extension_config_template.py
@@ -9,6 +9,7 @@ from typing import Any
from jiuwenswarm.gateway.config.enterprise.repository import EnterpriseRecordRepository
from jiuwenswarm.gateway.config.enterprise.tables.template_models import EXTENSION_CONFIG_TEMPLATE_TABLE_DEF
+
from ...infrastructure.repository_access import require_enterprise_repository
from ...infrastructure.utils import parse_iso_datetime, utc_now
from ...schemas.template_schemas import (
@@ -127,7 +128,6 @@ async def delete_extension_config_template(
def _build_row_from_template(
template: dict[str, Any],
*,
- jiuwenclaw_id: str,
now: Any,
) -> dict[str, Any]:
template_uuid = _normalize_template_id(template.get("template_id"))
@@ -138,7 +138,6 @@ def _build_row_from_template(
if custom_config is None:
custom_config = {}
return {
- "jiuwenclaw_id": jiuwenclaw_id,
"template_id": template_uuid,
"template_name": str(template["template_name"]).strip(),
"description": template.get("description"),
@@ -155,15 +154,13 @@ def _build_row_from_template(
async def _upsert_extension_config_template_from_sync(
repo: EnterpriseRecordRepository,
- template: dict[str, Any],
- *,
- jiuwenclaw_id: str,
+ template: dict[str, Any]
) -> None:
now = utc_now()
tid = _normalize_template_id(template.get("template_id"))
existing = await _get_row_for_instance(repo, tid)
row_data = _build_row_from_template(
- template, jiuwenclaw_id=jiuwenclaw_id, now=now
+ template, now=now
)
if existing is None:
await repo.create(row_data)
@@ -173,7 +170,7 @@ async def _upsert_extension_config_template_from_sync(
# existing 可能是 ISO 字符串;asyncpg 要求 datetime
row_data["created_at"] = parse_iso_datetime(created_at) or now
updates = {
- k: v for k, v in row_data.items() if k not in ("jiuwenclaw_id", "template_id")
+ k: v for k, v in row_data.items() if k not in ("template_id",)
}
updates["updated_at"] = utc_now()
await repo.update({"template_id": tid}, updates)
@@ -181,9 +178,7 @@ async def _upsert_extension_config_template_from_sync(
async def _sync_extension_config_templates_records(
repo: EnterpriseRecordRepository,
- templates: list[dict[str, Any]],
- *,
- jiuwenclaw_id: str,
+ templates: list[dict[str, Any]]
) -> dict[str, Any]:
incoming_ids: set[str] = set()
synced = 0
@@ -193,7 +188,7 @@ async def _sync_extension_config_templates_records(
tid = _normalize_template_id(item.get("template_id"))
incoming_ids.add(tid)
await _upsert_extension_config_template_from_sync(
- repo, item, jiuwenclaw_id=jiuwenclaw_id
+ repo, item
)
synced += 1
deleted = 0
@@ -209,14 +204,13 @@ class ExtensionConfigTemplateService:
async def create(
self,
- jiuwenclaw_id: str,
template: dict[str, Any],
) -> dict[str, Any]:
if not isinstance(template, dict):
raise ValueError("extension_config_templates.create requires template object")
repo = require_enterprise_repository(_TABLE)
await _upsert_extension_config_template_from_sync(
- repo, template, jiuwenclaw_id=jiuwenclaw_id
+ repo, template
)
result = {
"template_id": _normalize_template_id(template.get("template_id")),
@@ -229,7 +223,6 @@ class ExtensionConfigTemplateService:
async def update(
self,
- jiuwenclaw_id: str,
template_id: str,
updates: dict[str, Any],
) -> None:
@@ -251,7 +244,7 @@ class ExtensionConfigTemplateService:
tid,
)
- async def delete(self, jiuwenclaw_id: str, template_id: str) -> None:
+ async def delete(self, template_id: str) -> None:
if template_id is None:
raise ValueError("extension_config_templates.delete requires template_id")
tid = _normalize_template_id(template_id)
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/model_template.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/model_template.py
index 54ed2b3e63..1fa3819023 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/model_template.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/model_template.py
@@ -9,6 +9,7 @@ from typing import Any
from jiuwenswarm.gateway.config.enterprise.repository import EnterpriseRecordRepository
from jiuwenswarm.gateway.config.enterprise.tables.template_models import MODEL_TEMPLATE_TABLE_DEF
+
from ...infrastructure.repository_access import require_enterprise_repository
from ...infrastructure.utils import parse_iso_datetime, utc_now
from ...schemas.template_schemas import ModelTemplateUpdateRequest
@@ -106,13 +107,11 @@ async def delete_model_template(
def _build_row_from_template(
template: dict[str, Any],
*,
- jiuwenclaw_id: str,
now: Any,
) -> dict[str, Any]:
template_uuid = _normalize_template_id(template.get("template_id"))
model_type = _normalize_model_types(template.get("model_type"))
return {
- "jiuwenclaw_id": jiuwenclaw_id,
"template_id": template_uuid,
"template_name": str(template["template_name"]).strip(),
"description": template.get("description"),
@@ -137,15 +136,13 @@ def _build_row_from_template(
async def _upsert_model_template_from_sync(
repo: EnterpriseRecordRepository,
- template: dict[str, Any],
- *,
- jiuwenclaw_id: str,
+ template: dict[str, Any]
) -> None:
now = utc_now()
tid = _normalize_template_id(template.get("template_id"))
existing = await _get_row_for_instance(repo, tid)
row_data = _build_row_from_template(
- template, jiuwenclaw_id=jiuwenclaw_id, now=now
+ template, now=now
)
if existing is None:
await repo.create(row_data)
@@ -155,7 +152,7 @@ async def _upsert_model_template_from_sync(
# existing 可能是 ISO 字符串;asyncpg 要求 datetime
row_data["created_at"] = parse_iso_datetime(created_at) or now
updates = {
- key: value for key, value in row_data.items() if key not in ("jiuwenclaw_id", "template_id")
+ key: value for key, value in row_data.items() if key not in ("template_id",)
}
updates["updated_at"] = utc_now()
await repo.update({"template_id": tid}, updates)
@@ -163,9 +160,7 @@ async def _upsert_model_template_from_sync(
async def _sync_model_templates_records(
repo: EnterpriseRecordRepository,
- templates: list[dict[str, Any]],
- *,
- jiuwenclaw_id: str,
+ templates: list[dict[str, Any]]
) -> dict[str, Any]:
incoming_ids: set[str] = set()
synced = 0
@@ -174,7 +169,7 @@ async def _sync_model_templates_records(
raise ValueError("model_templates.sync templates must be objects")
tid = _normalize_template_id(item.get("template_id"))
incoming_ids.add(tid)
- await _upsert_model_template_from_sync(repo, item, jiuwenclaw_id=jiuwenclaw_id)
+ await _upsert_model_template_from_sync(repo, item)
synced += 1
deleted = 0
for row in await repo.list():
@@ -189,14 +184,13 @@ class ModelTemplateService:
async def create(
self,
- jiuwenclaw_id: str,
template: dict[str, Any],
) -> dict[str, Any]:
if not isinstance(template, dict):
raise ValueError("model_templates.create requires template object")
repo = require_enterprise_repository(_TABLE)
await _upsert_model_template_from_sync(
- repo, template, jiuwenclaw_id=jiuwenclaw_id
+ repo, template
)
result = {
"template_id": _normalize_template_id(template.get("template_id")),
@@ -209,7 +203,6 @@ class ModelTemplateService:
async def update(
self,
- jiuwenclaw_id: str,
template_id: str,
updates: dict[str, Any],
) -> None:
@@ -228,7 +221,7 @@ class ModelTemplateService:
tid,
)
- async def delete(self, jiuwenclaw_id: str, template_id: str) -> None:
+ async def delete(self, template_id: str) -> None:
if template_id is None:
raise ValueError("model_templates.delete requires template_id")
tid = _normalize_template_id(template_id)
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/service_config_template.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/service_config_template.py
index d75dc90ce6..c33046e488 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/service_config_template.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/service_config_template.py
@@ -10,6 +10,7 @@ from typing import Any
from jiuwenswarm.gateway.config.enterprise.repository import EnterpriseRecordRepository
from jiuwenswarm.gateway.config.enterprise.tables.template_models import SERVICE_CONFIG_TEMPLATE_TABLE_DEF
+
from ...infrastructure.repository_access import require_enterprise_repository
from ...infrastructure.utils import parse_iso_datetime, utc_now
from ...schemas.template_schemas import ServiceConfigTemplateUpdateRequest
@@ -111,12 +112,10 @@ async def delete_service_config_template(
def _build_row_from_template(
template: dict[str, Any],
*,
- jiuwenclaw_id: str,
now: datetime,
) -> dict[str, Any]:
template_uuid = _normalize_template_id(template.get("template_id"))
return {
- "jiuwenclaw_id": jiuwenclaw_id,
"template_id": template_uuid,
"template_name": str(template["template_name"]).strip(),
"description": template.get("description"),
@@ -210,15 +209,13 @@ def _build_row_from_template(
async def _upsert_service_config_template_from_sync(
repo: EnterpriseRecordRepository,
- template: dict[str, Any],
- *,
- jiuwenclaw_id: str,
+ template: dict[str, Any]
) -> None:
now = utc_now()
tid = _normalize_template_id(template.get("template_id"))
existing = await _get_row_for_instance(repo, tid)
row_data = _build_row_from_template(
- template, jiuwenclaw_id=jiuwenclaw_id, now=now
+ template, now=now
)
if existing is None:
await repo.create(row_data)
@@ -228,7 +225,7 @@ async def _upsert_service_config_template_from_sync(
# existing 可能是 ISO 字符串;asyncpg 要求 datetime
row_data["created_at"] = parse_iso_datetime(created_at) or now
updates = {
- k: v for k, v in row_data.items() if k not in ("jiuwenclaw_id", "template_id")
+ k: v for k, v in row_data.items() if k not in ("template_id",)
}
updates["updated_at"] = utc_now()
await repo.update({"template_id": tid}, updates)
@@ -236,9 +233,7 @@ async def _upsert_service_config_template_from_sync(
async def _sync_service_config_templates_records(
repo: EnterpriseRecordRepository,
- templates: list[dict[str, Any]],
- *,
- jiuwenclaw_id: str,
+ templates: list[dict[str, Any]]
) -> dict[str, Any]:
incoming_ids: set[str] = set()
synced = 0
@@ -248,7 +243,7 @@ async def _sync_service_config_templates_records(
tid = _normalize_template_id(item.get("template_id"))
incoming_ids.add(tid)
await _upsert_service_config_template_from_sync(
- repo, item, jiuwenclaw_id=jiuwenclaw_id
+ repo, item
)
synced += 1
deleted = 0
@@ -264,14 +259,13 @@ class ServiceConfigTemplateService:
async def create(
self,
- jiuwenclaw_id: str,
template: dict[str, Any],
) -> dict[str, Any]:
if not isinstance(template, dict):
raise ValueError("service_config_templates.create requires template object")
repo = require_enterprise_repository(_TABLE)
await _upsert_service_config_template_from_sync(
- repo, template, jiuwenclaw_id=jiuwenclaw_id
+ repo, template
)
result = {
"template_id": _normalize_template_id(template.get("template_id")),
@@ -284,7 +278,6 @@ class ServiceConfigTemplateService:
async def update(
self,
- jiuwenclaw_id: str,
template_id: str,
updates: dict[str, Any],
) -> None:
@@ -306,7 +299,7 @@ class ServiceConfigTemplateService:
tid,
)
- async def delete(self, jiuwenclaw_id: str, template_id: str) -> None:
+ async def delete(self, template_id: str) -> None:
if template_id is None:
raise ValueError("service_config_templates.delete requires template_id")
tid = _normalize_template_id(template_id)
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/skill_whitelist_template.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/skill_whitelist_template.py
index 0e798e876f..573929e091 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/skill_whitelist_template.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/skill_whitelist_template.py
@@ -9,6 +9,7 @@ from typing import Any
from jiuwenswarm.gateway.config.enterprise.repository import EnterpriseRecordRepository
from jiuwenswarm.gateway.config.enterprise.tables.template_models import SKILL_WHITELIST_TEMPLATE_TABLE_DEF
+
from ...infrastructure.repository_access import require_enterprise_repository
from ...infrastructure.utils import parse_iso_datetime, utc_now
from ...schemas.template_schemas import SkillWhitelistTemplateUpdateRequest, _validate_http_url
@@ -106,12 +107,10 @@ async def delete_skill_whitelist_template(
def _build_row_from_template(
template: dict[str, Any],
*,
- jiuwenclaw_id: str,
now: Any,
) -> dict[str, Any]:
template_uuid = _normalize_template_id(template.get("template_id"))
return {
- "jiuwenclaw_id": jiuwenclaw_id,
"template_id": template_uuid,
"template_name": str(template["template_name"]).strip(),
"description": template.get("description"),
@@ -127,15 +126,13 @@ def _build_row_from_template(
async def _upsert_skill_whitelist_template_from_sync(
repo: EnterpriseRecordRepository,
- template: dict[str, Any],
- *,
- jiuwenclaw_id: str,
+ template: dict[str, Any]
) -> None:
now = utc_now()
tid = _normalize_template_id(template.get("template_id"))
existing = await _get_row_for_instance(repo, tid)
row_data = _build_row_from_template(
- template, jiuwenclaw_id=jiuwenclaw_id, now=now
+ template, now=now
)
if existing is None:
await repo.create(row_data)
@@ -145,7 +142,7 @@ async def _upsert_skill_whitelist_template_from_sync(
# existing 可能是 ISO 字符串;asyncpg 要求 datetime
row_data["created_at"] = parse_iso_datetime(created_at) or now
updates = {
- k: v for k, v in row_data.items() if k not in ("jiuwenclaw_id", "template_id")
+ k: v for k, v in row_data.items() if k not in ("template_id",)
}
updates["updated_at"] = utc_now()
await repo.update({"template_id": tid}, updates)
@@ -153,9 +150,7 @@ async def _upsert_skill_whitelist_template_from_sync(
async def _sync_skill_whitelist_templates_records(
repo: EnterpriseRecordRepository,
- templates: list[dict[str, Any]],
- *,
- jiuwenclaw_id: str,
+ templates: list[dict[str, Any]]
) -> dict[str, Any]:
incoming_ids: set[str] = set()
synced = 0
@@ -165,7 +160,7 @@ async def _sync_skill_whitelist_templates_records(
tid = _normalize_template_id(item.get("template_id"))
incoming_ids.add(tid)
await _upsert_skill_whitelist_template_from_sync(
- repo, item, jiuwenclaw_id=jiuwenclaw_id
+ repo, item
)
synced += 1
deleted = 0
@@ -181,14 +176,13 @@ class SkillWhitelistTemplateService:
async def create(
self,
- jiuwenclaw_id: str,
template: dict[str, Any],
) -> dict[str, Any]:
if not isinstance(template, dict):
raise ValueError("skill_whitelist_templates.create requires template object")
repo = require_enterprise_repository(_TABLE)
await _upsert_skill_whitelist_template_from_sync(
- repo, template, jiuwenclaw_id=jiuwenclaw_id
+ repo, template
)
result = {
"template_id": _normalize_template_id(template.get("template_id")),
@@ -201,7 +195,6 @@ class SkillWhitelistTemplateService:
async def update(
self,
- jiuwenclaw_id: str,
template_id: str,
updates: dict[str, Any],
) -> None:
@@ -223,7 +216,7 @@ class SkillWhitelistTemplateService:
tid,
)
- async def delete(self, jiuwenclaw_id: str, template_id: str) -> None:
+ async def delete(self, template_id: str) -> None:
if template_id is None:
raise ValueError("skill_whitelist_templates.delete requires template_id")
tid = _normalize_template_id(template_id)
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.py
index 3f663cf04f..f1895098f8 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
@@ -11,7 +11,7 @@ from ..routers.template_routers import templates_router
def create_app() -> FastAPI:
- """Gateway 本机接口:无路径级实例段;``JIUWENCLAW_ID`` 仅作 Manager 注册/探活身份(未设则自动生成)。"""
+ """Gateway 本机配置接收接口(每网关独立 DB,无路径级实例段)。"""
app = FastAPI(title="Gateway Manager Config Receiver", docs_url="/docs", redoc_url=None)
@app.get("/api/health", tags=["System"])
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/utils.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/utils.py
index 550f8ddf99..13a17e476b 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/utils.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/infrastructure/utils.py
@@ -5,7 +5,6 @@
from __future__ import annotations
import os
-import uuid
from datetime import datetime, timezone
from typing import Any
@@ -65,40 +64,6 @@ KNOWN_SLOT_KEYS = frozenset({
})
-def set_jiuwenclaw_id(jiuwenclaw_id: str | None) -> None:
- """写入 ``JIUWENCLAW_ID`` 环境变量。"""
- if jiuwenclaw_id is None:
- os.environ.pop("JIUWENCLAW_ID", None)
- return
- normalized = str(jiuwenclaw_id).strip()
- if normalized:
- os.environ["JIUWENCLAW_ID"] = normalized
- else:
- os.environ.pop("JIUWENCLAW_ID", None)
-
-
-def get_jiuwenclaw_id() -> str:
- """优先读 ``JIUWENCLAW_ID``;未设置则生成 UUID v4 并写回 env(进程内稳定)。"""
- val = os.getenv("JIUWENCLAW_ID", "").strip()
- if val:
- return val
- jid = str(uuid.uuid4())
- os.environ["JIUWENCLAW_ID"] = jid
- return jid
-
-
-def assert_jiuwenclaw_id_matches(jiuwenclaw_id: str) -> str:
- """校验 config.push 顶层 ``jiuwenclaw_id`` 与本机 ``JIUWENCLAW_ID`` 一致,并返回有效 id。"""
- if not jiuwenclaw_id:
- raise ValueError("config.push payload requires jiuwenclaw_id")
- configured = get_jiuwenclaw_id()
- if jiuwenclaw_id != configured:
- raise ValueError(
- f"jiuwenclaw_id mismatch: push={jiuwenclaw_id!r} configured={configured!r}"
- )
- return configured
-
-
def utc_now() -> datetime:
"""返回当前 UTC 时间(带 ``timezone.utc`` 的 aware ``datetime``)。"""
return datetime.now(timezone.utc)
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/application_config_routers.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/application_config_routers.py
index e2872c08ab..3c0226536a 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/application_config_routers.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/application_config_routers.py
@@ -51,7 +51,7 @@ async def upsert_logging(
sync: Annotated[SyncContext, Depends(verify_sync(LoggingSyncBody))],
):
try:
- result = await LoggingConfigService().upsert(sync.jiuwenclaw_id, **sync.business)
+ result = await LoggingConfigService().upsert(**sync.business)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
trigger_runtime_config_update()
@@ -63,7 +63,7 @@ async def delete_logging(
sync: VerifySyncEnvelopeOnly,
):
try:
- await LoggingConfigService().delete(sync.jiuwenclaw_id)
+ await LoggingConfigService().delete()
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
trigger_runtime_config_update()
@@ -75,9 +75,7 @@ async def upsert_task_memory(
sync: Annotated[SyncContext, Depends(verify_sync(TaskMemorySyncBody))],
):
try:
- result = await TaskMemoryConfigService().upsert(
- sync.jiuwenclaw_id, sync.business
- )
+ result = await TaskMemoryConfigService().upsert(sync.business)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
trigger_runtime_config_update()
@@ -89,7 +87,7 @@ async def delete_task_memory(
sync: VerifySyncEnvelopeOnly,
):
try:
- await TaskMemoryConfigService().delete(sync.jiuwenclaw_id)
+ await TaskMemoryConfigService().delete()
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
trigger_runtime_config_update()
@@ -101,9 +99,7 @@ async def upsert_permissions(
sync: Annotated[SyncContext, Depends(verify_sync(PermissionsSyncBody))],
):
try:
- result = await PermissionsConfigService().upsert(
- sync.jiuwenclaw_id, **sync.business
- )
+ result = await PermissionsConfigService().upsert(**sync.business)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
trigger_runtime_config_update()
@@ -115,7 +111,7 @@ async def delete_permissions(
sync: VerifySyncEnvelopeOnly,
):
try:
- await PermissionsConfigService().delete(sync.jiuwenclaw_id)
+ await PermissionsConfigService().delete()
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
trigger_runtime_config_update()
@@ -127,7 +123,7 @@ async def upsert_memory(
sync: Annotated[SyncContext, Depends(verify_sync(MemorySyncBody))],
):
try:
- result = await MemoryConfigService().upsert(sync.jiuwenclaw_id, **sync.business)
+ result = await MemoryConfigService().upsert(**sync.business)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
trigger_runtime_config_update()
@@ -139,7 +135,7 @@ async def delete_memory(
sync: VerifySyncEnvelopeOnly,
):
try:
- await MemoryConfigService().delete(sync.jiuwenclaw_id)
+ await MemoryConfigService().delete()
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
trigger_runtime_config_update()
@@ -151,9 +147,7 @@ async def create_log_masking_rule(
sync: Annotated[SyncContext, Depends(verify_sync(LogMaskingCreateSyncBody))],
):
try:
- result = await LogMaskingRuleService().create(
- sync.jiuwenclaw_id, sync.business
- )
+ result = await LogMaskingRuleService().create(sync.business)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
trigger_runtime_config_update()
@@ -168,9 +162,7 @@ async def patch_log_masking_rule(
sync: Annotated[SyncContext, Depends(verify_sync(LogMaskingUpdateSyncBody))],
):
try:
- result = await LogMaskingRuleService().update(
- sync.jiuwenclaw_id, rule_id, sync.business
- )
+ result = await LogMaskingRuleService().update(rule_id, sync.business)
except ValueError as exc:
detail = str(exc)
status = 404 if "not found" in detail else 400
@@ -187,7 +179,7 @@ async def delete_log_masking_rule(
sync: VerifySyncEnvelopeOnly,
):
try:
- await LogMaskingRuleService().delete(sync.jiuwenclaw_id, rule_id)
+ await LogMaskingRuleService().delete(rule_id)
except ValueError as exc:
detail = str(exc)
status = 404 if "not found" in detail else 400
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/deps.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/deps.py
index 7c2af75dfe..6e17579786 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/deps.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/deps.py
@@ -7,11 +7,10 @@ from collections.abc import Callable
from dataclasses import dataclass
from typing import Annotated, Any, TypeVar
-from fastapi import Depends, HTTPException, Request
+from fastapi import Depends, Request
from pydantic import BaseModel
from ..http.sync_security import split_business
-from ..infrastructure.utils import assert_jiuwenclaw_id_matches, get_jiuwenclaw_id
from ..schemas.sync_schemas import SyncEnvelopeOnlyBody
TBody = TypeVar("TBody", bound=BaseModel)
@@ -22,32 +21,15 @@ class SyncContext:
"""同步上下文(不含业务分发)。"""
business: dict[str, Any]
- jiuwenclaw_id: str
method: str
-def require_jiuwenclaw_id(business: dict[str, Any] | None = None) -> str:
- """统一取本机实例 id(env 优先,否则自动生成);body 若带 id 则校验一致。"""
- jid = get_jiuwenclaw_id()
- body_jid = ""
- if business:
- body_jid = str(business.get("jiuwenclaw_id") or "").strip()
- if body_jid:
- try:
- assert_jiuwenclaw_id_matches(body_jid)
- except ValueError as exc:
- raise HTTPException(status_code=403, detail=str(exc)) from exc
- return jid
-
-
async def build_sync_context(body: BaseModel, method: str) -> SyncContext:
raw = body.model_dump(mode="python", exclude_unset=False)
business = split_business(raw)
- jid = require_jiuwenclaw_id(business)
- business.pop("jiuwenclaw_id", None)
+ business.pop("jiuwenclaw_id", None) # 历史字段,忽略
return SyncContext(
business=business,
- jiuwenclaw_id=jid,
method=method.upper(),
)
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/instance_resource_routers.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/instance_resource_routers.py
index 607a0e5b5a..7df554da64 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/instance_resource_routers.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/instance_resource_routers.py
@@ -34,7 +34,6 @@ async def upsert_instance_agent_resource(
sync = await build_sync_context(body, request.method)
try:
result = await InstanceAgentResourceService().upsert(
- sync.jiuwenclaw_id,
sync.business,
)
except ValueError as exc:
@@ -55,7 +54,6 @@ async def delete_instance_agent_resource(
sync = await build_sync_context(body, request.method)
try:
await InstanceAgentResourceService().delete(
- sync.jiuwenclaw_id,
resource_id,
)
except ValueError as exc:
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/instance_routers.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/instance_routers.py
index ee1f6c4934..ab48d1db63 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/instance_routers.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/instance_routers.py
@@ -28,7 +28,7 @@ async def instance_data_lifecycle(
status_code=400, detail=f"unsupported instance_data_lifecycle.op: {op!r}"
)
try:
- result = await InstanceDataLifecycleService().purge(sync.jiuwenclaw_id)
+ result = await InstanceDataLifecycleService().purge()
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return ResponseModel(code=200, message="success", data=sync_write_data(sync, result))
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/template_routers.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/template_routers.py
index 601d470e53..a4f1a85147 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/template_routers.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/template_routers.py
@@ -61,7 +61,7 @@ def _add_template_crud(
sync = await build_sync_context(body, request.method)
try:
result = await svc_factory().create(
- sync.jiuwenclaw_id, sync.business
+ sync.business
)
except ValueError as exc:
raise _http_exc(exc) from exc
@@ -78,7 +78,7 @@ def _add_template_crud(
sync = await build_sync_context(body, request.method)
try:
await svc_factory().update(
- sync.jiuwenclaw_id, template_id, sync.business
+ template_id, sync.business
)
except ValueError as exc:
raise _http_exc(exc) from exc
@@ -94,7 +94,7 @@ def _add_template_crud(
):
sync = await build_sync_context(body, request.method)
try:
- await svc_factory().delete(sync.jiuwenclaw_id, template_id)
+ await svc_factory().delete(template_id)
except ValueError as exc:
raise _http_exc(exc) from exc
trigger_runtime_config_update()
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/application_config_schemas.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/application_config_schemas.py
index 608107f515..f4d3a7d65e 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/application_config_schemas.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/application_config_schemas.py
@@ -56,7 +56,6 @@ class LogMaskingRuleCreateRequest(BaseModel):
model_config = ConfigDict(str_strip_whitespace=True)
- jiuwenclaw_id: str | None = Field(default=None, max_length=64)
rule_id: str = Field(..., min_length=1, max_length=64)
rule_name: str = Field(..., min_length=1, max_length=128)
description: str | None = Field(default=None, max_length=512)
@@ -84,6 +83,9 @@ class LogMaskingRuleUpdateRequest(BaseModel):
class InstanceDataLifecycleRequest(BaseModel):
- """实例数据生命周期(默认 purge)。"""
+ """实例数据生命周期(默认 purge)。
+
+ ``op=purge`` 会清空本 Gateway 库内全部实例级数据(不可逆;每网关独立 DB)。
+ """
op: str = Field(default="purge", max_length=32)
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/instance_resource_schemas.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/instance_resource_schemas.py
index dc77c28ffc..06a461faa2 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/instance_resource_schemas.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/instance_resource_schemas.py
@@ -17,7 +17,7 @@ MatchExprField = Annotated[Any, BeforeValidator(_validate_match_expr)]
class InstanceAgentResourceUpsertRequest(BaseModel):
- """与 Manager ``instance_agent_resource`` 行字段对齐(仍按本机 jiuwenclaw_id 隔离落库)。"""
+ """与 Manager ``instance_agent_resource`` 行字段对齐。"""
resource_id: str = Field(..., min_length=1, max_length=100)
ref_template_id: str = Field(..., min_length=1, max_length=100)
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/security/keys.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/security/keys.py
index 58cba9288a..3969839517 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/security/keys.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/security/keys.py
@@ -5,7 +5,7 @@
- 加密密钥对:单例持久化于 ``gateway_enc_keypair``,私钥永不外发;首启生成。
- 签名密钥对:单例持久化于 ``gateway_sign_keypair``,握手向对端出示 link-auth 令牌;首启生成。
-- Manager 签名公钥:握手分发,存 ``manager_sign_pubkey``,按 jiuwenclaw_id 关联。
+- Manager 签名公钥:握手分发,存 ``manager_sign_pubkey``(单例,id="default")。
"""
from __future__ import annotations
@@ -125,7 +125,6 @@ async def load_gateway_enc_privkey_by_fp(fingerprint: str | None) -> bytes | Non
async def store_manager_sign_pubkey(
- jiuwenclaw_id: str,
public_key_b64: str,
*,
key_version: str,
@@ -133,16 +132,12 @@ async def store_manager_sign_pubkey(
sign_alg: str = "Ed25519",
fingerprint: str | None = None,
) -> None:
- """落库/更新 Manager 签名公钥(可选;用于 config.push 验签)。
-
- 读写走装配层注入的 ``manager_sign_pubkey`` Repository(按启动时 ``instance_id`` 隔离)。
- ``jiuwenclaw_id`` 仍写入行内,供对账;lookup 以 Repository scope 为准。
- """
+ """落库/更新 Manager 签名公钥(单例,id="default";用于 config.push 验签)。"""
repo = require_enterprise_repository(_SIGN_PUBKEY_TABLE)
pub = cp.b64d(public_key_b64)
fp = fingerprint or cp.fingerprint(pub)
now = utc_now()
- existing = await repo.get()
+ existing = await repo.get({"id": _KEYPAIR_ID})
data: dict[str, Any] = {
"manager_id": manager_id,
"sign_alg": sign_alg,
@@ -153,34 +148,30 @@ async def store_manager_sign_pubkey(
"updated_at": now,
}
if existing is not None:
- await repo.update({}, data)
+ await repo.update({"id": _KEYPAIR_ID}, data)
else:
await repo.create(
{
- "jiuwenclaw_id": jiuwenclaw_id,
+ "id": _KEYPAIR_ID,
"bound_at": now,
**data,
},
)
logger.info(
- "[keys] bound manager sign pubkey jiuwenclaw_id=%s version=%s fp=%s",
- jiuwenclaw_id,
+ "[keys] bound manager sign pubkey version=%s fp=%s",
key_version,
fp[:16],
)
async def load_manager_sign_pubkey(
- jiuwenclaw_id: str, key_version: str | None = None
+ key_version: str | None = None,
) -> ManagerSignPublicKey | None:
- """读取 Manager 签名公钥;指定版本时需匹配,否则返回 None。"""
+ """读取 Manager 签名公钥(单例);指定版本时需匹配,否则返回 None。"""
repo = require_enterprise_repository(_SIGN_PUBKEY_TABLE)
- row = await repo.get()
+ row = await repo.get({"id": _KEYPAIR_ID})
if not row or not row.get("public_key") or str(row.get("status")) != "bound":
return None
- stored_jid = str(row.get("jiuwenclaw_id") or "")
- if jiuwenclaw_id and stored_jid and stored_jid != jiuwenclaw_id:
- return None
stored_version = str(row.get("key_version") or "")
if key_version and key_version != stored_version:
return None
@@ -188,13 +179,10 @@ async def load_manager_sign_pubkey(
return ManagerSignPublicKey(pub, stored_version, str(row.get("fingerprint") or cp.fingerprint(pub)))
-async def delete_manager_sign_pubkey(jiuwenclaw_id: str) -> None:
- """解绑时清除该实例的 Manager 签名公钥。"""
+async def delete_manager_sign_pubkey() -> None:
+ """清除本机 Manager 签名公钥(单例)。"""
repo = require_enterprise_repository(_SIGN_PUBKEY_TABLE)
- row = await repo.get()
+ row = await repo.get({"id": _KEYPAIR_ID})
if row is None:
return
- stored_jid = str(row.get("jiuwenclaw_id") or "")
- if jiuwenclaw_id and stored_jid and stored_jid != jiuwenclaw_id:
- return
- await repo.delete()
+ await repo.delete({"id": _KEYPAIR_ID})
diff --git a/tests/unit/agentserver/test_cron_runtime.py b/tests/unit/agentserver/test_cron_runtime.py
index b65c104a06..5f5533275e 100644
--- a/tests/unit/agentserver/test_cron_runtime.py
+++ b/tests/unit/agentserver/test_cron_runtime.py
@@ -113,6 +113,11 @@ def _make_cron_tools(tmp_path, monkeypatch) -> tuple[CronTools, _FakeGatewayPush
return None
monkeypatch.setattr(tools, "_reload_scheduler", _noop_reload)
+ # 本文件测本地 store / push 同步路径,不走企业 DB cron。
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.cron.enterprise_gate.enterprise_cron_enabled",
+ lambda **_kwargs: False,
+ )
return tools, push
diff --git a/tests/unit_tests/agentserver/test_enterprise_policy.py b/tests/unit_tests/agentserver/test_enterprise_policy.py
index f0634ad115..eacfd68b89 100644
--- a/tests/unit_tests/agentserver/test_enterprise_policy.py
+++ b/tests/unit_tests/agentserver/test_enterprise_policy.py
@@ -319,7 +319,7 @@ async def test_load_effective_config_by_instance_agent_resource(
filters: dict | None = None,
order_by: str = "",
) -> list[dict]:
- scoped = gateway_db.apply_instance_scope(table, dict(filters or {}))
+ scoped = dict(filters or {})
if table == "instance_agent_resource":
if scoped.get("resource_id") != resource_id:
return []
@@ -408,7 +408,7 @@ async def test_load_effective_config_skips_mapping_expr_in_template_ref(
filters: dict | None = None,
order_by: str = "",
) -> list[dict]:
- scoped = gateway_db.apply_instance_scope(table, dict(filters or {}))
+ scoped = dict(filters or {})
if table == "instance_agent_resource":
if scoped.get("resource_id") != resource_id:
return []
@@ -580,7 +580,7 @@ async def test_load_effective_config_loads_embedding_template(
filters: dict | None = None,
order_by: str = "",
) -> list[dict]:
- scoped = gateway_db.apply_instance_scope(table, dict(filters or {}))
+ scoped = dict(filters or {})
if table == "instance_agent_resource":
if scoped.get("resource_id") != resource_id:
return []
diff --git a/tests/unit_tests/gateway/test_channel_config_repository.py b/tests/unit_tests/gateway/test_channel_config_repository.py
index 0a6197fe45..850b8c1a24 100644
--- a/tests/unit_tests/gateway/test_channel_config_repository.py
+++ b/tests/unit_tests/gateway/test_channel_config_repository.py
@@ -311,13 +311,11 @@ async def test_create_channel_config_repository_selects_codec(monkeypatch) -> No
db_store = InMemoryPersistentBackend()
monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")
enterprise = create_channel_config_repository(
- db_store, instance_id="inst-1"
+ db_store, instance_id=""
)
await enterprise.upsert(ChannelConfig(channel_id="web", body={"enabled": True}))
- db_row = await db_store.get(
- "channel_config", {"channel_id": "web", "jiuwenclaw_id": "inst-1"}
- )
+ db_row = await db_store.get("channel_config", {"channel_id": "web"})
assert db_row is not None
assert db_row["channel_id"] == "web"
- assert db_row["jiuwenclaw_id"] == "inst-1"
+ assert "jiuwenclaw_id" not in db_row
assert db_row["config"] == {"enabled": True}
diff --git a/tests/unit_tests/gateway/test_config_poll.py b/tests/unit_tests/gateway/test_config_poll.py
index 954b0431fb..b9370fa3db 100644
--- a/tests/unit_tests/gateway/test_config_poll.py
+++ b/tests/unit_tests/gateway/test_config_poll.py
@@ -51,16 +51,13 @@ async def test_syncer_applies_when_row_updated_at_changes() -> None:
apply_mock = AsyncMock()
syncer = ConfigPollSyncer()
- async def _rows(table: str, _jid: str) -> list[dict]:
+ async def _rows(table: str) -> list[dict]:
if table != "logging_config":
return []
ts = ts1 if "logging_config" not in syncer._last_rows else ts2
return [{"updated_at": ts.isoformat()}]
with patch(
- "jiuwenswarm.gateway.config_poll.syncer.get_bound_jiuwenclaw_id",
- return_value="jid-1",
- ), patch(
"jiuwenswarm.gateway.config_poll.syncer.list_table_records",
side_effect=_rows,
), patch.dict(
@@ -83,15 +80,12 @@ async def test_syncer_skips_when_snapshot_unchanged() -> None:
apply_mock = AsyncMock()
syncer = ConfigPollSyncer()
- async def _rows(table: str, _jid: str) -> list[dict]:
+ async def _rows(table: str) -> list[dict]:
if table != "logging_config":
return []
return [{"updated_at": ts.isoformat()}]
with patch(
- "jiuwenswarm.gateway.config_poll.syncer.get_bound_jiuwenclaw_id",
- return_value="jid-1",
- ), patch(
"jiuwenswarm.gateway.config_poll.syncer.list_table_records",
side_effect=_rows,
), patch.dict(
@@ -110,7 +104,7 @@ async def test_syncer_applies_when_all_rows_deleted() -> None:
apply_mock = AsyncMock()
syncer = ConfigPollSyncer()
- async def _rows(table: str, _jid: str) -> list[dict]:
+ async def _rows(table: str) -> list[dict]:
if table != "logging_config":
return []
if "logging_config" not in syncer._last_rows:
@@ -118,9 +112,6 @@ async def test_syncer_applies_when_all_rows_deleted() -> None:
return []
with patch(
- "jiuwenswarm.gateway.config_poll.syncer.get_bound_jiuwenclaw_id",
- return_value="jid-1",
- ), patch(
"jiuwenswarm.gateway.config_poll.syncer.list_table_records",
side_effect=_rows,
), patch.dict(
@@ -140,7 +131,7 @@ async def test_syncer_detects_deleted_channel_row() -> None:
apply_mock = AsyncMock()
syncer = ConfigPollSyncer()
- async def _rows(table: str, _jid: str) -> list[dict]:
+ async def _rows(table: str) -> list[dict]:
if table != "channel_config":
return []
if "channel_config" not in syncer._last_rows:
@@ -160,9 +151,6 @@ async def test_syncer_detects_deleted_channel_row() -> None:
]
with patch(
- "jiuwenswarm.gateway.config_poll.syncer.get_bound_jiuwenclaw_id",
- return_value="jid-1",
- ), patch(
"jiuwenswarm.gateway.config_poll.syncer.list_table_records",
side_effect=_rows,
), patch.dict(
@@ -173,7 +161,7 @@ async def test_syncer_detects_deleted_channel_row() -> None:
await syncer.run_once()
await syncer.run_once()
assert apply_mock.await_count == 2
- second_ctx = apply_mock.await_args_list[1].args[1]
+ second_ctx = apply_mock.await_args_list[1].args[0]
assert second_ctx.removed_channel_ids == frozenset({"c1"})
@@ -183,15 +171,12 @@ async def test_syncer_keeps_snapshot_when_apply_fails() -> None:
apply_mock = AsyncMock(side_effect=RuntimeError("boom"))
syncer = ConfigPollSyncer()
- async def _rows(table: str, _jid: str) -> list[dict]:
+ async def _rows(table: str) -> list[dict]:
if table != "logging_config":
return []
return [{"updated_at": ts.isoformat()}]
with patch(
- "jiuwenswarm.gateway.config_poll.syncer.get_bound_jiuwenclaw_id",
- return_value="jid-1",
- ), patch(
"jiuwenswarm.gateway.config_poll.syncer.list_table_records",
side_effect=_rows,
), patch.dict(
@@ -216,7 +201,7 @@ async def test_syncer_normalizes_updated_at_for_snapshot() -> None:
syncer = ConfigPollSyncer()
calls = {"n": 0}
- async def _rows(table: str, _jid: str) -> list[dict]:
+ async def _rows(table: str) -> list[dict]:
if table != "logging_config":
return []
calls["n"] += 1
@@ -225,9 +210,6 @@ async def test_syncer_normalizes_updated_at_for_snapshot() -> None:
return [{"updated_at": ts.isoformat()}]
with patch(
- "jiuwenswarm.gateway.config_poll.syncer.get_bound_jiuwenclaw_id",
- return_value="jid-1",
- ), patch(
"jiuwenswarm.gateway.config_poll.syncer.list_table_records",
side_effect=_rows,
), patch.dict(
@@ -248,7 +230,6 @@ async def test_apply_logging_config_table_uses_passed_rows() -> None:
"jiuwenswarm.common.utils.apply_logging_config_payload",
) as apply_payload:
await apply_logging_config_table(
- "jid-1",
TableApplyContext(
rows=[{"level": "DEBUG", "gateway": "WARNING"}],
),
diff --git a/tests/unit_tests/gateway/test_config_poll_db.py b/tests/unit_tests/gateway/test_config_poll_db.py
index 983bb513f0..78b9df3583 100644
--- a/tests/unit_tests/gateway/test_config_poll_db.py
+++ b/tests/unit_tests/gateway/test_config_poll_db.py
@@ -8,7 +8,6 @@ from unittest.mock import AsyncMock, patch
import pytest
from jiuwenswarm.gateway.config_poll.db import (
- _poll_table_filters,
list_table_records,
row_snapshot,
row_stamp,
@@ -39,35 +38,25 @@ def test_row_snapshot_detects_delete_and_update() -> None:
assert row_stamp({"updated_at": None}) == ""
-def test_poll_table_filters_channel_config_is_global() -> None:
- assert _poll_table_filters("channel_config", "jid-1") == {}
-
-
-def test_poll_table_filters_other_tables_use_jiuwenclaw_id() -> None:
- assert _poll_table_filters("logging_config", "jid-1") == {"jiuwenclaw_id": "jid-1"}
- assert _poll_table_filters("log_masking_rule", "jid-1") == {"jiuwenclaw_id": "jid-1"}
- assert _poll_table_filters("logging_config", "") == {}
-
-
@pytest.mark.asyncio
-async def test_list_table_records_channel_config_without_jiuwenclaw_id() -> None:
+async def test_list_table_records_channel_config() -> None:
list_mock = AsyncMock(return_value=[{"channel_id": "web", "status": "active"}])
with patch(
"jiuwenswarm.server.runtime.enterprise_config.gateway_db.list_records",
list_mock,
):
- rows = await list_table_records("channel_config", "")
- list_mock.assert_awaited_once_with("channel_config", filters={})
+ rows = await list_table_records("channel_config")
+ list_mock.assert_awaited_once_with("channel_config")
assert rows == [{"channel_id": "web", "status": "active"}]
@pytest.mark.asyncio
-async def test_list_table_records_logging_requires_jiuwenclaw_id() -> None:
- list_mock = AsyncMock(return_value=[])
+async def test_list_table_records_logging_without_instance_filter() -> None:
+ list_mock = AsyncMock(return_value=[{"level": "INFO"}])
with patch(
"jiuwenswarm.server.runtime.enterprise_config.gateway_db.list_records",
list_mock,
):
- rows = await list_table_records("logging_config", "")
- list_mock.assert_not_awaited()
- assert rows == []
+ rows = await list_table_records("logging_config")
+ list_mock.assert_awaited_once_with("logging_config")
+ assert rows == [{"level": "INFO"}]
diff --git a/tests/unit_tests/gateway/test_config_poll_persistent.py b/tests/unit_tests/gateway/test_config_poll_persistent.py
index b38c50c2a7..5be15c01e3 100644
--- a/tests/unit_tests/gateway/test_config_poll_persistent.py
+++ b/tests/unit_tests/gateway/test_config_poll_persistent.py
@@ -20,18 +20,16 @@ async def test_list_table_records_via_persistent_store() -> None:
await store.create(
"logging_config",
{
- "jiuwenclaw_id": "jid-1",
"level": "INFO",
"updated_at": "2026-01-01T00:00:00+00:00",
},
)
set_persistent_store(store)
try:
- rows = await list_table_records("logging_config", "jid-1")
+ rows = await list_table_records("logging_config")
assert len(rows) == 1
assert rows[0]["level"] == "INFO"
- assert await list_table_records("logging_config", "other") == []
- assert await list_table_records("unknown_table", "jid-1") == []
+ assert await list_table_records("unknown_table") == []
finally:
clear_persistent_store()
@@ -43,4 +41,4 @@ async def test_list_table_records_without_store() -> None:
"jiuwenswarm.server.runtime.enterprise_config.gateway_db.list_records",
new=AsyncMock(return_value=[]),
):
- assert await list_table_records("logging_config", "jid-1") == []
+ assert await list_table_records("logging_config") == []
diff --git a/tests/unit_tests/gateway/test_cron_db_store_persistent.py b/tests/unit_tests/gateway/test_cron_db_store_persistent.py
index 3757966b87..4e619fd07e 100644
--- a/tests/unit_tests/gateway/test_cron_db_store_persistent.py
+++ b/tests/unit_tests/gateway/test_cron_db_store_persistent.py
@@ -2,8 +2,6 @@
from __future__ import annotations
-from unittest.mock import patch
-
import pytest
from jiuwenswarm.gateway.cron.db_store import GatewayDbCronJobStore
@@ -20,30 +18,26 @@ async def test_enterprise_cron_crud_via_persistent_store() -> None:
set_persistent_store(store)
cron = GatewayDbCronJobStore()
try:
- with patch(
- "jiuwenswarm.gateway.cron.db_store.get_bound_jiuwenclaw_id",
- return_value="jid-1",
- ):
- created = await cron.create_job(
- name="n1",
- cron_expr="*/5 * * * *",
- timezone="Asia/Shanghai",
- description="d",
- targets="web",
- )
- assert created.id
- got = await cron.get_job(created.id)
- assert got is not None
- assert got.name == "n1"
-
- updated = await cron.update_job(created.id, {"name": "n2"})
- assert updated.name == "n2"
-
- jobs = await cron.list_jobs()
- assert len(jobs) == 1
- assert jobs[0].name == "n2"
-
- assert await cron.delete_job(created.id) is True
- assert await cron.get_job(created.id) is None
+ created = await cron.create_job(
+ name="n1",
+ cron_expr="*/5 * * * *",
+ timezone="Asia/Shanghai",
+ description="d",
+ targets="web",
+ )
+ assert created.id
+ got = await cron.get_job(created.id)
+ assert got is not None
+ assert got.name == "n1"
+
+ updated = await cron.update_job(created.id, {"name": "n2"})
+ assert updated.name == "n2"
+
+ jobs = await cron.list_jobs()
+ assert len(jobs) == 1
+ assert jobs[0].name == "n2"
+
+ assert await cron.delete_job(created.id) is True
+ assert await cron.get_job(created.id) is None
finally:
clear_persistent_store()
diff --git a/tests/unit_tests/gateway/test_cron_tenant_registry.py b/tests/unit_tests/gateway/test_cron_tenant_registry.py
index b7e5a75902..b00f1da284 100644
--- a/tests/unit_tests/gateway/test_cron_tenant_registry.py
+++ b/tests/unit_tests/gateway/test_cron_tenant_registry.py
@@ -108,6 +108,15 @@ async def test_web_create_mirrors_to_agent_home(tmp_path, monkeypatch) -> None:
"jiuwenswarm.gateway.cron.tenant_registry.CronSchedulerService.reload",
AsyncMock(),
)
+ # 本用例验证文件 store 镜像;企业 cron 需路由三元组,与此无关。
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.cron.controller.enterprise_cron_enabled",
+ lambda **_kwargs: False,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.cron.enterprise_store.enterprise_cron_enabled",
+ lambda **_kwargs: False,
+ )
registry = CronTenantRegistry.get_instance(
agent_client=MagicMock(),
diff --git a/tests/unit_tests/gateway/test_enterprise_cron_gate.py b/tests/unit_tests/gateway/test_enterprise_cron_gate.py
index 71d43572d7..2d935b722e 100644
--- a/tests/unit_tests/gateway/test_enterprise_cron_gate.py
+++ b/tests/unit_tests/gateway/test_enterprise_cron_gate.py
@@ -1,11 +1,8 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-"""Enterprise cron gate / identity sticky unit tests."""
+"""Enterprise cron gate / sticky identity unit tests."""
from __future__ import annotations
-import os
-from unittest.mock import patch
-
import pytest
from jiuwenswarm.gateway.cron.cron_job_mutations import apply_cron_job_patch, build_new_cron_job
@@ -107,21 +104,20 @@ def test_job_matches_routing_and() -> None:
)
-def test_enterprise_cron_enabled_requires_jiuwenclaw_id(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_enterprise_cron_enabled_by_deployment_mode(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")
- monkeypatch.delenv("JIUWENCLAW_ID", raising=False)
- with patch(
- "jiuwenswarm.gateway.cron.enterprise_gate.get_bound_jiuwenclaw_id",
- return_value=None,
- ):
- assert enterprise_cron_enabled(deployment_mode="standalone") is False
-
- with patch(
- "jiuwenswarm.gateway.cron.enterprise_gate.get_bound_jiuwenclaw_id",
- return_value="jid-1",
- ):
- assert enterprise_cron_enabled(deployment_mode="standalone") is True
- assert enterprise_cron_enabled(deployment_mode="distributed") is False
+ assert enterprise_cron_enabled(deployment_mode="standalone") is True
+ assert enterprise_cron_enabled(deployment_mode="distributed") is False
+
+
+def test_enterprise_cron_disabled_for_personal_edition(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.delenv("JIUWENSWARM_EDITION", raising=False)
+ monkeypatch.setenv("JIUWENSWARM_EDITION", "personal")
+ assert enterprise_cron_enabled(deployment_mode="standalone") is False
def test_routing_triple_complete() -> None:
diff --git a/tests/unit_tests/gateway/test_enterprise_record_repository.py b/tests/unit_tests/gateway/test_enterprise_record_repository.py
index 9f5dd3d7f1..c1eb148a87 100644
--- a/tests/unit_tests/gateway/test_enterprise_record_repository.py
+++ b/tests/unit_tests/gateway/test_enterprise_record_repository.py
@@ -21,12 +21,12 @@ from jiuwenswarm.gateway.storage_assembly.setup import (
@pytest.mark.asyncio
-async def test_instance_agent_resource_crud_and_scope() -> None:
+async def test_instance_agent_resource_crud() -> None:
store = InMemoryPersistentBackend()
repo = EnterpriseRecordRepository(
store,
"instance_agent_resource",
- instance_id="inst-1",
+ instance_id="",
)
created = await repo.create(
{
@@ -36,7 +36,7 @@ async def test_instance_agent_resource_crud_and_scope() -> None:
"grants": [{"match_expr": "", "enabled": True}],
}
)
- assert created["jiuwenclaw_id"] == "inst-1"
+ assert "jiuwenclaw_id" not in created
assert created["resource_id"] == "bot-main"
got = await repo.get(resource_id="bot-main")
@@ -50,12 +50,6 @@ async def test_instance_agent_resource_crud_and_scope() -> None:
assert updated is not None
assert updated["resource_name"] == "main agent v2"
- other = EnterpriseRecordRepository(
- store,
- "instance_agent_resource",
- instance_id="inst-2",
- )
- assert await other.list() == []
assert await repo.delete(resource_id="bot-main") is True
assert await repo.get(resource_id="bot-main") is None
@@ -129,10 +123,10 @@ async def test_singleton_keypair_no_scope() -> None:
@pytest.mark.asyncio
-async def test_cron_job_repository_scope_and_key() -> None:
+async def test_cron_job_repository_key() -> None:
store = InMemoryPersistentBackend()
repo = create_enterprise_record_repository(
- store, "cron_job", instance_id="inst-1"
+ store, "cron_job", instance_id=""
)
created = await repo.create(
{
@@ -143,7 +137,7 @@ async def test_cron_job_repository_scope_and_key() -> None:
"targets": "web",
}
)
- assert created["jiuwenclaw_id"] == "inst-1"
+ assert "jiuwenclaw_id" not in created
assert created["job_id"] == "job-1"
assert await repo.get(job_id="job-1") is not None
@@ -152,13 +146,13 @@ async def test_cron_job_repository_scope_and_key() -> None:
async def test_task_memory_single_document_sync() -> None:
store = InMemoryPersistentBackend()
repo = EnterpriseRecordRepository(
- store, "task_memory_config", instance_id="inst-1"
+ store, "task_memory_config", instance_id=""
)
await repo.sync_by_business_key([{"enabled": True, "llm_model": "m"}])
body = await repo.get()
assert body is not None
assert body["enabled"] is True
- assert body["jiuwenclaw_id"] == "inst-1"
+ assert "jiuwenclaw_id" not in body
await repo.sync_by_business_key([])
assert await repo.get() is None
diff --git a/tests/unit_tests/gateway/test_instance_scope.py b/tests/unit_tests/gateway/test_instance_scope.py
index 1207251fcb..1ae1c2a79c 100644
--- a/tests/unit_tests/gateway/test_instance_scope.py
+++ b/tests/unit_tests/gateway/test_instance_scope.py
@@ -1,136 +1,27 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""Gateway 企业配置读库相关单测(每网关独立 DB,无实例行级隔离)。"""
from __future__ import annotations
import pytest
-from jiuwenswarm.gateway.config.enterprise.catalog import ENTERPRISE_RECORD_SPECS
-from jiuwenswarm.gateway.config.enterprise.instance_scope import (
- apply_instance_scope,
- instance_scoped_store_names,
- list_records_requires_bound_instance,
- resolve_gateway_instance_id,
- table_requires_instance_scope,
-)
-
-
-def test_instance_scoped_store_names_from_catalog() -> None:
- expected = {
- name
- for name, spec in ENTERPRISE_RECORD_SPECS.items()
- if spec.scope_field == "jiuwenclaw_id"
- }
- assert instance_scoped_store_names() == frozenset(expected)
- assert "cron_job" in instance_scoped_store_names()
- assert "extension_config_template" in instance_scoped_store_names()
- assert "gateway_enc_keypair" not in instance_scoped_store_names()
-
-
-def test_apply_instance_scope_adds_jiuwenclaw_id(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setenv("JIUWENCLAW_ID", "inst-a")
- scoped = apply_instance_scope(
- "extension_config_template",
- {"enabled": True},
- instance_id=resolve_gateway_instance_id(),
- )
- assert scoped == {"enabled": True, "jiuwenclaw_id": "inst-a"}
-
-
-def test_apply_instance_scope_respects_explicit_filter() -> None:
- scoped = apply_instance_scope(
- "model_template",
- {"jiuwenclaw_id": "explicit"},
- instance_id="other",
- )
- assert scoped["jiuwenclaw_id"] == "explicit"
-
-
-def test_apply_instance_scope_skips_global_tables() -> None:
- scoped = apply_instance_scope(
- "gateway_enc_keypair",
- {"id": 1},
- instance_id="inst-a",
- )
- assert scoped == {"id": 1}
-
-
-def test_list_records_requires_bound_instance_fail_closed() -> None:
- assert list_records_requires_bound_instance("cron_job", None) is True
- assert list_records_requires_bound_instance("cron_job", "jid") is False
- assert list_records_requires_bound_instance("channel_config", None) is False
-
-
-def test_resolve_gateway_instance_id_env_precedence(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- monkeypatch.delenv("JIUWENCLAW_ID", raising=False)
- monkeypatch.delenv("JIUWENSWARM_ID", raising=False)
- monkeypatch.delenv("GATEWAY_INSTANCE_ID", raising=False)
- monkeypatch.setenv("JIUWENCLAW_ID", "from-manager")
- monkeypatch.setenv("GATEWAY_INSTANCE_ID", "from-gateway")
- assert resolve_gateway_instance_id({}) == "from-manager"
-
-
-def test_resolve_gateway_instance_id_config_over_env(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- monkeypatch.setenv("JIUWENCLAW_ID", "env-id")
- cfg = {"gateway": {"instance_id": "cfg-id"}}
- assert resolve_gateway_instance_id(cfg) == "cfg-id"
-
-
-def test_resolve_gateway_instance_id_redis_error_falls_back_to_env(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- for key in (
- "JIUWENCLAW_ID",
- "JIUWENSWARM_ID",
- "JIUWENSWARM_PROVISIONED_INSTANCE_ID",
- "JIUWENCLAW_PROVISIONED_INSTANCE_ID",
- ):
- monkeypatch.delenv(key, raising=False)
- monkeypatch.setenv("GATEWAY_INSTANCE_ID", "from-env")
-
- def _boom() -> str:
- raise ConnectionError("redis unavailable")
-
- import jiuwenswarm.extensions.redis.redis_runtime as redis_runtime
-
- monkeypatch.setattr(redis_runtime, "get_gateway_instance_id", _boom)
- assert resolve_gateway_instance_id({}) == "from-env"
-
@pytest.mark.asyncio
-async def test_gateway_db_list_records_fail_closed_without_instance_id(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- from jiuwenswarm.server.runtime.enterprise_config import gateway_db
-
- monkeypatch.delenv("JIUWENCLAW_ID", raising=False)
- monkeypatch.delenv("JIUWENSWARM_ID", raising=False)
- monkeypatch.delenv("GATEWAY_INSTANCE_ID", raising=False)
- monkeypatch.setattr(gateway_db, "resolve_gateway_db_path", lambda: "/tmp/fake.db")
-
- rows = await gateway_db.list_records("extension_config_template", filters={"enabled": True})
- assert rows == []
-
-
-def test_gateway_db_apply_instance_scope_matches_shared_module(
+async def test_gateway_db_list_records_passes_filters(
monkeypatch: pytest.MonkeyPatch,
) -> None:
from jiuwenswarm.server.runtime.enterprise_config import gateway_db
- monkeypatch.setenv("JIUWENCLAW_ID", "sp-demo")
- scoped = gateway_db.apply_instance_scope(
- "skill_whitelist_template",
- {"template_id": "w1"},
- )
- assert scoped["jiuwenclaw_id"] == "sp-demo"
+ monkeypatch.setattr(gateway_db, "use_remote_gateway_db", lambda: False)
+ async def _sqlite(table, query, order_by):
+ assert table == "extension_config_template"
+ assert query == {"enabled": True}
+ return [{"template_id": "t1"}]
-def test_table_requires_instance_scope() -> None:
- assert table_requires_instance_scope("service_config_template") is True
- assert table_requires_instance_scope("permissions_config") is False
+ monkeypatch.setattr(gateway_db, "_list_records_sqlite", _sqlite)
+ rows = await gateway_db.list_records("extension_config_template", filters={"enabled": True})
+ assert rows == [{"template_id": "t1"}]
def test_use_remote_gateway_db_requires_enterprise_edition_and_host(
@@ -168,7 +59,6 @@ async def test_list_records_remote_does_not_fallback_to_sqlite(
monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")
monkeypatch.setenv("GATEWAY_DB_HOST", "db.example")
- monkeypatch.setenv("JIUWENCLAW_ID", "inst-a")
async def _boom(*_a, **_k):
raise RuntimeError("remote down")
diff --git a/tests/unit_tests/gateway/test_log_masking.py b/tests/unit_tests/gateway/test_log_masking.py
index b7a88a3709..a0b696c7b7 100644
--- a/tests/unit_tests/gateway/test_log_masking.py
+++ b/tests/unit_tests/gateway/test_log_masking.py
@@ -201,8 +201,8 @@ async def test_reload_log_masking_rule_db_authoritative_when_rows_present(monkey
@pytest.mark.asyncio
-async def test_reload_log_masking_rule_skips_gdb_without_jiuwenclaw_id(monkeypatch):
- """企业版 ``JIUWENCLAW_ID`` 未就绪时不访问 GDB,保留内置规则。"""
+async def test_reload_log_masking_rule_loads_gdb_without_jiuwenclaw_id(monkeypatch):
+ """企业版不依赖 ``JIUWENCLAW_ID``,直接读本网关 DB。"""
import jiuwenswarm.infrastructure.log_masking.engine as engine_mod
from jiuwenswarm.infrastructure.config import Settings
@@ -217,14 +217,14 @@ async def test_reload_log_masking_rule_skips_gdb_without_jiuwenclaw_id(monkeypat
LogMaskingEngine,
"list_enabled_log_masking_rule_rows",
new_callable=AsyncMock,
+ return_value=[],
) as list_rows,
patch.object(LogMaskingEngine, "reload_from_rows") as reload_from_rows,
):
await LogMaskingEngine.reload_log_masking_rule()
- list_rows.assert_not_called()
- reload_from_rows.assert_not_called()
- assert "******" in LogMaskingEngine.get_instance().sanitize("token=abc123")
+ list_rows.assert_awaited_once()
+ reload_from_rows.assert_called_once_with([], db_authoritative=False)
@pytest.mark.asyncio
diff --git a/tests/unit_tests/gateway/test_section_config_repositories.py b/tests/unit_tests/gateway/test_section_config_repositories.py
index 3147bb21a6..9ceb608415 100644
--- a/tests/unit_tests/gateway/test_section_config_repositories.py
+++ b/tests/unit_tests/gateway/test_section_config_repositories.py
@@ -71,15 +71,15 @@ async def test_permissions_tool_and_rule_helpers() -> None:
async def test_permissions_db_body_roundtrip() -> None:
store = InMemoryPersistentBackend()
repo = PermissionsConfigRepository(
- store, DbBodySectionCodec(), instance_id="inst-1"
+ store, DbBodySectionCodec(), instance_id=""
)
await repo.merge({"enabled": True})
document = await repo.get()
assert document is not None
assert document.body["enabled"] is True
- row = await store.get("permissions_config", {"jiuwenclaw_id": "inst-1"})
- assert row is not None
- assert row["body"]["enabled"] is True
+ rows = await store.list("permissions_config", limit=1)
+ assert rows
+ assert rows[0]["body"]["enabled"] is True
@pytest.mark.asyncio
@@ -98,14 +98,14 @@ async def test_logging_yaml_merge_levels() -> None:
async def test_logging_db_flat_codec() -> None:
store = InMemoryPersistentBackend()
repo = LoggingConfigRepository(
- store, db_logging_codec(), instance_id="inst-1"
+ store, db_logging_codec(), instance_id=""
)
await repo.merge_levels({"level": "ERROR", "full": "DEBUG"})
- row = await store.get("logging_config", {"jiuwenclaw_id": "inst-1"})
- assert row is not None
- assert row["level"] == "ERROR"
- assert row["full"] == "DEBUG"
- assert "body" not in row
+ rows = await store.list("logging_config", limit=1)
+ assert rows
+ assert rows[0]["level"] == "ERROR"
+ assert rows[0]["full"] == "DEBUG"
+ assert "body" not in rows[0]
@pytest.mark.asyncio