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
fix: 企业外置db默认sqlite逻辑优化
wudaweib7c9becf29e7
diff --git a/jiuwenswarm/agents/harness/team/distributed_runtime.py b/jiuwenswarm/agents/harness/team/distributed_runtime.pyindex 683b982cd7..05977b6904 100644--- a/jiuwenswarm/agents/harness/team/distributed_runtime.py+++ b/jiuwenswarm/agents/harness/team/distributed_runtime.py@@ -10,12 +10,42 @@ import asyncioimport copyimport importlib.utilimport logging+import osimport timefrom typing import Anyfrom urllib.parse import urlparselogger = logging.getLogger(__name__)+# Default allow silent PG→sqlite. Set to 0/false/off to refuse (enterprise).+_ENV_ALLOW_SQLITE_FALLBACK = "JIUWENSWARM_ALLOW_SQLITE_FALLBACK"+++class DistributedDependencyError(RuntimeError):+ """Raised when postgresql→sqlite fallback is explicitly disallowed."""+++def _truthy_flag(value: Any) -> bool:+ if isinstance(value, bool):+ return value+ return str(value or "").strip().lower() in {"1", "true", "yes", "on"}+++def _falsy_flag(value: Any) -> bool:+ if isinstance(value, bool):+ return not value+ return str(value or "").strip().lower() in {"0", "false", "no", "off"}+++def _allow_postgresql_to_sqlite() -> bool:+ """Default allow (silent fallback). Refuse only when env explicitly disables."""+ raw = os.environ.get(_ENV_ALLOW_SQLITE_FALLBACK)+ if raw is None or str(raw).strip() == "":+ return True+ if _falsy_flag(raw):+ return False+ return _truthy_flag(raw)+def is_distributed_mode(config_base: dict[str, Any]) -> bool:team_cfg = config_base.get("team", {}) if isinstance(config_base.get("team"), dict) else {}@@ -172,8 +202,31 @@ def missing_distributed_dependencies(config_base: dict[str, Any]) -> list[str]:return missing+def _rewrite_postgresql_storage_or_raise(team_cfg: dict[str, Any]) -> None:+ """Rewrite postgresql→sqlite by default; raise if env explicitly disallows."""+ if not is_postgresql_storage(team_cfg):+ return+ if not _allow_postgresql_to_sqlite():+ raise DistributedDependencyError(+ f"{_ENV_ALLOW_SQLITE_FALLBACK} is false: refusing silent rewrite of "+ "storage.type postgresql→sqlite. Install asyncpg "+ '(pip install -e ".[distribute]" / uv sync --extra distribute), '+ f"or unset / set {_ENV_ALLOW_SQLITE_FALLBACK}=1 for local-dev."+ )+ team_cfg["storage"] = {+ "type": "sqlite",+ "params": {"connection_string": "team.db"},+ }++def fallback_distributed_to_local(config_base: dict[str, Any]) -> dict[str, Any]:- """Create an in-memory local fallback config from distributed config."""+ """Create a local/inprocess fallback config from distributed config.++ Runtime/transport always fall back to local/inprocess. For postgresql+ storage: default remains silent rewrite to sqlite; if+ ``JIUWENSWARM_ALLOW_SQLITE_FALLBACK=0``, raise ``DistributedDependencyError``+ instead (enterprise external-DB boundary). Local sqlite storage is unchanged.+ """normalized = copy.deepcopy(config_base)team_cfg = normalized.get("team", {})@@ -192,11 +245,7 @@ def fallback_distributed_to_local(config_base: dict[str, Any]) -> dict[str, Any]transport_cfg.pop("params", None)team_cfg["transport"] = transport_cfg- if is_postgresql_storage(team_cfg):- team_cfg["storage"] = {- "type": "sqlite",- "params": {"connection_string": "team.db"},- }+ _rewrite_postgresql_storage_or_raise(team_cfg)modes_cfg = normalized.get("modes", {})if isinstance(modes_cfg, dict):@@ -211,11 +260,7 @@ def fallback_distributed_to_local(config_base: dict[str, Any]) -> dict[str, Any]transport_cfg["type"] = "inprocess"transport_cfg.pop("params", None)candidate["transport"] = transport_cfg- if is_postgresql_storage(candidate):- candidate["storage"] = {- "type": "sqlite",- "params": {"connection_string": "team.db"},- }+ _rewrite_postgresql_storage_or_raise(candidate)return normalizeddiff --git a/jiuwenswarm/resources/.env.template b/jiuwenswarm/resources/.env.templateindex 81a709a30e..00f28d6d40 100644--- a/jiuwenswarm/resources/.env.template+++ b/jiuwenswarm/resources/.env.template@@ -162,6 +162,11 @@ GITCODE_ACCESS_TOKEN=# marker. Must be a positive integer; blank/invalid/non-positive falls back to 4096.# JIUWENSWARM_TASK_TEXT_LIMIT=4096+# Distributed Team:配置为 postgresql 但缺少 asyncpg 时,是否允许静默改写为 sqlite。+# 未设置或 =1/true:允许(兼容本地/缺依赖);=0/false:拒绝并抛错(企业外置 DB 推荐)。+# 企业版请用容器/服务进程环境注入,不读取 .env 文件;勿写入 config.team.distributed.*.yaml。+# JIUWENSWARM_ALLOW_SQLITE_FALLBACK=1+# 独立 jiuwenswarm 普通单 Agent 的默认实现;部署到实际 AgentServer 进程后重启。# 优先于 flash.enabled,未设置时回退 config(默认 false);不控制技能检索。# OfficeClaw/PC 前台显式模式、Code、Team、Plan 及已有会话绑定保持原规则。diff --git a/tests/unit_tests/agentserver/test_distributed_runtime.py b/tests/unit_tests/agentserver/test_distributed_runtime.pyindex 4635a51ce2..c72841a013 100644--- a/tests/unit_tests/agentserver/test_distributed_runtime.py+++ b/tests/unit_tests/agentserver/test_distributed_runtime.py@@ -3,11 +3,28 @@import pytestfrom jiuwenswarm.agents.harness.team.distributed_runtime import (+ DistributedDependencyError,+ fallback_distributed_to_local,normalize_distributed_transport_fields,parse_port,)+def _pg_distributed_cfg():+ return {+ "team": {+ "runtime": {"mode": "distributed", "role": "leader"},+ "transport": {"type": "pyzmq", "params": {}},+ "storage": {+ "type": "postgresql",+ "params": {+ "connection_string": "postgresql+asyncpg://u:[email protected]:5432/db",+ },+ },+ }+ }++def test_normalize_leader_applies_pool_policy_when_pubsub_prefilled():"""Leader templates often pre-fill pubsub_*; pool policy must still run."""config_base = {@@ -102,3 +119,42 @@ def test_parse_port_raises_for_non_numeric_value():def test_parse_port_raises_for_out_of_range_value():with pytest.raises(ValueError, match="1\\.\\.65535"):parse_port(70000, 18557, "team.transport.params.leader.sub_port")+++def test_fallback_pg_env_unset_silently_rewrites_to_sqlite(monkeypatch):+ """Unset JIUWENSWARM_ALLOW_SQLITE_FALLBACK keeps legacy silent PG→sqlite."""+ monkeypatch.delenv("JIUWENSWARM_ALLOW_SQLITE_FALLBACK", raising=False)+ out = fallback_distributed_to_local(_pg_distributed_cfg())+ assert out["team"]["runtime"]["mode"] == "local"+ assert out["team"]["transport"]["type"] == "inprocess"+ assert out["team"]["storage"]["type"] == "sqlite"+ assert out["team"]["storage"]["params"]["connection_string"] == "team.db"+++def test_fallback_pg_env_true_rewrites_to_sqlite(monkeypatch):+ monkeypatch.setenv("JIUWENSWARM_ALLOW_SQLITE_FALLBACK", "1")+ out = fallback_distributed_to_local(_pg_distributed_cfg())+ assert out["team"]["storage"]["type"] == "sqlite"+++def test_fallback_pg_env_false_raises(monkeypatch):+ monkeypatch.setenv("JIUWENSWARM_ALLOW_SQLITE_FALLBACK", "0")+ with pytest.raises(DistributedDependencyError, match="JIUWENSWARM_ALLOW_SQLITE_FALLBACK is false"):+ fallback_distributed_to_local(_pg_distributed_cfg())+++def test_fallback_local_sqlite_storage_unchanged():+ cfg = {+ "team": {+ "runtime": {"mode": "distributed", "role": "leader"},+ "transport": {"type": "pyzmq"},+ "storage": {+ "type": "sqlite",+ "params": {"connection_string": "keep-me.db"},+ },+ }+ }+ out = fallback_distributed_to_local(cfg)+ assert out["team"]["runtime"]["mode"] == "local"+ assert out["team"]["storage"]["type"] == "sqlite"+ assert out["team"]["storage"]["params"]["connection_string"] == "keep-me.db"