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:添加经验自演进开关

Zql9925f2682bc5d4
diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.py
index 68977be770..a2a2b16d02 100644
--- a/jiuwenswarm/common/config.py
+++ b/jiuwenswarm/common/config.py
@@ -928,6 +928,21 @@ def update_evolution_enabled_in_config(value: bool) -> None:
dump_yaml_round_trip(_current_config_yaml_path(), data)
+def update_ttse_enabled_in_config(value: bool) -> None:
+ """更新 react.ttse.enabled(经验自演进 / TTSE 总开关)并写回用户 override。"""
+ data = load_yaml_round_trip(_current_config_yaml_path())
+ react = data.get("react")
+ if not isinstance(react, dict):
+ react = {}
+ data["react"] = react
+ ttse = react.get("ttse")
+ if not isinstance(ttse, dict):
+ ttse = {}
+ react["ttse"] = ttse
+ ttse["enabled"] = value
+ dump_yaml_round_trip(_current_config_yaml_path(), data)
+
+
def update_context_engine_enabled_in_config(value: bool) -> None:
"""更新 react.context_engine_config.enabled(上下文压缩开关)并写回。"""
data = load_yaml_round_trip(_current_config_yaml_path())
diff --git a/jiuwenswarm/common/local_env_config.py b/jiuwenswarm/common/local_env_config.py
index 5e45b178ee..fd8866339d 100644
--- a/jiuwenswarm/common/local_env_config.py
+++ b/jiuwenswarm/common/local_env_config.py
@@ -109,6 +109,7 @@ BUSINESS_MIRROR_KEYS: frozenset[str] = frozenset(
"API_BASE",
"MEMORY_ENGINE",
"EVOLUTION_ENABLED",
+ "TTSE_ENABLED",
"EMBED_API_KEY",
"EMBED_API_BASE",
"EMBED_MODEL",
diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
index 4fdb3be8c5..c5a55a0c1c 100644
--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
@@ -47,10 +47,12 @@ from jiuwenswarm.common.config import (
get_config_raw,
get_default_models,
get_evolution_enabled,
+ get_ttse_enabled,
resolve_legacy_team_model_ref,
replace_teams_in_config,
update_default_models_in_config,
update_evolution_enabled_in_config,
+ update_ttse_enabled_in_config,
update_context_engine_enabled_in_config,
update_default_model_provider_in_config,
update_kv_cache_affinity_enabled_in_config,
@@ -958,6 +960,7 @@ CONFIG_KEYS = tuple(_CONFIG_SET_ENV_MAP.keys())
# 来自 config.yaml 的配置项(前端 param 名 -> config.yaml 路径)
_CONFIG_YAML_KEYS = frozenset({
"evolution_enabled",
+ "ttse_enabled",
"context_engine_enabled",
"kv_cache_release_enabled",
"kv_cache_affinity_enabled",
@@ -2327,6 +2330,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
# skill_create: tip 优先,fallback to config.yaml
evolution_cfg = (raw.get("react") or {}).get("evolution") or {}
payload["evolution_enabled"] = "true" if get_evolution_enabled(raw) else "false"
+ payload["ttse_enabled"] = "true" if get_ttse_enabled(raw) else "false"
skill_create_env = read_env_if_set("SKILL_CREATE")
if skill_create_env is not None:
payload["skill_create"] = "true" if skill_create_env.lower() in ("true", "1", "yes") else "false"
@@ -2364,6 +2368,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
payload.setdefault("setup_guide_enabled", "true")
payload.setdefault("trajectory_ui_enabled", "false")
payload.setdefault("evolution_enabled", "true")
+ payload.setdefault("ttse_enabled", "true")
payload.setdefault("skill_create", "false")
payload.setdefault("memory_forbidden_enabled", "false")
payload.setdefault("memory_forbidden_description", "")
@@ -2551,6 +2556,8 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
try:
if param_key == "evolution_enabled":
update_evolution_enabled_in_config(parsed)
+ elif param_key == "ttse_enabled":
+ update_ttse_enabled_in_config(parsed)
elif param_key == "context_engine_enabled":
update_context_engine_enabled_in_config(parsed)
elif param_key == "kv_cache_release_enabled":
diff --git a/jiuwenswarm/perf/evolution_rail_short_circuit.py b/jiuwenswarm/perf/evolution_rail_short_circuit.py
index 3cd07e67a7..028b22b4b0 100644
--- a/jiuwenswarm/perf/evolution_rail_short_circuit.py
+++ b/jiuwenswarm/perf/evolution_rail_short_circuit.py
@@ -1,11 +1,14 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.
-"""[PERF 实验] symphony 关闭时短路 evolution rail 轨迹采集。
+"""[PERF 实验] 企业版 + symphony 关闭时短路 evolution rail 轨迹 drain。
实测(py-spy, N=1 连续轮次): EvolutionRail.after_model_call 占回合时间 ~40%
(drain/enrich/merge 轨迹管道),而 symphony.enabled=false 时这些数据无处可去。
-本补丁在 symphony 主开关关闭时将 after_model_call / after_tool_call /
-after_task_iteration 短路为 no-op,用于量化验证;生产化修复应在核心侧
-"未启用即不订阅"。
+本补丁仅在企业版生效;个人版不短路,保证自演进轨迹路径完整。
+企业版在 symphony 主开关关闭时将 after_model_call / after_tool_call /
+after_task_iteration 短路为 no-op;生产化修复应在核心侧"未启用即不订阅"。
+
+注意: 不可短路 before_invoke —— SkillEvolutionRail 依赖其订阅轨迹,
+短路会导致 after_invoke 时 trajectory=None、自演进无法触发。
"""
import logging
@@ -19,6 +22,14 @@ def apply_evolution_rail_short_circuit() -> None:
global _APPLIED
if _APPLIED:
return
+
+ from jiuwenswarm.edition import is_enterprise
+
+ if not is_enterprise():
+ _APPLIED = True
+ logger.info("[evolution_short_circuit] 个人版跳过: 不短路 evolution rail")
+ return
+
try:
from openjiuwen.harness.rails.evolution.evolution_rail import EvolutionRail
except Exception: # noqa: BLE001 - 核心无该 rail 时静默跳过
@@ -32,7 +43,7 @@ def apply_evolution_rail_short_circuit() -> None:
cfg = load_symphony_config()
if not cfg.enabled:
- return None # symphony 未启用:轨迹采集短路
+ return None # symphony 未启用:轨迹 drain 短路
except Exception: # noqa: BLE001 - 判定失败走原路径
pass
return await orig(self, ctx)
@@ -40,8 +51,9 @@ def apply_evolution_rail_short_circuit() -> None:
_short_circuited.__name__ = name
return _short_circuited
+ # 不短路 before_invoke:技能自演进依赖其订阅轨迹;
+ # symphony 关闭时仍短路 drain 路径以省回合时延。
for _name in (
- "before_invoke", # 订阅轨迹 span:每事件序列化(to_json_compatible/_copy_json)的源头
"after_model_call",
"after_tool_call",
"after_task_iteration",
@@ -50,4 +62,4 @@ def apply_evolution_rail_short_circuit() -> None:
if _orig is not None:
setattr(EvolutionRail, _name, _make_short_circuited(_name, _orig))
_APPLIED = True
- logger.info("[evolution_short_circuit] 已应用: symphony 关闭时跳过轨迹采集")
+ logger.info("[evolution_short_circuit] 已应用(企业版): symphony 关闭时跳过轨迹 drain")
diff --git a/jiuwenswarm/server/app_agentserver.py b/jiuwenswarm/server/app_agentserver.py
index d783d55b9e..985a964331 100644
--- a/jiuwenswarm/server/app_agentserver.py
+++ b/jiuwenswarm/server/app_agentserver.py
@@ -148,7 +148,7 @@ from jiuwenswarm.llm_sse_patch import apply_openai_sse_invoke_patch
apply_openai_sse_invoke_patch()
-# [PERF 实验] symphony 关闭时短路 evolution rail 轨迹采集(实测占回合 ~40%)
+# [PERF 实验] 企业版 + symphony 关闭时短路 evolution rail 轨迹 drain
from jiuwenswarm.perf.evolution_rail_short_circuit import (
apply_evolution_rail_short_circuit,
)
diff --git a/jiuwenswarm/server/runtime/sync_agents_configs.py b/jiuwenswarm/server/runtime/sync_agents_configs.py
index 30ee58bb1e..09a23e7535 100644
--- a/jiuwenswarm/server/runtime/sync_agents_configs.py
+++ b/jiuwenswarm/server/runtime/sync_agents_configs.py
@@ -25,6 +25,7 @@ SYNC_ENV_SCHEMA: frozenset[str] = frozenset(
"API_BASE",
"MEMORY_ENGINE",
"EVOLUTION_ENABLED",
+ "TTSE_ENABLED",
"EMBED_API_KEY",
"EMBED_API_BASE",
"EMBED_MODEL",
@@ -135,16 +136,43 @@ def _ensure_react_evolution_dict(result: dict[str, Any]) -> dict[str, Any]:
return evolution
+def _ensure_react_ttse_dict(result: dict[str, Any]) -> dict[str, Any]:
+ """Prefer config.react.ttse; migrate bare config.ttse into react when needed."""
+ react = result.get("react")
+ if not isinstance(react, dict):
+ react = {}
+ result["react"] = react
+ ttse = react.get("ttse")
+ if not isinstance(ttse, dict):
+ top = result.pop("ttse", None)
+ ttse = top if isinstance(top, dict) else {}
+ react["ttse"] = ttse
+ else:
+ top = result.pop("ttse", None)
+ if isinstance(top, dict) and top:
+ logger.warning(
+ "sync_agents_configs: discarding top-level ttse=%r; "
+ "react.ttse takes precedence",
+ top,
+ )
+ return ttse
+
+
def synthesize_config(
config: Any,
env: dict[str, Any] | None = None,
) -> dict[str, Any]:
- """Materialize memory/evolution into config; protocol authority is env.
+ """Materialize memory/evolution/ttse into config; protocol authority is env.
- Writes ``config.memory.engine`` and ``config.react.evolution`` from
+ Writes ``config.memory.engine`` and ``config.react.evolution.enabled`` from
``MEMORY_ENGINE`` / ``EVOLUTION_ENABLED``. Mis-sent config blocks are
overlaid from env (warn). When env values are blank/absent, falls back to
existing config then defaults (``builtin`` / ``enabled=false``).
+
+ ``react.ttse.enabled`` is set only when inbound config or ``TTSE_ENABLED``
+ is explicit. Omitting the key keeps sparse sync snapshots compatible with
+ ``_merge_ttse_config`` (runtime wins only when present; otherwise disk /
+ template default applies — shipped template defaults to ``true``).
"""
if not isinstance(config, dict):
raise ValueError("agent config must be an object")
@@ -156,15 +184,22 @@ def synthesize_config(
inbound_engine = str(mem_in.get("engine")).strip().lower()
inbound_evo: bool | None = None
+ inbound_ttse: bool | None = None
react_in = config.get("react")
if isinstance(react_in, dict) and isinstance(react_in.get("evolution"), dict):
if "enabled" in react_in["evolution"]:
inbound_evo = bool(react_in["evolution"].get("enabled"))
elif isinstance(config.get("evolution"), dict) and "enabled" in config["evolution"]:
inbound_evo = bool(config["evolution"].get("enabled"))
+ if isinstance(react_in, dict) and isinstance(react_in.get("ttse"), dict):
+ if "enabled" in react_in["ttse"]:
+ inbound_ttse = bool(react_in["ttse"].get("enabled"))
+ elif isinstance(config.get("ttse"), dict) and "enabled" in config["ttse"]:
+ inbound_ttse = bool(config["ttse"].get("enabled"))
memory = _ensure_memory_dict(result)
evolution = _ensure_react_evolution_dict(result)
+ ttse = _ensure_react_ttse_dict(result)
engine = (
inbound_engine
@@ -172,6 +207,8 @@ def synthesize_config(
else "builtin"
)
evo_enabled = bool(inbound_evo) if inbound_evo is not None else False
+ # None = leave key absent so _merge_ttse_config inherits on-disk default.
+ ttse_enabled: bool | None = bool(inbound_ttse) if inbound_ttse is not None else None
if isinstance(env, dict):
env_engine_raw = env.get("MEMORY_ENGINE")
@@ -205,8 +242,21 @@ def synthesize_config(
)
evo_enabled = env_evo
+ env_ttse = _env_bool(env.get("TTSE_ENABLED"))
+ if env_ttse is not None:
+ if inbound_ttse is not None and inbound_ttse != env_ttse:
+ logger.warning(
+ "sync_agents_configs: TTSE_ENABLED env=%r overlays "
+ "mis-sent config enabled=%r",
+ env.get("TTSE_ENABLED"),
+ inbound_ttse,
+ )
+ ttse_enabled = env_ttse
+
memory["engine"] = engine
evolution["enabled"] = evo_enabled
+ if ttse_enabled is not None:
+ ttse["enabled"] = ttse_enabled
return result
diff --git a/tests/unit_tests/agentserver/test_sync_agents_configs.py b/tests/unit_tests/agentserver/test_sync_agents_configs.py
index 35dff6e611..b63bc6de5c 100644
--- a/tests/unit_tests/agentserver/test_sync_agents_configs.py
+++ b/tests/unit_tests/agentserver/test_sync_agents_configs.py
@@ -15,6 +15,7 @@ from jiuwenswarm.server.runtime.sync_agents_configs import (
build_agent_spec,
compute_content_hash,
materialize_sync_env,
+ synthesize_config,
validate_sync_payload,
)
from jiuwenswarm.server.runtime.tenant_agent_pool import TenantAgentPool
@@ -421,12 +422,103 @@ class TestSyncAgentsConfigsValidation:
}
)
+ @staticmethod
+ def test_ttse_enabled_required_like_evolution():
+ """TTSE_ENABLED is a required SYNC_ENV_SCHEMA key (same as EVOLUTION_ENABLED)."""
+ assert "TTSE_ENABLED" in SYNC_ENV_SCHEMA
+ assert "EVOLUTION_ENABLED" in SYNC_ENV_SCHEMA
+ env = _full_env()
+ del env["TTSE_ENABLED"]
+ with pytest.raises(ValueError, match="TTSE_ENABLED"):
+ validate_sync_payload(
+ {
+ "revision": "r1",
+ "service_id": "default",
+ "agents": [
+ {
+ "agent_id": "office",
+ "config": {},
+ "env": env,
+ "runtime": {},
+ }
+ ],
+ }
+ )
+
@staticmethod
def test_materialize_omits_null_keeps_empty():
env = materialize_sync_env({"API_KEY": "k", "MODEL_NAME": None, "API_BASE": ""})
assert env == {"API_KEY": "k", "API_BASE": ""}
+class TestSynthesizeTtseConfig:
+ """TTSE materialization: env wins when set; omit enabled when sparse."""
+
+ @staticmethod
+ def test_env_and_config_materialize_enabled():
+ out = synthesize_config(
+ {"react": {"ttse": {"enabled": False, "evolve_enabled": True}}},
+ {"TTSE_ENABLED": "true"},
+ )
+ assert out["react"]["ttse"]["enabled"] is True
+ assert out["react"]["ttse"]["evolve_enabled"] is True
+
+ @staticmethod
+ def test_env_overlays_config_with_warning(caplog):
+ import logging
+
+ with caplog.at_level(logging.WARNING, logger="jiuwenswarm.server.runtime.sync_agents_configs"):
+ out = synthesize_config(
+ {"react": {"ttse": {"enabled": True}}},
+ {"TTSE_ENABLED": "false"},
+ )
+ assert out["react"]["ttse"]["enabled"] is False
+ assert any("TTSE_ENABLED" in r.message for r in caplog.records)
+
+ @staticmethod
+ def test_sparse_inbound_omits_enabled_key():
+ """No ttse / no TTSE_ENABLED → do not write enabled:false (inherit disk)."""
+ out = synthesize_config({"react": {"evolution": {"enabled": True}}}, None)
+ ttse = out["react"].get("ttse") or {}
+ assert "enabled" not in ttse
+
+ @staticmethod
+ def test_top_level_ttse_migrates_into_react():
+ out = synthesize_config(
+ {"ttse": {"enabled": True, "inject_enabled": False}},
+ None,
+ )
+ assert "ttse" not in out
+ assert out["react"]["ttse"]["enabled"] is True
+ assert out["react"]["ttse"]["inject_enabled"] is False
+
+ @staticmethod
+ def test_react_ttse_wins_over_top_level(caplog):
+ import logging
+
+ with caplog.at_level(logging.WARNING, logger="jiuwenswarm.server.runtime.sync_agents_configs"):
+ out = synthesize_config(
+ {
+ "react": {"ttse": {"enabled": True}},
+ "ttse": {"enabled": False},
+ },
+ None,
+ )
+ assert out["react"]["ttse"]["enabled"] is True
+ assert "ttse" not in out
+ assert any("top-level ttse" in r.message for r in caplog.records)
+
+ @staticmethod
+ def test_explicit_config_without_env():
+ out = synthesize_config({"react": {"ttse": {"enabled": True}}}, None)
+ assert out["react"]["ttse"]["enabled"] is True
+
+
+# ---------------------------------------------------------------------------
+# async sync_agents_configs integration
+# ---------------------------------------------------------------------------
+
+
@pytest.mark.asyncio
async def test_sync_first_adds_agents_registry_contains(mock_warmup):
pool = TenantAgentPool.get_instance()
diff --git a/tests/unit_tests/test_app_web_handlers.py b/tests/unit_tests/test_app_web_handlers.py
index fd44105d8b..c4f1709e9d 100644
--- a/tests/unit_tests/test_app_web_handlers.py
+++ b/tests/unit_tests/test_app_web_handlers.py
@@ -736,6 +736,58 @@ async def test_config_set_persists_evolution_enabled(monkeypatch):
}
+async def test_config_set_persists_ttse_enabled(monkeypatch):
+ channel = FakeWebChannel()
+ persisted: list[bool] = []
+ reload_options_seen: list[dict] = []
+
+ monkeypatch.setattr(
+ app_web_handlers,
+ "get_config_raw",
+ lambda: {"react": {"ttse": {"enabled": True}}},
+ )
+ monkeypatch.setattr(
+ app_web_handlers,
+ "get_config",
+ lambda: {"react": {"ttse": {"enabled": False}}},
+ )
+ monkeypatch.setattr(
+ app_web_handlers,
+ "update_ttse_enabled_in_config",
+ lambda enabled: persisted.append(enabled),
+ )
+
+ async def on_config_saved(updated_keys, *, env_updates, config_payload, reload_options):
+ del updated_keys, env_updates, config_payload
+ reload_options_seen.append(dict(reload_options))
+ return True
+
+ _register_web_handlers(
+ WebHandlersBindParams(
+ channel=channel,
+ on_config_saved=on_config_saved,
+ )
+ )
+
+ await channel.methods["config.set"](
+ object(),
+ "req-ttse-enabled",
+ {"ttse_enabled": "false"},
+ "sess-ttse-enabled",
+ )
+
+ assert persisted == [False]
+ assert reload_options_seen == [{
+ "target_channel_id": "web",
+ "reload_scopes": ["agent_runtime"],
+ }]
+ assert channel.responses[-1]["payload"] == {
+ "updated": ["ttse_enabled"],
+ "applied_without_restart": True,
+ }
+
+
@pytest.mark.asyncio
async def test_models_replace_all_applies_scoped_reload_before_responding(monkeypatch):
channel = FakeWebChannel()
diff --git a/tests/unit_tests/test_config.py b/tests/unit_tests/test_config.py
index 8543328733..9e52f77611 100644
--- a/tests/unit_tests/test_config.py
+++ b/tests/unit_tests/test_config.py
@@ -26,6 +26,7 @@ from jiuwenswarm.common.config import (
update_skill_retrieval_in_config,
update_setup_guide_enabled_in_config,
update_evolution_enabled_in_config,
+ update_ttse_enabled_in_config,
update_xiaoyi_runtime_in_config,
)
@@ -172,6 +173,19 @@ class TestConfigFunctions:
assert raw["react"]["evolution"]["enabled"] is False
assert get_evolution_enabled(raw) is False
+ @staticmethod
+ def test_update_ttse_enabled_in_config(
+ monkeypatch: pytest.MonkeyPatch,
+ temp_config_file: Path,
+ ):
+ monkeypatch.setattr("jiuwenswarm.common.config.get_config_file", lambda: temp_config_file)
+
+ update_ttse_enabled_in_config(False)
+
+ raw = yaml.safe_load(temp_config_file.read_text(encoding="utf-8"))
+ assert raw["react"]["ttse"]["enabled"] is False
+ assert get_ttse_enabled(raw) is False
+
@pytest.mark.parametrize(
("config", "expected"),
[