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(flash): flash模式适配技能自演进

qwqssqwq7942e0b453e7
diff --git a/.env.example b/.env.example
index f20846366c..1aabb396c3 100644
--- a/.env.example
+++ b/.env.example
@@ -14,6 +14,16 @@
# config.yaml: skill_selection.enabled: ${JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED:-false}
# JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED=false
+# Flash 技能自演进独立开关,不继承 react.evolution 全局开关。
+# 设置 true/false 覆盖 flash.evolution.enabled;未设置默认 false(在线演进不开启)。
+# config.yaml: evolution.enabled: ${JIUWENSWARM_FLASH_EVOLUTION_ENABLED:-false}
+# JIUWENSWARM_FLASH_EVOLUTION_ENABLED=false
+
+# Flash SkillSleep 独立开关;rail 常驻,训练是否执行仍看技能级 selfEvolution。
+# 设置 true/false 覆盖 flash.evolution.skill_sleep.enabled;未设置默认 true。
+# config.yaml: evolution.skill_sleep.enabled: ${JIUWENSWARM_FLASH_SKILL_SLEEP_ENABLED:-true}
+# JIUWENSWARM_FLASH_SKILL_SLEEP_ENABLED=true
+
# Enterprise Claw Manager / Gateway manager_ws_client examples
# =============================================================================
# MANAGER CONFIGURATION
diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.py
index c40284c8f3..b5854d5932 100644
--- a/jiuwenswarm/common/config.py
+++ b/jiuwenswarm/common/config.py
@@ -164,19 +164,23 @@ def _normalize_flash_config(config: dict[str, Any]) -> None:
flash = config.get("flash")
if not isinstance(flash, dict):
return
+ evolution = flash.get("evolution")
+ skill_sleep = evolution.get("skill_sleep") if isinstance(evolution, dict) else None
switches = (
- (flash, "JIUWENSWARM_FLASH_ENABLED"),
- (flash.get("skill_selection"), "JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED"),
+ (flash, "JIUWENSWARM_FLASH_ENABLED", False),
+ (flash.get("skill_selection"), "JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED", False),
+ (evolution, "JIUWENSWARM_FLASH_EVOLUTION_ENABLED", False),
+ (skill_sleep, "JIUWENSWARM_FLASH_SKILL_SLEEP_ENABLED", True),
)
- for section, env_name in switches:
+ for section, env_name, default_value in switches:
if not isinstance(section, dict):
continue
- value = section.get("enabled", False)
+ value = section.get("enabled", default_value)
if isinstance(value, bool):
# 旧 YAML / provider 的布尔值仅作回退;复用与模板相同的占位符解析。
default = str(value).lower()
value = resolve_env_vars("${" + env_name + ":-" + default + "}")
- section["enabled"] = coerce_config_bool(value, default=False)
+ section["enabled"] = coerce_config_bool(value, default=default_value)
def resolve_config_env_vars(config: dict[str, Any]) -> dict[str, Any]:
diff --git a/jiuwenswarm/common/docs/specs/S_08_config-and-environment.md b/jiuwenswarm/common/docs/specs/S_08_config-and-environment.md
index b6f6dbcdbe..201373bff1 100644
--- a/jiuwenswarm/common/docs/specs/S_08_config-and-environment.md
+++ b/jiuwenswarm/common/docs/specs/S_08_config-and-environment.md
@@ -88,11 +88,17 @@ Default)要配置源,否则合并 YAML 模板 + 用户 override 并经 `reso
保留原规则。`flash` 保留独立 canonical,并纳入单 Agent 轨迹白名单;尚未实现的
`flash.*` 在此入口拒绝。续接结合已存 `mode` 与 `adapter_mode` 恢复,保证前台准备与租户池二次解析一致;活跃 Plan 与中断归属优先于新的默认模式。
-- **N16 Flash 配置占位符**:模板的 `flash.enabled` 与
- `flash.skill_selection.enabled` 分别引用 `${JIUWENSWARM_FLASH_ENABLED:-false}`
- 与 `${JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED:-false}`;两变量属于 Track A,
+- **N16 Flash 配置占位符**:模板的 `flash.enabled`、
+ `flash.skill_selection.enabled`、`flash.evolution.enabled` 与
+ `flash.evolution.skill_sleep.enabled` 分别引用
+ `${JIUWENSWARM_FLASH_ENABLED:-false}`、
+ `${JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED:-false}`、
+ `${JIUWENSWARM_FLASH_EVOLUTION_ENABLED:-false}` 与
+ `${JIUWENSWARM_FLASH_SKILL_SLEEP_ENABLED:-true}`;四变量属于 Track A,
沙箱启动注入后经统一配置加载解析,`get_config()` 返回布尔值,消费方不再直读环境。
- 旧 YAML / provider 中的布尔值在运行时作为同名占位符的默认值,环境变量可双向覆盖;
+ Flash 在线技能自演进不继承 `react.evolution` 全局开关,默认关闭;SkillSleep
+ 独立常驻默认开启,训练是否执行仍由技能级 `selfEvolution` 决定。旧 YAML /
+ provider 中的布尔值在运行时作为同名占位符的默认值,环境变量可双向覆盖;
未注入时保留原布尔配置。非法字符串关闭开关,不改变其它字段的字符串解析语义。
配置文件、实例创建/热更新快照及预热均通过 `resolve_config_env_vars` 统一解析。
原始 YAML、合并缓存及 provider 输入保持不变;重启或清理配置缓存后重新解析。
diff --git a/jiuwenswarm/common/local_env_config.py b/jiuwenswarm/common/local_env_config.py
index fefbcc0809..fe4e647e6d 100644
--- a/jiuwenswarm/common/local_env_config.py
+++ b/jiuwenswarm/common/local_env_config.py
@@ -85,6 +85,8 @@ SPAWN_ENV_KEYS: frozenset[str] = frozenset(
# Flash 部署开关由 config.yaml 占位符读取,任务 overlay 不应屏蔽沙箱启动值。
"JIUWENSWARM_FLASH_ENABLED",
"JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED",
+ "JIUWENSWARM_FLASH_EVOLUTION_ENABLED",
+ "JIUWENSWARM_FLASH_SKILL_SLEEP_ENABLED",
# HTTP/SSE service-to-service mTLS. These values are process-scoped;
# certificate paths point to files mounted by the deployment layer.
"JIUWENSWARM_LINK_MTLS_MODE",
diff --git a/jiuwenswarm/resources/.env.template b/jiuwenswarm/resources/.env.template
index 98bcc965f7..c4aa4b6508 100644
--- a/jiuwenswarm/resources/.env.template
+++ b/jiuwenswarm/resources/.env.template
@@ -179,3 +179,13 @@ GITCODE_ACCESS_TOKEN=
# 只覆盖运行时生效值,不改写 config 文件;同样须注入 AgentServer 进程并重启。
# config.yaml: skill_selection.enabled: ${JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED:-false}
# JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED=false
+
+# Flash 技能自演进独立开关,不继承 react.evolution 全局开关。
+# 设置 true/false 覆盖 flash.evolution.enabled;未设置默认 false(在线演进不开启)。
+# config.yaml: evolution.enabled: ${JIUWENSWARM_FLASH_EVOLUTION_ENABLED:-false}
+# JIUWENSWARM_FLASH_EVOLUTION_ENABLED=false
+
+# Flash SkillSleep 独立开关;rail 常驻,训练是否执行仍看技能级 selfEvolution。
+# 设置 true/false 覆盖 flash.evolution.skill_sleep.enabled;未设置默认 true。
+# config.yaml: evolution.skill_sleep.enabled: ${JIUWENSWARM_FLASH_SKILL_SLEEP_ENABLED:-true}
+# JIUWENSWARM_FLASH_SKILL_SLEEP_ENABLED=true
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index f68c3cb592..498392bdf2 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -1837,6 +1837,15 @@ flash:
enabled: ${JIUWENSWARM_FLASH_ENABLED:-false}
# 必须在模板声明:启动清理及配置合并会删除模板中不存在的字段。
# 模块可独立删除;这些默认值不启用功能,也不影响其他 Agent mode。
+ # Flash 专属受限技能自演进开关:
+ # evolution.enabled=false(默认)— Flash 不挂在线被动演进 / HITL 审批 rail,
+ # 不继承全局 react.evolution.enabled,避免升级后静默开启。
+ # evolution.skill_sleep.enabled=true(默认)— 保持 Deep 的 SkillSleep 常驻契约,
+ # 是否离线训练仍由技能级 selfEvolution 决定;两者独立。
+ evolution:
+ enabled: ${JIUWENSWARM_FLASH_EVOLUTION_ENABLED:-false}
+ skill_sleep:
+ enabled: ${JIUWENSWARM_FLASH_SKILL_SLEEP_ENABLED:-true}
skill_selection:
enabled: ${JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED:-false}
catalog_check_interval_s: 5.0
diff --git a/jiuwenswarm/server/handlers/_shared.py b/jiuwenswarm/server/handlers/_shared.py
index d41f6a38d4..98ca94d7f4 100644
--- a/jiuwenswarm/server/handlers/_shared.py
+++ b/jiuwenswarm/server/handlers/_shared.py
@@ -192,8 +192,9 @@ def resolve_agent_request_mode(
OfficeClaw 前台入口传入 ``allow_flash_default=False``,仅接受显式选型。
注:cron / heartbeat / proactive 等后台流水线若发 agent 类 mode,同样会被
- 归到 flash——flash 保留 filesystem / bash / skill / 子代理能力,仅裁掉
- memory 巩固与 skill 演进(flash 设计即关),单次执行无破坏性,故不单独排除。
+ 归到 flash——flash 保留 filesystem / bash / skill / 子代理能力,裁掉
+ memory 巩固;技能自演进按部署配置受限启用(不含 skill_create /
+ review follow-up),单次执行无破坏性,故不单独排除。
"""
raw_value = getattr(raw_mode, "value", raw_mode)
mode_text = raw_value.strip().lower() if isinstance(raw_value, str) else ""
diff --git a/jiuwenswarm/server/runtime/agent_adapter/evolution_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/evolution_helpers.py
index b5677fa7a2..0b3632c466 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/evolution_helpers.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/evolution_helpers.py
@@ -650,9 +650,15 @@ def resolve_evolution_event_timeout_sec(
def is_evolution_approval_event(evt: Any) -> bool:
+ payload = event_payload_dict(evt)
+ meta = evolution_meta_from_payload(payload)
+ event_kind = meta.get("event_kind")
+ if isinstance(event_kind, str) and event_kind:
+ return event_kind == "approval"
+ # Legacy rail events predate ``_evolution_meta.event_kind``; preserve their
+ # approval transport compatibility. Explicit non-approval metadata above wins.
if event_type(evt) == "chat.ask_user_question":
return True
- payload = event_payload_dict(evt)
return payload.get("event_type") == "chat.ask_user_question"
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 69aaf380b4..0ac0df4eae 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -1184,6 +1184,14 @@ class JiuWenSwarmDeepAdapter:
self._avatar_rail: Any = None
self._tool_cards = None
self._evolution_watcher_tasks: set[asyncio.Task] = set()
+ # Active passive-evolution watcher ownership by (channel_id, session_id).
+ # A resumed request gets a new request-id; the old paused stream's watcher
+ # must be superseded instead of idling until the host timeout.
+ self._evolution_watchers: dict[tuple[str, str], asyncio.Task] = {}
+ # SkillSleep background tasks are tracked separately from passive-evolution
+ # watchers so disabling the evolution switch can stop sleep work without
+ # broadening watcher teardown semantics.
+ self._skill_sleep_tasks: set[asyncio.Task] = set()
self._ttse_cleanup_tasks: set[asyncio.Task] = set()
self._sys_operation = None
self._sys_operation_card: SysOperationCard | None = None
@@ -6619,9 +6627,130 @@ class JiuWenSwarmDeepAdapter:
)
def _track_skill_sleep_task(self, task: asyncio.Task) -> None:
- """Track background sleep tasks with evolution watcher set."""
+ """Track background sleep tasks with the adapter without watcher teardown."""
+ sleep_tasks = getattr(self, "_skill_sleep_tasks", None)
+ if sleep_tasks is None:
+ sleep_tasks = set()
+ self._skill_sleep_tasks = sleep_tasks
+ sleep_tasks.add(task)
+ watcher_tasks = getattr(self, "_evolution_watcher_tasks", None)
+ if watcher_tasks is None:
+ watcher_tasks = set()
+ self._evolution_watcher_tasks = watcher_tasks
+ watcher_tasks.add(task)
+ task.add_done_callback(self._on_skill_sleep_task_done)
+
+ def _start_evolution_watcher(
+ self,
+ rid: str,
+ cid: str,
+ session_id: str,
+ ) -> asyncio.Task | None:
+ """Start a passive-evolution watcher owned by channel and session.
+
+ Permission-approved continuation streams use a new request-id. When that
+ continuation reaches stream completion, this method supersedes the old
+ paused request's watcher instead of leaving its idle timer running until
+ timeout. Ownership is scoped to ``(channel_id, session_id)``. Supersession
+ stops only the old watcher; it does not cancel the shared rail's pending
+ evolution work, which may still be serving unrelated sessions.
+ """
+ if self._skill_evolution_rail is None:
+ return None
+
+ key = (str(cid), str(session_id))
+ watchers = getattr(self, "_evolution_watchers", None)
+ if watchers is None:
+ watchers = {}
+ self._evolution_watchers = watchers
+ old_task = watchers.get(key)
+ if old_task is not None and not old_task.done():
+ # The flag is read by the watcher's cancellation handler. A route
+ # handoff must not call ``cancel_pending_evolution()`` because that
+ # SDK method cancels all background tasks on the shared rail.
+ old_task._evolution_watcher_graceful = True # pylint: disable=protected-access
+ old_task.cancel()
+
+ task = asyncio.create_task(self._watch_evolution_and_push(rid, cid, session_id))
+ watchers[key] = task
task.add_done_callback(self._on_evolution_watcher_done)
- self._evolution_watcher_tasks.add(task)
+ watcher_tasks = getattr(self, "_evolution_watcher_tasks", None)
+ if watcher_tasks is None:
+ watcher_tasks = set()
+ self._evolution_watcher_tasks = watcher_tasks
+ watcher_tasks.add(task)
+ return task
+
+ async def _cancel_evolution_watchers(self) -> None:
+ """Cancel adapter-owned passive-evolution watcher tasks.
+
+ ``_evolution_watcher_tasks`` is also used to keep SkillSleep background
+ tasks referenceable. Those tasks retain their runner-owned lifecycle and
+ must not be cancelled as a side effect of watcher teardown.
+ """
+ watchers = getattr(self, "_evolution_watchers", None)
+ if not isinstance(watchers, dict):
+ return
+ tasks = set(watchers.values())
+ for task in tasks:
+ if not task.done():
+ task.cancel()
+ if tasks:
+ await asyncio.gather(*tasks, return_exceptions=True)
+ for task in tasks:
+ watcher_tasks = getattr(self, "_evolution_watcher_tasks", None)
+ if isinstance(watcher_tasks, set):
+ watcher_tasks.discard(task)
+ watchers.clear()
+
+ def _on_skill_sleep_task_done(self, task: asyncio.Task) -> None:
+ """Discard a completed SkillSleep task and log unexpected failures."""
+ sleep_tasks = getattr(self, "_skill_sleep_tasks", None)
+ if isinstance(sleep_tasks, set):
+ sleep_tasks.discard(task)
+ watcher_tasks = getattr(self, "_evolution_watcher_tasks", None)
+ if isinstance(watcher_tasks, set):
+ watcher_tasks.discard(task)
+ try:
+ task.result()
+ except asyncio.CancelledError:
+ return
+ except Exception as exc:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] SkillSleep background task exception: %s",
+ exc,
+ )
+
+ async def _unconfigure_skill_sleep_rail(self) -> None:
+ """Unmount SkillSleep and stop sleep work when evolution is disabled."""
+ rail = getattr(self, "_skill_sleep_rail", None)
+ tasks = getattr(self, "_skill_sleep_tasks", None)
+ if rail is None and not tasks:
+ return
+
+ pending = set(tasks or set())
+ for task in pending:
+ if not task.done():
+ task.cancel()
+ if pending:
+ await asyncio.gather(*pending, return_exceptions=True)
+
+ if rail is not None:
+ if self._instance is None:
+ self._skill_sleep_rail = None
+ return
+ unregister = getattr(self._instance, "unregister_rail", None)
+ if not callable(unregister):
+ return
+ try:
+ await unregister(rail)
+ except Exception as exc:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] SkillSleepRail unregister failed: %s",
+ exc,
+ )
+ return
+ self._skill_sleep_rail = None
async def _reconcile_skill_sleep_rail(self) -> None:
"""Register SkillSleepRail when it is not mounted yet."""
@@ -7105,29 +7234,43 @@ class JiuWenSwarmDeepAdapter:
if self._instance is None:
return
- rails = [
- rail
- for rail in (self._skill_evolution_rail, self._evolution_interrupt_rail)
- if rail is not None
- ]
+ unregistered_rails: list[Any] = []
try:
unconfigure_skill_evolution(self._instance, team=False)
- except AttributeError:
- logger.debug(
- "[JiuWenSwarmDeepAdapter] evolution bulk unconfigure unavailable"
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] evolution bulk unconfigure failed: %s",
+ exc,
)
unregister = getattr(self._instance, "unregister_rail", None)
if callable(unregister):
- for rail in rails:
- await unregister(rail)
+ for attr_name, rail in (
+ ("_skill_evolution_rail", self._skill_evolution_rail),
+ ("_evolution_interrupt_rail", self._evolution_interrupt_rail),
+ ):
+ if rail is None:
+ continue
+ try:
+ await unregister(rail)
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] evolution rail unregister failed "
+ "attr=%s error=%s",
+ attr_name,
+ exc,
+ )
+ continue
+ setattr(self, attr_name, None)
+ unregistered_rails.append(rail)
+ else:
+ self._skill_evolution_rail = None
+ self._evolution_interrupt_rail = None
stale_rails = getattr(self._instance, "_stale_rails", None)
if isinstance(stale_rails, list):
- removed_ids = {id(rail) for rail in rails}
+ removed_ids = {id(rail) for rail in unregistered_rails}
self._instance._stale_rails = [ # pylint: disable=protected-access
rail for rail in stale_rails if id(rail) not in removed_ids
]
- self._skill_evolution_rail = None
- self._evolution_interrupt_rail = None
def _refresh_active_evolution_rail_refs(self) -> None:
"""Refresh cached rail references after agent-core runtime configure."""
@@ -8093,8 +8236,8 @@ class JiuWenSwarmDeepAdapter:
{"config": config},
),
)
- # SkillSleepRail is always mounted; per-skill selfEvolution decides
- # whether a sleep cycle actually runs.
+ # SkillSleepRail is always mounted;
+ # per-skill selfEvolution decides whether a sleep cycle actually runs.
rail_infos.insert(
2,
_RailBuildInfo(
@@ -11745,6 +11888,7 @@ class JiuWenSwarmDeepAdapter:
async def cleanup(self) -> None:
"""Release adapter-owned external runtime resources."""
+ await self._cancel_evolution_watchers()
eternal_conversation_rail = getattr(self, "_eternal_conversation_rail", None)
if eternal_conversation_rail is not None:
try:
@@ -17598,11 +17742,7 @@ class JiuWenSwarmDeepAdapter:
)
if self._skill_evolution_rail is not None:
- task = asyncio.create_task(
- self._watch_evolution_and_push(rid, cid, session_id)
- )
- task.add_done_callback(self._on_evolution_watcher_done)
- self._evolution_watcher_tasks.add(task)
+ self._start_evolution_watcher(rid, cid, session_id)
if self._ttse_rail is not None:
ttse_task = asyncio.create_task(
self._cleanup_ttse_background_tasks(rid, session_id)
@@ -19459,7 +19599,11 @@ class JiuWenSwarmDeepAdapter:
return
except asyncio.CancelledError:
try:
- await _cleanup_evolution_rail(cancel=True)
+ current_task = asyncio.current_task()
+ graceful = bool(
+ getattr(current_task, "_evolution_watcher_graceful", False)
+ )
+ await _cleanup_evolution_rail(cancel=not graceful)
finally:
raise
except Exception as exc:
@@ -19492,9 +19636,19 @@ class JiuWenSwarmDeepAdapter:
Discards the task from the tracking set and logs any exception.
"""
- self._evolution_watcher_tasks.discard(task)
+ watchers = getattr(self, "_evolution_watchers", None)
+ if isinstance(watchers, dict):
+ for key, current_task in list(watchers.items()):
+ if current_task is task:
+ watchers.pop(key, None)
+ watcher_tasks = getattr(self, "_evolution_watcher_tasks", None)
+ if isinstance(watcher_tasks, set):
+ watcher_tasks.discard(task)
try:
task.result()
+ except asyncio.CancelledError:
+ # Supersession and adapter teardown intentionally cancel old watchers.
+ return
except Exception as exc:
logger.warning("[JiuWenSwarmDeepAdapter] evolution watcher task exception: %s", exc)
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py b/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py
index c096c9ad8a..9e6075c133 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py
@@ -1,5 +1,5 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-"""Flash 模式适配器 — 极简单 agent profile。
+"""Flash 模式适配器 — 轻量受限 agent profile。
仿照 :class:`JiuwenSwarmCodeAdapter` 的「独立 mode + 继承 DeepAdapter」结构,flash
是和 agent / code 平级的独立 mode:``create_adapter(mode="flash")`` 工厂分叉,
@@ -45,8 +45,8 @@ flash 行为由类常量定义:
``_update_agent_rails()`` 动态注册 context_assemble / memory 等 rail,绕过
``_instantiate_rails`` 的白名单裁剪——flash 覆盖此方法不调 ``_update_agent_rails()``,
单独装配身份上下文和记忆,并卸载白名单外的动态 rail。
-- :meth:`try_start_dreaming` / :meth:`try_stop_dreaming` — no-op。flash 是「无自演进」
- profile,memory dreaming(被动记忆巩固)属自演进范畴,不挂。
+- :meth:`try_start_dreaming` / :meth:`try_stop_dreaming` — no-op。flash 支持
+ 受限 skill 自演进,但不挂 memory dreaming(被动记忆巩固)与 TTSE。
工具面 override(rail 构建 / 工具卡注册两个层面,类都来自
``jiuwenswarm.agents.harness.flash`` 包):
@@ -131,6 +131,7 @@ from jiuwenswarm.agents.harness.flash import (
SlimSysOperationRail,
)
from jiuwenswarm.common.config import (
+ coerce_config_bool,
get_evolution_review_trigger_enabled,
get_skill_create_enabled,
resolve_string_or_list_config,
@@ -166,8 +167,27 @@ logger = logging.getLogger(__name__)
_FLASH_TURBO_TOOL_NAME = "skill_acceleration_exec"
+def _flash_evolution_enabled(config: dict[str, Any] | None) -> bool:
+ """Return the Flash-only online skill-evolution switch (default false)."""
+ flash = config.get("flash") if isinstance(config, dict) else None
+ evolution = flash.get("evolution") if isinstance(flash, dict) else None
+ if not isinstance(evolution, dict):
+ return False
+ return coerce_config_bool(evolution.get("enabled", False), default=False)
+
+
+def _flash_skill_sleep_enabled(config: dict[str, Any] | None) -> bool:
+ """Return the Flash-only SkillSleep switch (default true, as in Deep)."""
+ flash = config.get("flash") if isinstance(config, dict) else None
+ evolution = flash.get("evolution") if isinstance(flash, dict) else None
+ skill_sleep = evolution.get("skill_sleep") if isinstance(evolution, dict) else None
+ if not isinstance(skill_sleep, dict):
+ return True
+ return coerce_config_bool(skill_sleep.get("enabled", True), default=True)
+
+
class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
- """Flash 模式适配器 — 极简单 agent profile(单轮、无 task loop、无自演进)。
+ """Flash 模式适配器 — 极简单 agent profile(单轮、无 task loop)。
继承 :class:`JiuWenSwarmDeepAdapter`,通过工具工厂、配置合并和 rail 生命周期
扩展点注入 flash 行为;覆盖五个宿主方法
@@ -182,12 +202,10 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
_defer_image_sdk_imports = True
# ── flash 行为定义(类常量,仿 CodeAdapter._FIXED_RAIL_NAMES) ─────────
- # react/evolution 覆盖:深合并进 config_base 的 react 段。这些是 flash「单轮、
- # 无 task loop、无自演进」的定义性属性,非可调参数。
+ # react/evolution 覆盖:深合并进 config_base 的 react 段。这些是 flash
+ # 「单轮、无 task loop、无 SkillCreate / review follow-up」的定义性属性,
+ # 非可调参数。``skill_evolution`` 交给部署配置决定,Flash 只挂受限演进 rail。
# enable_task_loop=false — flash 不跑多轮 task 协调循环,只单轮 ReAct。
- # skill_evolution=false — 门控游离的 SkillEvolutionRail(由
- # get_evolution_enabled 读,不走 keep/drop 表);
- # keep/drop 碰不到它,必须这里关。
# skill_create=false — 与 review_trigger 同为 false,否则触发 force-revive
# 把 enable_task_loop 强拉回 true。
# review_trigger=false — 同上。
@@ -201,7 +219,6 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
_FLASH_REACT_OVERRIDE: dict[str, Any] = {
"enable_task_loop": False,
"evolution": {
- "skill_evolution": False,
"skill_create": False,
"review_trigger": False,
},
@@ -231,7 +248,8 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
# ListSkillTool 由其 setup() 注册(全仓库无其它注册点),技能目录/引导 prompt
# 也由它注入。「技能执行」≠「技能演进」:前者是跑已安装技能,flash 必须保留
# (否则 search/install 得到却执行不了,后台 skill_turbo PPT 等直接失败);
- # 后者(SkillEvolutionRail / SkillCreateRail)属自演进,flash 不留。两者分开。
+ # 后者中的受限演进 rail(SkillEvolutionRail / EvolutionInterruptRail /
+ # SkillSleepRail)由本仓保留,SkillCreate 仍排除。两者分开。
# _skill_credential_injection_rail:技能 envs(react.skill_envs 凭证)注入,
# 没有 it 则带凭证的技能跑不起来,与 _skill_rail 同进同出。
# _ask_user_rail:交互请求由 _set_user_interaction_enabled(在
@@ -285,6 +303,11 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
"_skill_rail",
"_flash_skill_selection_rail",
"_skill_credential_injection_rail",
+ # 受限技能自演进:在线被动演进、主动演进审批/中断、离线休眠训练。
+ # SkillCreate / review follow-up 仍不进入 Flash profile。
+ "_skill_evolution_rail",
+ "_evolution_interrupt_rail",
+ "_skill_sleep_rail",
# _skill_active_state_rail / _skill_authorization_rail: 活跃技能状态与
# skill_tool 授权门禁——保持与 normal 对等的技能链(上游 flash 裁掉了
# 这两个,本仓决策保留)。
@@ -337,6 +360,7 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
super().__init__(workspace_dir=workspace_dir, agent_id=agent_id, service_id=service_id)
self._flash_startup_preparations = {}
self._flash_context_rail_lock = asyncio.Lock()
+ self._flash_evolution_rail_lock = asyncio.Lock()
self._flash_context_agent_sysop = None
@contextmanager
@@ -959,7 +983,10 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
``modes.agent.memory.enabled``,未开启则卸载);``_memory_rail`` 在 keep
白名单内,不会被后续卸载步骤误删。外接记忆与云画像沿用父类的
engine/provider 配置入口,独立于内置 memory 的模式开关。
- 3. 卸载白名单(``_FLASH_RAIL_KEEP`` ∪ ``_PROFILE_PROTECTED_RAILS``)外的、
+ 3. 受限自演进 reconcile:只挂载/卸载 ``SkillEvolutionRail``、
+ ``EvolutionInterruptRail`` 和 ``SkillSleepRail``,不进入父类全量
+ ``_update_agent_rails()``;
+ 4. 卸载白名单(``_FLASH_RAIL_KEEP`` ∪ ``_PROFILE_PROTECTED_RAILS``)外的、
可能被父类/旧 reload 残留注册的动态 rail。
白名单内的 rail(task_planning / context_processor / skill 等)冷启动已由
@@ -976,9 +1003,82 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
await self._handle_memory_rail_by_config("agent")
await self._handle_external_memory_rail_by_config()
await self._handle_office_ace_user_profile_rail_by_config()
+ await self._reconcile_flash_evolution_rails()
await self._drop_non_whitelist_dynamic_rails()
self._refresh_rail_observability_snapshot()
+ async def _reconcile_flash_evolution_rails(self) -> None:
+ """Reconcile only the restricted skill-evolution rails for Flash.
+
+ Online evolution is Flash-only and opt-in through
+ ``flash.evolution.enabled``. SkillSleep is independently gated by
+ ``flash.evolution.skill_sleep.enabled`` and defaults to the same
+ resident-rail contract as DeepAdapter; whether it trains is still
+ decided by the per-skill ``selfEvolution`` setting. A dedicated lock
+ serializes registration, unregistration, and reconciliation across
+ concurrent requests and reloads. The register→await→cache sequence has
+ suspend points, so sharing the context-rail lock would mix two
+ unrelated failure domains and permit interleaved half-mounted state.
+ """
+ async with self._flash_evolution_rail_lock:
+ full_config = self._config_base_cache
+ if _flash_evolution_enabled(full_config):
+ await self._ensure_active_evolution_rails_registered()
+ elif (
+ self._skill_evolution_rail is not None
+ or self._evolution_interrupt_rail is not None
+ ):
+ try:
+ await self._unconfigure_active_evolution_rails()
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[JiuWenSwarmFlashAdapter] active evolution rail unconfigure failed: %s",
+ exc,
+ )
+
+ if _flash_skill_sleep_enabled(full_config):
+ await self._reconcile_skill_sleep_rail()
+ elif self._skill_sleep_rail is not None:
+ try:
+ await self._unconfigure_skill_sleep_rail()
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[JiuwenSwarmFlashAdapter] SkillSleepRail unconfigure failed: %s",
+ exc,
+ )
+
+ async def _reconcile_evolution_rails(self) -> None:
+ """Keep Flash reloads on the restricted evolution rail set.
+
+ The inherited DeepAdapter reconcile also mounts TTSE. Flash intentionally
+ excludes TTSE and reads only the Flash evolution switches above, so
+ reload must not widen the Flash profile through the parent implementation.
+ """
+ await self._reconcile_flash_evolution_rails()
+
+ def _sync_active_evolution_review_agent_after_reload(self) -> None:
+ """Restore the Flash evolution reviewer after a DeepAgent reload.
+
+ Flash online evolution is gated by the Flash-specific switch, not the
+ inherited global ``react.evolution`` switch. A retained rail must
+ therefore restore its review subagent even when the global switch is
+ disabled.
+ """
+ if self._instance is None or self._skill_evolution_rail is None:
+ return
+ if not _flash_evolution_enabled(self._config_base_cache):
+ return
+
+ register_review_agent = getattr(
+ self._skill_evolution_rail,
+ "_register_evolution_review_agent",
+ None,
+ )
+ if callable(register_review_agent):
+ register_review_agent(self._instance)
+
+ self._refresh_active_evolution_rail_refs()
+
async def _ensure_flash_context_rail(self) -> None:
"""Attach workspace identity without enabling the full agent profile."""
async with self._flash_context_rail_lock:
@@ -1042,9 +1142,9 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
async def try_start_dreaming(self, busy_checker=None) -> None:
"""no-op:flash 不启 memory dreaming.
- flash 是「无自演进」profile(``enable_task_loop=false`` / ``skill_evolution=
- false``),memory dreaming(被动记忆巩固,跑在 idle 时合并会话记忆)属自演进
- 范畴,与 flash 语义不符。父类 ``try_start_dreaming`` 对 flash 落到
+ flash 的受限 skill 自演进不包含 memory dreaming。memory dreaming
+ (被动记忆巩固,跑在 idle 时合并会话记忆)属于 memory 子系统,与
+ flash 语义不符。父类 ``try_start_dreaming`` 对 flash 落到
``_dreaming_mode="agent"``(interface_deep.py:9044,``mode.startswith("agent")``
else ``"agent"``)仍会启 dreaming,故这里显式 no-op 拦截,避免 flash facade
误启后台记忆巩固。
@@ -1425,6 +1525,7 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
("_office_ace_user_profile_rail", "OfficeAceUserProfileRail"),
("_skill_evolution_rail", "SkillEvolutionRail"),
("_evolution_interrupt_rail", "EvolutionInterruptRail"),
+ ("_skill_sleep_rail", "SkillSleepRail"),
("_skill_create_rail", "SkillCreateRail"),
)
diff --git a/tests/unit_tests/agentserver/test_evolution_helpers.py b/tests/unit_tests/agentserver/test_evolution_helpers.py
index 2ced6ba303..aedec07ff8 100644
--- a/tests/unit_tests/agentserver/test_evolution_helpers.py
+++ b/tests/unit_tests/agentserver/test_evolution_helpers.py
@@ -122,6 +122,31 @@ def test_evolution_helpers_parse_approval_and_outcome_events():
assert evolution_helpers.extract_evolution_request_id(approval) == "team_skill_evolve_req1"
+def test_evolution_approval_uses_explicit_event_kind_before_legacy_type():
+ legacy = SimpleNamespace(
+ type="chat.ask_user_question",
+ payload={"request_id": "legacy-approval"},
+ )
+ explicit_approval = SimpleNamespace(
+ type="chat.ask_user_question",
+ payload={
+ "request_id": "explicit-approval",
+ "_evolution_meta": {"event_kind": "approval"},
+ },
+ )
+ explicit_progress = SimpleNamespace(
+ type="chat.ask_user_question",
+ payload={
+ "request_id": "explicit-progress",
+ "_evolution_meta": {"event_kind": "progress"},
+ },
+ )
+
+ assert evolution_helpers.is_evolution_approval_event(legacy) is True
+ assert evolution_helpers.is_evolution_approval_event(explicit_approval) is True
+ assert evolution_helpers.is_evolution_approval_event(explicit_progress) is False
+
+
def test_evolution_helpers_parse_noop_outcome_status_from_sdk_metadata():
outcome = SimpleNamespace(
type="llm_reasoning",
diff --git a/tests/unit_tests/agentserver/test_evolution_push_delivery.py b/tests/unit_tests/agentserver/test_evolution_push_delivery.py
index 2c5dbd9873..cd559bced9 100644
--- a/tests/unit_tests/agentserver/test_evolution_push_delivery.py
+++ b/tests/unit_tests/agentserver/test_evolution_push_delivery.py
@@ -99,7 +99,6 @@ class _FakeEvolutionRail:
async def cleanup_background_tasks(self) -> None:
self.cleanup_calls += 1
-
class _FakeApprovalRail:
def __init__(
self,
@@ -176,6 +175,231 @@ class _TestAdapter(JiuWenSwarmDeepAdapter):
await watcher(request_id, channel_id, session_id)
+async def test_evolution_watcher_supersedes_previous_request_for_same_session(monkeypatch):
+ """A resumed request replaces the paused request's old watcher ownership."""
+ adapter = object.__new__(JiuWenSwarmDeepAdapter)
+ adapter._skill_evolution_rail = object()
+ adapter._evolution_watcher_tasks = set()
+ adapter._evolution_watchers = {}
+ release = asyncio.Event()
+ started = asyncio.Event()
+
+ async def watch(request_id: str, channel_id: str, session_id: str) -> None:
+ started.set()
+ await release.wait()
+
+ monkeypatch.setattr(adapter, "_watch_evolution_and_push", watch)
+
+ first = adapter._start_evolution_watcher("rid-old", "channel-1", "session-1")
+ await started.wait()
+ started.clear()
+ second = adapter._start_evolution_watcher("rid-new", "channel-1", "session-1")
+ await started.wait()
+ await asyncio.sleep(0)
+
+ assert first.cancelled()
+ assert getattr(first, "_evolution_watcher_graceful", False) is True
+ assert adapter._evolution_watchers[("channel-1", "session-1")] is second
+ assert second in adapter._evolution_watcher_tasks
+
+ release.set()
+ await second
+ await asyncio.sleep(0)
+
+ assert ("channel-1", "session-1") not in adapter._evolution_watchers
+ assert second not in adapter._evolution_watcher_tasks
+
+
+async def test_cancel_evolution_watchers_does_not_cancel_skill_sleep_tasks():
+ """Adapter-owned watchers are teardown-safe without changing SkillSleep lifetime."""
+ adapter = object.__new__(JiuWenSwarmDeepAdapter)
+ adapter._evolution_watcher_tasks = set()
+ adapter._evolution_watchers = {}
+ watcher_release = asyncio.Event()
+ sleep_release = asyncio.Event()
+ watcher_task = asyncio.create_task(watcher_release.wait())
+ sleep_task = asyncio.create_task(sleep_release.wait())
+ adapter._evolution_watcher_tasks.update({watcher_task, sleep_task})
+ adapter._evolution_watchers[("channel-1", "session-1")] = watcher_task
+
+ await adapter._cancel_evolution_watchers()
+
+ assert watcher_task.cancelled()
+ assert not adapter._evolution_watchers
+ assert sleep_task in adapter._evolution_watcher_tasks
+ assert not sleep_task.done()
+
+ sleep_release.set()
+ await sleep_task
+
+
+async def test_stream_start_does_not_cancel_inflight_route_watcher(monkeypatch):
+ """A new request must not abort an in-flight prior passive evolution."""
+ adapter = object.__new__(JiuWenSwarmDeepAdapter)
+ adapter._is_session_scoped_adapter = True
+ adapter._instance = object()
+ adapter._deepresearch_rewrite_tx_uncertain = False
+ adapter._STALE_CRON_PERMISSION_TEXT = "stale"
+
+ async def refresh_stale_mcp_tool_lists() -> None:
+ return None
+
+ async def block_stale_cron_permission_resume(request) -> bool:
+ return True
+
+ monkeypatch.setattr(adapter, "_refresh_stale_mcp_tool_lists", refresh_stale_mcp_tool_lists)
+ monkeypatch.setattr(
+ adapter,
+ "_inject_extension_config_into_inputs",
+ lambda inputs: None,
+ )
+ monkeypatch.setattr(
+ interface_deep_module,
+ "_inject_model_selection_into_inputs",
+ lambda request, inputs: None,
+ )
+ monkeypatch.setattr(
+ interface_deep_module,
+ "_inject_model_routing_into_inputs",
+ lambda request, inputs: None,
+ )
+ monkeypatch.setattr(
+ interface_deep_module,
+ "_inject_request_id_into_inputs",
+ lambda request, inputs: None,
+ )
+ monkeypatch.setattr(adapter, "_has_valid_model_config", lambda model_name: True)
+ monkeypatch.setattr(
+ adapter,
+ "_block_stale_cron_permission_resume",
+ block_stale_cron_permission_resume,
+ )
+ request = SimpleNamespace(
+ request_id="rid-new",
+ channel_id="channel-1",
+ session_id="session-1",
+ params={},
+ metadata={},
+ )
+ chunks = [chunk async for chunk in adapter._process_message_stream_impl(request, {})]
+
+ assert chunks[-1].is_complete is True
+
+
+async def test_superseded_evolution_watcher_does_not_cancel_shared_pending_evolution(
+ monkeypatch,
+):
+ """Route handoff stops the listener without killing rail-owned evolution work."""
+ _FakeTransport.pushes = []
+ drain_release = asyncio.Event()
+
+ class _BlockingRail(_FakeEvolutionRail):
+ def __init__(self):
+ super().__init__(batches=[[]])
+ self.cancel_calls = 0
+
+ async def cancel_pending_evolution(self) -> None:
+ self.cancel_calls += 1
+
+ async def drain_pending_approval_events(self, wait=False, timeout=None):
+ self.drain_waits.append(wait)
+ await drain_release.wait()
+ return []
+
+ rail = _BlockingRail()
+ adapter = _TestAdapter.build_with_rail(rail)
+ monkeypatch.setattr(
+ "jiuwenswarm.server.gateway_push.WebSocketGatewayPushTransport",
+ _FakeTransport,
+ )
+ task = asyncio.create_task(
+ adapter.watch_evolution_and_push("rid", "channel-1", "session-1")
+ )
+ await asyncio.sleep(0)
+ assert rail.drain_waits
+
+ task._evolution_watcher_graceful = True
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ assert rail.cleanup_calls == 1
+ assert rail.cancel_calls == 0
+
+
+async def test_active_evolution_rail_unconfigure_isolates_failures(monkeypatch):
+ """One failed unregister keeps its cached reference; the other can still unload."""
+ adapter = object.__new__(JiuWenSwarmDeepAdapter)
+ active_rail = object()
+ interrupt_rail = object()
+ adapter._instance = SimpleNamespace()
+ adapter._skill_evolution_rail = active_rail
+ adapter._evolution_interrupt_rail = interrupt_rail
+ calls: list[object] = []
+
+ async def unregister(rail):
+ calls.append(rail)
+ if rail is active_rail:
+ raise RuntimeError("active rail unregister failed")
+
+ def bulk_unconfigure(instance, team=False):
+ return None
+
+ adapter._instance.unregister_rail = unregister
+ monkeypatch.setattr(interface_deep_module, "unconfigure_skill_evolution", bulk_unconfigure)
+
+ await adapter._unconfigure_active_evolution_rails()
+
+ assert calls == [active_rail, interrupt_rail]
+ assert adapter._skill_evolution_rail is active_rail
+ assert adapter._evolution_interrupt_rail is None
+
+
+async def test_skill_sleep_rail_unconfigure_keeps_cache_on_failure():
+ """A failed SkillSleep unregister must not erase the still-mounted rail reference."""
+ adapter = object.__new__(JiuWenSwarmDeepAdapter)
+ rail = object()
+ adapter._instance = SimpleNamespace()
+ adapter._skill_sleep_rail = rail
+ adapter._skill_sleep_tasks = set()
+
+ async def unregister(unmounted_rail):
+ assert unmounted_rail is rail
+ raise RuntimeError("SkillSleep unregister failed")
+
+ adapter._instance.unregister_rail = unregister
+
+ await adapter._unconfigure_skill_sleep_rail()
+
+ assert adapter._skill_sleep_rail is rail
+
+
+async def test_cancel_evolution_watchers_cleans_registry_without_user_data():
+ """Adapter teardown cancels its own in-flight watchers and empties ownership."""
+ adapter = object.__new__(JiuWenSwarmDeepAdapter)
+ adapter._evolution_watcher_tasks = set()
+ adapter._evolution_watchers = {}
+ release = asyncio.Event()
+ task = asyncio.create_task(release.wait())
+ adapter._evolution_watcher_tasks.add(task)
+ adapter._evolution_watchers[("channel-1", "session-1")] = task
+
+ await adapter._cancel_evolution_watchers()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ assert task.cancelled()
+ assert not adapter._evolution_watchers
+ assert not adapter._evolution_watcher_tasks
+
+
@pytest.mark.asyncio
async def test_normal_evolution_watcher_runs_when_rail_mounted(monkeypatch):
"""Mounted evolution rail enables passive scan; watcher does not gate on signal_trigger."""
diff --git a/tests/unit_tests/agentserver/test_flash_adapter_rails.py b/tests/unit_tests/agentserver/test_flash_adapter_rails.py
index 0a7393dadd..eae8efc42a 100644
--- a/tests/unit_tests/agentserver/test_flash_adapter_rails.py
+++ b/tests/unit_tests/agentserver/test_flash_adapter_rails.py
@@ -17,6 +17,7 @@ Covers the review findings on PR6431:
``try_stop_dreaming`` are no-ops).
"""
+import asyncio
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
@@ -28,6 +29,7 @@ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
JiuWenSwarmDeepAdapter,
_RailBuildInfo,
)
+from jiuwenswarm.server.runtime.agent_adapter import interface_flash
from jiuwenswarm.server.runtime.agent_adapter.interface_flash import (
JiuwenSwarmFlashAdapter,
)
@@ -77,6 +79,9 @@ def test_keep_whitelist_keeps_protected_and_drops_others():
_info("_permission_rail"), # in KEEP and PROTECTED
_info("_disabled_tools_rail"), # PROTECTED only
_info("_skill_rail"), # in KEEP (skill execution)
+ _info("_skill_evolution_rail"), # in KEEP (restricted evolution)
+ _info("_evolution_interrupt_rail"), # in KEEP (restricted evolution)
+ _info("_skill_sleep_rail"), # in KEEP (restricted evolution)
_info("_skill_credential_injection_rail"), # in KEEP
_info("_skill_active_state_rail"), # in KEEP(本仓决策:技能链对等保留)
_info("_skill_authorization_rail"), # in KEEP(本仓决策:授权门禁保留)
@@ -97,6 +102,9 @@ def test_keep_whitelist_keeps_protected_and_drops_others():
"_permission_rail",
"_disabled_tools_rail",
"_skill_rail",
+ "_skill_evolution_rail",
+ "_evolution_interrupt_rail",
+ "_skill_sleep_rail",
"_skill_credential_injection_rail",
"_skill_active_state_rail",
"_skill_authorization_rail",
@@ -147,15 +155,16 @@ def test_skill_execution_rails_are_in_keep():
prompt injection come from ``_skill_rail`` (SkillUseRail), and skill envs
(``react.skill_envs`` credentials) from ``_skill_credential_injection_rail``.
Both must be in the whitelist or flash is a half-state: can install but not
- run skills (background skill_turbo PPT jobs would fail). Skill *evolution*
- (SkillEvolutionRail / SkillCreateRail) stays dropped — that is the
- self-evolution flash excludes by design.
+ run skills (background skill_turbo PPT jobs would fail). Restricted skill
+ self-evolution is kept, while SkillCreate stays outside the Flash profile.
"""
keep = JiuwenSwarmFlashAdapter._FLASH_RAIL_KEEP
assert "_skill_rail" in keep
assert "_skill_credential_injection_rail" in keep
- # evolution / create rails are NOT kept (self-evolution, excluded by design).
- assert "_skill_evolution_rail" not in keep
+ assert "_skill_evolution_rail" in keep
+ assert "_evolution_interrupt_rail" in keep
+ assert "_skill_sleep_rail" in keep
+ # SkillCreate remains excluded from Flash.
assert "_skill_create_rail" not in keep
@@ -267,16 +276,323 @@ async def test_update_rails_for_mode_does_not_call_update_agent_rails():
assert called["n"] == 0
+async def test_flash_reconcile_registers_active_evolution_when_enabled(monkeypatch):
+ """Flash mounts restricted online evolution rails only when opted in."""
+ adapter = JiuwenSwarmFlashAdapter()
+ adapter._config_base_cache = {
+ "flash": {"evolution": {"enabled": True, "skill_sleep": {"enabled": True}}},
+ }
+ adapter._config_cache = {"evolution": {"skill_evolution": True}}
+ adapter._instance = SimpleNamespace(register_rail=AsyncMock())
+ ensure = AsyncMock()
+ unconfigure = AsyncMock()
+ reconcile_sleep = AsyncMock()
+
+ monkeypatch.setattr(adapter, "_ensure_active_evolution_rails_registered", ensure)
+ monkeypatch.setattr(adapter, "_unconfigure_active_evolution_rails", unconfigure)
+ monkeypatch.setattr(adapter, "_reconcile_skill_sleep_rail", reconcile_sleep)
+
+ await adapter._reconcile_flash_evolution_rails()
+
+ ensure.assert_awaited_once()
+ unconfigure.assert_not_awaited()
+ reconcile_sleep.assert_awaited_once()
+
+
+async def test_flash_reconcile_defaults_keep_skill_sleep_without_online_evolution(monkeypatch):
+ """Flash defaults are closed online evolution and resident SkillSleep."""
+ adapter = JiuwenSwarmFlashAdapter()
+ adapter._config_base_cache = {}
+ adapter._instance = SimpleNamespace(unregister_rail=AsyncMock())
+ adapter._skill_evolution_rail = object()
+ adapter._evolution_interrupt_rail = object()
+ adapter._skill_sleep_rail = object()
+ ensure = AsyncMock()
+ unconfigure = AsyncMock()
+ reconcile_sleep = AsyncMock()
+ unconfigure_sleep = AsyncMock()
+
+ monkeypatch.setattr(adapter, "_ensure_active_evolution_rails_registered", ensure)
+ monkeypatch.setattr(adapter, "_unconfigure_active_evolution_rails", unconfigure)
+ monkeypatch.setattr(adapter, "_reconcile_skill_sleep_rail", reconcile_sleep)
+ monkeypatch.setattr(adapter, "_unconfigure_skill_sleep_rail", unconfigure_sleep)
+
+ await adapter._reconcile_flash_evolution_rails()
+
+ ensure.assert_not_awaited()
+ unconfigure.assert_awaited_once()
+ reconcile_sleep.assert_awaited_once()
+ unconfigure_sleep.assert_not_awaited()
+
+
+async def test_flash_reconcile_does_not_inherit_global_skill_evolution_switch(monkeypatch):
+ """Flash online evolution is opt-in and never falls back to react.evolution."""
+ adapter = JiuwenSwarmFlashAdapter()
+ adapter._config_base_cache = {
+ "react": {"evolution": {"enabled": True, "skill_evolution": True}},
+ "flash": {"evolution": {"enabled": False, "skill_sleep": {"enabled": True}}},
+ }
+ adapter._config_cache = {"evolution": {"enabled": True, "skill_evolution": True}}
+ adapter._instance = SimpleNamespace(unregister_rail=AsyncMock())
+ adapter._skill_evolution_rail = object()
+ adapter._evolution_interrupt_rail = object()
+ adapter._skill_sleep_rail = object()
+ ensure = AsyncMock()
+ unconfigure = AsyncMock()
+ reconcile_sleep = AsyncMock()
+ unconfigure_sleep = AsyncMock()
+
+ monkeypatch.setattr(adapter, "_ensure_active_evolution_rails_registered", ensure)
+ monkeypatch.setattr(adapter, "_unconfigure_active_evolution_rails", unconfigure)
+ monkeypatch.setattr(adapter, "_reconcile_skill_sleep_rail", reconcile_sleep)
+ monkeypatch.setattr(adapter, "_unconfigure_skill_sleep_rail", unconfigure_sleep)
+
+ await adapter._reconcile_flash_evolution_rails()
+
+ ensure.assert_not_awaited()
+ unconfigure.assert_awaited_once()
+ reconcile_sleep.assert_awaited_once()
+ unconfigure_sleep.assert_not_awaited()
+
+
+async def test_flash_reconcile_can_disable_skill_sleep_independently(monkeypatch):
+ """A Flash-only SkillSleep switch can unload sleep without online rails."""
+ adapter = JiuwenSwarmFlashAdapter()
+ adapter._config_base_cache = {
+ "flash": {"evolution": {"enabled": True, "skill_sleep": {"enabled": False}}},
+ }
+ adapter._config_cache = {}
+ adapter._instance = SimpleNamespace(register_rail=AsyncMock(), unregister_rail=AsyncMock())
+ adapter._skill_evolution_rail = object()
+ adapter._skill_sleep_rail = object()
+ ensure = AsyncMock()
+ unconfigure_sleep = AsyncMock()
+
+ monkeypatch.setattr(adapter, "_ensure_active_evolution_rails_registered", ensure)
+ monkeypatch.setattr(adapter, "_unconfigure_skill_sleep_rail", unconfigure_sleep)
+
+ await adapter._reconcile_flash_evolution_rails()
+
+ ensure.assert_awaited_once()
+ unconfigure_sleep.assert_awaited_once()
+
+
+async def test_flash_reconcile_unmounts_evolution_when_disabled(monkeypatch):
+ """A disabled online switch unmounts only online evolution rails."""
+ adapter = JiuwenSwarmFlashAdapter()
+ adapter._config_base_cache = {
+ "flash": {"evolution": {"enabled": False, "skill_sleep": {"enabled": True}}},
+ }
+ adapter._config_cache = {"evolution": {"enabled": True}}
+ adapter._instance = SimpleNamespace(unregister_rail=AsyncMock())
+ adapter._skill_evolution_rail = object()
+ adapter._evolution_interrupt_rail = object()
+ adapter._skill_sleep_rail = object()
+ ensure = AsyncMock()
+ unconfigure = AsyncMock()
+ reconcile_sleep = AsyncMock()
+
+ monkeypatch.setattr(adapter, "_ensure_active_evolution_rails_registered", ensure)
+ monkeypatch.setattr(adapter, "_unconfigure_active_evolution_rails", unconfigure)
+ monkeypatch.setattr(adapter, "_reconcile_skill_sleep_rail", reconcile_sleep)
+
+ await adapter._reconcile_flash_evolution_rails()
+
+ ensure.assert_not_awaited()
+ unconfigure.assert_awaited_once()
+ reconcile_sleep.assert_awaited_once()
+
+
+async def test_flash_reconcile_keeps_cold_started_skill_sleep_by_default(monkeypatch):
+ """A cold-mounted SkillSleep rail remains resident by Flash default."""
+ adapter = JiuwenSwarmFlashAdapter()
+ adapter._config_base_cache = {
+ "flash": {"evolution": {"enabled": False, "skill_sleep": {"enabled": True}}},
+ }
+ adapter._config_cache = {}
+ adapter._instance = SimpleNamespace(unregister_rail=AsyncMock())
+ adapter._skill_sleep_rail = object()
+ ensure = AsyncMock()
+ unconfigure = AsyncMock()
+ reconcile_sleep = AsyncMock()
+
+ monkeypatch.setattr(adapter, "_ensure_active_evolution_rails_registered", ensure)
+ monkeypatch.setattr(adapter, "_unconfigure_active_evolution_rails", unconfigure)
+ monkeypatch.setattr(adapter, "_reconcile_skill_sleep_rail", reconcile_sleep)
+
+ await adapter._reconcile_flash_evolution_rails()
+
+ ensure.assert_not_awaited()
+ unconfigure.assert_not_awaited()
+ reconcile_sleep.assert_awaited_once()
+
+
+async def test_flash_reconcile_unmounts_cold_started_skill_sleep_when_disabled(monkeypatch):
+ """An explicit ``skill_sleep.enabled=false`` must remove a cold-mounted rail."""
+ adapter = JiuwenSwarmFlashAdapter()
+ adapter._config_base_cache = {
+ "flash": {"evolution": {"enabled": False, "skill_sleep": {"enabled": False}}},
+ }
+ adapter._config_cache = {}
+ adapter._instance = SimpleNamespace(unregister_rail=AsyncMock())
+ adapter._skill_sleep_rail = object()
+ ensure = AsyncMock()
+ unconfigure = AsyncMock()
+ unconfigure_sleep = AsyncMock()
+
+ monkeypatch.setattr(adapter, "_ensure_active_evolution_rails_registered", ensure)
+ monkeypatch.setattr(adapter, "_unconfigure_active_evolution_rails", unconfigure)
+ monkeypatch.setattr(adapter, "_unconfigure_skill_sleep_rail", unconfigure_sleep)
+
+ await adapter._reconcile_flash_evolution_rails()
+
+ ensure.assert_not_awaited()
+ unconfigure.assert_not_awaited()
+ unconfigure_sleep.assert_awaited_once()
+
+
+def test_flash_review_agent_restores_when_only_flash_evolution_enabled(monkeypatch):
+ """Flash reload must not require the inherited global evolution switch."""
+
+ class _SkillEvolutionRail:
+ def __init__(self):
+ self.registered_agent = None
+
+ def _register_evolution_review_agent(self, agent):
+ self.registered_agent = agent
+
+ class _EvolutionInterruptRail:
+ pass
+
+ class _SubagentRail:
+ pass
+
+ class _Instance:
+ def __init__(self, rails):
+ self.rails = rails
+
+ def find_rails_by_type(self, rail_types):
+ return [rail for rail in self.rails if isinstance(rail, rail_types)]
+
+ rail = _SkillEvolutionRail()
+ interrupt_rail = _EvolutionInterruptRail()
+ subagent_rail = _SubagentRail()
+ instance = _Instance([subagent_rail, interrupt_rail, rail])
+ adapter = JiuwenSwarmFlashAdapter()
+ adapter._instance = instance
+ adapter._skill_evolution_rail = rail
+ adapter._config_base_cache = {
+ "flash": {"evolution": {"enabled": True, "skill_sleep": {"enabled": True}}},
+ "react": {"evolution": {"enabled": False}},
+ }
+ adapter._config_cache = adapter._config_base_cache["react"]
+
+ refresh_refs = Mock()
+ monkeypatch.setattr(adapter, "_refresh_active_evolution_rail_refs", refresh_refs)
+
+ adapter._sync_active_evolution_review_agent_after_reload()
+
+ assert rail.registered_agent is instance
+ refresh_refs.assert_called_once_with()
+
+
+async def test_flash_reconcile_isolates_unmount_failures(monkeypatch):
+ """A failed active-rail unmount must not block SkillSleep reconciliation."""
+ adapter = JiuwenSwarmFlashAdapter()
+ adapter._config_base_cache = {
+ "flash": {"evolution": {"enabled": False, "skill_sleep": {"enabled": True}}},
+ }
+ adapter._config_cache = {}
+ adapter._instance = SimpleNamespace(unregister_rail=AsyncMock())
+ adapter._skill_evolution_rail = object()
+ adapter._skill_sleep_rail = object()
+ reconcile_sleep = AsyncMock()
+
+ async def fail_active() -> None:
+ raise RuntimeError("active rail unregister failed")
+
+ monkeypatch.setattr(adapter, "_ensure_active_evolution_rails_registered", AsyncMock())
+ monkeypatch.setattr(adapter, "_unconfigure_active_evolution_rails", fail_active)
+ monkeypatch.setattr(adapter, "_reconcile_skill_sleep_rail", reconcile_sleep)
+
+ await adapter._reconcile_flash_evolution_rails()
+
+ reconcile_sleep.assert_awaited_once()
+
+
+async def test_flash_reload_reconcile_does_not_mount_ttse(monkeypatch):
+ """Hot reload keeps Flash on restricted evolution rails and skips TTSE."""
+ adapter = JiuwenSwarmFlashAdapter()
+ restricted = AsyncMock()
+ ensure_ttse = AsyncMock()
+ reconcile_sleep = AsyncMock()
+
+ monkeypatch.setattr(adapter, "_reconcile_flash_evolution_rails", restricted)
+ monkeypatch.setattr(adapter, "_ensure_ttse_rail_registered", ensure_ttse)
+ monkeypatch.setattr(adapter, "_reconcile_skill_sleep_rail", reconcile_sleep)
+
+ await adapter._reconcile_evolution_rails()
+
+ restricted.assert_awaited_once()
+ ensure_ttse.assert_not_awaited()
+
+
+async def test_flash_reconcile_serializes_concurrent_rail_updates(monkeypatch):
+ """Registration and unregister await points must not interleave in Flash."""
+ adapter = JiuwenSwarmFlashAdapter()
+ adapter._config_base_cache = {
+ "flash": {"evolution": {"enabled": True, "skill_sleep": {"enabled": True}}},
+ }
+ adapter._config_cache = {"evolution": {"enabled": True}}
+ adapter._instance = SimpleNamespace(register_rail=AsyncMock())
+ active = 0
+ observed_max = 0
+
+ async def ensure():
+ nonlocal active, observed_max
+ active += 1
+ observed_max = max(observed_max, active)
+ await asyncio.sleep(0)
+ active -= 1
+
+ monkeypatch.setattr(adapter, "_ensure_active_evolution_rails_registered", ensure)
+ monkeypatch.setattr(adapter, "_unconfigure_active_evolution_rails", AsyncMock())
+ monkeypatch.setattr(adapter, "_reconcile_skill_sleep_rail", AsyncMock())
+
+ await asyncio.gather(
+ adapter._reconcile_flash_evolution_rails(),
+ adapter._reconcile_flash_evolution_rails(),
+ )
+
+ assert observed_max == 1
+
+
def test_flash_rail_snapshot_is_stable_and_fingerprint_is_stable():
adapter = object.__new__(JiuwenSwarmFlashAdapter)
adapter._task_planning_rail = object()
adapter._memory_rail = object()
adapter._context_assemble_rail = object()
+ adapter._skill_evolution_rail = object()
+ adapter._evolution_interrupt_rail = object()
+ adapter._skill_sleep_rail = object()
snapshot = adapter._rail_snapshot()
fingerprint = adapter._profile_fingerprint()
- assert snapshot == "task_planning_rail,context_assemble_rail,memory_rail"
+ assert snapshot == (
+ "task_planning_rail,context_assemble_rail,memory_rail,"
+ "skill_evolution_rail,evolution_interrupt_rail,skill_sleep_rail"
+ )
assert fingerprint == adapter._profile_fingerprint()
assert len(fingerprint) == 12
@@ -504,7 +820,7 @@ def test_flash_override_keeps_task_loop_false_against_global_skill_create():
assert react["enable_task_loop"] is False
assert react["evolution"]["skill_create"] is False
assert react["evolution"]["review_trigger"] is False
- assert react["evolution"]["skill_evolution"] is False
+ assert react["evolution"]["skill_evolution"] is True
# With the overlay applied, task_loop resolves False (no force-revive).
assert _resolve_enable_task_loop(react, merged) is False
diff --git a/tests/unit_tests/agentserver/test_flash_adapter_tool_face.py b/tests/unit_tests/agentserver/test_flash_adapter_tool_face.py
index a1bbe190ea..f49199be93 100644
--- a/tests/unit_tests/agentserver/test_flash_adapter_tool_face.py
+++ b/tests/unit_tests/agentserver/test_flash_adapter_tool_face.py
@@ -66,20 +66,23 @@ class _FakeAbilityManager:
def test_keep_whitelist_retains_skill_and_security_rails() -> None:
- """技能链与 disabled_tools 的冷启动表项必须存活(reload 复活点对齐)。"""
+ """技能链、受限自演进与 disabled_tools 的冷启动表项必须存活。"""
adapter = _bare_adapter(JiuwenSwarmFlashAdapter)
keep = [
"_skill_rail",
"_skill_credential_injection_rail",
"_skill_active_state_rail",
"_skill_authorization_rail",
+ "_skill_evolution_rail",
+ "_evolution_interrupt_rail",
+ "_skill_sleep_rail",
"_disabled_tools_rail",
"_permission_rail",
"_filesystem_rail",
"_skill_turbo_prompt_rail",
]
drop = [
- "_skill_evolution_rail",
+ "_skill_create_rail",
"_a2a_outbound_toolkit_rail",
"_symphony_orchestration_rail",
]
@@ -88,6 +91,24 @@ def test_keep_whitelist_retains_skill_and_security_rails() -> None:
assert [info.attr_name for info in filtered] == keep
+def test_flash_tool_face_keeps_rail_owned_evolution_tools_only() -> None:
+ """Flash accepts the six rail-owned evolution tools, not SkillCreate/TTSE."""
+ drop_names = JiuwenSwarmFlashAdapter._FLASH_TOOL_CARD_DROP_NAMES
+ rail_owned_evolution_tools = {
+ "prepare_skill_evolution",
+ "evolve_review_task",
+ "list_skill_experiences",
+ "read_skill_experiences",
+ "evolve_skill_experiences",
+ "simplify_skill_experiences",
+ }
+ keep = JiuwenSwarmFlashAdapter._FLASH_RAIL_KEEP
+
+ assert rail_owned_evolution_tools.isdisjoint(drop_names)
+ assert "_skill_create_rail" not in keep
+ assert "_ttse_rail" not in keep
+
+
# ── react 覆盖(eager_tools 整表替换 / evolution 深合并 / env 告警) ──
diff --git a/tests/unit_tests/agentserver/test_flash_external_memory_integration.py b/tests/unit_tests/agentserver/test_flash_external_memory_integration.py
index 9fa9f18d7a..faf5d22e25 100644
--- a/tests/unit_tests/agentserver/test_flash_external_memory_integration.py
+++ b/tests/unit_tests/agentserver/test_flash_external_memory_integration.py
@@ -29,6 +29,10 @@ class RecordingAgent:
@pytest.fixture
def flash_memory(monkeypatch):
config = {
+ # Keep these memory-lifecycle tests focused on their own rails.
+ # SkillSleep now defaults to resident (matching Deep), but it has no
+ # ``kind`` attribute and is independently gated in its own tests.
+ "flash": {"evolution": {"skill_sleep": {"enabled": False}}},
"memory": {
"mode": "local",
"engine": "external",
@@ -42,6 +46,10 @@ def flash_memory(monkeypatch):
monkeypatch.setattr(interface_deep, "get_config", lambda: config)
monkeypatch.setattr(memory_module, "get_memory_section", lambda cfg=None: (cfg or config)["memory"])
adapter = JiuwenSwarmFlashAdapter()
+ # The full config snapshot gates Flash-only SkillSleep; the react subtree
+ # remains the input for tool/runtime react settings.
+ adapter._config_base_cache = config
+ adapter._config_cache = config.get("react", {})
adapter._instance = RecordingAgent()
# Isolate workspace context and built-in memory from the external gates.
monkeypatch.setattr(adapter, "_ensure_flash_context_rail", AsyncMock())
diff --git a/tests/unit_tests/agentserver/test_flash_identity_memory.py b/tests/unit_tests/agentserver/test_flash_identity_memory.py
index 3e66eedfbe..69489492f4 100644
--- a/tests/unit_tests/agentserver/test_flash_identity_memory.py
+++ b/tests/unit_tests/agentserver/test_flash_identity_memory.py
@@ -44,6 +44,7 @@ def _isolate_other_rails(monkeypatch, adapter):
"_handle_memory_rail_by_config",
"_handle_external_memory_rail_by_config",
"_handle_office_ace_user_profile_rail_by_config",
+ "_reconcile_flash_evolution_rails",
):
monkeypatch.setattr(adapter, name, AsyncMock())
monkeypatch.setattr(adapter, "_rebind_late_read_rails_to_local", Mock())
diff --git a/tests/unit_tests/common/test_flash_env_config.py b/tests/unit_tests/common/test_flash_env_config.py
index e4485ed71e..3456df2d77 100644
--- a/tests/unit_tests/common/test_flash_env_config.py
+++ b/tests/unit_tests/common/test_flash_env_config.py
@@ -12,6 +12,8 @@ from jiuwenswarm.common import local_env_config as env_config
FLASH_ENV = "JIUWENSWARM_FLASH_ENABLED"
SKILL_ENV = "JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED"
+FLASH_EVOLUTION_ENV = "JIUWENSWARM_FLASH_EVOLUTION_ENABLED"
+FLASH_SKILL_SLEEP_ENV = "JIUWENSWARM_FLASH_SKILL_SLEEP_ENABLED"
@pytest.fixture
@@ -20,6 +22,8 @@ def config_file(monkeypatch, tmp_path):
monkeypatch.setattr(config_module, "get_config_file", lambda: path)
monkeypatch.delenv(FLASH_ENV, raising=False)
monkeypatch.delenv(SKILL_ENV, raising=False)
+ monkeypatch.delenv(FLASH_EVOLUTION_ENV, raising=False)
+ monkeypatch.delenv(FLASH_SKILL_SLEEP_ENV, raising=False)
providers.reset_config_provider()
config_module.clear_config_cache()
yield path
@@ -41,6 +45,46 @@ def test_shipped_placeholders_resolve_to_false_without_modifying_raw_config(conf
assert not config_file.exists()
+def test_shipped_flash_evolution_switches_default_to_closed_online_and_resident_sleep(config_file):
+ raw = config_module.get_config_raw()
+ flash = raw.get("flash", {})
+ evolution = flash.get("evolution", {})
+ assert evolution.get("enabled") == f"${{{FLASH_EVOLUTION_ENV}:-false}}"
+ assert evolution.get("skill_sleep", {}).get("enabled") == (
+ f"${{{FLASH_SKILL_SLEEP_ENV}:-true}}"
+ )
+
+ resolved = config_module.get_config()
+ resolved_evolution = resolved.get("flash", {}).get("evolution", {})
+ assert resolved_evolution.get("enabled") is False
+ assert resolved_evolution.get("skill_sleep", {}).get("enabled") is True
+
+
+ "raw,expected",
+ [
+ ("true", True),
+ ("1", True),
+ ("yes", True),
+ ("on", True),
+ ("false", False),
+ ("0", False),
+ ("no", False),
+ ("off", False),
+ ("", False),
+ ("invalid", False),
+ ],
+)
+def test_flash_evolution_environment_overrides_normalize_to_booleans(
+ config_file, monkeypatch, raw, expected
+):
+ monkeypatch.setenv(FLASH_EVOLUTION_ENV, raw)
+ monkeypatch.setenv(FLASH_SKILL_SLEEP_ENV, "false" if expected else "true")
+ evolution = config_module.get_config().get("flash", {}).get("evolution", {})
+ assert evolution.get("enabled") is expected
+ assert evolution.get("skill_sleep", {}).get("enabled") is (not expected)
+
+
@pytest.mark.parametrize("name", [FLASH_ENV, SKILL_ENV])
@pytest.mark.parametrize("raw,expected", [
("true", True), (" TRUE ", True), ("1", True), ("yes", True), ("on", True),
@@ -97,6 +141,20 @@ def test_custom_placeholder_defaults_and_unrelated_strings_are_preserved(config_
assert config_module.resolve_env_vars("${FLASH_TEST_MISSING-false}") == "false"
+def test_sparse_skill_sleep_section_defaults_to_resident(config_file, monkeypatch):
+ resolved = config_module.resolve_config_env_vars(
+ {
+ "flash": {
+ "evolution": {
+ "skill_sleep": {"call_threshold": 2},
+ },
+ },
+ }
+ ).get("flash", {}).get("evolution", {})
+ assert resolved.get("skill_sleep", {}).get("enabled") is True
+ assert resolved.get("skill_sleep", {}).get("call_threshold") == 2
+
+
def test_sandbox_values_survive_sealed_task_overlay_and_child_export(config_file, monkeypatch):
monkeypatch.setenv(FLASH_ENV, "true")
monkeypatch.setenv(SKILL_ENV, "false")