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

fix:兜底压缩

liubuyu18044a59c1b6d
diff --git a/jiuwenswarm/agents/harness/common/rails/context_overflow_recovery_rail.py b/jiuwenswarm/agents/harness/common/rails/context_overflow_recovery_rail.py
index 7bd1f71e63..4093ac927d 100644
--- a/jiuwenswarm/agents/harness/common/rails/context_overflow_recovery_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/context_overflow_recovery_rail.py
@@ -6,9 +6,6 @@ from __future__ import annotations
import re
from typing import Any, Optional
-from openjiuwen.core.context_engine.processor.compressor.full_compact_processor import (
- FullCompactProcessor,
-)
from openjiuwen.harness.rails.base import DeepAgentRail
from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
from openjiuwen.core.common.logging import logger
@@ -184,7 +181,12 @@ class ContextOverflowRecoveryRail(DeepAgentRail):
logger.warning("[ContextOverflowRecovery] Context has no _processors when finding FullCompactProcessor")
return None
for processor in processors:
- if isinstance(processor, FullCompactProcessor):
+ # 框架以 processor_type() 同名键标识处理器(见 MetaContextProcessor +
+ # ContextEngine._PROCESSOR_MAP)。forked.activate() 把 "FullCompactProcessor"
+ # 键覆盖为 forked 类,其实例不继承原始类,isinstance 会漏判;改用同名键 +
+ # set_force_compact 能力识别,forked/原始实例均可命中。
+ proc_type_fn = getattr(processor, "processor_type", None)
+ if callable(proc_type_fn) and proc_type_fn() == "FullCompactProcessor":
return processor
logger.warning(
"[ContextOverflowRecovery] No FullCompactProcessor found in context processors: %s",
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index edfe675745..ee43c00799 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -646,6 +646,14 @@ react:
min_target_context_ratio: 0.1 # 压缩目标下限(占窗口比例)
keep_recent_messages: 4 # 保留最近消息数
+ # 兜底压缩:整窗口 token 超阈值时调一次 LLM 把历史压成 summary,并在尾部 reinject 最近 skill/file/task_status 等关键状态。
+ # 仅用于溢出恢复:日常 add 路径不触发,由 ContextOverflowRecoveryRail 在 413/上下文溢出时靠 set_force_compact 在 GET 路径触发。
+ # 413 恢复时 threshold_override 会按模型真实窗口*0.85 自适应覆盖下方 trigger_total_tokens。
+ full_compact_processor_config:
+ trigger_total_tokens: 100000 # 整窗口 token 阈值;溢出兜底用,高于日常压缩阈值,仅在真溢出时被动触发
+ compression_call_max_tokens: 200000 # 压缩调 LLM 时的最大上下文预算
+ messages_to_keep: 10 # 保留最近 N 条;buffer < 此值时不会删历史,只新增 summary
+
# 连续相同 reasoning+工具集 / 相同工具入参时,折叠重复轮次;超阈值后兜底中止
reasoning_tool_loop_compact_config:
enabled: true # 是否启用循环压缩
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
index f132220701..43be2cb093 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
@@ -358,6 +358,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
"JiuSwarmStreamEventRail", "SecurityRail",
"LspRail", "ProjectMemoryRail", "PermissionInterruptRail",
"ContextProcessorRail",
+ "ContextOverflowRecoveryRail",
"SysOperationRail", "CodingMemoryRail",
"AgentModeRail", "StructuredAskUserRail", "ConfirmInterruptRail",
"FileSystemRail", # 别名
@@ -617,6 +618,12 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
{"tool_names": ["switch_mode"]},
),
_RailBuildInfo("_context_processor_rail", self._build_context_processor_rail),
+ # 溢出兜底:与链路 A(DeepAdapter)对齐,复用父类 _build_context_overflow_recovery_rail。
+ # ContextOverflowRecoveryRail 在 413/上下文溢出时靠 set_force_compact 触发 FullCompact。
+ _RailBuildInfo(
+ "_context_overflow_recovery_rail",
+ self._build_context_overflow_recovery_rail,
+ ),
_RailBuildInfo("_code_task_planning_rail", self._build_code_task_planning_rail),
_RailBuildInfo("_code_agent_rail", self._build_code_agent_rail),
_RailBuildInfo("_code_plan_approval_rail", self._build_plan_approval_rail),
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index baa58a9e5a..7769c02ba4 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -77,6 +77,10 @@ from openjiuwen.harness.rails import (
from openjiuwen.harness.rails.evolution import EvolutionReviewRuntime
from openjiuwen.harness.rails.context_engineer.context_assemble_rail import ContextAssembleRail
from openjiuwen.harness.rails.context_engineer.context_processor_rail import ContextProcessorRail
+# FullCompact 仅用于溢出兜底(413/上下文溢出),日常压缩由 preset 链承担。
+# 从 processor.compressor 包入口取 Config(__init__ 显式导出,跨版本稳定);
+# _merge_processors 只认 BaseModel 实例,不区分配置类来源
+from openjiuwen.core.context_engine.processor.compressor import FullCompactProcessorConfig
from openjiuwen.harness.rails.interrupt.confirm_rail import ConfirmPayload as _SkillTurboConfirmPayload
try:
from openjiuwen.agent_evolving.skill_self_evolution import resolve_skill_evolution_action
@@ -1441,6 +1445,16 @@ def _build_context_processor_rail(config: dict[str, Any]) -> ContextProcessorRai
if isinstance(round_level_cfg, dict) and round_level_cfg:
user_processors.append(("RoundLevelCompressor", round_level_cfg))
+ # 兜底压缩:整窗口 token 超阈值时调一次 LLM 把历史压成 summary。
+ # ContextOverflowRecoveryRail 在 413/上下文溢出时靠 set_force_compact 触发。
+ # 注意:FullCompactProcessor 不在 0.1.16 preset 链中,_merge_processors 对非 preset
+ # processor 不接受 dict(无 base_cfg 可合并),必须传完整 BaseModel 实例。
+ full_compact_cfg = context_engine_cfg.get("full_compact_processor_config", {})
+ if isinstance(full_compact_cfg, dict) and full_compact_cfg:
+ user_processors.append(
+ ("FullCompactProcessor", FullCompactProcessorConfig(**full_compact_cfg))
+ )
+
reasoning_loop_cfg = context_engine_cfg.get("reasoning_tool_loop_compact_config", {})
if isinstance(reasoning_loop_cfg, dict) and reasoning_loop_cfg:
reasoning_loop_cfg = {
diff --git a/tests/unit_tests/agentserver/test_code_adapter_context_overflow_recovery_rail.py b/tests/unit_tests/agentserver/test_code_adapter_context_overflow_recovery_rail.py
new file mode 100644
index 0000000000..df6f8c2be6
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_code_adapter_context_overflow_recovery_rail.py
@@ -0,0 +1,128 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Unit tests for ContextOverflowRecoveryRail registration in JiuwenSwarmCodeAdapter.
+
+链路 B (code 模式) 补齐溢出兜底 rail 的桩测。验证:
+- TC-001: _FIXED_RAIL_NAMES 含 ContextOverflowRecoveryRail(防动态重复注册 + 标记为固定)
+- TC-002: _RAIL_BUILD_NAMES 不含 ContextOverflowRecoveryRail(固定 rail 不走动态加载)
+- TC-003: _build_agent_rails 返回的固定列表含 _context_overflow_recovery_rail 条目(属性名正确)
+- TC-004: _build_context_overflow_recovery_rail 复用父类方法,可调用且返回 rail 实例或 None(不抛)
+
+NOTE: 复用 lsp_rail 测试的 mock 注入模式 —— InMemoryTrajectoryRegistry 在已发布的
+openjiuwen 包里尚不存在,需在 import 链解析前注入 mock,否则 collection 失败。
+"""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock
+
+import openjiuwen.agent_evolving.trajectory as _traj_mod
+if not hasattr(_traj_mod, "InMemoryTrajectoryRegistry"):
+ _traj_mod.InMemoryTrajectoryRegistry = MagicMock
+
+import jiuwenswarm.server.runtime.agent_adapter.interface_code as _ic_mod
+from jiuwenswarm.agents.harness.common.rails.context_overflow_recovery_rail import (
+ ContextOverflowRecoveryRail,
+)
+
+_RAIL_BUILD_NAMES = getattr(_ic_mod, "_RAIL_BUILD_NAMES")
+_RailBuildInfo = getattr(_ic_mod, "_RailBuildInfo")
+JiuwenSwarmCodeAdapter = _ic_mod.JiuwenSwarmCodeAdapter
+_FIXED_RAIL_NAMES = getattr(JiuwenSwarmCodeAdapter, "_FIXED_RAIL_NAMES")
+
+
+# ─── TC-001: _FIXED_RAIL_NAMES 含 ContextOverflowRecoveryRail ─────────────
+
+
+def test_fixed_rail_names_contains_context_overflow_recovery_rail():
+ """Verify ContextOverflowRecoveryRail is registered as a fixed rail for code mode.
+
+ 链路 B 原本缺溢出恢复 rail;补齐后该名字必须在 _FIXED_RAIL_NAMES 里,
+ 既标记为固定 rail,又防止 modes.code.rails 动态配置时重复注册。
+ """
+ assert "ContextOverflowRecoveryRail" in _FIXED_RAIL_NAMES, (
+ "ContextOverflowRecoveryRail should be in _FIXED_RAIL_NAMES "
+ "so code mode has overflow recovery parity with deep mode (link A)"
+ )
+
+
+# ─── TC-002: _RAIL_BUILD_NAMES 不含 ContextOverflowRecoveryRail ───────────
+
+
+def test_rail_build_names_does_not_contain_context_overflow_recovery_rail():
+ """Verify recovery rail is NOT in the dynamic rail map (it's a fixed rail)."""
+ assert "ContextOverflowRecoveryRail" not in _RAIL_BUILD_NAMES, (
+ "ContextOverflowRecoveryRail is a fixed rail and should not appear "
+ "in _RAIL_BUILD_NAMES (dynamic-config map); fixed rails are added "
+ "directly to _build_agent_rails"
+ )
+
+
+# ─── TC-003: _build_agent_rails 固定列表含 recovery rail 条目 ──────────────
+
+
+def test_build_agent_rails_includes_context_overflow_recovery_rail_entry():
+ """Verify the fixed rail list built by _build_agent_rails contains a
+ _context_overflow_recovery_rail RailBuildInfo with the correct attr_name.
+
+ _build_agent_rails 末尾会调 _instantiate_rails 把 RailBuildInfo 列表实例化成
+ rail 列表,因此桩掉 _instantiate_rails 让它原样返回 rail_infos,避免触发真实
+ rail 构造的重依赖,只校验 RailBuildInfo 的 attr_name 与 build_func。
+ """
+ adapter = JiuwenSwarmCodeAdapter()
+
+ # 桩 _instantiate_rails:直接返回传入的 rail_infos(不实例化),便于检查条目
+ captured: list = []
+ real_instantiate = adapter._instantiate_rails
+
+ def _passthrough_instantiate(rail_infos, config_base, *args, **kwargs):
+ captured.extend(rail_infos)
+ return rail_infos
+
+ object.__setattr__(adapter, "_instantiate_rails", _passthrough_instantiate)
+ try:
+ adapter._build_agent_rails(config={}, config_base={}, mode="code")
+ finally:
+ object.__setattr__(adapter, "_instantiate_rails", real_instantiate)
+
+ rail_infos = captured
+ attr_names = [ri.attr_name for ri in rail_infos]
+ assert "_context_overflow_recovery_rail" in attr_names, (
+ "fixed rail list should contain _context_overflow_recovery_rail entry"
+ )
+ # 与 _context_processor_rail 相邻,体现“上下文处理 + 溢出兜底”的成对设计
+ proc_idx = attr_names.index("_context_processor_rail")
+ recovery_idx = attr_names.index("_context_overflow_recovery_rail")
+ assert recovery_idx == proc_idx + 1, (
+ "_context_overflow_recovery_rail should immediately follow "
+ f"_context_processor_rail (got proc_idx={proc_idx}, recovery_idx={recovery_idx})"
+ )
+ # build_func 应复用父类 _build_context_overflow_recovery_rail(静态方法)
+ recovery_info = rail_infos[recovery_idx]
+ assert recovery_info.build_func == adapter._build_context_overflow_recovery_rail, (
+ "recovery rail build_func should be the inherited parent static method "
+ "_build_context_overflow_recovery_rail"
+ )
+
+
+# ─── TC-004: _build_context_overflow_recovery_rail 可调用且返回 rail/None ──
+
+
+def test_build_context_overflow_recovery_rail_callable_returns_rail_or_none():
+ """Verify the inherited parent build method is callable and returns either
+ a ContextOverflowRecoveryRail instance or None (never raises).
+
+ 父类 JiuWenSwarmDeepAdapter._build_context_overflow_recovery_rail 是 @staticmethod,
+ 内部 try/except 包裹实例化;CodeAdapter 继承后应同样可调用,返回值类型正确。
+ """
+ adapter = JiuwenSwarmCodeAdapter()
+ # 静态方法,可通过实例或类调用
+ result = adapter._build_context_overflow_recovery_rail()
+ assert result is None or isinstance(result, ContextOverflowRecoveryRail), (
+ f"expected None or ContextOverflowRecoveryRail, got {type(result).__name__}"
+ )
+ # 成功路径:max_recovery_attempts 应为 3(父类硬编码)
+ if result is not None:
+ assert result._max_recovery_attempts == 3, (
+ "ContextOverflowRecoveryRail should be built with max_recovery_attempts=3"
+ )