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

test(runtime): keep this PR within the 50-file limit

n99357702852f50f50d5ed
diff --git a/tests/unit_tests/agentserver/live_ws_harness.py b/tests/unit_tests/agentserver/live_ws_harness.py
deleted file mode 100644
index acf340e558..0000000000
--- a/tests/unit_tests/agentserver/live_ws_harness.py
+++ /dev/null
@@ -1,270 +0,0 @@
-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-
-"""Stdlib HTTP + WebSocket harness for live-browser subagent store checks."""
-
-from __future__ import annotations
-
-import base64
-import hashlib
-import json
-import socket
-import threading
-from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
-from pathlib import Path
-from typing import Any
-
-_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
-
-
-def encode_ws_text(text: str) -> bytes:
- payload = text.encode("utf-8")
- header = bytearray([0x81])
- length = len(payload)
- if length < 126:
- header.append(length)
- elif length < 65536:
- header.append(126)
- header.extend(length.to_bytes(2, "big"))
- else:
- header.append(127)
- header.extend(length.to_bytes(8, "big"))
- return bytes(header) + payload
-
-
-def decode_ws_text(sock: socket.socket) -> str | None:
- header = sock.recv(2)
- if len(header) < 2:
- return None
- opcode = header[0] & 0x0F
- masked = bool(header[1] & 0x80)
- length = header[1] & 0x7F
- if length == 126:
- ext = sock.recv(2)
- if len(ext) < 2:
- return None
- length = int.from_bytes(ext, "big")
- elif length == 127:
- ext = sock.recv(8)
- if len(ext) < 8:
- return None
- length = int.from_bytes(ext, "big")
- mask = sock.recv(4) if masked else b""
- if masked and len(mask) < 4:
- return None
- data = b""
- while len(data) < length:
- chunk = sock.recv(length - len(data))
- if not chunk:
- return None
- data += chunk
- if masked:
- data = bytes(byte ^ mask[index % 4] for index, byte in enumerate(data))
- if opcode == 0x8:
- return None
- return data.decode("utf-8")
-
-
-def accept_ws_key(key: str) -> str:
- digest = hashlib.sha1((key + _GUID).encode("utf-8")).digest()
- return base64.b64encode(digest).decode("ascii")
-
-
-def three_child_ws_payloads(session_id: str) -> list[dict[str, Any]]:
- """Backend-shaped Web payloads for the three-child H sequence."""
- events: list[dict[str, Any]] = []
- children = ("sa-a", "sa-b", "sa-c")
- for index, child_id in enumerate(children):
- events.append(
- {
- "event_type": "chat.subtask_update",
- "session_id": session_id,
- "parent_session_id": session_id,
- "subagent_id": child_id,
- "display_name": f"Child {child_id}",
- "status": "running",
- "legacy_status": "running",
- "revision": 1,
- "created_at": 1000 + index,
- "updated_at": 1000 + index,
- }
- )
- events.append(
- {
- "event_type": "chat.subagent_activity",
- "session_id": session_id,
- "parent_session_id": session_id,
- "subagent_id": child_id,
- "activity_id": f"{child_id}-think",
- "task_id": f"task-{child_id}",
- "seq": 1,
- "kind": "thinking",
- "summary": f"{child_id} thinking",
- "at_ms": 1100 + index,
- }
- )
- events.append(
- {
- "event_type": "chat.subtask_update",
- "session_id": session_id,
- "parent_session_id": session_id,
- "subagent_id": "sa-a",
- "display_name": "Child sa-a",
- "status": "idle",
- "legacy_status": "completed",
- "turn_outcome": "completed",
- "can_send_input": True,
- "lifecycle": "live",
- "revision": 2,
- "created_at": 1000,
- "updated_at": 2000,
- }
- )
- events.append(
- {
- "event_type": "chat.subtask_update",
- "session_id": session_id,
- "parent_session_id": session_id,
- "subagent_id": "sa-c",
- "display_name": "Child sa-c",
- "status": "closed",
- "legacy_status": "error",
- "closed_reason": "failed",
- "revision": 2,
- "created_at": 1002,
- "updated_at": 2100,
- }
- )
- return events
-
-
-class _HarnessHandler(SimpleHTTPRequestHandler):
- snapshot: dict[str, Any] | None = None
- snapshot_event = threading.Event()
-
- def log_message(self, format: str, *args: object) -> None:
- del format, args
-
- def do_POST(self) -> None: # noqa: N802
- if self.path != "/snapshot":
- self.send_error(404)
- return
- length = int(self.headers.get("Content-Length", "0"))
- body = self.rfile.read(length)
- try:
- payload = json.loads(body.decode("utf-8"))
- except json.JSONDecodeError:
- self.send_error(400)
- return
- type(self).snapshot = payload
- type(self).snapshot_event.set()
- self.send_response(204)
- self.end_headers()
-
-
-class LiveWsHarness:
- """Serve the frontend harness and push the three-child WS sequence."""
-
- def __init__(self, root: Path, session_id: str = "session-h") -> None:
- self.root = root
- self.session_id = session_id
- self.http: ThreadingHTTPServer | None = None
- self.ws_sock: socket.socket | None = None
- self._http_thread: threading.Thread | None = None
- self._ws_thread: threading.Thread | None = None
- self.ready = threading.Event()
- self.done = threading.Event()
- self.client_snapshot: dict[str, Any] | None = None
-
- @property
- def http_url(self) -> str:
- if self.http is None:
- raise RuntimeError("http server is not started")
- host, port = self.http.server_address
- return f"http://127.0.0.1:{port}/index.html?session={self.session_id}&ws=ws://127.0.0.1:{self.ws_port}"
-
- @property
- def ws_port(self) -> int:
- if self.ws_sock is None:
- raise RuntimeError("ws server is not started")
- return int(self.ws_sock.getsockname()[1])
-
- def start(self) -> None:
- _HarnessHandler.snapshot = None
- _HarnessHandler.snapshot_event.clear()
- self.http = ThreadingHTTPServer(
- ("127.0.0.1", 0),
- lambda *args, **kwargs: _HarnessHandler(*args, directory=str(self.root), **kwargs),
- )
- self._http_thread = threading.Thread(target=self.http.serve_forever, daemon=True)
- self._http_thread.start()
- self.ws_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- self.ws_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- self.ws_sock.bind(("127.0.0.1", 0))
- self.ws_sock.listen(1)
- self._ws_thread = threading.Thread(target=self._serve_ws, daemon=True)
- self._ws_thread.start()
-
- def _serve_ws(self) -> None:
- if self.ws_sock is None:
- return
- conn, _addr = self.ws_sock.accept()
- with conn:
- request = b""
- while b"\r\n\r\n" not in request:
- chunk = conn.recv(4096)
- if not chunk:
- return
- request += chunk
- headers = {}
- for line in request.decode("iso-8859-1").split("\r\n")[1:]:
- if ":" in line:
- key, value = line.split(":", 1)
- headers[key.strip().lower()] = value.strip()
- key = headers.get("sec-websocket-key")
- if not key:
- return
- accept = accept_ws_key(key)
- response = (
- "HTTP/1.1 101 Switching Protocols\r\n"
- "Upgrade: websocket\r\n"
- "Connection: Upgrade\r\n"
- f"Sec-WebSocket-Accept: {accept}\r\n\r\n"
- )
- conn.sendall(response.encode("ascii"))
- first = decode_ws_text(conn)
- if first is None:
- return
- self.ready.set()
- for payload in three_child_ws_payloads(self.session_id):
- conn.sendall(encode_ws_text(json.dumps(payload)))
- conn.sendall(encode_ws_text(json.dumps({"type": "done"})))
- snapshot_msg = decode_ws_text(conn)
- if snapshot_msg:
- try:
- parsed = json.loads(snapshot_msg)
- except json.JSONDecodeError:
- parsed = None
- if isinstance(parsed, dict) and parsed.get("type") == "snapshot":
- snap = parsed.get("snapshot")
- if isinstance(snap, dict):
- self.client_snapshot = snap
- self.done.set()
-
- def wait_snapshot(self, timeout: float = 20.0) -> dict[str, Any]:
- _HarnessHandler.snapshot_event.wait(timeout)
- if isinstance(_HarnessHandler.snapshot, dict):
- return _HarnessHandler.snapshot
- self.done.wait(timeout)
- if isinstance(self.client_snapshot, dict):
- return self.client_snapshot
- raise TimeoutError("live WS harness did not receive a browser snapshot")
-
- def close(self) -> None:
- if self.http is not None:
- self.http.shutdown()
- self.http.server_close()
- if self.ws_sock is not None:
- self.ws_sock.close()
-
-
-__all__ = ["LiveWsHarness", "three_child_ws_payloads"]
diff --git a/tests/unit_tests/agentserver/rails/test_circuit_breaker_rail.py b/tests/unit_tests/agentserver/rails/test_circuit_breaker_rail.py
deleted file mode 100644
index 4d9f98764e..0000000000
--- a/tests/unit_tests/agentserver/rails/test_circuit_breaker_rail.py
+++ /dev/null
@@ -1,200 +0,0 @@
-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-
-"""Loop-detection tests for develop's CircuitBreakerRail.
-
-These cover repeat / ping-pong / unknown-tool / no-progress interrupts.
-They are not the issue 3975 OPEN/HALF_OPEN recovery breaker.
-"""
-
-from __future__ import annotations
-
-import time
-from types import SimpleNamespace
-
-from openjiuwen.core.single_agent.rail.base import (
- AgentCallbackContext,
- ToolCallInputs,
-)
-
-from jiuwenswarm.agents.harness.common.rails.execution_guard.circuit_breaker_rail import (
- CircuitBreakerConfig,
- CircuitBreakerRail,
- ToolCallRecord,
-)
-from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
- JiuWenSwarmDeepAdapter,
- _agent_ras_kwargs_from_config,
-)
-
-
-def _record(
- tool_name: str,
- args_hash: str,
- result_hash: str | None = "r1",
- *,
- has_error: bool = False,
-) -> ToolCallRecord:
- return ToolCallRecord(
- tool_name=tool_name,
- args_hash=args_hash,
- result_hash=result_hash,
- timestamp=time.time(),
- has_error=has_error,
- )
-
-
-def _rail(**overrides: int) -> CircuitBreakerRail:
- return CircuitBreakerRail(
- CircuitBreakerConfig(
- warning_threshold=overrides.get("warning_threshold", 3),
- critical_threshold=overrides.get("critical_threshold", 4),
- global_breaker_threshold=overrides.get("global_breaker_threshold", 5),
- unknown_tool_threshold=overrides.get("unknown_tool_threshold", 3),
- )
- )
-
-
-def test_generic_repeat_warns_without_force_finish() -> None:
- rail = _rail(warning_threshold=3, global_breaker_threshold=10)
- history = [
- _record("read_file", "a", f"out-{index}")
- for index in range(3)
- ]
- result = rail._detect(history, "read_file", "a")
- assert result.stuck is True
- assert result.level == "warning"
- assert result.detector == "generic_repeat"
-
-
-def test_global_breaker_interrupts_no_progress() -> None:
- rail = _rail(global_breaker_threshold=5)
- history = [_record("bash", "cmd", "same") for _ in range(5)]
- result = rail._detect(history, "bash", "cmd")
- assert result.stuck is True
- assert result.level == "critical"
- assert result.detector == "global_circuit_breaker"
-
-
-def test_unknown_tool_repeat_interrupts_error_streak() -> None:
- rail = _rail(unknown_tool_threshold=3, global_breaker_threshold=10)
- history = [
- _record("missing_tool", "x", f"err-{index}", has_error=True)
- for index in range(3)
- ]
- result = rail._detect(history, "missing_tool", "x")
- assert result.stuck is True
- assert result.level == "critical"
- assert result.detector == "unknown_tool_repeat"
-
-
-def test_ping_pong_critical_when_both_sides_stall() -> None:
- rail = _rail(critical_threshold=3, warning_threshold=2, global_breaker_threshold=20)
- history: list[ToolCallRecord] = []
- for _ in range(3):
- history.append(_record("read_file", "hash-a", "same-a"))
- history.append(_record("write_file", "hash-b", "same-b"))
- result = rail._detect(history, "write_file", "hash-b")
- assert result.stuck is True
- assert result.level == "critical"
- assert result.detector == "ping_pong"
-
-
-def test_cleanup_session_drops_history() -> None:
- rail = _rail()
- rail._histories["s1"] = [_record("bash", "a")]
- rail._histories["s2"] = [_record("bash", "b")]
- rail.cleanup_session("s1")
- assert "s1" not in rail._histories
- assert "s2" in rail._histories
-
-
-def test_detect_is_isolated_per_session_history() -> None:
- rail = _rail(warning_threshold=3, global_breaker_threshold=10)
- session_a = [_record("read_file", "a", f"a-{index}") for index in range(3)]
- session_b = [_record("read_file", "a", "once")]
- hot = rail._detect(session_a, "read_file", "a")
- cold = rail._detect(session_b, "read_file", "a")
- assert hot.detector == "generic_repeat"
- assert cold.stuck is False
-
-
-async def test_after_tool_call_force_finishes_unknown_tool() -> None:
- rail = _rail(unknown_tool_threshold=2, global_breaker_threshold=10)
- rail._histories["s1"] = [_record("ghost", "g", "e1", has_error=True)]
- ctx = AgentCallbackContext(
- agent=object(),
- inputs=ToolCallInputs(
- tool_call=SimpleNamespace(name="ghost", arguments={"k": 1}),
- tool_result={"success": False, "error": "not found"},
- ),
- extra={"__jiuwenswarm_cb_session_id__": "s1"},
- )
- await rail.after_tool_call(ctx)
- assert ctx.has_force_finish_request is True
-
-
-def test_circuit_breaker_builder_stays_disabled_by_default(monkeypatch) -> None:
- from jiuwenswarm.server.runtime.agent_adapter import interface_deep as deep_mod
-
- monkeypatch.setattr(deep_mod, "get_config", lambda: {"execution_guard": {}})
- adapter = JiuWenSwarmDeepAdapter()
- assert adapter._build_circuit_breaker_rail() is None
-
-
-def test_circuit_breaker_builder_rejects_invalid_thresholds(monkeypatch) -> None:
- from jiuwenswarm.server.runtime.agent_adapter import interface_deep as deep_mod
-
- monkeypatch.setattr(
- deep_mod,
- "get_config",
- lambda: {
- "execution_guard": {
- "circuit_breaker": {
- "enabled": True,
- "warning_threshold": "10",
- "critical_threshold": 5,
- }
- }
- },
- )
- adapter = JiuWenSwarmDeepAdapter()
- assert adapter._build_circuit_breaker_rail() is None
-
-
-def test_circuit_breaker_builder_coerces_string_thresholds(monkeypatch) -> None:
- from jiuwenswarm.server.runtime.agent_adapter import interface_deep as deep_mod
-
- monkeypatch.setattr(
- deep_mod,
- "get_config",
- lambda: {
- "execution_guard": {
- "circuit_breaker": {
- "enabled": True,
- "warning_threshold": "10",
- "critical_threshold": "20",
- "global_breaker_threshold": "30",
- "unknown_tool_threshold": "10",
- }
- }
- },
- )
- adapter = JiuWenSwarmDeepAdapter()
- rail = adapter._build_circuit_breaker_rail()
- assert rail is not None
- assert rail._config.warning_threshold == 10
- assert rail._config.critical_threshold == 20
-
-
-def test_dest_agent_ras_passthrough_is_not_disabled() -> None:
- """dest-stable RAS remains the default loop detector; do not overwrite it."""
- kwargs = _agent_ras_kwargs_from_config(
- {
- "agent_ras": {
- "enabled": True,
- "detectors": {"repeat_tool": {"enabled": True}},
- }
- }
- )
- assert kwargs["agent_ras"]["enabled"] is True
- assert kwargs["agent_ras"]["detectors"]["repeat_tool"]["enabled"] is True
diff --git a/tests/unit_tests/agentserver/rails/test_tool_result_error_detector.py b/tests/unit_tests/agentserver/rails/test_tool_result_error_detector.py
deleted file mode 100644
index e663d29eac..0000000000
--- a/tests/unit_tests/agentserver/rails/test_tool_result_error_detector.py
+++ /dev/null
@@ -1,255 +0,0 @@
-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-
-"""Contract tests for ToolResultErrorDetector.
-
-The detector's own docstring invites any module to import and reuse it, so
-its behaviour is a shared contract rather than a private helper of
-CircuitBreakerRail. Different consumers can want opposite things from it: a
-circuit breaker counting consecutive failures of one tool must not fire on a
-healthy result, while a rail that holds a task open until a required tool has
-succeeded must not read a failure as success.
-
-An unrecognised shape resolves to "no error", which is conservative for a
-consumer that only wants to avoid false positives and dangerous for one that
-must not miss a failure. That asymmetry is why every tool contract the
-detector is expected to understand is pinned here rather than left to
-whichever rail happens to exercise it.
-
-Adding a tool that signals failure in a bare string means registering its
-marker via ``ToolResultErrorDetector.register_plain_error_prefix`` from the
-feature's own module -- not editing ``_PLAIN_ERROR_PREFIXES``. That tuple
-stays generic; only ``[ERROR]:``, the project-wide tool-failure convention,
-belongs in it.
-"""
-
-from __future__ import annotations
-
-import json
-
-import pytest
-
-from jiuwenswarm.agents.harness.common.rails.execution_guard.circuit_breaker_rail import (
- ToolResultErrorDetector as Detector,
-)
-
-
-class _Result:
- """A tool result object exposing success/data/error attributes."""
-
- def __init__(self, success: bool, data=None, error=None) -> None:
- self.success = success
- self.data = data
- self.error = error
-
-
-# ---------------------------------------------------------------------------
-# Failures the detector must recognise
-# ---------------------------------------------------------------------------
-
-FAILURES = [
- pytest.param({"success": False, "error": "boom"}, id="dict-success-false"),
- pytest.param({"is_error": True}, id="dict-is-error"),
- pytest.param({"isError": "true"}, id="dict-isError-string"),
- pytest.param({"status": "failed"}, id="dict-status-failed"),
- pytest.param({"result_type": "error"}, id="dict-result-type"),
- pytest.param({"error": "something went wrong"}, id="dict-error-field"),
- pytest.param({"data": {"success": False}}, id="dict-nested-data"),
- # mcp_exec_command: a completed command that exited non-zero.
- pytest.param(
- json.dumps({"command": "git log", "exit_code": 128, "stdout": "",
- "stderr": "fatal: Out of memory, realloc failed"}),
- id="json-exit-code",
- ),
- pytest.param({"returncode": 1}, id="dict-returncode"),
- # Repr of a result object, as it reaches the session history.
- pytest.param("success=False data={'content': 'x'} error='boom'", id="repr-false"),
- # mcp_exec_command: the paths that never produce an exit code.
- pytest.param("[ERROR]: command timed out after 300s.", id="shell-timeout"),
- pytest.param("[ERROR]: command failed to start: No such file", id="shell-spawn"),
- pytest.param("[ERROR]: command execution failed: boom", id="shell-exec"),
- pytest.param("[ERROR]: background command failed: nope", id="shell-background"),
- # The same convention from other tool modules.
- pytest.param("[ERROR]: query cannot be empty.", id="search-empty-query"),
- pytest.param("[ERROR]: failed to fetch webpage: timeout", id="web-fetch-failed"),
- pytest.param("[ERROR]: read_pdf failed: boom", id="pdf-failed"),
- pytest.param(_Result(False, error="boom"), id="object-success-false"),
-]
-
-
[email protected]("value", FAILURES)
-def test_failures_are_recognised(value) -> None:
- assert Detector.has_error(value) is True
-
-
-# ---------------------------------------------------------------------------
-# Successes the detector must not misread
-# ---------------------------------------------------------------------------
-
-SUCCESSES = [
- pytest.param({"success": True, "data": {"content": "ok"}}, id="dict-success-true"),
- pytest.param({"status": "ok"}, id="dict-status-ok"),
- pytest.param({"error": None}, id="dict-error-none"),
- pytest.param({"error": "none"}, id="dict-error-literal-none"),
- pytest.param(
- json.dumps({"command": "git log", "exit_code": 0, "stdout": "d4c3e32a",
- "stderr": ""}),
- id="json-exit-zero",
- ),
- pytest.param("success=True data={'content': 'ok'} error=None", id="repr-true"),
- # mcp_free_search on success: bare prose, no envelope, no marker.
- pytest.param(
- "Free search results (DuckDuckGo) for: circuit breaker\n"
- "1. Circuit breaker pattern\n https://example.invalid/cb",
- id="search-plain-success",
- ),
- # wiki_query on success: the model's answer, returned bare. Nothing in
- # its shape separates it from arbitrary prose, which is exactly why a
- # plain-string convention has to be a marker no success can start with.
- pytest.param(
- "The retry budget is consumed per tool, not per session.",
- id="wiki-plain-success",
- ),
- pytest.param(_Result(True, data={"content": "ok"}), id="object-success-true"),
-]
-
-
[email protected]("value", SUCCESSES)
-def test_successes_are_not_flagged(value) -> None:
- assert Detector.has_error(value) is False
-
-
-# ---------------------------------------------------------------------------
-# Shapes the detector cannot classify
-# ---------------------------------------------------------------------------
-
-UNCLASSIFIABLE = [
- pytest.param(None, id="none"),
- pytest.param("", id="empty-string"),
- pytest.param("plain prose with no contract", id="free-text"),
- pytest.param("{not json", id="broken-json"),
-]
-
-
[email protected]("value", UNCLASSIFIABLE)
-def test_unclassifiable_shapes_claim_neither(value) -> None:
- """Neither an error nor an explicit success, and the consequences differ.
-
- A consumer that only wants to avoid false positives reads "not an error"
- and declines to count the call -- conservative, and it will not interrupt
- a run spuriously.
-
- A consumer that must not miss a failure reads the same value as
- satisfied, because its rule is `if not errored`. That is not an oversight
- to be tightened later: several tools return a bare string on success --
- `wiki_query` returns the model's answer, `mcp_free_search` returns a
- formatted result list -- so a gate that demanded explicit success would
- reject every one of them.
-
- The cost is real and worth stating plainly. A tool that signals failure
- in free text opens the gate for such a consumer. That is exactly the
- failure mode `_PLAIN_ERROR_PREFIXES` and `register_plain_error_prefix`
- exist to close: for any tool whose failure is a bare string, a registered
- marker is the only thing standing between a rejection and a task marked
- complete.
- """
- assert Detector.has_error(value) is False
- assert Detector.has_explicit_success(value) is False
-
-
-# ---------------------------------------------------------------------------
-# has_explicit_success is narrower than "not an error"
-# ---------------------------------------------------------------------------
-
-
-def test_explicit_success_requires_the_success_field() -> None:
- assert Detector.has_explicit_success({"success": True}) is True
- assert Detector.has_explicit_success({"status": "ok"}) is False
- assert Detector.has_explicit_success("Free search results for: anything") is False
-
-
-def test_a_success_field_beats_a_nonzero_exit_code() -> None:
- """An explicit success wins over the exit-code heuristic."""
- assert Detector.has_error({"success": True, "exit_code": 1}) is False
-
-
-def test_plain_error_prefix_is_matched_case_insensitively() -> None:
- assert Detector.has_error("[error]: command timed out after 300s.") is True
-
-
-def test_a_prefix_must_start_the_string() -> None:
- """A mention inside prose is not a failure signal."""
- assert Detector.has_error(
- "The tool replied [ERROR]: earlier, but this run succeeded."
- ) is False
-
-
-# ---------------------------------------------------------------------------
-# A deliberate non-match
-# ---------------------------------------------------------------------------
-
-WIKI_FAILURES = [
- pytest.param("Error: Query cannot be empty.", id="wiki-error-colon"),
- pytest.param("Error querying wiki: connection refused", id="wiki-error-querying"),
- pytest.param("Wiki Query Error: boom", id="wiki-error-suffix"),
-]
-
-
[email protected]("value", WIKI_FAILURES)
-def test_bare_error_prose_is_not_matched(value) -> None:
- """`wiki_tools` signals failure in prose, and that stays unrecognised.
-
- Three different shapes appear in one file, and the common part is the word
- "Error" in ordinary prose. Adding it as a prefix would flag any tool whose
- successful output begins with that word, so the detector deliberately does
- not match it.
-
- This is a decision, not an oversight. The fix belongs in the tools:
- converge those returns on the project's `[ERROR]:` convention, and they
- are covered by the existing entry with no change here. Teaching this
- detector every dialect is what produced the gap it was written to close.
- """
- assert Detector.has_error(value) is False
-
-
-# ---------------------------------------------------------------------------
-# register_plain_error_prefix: feature-owned markers, without editing the rail
-# ---------------------------------------------------------------------------
-
-
-def _clean_registered_prefixes():
- """Isolate a test's registrations from every other test in the suite."""
- saved = set(Detector._extra_plain_error_prefixes)
- try:
- yield
- finally:
- Detector._extra_plain_error_prefixes.clear()
- Detector._extra_plain_error_prefixes.update(saved)
-
-
-def test_registered_prefix_is_recognised(_clean_registered_prefixes) -> None:
- """A feature can teach the detector its own bare-string convention.
-
- A tool whose failure contract is a bare string of its own -- rather than
- the project-wide `[ERROR]:` -- registers that marker from its own module.
- Nothing feature-specific has to be added to the rail for it to be counted.
- """
- assert Detector.has_error("EXAMPLE_TOOL_ERROR: unknown snapshot id.") is False
-
- Detector.register_plain_error_prefix("EXAMPLE_TOOL_ERROR:")
-
- assert Detector.has_error(
- "EXAMPLE_TOOL_ERROR: unknown snapshot id. Correct the payload and "
- "call the tool again."
- ) is True
-
-
-def test_registered_prefix_is_matched_case_insensitively(_clean_registered_prefixes) -> None:
- Detector.register_plain_error_prefix("my_tool_error:")
- assert Detector.has_error("My_Tool_Error: boom") is True
-
-
-def test_registering_a_blank_prefix_is_a_no_op(_clean_registered_prefixes) -> None:
- before = set(Detector._extra_plain_error_prefixes)
- Detector.register_plain_error_prefix(" ")
- assert Detector._extra_plain_error_prefixes == before
diff --git a/tests/unit_tests/agentserver/test_agentserver_modes.py b/tests/unit_tests/agentserver/test_agentserver_modes.py
index 5e40ba2004..fbb58b4c6a 100644
--- a/tests/unit_tests/agentserver/test_agentserver_modes.py
+++ b/tests/unit_tests/agentserver/test_agentserver_modes.py
@@ -1931,7 +1931,7 @@ def test_deep_adapter_build_agent_rails_adds_ask_user_for_agent_modes(monkeypatc
monkeypatch.setattr(adapter, "_build_security_rail", lambda: None)
monkeypatch.setattr(adapter, "_build_heartbeat_rail", lambda: None)
monkeypatch.setattr(adapter, "_build_avatar_rail", lambda: None)
- monkeypatch.setattr(adapter, "_build_subagent_rail", lambda **_kwargs: None)
+ monkeypatch.setattr(adapter, "_build_subagent_rail", lambda: None)
monkeypatch.setattr(adapter, "_build_skill_rail", lambda **_kwargs: None)
monkeypatch.setattr(adapter, "_build_skill_retrieval_prompt_rail", lambda: None)
monkeypatch.setattr(adapter, "_build_symphony_orchestration_rail", lambda: orchestration_rail)
diff --git a/tests/unit_tests/agentserver/test_multi_session_notify.py b/tests/unit_tests/agentserver/test_multi_session_notify.py
deleted file mode 100644
index adeb539c11..0000000000
--- a/tests/unit_tests/agentserver/test_multi_session_notify.py
+++ /dev/null
@@ -1,142 +0,0 @@
-from __future__ import annotations
-
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import pytest
-
-from jiuwenswarm.agents.harness.common.tools.multi_session_toolkits import (
- MultiSessionToolkit,
- SessionTask,
- Status,
-)
-from jiuwenswarm.server.runtime.agent_manager import AgentManager
-
-
-def _completed_toolkit() -> MultiSessionToolkit:
- toolkit = object.__new__(MultiSessionToolkit)
- toolkit.session_id = "parent-session"
- toolkit.channel_id = "web"
- toolkit.request_id = "request-1"
- toolkit._agent_manager = None
- toolkit.sessions = [
- SessionTask(
- session_id="child-session",
- description="Summarize the result",
- status=Status.COMPLETED,
- result="done",
- )
- ]
- toolkit._send_task_notification = AsyncMock()
- return toolkit
-
-
-async def test_completed_batch_uses_current_agent_manager_contract() -> None:
- toolkit = _completed_toolkit()
- manager = MagicMock(spec=AgentManager)
- manager.get_agent_nowait.return_value = None
- server = MagicMock()
- server.get_agent_manager.return_value = manager
- server.get_agent.return_value = None
-
- with (
- patch(
- "jiuwenswarm.server.agent_ws_server.AgentWebSocketServer.current_instance",
- return_value=server,
- ),
- patch(
- "jiuwenswarm.agents.harness.common.tools.multi_session_toolkits.send_runtime_push",
- new=AsyncMock(return_value=True),
- ) as push,
- ):
- await toolkit.notify("child-session", Status.COMPLETED, result="done")
-
- manager.get_agent_nowait.assert_called_once_with("web")
- server.get_agent.assert_called_once()
- push.assert_awaited_once()
-
-
-async def test_completed_batch_uses_injected_agent_manager() -> None:
- toolkit = _completed_toolkit()
- manager = MagicMock(spec=AgentManager)
- manager.get_agent_nowait.return_value = None
- toolkit._agent_manager = manager
-
- with (
- patch(
- "jiuwenswarm.server.agent_ws_server.AgentWebSocketServer.current_instance",
- ) as current_instance,
- patch(
- "jiuwenswarm.agents.harness.common.tools.multi_session_toolkits.send_runtime_push",
- new=AsyncMock(return_value=True),
- ) as push,
- ):
- await toolkit.notify("child-session", Status.COMPLETED, result="done")
-
- current_instance.assert_not_called()
- manager.get_agent_nowait.assert_called_once_with("web")
- push.assert_awaited_once()
-
-
-async def test_notify_without_runtime_host_keeps_local_summary() -> None:
- toolkit = _completed_toolkit()
-
- with (
- patch(
- "jiuwenswarm.agents.harness.common.tools.multi_session_toolkits.send_runtime_push",
- new=AsyncMock(return_value=False),
- ) as push,
- patch(
- "jiuwenswarm.agents.harness.common.tools.multi_session_toolkits.logger"
- ) as toolkit_logger,
- ):
- await toolkit.notify("child-session", Status.COMPLETED, result="done")
-
- push.assert_awaited_once()
- info_messages = [
- " ".join(str(part) for part in call.args)
- for call in toolkit_logger.info.call_args_list
- ]
- assert any("Runtime push host unavailable" in message for message in info_messages)
- assert any("parent-session" in message for message in info_messages)
-
-
-async def test_agent_server_push_host_lifecycle_out_of_order(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- from jiuwenswarm.runtime import host_services
- from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer
-
- monkeypatch.setattr(host_services, "_runtime_push_handler", None)
- monkeypatch.setattr(host_services, "_runtime_push_handlers", [])
-
- first = AgentWebSocketServer.__new__(AgentWebSocketServer)
- first._runtime_push_handler = None
- first._previous_runtime_push_handler = None
-
- async def first_push(_msg: dict) -> int:
- return 1
-
- first.send_push = first_push # type: ignore[method-assign]
-
- second = AgentWebSocketServer.__new__(AgentWebSocketServer)
- second._runtime_push_handler = None
- second._previous_runtime_push_handler = None
- calls: list[str] = []
-
- async def second_push(_msg: dict) -> int:
- calls.append("second")
- return 1
-
- second.send_push = second_push # type: ignore[method-assign]
-
- first._install_runtime_push_host()
- second._install_runtime_push_host()
- first._restore_runtime_push_host()
- assert await host_services.send_runtime_push({"value": 1}) is True
- assert calls == ["second"]
- second._restore_runtime_push_host()
- assert await host_services.send_runtime_push({"value": 2}) is False
diff --git a/tests/unit_tests/agentserver/test_statusline_setup_subagent.py b/tests/unit_tests/agentserver/test_statusline_setup_subagent.py
deleted file mode 100644
index 26561371c7..0000000000
--- a/tests/unit_tests/agentserver/test_statusline_setup_subagent.py
+++ /dev/null
@@ -1,209 +0,0 @@
-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-
-"""Registration tests for the built-in statusline-setup subagent."""
-
-from __future__ import annotations
-
-from unittest.mock import MagicMock
-
-from openjiuwen.harness.rails import SysOperationRail
-
-from jiuwenswarm.agents.swarm.config_specs import build_member_subagent_specs
-from jiuwenswarm.agents.swarm import registry
-from jiuwenswarm.server.runtime.agent_adapter.interface_code import (
- JiuwenSwarmCodeAdapter,
-)
-from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
- JiuWenSwarmDeepAdapter,
-)
-from jiuwenswarm.server.runtime.agent_adapter.statusline_setup_agent import (
- DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS,
- STATUSLINE_SETUP_AGENT_TYPE,
-)
-from jiuwenswarm.server.runtime.agent_config_service import AgentConfigService
-
-
-def test_statusline_setup_is_a_builtin_agent_definition(tmp_path):
- definition = AgentConfigService(tmp_path).get_agent(STATUSLINE_SETUP_AGENT_TYPE)
-
- assert definition is not None
- assert definition.source == "builtin"
- assert definition.tools == ["Read", "Write", "Edit", "Bash"]
- assert "statusline-setup subagent" in definition.prompt
-
-
-def test_single_agent_runtime_registers_statusline_setup(monkeypatch, tmp_path):
- adapter = JiuWenSwarmDeepAdapter()
- adapter._workspace_dir = str(tmp_path)
- adapter._sys_operation = None
- monkeypatch.setattr(adapter, "_browser_runtime_enabled", lambda: False)
-
- subagents, _ = adapter._build_configured_subagents(
- MagicMock(),
- {
- "max_iterations": 20,
- "subagents": {
- STATUSLINE_SETUP_AGENT_TYPE: {
- "enabled": True,
- "max_iterations": 9,
- }
- },
- },
- {},
- )
-
- assert subagents is not None
- assert [spec.agent_card.name for spec in subagents] == [STATUSLINE_SETUP_AGENT_TYPE]
- assert subagents[0].max_iterations == 9
- assert subagents[0].enable_task_loop is False
- assert any(isinstance(rail, SysOperationRail) for rail in subagents[0].rails)
-
-
-def test_single_agent_runtime_does_not_register_when_disabled(monkeypatch, tmp_path):
- adapter = JiuWenSwarmDeepAdapter()
- adapter._workspace_dir = str(tmp_path)
- adapter._sys_operation = None
- monkeypatch.setattr(adapter, "_browser_runtime_enabled", lambda: False)
-
- subagents, _ = adapter._build_configured_subagents(
- MagicMock(),
- {"subagents": {STATUSLINE_SETUP_AGENT_TYPE: {"enabled": False}}},
- {},
- )
-
- assert subagents is None
-
-
-def test_code_runtime_registers_statusline_setup_by_default(monkeypatch, tmp_path):
- adapter = JiuwenSwarmCodeAdapter()
- adapter._workspace_dir = str(tmp_path)
- adapter._project_dir = str(tmp_path)
- adapter._coding_memory_rail = None
- sys_operation = MagicMock()
- adapter._sys_operation = sys_operation
- monkeypatch.setattr(adapter, "_browser_runtime_enabled", lambda: False)
-
- subagents, _ = adapter._build_configured_subagents(
- MagicMock(),
- {"max_iterations": 20},
- {},
- )
-
- assert subagents is not None
- assert [spec.agent_card.name for spec in subagents] == [
- STATUSLINE_SETUP_AGENT_TYPE,
- "explore_agent",
- "plan_agent",
- ]
- statusline_spec = subagents[0]
- assert statusline_spec.max_iterations == DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS
- assert statusline_spec.enable_task_loop is False
- assert statusline_spec.sys_operation is sys_operation
- assert statusline_spec.workspace == str(tmp_path)
-
-
-def test_code_runtime_honors_explicit_statusline_disable(monkeypatch, tmp_path):
- adapter = JiuwenSwarmCodeAdapter()
- adapter._workspace_dir = str(tmp_path)
- adapter._project_dir = str(tmp_path)
- adapter._coding_memory_rail = None
- adapter._sys_operation = MagicMock()
- monkeypatch.setattr(adapter, "_browser_runtime_enabled", lambda: False)
-
- subagents, _ = adapter._build_configured_subagents(
- MagicMock(),
- {"subagents": {STATUSLINE_SETUP_AGENT_TYPE: {"enabled": False}}},
- {},
- )
-
- assert subagents is not None
- assert [spec.agent_card.name for spec in subagents] == [
- "explore_agent",
- "plan_agent",
- ]
-
-
-def test_code_runtime_honors_explicit_statusline_iteration_budget(
- monkeypatch,
- tmp_path,
-):
- adapter = JiuwenSwarmCodeAdapter()
- adapter._workspace_dir = str(tmp_path)
- adapter._project_dir = str(tmp_path)
- adapter._coding_memory_rail = None
- adapter._sys_operation = MagicMock()
- monkeypatch.setattr(adapter, "_browser_runtime_enabled", lambda: False)
-
- subagents, _ = adapter._build_configured_subagents(
- MagicMock(),
- {
- "max_iterations": 100,
- "subagents": {
- STATUSLINE_SETUP_AGENT_TYPE: {
- "enabled": True,
- "max_iterations": 7,
- }
- },
- },
- {},
- )
-
- assert subagents is not None
- assert subagents[0].agent_card.name == STATUSLINE_SETUP_AGENT_TYPE
- assert subagents[0].max_iterations == 7
-
-
-def test_team_member_runtime_registers_same_builtin_subagent():
- specs = build_member_subagent_specs(
- {
- "react": {
- "subagents": {
- STATUSLINE_SETUP_AGENT_TYPE: {"enabled": True},
- }
- }
- },
- "team",
- "leader",
- )
-
- assert len(specs) == 1
- assert specs[0].agent_card.name == STATUSLINE_SETUP_AGENT_TYPE
- assert specs[0].factory_name == registry.STATUSLINE_SETUP_AGENT
- assert (
- specs[0].factory_kwargs["max_iterations"]
- == DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS
- )
-
-
-def test_team_member_runtime_honors_statusline_disable_and_iteration_budget():
- disabled_specs = build_member_subagent_specs(
- {
- "react": {
- "subagents": {
- STATUSLINE_SETUP_AGENT_TYPE: {"enabled": False},
- }
- }
- },
- "team",
- "leader",
- )
- assert disabled_specs == []
-
- configured_specs = build_member_subagent_specs(
- {
- "react": {
- "max_iterations": 100,
- "subagents": {
- STATUSLINE_SETUP_AGENT_TYPE: {
- "enabled": True,
- "max_iterations": 7,
- },
- },
- }
- },
- "team",
- "leader",
- )
- assert len(configured_specs) == 1
- assert configured_specs[0].agent_card.name == STATUSLINE_SETUP_AGENT_TYPE
- assert configured_specs[0].factory_kwargs["max_iterations"] == 7
diff --git a/tests/unit_tests/agentserver/test_subagent_history_routing.py b/tests/unit_tests/agentserver/test_subagent_history_routing.py
deleted file mode 100644
index 8123e782ba..0000000000
--- a/tests/unit_tests/agentserver/test_subagent_history_routing.py
+++ /dev/null
@@ -1,116 +0,0 @@
-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-
-"""Regression tests for parent-owned subagent history persistence."""
-
-from __future__ import annotations
-
-from jiuwenswarm.common.schema.message import EventType
-from jiuwenswarm.gateway.channel_manager.web.web_ws_transport import (
- _WEB_FULL_PAYLOAD_EVENT_TYPES,
-)
-from jiuwenswarm.server.runtime.session import session_history, session_metadata
-
-
-def test_subagent_history_writes_use_dedicated_child_bucket(monkeypatch) -> None:
- persisted: list[tuple[str, str, list[dict], str | None]] = []
- metadata_updates: list[dict] = []
- monkeypatch.setattr(
- session_history,
- "_batch_write_subagent_items",
- lambda sid, child_id, items, root: persisted.append((sid, child_id, items, root)),
- )
- monkeypatch.setattr(
- session_metadata,
- "update_session_metadata",
- lambda **kwargs: metadata_updates.append(kwargs),
- )
-
- session_history.append_history_record(
- session_id="parent-session",
- request_id="request-1",
- channel_id="web",
- role="assistant",
- content="result",
- timestamp=1.0,
- event_type="chat.final",
- task_id="task-1",
- subagent_id="subagent-1",
- mode="subagent",
- )
-
- assert len(persisted) == 1
- sid, child_id, items, _root = persisted[0]
- assert sid == "parent-session"
- assert child_id == "subagent-1"
- assert len(items) == 1
- assert items[0]["session_id"] == "parent-session"
- assert items[0]["subagent_id"] == "subagent-1"
- assert items[0]["mode"] == "subagent"
- assert metadata_updates == []
-
-
-def test_subagent_rows_go_under_parent_subagents_dir(tmp_path, monkeypatch) -> None:
- monkeypatch.setattr(session_history, "get_agent_sessions_dir", lambda: tmp_path)
- session_history.append_history_record(
- session_id="parent1",
- request_id="r-parent",
- channel_id="web",
- role="user",
- content="hello",
- timestamp=1.0,
- )
- session_history.append_history_record(
- session_id="parent1",
- subagent_id="sa-explore-1",
- request_id="sa-explore-1:1",
- channel_id="subagent",
- role="assistant",
- content="child note",
- timestamp=2.0,
- event_type="chat.delta",
- mode="subagent",
- extra={"parent_session_id": "parent1"},
- )
-
- parent_rows = session_history.load_history_records("parent1")
- child_rows = session_history.load_history_records(
- "parent1",
- subagent_id="sa-explore-1",
- )
- assert [row.get("content") for row in parent_rows] == ["hello"]
- assert any(row.get("content") == "child note" for row in child_rows)
- child_path, error = session_history.resolve_subagent_history_path(
- "parent1",
- "sa-explore-1",
- create=False,
- )
- assert error is None
- assert child_path is not None
- assert child_path.exists()
- assert "subagents" in child_path.parts
- assert not session_history.history_exists("parent1", subagent_id="../escape")
-
-
-def test_empty_subagent_activity_is_persistable(tmp_path, monkeypatch) -> None:
- monkeypatch.setattr(session_history, "get_agent_sessions_dir", lambda: tmp_path)
- session_history.append_history_record(
- session_id="parent1",
- subagent_id="sa-1",
- request_id="sa-1:activity:turn:1",
- channel_id="subagent",
- role="assistant",
- content="",
- timestamp=3.0,
- event_type="chat.subagent_activity",
- extra={"subagent_activity": {"subagent_id": "sa-1", "summary": ""}},
- mode="subagent",
- )
- rows = session_history.load_history_records("parent1", subagent_id="sa-1")
- assert len(rows) == 1
- assert rows[0]["event_type"] == "chat.subagent_activity"
-
-
-def test_web_allowlist_includes_subagent_activity() -> None:
- assert EventType.CHAT_SUBAGENT_ACTIVITY.value == "chat.subagent_activity"
- assert "chat.subagent_activity" in _WEB_FULL_PAYLOAD_EVENT_TYPES
- assert "task.start" in _WEB_FULL_PAYLOAD_EVENT_TYPES
diff --git a/tests/unit_tests/runtime/test_runtime_host_services.py b/tests/unit_tests/runtime/test_runtime_host_services.py
deleted file mode 100644
index 50350f4fae..0000000000
--- a/tests/unit_tests/runtime/test_runtime_host_services.py
+++ /dev/null
@@ -1,68 +0,0 @@
-from __future__ import annotations
-
-import pytest
-
-from jiuwenswarm.runtime import host_services
-
-
[email protected](autouse=True)
-def _isolate_host_handlers(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(host_services, "_runtime_push_handler", None)
- monkeypatch.setattr(host_services, "_runtime_push_handlers", [])
-
-
-async def test_push_owner_out_of_order_restore_does_not_revive_stale_owner() -> None:
- calls: list[str] = []
-
- async def first(_message: dict) -> None:
- calls.append("first")
-
- async def second(_message: dict) -> None:
- calls.append("second")
-
- first_previous = host_services.install_runtime_push_handler(first)
- second_previous = host_services.install_runtime_push_handler(second)
-
- host_services.restore_runtime_push_handler(first, first_previous)
- assert await host_services.send_runtime_push({"value": 1}) is True
- assert calls == ["second"]
-
- host_services.restore_runtime_push_handler(second, second_previous)
- assert await host_services.send_runtime_push({"value": 2}) is False
- assert calls == ["second"]
-
-
-async def test_runtime_host_push_transport_has_explicit_unavailable_contract() -> None:
- transport = host_services.RuntimeHostPushTransport()
-
- with pytest.raises(RuntimeError, match="without a resident host"):
- await transport.send_push({"value": 1})
-
- captured: list[dict] = []
-
- async def capture(message: dict) -> None:
- captured.append(message)
-
- previous = host_services.install_runtime_push_handler(capture)
- try:
- await transport.send_push({"value": 2})
- finally:
- host_services.restore_runtime_push_handler(capture, previous)
-
- assert captured == [{"value": 2}]
-
-
-async def test_runtime_push_propagates_explicit_delivery_failure() -> None:
- async def reject(_message: dict) -> bool:
- return False
-
- previous = host_services.install_runtime_push_handler(reject)
- try:
- assert await host_services.send_runtime_push({"value": 1}) is False
- with pytest.raises(RuntimeError, match="without a resident host"):
- await host_services.RuntimeHostPushTransport().send_push({"value": 2})
- finally:
- host_services.restore_runtime_push_handler(reject, previous)