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(context_engine): integrate proactive context (MR !4489)

程凯1cddb574823e
diff --git a/jiuwenswarm/common/schema/message.py b/jiuwenswarm/common/schema/message.py
index f276e661e3..9abb0defd6 100644
--- a/jiuwenswarm/common/schema/message.py
+++ b/jiuwenswarm/common/schema/message.py
@@ -164,6 +164,33 @@ class ReqMethod(Enum):
SYMPHONY_GRAPH = "symphony.graph"
SYMPHONY_PLAN = "symphony.plan"
+ PERSONAL_CONTEXT_RUNTIME_STATUS = "personal_context.runtime.status"
+ PERSONAL_CONTEXT_RUNTIME_START = "personal_context.runtime.start"
+ PERSONAL_CONTEXT_RUNTIME_STOP = "personal_context.runtime.stop"
+ PERSONAL_CONTEXT_RUNTIME_GET_CONFIG = "personal_context.runtime.get_config"
+ PERSONAL_CONTEXT_RUNTIME_PATCH_CONFIG = "personal_context.runtime.patch_config"
+ PERSONAL_CONTEXT_RUNTIME_SELECT_MODEL = "personal_context.runtime.select_model"
+ PERSONAL_CONTEXT_FETCH_LIST_SERVICES = "personal_context.fetch.list_services"
+ PERSONAL_CONTEXT_FETCH_CREATE_SERVICE = "personal_context.fetch.create_service"
+ PERSONAL_CONTEXT_FETCH_DELETE_SERVICE = "personal_context.fetch.delete_service"
+ PERSONAL_CONTEXT_FETCH_PATCH_SERVICE = "personal_context.fetch.patch_service"
+ PERSONAL_CONTEXT_FETCH_START_SERVICE = "personal_context.fetch.start_service"
+ PERSONAL_CONTEXT_FETCH_STOP_SERVICE = "personal_context.fetch.stop_service"
+ PERSONAL_CONTEXT_FETCH_START_SCHEDULER = "personal_context.fetch.start_scheduler"
+ PERSONAL_CONTEXT_FETCH_STOP_SCHEDULER = "personal_context.fetch.stop_scheduler"
+ PERSONAL_CONTEXT_FETCH_RUN_ALL = "personal_context.fetch.run_all"
+ PERSONAL_CONTEXT_FETCH_RUN_ONE = "personal_context.fetch.run_one"
+ PERSONAL_CONTEXT_FETCH_GET_RUN_STATUS = "personal_context.fetch.get_run_status"
+ PERSONAL_CONTEXT_FETCH_GET_AUTHORIZATION_STATUS = (
+ "personal_context.fetch.get_authorization_status"
+ )
+ PERSONAL_CONTEXT_FETCH_AUTHORIZE_PROVIDER = (
+ "personal_context.fetch.authorize_provider"
+ )
+ PERSONAL_CONTEXT_CONTEXT_STREAM_GRAPH = "personal_context.context.stream_graph"
+ PERSONAL_CONTEXT_CONTEXT_SEARCH_PAGES = "personal_context.context.search_pages"
+ PERSONAL_CONTEXT_CONTEXT_GET_NODE = "personal_context.context.get_node"
+
# Plugin management (reuses skills marketplace infrastructure)
PLUGINS_LIST = "plugins.list"
PLUGINS_INSTALL = "plugins.install"
diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
index 88843c6006..8578494476 100644
--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
@@ -697,6 +697,28 @@ _FORWARD_REQ_METHODS = frozenset({
"symphony.score_status",
"symphony.graph",
"symphony.plan",
+ "personal_context.runtime.status",
+ "personal_context.runtime.start",
+ "personal_context.runtime.stop",
+ "personal_context.runtime.get_config",
+ "personal_context.runtime.patch_config",
+ "personal_context.runtime.select_model",
+ "personal_context.fetch.list_services",
+ "personal_context.fetch.create_service",
+ "personal_context.fetch.delete_service",
+ "personal_context.fetch.patch_service",
+ "personal_context.fetch.start_service",
+ "personal_context.fetch.stop_service",
+ "personal_context.fetch.start_scheduler",
+ "personal_context.fetch.stop_scheduler",
+ "personal_context.fetch.run_all",
+ "personal_context.fetch.run_one",
+ "personal_context.fetch.get_run_status",
+ "personal_context.fetch.get_authorization_status",
+ "personal_context.fetch.authorize_provider",
+ "personal_context.context.stream_graph",
+ "personal_context.context.search_pages",
+ "personal_context.context.get_node",
"plugins.list",
"plugins.install",
"plugins.uninstall",
@@ -809,6 +831,28 @@ _FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset({
"symphony.score_status",
"symphony.graph",
"symphony.plan",
+ "personal_context.runtime.status",
+ "personal_context.runtime.start",
+ "personal_context.runtime.stop",
+ "personal_context.runtime.get_config",
+ "personal_context.runtime.patch_config",
+ "personal_context.runtime.select_model",
+ "personal_context.fetch.list_services",
+ "personal_context.fetch.create_service",
+ "personal_context.fetch.delete_service",
+ "personal_context.fetch.patch_service",
+ "personal_context.fetch.start_service",
+ "personal_context.fetch.stop_service",
+ "personal_context.fetch.start_scheduler",
+ "personal_context.fetch.stop_scheduler",
+ "personal_context.fetch.run_all",
+ "personal_context.fetch.run_one",
+ "personal_context.fetch.get_run_status",
+ "personal_context.fetch.get_authorization_status",
+ "personal_context.fetch.authorize_provider",
+ "personal_context.context.stream_graph",
+ "personal_context.context.search_pages",
+ "personal_context.context.get_node",
"plugins.list",
"plugins.install",
"plugins.uninstall",
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index e1d450f3b6..981f8458c0 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -155,6 +155,11 @@ from jiuwenswarm.common.security.ws_origin import (
is_origin_check_enabled,
is_allowed_browser_origin,
)
+from jiuwenswarm.server.personal_context import PersonalContextHostAPI
+from jiuwenswarm.server.personal_context.ws_handler import (
+ PERSONAL_CONTEXT_REQUEST_METHODS as _PERSONAL_CONTEXT_REQ_METHODS,
+ handle_personal_context_request,
+)
logger = logging.getLogger(__name__)
@@ -361,6 +366,11 @@ class AgentWebSocketServer:
self._default_model: Optional[Any] = None
# 本地 jiuwenbox 子进程管理器 (lazy 启动, 在 /sandbox enable 时 ensure_running)
self._jiuwenbox_runner = JiuwenBoxRunner.instance()
+ # AgentServer 内唯一持有的进程内 PersonalContext Host;Context Rail 使用同一固定目录。
+ self._personal_context_host = PersonalContextHostAPI(
+ home=Path.home() / ".jiuwenswarm" / ".personal_context",
+ )
+ self._personal_context_start_task: asyncio.Task[None] | None = None
# Proactive recommendation engine (set by app_agentserver for debug trigger)
self._proactive_engine: Any = None
get_acp_output_manager().set_send_push_callback(
@@ -528,6 +538,10 @@ class AgentWebSocketServer:
await _warmup_phase3()
asyncio.create_task(_phase3_after_phase12(), name="startup-warmup-query")
+ self._personal_context_start_task = asyncio.create_task(
+ self._start_personal_context_best_effort(),
+ name="personal-context-host-start",
+ )
# WS 监听已经开放, 现在按 config.yaml::sandbox 的 runtime.enabled +
# startup_mode 决定要不要自动把 jiuwenbox 子进程也拉起来。失败不阻塞
# 启动 (用户依然可以在 TUI 里跑 /sandbox enable 重试)。
@@ -581,6 +595,43 @@ class AgentWebSocketServer:
lag_ms,
)
+ async def _start_personal_context_best_effort(self) -> None:
+ """Start optional PersonalContext without changing AgentServer readiness."""
+ start_cancelled: asyncio.CancelledError | None = None
+ try:
+ await self._personal_context_host.start()
+ except asyncio.CancelledError as exc:
+ start_cancelled = exc
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[AgentWebSocketServer] optional PersonalContext startup failed: %s",
+ type(exc).__name__,
+ )
+ return
+ if start_cancelled is not None:
+ raise start_cancelled
+
+ rail_sync_cancelled: asyncio.CancelledError | None = None
+ try:
+ state_reader = getattr(
+ self._personal_context_host, "is_runtime_enabled", None
+ )
+ enabled = bool(await state_reader()) if callable(state_reader) else False
+ manager_setter = getattr(
+ self._agent_manager, "set_personal_context_runtime_enabled", None
+ )
+ if callable(manager_setter):
+ await manager_setter(enabled)
+ except asyncio.CancelledError as exc:
+ rail_sync_cancelled = exc
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[AgentWebSocketServer] optional PersonalContext Rail sync failed: %s",
+ type(exc).__name__,
+ )
+ if rail_sync_cancelled is not None:
+ raise rail_sync_cancelled
+
async def _bootstrap_internal_jiuwenbox(self) -> None:
"""启动时按 ``config.yaml::sandbox`` 自动拉起 jiuwenbox 子进程。
@@ -930,8 +981,46 @@ class AgentWebSocketServer:
)
return forbidden_origin_response(args)
+ async def _stop_personal_context_best_effort(self) -> None:
+ """Cancel PersonalContext startup and stop PersonalContext without masking main shutdown."""
+ start_task = self._personal_context_start_task
+ self._personal_context_start_task = None
+ if start_task is not None:
+ if not start_task.done():
+ start_task.cancel()
+ try:
+ await start_task
+ except asyncio.CancelledError:
+ current_task = asyncio.current_task()
+ if current_task is not None and current_task.cancelling():
+ raise
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[AgentWebSocketServer] optional PersonalContext startup cleanup failed: %s",
+ type(exc).__name__,
+ )
+ stop_cancelled: asyncio.CancelledError | None = None
+ try:
+ await self._personal_context_host.stop()
+ except asyncio.CancelledError as exc:
+ stop_cancelled = exc
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[AgentWebSocketServer] optional PersonalContext stop failed: %s",
+ type(exc).__name__,
+ )
+ if stop_cancelled is not None:
+ raise stop_cancelled
+
async def stop(self) -> None:
"""停止 WebSocket 服务端."""
+ try:
+ await self._stop_main_services()
+ finally:
+ await self._stop_personal_context_best_effort()
+
+ async def _stop_main_services(self) -> None:
+ """Run the unchanged AgentServer shutdown before optional PersonalContext cleanup."""
global _startup_warmup_task
async def _cancel_warmup_task(task: asyncio.Task[None] | None, label: str) -> None:
@@ -1125,6 +1214,23 @@ class AgentWebSocketServer:
return
request = result.request
+ # PersonalContext 请求在通用流水线之前拦截:其 wire 语义(host 持有、
+ # runtime 开关联动)与表驱动分发无关,直接交给独立 handler。
+ if request.req_method in _PERSONAL_CONTEXT_REQ_METHODS:
+ manager = getattr(self, "_agent_manager", None)
+ runtime_callback = getattr(
+ manager, "set_personal_context_runtime_enabled", None
+ )
+ await handle_personal_context_request(
+ self._personal_context_host,
+ ws,
+ request,
+ send_lock,
+ runtime_enabled_changed=(
+ runtime_callback if callable(runtime_callback) else None
+ ),
+ )
+ return
# 汇合点在server/pipeline.py
ctx = RequestContext(
request=request,
diff --git a/jiuwenswarm/server/personal_context/__init__.py b/jiuwenswarm/server/personal_context/__init__.py
new file mode 100644
index 0000000000..3d44bf8a49
--- /dev/null
+++ b/jiuwenswarm/server/personal_context/__init__.py
@@ -0,0 +1,5 @@
+"""JiuwenSwarm's in-process personal-context host boundary."""
+
+from jiuwenswarm.server.personal_context.host_api import PersonalContextHostAPI
+
+__all__ = ["PersonalContextHostAPI"]
diff --git a/jiuwenswarm/server/personal_context/host_api.py b/jiuwenswarm/server/personal_context/host_api.py
new file mode 100644
index 0000000000..89e4d83332
--- /dev/null
+++ b/jiuwenswarm/server/personal_context/host_api.py
@@ -0,0 +1,946 @@
+"""JiuwenSwarm's in-process owner of the embedded PersonalContext runtime.
+
+The Host owns the configuration file and Core lifecycle, and delegates Context
+queries to Core. It does not expose a transport, create a second service
+object, or read any Context file itself.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+from copy import deepcopy
+import os
+from pathlib import Path
+import stat
+import tempfile
+from typing import NoReturn, cast
+
+import yaml
+
+from openjiuwen.harness.personal_context import PersonalContext
+
+from jiuwenswarm.common.config import get_default_models
+
+
+_CONFIG_FILENAME = "personal_context.yaml"
+_MAX_CONFIG_BYTES = 4 * 1024 * 1024
+_STOP_TIMEOUT_SECONDS = 30.0
+
+
+def _initial_stored_config(*, enabled: bool) -> dict[str, object]:
+ return {
+ "enabled": enabled,
+ "fetching_enabled": False,
+ "strategy_profile": "rules",
+ "fetch_services": [],
+ }
+
+
+def _unconfigured_projection() -> dict[str, object]:
+ return {
+ "configured": False,
+ "enabled": False,
+ "fetching_enabled": False,
+ "strategy_profile": "rules",
+ "model_index": None,
+ "fetch_services": [],
+ }
+
+
+def _host_error(
+ message: str,
+ *,
+ status_name: str = "CONTEXT_PROACTIVE_CONFIG_INVALID",
+ cause: BaseException | None = None,
+) -> PersonalContext.Error:
+ """Create the existing Core error type without adding a Host exception."""
+
+ # PersonalContext.Config.from_dict() is the Core's public error-construction boundary.
+ # Deliberately use it instead of importing another Core error class here:
+ # the JiuwenSwarm side has exactly one Core import, PersonalContext.
+ try:
+ PersonalContext.Config.from_dict({})
+ except PersonalContext.Error as baseline:
+ # Core intentionally keeps PersonalContext-owned status values behind the single
+ # PersonalContext import; this Host compatibility bridge therefore uses its
+ # protected resolver without importing a second Core symbol.
+ status = PersonalContext._status_for_name(status_name) # pylint: disable=protected-access
+ return type(baseline)(status, msg=message, cause=cause)
+ return PersonalContext.Error(PersonalContext.Error.status, msg=message, cause=cause)
+
+
+def _raise_host_error(
+ message: str,
+ *,
+ status_name: str = "CONTEXT_PROACTIVE_CONFIG_INVALID",
+ cause: BaseException | None = None,
+) -> NoReturn:
+ raise _host_error(message, status_name=status_name, cause=cause) from None
+
+
+def _as_host_error(
+ exc: BaseException,
+ message: str,
+ *,
+ status_name: str = "CONTEXT_PROACTIVE_STATE_INVALID",
+) -> PersonalContext.Error:
+ if isinstance(exc, PersonalContext.Error):
+ return exc
+ return _host_error(message, status_name=status_name, cause=exc)
+
+
+def _reject_symlink_chain(path: Path) -> None:
+ current = path
+ while True:
+ if current.is_symlink():
+ _raise_host_error(
+ "PersonalContext configuration path must not traverse a symlink",
+ status_name="CONTEXT_PROACTIVE_FILE_EXECUTION_ERROR",
+ )
+ parent = current.parent
+ if parent == current:
+ return
+ current = parent
+
+
+def _serialize_config(config: dict[str, object]) -> bytes:
+ try:
+ text = yaml.safe_dump(config, allow_unicode=True, sort_keys=False)
+ payload = text.encode("utf-8")
+ if len(payload) > _MAX_CONFIG_BYTES:
+ _raise_host_error("PersonalContext configuration exceeds the 4 MiB limit")
+ return payload
+ except PersonalContext.Error:
+ raise
+ except Exception as exc:
+ _raise_host_error(
+ "PersonalContext configuration could not be serialized", cause=exc
+ )
+
+
+def _stage_yaml(path: Path, payload: bytes) -> Path:
+ temporary: Path | None = None
+ try:
+ _reject_symlink_chain(path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.NamedTemporaryFile(
+ mode="wb",
+ dir=path.parent,
+ prefix=f".{path.name}.",
+ suffix=".tmp",
+ delete=False,
+ ) as handle:
+ temporary = Path(handle.name)
+ handle.write(payload)
+ handle.flush()
+ os.fsync(handle.fileno())
+ with contextlib.suppress(OSError):
+ os.chmod(temporary, 0o600)
+ return temporary
+ except PersonalContext.Error:
+ if temporary is not None:
+ with contextlib.suppress(FileNotFoundError):
+ temporary.unlink()
+ raise
+ except Exception as exc:
+ if temporary is not None:
+ with contextlib.suppress(FileNotFoundError):
+ temporary.unlink()
+ _raise_host_error(
+ "PersonalContext configuration temporary file could not be written",
+ status_name="CONTEXT_PROACTIVE_FILE_EXECUTION_ERROR",
+ cause=exc,
+ )
+
+
+def _replace_yaml(temporary: Path, path: Path) -> None:
+ try:
+ _reject_symlink_chain(path)
+ os.replace(temporary, path)
+ with contextlib.suppress(OSError):
+ os.chmod(path, 0o600)
+ except PersonalContext.Error:
+ raise
+ except Exception as exc:
+ _raise_host_error(
+ "PersonalContext configuration file could not be replaced",
+ status_name="CONTEXT_PROACTIVE_FILE_EXECUTION_ERROR",
+ cause=exc,
+ )
+
+
+def _cleanup_temporary(path: Path | None) -> None:
+ if path is not None:
+ with contextlib.suppress(FileNotFoundError):
+ path.unlink()
+
+
+def _publish_yaml(path: Path, payload: bytes) -> None:
+ temporary = _stage_yaml(path, payload)
+ try:
+ _replace_yaml(temporary, path)
+ finally:
+ _cleanup_temporary(temporary)
+
+
+def _read_yaml(path: Path) -> dict[str, object] | None:
+ try:
+ _reject_symlink_chain(path)
+ try:
+ with path.open("rb") as handle:
+ opened = os.fstat(handle.fileno())
+ if not stat.S_ISREG(opened.st_mode):
+ _raise_host_error(
+ "PersonalContext configuration path is not a file",
+ status_name="CONTEXT_PROACTIVE_FILE_EXECUTION_ERROR",
+ )
+ payload = handle.read(_MAX_CONFIG_BYTES + 1)
+ if len(payload) > _MAX_CONFIG_BYTES:
+ _raise_host_error(
+ "PersonalContext configuration exceeds the 4 MiB limit"
+ )
+ text = payload.decode("utf-8")
+ except FileNotFoundError:
+ return None
+ except PersonalContext.Error:
+ raise
+ except Exception as exc:
+ _raise_host_error(
+ "PersonalContext configuration YAML could not be read",
+ status_name="CONTEXT_PROACTIVE_FILE_EXECUTION_ERROR",
+ cause=exc,
+ )
+ try:
+ loaded = yaml.safe_load(text)
+ except Exception as exc:
+ _raise_host_error(
+ "PersonalContext configuration YAML is invalid", cause=exc
+ )
+ if not isinstance(loaded, dict):
+ _raise_host_error(
+ "PersonalContext configuration YAML must contain an object"
+ )
+ return loaded
+ except PersonalContext.Error:
+ raise
+ except Exception as exc:
+ _raise_host_error(
+ "PersonalContext configuration YAML could not be read", cause=exc
+ )
+
+
+def _is_runtime_active(status: object) -> bool:
+ return getattr(status, "state", None) in {"STARTING", "RUNNING"}
+
+
+def _resolve_model_reference(
+ model_index: object,
+) -> tuple[dict[str, object], dict[str, object]]:
+ if type(model_index) is not int or model_index < 0:
+ _raise_host_error("model_index must be a non-negative integer")
+ models = get_default_models()
+ if model_index >= len(models):
+ _raise_host_error("selected JiuwenSwarm model no longer exists")
+ entry = models[model_index]
+ if not isinstance(entry, dict):
+ _raise_host_error("selected JiuwenSwarm model is invalid")
+ client_raw = entry.get("model_client_config")
+ request_raw = entry.get("model_config_obj")
+ if not isinstance(client_raw, dict) or not isinstance(request_raw, dict):
+ _raise_host_error("selected JiuwenSwarm model is invalid")
+ client = deepcopy(client_raw)
+ request = deepcopy(request_raw)
+ model_name = str(client.pop("model_name", "")).strip()
+ if not model_name:
+ _raise_host_error("selected JiuwenSwarm model is invalid")
+ request["model"] = model_name
+ return client, request
+
+
+def _build_core_config(stored: dict[str, object]) -> PersonalContext.Config:
+ raw = deepcopy(stored)
+ model_index = raw.pop("model_index", None)
+ raw.pop("model_client", None)
+ raw.pop("model_request", None)
+ if model_index is not None:
+ client, request = _resolve_model_reference(model_index)
+ raw["model_client"] = client
+ raw["model_request"] = request
+ try:
+ return PersonalContext.Config.from_dict(raw)
+ except PersonalContext.Error:
+ raise
+ except Exception as exc:
+ _raise_host_error("PersonalContext configuration is invalid", cause=exc)
+
+
+def _prepare_stored_config(
+ config: dict[str, object],
+) -> tuple[dict[str, object], PersonalContext.Config]:
+ if not isinstance(config, dict):
+ _raise_host_error("PersonalContext configuration must be an object")
+ stored = deepcopy(config)
+ stored.pop("model_client", None)
+ stored.pop("model_request", None)
+ candidate = _build_core_config(stored)
+ normalized = candidate.model_dump(mode="json", by_alias=True)
+ normalized.pop("model_client", None)
+ normalized.pop("model_request", None)
+ if "model_index" in stored:
+ normalized["model_index"] = stored["model_index"]
+ return normalized, candidate
+
+
+class PersonalContextHostAPI:
+ """The only JiuwenSwarm API for configuring and controlling embedded PersonalContext."""
+
+ def __init__(self, *, home: str | Path) -> None:
+ self._home = Path(home).expanduser().resolve()
+ self._config_path = self._home / _CONFIG_FILENAME
+ self._personal_context = PersonalContext(home=self._home)
+ self._config: PersonalContext.Config | None = None
+ self._stored_config: dict[str, object] | None = None
+ self._operation_lock = asyncio.Lock()
+
+ async def configure(self, config: dict[str, object]) -> None:
+ """Validate, save, and apply one complete configuration."""
+
+ stored, candidate = _prepare_stored_config(config)
+ payload = _serialize_config(stored)
+
+ async with self._operation_lock:
+ await self._apply_configuration_locked(candidate, stored, payload)
+
+ async def _apply_configuration_locked(
+ self,
+ candidate: PersonalContext.Config,
+ stored: dict[str, object],
+ payload: bytes,
+ *,
+ known_previous_active: bool | None = None,
+ ) -> None:
+ """Apply one validated complete configuration while the Host lock is held."""
+
+ previous = self._config
+ previous_stored = self._stored_config
+ same_configuration = previous is not None and previous == candidate
+
+ previous_active = False
+ if previous is not None:
+ if known_previous_active is not None:
+ previous_active = known_previous_active
+ else:
+ try:
+ previous_active = _is_runtime_active(
+ await self._personal_context.snapshot()
+ )
+ except asyncio.CancelledError:
+ raise
+ except BaseException as exc:
+ raise _as_host_error(
+ exc,
+ "PersonalContext runtime status could not be read",
+ ) from None
+ if same_configuration and previous_active == candidate.enabled:
+ _publish_yaml(self._config_path, payload)
+ self._stored_config = deepcopy(stored)
+ return
+
+ temporary: Path | None = _stage_yaml(self._config_path, payload)
+ disabling = previous is not None and previous.enabled and not candidate.enabled
+ disabled_yaml_published = False
+ rollback_runtime = False
+ phase = "stop"
+ try:
+ if disabling:
+ phase = "replace"
+ if temporary is None:
+ _raise_host_error("PersonalContext configuration staging failed")
+ _replace_yaml(temporary, self._config_path)
+ temporary = None
+ disabled_yaml_published = True
+
+ if previous is not None:
+ phase = "stop"
+ rollback_runtime = True
+ await self._personal_context.deactivate_runtime(
+ timeout_seconds=_STOP_TIMEOUT_SECONDS
+ )
+
+ phase = "set"
+ rollback_runtime = True
+ await self._personal_context.set_configuration(candidate)
+
+ if candidate.enabled:
+ phase = "activate"
+ await self._personal_context.activate_runtime()
+
+ if not disabled_yaml_published:
+ phase = "replace"
+ if temporary is None:
+ _raise_host_error("PersonalContext configuration staging failed")
+ _replace_yaml(temporary, self._config_path)
+ temporary = None
+
+ self._config = candidate
+ self._stored_config = deepcopy(stored)
+ except BaseException as exc:
+ rollback_error: BaseException | None = None
+ if rollback_runtime or disabled_yaml_published:
+ try:
+ await self._restore_previous(
+ previous,
+ previous_stored,
+ previous_active,
+ )
+ except BaseException as restore_exc:
+ rollback_error = restore_exc
+ if disabled_yaml_published and previous_stored is not None:
+ try:
+ _publish_yaml(
+ self._config_path,
+ _serialize_config(previous_stored),
+ )
+ except BaseException as restore_exc:
+ rollback_error = rollback_error or restore_exc
+ if isinstance(exc, asyncio.CancelledError):
+ raise
+ if rollback_error is not None:
+ raise _as_host_error(
+ rollback_error,
+ "PersonalContext previous configuration could not be restored",
+ ) from None
+ if phase == "set":
+ raise _as_host_error(
+ exc,
+ "PersonalContext configuration could not be applied",
+ status_name="CONTEXT_PROACTIVE_CONFIG_INVALID",
+ ) from None
+ if phase == "activate":
+ raise _as_host_error(
+ exc,
+ "PersonalContext runtime could not be started",
+ ) from None
+ if phase == "replace":
+ raise _as_host_error(
+ exc,
+ "PersonalContext configuration file could not be replaced",
+ status_name="CONTEXT_PROACTIVE_FILE_EXECUTION_ERROR",
+ ) from None
+ raise _as_host_error(
+ exc,
+ "PersonalContext previous runtime could not be stopped",
+ ) from None
+ finally:
+ _cleanup_temporary(temporary)
+
+ async def get_overview(self) -> dict[str, object]:
+ """Return one consistent copy of the full configuration and Core status."""
+
+ async with self._operation_lock:
+ config = deepcopy(self._stored_config)
+ status = await self._personal_context.snapshot()
+ return {
+ "configured": self._stored_config is not None,
+ "config": config,
+ "status": status.model_dump(mode="json"),
+ }
+
+ async def get_runtime_config(self) -> dict[str, object]:
+ """Return the complete persistent PersonalContext configuration."""
+
+ async with self._operation_lock:
+ if self._stored_config is None:
+ return _unconfigured_projection()
+ return deepcopy(self._stored_config)
+
+ async def patch_runtime_config(
+ self,
+ patch: dict[str, object],
+ ) -> dict[str, object]:
+ """Atomically patch the allowed runtime configuration fields."""
+
+ if not isinstance(patch, dict):
+ _raise_host_error("patch must be an object")
+ unknown = set(patch) - {"strategy_profile"}
+ if unknown:
+ _raise_host_error("runtime patch contains unsupported fields")
+ async with self._operation_lock:
+ if self._stored_config is None:
+ _raise_host_error("PersonalContext is not configured")
+ stored = deepcopy(self._stored_config)
+ stored.update(deepcopy(patch))
+ stored, candidate = _prepare_stored_config(stored)
+ await self._apply_configuration_locked(
+ candidate,
+ stored,
+ _serialize_config(stored),
+ )
+ return deepcopy(stored)
+
+ async def select_model(self, model_index: int) -> dict[str, object]:
+ """Select one current JiuwenSwarm model by its models.list index."""
+
+ if type(model_index) is not int or model_index < 0:
+ _raise_host_error("model_index must be a non-negative integer")
+ async with self._operation_lock:
+ if self._stored_config is None:
+ _raise_host_error("PersonalContext is not configured")
+ stored = deepcopy(self._stored_config)
+ stored["model_index"] = model_index
+ stored, candidate = _prepare_stored_config(stored)
+ await self._apply_configuration_locked(
+ candidate,
+ stored,
+ _serialize_config(stored),
+ )
+ return deepcopy(stored)
+
+ async def set_runtime_enabled(self, enabled: bool) -> dict[str, object]:
+ """Persist and apply the whole PersonalContext runtime enable switch."""
+
+ if not isinstance(enabled, bool):
+ _raise_host_error("enabled must be a boolean")
+ async with self._operation_lock:
+ first_start = self._stored_config is None
+ if self._stored_config is None:
+ if not enabled:
+ return _unconfigured_projection()
+ stored = _initial_stored_config(enabled=True)
+ else:
+ stored = deepcopy(self._stored_config)
+ stored["enabled"] = enabled
+ stored, candidate = _prepare_stored_config(stored)
+ await self._apply_configuration_locked(
+ candidate,
+ stored,
+ _serialize_config(stored),
+ )
+ result = deepcopy(stored)
+ if first_start:
+ result["model_index"] = None
+ return result
+
+ async def list_fetch_services(self) -> list[dict[str, object]]:
+ """Return every fixed fetch service with current state and last error."""
+
+ async with self._operation_lock:
+ if self._stored_config is None:
+ return []
+ status = await self._personal_context.snapshot()
+ states = getattr(status, "fetch_service_states", {})
+ errors = getattr(status, "fetch_service_errors", {})
+ services = cast(
+ list[dict[str, object]],
+ deepcopy(self._stored_config["fetch_services"]),
+ )
+ for service in services:
+ service_id = cast(str, service["service_id"])
+ service["state"] = states.get(service_id, "STOPPED")
+ service["last_error"] = errors.get(service_id)
+ return services
+
+ async def create_fetch_service(
+ self,
+ service: dict[str, object],
+ ) -> dict[str, object]:
+ """Validate, persist, and apply one new fixed-provider fetch service."""
+
+ async with self._operation_lock:
+ if self._stored_config is None:
+ _raise_host_error("PersonalContext is not configured")
+ if not isinstance(service, dict):
+ _raise_host_error("service must be an object")
+ stored = deepcopy(self._stored_config)
+ services = cast(list[dict[str, object]], stored["fetch_services"])
+ service_id = service.get("service_id")
+ normalized_id = service_id.strip() if isinstance(service_id, str) else None
+ existing_ids = {cast(str, item["service_id"]) for item in services}
+ if normalized_id is not None and normalized_id in existing_ids:
+ _raise_host_error("PersonalContext fetch service already exists")
+ provider = service.get("provider")
+ normalized_provider = (
+ provider.strip().casefold() if isinstance(provider, str) else None
+ )
+ if normalized_provider is not None:
+ provider_count = sum(
+ item.get("provider") == normalized_provider for item in services
+ )
+ if provider_count >= 20:
+ _raise_host_error(
+ f"{normalized_provider} fetch service limit of 20 has been reached"
+ )
+ services.append(deepcopy(service))
+ stored, candidate = _prepare_stored_config(stored)
+ await self._apply_configuration_locked(
+ candidate,
+ stored,
+ _serialize_config(stored),
+ )
+ normalized_services = cast(
+ list[dict[str, object]],
+ stored["fetch_services"],
+ )
+ created = next(
+ item
+ for item in normalized_services
+ if cast(str, item["service_id"]) not in existing_ids
+ )
+ return deepcopy(created)
+
+ async def delete_fetch_service(self, service_id: str) -> None:
+ """Remove one stopped service and its cursor while retaining Context files."""
+
+ async with self._operation_lock:
+ if self._stored_config is None:
+ _raise_host_error("PersonalContext is not configured")
+ if not isinstance(service_id, str) or not service_id.strip():
+ _raise_host_error("service_id must be a non-empty string")
+ normalized_id = service_id.strip()
+ stored = deepcopy(self._stored_config)
+ services = cast(list[dict[str, object]], stored["fetch_services"])
+ if not any(item["service_id"] == normalized_id for item in services):
+ _raise_host_error("unknown PersonalContext fetch service")
+ try:
+ status = await self._personal_context.snapshot()
+ except asyncio.CancelledError:
+ raise
+ except BaseException as exc:
+ raise _as_host_error(
+ exc,
+ "PersonalContext runtime status could not be read",
+ ) from None
+ states = getattr(status, "fetch_service_states", {})
+ fetch_state = states.get(normalized_id)
+ if fetch_state != "STOPPED":
+ if fetch_state in {"STARTING", "RUNNING", "STOPPING"}:
+ _raise_host_error("PersonalContext 抓取服务正在执行,无法删除")
+ _raise_host_error("PersonalContext 抓取服务尚未停止,请先停止后再删除")
+ try:
+ cursor_payload = self._personal_context.remove_fetch_cursor(
+ normalized_id
+ )
+ except asyncio.CancelledError:
+ raise
+ except BaseException as exc:
+ raise _as_host_error(
+ exc,
+ "PersonalContext fetch cursor could not be removed",
+ status_name="CONTEXT_PROACTIVE_FILE_EXECUTION_ERROR",
+ ) from None
+ try:
+ stored["fetch_services"] = [
+ item for item in services if item["service_id"] != normalized_id
+ ]
+ stored, candidate = _prepare_stored_config(stored)
+ await self._apply_configuration_locked(
+ candidate,
+ stored,
+ _serialize_config(stored),
+ known_previous_active=_is_runtime_active(status),
+ )
+ except BaseException as exc:
+ restore_error: BaseException | None = None
+ try:
+ self._personal_context.restore_fetch_cursor(
+ normalized_id,
+ cursor_payload,
+ )
+ except BaseException as restore_exc:
+ restore_error = restore_exc
+ if isinstance(exc, asyncio.CancelledError):
+ raise
+ if restore_error is not None:
+ raise _as_host_error(
+ restore_error,
+ "PersonalContext fetch cursor could not be restored",
+ status_name="CONTEXT_PROACTIVE_FILE_EXECUTION_ERROR",
+ ) from None
+ raise _as_host_error(
+ exc,
+ "PersonalContext fetch service could not be deleted",
+ ) from None
+
+ async def patch_fetch_service(
+ self,
+ service_id: str,
+ patch: dict[str, object],
+ ) -> dict[str, object]:
+ """Atomically patch one existing fixed fetch service."""
+
+ if not isinstance(service_id, str) or not service_id.strip():
+ _raise_host_error("service_id must be a non-empty string")
+ if not isinstance(patch, dict):
+ _raise_host_error("patch must be an object")
+ allowed = {
+ "interval_seconds",
+ "max_items_per_run",
+ "source",
+ "credentials",
+ }
+ if set(patch) - allowed:
+ _raise_host_error("fetch service patch contains unsupported fields")
+ normalized_id = service_id.strip()
+ async with self._operation_lock:
+ if self._stored_config is None:
+ _raise_host_error("PersonalContext is not configured")
+ stored = deepcopy(self._stored_config)
+ services = cast(list[dict[str, object]], stored["fetch_services"])
+ target = next(
+ (
+ service
+ for service in services
+ if service["service_id"] == normalized_id
+ ),
+ None,
+ )
+ if target is None:
+ _raise_host_error("unknown PersonalContext fetch service")
+ target.update(deepcopy(patch))
+ stored, candidate = _prepare_stored_config(stored)
+ await self._apply_configuration_locked(
+ candidate,
+ stored,
+ _serialize_config(stored),
+ )
+ updated_services = cast(
+ list[dict[str, object]],
+ stored["fetch_services"],
+ )
+ updated = next(
+ service
+ for service in updated_services
+ if service["service_id"] == normalized_id
+ )
+ return deepcopy(updated)
+
+ async def get_fetch_run_status(
+ self,
+ service_id: str | None = None,
+ ) -> dict[str, object]:
+ """Return current run state and last retained error for fetch services."""
+
+ if service_id is not None and (
+ not isinstance(service_id, str) or not service_id.strip()
+ ):
+ _raise_host_error("service_id must be a non-empty string")
+ normalized_id = service_id.strip() if service_id is not None else None
+ async with self._operation_lock:
+ configured_ids: list[str] = []
+ if self._stored_config is not None:
+ services = cast(
+ list[dict[str, object]],
+ self._stored_config["fetch_services"],
+ )
+ configured_ids = [cast(str, item["service_id"]) for item in services]
+ if normalized_id is not None and normalized_id not in configured_ids:
+ _raise_host_error("unknown PersonalContext fetch service")
+ status = await self._personal_context.snapshot()
+ states = getattr(status, "fetch_service_states", {})
+ errors = getattr(status, "fetch_service_errors", {})
+
+ def project(item_id: str) -> dict[str, object]:
+ return {
+ "service_id": item_id,
+ "state": states.get(item_id, "STOPPED"),
+ "last_error": errors.get(item_id),
+ }
+
+ if normalized_id is not None:
+ return project(normalized_id)
+ return {"services": [project(item_id) for item_id in configured_ids]}
+
+ async def set_fetching(
+ self,
+ *,
+ enabled: bool,
+ service_id: str | None = None,
+ ) -> None:
+ """Persist and hot-apply the global or one-service fetch switch."""
+
+ if not isinstance(enabled, bool):
+ _raise_host_error("enabled must be a boolean")
+ if service_id is not None and not isinstance(service_id, str):
+ _raise_host_error("service_id must be a string")
+ async with self._operation_lock:
+ if self._stored_config is None:
+ _raise_host_error(
+ "PersonalContext configuration must be set before changing fetching"
+ )
+ raw = deepcopy(self._stored_config)
+ if service_id is None:
+ raw["fetching_enabled"] = enabled
+ else:
+ normalized_id = service_id.strip()
+ if not normalized_id:
+ _raise_host_error("service_id must not be empty")
+ services = cast(list[dict[str, object]], raw["fetch_services"])
+ target = next(
+ (item for item in services if item["service_id"] == normalized_id),
+ None,
+ )
+ if target is None:
+ _raise_host_error("unknown PersonalContext fetch service")
+ target["enabled"] = enabled
+ raw, candidate = _prepare_stored_config(raw)
+ await self._apply_configuration_locked(
+ candidate,
+ raw,
+ _serialize_config(raw),
+ )
+
+ async def run_fetch(
+ self,
+ *,
+ service_id: str | None = None,
+ ) -> dict[str, object]:
+ """Delegate one immediate fetch request without changing configuration."""
+
+ async with self._operation_lock:
+ return await self._personal_context.run_fetch(service_id=service_id)
+
+ async def get_graph(self) -> dict[str, object]:
+ """Read the last published Context structure without starting Core."""
+
+ return await self._personal_context.get_graph()
+
+ async def search_graph(self, query: str) -> dict[str, object]:
+ """Search the last published Context pages without starting Core."""
+
+ return await self._personal_context.search_graph(query)
+
+ async def get_graph_page(self, node_id: str) -> dict[str, object]:
+ """Read one published Context page without starting Core."""
+
+ return await self._personal_context.get_graph_page(node_id)
+
+ async def get_authorization_status(self, provider: str) -> dict[str, object]:
+ """Read provider authorization status without storing Host-side state."""
+
+ async with self._operation_lock:
+ if self._config is None:
+ _raise_host_error(
+ "PersonalContext configuration must be set before provider authorization"
+ )
+ result: dict[str, object] | None = None
+ cancelled: asyncio.CancelledError | None = None
+ try:
+ result = await self._personal_context.get_authorization_status(provider)
+ except asyncio.CancelledError as exc:
+ cancelled = exc
+ except Exception as exc:
+ raise _as_host_error(
+ exc, "PersonalContext provider authorization status failed"
+ ) from None
+ if cancelled is not None:
+ raise cancelled
+ if result is None:
+ _raise_host_error(
+ "PersonalContext provider authorization status returned no result"
+ )
+ return result
+
+ async def authorize_provider(self, provider: str) -> dict[str, object]:
+ """Check or begin user authorization for a configured provider."""
+
+ async with self._operation_lock:
+ if self._config is None:
+ _raise_host_error(
+ "PersonalContext configuration must be set before provider authorization"
+ )
+ try:
+ return await self._personal_context.authorize_provider(provider)
+ except asyncio.CancelledError:
+ raise
+ except BaseException as exc:
+ raise _as_host_error(
+ exc, "PersonalContext provider authorization failed"
+ ) from None
+
+ async def start(self) -> None:
+ """Load the file once when needed and start the configured Core."""
+
+ async with self._operation_lock:
+ if self._config is None:
+ raw = _read_yaml(self._config_path)
+ if raw is None:
+ return
+ stored, config = _prepare_stored_config(raw)
+ try:
+ await self._personal_context.set_configuration(config)
+ except BaseException as exc:
+ if isinstance(exc, asyncio.CancelledError):
+ raise
+ raise _as_host_error(
+ exc,
+ "PersonalContext configuration could not be applied",
+ status_name="CONTEXT_PROACTIVE_CONFIG_INVALID",
+ ) from None
+ self._config = config
+ self._stored_config = stored
+ config = self._config
+ if config is None or not config.enabled:
+ return
+ try:
+ await self._personal_context.activate_runtime()
+ except BaseException as exc:
+ if isinstance(exc, asyncio.CancelledError):
+ raise
+ raise _as_host_error(
+ exc, "PersonalContext runtime could not be started"
+ ) from None
+
+ async def is_runtime_enabled(self) -> bool:
+ """Return the loaded Host switch without reading or parsing YAML."""
+
+ async with self._operation_lock:
+ config = self._config
+ return bool(config is not None and config.enabled)
+
+ async def get_status(self) -> PersonalContext.Status:
+ """Return the Core's bounded, credential-free status snapshot."""
+
+ return await self._personal_context.snapshot()
+
+ async def stop(self, *, timeout_seconds: float = _STOP_TIMEOUT_SECONDS) -> None:
+ """Stop Core runtime while preserving configuration and published files."""
+
+ if timeout_seconds <= 0:
+ _raise_host_error(
+ "timeout_seconds must be greater than zero",
+ status_name="CONTEXT_PROACTIVE_RUNTIME_TIMEOUT",
+ )
+ async with self._operation_lock:
+ try:
+ await self._personal_context.deactivate_runtime(
+ timeout_seconds=timeout_seconds
+ )
+ except asyncio.CancelledError:
+ raise
+ except BaseException as exc:
+ raise _as_host_error(
+ exc, "PersonalContext runtime could not be stopped"
+ ) from None
+
+ async def _restore_previous(
+ self,
+ previous: PersonalContext.Config | None,
+ previous_stored: dict[str, object] | None,
+ was_active: bool,
+ ) -> None:
+ """Restore after a failed candidate configuration operation."""
+
+ await self._personal_context.deactivate_runtime(
+ timeout_seconds=_STOP_TIMEOUT_SECONDS
+ )
+ if previous is None:
+ self._personal_context = PersonalContext(home=self._home)
+ self._config = None
+ self._stored_config = None
+ return
+ await self._personal_context.set_configuration(previous)
+ if was_active and previous.enabled:
+ await self._personal_context.activate_runtime()
+ self._config = previous
+ self._stored_config = deepcopy(previous_stored)
diff --git a/jiuwenswarm/server/personal_context/ws_handler.py b/jiuwenswarm/server/personal_context/ws_handler.py
new file mode 100644
index 0000000000..8907be9fa2
--- /dev/null
+++ b/jiuwenswarm/server/personal_context/ws_handler.py
@@ -0,0 +1,360 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""PersonalContext WebSocket request dispatch on JiuwenSwarm's existing E2A wire path."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from collections.abc import Awaitable, Callable
+from typing import TYPE_CHECKING, Any, cast
+
+from openjiuwen.core.common.exception.errors import BaseError
+
+from jiuwenswarm.common.e2a.wire_codec import (
+ encode_agent_chunk_for_wire,
+ encode_agent_response_for_wire,
+)
+from jiuwenswarm.common.schema.agent import (
+ AgentRequest,
+ AgentResponse,
+ AgentResponseChunk,
+)
+from jiuwenswarm.common.schema.message import ReqMethod
+from jiuwenswarm.server.ws_send import send_wire_payload
+
+if TYPE_CHECKING:
+ from jiuwenswarm.server.personal_context.host_api import PersonalContextHostAPI
+
+
+logger = logging.getLogger(__name__)
+
+PERSONAL_CONTEXT_REQUEST_METHODS = frozenset(
+ {
+ ReqMethod.PERSONAL_CONTEXT_RUNTIME_STATUS,
+ ReqMethod.PERSONAL_CONTEXT_RUNTIME_START,
+ ReqMethod.PERSONAL_CONTEXT_RUNTIME_STOP,
+ ReqMethod.PERSONAL_CONTEXT_RUNTIME_GET_CONFIG,
+ ReqMethod.PERSONAL_CONTEXT_RUNTIME_PATCH_CONFIG,
+ ReqMethod.PERSONAL_CONTEXT_RUNTIME_SELECT_MODEL,
+ ReqMethod.PERSONAL_CONTEXT_FETCH_LIST_SERVICES,
+ ReqMethod.PERSONAL_CONTEXT_FETCH_CREATE_SERVICE,
+ ReqMethod.PERSONAL_CONTEXT_FETCH_DELETE_SERVICE,
+ ReqMethod.PERSONAL_CONTEXT_FETCH_PATCH_SERVICE,
+ ReqMethod.PERSONAL_CONTEXT_FETCH_START_SERVICE,
+ ReqMethod.PERSONAL_CONTEXT_FETCH_STOP_SERVICE,
+ ReqMethod.PERSONAL_CONTEXT_FETCH_START_SCHEDULER,
+ ReqMethod.PERSONAL_CONTEXT_FETCH_STOP_SCHEDULER,
+ ReqMethod.PERSONAL_CONTEXT_FETCH_RUN_ALL,
+ ReqMethod.PERSONAL_CONTEXT_FETCH_RUN_ONE,
+ ReqMethod.PERSONAL_CONTEXT_FETCH_GET_RUN_STATUS,
+ ReqMethod.PERSONAL_CONTEXT_FETCH_GET_AUTHORIZATION_STATUS,
+ ReqMethod.PERSONAL_CONTEXT_FETCH_AUTHORIZE_PROVIDER,
+ ReqMethod.PERSONAL_CONTEXT_CONTEXT_STREAM_GRAPH,
+ ReqMethod.PERSONAL_CONTEXT_CONTEXT_SEARCH_PAGES,
+ ReqMethod.PERSONAL_CONTEXT_CONTEXT_GET_NODE,
+ }
+)
+
+
+def _payload(value: object) -> dict[str, object]:
+ if value is None:
+ return {"ok": True}
+ if isinstance(value, dict):
+ return value
+ if hasattr(value, "model_dump"):
+ dumped = value.model_dump(mode="json")
+ if isinstance(dumped, dict):
+ return dumped
+ raise TypeError("PersonalContext Host result must be an object")
+
+
+def _text(params: dict[str, object], name: str) -> str:
+ value = params.get(name)
+ if not isinstance(value, str) or not value.strip():
+ raise ValueError(f"{name} must be a non-empty string")
+ return value.strip()
+
+
+async def _send_result(
+ ws: Any,
+ request: AgentRequest,
+ send_lock: asyncio.Lock,
+ payload: dict[str, object],
+) -> None:
+ if request.is_stream:
+ wire = encode_agent_chunk_for_wire(
+ AgentResponseChunk(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ payload=payload,
+ is_complete=True,
+ agent_ref=request.agent_ref,
+ ),
+ response_id=request.request_id,
+ sequence=0,
+ )
+ else:
+ wire = encode_agent_response_for_wire(
+ AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=True,
+ payload=payload,
+ agent_ref=request.agent_ref,
+ ),
+ response_id=request.request_id,
+ )
+ async with send_lock:
+ await send_wire_payload(ws, wire)
+
+
+async def _send_error(
+ ws: Any,
+ request: AgentRequest,
+ send_lock: asyncio.Lock,
+ *,
+ message: str,
+ code: object,
+ status: str | None = None,
+) -> None:
+ payload: dict[str, object] = {"error": message, "code": code}
+ if status is not None:
+ payload["status"] = status
+ if request.is_stream:
+ payload["event_type"] = "chat.error"
+ wire = encode_agent_chunk_for_wire(
+ AgentResponseChunk(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ payload=payload,
+ is_complete=True,
+ agent_ref=request.agent_ref,
+ ),
+ response_id=request.request_id,
+ sequence=0,
+ )
+ else:
+ wire = encode_agent_response_for_wire(
+ AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=False,
+ payload=payload,
+ agent_ref=request.agent_ref,
+ ),
+ response_id=request.request_id,
+ )
+ async with send_lock:
+ await send_wire_payload(ws, wire)
+
+
+async def _stream_graph(
+ host: PersonalContextHostAPI,
+ ws: Any,
+ request: AgentRequest,
+ send_lock: asyncio.Lock,
+) -> None:
+ graph = await host.get_graph()
+ nodes = graph.get("nodes")
+ edges = graph.get("edges")
+ if not isinstance(nodes, list) or not isinstance(edges, list):
+ raise TypeError("PersonalContext graph nodes and edges must be arrays")
+ events: list[dict[str, object]] = [
+ {
+ "event_type": "personal_context.graph.start",
+ "context_ready": bool(graph.get("context_ready")),
+ }
+ ]
+ events.extend(
+ {
+ "event_type": "personal_context.graph.nodes",
+ "nodes": nodes[index: index + 200],
+ }
+ for index in range(0, len(nodes), 200)
+ )
+ events.extend(
+ {
+ "event_type": "personal_context.graph.edges",
+ "edges": edges[index: index + 200],
+ }
+ for index in range(0, len(edges), 200)
+ )
+ events.append(
+ {
+ "event_type": "personal_context.graph.end",
+ "node_count": len(nodes),
+ "edge_count": len(edges),
+ }
+ )
+ for sequence, event in enumerate(events):
+ wire = encode_agent_chunk_for_wire(
+ AgentResponseChunk(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ payload=event,
+ is_complete=sequence == len(events) - 1,
+ agent_ref=request.agent_ref,
+ ),
+ response_id=request.request_id,
+ sequence=sequence,
+ )
+ async with send_lock:
+ await send_wire_payload(ws, wire)
+
+
+async def _execute(
+ host: PersonalContextHostAPI,
+ request: AgentRequest,
+ *,
+ runtime_enabled_changed: Callable[[bool], Awaitable[None]] | None = None,
+) -> dict[str, object]:
+ method = request.req_method
+ params = request.params
+ if method == ReqMethod.PERSONAL_CONTEXT_RUNTIME_STATUS:
+ return _payload(await host.get_status())
+ if method == ReqMethod.PERSONAL_CONTEXT_RUNTIME_START:
+ result = await host.set_runtime_enabled(True)
+ await _notify_runtime_enabled(runtime_enabled_changed, True)
+ return _payload(result)
+ if method == ReqMethod.PERSONAL_CONTEXT_RUNTIME_STOP:
+ result = await host.set_runtime_enabled(False)
+ await _notify_runtime_enabled(runtime_enabled_changed, False)
+ return _payload(result)
+ if method == ReqMethod.PERSONAL_CONTEXT_RUNTIME_GET_CONFIG:
+ return await host.get_runtime_config()
+ if method == ReqMethod.PERSONAL_CONTEXT_RUNTIME_PATCH_CONFIG:
+ return await host.patch_runtime_config(
+ cast(dict[str, object], params.get("patch"))
+ )
+ if method == ReqMethod.PERSONAL_CONTEXT_RUNTIME_SELECT_MODEL:
+ return await host.select_model(cast(int, params.get("model_index")))
+ if method == ReqMethod.PERSONAL_CONTEXT_FETCH_LIST_SERVICES:
+ return {"services": await host.list_fetch_services()}
+ if method == ReqMethod.PERSONAL_CONTEXT_FETCH_CREATE_SERVICE:
+ service = params.get("service")
+ if not isinstance(service, dict):
+ raise ValueError("service must be an object")
+ return await host.create_fetch_service(cast(dict[str, object], service))
+ if method == ReqMethod.PERSONAL_CONTEXT_FETCH_DELETE_SERVICE:
+ await host.delete_fetch_service(_text(params, "service_id"))
+ return {"ok": True}
+ if method == ReqMethod.PERSONAL_CONTEXT_FETCH_PATCH_SERVICE:
+ return await host.patch_fetch_service(
+ _text(params, "service_id"),
+ cast(dict[str, object], params.get("patch")),
+ )
+ if method in {
+ ReqMethod.PERSONAL_CONTEXT_FETCH_START_SERVICE,
+ ReqMethod.PERSONAL_CONTEXT_FETCH_STOP_SERVICE,
+ }:
+ await host.set_fetching(
+ enabled=method == ReqMethod.PERSONAL_CONTEXT_FETCH_START_SERVICE,
+ service_id=_text(params, "service_id"),
+ )
+ return {"ok": True}
+ if method in {
+ ReqMethod.PERSONAL_CONTEXT_FETCH_START_SCHEDULER,
+ ReqMethod.PERSONAL_CONTEXT_FETCH_STOP_SCHEDULER,
+ }:
+ await host.set_fetching(
+ enabled=method == ReqMethod.PERSONAL_CONTEXT_FETCH_START_SCHEDULER,
+ )
+ return {"ok": True}
+ if method == ReqMethod.PERSONAL_CONTEXT_FETCH_RUN_ALL:
+ return await host.run_fetch()
+ if method == ReqMethod.PERSONAL_CONTEXT_FETCH_RUN_ONE:
+ return await host.run_fetch(service_id=_text(params, "service_id"))
+ if method == ReqMethod.PERSONAL_CONTEXT_FETCH_GET_RUN_STATUS:
+ return await host.get_fetch_run_status(
+ cast(str | None, params.get("service_id"))
+ )
+ if method == ReqMethod.PERSONAL_CONTEXT_FETCH_GET_AUTHORIZATION_STATUS:
+ return await host.get_authorization_status(_text(params, "provider"))
+ if method == ReqMethod.PERSONAL_CONTEXT_FETCH_AUTHORIZE_PROVIDER:
+ return await host.authorize_provider(_text(params, "provider"))
+ if method == ReqMethod.PERSONAL_CONTEXT_CONTEXT_SEARCH_PAGES:
+ return await host.search_graph(_text(params, "query"))
+ if method == ReqMethod.PERSONAL_CONTEXT_CONTEXT_GET_NODE:
+ return await host.get_graph_page(_text(params, "node_id"))
+ raise ValueError("unknown PersonalContext method")
+
+
+async def _notify_runtime_enabled(
+ callback: Callable[[bool], Awaitable[None]] | None,
+ enabled: bool,
+) -> None:
+ """Best-effort notification; a Rail refresh must not fail the API call."""
+
+ if callback is None:
+ return
+ cancelled: asyncio.CancelledError | None = None
+ try:
+ await callback(enabled)
+ except asyncio.CancelledError as exc:
+ cancelled = exc
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "PersonalContext runtime Rail refresh failed: %s",
+ type(exc).__name__,
+ )
+ if cancelled is not None:
+ raise cancelled
+
+
+async def handle_personal_context_request(
+ host: PersonalContextHostAPI,
+ ws: Any,
+ request: AgentRequest,
+ send_lock: asyncio.Lock,
+ *,
+ runtime_enabled_changed: Callable[[bool], Awaitable[None]] | None = None,
+) -> None:
+ """Execute one parsed PersonalContext request without introducing a PersonalContext wire protocol."""
+
+ try:
+ if request.req_method == ReqMethod.PERSONAL_CONTEXT_CONTEXT_STREAM_GRAPH:
+ if not request.is_stream:
+ raise ValueError(
+ "personal_context.context.stream_graph requires is_stream=true"
+ )
+ await _stream_graph(host, ws, request, send_lock)
+ return
+ await _send_result(
+ ws,
+ request,
+ send_lock,
+ await _execute(
+ host,
+ request,
+ runtime_enabled_changed=runtime_enabled_changed,
+ ),
+ )
+ except asyncio.CancelledError:
+ raise
+ except ValueError as exc:
+ await _send_error(
+ ws,
+ request,
+ send_lock,
+ message=str(exc),
+ code="BAD_REQUEST",
+ )
+ except BaseError as exc:
+ await _send_error(
+ ws,
+ request,
+ send_lock,
+ message=exc.message,
+ code=exc.code,
+ status=exc.status.name,
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.warning("PersonalContext request failed: %s", type(exc).__name__)
+ await _send_error(
+ ws,
+ request,
+ send_lock,
+ message="PersonalContext request failed",
+ code="INTERNAL_ERROR",
+ )
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.py
index 8fb4e4d107..92eeb3ef62 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py
@@ -1050,6 +1050,10 @@ class JiuWenSwarm:
skill_manager: SkillManager | None = None,
) -> None:
self._adapter: AgentAdapter | None = None
+ # PersonalContext Rail follows the Host runtime switch. Keep the
+ # latest snapshot on the facade so a lazily-created adapter inherits
+ # the current state before its first rail synchronization.
+ self._personal_context_runtime_enabled: bool = False
self._sdk_name: str | None = None
# 多租户:user_workspace_dir 为 workspace_key 对应的用户根,再拼相对 workspace/sessions。
enterprise = is_enterprise()
@@ -1157,6 +1161,11 @@ class JiuWenSwarm:
)
if hasattr(self._adapter, "set_skill_manager"):
self._adapter.set_skill_manager(self._skill_manager)
+ setter = getattr(
+ self._adapter, "set_personal_context_runtime_enabled", None
+ )
+ if callable(setter):
+ setter(self._personal_context_runtime_enabled)
self._skill_manager.set_skillnet_install_complete_hook(
self._on_skillnet_install_complete
)
@@ -1259,6 +1268,31 @@ class JiuWenSwarm:
wk_token = bind_workspace_key(str(mem_wk))
return tenant_tokens, (mem_ws_token, mem_aid_token, env_ns_token, wk_token)
+ def set_personal_context_runtime_enabled(self, enabled: bool) -> None:
+ """Store and forward the PersonalContext Host runtime switch."""
+
+ self._personal_context_runtime_enabled = bool(enabled)
+ adapter = self._adapter
+ setter = (
+ getattr(adapter, "set_personal_context_runtime_enabled", None)
+ if adapter is not None
+ else None
+ )
+ if callable(setter):
+ setter(self._personal_context_runtime_enabled)
+
+ async def refresh_personal_context_rail(self) -> None:
+ """Refresh the PersonalContext Rail without creating an Agent."""
+
+ adapter = self._adapter
+ refresher = (
+ getattr(adapter, "refresh_personal_context_rail", None)
+ if adapter is not None
+ else None
+ )
+ if callable(refresher):
+ await refresher()
+
@staticmethod
def _reset_tenant_request_context(tenant_tokens: Any, mem_token: Any) -> None:
from jiuwenswarm.server.runtime.tenant_context import (
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 2bb127cd6b..aceed4b644 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -77,6 +77,7 @@ from openjiuwen.harness.rails import (
configure_skill_evolution_runtime,
unconfigure_skill_evolution,
)
+from openjiuwen.harness.rails.personal_context import PersonalContextRail
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
@@ -2224,6 +2225,8 @@ class JiuWenSwarmDeepAdapter:
self._runtime_prompt_rail: RuntimePromptRail | None = None
self._response_prompt_rail: ResponsePromptRail | None = None
self._prompt_attachment_loader: PromptAttachmentLoader | None = None
+ self._personal_context_rail: PersonalContextRail | None = None
+ self._personal_context_rail_lock = asyncio.Lock()
self._security_rail: SecurityRail | None = None
self._memory_rail: MemoryRail | None = None
self._external_memory_rail: Any = None
@@ -2233,6 +2236,10 @@ class JiuWenSwarmDeepAdapter:
self._memory_embedding_fingerprint: str = ""
# 最近一次请求使用的 mode:reload 时无 runtime_config 上下文,靠它主动刷新 memory rail。
self._last_mode: str | None = None
+ # PersonalContext is controlled by the Host runtime switch. Keep the
+ # last control-plane snapshot here so the disabled path never mounts a
+ # rail merely because an Agent mode request arrived.
+ self._personal_context_runtime_enabled: bool = False
# 延时重索引任务(debounce):连续改多次 embedding 只在最后一次后跑一次。
self._memory_reindex_task: asyncio.Task | None = None
self._llm_retry_rail: LLMRetryRail | None = None
@@ -2559,6 +2566,9 @@ class JiuWenSwarmDeepAdapter:
# adapter defaults to default/default and would read placeholder .env
# model credentials instead of the synced per-agent tip bag.
adapter.copy_tenant_env_bindings_from(self)
+ adapter.set_personal_context_runtime_enabled(
+ self._personal_context_runtime_enabled
+ )
if self._skill_manager is not None:
adapter.set_skill_manager(self._skill_manager)
return adapter
@@ -10115,6 +10125,97 @@ class JiuWenSwarmDeepAdapter:
"""
self._last_mode = mode
await self._update_agent_rails()
+ await self._sync_personal_context_rail(mode)
+
+ def _personal_context_rail_enabled(self, mode: str) -> bool:
+ """Return whether this request mode uses the embedded Core Rail."""
+
+ return (
+ not self._is_code_agent
+ and mode in {"agent", "agent.fast", "agent.plan"}
+ and self._personal_context_runtime_enabled
+ )
+
+ def set_personal_context_runtime_enabled(self, enabled: bool) -> None:
+ """Store the Host switch snapshot for this adapter and future sessions."""
+
+ self._personal_context_runtime_enabled = bool(enabled)
+ if not self._is_session_scoped_adapter:
+ for adapter in list(getattr(self, "_session_adapters", {}).values()):
+ adapter.set_personal_context_runtime_enabled(enabled)
+
+ async def refresh_personal_context_rail(self) -> None:
+ """Apply the current Host switch to this adapter and live session adapters."""
+
+ mode = self._last_mode
+ if mode is not None:
+ await self._sync_personal_context_rail(mode)
+ if not self._is_session_scoped_adapter:
+ for adapter in list(self._session_adapters.values()):
+ cancelled: asyncio.CancelledError | None = None
+ try:
+ await adapter.refresh_personal_context_rail()
+ except asyncio.CancelledError as exc:
+ cancelled = exc
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] optional PersonalContext session "
+ "Rail refresh failed: %s",
+ type(exc).__name__,
+ )
+ if cancelled is not None:
+ raise cancelled
+
+ async def _sync_personal_context_rail(self, mode: str) -> None:
+ """Register or detach the fixed-path Core Rail for normal agent modes."""
+
+ async with self._personal_context_rail_lock:
+ enabled = self._personal_context_rail_enabled(mode)
+ rail = self._personal_context_rail
+
+ if rail is not None and not enabled:
+ try:
+ await self._instance.unregister_rail(rail)
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] optional PersonalContext Rail "
+ "unregister failed: %s",
+ type(exc).__name__,
+ )
+ return
+ self._personal_context_rail = None
+ rail = None
+
+ if not enabled:
+ return
+
+ if rail is None:
+ try:
+ rail = PersonalContextRail(
+ Path.home() / ".jiuwenswarm" / ".personal_context"
+ )
+ await self._instance.register_rail(rail)
+ except Exception as exc: # noqa: BLE001
+ if rail is not None:
+ try:
+ await self._instance.unregister_rail(rail)
+ except Exception as cleanup_exc: # noqa: BLE001
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] optional PersonalContext Rail "
+ "registration cleanup failed: %s",
+ type(cleanup_exc).__name__,
+ )
+ self._personal_context_rail = None
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] optional PersonalContext Rail "
+ "registration failed: %s",
+ type(exc).__name__,
+ )
+ return
+ self._personal_context_rail = rail
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] PersonalContextRail registered for %s", mode
+ )
async def _reconcile_evolution_rails(self) -> None:
"""Apply evolution rail configuration through its runtime owner."""
@@ -12674,6 +12775,13 @@ class JiuWenSwarmDeepAdapter:
exc,
)
clear_session_skill_state(str(self._parent_session_id or "").strip())
+ try:
+ await self._sync_personal_context_rail("cleanup")
+ except BaseException as exc: # noqa: BLE001
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] PersonalContextRail cleanup failed: %s",
+ exc,
+ )
self._teardown_agent_owned_tools()
self._release_sys_operations()
# 取消未到期的延时重索引 task,避免 adapter cleanup 后仍有孤儿 task
diff --git a/jiuwenswarm/server/runtime/agent_manager.py b/jiuwenswarm/server/runtime/agent_manager.py
index ba7aad22bd..f0b08554bc 100644
--- a/jiuwenswarm/server/runtime/agent_manager.py
+++ b/jiuwenswarm/server/runtime/agent_manager.py
@@ -146,6 +146,9 @@ class AgentManager:
workspace_key: str | None = None,
) -> None:
self.agents: dict[str, dict[str, "JiuWenSwarm"]] = {}
+ # Snapshot of the optional PersonalContext runtime switch. New
+ # cached agents inherit it before their first rail synchronization.
+ self._personal_context_runtime_enabled: bool = False
# 记录每个 (channel_id, mode) 的创建参数, 便于 recreate_agent 立刻重建
self._agent_create_params: dict[str, dict[str, dict[str, Any]]] = {}
self._client_capabilities_by_channel: dict[str, dict[str, Any]] = {}
@@ -591,6 +594,9 @@ class AgentManager:
setattr(agent, "_workspace_key", self._workspace_key)
if self._user_workspace_dir is not None:
setattr(agent, "_user_workspace_dir", self._user_workspace_dir)
+ setter = getattr(agent, "set_personal_context_runtime_enabled", None)
+ if callable(setter):
+ setter(self._personal_context_runtime_enabled)
await agent.create_instance(
config,
mode=mode_key,
@@ -615,6 +621,39 @@ class AgentManager:
if overlay_token is not None:
reset_task_env_overlay(overlay_token)
+ async def set_personal_context_runtime_enabled(self, enabled: bool) -> None:
+ """Broadcast the Host switch to already cached Agent facades.
+
+ The manager deliberately iterates only existing wrappers. Toggling
+ PersonalContext must not create an Agent or otherwise affect normal
+ AgentServer work when the feature is disabled.
+ """
+
+ self._personal_context_runtime_enabled = bool(enabled)
+ for channel_agents in list(self.agents.values()):
+ if not isinstance(channel_agents, dict):
+ continue
+ for agent in list(channel_agents.values()):
+ cancelled: asyncio.CancelledError | None = None
+ try:
+ setter = getattr(
+ agent, "set_personal_context_runtime_enabled", None
+ )
+ if callable(setter):
+ setter(self._personal_context_runtime_enabled)
+ refresher = getattr(agent, "refresh_personal_context_rail", None)
+ if callable(refresher):
+ await refresher()
+ except asyncio.CancelledError as exc:
+ cancelled = exc
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[AgentManager] PersonalContext Rail refresh failed: %s",
+ type(exc).__name__,
+ )
+ if cancelled is not None:
+ raise cancelled
+
async def initialize(
self, channel_id: str = "", extra_config: dict[str, Any] | None = None
) -> dict[str, Any] | None:
diff --git a/tests/unit_tests/agentserver/test_personal_context_lifecycle.py b/tests/unit_tests/agentserver/test_personal_context_lifecycle.py
new file mode 100644
index 0000000000..b21caccce5
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_personal_context_lifecycle.py
@@ -0,0 +1,316 @@
+"""Embedded PersonalContext Host lifecycle contracts for AgentWebSocketServer."""
+
+from __future__ import annotations
+
+import asyncio
+import ast
+import contextlib
+from pathlib import Path
+from unittest.mock import AsyncMock
+
+import pytest
+
+from jiuwenswarm.server import agent_ws_server as server_module
+from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer
+
+
+AGENT_WS_SERVER_PATH = (
+ Path(__file__).parents[3] / "jiuwenswarm" / "server" / "agent_ws_server.py"
+)
+
+
+class _FakePersonalContextHost:
+ instances: list["_FakePersonalContextHost"] = []
+
+ def __init__(self, *, home: str | Path) -> None:
+ self.home = Path(home)
+ self.events: list[tuple[str, object]] = []
+ self.runtime_enabled = False
+ self.__class__.instances.append(self)
+
+ async def start(self) -> None:
+ self.events.append(("start", None))
+
+ async def is_runtime_enabled(self) -> bool:
+ return self.runtime_enabled
+
+ async def stop(self, *, timeout_seconds: float = 30.0) -> None:
+ self.events.append(("stop", timeout_seconds))
+
+
+class _FakeWebSocketServer:
+ def __init__(self, events: list[str]) -> None:
+ self.events = events
+ self.closed = False
+
+ def close(self) -> None:
+ self.events.append("ws-close")
+ self.closed = True
+
+ async def wait_closed(self) -> None:
+ self.events.append("ws-wait-closed")
+
+
+class _FailingWebSocketServer:
+ def close(self) -> None:
+ raise RuntimeError("close failed")
+
+ async def wait_closed(self) -> None:
+ raise AssertionError("wait_closed should not run after close failure")
+
+
[email protected](autouse=True)
+def _reset_fake_host() -> None:
+ _FakePersonalContextHost.instances.clear()
+
+
+def _server(monkeypatch: pytest.MonkeyPatch) -> AgentWebSocketServer:
+ monkeypatch.setattr(
+ server_module, "PersonalContextHostAPI", _FakePersonalContextHost
+ )
+ return AgentWebSocketServer(host="127.0.0.1", port=0)
+
+
+def test_personal_context_cancellation_handlers_do_not_raise_inside_except() -> None:
+ tree = ast.parse(AGENT_WS_SERVER_PATH.read_text(encoding="utf-8"))
+ functions = {
+ node.name: node
+ for node in ast.walk(tree)
+ if isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef))
+ }
+
+ for function_name in (
+ "_start_personal_context_best_effort",
+ "_stop_personal_context_best_effort",
+ ):
+ function = functions[function_name]
+ for handler in ast.walk(function):
+ if not isinstance(handler, ast.ExceptHandler):
+ continue
+ if ast.unparse(handler.type) != "asyncio.CancelledError":
+ continue
+ assert not any(
+ isinstance(statement, ast.Raise) and statement.exc is None
+ for statement in handler.body
+ ), function_name
+
+
+async def test_agentserver_constructs_one_host_at_fixed_home(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(Path, "home", staticmethod(lambda: Path("C:/users/tester")))
+ server = _server(monkeypatch)
+
+ assert len(_FakePersonalContextHost.instances) == 1
+ assert _FakePersonalContextHost.instances[0].home == Path(
+ "C:/users/tester/.jiuwenswarm/.personal_context"
+ )
+ assert server._personal_context_host is _FakePersonalContextHost.instances[0] # pylint: disable=protected-access
+
+
+async def test_start_opens_websocket_without_waiting_for_personal_context(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ server = _server(monkeypatch)
+ host = _FakePersonalContextHost.instances[0]
+ personal_context_started = asyncio.Event()
+ release_personal_context = asyncio.Event()
+ events: list[str] = []
+
+ async def _delayed_start() -> None:
+ host.events.append(("start", None))
+ personal_context_started.set()
+ await release_personal_context.wait()
+
+ async def _serve(*_args: object, **_kwargs: object) -> _FakeWebSocketServer:
+ events.append("ws-serve")
+ return _FakeWebSocketServer(events)
+
+ host.start = _delayed_start # type: ignore[method-assign]
+ monkeypatch.setattr(server_module, "reset_harness_packages_state", lambda: None)
+ from jiuwenswarm.server.runtime.agent_adapter import interface_deep
+
+ async def _checkpointer() -> None:
+ return None
+
+ monkeypatch.setattr(interface_deep, "ensure_persistent_checkpointer", _checkpointer)
+ monkeypatch.setattr("websockets.legacy.server.serve", _serve)
+ monkeypatch.setattr(server, "_bootstrap_internal_jiuwenbox", _noop_async)
+
+ await server.start()
+ task = server._personal_context_start_task # pylint: disable=protected-access
+ try:
+ await asyncio.wait_for(personal_context_started.wait(), timeout=1.0)
+
+ assert events == ["ws-serve"]
+ assert task is not None
+ release_personal_context.set()
+ await task
+ finally:
+ release_personal_context.set()
+ if task is not None:
+ if not task.done():
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await task
+
+
+async def test_start_restores_enabled_personal_context_state_to_agent_manager(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ server = _server(monkeypatch)
+ host = _FakePersonalContextHost.instances[0]
+ host.runtime_enabled = True
+ manager_update = AsyncMock()
+ server._agent_manager.set_personal_context_runtime_enabled = manager_update # type: ignore[method-assign]
+ events: list[str] = []
+
+ async def _serve(*_args: object, **_kwargs: object) -> _FakeWebSocketServer:
+ events.append("ws-serve")
+ return _FakeWebSocketServer(events)
+
+ monkeypatch.setattr(server_module, "reset_harness_packages_state", lambda: None)
+ from jiuwenswarm.server.runtime.agent_adapter import interface_deep
+
+ async def _checkpointer() -> None:
+ return None
+
+ monkeypatch.setattr(interface_deep, "ensure_persistent_checkpointer", _checkpointer)
+ monkeypatch.setattr("websockets.legacy.server.serve", _serve)
+ monkeypatch.setattr(server, "_bootstrap_internal_jiuwenbox", _noop_async)
+
+ await server.start()
+ task = server._personal_context_start_task # pylint: disable=protected-access
+ assert task is not None
+ await task
+
+ assert events == ["ws-serve"]
+ manager_update.assert_awaited_once_with(True)
+
+
+async def test_stop_calls_host_even_when_websocket_never_started(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ server = _server(monkeypatch)
+
+ await server.stop()
+
+ assert _FakePersonalContextHost.instances[0].events == [("stop", 30.0)]
+
+
+async def test_personal_context_start_failure_does_not_fail_agentserver_start(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ server = _server(monkeypatch)
+ host = _FakePersonalContextHost.instances[0]
+ events: list[str] = []
+
+ async def _failed_start() -> None:
+ host.events.append(("start", None))
+ raise RuntimeError("bad personal_context config")
+
+ async def _serve(*_args: object, **_kwargs: object) -> _FakeWebSocketServer:
+ events.append("ws-serve")
+ return _FakeWebSocketServer(events)
+
+ host.start = _failed_start # type: ignore[method-assign]
+ monkeypatch.setattr(server_module, "reset_harness_packages_state", lambda: None)
+ monkeypatch.setattr("websockets.legacy.server.serve", _serve)
+ monkeypatch.setattr(server, "_bootstrap_internal_jiuwenbox", _noop_async)
+
+ await server.start()
+ assert server._personal_context_start_task is not None # pylint: disable=protected-access
+ await server._personal_context_start_task # pylint: disable=protected-access
+
+ assert server._server is not None # pylint: disable=protected-access
+ assert events == ["ws-serve"]
+
+
+async def test_personal_context_stop_failure_does_not_change_normal_stop_result(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ server = _server(monkeypatch)
+ host = _FakePersonalContextHost.instances[0]
+ events: list[str] = []
+
+ async def _failed_stop(*, timeout_seconds: float = 30.0) -> None:
+ del timeout_seconds
+ raise RuntimeError("PersonalContext stop failed")
+
+ host.stop = _failed_stop # type: ignore[method-assign]
+ server._server = _FakeWebSocketServer(events) # pylint: disable=protected-access
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.session.kv_cache_product_hooks.cancel_pending_tasks",
+ _noop_async,
+ )
+ monkeypatch.setattr(server._jiuwenbox_runner, "stop", _noop_async)
+
+ await server.stop()
+
+ assert events == ["ws-close", "ws-wait-closed"]
+
+
+async def test_stop_finishes_main_services_before_personal_context_cleanup(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ server = _server(monkeypatch)
+ host = _FakePersonalContextHost.instances[0]
+ events: list[str] = []
+
+ async def _record_personal_context_stop(*, timeout_seconds: float = 30.0) -> None:
+ del timeout_seconds
+ events.append("personal-context-stop")
+
+ host.stop = _record_personal_context_stop # type: ignore[method-assign]
+ server._server = _FakeWebSocketServer(events) # pylint: disable=protected-access
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.session.kv_cache_product_hooks.cancel_pending_tasks",
+ _noop_async,
+ )
+ monkeypatch.setattr(server._jiuwenbox_runner, "stop", _noop_async)
+
+ await server.stop()
+
+ assert events == ["ws-close", "ws-wait-closed", "personal-context-stop"]
+
+
+async def test_stop_calls_host_when_websocket_close_fails(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ server = _server(monkeypatch)
+ host = _FakePersonalContextHost.instances[0]
+ server._server = _FailingWebSocketServer() # pylint: disable=protected-access
+
+ with pytest.raises(RuntimeError, match="close failed"):
+ await server.stop()
+
+ assert host.events == [("stop", 30.0)]
+
+
+async def test_stop_does_not_swallow_cancelled_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ server = _server(monkeypatch)
+ host = _FakePersonalContextHost.instances[0]
+
+ async def _cancelled_stop(*, timeout_seconds: float = 30.0) -> None:
+ del timeout_seconds
+ raise asyncio.CancelledError
+
+ host.stop = _cancelled_stop # type: ignore[method-assign]
+
+ with pytest.raises(asyncio.CancelledError):
+ await server.stop()
+
+
+async def _noop_async() -> None:
+ return None
diff --git a/tests/unit_tests/agentserver/test_personal_context_rail_registration.py b/tests/unit_tests/agentserver/test_personal_context_rail_registration.py
new file mode 100644
index 0000000000..75d970dce1
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_personal_context_rail_registration.py
@@ -0,0 +1,312 @@
+"""Agent mode registration uses the single Core PersonalContextRail."""
+
+from __future__ import annotations
+
+import ast
+import asyncio
+from pathlib import Path
+
+import pytest
+
+from jiuwenswarm.server.runtime.agent_adapter import interface_deep
+from jiuwenswarm.server.runtime.agent_adapter.interface import JiuWenSwarm
+from jiuwenswarm.server.runtime.agent_manager import AgentManager
+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
+ JiuWenSwarmDeepAdapter,
+)
+
+
+def _source(path: str) -> str:
+ return Path(path).read_text(encoding="utf-8")
+
+
+def test_deep_adapter_imports_core_personal_context_rail_only() -> None:
+ module = (
+ Path(__file__).parents[3]
+ / "jiuwenswarm"
+ / "server"
+ / "runtime"
+ / "agent_adapter"
+ / "interface_deep.py"
+ )
+ tree = ast.parse(_source(str(module)))
+ imports = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, (ast.Import, ast.ImportFrom))
+ ]
+ imported_names = {
+ alias.name
+ for node in imports
+ for alias in (node.names if isinstance(node, ast.Import) else node.names)
+ }
+
+ assert "PersonalContextRail" in imported_names
+ assert "ProactiveContextRail" not in imported_names
+
+
+async def test_agent_fast_and_plan_share_one_rail(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ adapter = object.__new__(JiuWenSwarmDeepAdapter)
+ adapter._is_code_agent = False # pylint: disable=protected-access
+ adapter._instance = _FakeAgent() # pylint: disable=protected-access
+ adapter._personal_context_rail = None # pylint: disable=protected-access
+ adapter._personal_context_rail_lock = asyncio.Lock() # pylint: disable=protected-access
+ adapter._personal_context_runtime_enabled = True # pylint: disable=protected-access
+
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.agent_adapter.interface_deep.PersonalContextRail",
+ _FakeRail,
+ raising=False,
+ )
+ monkeypatch.setattr(
+ adapter,
+ "_personal_context_rail_enabled",
+ lambda mode: mode in {"agent.fast", "agent.plan"},
+ )
+
+ await adapter._sync_personal_context_rail("agent.fast") # pylint: disable=protected-access
+ first = adapter._personal_context_rail # pylint: disable=protected-access
+ await adapter._sync_personal_context_rail("agent.plan") # pylint: disable=protected-access
+
+ assert first is adapter._personal_context_rail # pylint: disable=protected-access
+ assert adapter._instance.registered == [first] # pylint: disable=protected-access
+
+
+def _adapter(
+ agent: _FakeAgent,
+ *,
+ runtime_enabled: bool = True,
+) -> JiuWenSwarmDeepAdapter:
+ adapter = object.__new__(JiuWenSwarmDeepAdapter)
+ adapter._is_code_agent = False # pylint: disable=protected-access
+ adapter._instance = agent # pylint: disable=protected-access
+ adapter._personal_context_rail = None # pylint: disable=protected-access
+ adapter._personal_context_rail_lock = asyncio.Lock() # pylint: disable=protected-access
+ adapter._personal_context_runtime_enabled = runtime_enabled # pylint: disable=protected-access
+ adapter._last_mode = "agent" # pylint: disable=protected-access
+ adapter._is_session_scoped_adapter = True # pylint: disable=protected-access
+ adapter._session_adapters = {} # pylint: disable=protected-access
+ return adapter
+
+
+async def test_personal_context_rail_disabled_does_not_register() -> None:
+ agent = _FakeAgent()
+ adapter = _adapter(agent, runtime_enabled=False)
+
+ await adapter._sync_personal_context_rail("agent") # pylint: disable=protected-access
+
+ assert adapter._personal_context_rail is None # pylint: disable=protected-access
+ assert agent.register_attempts == []
+
+
+async def test_personal_context_runtime_refresh_unregisters_and_reregisters(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ agent = _FakeAgent()
+ adapter = _adapter(agent, runtime_enabled=True)
+ monkeypatch.setattr(interface_deep, "PersonalContextRail", _FakeRail)
+
+ await adapter._sync_personal_context_rail("agent") # pylint: disable=protected-access
+ rail = adapter._personal_context_rail # pylint: disable=protected-access
+ assert rail is not None
+
+ adapter.set_personal_context_runtime_enabled(False)
+ await adapter.refresh_personal_context_rail()
+ assert adapter._personal_context_rail is None # pylint: disable=protected-access
+ assert agent.unregister_attempts == [rail]
+
+ adapter.set_personal_context_runtime_enabled(True)
+ await adapter.refresh_personal_context_rail()
+ assert adapter._personal_context_rail is not None # pylint: disable=protected-access
+ assert len(agent.register_attempts) == 2
+
+
+async def test_personal_context_runtime_refresh_reaches_session_adapters(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ root = _adapter(_FakeAgent(), runtime_enabled=False)
+ root._is_session_scoped_adapter = False # pylint: disable=protected-access
+ child = _adapter(_FakeAgent(), runtime_enabled=False)
+ child._last_mode = "agent" # pylint: disable=protected-access
+ root._session_adapters = {"session-1": child} # pylint: disable=protected-access
+ monkeypatch.setattr(interface_deep, "PersonalContextRail", _FakeRail)
+
+ root.set_personal_context_runtime_enabled(True)
+ await root.refresh_personal_context_rail()
+
+ assert root._personal_context_rail is not None # pylint: disable=protected-access
+ assert child._personal_context_rail is not None # pylint: disable=protected-access
+ assert child._personal_context_runtime_enabled is True # pylint: disable=protected-access
+
+
+async def test_personal_context_manager_broadcast_isolated_per_agent() -> None:
+ first = _FakeManagedAgent()
+ failed = _FakeManagedAgent(fail_refresh=True)
+ manager = object.__new__(AgentManager)
+ manager.agents = {"web": {"first": first, "failed": failed}}
+ manager._personal_context_runtime_enabled = False # pylint: disable=protected-access
+
+ await manager.set_personal_context_runtime_enabled(True)
+
+ assert manager._personal_context_runtime_enabled is True # pylint: disable=protected-access
+ assert first.enabled_values == [True]
+ assert first.refresh_count == 1
+ assert failed.enabled_values == [True]
+
+
+async def test_personal_context_facade_forwards_runtime_refresh() -> None:
+ facade = object.__new__(JiuWenSwarm)
+ adapter = _FakeManagedAgent()
+ facade._adapter = adapter # pylint: disable=protected-access
+ facade._personal_context_runtime_enabled = False # pylint: disable=protected-access
+
+ facade.set_personal_context_runtime_enabled(True)
+ await facade.refresh_personal_context_rail()
+
+ assert facade._personal_context_runtime_enabled is True # pylint: disable=protected-access
+ assert adapter.enabled_values == [True]
+ assert adapter.refresh_count == 1
+
+
+async def test_personal_context_rail_constructor_failure_is_fail_open(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ agent = _FakeAgent()
+ adapter = _adapter(agent)
+
+ def _failed_constructor(_home: str | Path) -> object:
+ raise RuntimeError("construction failed")
+
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.agent_adapter.interface_deep.PersonalContextRail",
+ _failed_constructor,
+ )
+
+ await adapter._sync_personal_context_rail("agent.fast") # pylint: disable=protected-access
+
+ assert adapter._personal_context_rail is None # pylint: disable=protected-access
+ assert await agent.normal_request() == "ok"
+
+
+async def test_personal_context_rail_registration_and_cleanup_failure_is_fail_open(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ agent = _FakeAgent(fail_register=True, fail_unregister=True)
+ adapter = _adapter(agent)
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.agent_adapter.interface_deep.PersonalContextRail",
+ _FakeRail,
+ )
+
+ await adapter._sync_personal_context_rail("agent.fast") # pylint: disable=protected-access
+
+ assert len(agent.register_attempts) == 1
+ assert agent.unregister_attempts == agent.register_attempts
+ assert adapter._personal_context_rail is None # pylint: disable=protected-access
+ assert await agent.normal_request() == "ok"
+
+
+async def test_personal_context_rail_unregister_failure_keeps_reference_and_does_not_reregister() -> (
+ None
+):
+ rail = _FakeRail(Path("personal_context"))
+ agent = _FakeAgent(fail_unregister=True)
+ agent.registered.append(rail)
+ adapter = _adapter(agent)
+ adapter._personal_context_rail = rail # pylint: disable=protected-access
+
+ await adapter._sync_personal_context_rail("code.normal") # pylint: disable=protected-access
+
+ assert agent.unregister_attempts == [rail]
+ assert adapter._personal_context_rail is rail # pylint: disable=protected-access
+ assert await agent.normal_request() == "ok"
+
+ agent.fail_unregister = False
+ await adapter._sync_personal_context_rail("agent") # pylint: disable=protected-access
+
+ assert adapter._personal_context_rail is rail # pylint: disable=protected-access
+ assert agent.registered == [rail]
+ assert agent.register_attempts == []
+
+
+async def test_personal_context_rail_cancellation_still_propagates(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ agent = _FakeAgent(cancel_register=True)
+ adapter = _adapter(agent)
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.agent_adapter.interface_deep.PersonalContextRail",
+ _FakeRail,
+ )
+
+ with pytest.raises(asyncio.CancelledError):
+ await adapter._sync_personal_context_rail("agent.fast") # pylint: disable=protected-access
+
+
+class _FakeAgent:
+ def __init__(
+ self,
+ *,
+ fail_register: bool = False,
+ fail_unregister: bool = False,
+ cancel_register: bool = False,
+ ) -> None:
+ self.registered: list[object] = []
+ self.register_attempts: list[object] = []
+ self.unregister_attempts: list[object] = []
+ self.fail_register = fail_register
+ self.fail_unregister = fail_unregister
+ self.cancel_register = cancel_register
+
+ async def register_rail(self, rail: object) -> None:
+ self.register_attempts.append(rail)
+ self.registered.append(rail)
+ if self.cancel_register:
+ raise asyncio.CancelledError
+ if self.fail_register:
+ raise RuntimeError("register failed")
+
+ async def unregister_rail(self, rail: object) -> None:
+ self.unregister_attempts.append(rail)
+ if self.fail_unregister:
+ raise RuntimeError("unregister failed")
+ if rail in self.registered:
+ self.registered.remove(rail)
+
+ async def normal_request(self) -> str:
+ return "ok"
+
+
+class _FakeRail:
+ def __init__(self, home: str | Path) -> None:
+ self.home = Path(home)
+
+ def set_language(self, language: str) -> None:
+ del language
+
+
+class _FakeManagedAgent:
+ def __init__(self, *, fail_refresh: bool = False) -> None:
+ self.enabled_values: list[bool] = []
+ self.refresh_count = 0
+ self.fail_refresh = fail_refresh
+
+ def set_personal_context_runtime_enabled(self, enabled: bool) -> None:
+ self.enabled_values.append(enabled)
+
+ async def refresh_personal_context_rail(self) -> None:
+ self.refresh_count += 1
+ if self.fail_refresh:
+ raise RuntimeError("refresh failed")
diff --git a/tests/unit_tests/agentserver/test_personal_context_websocket_api.py b/tests/unit_tests/agentserver/test_personal_context_websocket_api.py
new file mode 100644
index 0000000000..0ee21999da
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_personal_context_websocket_api.py
@@ -0,0 +1,844 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""PersonalContext WebSocket API routing and Graph streaming tests."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from unittest.mock import AsyncMock
+
+import pytest
+from openjiuwen.core.common.exception.codes import StatusCode
+from openjiuwen.core.common.exception.errors import BaseError
+
+from jiuwenswarm.common.e2a import wire_codec
+from jiuwenswarm.common.e2a.wire_codec import parse_agent_server_wire_unary
+from jiuwenswarm.gateway.routing import agent_client
+from jiuwenswarm.common.schema.agent import AgentResponse
+from jiuwenswarm.common.schema.agent import AgentRequest
+from jiuwenswarm.server import pipeline as pipeline_module
+from jiuwenswarm.common.schema.message import ReqMethod
+from jiuwenswarm.server import agent_ws_server as server_module
+from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer
+from jiuwenswarm.server.personal_context import ws_handler
+from jiuwenswarm.server.personal_context.ws_handler import (
+ handle_personal_context_request,
+)
+
+
+def test_personal_context_does_not_extend_generic_e2a_codec_or_gateway_client() -> None:
+ assert not hasattr(wire_codec, "validate_personal_context_e2a_request_dict")
+ assert not hasattr(wire_codec, "encode_personal_context_request_for_wire")
+ assert not hasattr(wire_codec, "encode_personal_context_response_for_wire")
+ assert not hasattr(wire_codec, "encode_personal_context_chunk_for_wire")
+ assert not hasattr(agent_client, "_is_personal_context_method")
+
+
+def test_agent_server_delegates_personal_context_requests_to_module_handler() -> None:
+ assert callable(ws_handler.handle_personal_context_request)
+ assert not hasattr(AgentWebSocketServer, "_handle_personal_context_request")
+
+
+class _FakeHost:
+ def __init__(self) -> None:
+ self.calls: list[tuple[str, object]] = []
+ self.failure: BaseException | None = None
+ self.graph: dict[str, object] = {
+ "context_ready": True,
+ "nodes": [],
+ "edges": [],
+ }
+
+ def _record(self, name: str, value: object, result: object) -> object:
+ if self.failure is not None:
+ raise self.failure
+ self.calls.append((name, value))
+ return result
+
+ async def get_status(self) -> dict[str, object]:
+ return self._record("get_status", None, {"state": "RUNNING"})
+
+ async def set_runtime_enabled(self, enabled: bool) -> dict[str, object]:
+ return self._record(
+ "set_runtime_enabled",
+ enabled,
+ {"enabled": enabled},
+ )
+
+ async def get_runtime_config(self) -> dict[str, object]:
+ return self._record(
+ "get_runtime_config",
+ None,
+ {"strategy_profile": "rules"},
+ )
+
+ async def patch_runtime_config(
+ self,
+ patch: dict[str, object],
+ ) -> dict[str, object]:
+ return self._record("patch_runtime_config", patch, dict(patch))
+
+ async def select_model(self, model_index: int) -> dict[str, object]:
+ if type(model_index) is not int or model_index < 0:
+ raise ValueError("model_index must be a non-negative integer")
+ return self._record(
+ "select_model",
+ model_index,
+ {"model_index": model_index},
+ )
+
+ async def list_fetch_services(self) -> list[dict[str, object]]:
+ return self._record(
+ "list_fetch_services",
+ None,
+ [{"service_id": "github-main", "state": "STOPPED"}],
+ )
+
+ async def create_fetch_service(
+ self,
+ service: dict[str, object],
+ ) -> dict[str, object]:
+ return self._record("create_fetch_service", service, dict(service))
+
+ async def delete_fetch_service(self, service_id: str) -> None:
+ self._record("delete_fetch_service", service_id, None)
+
+ async def patch_fetch_service(
+ self,
+ service_id: str,
+ patch: dict[str, object],
+ ) -> dict[str, object]:
+ return self._record(
+ "patch_fetch_service",
+ (service_id, patch),
+ {"service_id": service_id, **patch},
+ )
+
+ async def set_fetching(
+ self,
+ *,
+ enabled: bool,
+ service_id: str | None = None,
+ ) -> None:
+ self._record("set_fetching", (enabled, service_id), None)
+
+ async def run_fetch(
+ self,
+ *,
+ service_id: str | None = None,
+ ) -> dict[str, object]:
+ return self._record(
+ "run_fetch",
+ service_id,
+ {
+ "state": "accepted",
+ "service_ids": [service_id] if service_id else ["github-main"],
+ },
+ )
+
+ async def get_fetch_run_status(
+ self,
+ service_id: str | None = None,
+ ) -> dict[str, object]:
+ return self._record(
+ "get_fetch_run_status",
+ service_id,
+ {"service_id": service_id, "state": "RUNNING"},
+ )
+
+ async def get_authorization_status(self, provider: str) -> dict[str, object]:
+ return self._record(
+ "get_authorization_status",
+ provider,
+ {
+ "provider": provider,
+ "state": "authorized",
+ "verification_url": None,
+ "expires_at": None,
+ "error": None,
+ },
+ )
+
+ async def authorize_provider(self, provider: str) -> dict[str, object]:
+ return self._record(
+ "authorize_provider",
+ provider,
+ {
+ "provider": provider,
+ "state": "authorized",
+ "verification_url": None,
+ "expires_at": None,
+ "error": None,
+ },
+ )
+
+ async def get_graph(self) -> dict[str, object]:
+ return self._record("get_graph", None, self.graph)
+
+ async def search_graph(self, query: str) -> dict[str, object]:
+ return self._record("search_graph", query, {"results": []})
+
+ async def get_graph_page(self, node_id: str) -> dict[str, object]:
+ return self._record(
+ "get_graph_page",
+ node_id,
+ {"node_id": node_id, "markdown": "# PersonalContext\n"},
+ )
+
+
+class _FakeWebSocket:
+ def __init__(self) -> None:
+ self.sent: list[dict[str, object]] = []
+ self.open = True
+
+
+def capture_wire(monkeypatch: pytest.MonkeyPatch) -> None:
+ async def _capture(ws: _FakeWebSocket, payload: dict[str, object]) -> bool:
+ ws.sent.append(payload)
+ return True
+
+ monkeypatch.setattr(server_module, "send_wire_payload", _capture)
+ monkeypatch.setattr(ws_handler, "send_wire_payload", _capture)
+
+
+def _server() -> tuple[AgentWebSocketServer, _FakeHost]:
+ server = AgentWebSocketServer.__new__(AgentWebSocketServer)
+ host = _FakeHost()
+ server._personal_context_host = host
+ return server, host
+
+
+def _request(
+ method: ReqMethod,
+ params: dict[str, object] | None = None,
+ *,
+ is_stream: bool = False,
+) -> AgentRequest:
+ return AgentRequest(
+ request_id="personal-context-1",
+ channel_id="web",
+ req_method=method,
+ params=params or {},
+ is_stream=is_stream,
+ agent_ref={"mode": "agent", "id": "agent-1"},
+ )
+
+
+def _canonical(
+ method: str,
+ params: dict[str, object] | None = None,
+ *,
+ is_stream: bool = False,
+) -> str:
+ return json.dumps(
+ {
+ "protocol_version": "1.0",
+ "request_id": "personal-context-wire-1",
+ "channel": "web",
+ "method": method,
+ "params": params or {},
+ "is_stream": is_stream,
+ "agent_ref": {"mode": "agent", "id": "agent-1"},
+ }
+ )
+
+
+SERVICE_PAYLOAD: dict[str, object] = {
+ "service_id": "local-files-1",
+ "provider": "local_files",
+ "enabled": True,
+ "interval_seconds": 3_600,
+ "max_items_per_run": 100,
+ "source": {"root_dir": "D:/context"},
+ "credentials": {},
+}
+
+
+PERSONAL_CONTEXT_HOST_CALLS = [
+ (ReqMethod.PERSONAL_CONTEXT_RUNTIME_STATUS, {}, "get_status", None, None),
+ (ReqMethod.PERSONAL_CONTEXT_RUNTIME_START, {}, "set_runtime_enabled", True, None),
+ (ReqMethod.PERSONAL_CONTEXT_RUNTIME_STOP, {}, "set_runtime_enabled", False, None),
+ (
+ ReqMethod.PERSONAL_CONTEXT_RUNTIME_GET_CONFIG,
+ {},
+ "get_runtime_config",
+ None,
+ None,
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_RUNTIME_PATCH_CONFIG,
+ {"patch": {"strategy_profile": "rules"}},
+ "patch_runtime_config",
+ {"strategy_profile": "rules"},
+ None,
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_RUNTIME_SELECT_MODEL,
+ {"model_index": 0},
+ "select_model",
+ 0,
+ None,
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_LIST_SERVICES,
+ {},
+ "list_fetch_services",
+ None,
+ None,
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_CREATE_SERVICE,
+ {"service": SERVICE_PAYLOAD},
+ "create_fetch_service",
+ SERVICE_PAYLOAD,
+ SERVICE_PAYLOAD,
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_DELETE_SERVICE,
+ {"service_id": "local-files-1"},
+ "delete_fetch_service",
+ "local-files-1",
+ {"ok": True},
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_PATCH_SERVICE,
+ {"service_id": "github-main", "patch": {"interval_seconds": 10_800}},
+ "patch_fetch_service",
+ ("github-main", {"interval_seconds": 10_800}),
+ None,
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_START_SERVICE,
+ {"service_id": " github-main "},
+ "set_fetching",
+ (True, "github-main"),
+ None,
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_STOP_SERVICE,
+ {"service_id": "github-main"},
+ "set_fetching",
+ (False, "github-main"),
+ None,
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_START_SCHEDULER,
+ {},
+ "set_fetching",
+ (True, None),
+ None,
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_STOP_SCHEDULER,
+ {},
+ "set_fetching",
+ (False, None),
+ None,
+ ),
+ (ReqMethod.PERSONAL_CONTEXT_FETCH_RUN_ALL, {}, "run_fetch", None, None),
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_RUN_ONE,
+ {"service_id": "github-main"},
+ "run_fetch",
+ "github-main",
+ None,
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_GET_RUN_STATUS,
+ {"service_id": "github-main"},
+ "get_fetch_run_status",
+ "github-main",
+ None,
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_GET_AUTHORIZATION_STATUS,
+ {"provider": "feishu"},
+ "get_authorization_status",
+ "feishu",
+ {
+ "provider": "feishu",
+ "state": "authorized",
+ "verification_url": None,
+ "expires_at": None,
+ "error": None,
+ },
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_AUTHORIZE_PROVIDER,
+ {"provider": "feishu"},
+ "authorize_provider",
+ "feishu",
+ {
+ "provider": "feishu",
+ "state": "authorized",
+ "verification_url": None,
+ "expires_at": None,
+ "error": None,
+ },
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_CONTEXT_SEARCH_PAGES,
+ {"query": " 主动上下文 "},
+ "search_graph",
+ "主动上下文",
+ None,
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_CONTEXT_GET_NODE,
+ {"node_id": "page:topics/personal_context.md"},
+ "get_graph_page",
+ "page:topics/personal_context.md",
+ None,
+ ),
+]
+
+
+def test_agentserver_registers_exact_22_personal_context_methods() -> None:
+ assert server_module._PERSONAL_CONTEXT_REQ_METHODS == {
+ item for item in ReqMethod if item.value.startswith("personal_context.")
+ }
+ assert len(server_module._PERSONAL_CONTEXT_REQ_METHODS) == 22
+
+
+ ("method", "params", "host_method", "host_argument", "expected_result"),
+ PERSONAL_CONTEXT_HOST_CALLS,
+)
+async def test_non_graph_methods_call_exact_host_operation(
+ capture_wire: None,
+ method: ReqMethod,
+ params: dict[str, object],
+ host_method: str,
+ host_argument: object,
+ expected_result: dict[str, object] | None,
+) -> None:
+ server, host = _server()
+ ws = _FakeWebSocket()
+
+ await handle_personal_context_request(
+ host, ws, _request(method, params), asyncio.Lock()
+ )
+
+ assert host.calls == [(host_method, host_argument)]
+ assert len(ws.sent) == 1
+ assert ws.sent[0]["protocol_version"] == "1.0"
+ assert ws.sent[0]["is_final"] is True
+ assert ws.sent[0]["status"] == "succeeded"
+ assert ws.sent[0]["agent_ref"] == {"mode": "agent", "id": "agent-1"}
+ if expected_result is not None:
+ response = parse_agent_server_wire_unary(ws.sent[0])
+ assert response.payload == expected_result
+
+
+ ("method", "enabled"),
+ [
+ (ReqMethod.PERSONAL_CONTEXT_RUNTIME_START, True),
+ (ReqMethod.PERSONAL_CONTEXT_RUNTIME_STOP, False),
+ ],
+)
+async def test_runtime_switch_notifies_agent_manager_after_host_success(
+ capture_wire: None,
+ method: ReqMethod,
+ enabled: bool,
+) -> None:
+ _server_instance, host = _server()
+ ws = _FakeWebSocket()
+ notifications: list[tuple[bool, list[tuple[str, object]]]] = []
+
+ async def _runtime_changed(value: bool) -> None:
+ notifications.append((value, list(host.calls)))
+
+ await handle_personal_context_request(
+ host,
+ ws,
+ _request(method),
+ asyncio.Lock(),
+ runtime_enabled_changed=_runtime_changed,
+ )
+
+ assert host.calls == [("set_runtime_enabled", enabled)]
+ assert notifications == [(enabled, host.calls)]
+ assert ws.sent[0]["status"] == "succeeded"
+
+
+async def test_runtime_switch_callback_failure_is_fail_open(
+ capture_wire: None,
+) -> None:
+ _server_instance, host = _server()
+ ws = _FakeWebSocket()
+
+ async def _failed_callback(_enabled: bool) -> None:
+ raise RuntimeError("manager refresh failed")
+
+ await handle_personal_context_request(
+ host,
+ ws,
+ _request(ReqMethod.PERSONAL_CONTEXT_RUNTIME_START),
+ asyncio.Lock(),
+ runtime_enabled_changed=_failed_callback,
+ )
+
+ assert host.calls == [("set_runtime_enabled", True)]
+ assert ws.sent[0]["status"] == "succeeded"
+
+
+ ("method", "invalid_params", "valid_params", "valid_host_call"),
+ [
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_CREATE_SERVICE,
+ {},
+ {"service": SERVICE_PAYLOAD},
+ ("create_fetch_service", SERVICE_PAYLOAD),
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_CREATE_SERVICE,
+ {"service": "not-an-object"},
+ {"service": SERVICE_PAYLOAD},
+ ("create_fetch_service", SERVICE_PAYLOAD),
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_DELETE_SERVICE,
+ {},
+ {"service_id": "local-files-1"},
+ ("delete_fetch_service", "local-files-1"),
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_DELETE_SERVICE,
+ {"service_id": " "},
+ {"service_id": "local-files-1"},
+ ("delete_fetch_service", "local-files-1"),
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_DELETE_SERVICE,
+ {"service_id": 1},
+ {"service_id": "local-files-1"},
+ ("delete_fetch_service", "local-files-1"),
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_GET_AUTHORIZATION_STATUS,
+ {},
+ {"provider": "feishu"},
+ ("get_authorization_status", "feishu"),
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_GET_AUTHORIZATION_STATUS,
+ {"provider": " "},
+ {"provider": "feishu"},
+ ("get_authorization_status", "feishu"),
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_GET_AUTHORIZATION_STATUS,
+ {"provider": 1},
+ {"provider": "feishu"},
+ ("get_authorization_status", "feishu"),
+ ),
+ ],
+)
+async def test_source_management_bad_request_keeps_connection_available(
+ capture_wire: None,
+ method: ReqMethod,
+ invalid_params: dict[str, object],
+ valid_params: dict[str, object],
+ valid_host_call: tuple[str, object],
+) -> None:
+ _server_instance, host = _server()
+ ws = _FakeWebSocket()
+
+ await handle_personal_context_request(
+ host,
+ ws,
+ _request(method, invalid_params),
+ asyncio.Lock(),
+ )
+
+ assert host.calls == []
+ assert ws.open is True
+ assert ws.sent[0]["status"] == "failed"
+ assert ws.sent[0]["body"]["details"]["code"] == "BAD_REQUEST"
+
+ await handle_personal_context_request(
+ host,
+ ws,
+ _request(method, valid_params),
+ asyncio.Lock(),
+ )
+
+ assert host.calls == [valid_host_call]
+ assert len(ws.sent) == 2
+ assert ws.sent[1]["status"] == "succeeded"
+ assert ws.sent[1]["is_final"] is True
+
+
+async def test_select_model_rejects_old_origin_index_parameter(
+ capture_wire: None,
+) -> None:
+ _server_instance, host = _server()
+ ws = _FakeWebSocket()
+
+ await handle_personal_context_request(
+ host,
+ ws,
+ _request(ReqMethod.PERSONAL_CONTEXT_RUNTIME_SELECT_MODEL, {"origin_index": 0}),
+ asyncio.Lock(),
+ )
+
+ assert host.calls == []
+ assert ws.sent[0]["status"] == "failed"
+ assert ws.sent[0]["body"]["details"]["code"] == "BAD_REQUEST"
+
+
+async def test_non_graph_stream_request_is_one_completed_chunk(
+ capture_wire: None,
+) -> None:
+ server, host = _server()
+ ws = _FakeWebSocket()
+
+ await handle_personal_context_request(
+ host,
+ ws,
+ _request(ReqMethod.PERSONAL_CONTEXT_RUNTIME_STATUS, is_stream=True),
+ asyncio.Lock(),
+ )
+
+ assert host.calls == [("get_status", None)]
+ assert len(ws.sent) == 1
+ assert ws.sent[0]["is_stream"] is True
+ assert ws.sent[0]["is_final"] is True
+
+
+async def test_graph_stream_is_bounded_ordered_and_final(
+ capture_wire: None,
+) -> None:
+ server, host = _server()
+ host.graph = {
+ "context_ready": True,
+ "nodes": [{"id": f"page:{index}"} for index in range(450)],
+ "edges": [{"source": f"page:{index}"} for index in range(250)],
+ }
+ ws = _FakeWebSocket()
+
+ await handle_personal_context_request(
+ host,
+ ws,
+ _request(ReqMethod.PERSONAL_CONTEXT_CONTEXT_STREAM_GRAPH, is_stream=True),
+ asyncio.Lock(),
+ )
+
+ assert host.calls == [("get_graph", None)]
+ assert [frame["sequence"] for frame in ws.sent] == list(range(7))
+ assert [frame["is_final"] for frame in ws.sent] == [
+ False,
+ False,
+ False,
+ False,
+ False,
+ False,
+ True,
+ ]
+ events = [
+ frame["body"]["result"] if frame["is_final"] else frame["body"]["delta"]
+ for frame in ws.sent
+ ]
+ assert [event["event_type"] for event in events] == [
+ "personal_context.graph.start",
+ "personal_context.graph.nodes",
+ "personal_context.graph.nodes",
+ "personal_context.graph.nodes",
+ "personal_context.graph.edges",
+ "personal_context.graph.edges",
+ "personal_context.graph.end",
+ ]
+ assert events[-1]["node_count"] == 450
+ assert events[-1]["edge_count"] == 250
+
+
+async def test_graph_requires_stream_request(capture_wire: None) -> None:
+ server, host = _server()
+ ws = _FakeWebSocket()
+
+ await handle_personal_context_request(
+ host,
+ ws,
+ _request(ReqMethod.PERSONAL_CONTEXT_CONTEXT_STREAM_GRAPH),
+ asyncio.Lock(),
+ )
+
+ assert host.calls == []
+ assert ws.sent[0]["status"] == "failed"
+ assert ws.sent[0]["body"]["details"]["code"] == "BAD_REQUEST"
+
+
+async def test_canonical_personal_context_bypasses_chat_hooks_and_agent_creation(
+ capture_wire: None,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ server, host = _server()
+ monkeypatch.setattr(
+ pipeline_module,
+ "_trigger_before_chat_request_hook",
+ AsyncMock(side_effect=AssertionError("PersonalContext must bypass chat hooks")),
+ )
+ monkeypatch.setattr(
+ pipeline_module,
+ "_handle_unary",
+ AsyncMock(side_effect=AssertionError("PersonalContext must bypass Agent creation")),
+ )
+ ws = _FakeWebSocket()
+
+ await server._handle_message(
+ ws,
+ _canonical("personal_context.runtime.status"),
+ asyncio.Lock(),
+ )
+
+ assert host.calls == [("get_status", None)]
+ pipeline_module._trigger_before_chat_request_hook.assert_not_awaited()
+ pipeline_module._handle_unary.assert_not_awaited()
+
+
+ ("method", "params", "host_call"),
+ [
+ ("personal_context.runtime.status", {}, ("get_status", None)),
+ ("personal_context.runtime.get_config", {}, ("get_runtime_config", None)),
+ ("personal_context.fetch.list_services", {}, ("list_fetch_services", None)),
+ (
+ "personal_context.fetch.get_run_status",
+ {},
+ ("get_fetch_run_status", None),
+ ),
+ (
+ "personal_context.context.search_pages",
+ {"query": "context"},
+ ("search_graph", "context"),
+ ),
+ (
+ "personal_context.context.get_node",
+ {"node_id": "page:description.md"},
+ ("get_graph_page", "page:description.md"),
+ ),
+ ],
+)
+async def test_canonical_wire_round_trip_for_query_methods(
+ capture_wire: None,
+ method: str,
+ params: dict[str, object],
+ host_call: tuple[str, object],
+) -> None:
+ server, host = _server()
+ ws = _FakeWebSocket()
+
+ await server._handle_message(ws, _canonical(method, params), asyncio.Lock())
+
+ response = parse_agent_server_wire_unary(ws.sent[0])
+ assert host.calls == [host_call]
+ assert response.ok is True
+
+
+async def test_personal_context_failure_keeps_connection_and_ordinary_request_available(
+ capture_wire: None,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ server, host = _server()
+ host.failure = RuntimeError("PersonalContext start failed")
+ ws = _FakeWebSocket()
+
+ await server._handle_message(
+ ws,
+ _canonical("personal_context.runtime.start"),
+ asyncio.Lock(),
+ )
+
+ assert ws.sent[0]["response_kind"] == "e2a.error"
+ assert ws.open is True
+
+ async def ordinary_response(
+ ctx: object,
+ request: AgentRequest,
+ ) -> None:
+ wire = server_module.encode_agent_response_for_wire(
+ AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=True,
+ payload={"content": "ordinary agent still works"},
+ ),
+ response_id=request.request_id,
+ )
+ await server_module.send_wire_payload(ws, wire)
+
+ monkeypatch.setattr(
+ pipeline_module, "_trigger_before_chat_request_hook", AsyncMock()
+ )
+ monkeypatch.setattr(
+ pipeline_module, "_ensure_auto_team_binding_for_chat", AsyncMock()
+ )
+ monkeypatch.setattr(
+ pipeline_module, "_handle_unary", AsyncMock(side_effect=ordinary_response)
+ )
+ await server._handle_message(
+ ws,
+ json.dumps(
+ {
+ "protocol_version": "1.0",
+ "request_id": "ordinary-1",
+ "channel": "web",
+ "method": "chat.send",
+ "params": {"query": "hello"},
+ }
+ ),
+ asyncio.Lock(),
+ )
+
+ assert ws.sent[1]["status"] == "succeeded"
+ pipeline_module._handle_unary.assert_awaited_once()
+
+
+async def test_core_error_is_returned_as_final_e2a_error(capture_wire: None) -> None:
+ server, host = _server()
+ host.failure = BaseError(StatusCode.ERROR, msg="safe PersonalContext error")
+ ws = _FakeWebSocket()
+
+ await handle_personal_context_request(
+ host,
+ ws,
+ _request(ReqMethod.PERSONAL_CONTEXT_RUNTIME_STATUS),
+ asyncio.Lock(),
+ )
+
+ assert ws.sent[0]["response_kind"] == "e2a.error"
+ assert ws.sent[0]["body"]["details"] == {
+ "error": "safe PersonalContext error",
+ "code": StatusCode.ERROR.code,
+ "status": "ERROR",
+ }
+
+
+async def test_handler_propagates_cancellation(capture_wire: None) -> None:
+ server, host = _server()
+ host.failure = asyncio.CancelledError()
+
+ with pytest.raises(asyncio.CancelledError):
+ await handle_personal_context_request(
+ host,
+ _FakeWebSocket(),
+ _request(ReqMethod.PERSONAL_CONTEXT_RUNTIME_STATUS),
+ asyncio.Lock(),
+ )
diff --git a/tests/unit_tests/evolution/test_message.py b/tests/unit_tests/evolution/test_message.py
index 25c069d76a..3301ae0ce8 100644
--- a/tests/unit_tests/evolution/test_message.py
+++ b/tests/unit_tests/evolution/test_message.py
@@ -25,6 +25,40 @@ class TestReqMethod:
assert ReqMethod.CONFIG_GET.value == "config.get"
assert ReqMethod.CONFIG_SET.value == "config.set"
+ @staticmethod
+ def test_personal_context_methods():
+ """Test PersonalContext request methods exposed through the WebSocket gateway."""
+ methods = {
+ item.value
+ for item in ReqMethod
+ if item.value.startswith("personal_context.")
+ }
+ assert methods == {
+ "personal_context.runtime.status",
+ "personal_context.runtime.start",
+ "personal_context.runtime.stop",
+ "personal_context.runtime.get_config",
+ "personal_context.runtime.patch_config",
+ "personal_context.runtime.select_model",
+ "personal_context.fetch.list_services",
+ "personal_context.fetch.create_service",
+ "personal_context.fetch.delete_service",
+ "personal_context.fetch.patch_service",
+ "personal_context.fetch.start_service",
+ "personal_context.fetch.stop_service",
+ "personal_context.fetch.start_scheduler",
+ "personal_context.fetch.stop_scheduler",
+ "personal_context.fetch.run_all",
+ "personal_context.fetch.run_one",
+ "personal_context.fetch.get_run_status",
+ "personal_context.fetch.get_authorization_status",
+ "personal_context.fetch.authorize_provider",
+ "personal_context.context.stream_graph",
+ "personal_context.context.search_pages",
+ "personal_context.context.get_node",
+ }
+ assert len(methods) == 22
+
@staticmethod
def test_session_methods():
"""Test session-related request methods."""
diff --git a/tests/unit_tests/personal_context/test_closed_class_inventory.py b/tests/unit_tests/personal_context/test_closed_class_inventory.py
new file mode 100644
index 0000000000..73882d2c01
--- /dev/null
+++ b/tests/unit_tests/personal_context/test_closed_class_inventory.py
@@ -0,0 +1,42 @@
+"""Clean-cut checks for the single JiuwenSwarm PersonalContext host class."""
+
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+
+ROOT = Path(__file__).parents[3]
+HOST = ROOT / "jiuwenswarm" / "server" / "personal_context"
+LEGACY_PACKAGE = ROOT / "jiuwenswarm" / "server" / "proactive_harness"
+
+
+def _classes(path: Path) -> set[str]:
+ result: set[str] = set()
+ for file in sorted(path.rglob("*.py")):
+ tree = ast.parse(file.read_text(encoding="utf-8"))
+ result.update(
+ node.name for node in ast.walk(tree) if isinstance(node, ast.ClassDef)
+ )
+ return result
+
+
+def test_jiuwen_swarm_declares_only_the_host_class() -> None:
+ assert _classes(HOST) == {"PersonalContextHostAPI"}
+
+
+def test_legacy_host_package_is_removed() -> None:
+ assert not any(LEGACY_PACKAGE.rglob("*.py"))
+
+
+def test_host_has_no_legacy_transport_imports() -> None:
+ source = "\n".join(file.read_text(encoding="utf-8") for file in HOST.rglob("*.py"))
+ for forbidden in (
+ "ProactiveHarness",
+ "ProactiveContextService",
+ "proactive_harness",
+ "open_description_reader",
+ "FastAPI",
+ "uvicorn",
+ ):
+ assert forbidden not in source
diff --git a/tests/unit_tests/personal_context/test_host_api.py b/tests/unit_tests/personal_context/test_host_api.py
new file mode 100644
index 0000000000..c14e01d645
--- /dev/null
+++ b/tests/unit_tests/personal_context/test_host_api.py
@@ -0,0 +1,2144 @@
+from __future__ import annotations
+
+import ast
+import asyncio
+import contextlib
+from copy import deepcopy
+from pathlib import Path
+from types import SimpleNamespace
+from typing import BinaryIO, cast
+
+import pytest
+import yaml
+
+from openjiuwen.harness.personal_context import PersonalContext
+
+from jiuwenswarm.server.personal_context import host_api as host_module
+from jiuwenswarm.server.personal_context.host_api import PersonalContextHostAPI
+
+
+HOST_API_PATH = (
+ Path(__file__).parents[3]
+ / "jiuwenswarm"
+ / "server"
+ / "personal_context"
+ / "host_api.py"
+)
+
+UNCONFIGURED_PROJECTION = {
+ "configured": False,
+ "enabled": False,
+ "fetching_enabled": False,
+ "strategy_profile": "rules",
+ "model_index": None,
+ "fetch_services": [],
+}
+
+
+def _config(
+ *,
+ enabled: bool = True,
+ fetching_enabled: bool = True,
+ root_dir: Path | None = None,
+ interval: float = 60.0,
+) -> dict[str, object]:
+ root = root_dir or Path.cwd()
+ return {
+ "enabled": enabled,
+ "fetching_enabled": fetching_enabled,
+ "strategy_profile": "rules",
+ "fetch_services": [
+ {
+ "service_id": "local-notes",
+ "provider": "local_files",
+ "enabled": True,
+ "interval_seconds": interval,
+ "source": {"root_dir": str(root)},
+ "credentials": {},
+ }
+ ],
+ }
+
+
+def _local_service(service_id: str, root_dir: Path) -> dict[str, object]:
+ return {
+ "service_id": service_id,
+ "provider": "local_files",
+ "enabled": True,
+ "interval_seconds": 60.0,
+ "max_items_per_run": None,
+ "source": {"root_dir": str(root_dir)},
+ "credentials": {},
+ }
+
+
+def _bookmark_service(service_id: str) -> dict[str, object]:
+ return {
+ "service_id": service_id,
+ "provider": "browser_bookmarks",
+ "enabled": True,
+ "interval_seconds": 60.0,
+ "max_items_per_run": None,
+ "source": {},
+ "credentials": {},
+ }
+
+
+def _config_with_services(
+ services: list[dict[str, object]],
+) -> dict[str, object]:
+ return {
+ "enabled": False,
+ "fetching_enabled": False,
+ "strategy_profile": "rules",
+ "fetch_services": services,
+ }
+
+
+class _FakeStatus:
+ state = "RUNNING"
+
+ def model_dump(self, *, mode: str) -> dict[str, object]:
+ assert mode == "json"
+ return {"state": self.state, "configured": True}
+
+
+class FakeCore:
+ Config = None
+
+ def __init__(self) -> None:
+ self.calls: list[tuple[str, object]] = []
+ self.snapshot_result: object = object()
+ self.snapshot_error: BaseException | None = None
+ self.configured: object | None = None
+ self.active = False
+ self.deactivate_error: BaseException | None = None
+ self.deactivate_changes_active_before_error = False
+ self.set_error: BaseException | None = None
+ self.activate_error: BaseException | None = None
+ self.activate_started: asyncio.Event | None = None
+ self.activate_release: asyncio.Event | None = None
+ self.deactivate_started: asyncio.Event | None = None
+ self.deactivate_release: asyncio.Event | None = None
+ self.cursor_payloads: dict[str, bytes] = {}
+ self.remove_cursor_error: BaseException | None = None
+ self.restore_cursor_error: BaseException | None = None
+ self.authorization_status_result: dict[str, object] = {
+ "provider": "feishu",
+ "state": "authorized",
+ "verification_url": None,
+ "expires_at": None,
+ "error": None,
+ }
+ self.authorization_status_error: BaseException | None = None
+ self.authorization_status_started: asyncio.Event | None = None
+ self.authorization_status_release: asyncio.Event | None = None
+
+ async def set_configuration(self, config: object) -> None:
+ self.calls.append(("set_configuration", config))
+ if self.set_error is not None:
+ error = self.set_error
+ self.set_error = None
+ raise error
+ self.configured = config
+
+ async def activate_runtime(self) -> None:
+ self.calls.append(("activate_runtime", None))
+ if self.activate_started is not None:
+ self.activate_started.set()
+ if self.activate_release is not None:
+ await self.activate_release.wait()
+ if self.activate_error is not None:
+ error = self.activate_error
+ self.activate_error = None
+ raise error
+ self.active = True
+
+ async def deactivate_runtime(self, *, timeout_seconds: float = 30.0) -> None:
+ self.calls.append(("deactivate_runtime", timeout_seconds))
+ if self.deactivate_started is not None:
+ self.deactivate_started.set()
+ if self.deactivate_release is not None:
+ await self.deactivate_release.wait()
+ if self.deactivate_error is not None:
+ error = self.deactivate_error
+ self.deactivate_error = None
+ if self.deactivate_changes_active_before_error:
+ self.active = False
+ raise error
+ self.active = False
+
+ async def snapshot(self) -> object:
+ self.calls.append(("snapshot", None))
+ if self.snapshot_error is not None:
+ error = self.snapshot_error
+ self.snapshot_error = None
+ raise error
+ return self.snapshot_result
+
+ async def authorize_provider(self, provider: str) -> dict[str, object]:
+ self.calls.append(("authorize_provider", provider))
+ return {
+ "provider": provider,
+ "state": "authorized",
+ "verification_url": None,
+ "expires_at": None,
+ "error": None,
+ }
+
+ async def get_authorization_status(self, provider: str) -> dict[str, object]:
+ self.calls.append(("get_authorization_status", provider))
+ if self.authorization_status_started is not None:
+ self.authorization_status_started.set()
+ if self.authorization_status_release is not None:
+ await asyncio.wait_for(
+ self.authorization_status_release.wait(), timeout=5.0
+ )
+ if self.authorization_status_error is not None:
+ raise self.authorization_status_error
+ return dict(self.authorization_status_result)
+
+ async def run_fetch(
+ self,
+ *,
+ service_id: str | None = None,
+ ) -> dict[str, object]:
+ self.calls.append(("run_fetch", service_id))
+ return {
+ "state": "accepted",
+ "service_ids": [service_id or "local-notes"],
+ }
+
+ def remove_fetch_cursor(self, service_id: str) -> bytes | None:
+ self.calls.append(("remove_fetch_cursor", service_id))
+ if self.remove_cursor_error is not None:
+ error = self.remove_cursor_error
+ self.remove_cursor_error = None
+ raise error
+ return self.cursor_payloads.pop(service_id, None)
+
+ def restore_fetch_cursor(
+ self,
+ service_id: str,
+ payload: bytes | None,
+ ) -> None:
+ self.calls.append(("restore_fetch_cursor", (service_id, payload)))
+ if self.restore_cursor_error is not None:
+ error = self.restore_cursor_error
+ self.restore_cursor_error = None
+ raise error
+ if payload is None:
+ self.cursor_payloads.pop(service_id, None)
+ else:
+ self.cursor_payloads[service_id] = payload
+
+ async def get_graph(self) -> dict[str, object]:
+ self.calls.append(("get_graph", None))
+ return {"context_ready": True, "nodes": [], "edges": []}
+
+ async def search_graph(self, query: str) -> dict[str, object]:
+ self.calls.append(("search_graph", query))
+ return {
+ "results": [
+ {
+ "node_id": "page:topics/personal_context.md",
+ "title": "主动上下文",
+ "path": "topics/personal_context.md",
+ "snippet": "主动上下文",
+ }
+ ]
+ }
+
+ async def get_graph_page(self, node_id: str) -> dict[str, object]:
+ self.calls.append(("get_graph_page", node_id))
+ return {
+ "node_id": node_id,
+ "title": "主动上下文",
+ "path": "topics/personal_context.md",
+ "markdown": "# 主动上下文\n",
+ }
+
+
+def fake_host(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> tuple[PersonalContextHostAPI, FakeCore]:
+ host = PersonalContextHostAPI(home=tmp_path / "personal_context")
+ fake = FakeCore()
+ monkeypatch.setattr(host, "_personal_context", fake)
+ return host, fake
+
+
+def test_host_module_imports_personal_context_from_harness() -> None:
+ tree = ast.parse(HOST_API_PATH.read_text(encoding="utf-8"))
+ imported: list[str] = []
+ for node in ast.walk(tree):
+ if (
+ isinstance(node, ast.ImportFrom)
+ and node.module == "openjiuwen.harness.personal_context"
+ ):
+ imported.extend(alias.name for alias in node.names)
+ assert imported == ["PersonalContext"]
+
+
+def test_boolean_switches_use_isinstance_guards() -> None:
+ source = HOST_API_PATH.read_text(encoding="utf-8")
+
+ assert source.count("if not isinstance(enabled, bool):") == 2
+ assert "type(enabled) is not bool" not in source
+
+
+def test_authorization_cancellation_is_rethrown_after_exception_handler() -> None:
+ tree = ast.parse(HOST_API_PATH.read_text(encoding="utf-8"))
+ function = next(
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.AsyncFunctionDef)
+ and node.name == "get_authorization_status"
+ )
+
+ handlers = [
+ node
+ for node in ast.walk(function)
+ if isinstance(node, ast.ExceptHandler)
+ and ast.unparse(node.type) == "asyncio.CancelledError"
+ ]
+ assert len(handlers) == 1
+ assert not any(
+ isinstance(statement, ast.Raise) and statement.exc is None
+ for statement in handlers[0].body
+ )
+
+
+def test_constructor_does_not_read_or_write_yaml(tmp_path: Path) -> None:
+ home = tmp_path / "personal_context"
+ host = PersonalContextHostAPI(home=home)
+ assert not home.exists()
+ assert not (home / "personal_context.yaml").exists()
+ assert host._config is None
+
+
+async def test_start_without_yaml_keeps_host_unconfigured(tmp_path: Path) -> None:
+ home = tmp_path / "personal_context"
+ host = PersonalContextHostAPI(home=home)
+ await host.start()
+ status = await host.get_status()
+ assert status.configured is False
+ assert status.state == "CREATED"
+ assert not home.exists()
+
+
[email protected]("enabled", [False, True])
+async def test_runtime_enabled_projection_reads_loaded_configuration(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+ enabled: bool,
+) -> None:
+ host, _core = fake_host
+
+ assert await host.is_runtime_enabled() is False
+
+ await host.configure(_config(enabled=enabled, root_dir=tmp_path))
+
+ assert await host.is_runtime_enabled() is enabled
+
+
+async def test_unconfigured_projection_and_stop_are_read_only_until_first_start(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+) -> None:
+ host, core = fake_host
+
+ assert await host.get_runtime_config() == UNCONFIGURED_PROJECTION
+ assert await host.set_runtime_enabled(False) == UNCONFIGURED_PROJECTION
+ assert not host._home.exists()
+ assert core.calls == []
+
+ started = await host.set_runtime_enabled(True)
+
+ assert started["enabled"] is True
+ assert started["fetching_enabled"] is False
+ assert started["strategy_profile"] == "rules"
+ assert started["model_index"] is None
+ assert started["fetch_services"] == []
+ assert host._config_path.is_file()
+ assert [name for name, _value in core.calls] == [
+ "set_configuration",
+ "activate_runtime",
+ ]
+ assert core.active is True
+
+
[email protected]("failure_attribute", ["set_error", "activate_error"])
+async def test_first_start_core_failure_rolls_back_to_unconfigured(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ failure_attribute: str,
+) -> None:
+ host, core = fake_host
+ setattr(core, failure_attribute, RuntimeError("first start failed"))
+
+ with pytest.raises(PersonalContext.Error):
+ await host.set_runtime_enabled(True)
+
+ expected_calls = ["set_configuration", "deactivate_runtime"]
+ if failure_attribute == "activate_error":
+ expected_calls = [
+ "set_configuration",
+ "activate_runtime",
+ "deactivate_runtime",
+ ]
+ assert [name for name, _value in core.calls] == expected_calls
+ assert host._config is None
+ assert host._stored_config is None
+ assert not host._config_path.exists()
+ assert not core.active
+ assert list(host._home.glob(".*.tmp")) == []
+
+
+async def test_first_start_cancellation_rolls_back_to_unconfigured(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+) -> None:
+ host, core = fake_host
+ core.activate_started = asyncio.Event()
+ core.activate_release = asyncio.Event()
+
+ task = asyncio.create_task(host.set_runtime_enabled(True))
+ await asyncio.sleep(0)
+ if task.done():
+ await task
+ pytest.fail("first start completed before Core activation was observed")
+ await asyncio.wait_for(core.activate_started.wait(), timeout=1.0)
+ task.cancel()
+ core.activate_release.set()
+
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ assert task.cancelled()
+ assert host._config is None
+ assert host._stored_config is None
+ assert not host._config_path.exists()
+ assert not core.active
+ assert list(host._home.glob(".*.tmp")) == []
+
+
+async def test_first_start_replace_failure_stops_core_and_removes_temporary_file(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ host, core = fake_host
+
+ def fail_replace(_temporary: Path, _path: Path) -> None:
+ raise OSError("replace failed")
+
+ monkeypatch.setattr(host_module, "_replace_yaml", fail_replace)
+
+ with pytest.raises(PersonalContext.Error):
+ await host.set_runtime_enabled(True)
+
+ assert [name for name, _value in core.calls] == [
+ "set_configuration",
+ "activate_runtime",
+ "deactivate_runtime",
+ ]
+ assert not core.active
+ assert host._config is None
+ assert host._stored_config is None
+ assert not host._config_path.exists()
+ assert list(host._home.glob(".*.tmp")) == []
+
+
+async def test_first_start_replace_and_rollback_stop_failure_keeps_core_reference(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ host, core = fake_host
+ core.deactivate_error = RuntimeError("sensitive rollback stop failure")
+
+ def fail_replace(_temporary: Path, _path: Path) -> None:
+ raise OSError("replace failed")
+
+ monkeypatch.setattr(host_module, "_replace_yaml", fail_replace)
+
+ with pytest.raises(PersonalContext.Error) as caught:
+ await host.set_runtime_enabled(True)
+
+ assert caught.value.status.name == "CONTEXT_PROACTIVE_STATE_INVALID"
+ assert "previous configuration could not be restored" in str(caught.value)
+ assert "sensitive rollback stop failure" not in str(caught.value)
+ assert [name for name, _value in core.calls] == [
+ "set_configuration",
+ "activate_runtime",
+ "deactivate_runtime",
+ ]
+ assert host._personal_context is core
+ assert core.active is True
+ assert host._config is None
+ assert host._stored_config is None
+ assert not host._config_path.exists()
+ assert list(host._home.glob(".*.tmp")) == []
+
+
+async def test_configure_writes_yaml_and_starts_enabled_core(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore], tmp_path: Path
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(root_dir=tmp_path))
+ assert (host._home / "personal_context.yaml").is_file()
+ saved = yaml.safe_load(
+ (host._home / "personal_context.yaml").read_text(encoding="utf-8")
+ )
+ assert saved["enabled"] is True
+ assert [name for name, _ in core.calls] == ["set_configuration", "activate_runtime"]
+
+
+async def test_authorize_provider_delegates_to_configured_core(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore], tmp_path: Path
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ core.calls.clear()
+
+ result = await host.authorize_provider("feishu")
+
+ assert result["state"] == "authorized"
+ assert core.calls == [("authorize_provider", "feishu")]
+
+
+async def test_get_authorization_status_delegates_full_result_to_configured_core(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore], tmp_path: Path
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ core.calls.clear()
+
+ result = await host.get_authorization_status("feishu")
+
+ assert result == {
+ "provider": "feishu",
+ "state": "authorized",
+ "verification_url": None,
+ "expires_at": None,
+ "error": None,
+ }
+ assert core.calls == [("get_authorization_status", "feishu")]
+
+
+async def test_get_authorization_status_rejects_unconfigured_host_without_core_call(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+) -> None:
+ host, core = fake_host
+
+ with pytest.raises(PersonalContext.Error) as caught:
+ await host.get_authorization_status("feishu")
+
+ assert caught.value.status.name == "CONTEXT_PROACTIVE_CONFIG_INVALID"
+ assert core.calls == []
+
+
+async def test_get_authorization_status_safely_converts_core_failure(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore], tmp_path: Path
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ core.calls.clear()
+ core.authorization_status_error = RuntimeError(
+ "token=top-secret https://example.invalid/auth?device_code=device-secret C:/private/user"
+ )
+
+ with pytest.raises(PersonalContext.Error) as caught:
+ await host.get_authorization_status("feishu")
+
+ assert caught.value.status.name == "CONTEXT_PROACTIVE_STATE_INVALID"
+ serialized = str(caught.value)
+ for secret in ("top-secret", "device-secret", "example.invalid", "C:/private/user"):
+ assert secret not in serialized
+ assert core.calls == [("get_authorization_status", "feishu")]
+
+
+async def test_get_authorization_status_uses_operation_lock_and_propagates_cancellation(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore], tmp_path: Path
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ core.calls.clear()
+
+ await host._operation_lock.acquire()
+ blocked = asyncio.create_task(host.get_authorization_status("feishu"))
+ try:
+ await asyncio.sleep(0)
+ assert core.calls == []
+ finally:
+ host._operation_lock.release()
+ assert (await asyncio.wait_for(blocked, timeout=1.0))["state"] == "authorized"
+
+ core.calls.clear()
+ core.authorization_status_started = asyncio.Event()
+ core.authorization_status_release = asyncio.Event()
+ cancelled = asyncio.create_task(host.get_authorization_status("feishu"))
+ try:
+ await asyncio.wait_for(core.authorization_status_started.wait(), timeout=1.0)
+ cancelled.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(cancelled, timeout=1.0)
+ finally:
+ core.authorization_status_release.set()
+ if not cancelled.done():
+ cancelled.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await asyncio.wait_for(cancelled, timeout=1.0)
+ assert cancelled.cancelled()
+ await asyncio.wait_for(host._operation_lock.acquire(), timeout=1.0)
+ host._operation_lock.release()
+
+
+async def test_get_graph_delegates_to_core(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+) -> None:
+ host, core = fake_host
+
+ result = await host.get_graph()
+
+ assert result == {"context_ready": True, "nodes": [], "edges": []}
+ assert core.calls == [("get_graph", None)]
+
+
+async def test_search_graph_delegates_to_core(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+) -> None:
+ host, core = fake_host
+
+ result = await host.search_graph("主动上下文")
+
+ assert result["results"][0]["node_id"] == "page:topics/personal_context.md"
+ assert core.calls == [("search_graph", "主动上下文")]
+
+
+async def test_get_graph_page_delegates_to_core(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+) -> None:
+ host, core = fake_host
+
+ result = await host.get_graph_page("page:topics/personal_context.md")
+
+ assert result["markdown"] == "# 主动上下文\n"
+ assert core.calls == [("get_graph_page", "page:topics/personal_context.md")]
+
+
+async def test_configure_same_semantics_only_replaces_yaml(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore], tmp_path: Path
+) -> None:
+ host, core = fake_host
+ config = _config(root_dir=tmp_path)
+ await host.configure(config)
+ core.snapshot_result = _FakeStatus()
+ core.calls.clear()
+ await host.configure(config)
+ assert [name for name, _ in core.calls] == ["snapshot"]
+
+
+async def test_configure_changed_semantics_stops_sets_and_restarts(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore], tmp_path: Path
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(root_dir=tmp_path, interval=60.0))
+ core.calls.clear()
+ await host.configure(_config(root_dir=tmp_path, interval=120.0))
+ assert [name for name, _ in core.calls] == [
+ "snapshot",
+ "deactivate_runtime",
+ "set_configuration",
+ "activate_runtime",
+ ]
+
+
+async def test_disabled_configuration_does_not_activate_or_delete_context(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore], tmp_path: Path
+) -> None:
+ host, core = fake_host
+ context = host._home / "workspace" / "context"
+ context.mkdir(parents=True)
+ description = context / "description.md"
+ description.write_text("keep", encoding="utf-8")
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ assert description.read_text(encoding="utf-8") == "keep"
+ assert [name for name, _ in core.calls] == ["set_configuration"]
+
+
+async def test_start_loads_existing_yaml_only_once(tmp_path: Path) -> None:
+ home = tmp_path / "personal_context"
+ home.mkdir()
+ config = _config(enabled=False, root_dir=tmp_path)
+ (home / "personal_context.yaml").write_text(
+ yaml.safe_dump(config, sort_keys=False), encoding="utf-8"
+ )
+ host = PersonalContextHostAPI(home=home)
+ await host.start()
+ assert host._config is not None
+ (home / "personal_context.yaml").write_text(
+ "not: a PersonalContext config", encoding="utf-8"
+ )
+ await host.start()
+ assert host._config is not None
+
+
+async def test_get_status_does_not_wait_for_operation_lock(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+) -> None:
+ host, core = fake_host
+ core.snapshot_result = "status"
+ await host._operation_lock.acquire()
+ try:
+ assert await asyncio.wait_for(host.get_status(), timeout=0.1) == "status"
+ finally:
+ host._operation_lock.release()
+
+
+async def test_get_overview_returns_full_config_including_credentials(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ config = _config(enabled=False, root_dir=tmp_path)
+ service = cast(list[dict[str, object]], config["fetch_services"])[0]
+ service["provider"] = "github"
+ service["source"] = {
+ "owner": "openjiuwen",
+ "repo": "agent-core",
+ "resources": ["readme", "issues", "pull_requests", "commits", "code"],
+ }
+ service["credentials"] = {"token": "plain-token"}
+ core.snapshot_result = _FakeStatus()
+
+ await host.configure(config)
+ overview = await host.get_overview()
+
+ assert overview["configured"] is True
+ assert overview["config"]["fetch_services"][0]["credentials"] == {
+ "token": "plain-token"
+ }
+ assert overview["status"] == {"state": "RUNNING", "configured": True}
+
+
+async def test_patch_runtime_configuration_changes_only_strategy_profile(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ host_module,
+ "get_default_models",
+ lambda: [
+ {
+ "model_client_config": {
+ "client_provider": "OpenAI",
+ "api_key": "key",
+ "api_base": "https://example.invalid/v1",
+ "model_name": "model-a",
+ },
+ "model_config_obj": {"temperature": 0.2},
+ }
+ ],
+ )
+ host, _core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ await host.select_model(model_index=0)
+ before = await host.get_runtime_config()
+
+ after = await host.patch_runtime_config({"strategy_profile": "balanced"})
+
+ assert after["strategy_profile"] == "balanced"
+ assert after["fetch_services"] == before["fetch_services"]
+ assert after["model_index"] == 0
+
+
+async def test_patch_runtime_configuration_rejects_unknown_field_without_writing(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, _core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ before = host._config_path.read_bytes()
+
+ with pytest.raises(PersonalContext.Error):
+ await host.patch_runtime_config({"enabled": True})
+
+ assert host._config_path.read_bytes() == before
+
+
+async def test_select_model_persists_only_model_index(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ host_module,
+ "get_default_models",
+ lambda: [
+ {
+ "model_client_config": {
+ "client_provider": "OpenAI",
+ "api_key": "key",
+ "api_base": "https://example.invalid/v1",
+ "model_name": "model-a",
+ },
+ "model_config_obj": {"temperature": 0.2},
+ }
+ ],
+ )
+ host, core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ core.calls.clear()
+
+ result = await host.select_model(model_index=0)
+
+ saved = yaml.safe_load(host._config_path.read_text(encoding="utf-8"))
+ applied = next(
+ value for name, value in reversed(core.calls) if name == "set_configuration"
+ )
+ assert result["model_index"] == 0
+ assert saved["model_index"] == 0
+ assert "model_origin_index" not in saved
+ assert "model_client" not in saved
+ assert "model_request" not in saved
+ assert applied.model_request.model_name == "model-a"
+
+
+async def test_configure_rejects_old_model_origin_index(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ host_module,
+ "get_default_models",
+ lambda: [
+ {
+ "model_client_config": {
+ "client_provider": "OpenAI",
+ "api_key": "key",
+ "api_base": "https://example.invalid/v1",
+ "model_name": "model-a",
+ },
+ "model_config_obj": {"temperature": 0.2},
+ }
+ ],
+ )
+ host, _core = fake_host
+ stored = _config(enabled=False, root_dir=tmp_path)
+ stored["model_origin_index"] = 0
+
+ with pytest.raises(PersonalContext.Error):
+ await host.configure(stored)
+
+ assert not host._config_path.exists()
+
+
+async def test_select_model_rejects_missing_model_without_writing(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(host_module, "get_default_models", lambda: [])
+ host, _core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ before = host._config_path.read_bytes()
+
+ with pytest.raises(PersonalContext.Error):
+ await host.select_model(model_index=0)
+
+ assert host._config_path.read_bytes() == before
+
+
+async def test_runtime_model_strategy_requires_selected_model_without_writing(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, _core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ before = host._config_path.read_bytes()
+
+ with pytest.raises(PersonalContext.Error):
+ await host.patch_runtime_config({"strategy_profile": "agent"})
+
+ assert host._config_path.read_bytes() == before
+
+
+async def test_start_rejects_saved_model_index_when_model_was_removed(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ home = tmp_path / "personal_context"
+ home.mkdir()
+ stored = _config(enabled=True, root_dir=tmp_path)
+ stored["strategy_profile"] = "balanced"
+ stored["model_index"] = 0
+ (home / "personal_context.yaml").write_text(
+ yaml.safe_dump(stored, sort_keys=False),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(host_module, "get_default_models", lambda: [])
+ host = PersonalContextHostAPI(home=home)
+
+ with pytest.raises(PersonalContext.Error):
+ await host.start()
+
+ assert host._config is None
+ assert host._stored_config is None
+
+
+async def test_set_runtime_enabled_persists_and_applies_switch(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ core.snapshot_result = _FakeStatus()
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ core.calls.clear()
+
+ started = await host.set_runtime_enabled(True)
+ stopped = await host.set_runtime_enabled(False)
+
+ assert started["enabled"] is True
+ assert stopped["enabled"] is False
+ saved = yaml.safe_load(host._config_path.read_text(encoding="utf-8"))
+ assert saved["enabled"] is False
+ assert [name for name, _ in core.calls].count("activate_runtime") == 1
+
+
+async def test_same_enabled_candidate_restarts_stopped_runtime_before_yaml_publish(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=True, root_dir=tmp_path))
+ await host.stop()
+ core.snapshot_result = SimpleNamespace(state="STOPPED")
+ core.calls.clear()
+ active_at_replace: list[bool] = []
+ original_replace = host_module._replace_yaml
+
+ def record_replace(temporary: Path, path: Path) -> None:
+ active_at_replace.append(core.active)
+ original_replace(temporary, path)
+
+ monkeypatch.setattr(host_module, "_replace_yaml", record_replace)
+
+ result = await host.set_runtime_enabled(True)
+
+ assert result["enabled"] is True
+ assert core.active is True
+ assert active_at_replace == [True]
+ assert [name for name, _ in core.calls] == [
+ "snapshot",
+ "deactivate_runtime",
+ "set_configuration",
+ "activate_runtime",
+ ]
+
+
+async def test_same_disabled_candidate_stops_unexpected_active_runtime_before_publish(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ core.active = True
+ core.snapshot_result = SimpleNamespace(state="RUNNING")
+ core.calls.clear()
+ active_at_replace: list[bool] = []
+ original_replace = host_module._replace_yaml
+
+ def record_replace(temporary: Path, path: Path) -> None:
+ active_at_replace.append(core.active)
+ original_replace(temporary, path)
+
+ monkeypatch.setattr(host_module, "_replace_yaml", record_replace)
+
+ result = await host.set_runtime_enabled(False)
+
+ assert result["enabled"] is False
+ assert core.active is False
+ assert active_at_replace == [False]
+ assert [name for name, _ in core.calls] == [
+ "snapshot",
+ "deactivate_runtime",
+ "set_configuration",
+ ]
+
+
+async def test_snapshot_failure_aborts_before_staging_or_runtime_changes(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=True, root_dir=tmp_path))
+ old_yaml = host._config_path.read_bytes()
+ old_config = host._config
+ old_stored = host._stored_config
+ core.calls.clear()
+ core.snapshot_error = RuntimeError("sensitive snapshot detail")
+ stage_calls: list[tuple[Path, bytes]] = []
+ original_stage = host_module._stage_yaml
+
+ def record_stage(path: Path, payload: bytes) -> Path:
+ stage_calls.append((path, payload))
+ return original_stage(path, payload)
+
+ monkeypatch.setattr(host_module, "_stage_yaml", record_stage)
+
+ with pytest.raises(PersonalContext.Error) as caught:
+ await host.set_runtime_enabled(False)
+
+ assert caught.value.status.name == "CONTEXT_PROACTIVE_STATE_INVALID"
+ assert "sensitive snapshot detail" not in str(caught.value)
+ assert core.calls == [("snapshot", None)]
+ assert core.active is True
+ assert stage_calls == []
+ assert host._config is old_config
+ assert host._stored_config is old_stored
+ assert host._config_path.read_bytes() == old_yaml
+ assert list(host._home.glob(".*.tmp")) == []
+
+
+async def test_disable_publishes_false_before_waiting_for_core_stop(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=True, root_dir=tmp_path))
+ core.snapshot_result = _FakeStatus()
+ core.deactivate_started = asyncio.Event()
+ core.deactivate_release = asyncio.Event()
+
+ task = asyncio.create_task(host.set_runtime_enabled(False))
+ try:
+ await asyncio.wait_for(core.deactivate_started.wait(), timeout=1.0)
+ saved_while_waiting = yaml.safe_load(
+ host._config_path.read_text(encoding="utf-8")
+ )
+ assert saved_while_waiting["enabled"] is False
+ assert host._stored_config is not None
+ assert host._stored_config["enabled"] is True
+
+ core.deactivate_release.set()
+ stopped = await task
+ finally:
+ core.deactivate_release.set()
+ if not task.done():
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await task
+ assert stopped["enabled"] is False
+ assert core.active is False
+
+
+async def test_disable_failure_restores_enabled_yaml_memory_and_runtime(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=True, root_dir=tmp_path))
+ core.snapshot_result = _FakeStatus()
+ old_yaml = host._config_path.read_bytes()
+ old_config = host._config
+ old_stored = deepcopy(host._stored_config)
+ core.calls.clear()
+ core.set_error = RuntimeError("disabled configuration failed")
+
+ with pytest.raises(PersonalContext.Error):
+ await host.set_runtime_enabled(False)
+
+ assert host._config == old_config
+ assert host._stored_config == old_stored
+ assert host._config_path.read_bytes() == old_yaml
+ assert yaml.safe_load(old_yaml)["enabled"] is True
+ assert core.active is True
+ assert list(host._home.glob(".*.tmp")) == []
+
+
+async def test_disable_cancellation_restores_enabled_yaml_memory_and_runtime(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=True, root_dir=tmp_path))
+ core.snapshot_result = _FakeStatus()
+ old_yaml = host._config_path.read_bytes()
+ old_config = host._config
+ old_stored = deepcopy(host._stored_config)
+ core.calls.clear()
+ core.deactivate_started = asyncio.Event()
+ core.deactivate_release = asyncio.Event()
+
+ task = asyncio.create_task(host.set_runtime_enabled(False))
+ try:
+ await asyncio.wait_for(core.deactivate_started.wait(), timeout=1.0)
+ assert (
+ yaml.safe_load(host._config_path.read_text(encoding="utf-8"))["enabled"]
+ is False
+ )
+ task.cancel()
+ core.deactivate_release.set()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ finally:
+ core.deactivate_release.set()
+ if not task.done():
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await task
+
+ assert task.cancelled()
+ assert host._config == old_config
+ assert host._stored_config == old_stored
+ assert host._config_path.read_bytes() == old_yaml
+ assert core.active is True
+ assert list(host._home.glob(".*.tmp")) == []
+
+
+async def test_runtime_start_failure_rolls_back_file_and_memory(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ core.snapshot_result = _FakeStatus()
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ old_yaml = host._config_path.read_bytes()
+ old_config = host._config
+ old_stored = host._stored_config
+ core.activate_error = RuntimeError("start failed")
+
+ with pytest.raises(PersonalContext.Error):
+ await host.set_runtime_enabled(True)
+
+ assert host._config == old_config
+ assert host._stored_config == old_stored
+ assert host._config_path.read_bytes() == old_yaml
+
+
+async def test_runtime_operations_reject_unconfigured_host(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+) -> None:
+ host, _core = fake_host
+
+ with pytest.raises(PersonalContext.Error):
+ await host.patch_runtime_config({"strategy_profile": "rules"})
+ with pytest.raises(PersonalContext.Error):
+ await host.select_model(0)
+
+
+async def test_list_fetch_services_combines_config_state_and_error(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ core.snapshot_result = SimpleNamespace(
+ fetch_service_states={"local-notes": "RUNNING"},
+ fetch_service_errors={"local-notes": "last failure"},
+ )
+
+ services = await host.list_fetch_services()
+
+ assert services == [
+ {
+ "service_id": "local-notes",
+ "provider": "local_files",
+ "enabled": True,
+ "interval_seconds": 60.0,
+ "max_items_per_run": None,
+ "source": {"root_dir": str(tmp_path)},
+ "credentials": {},
+ "state": "RUNNING",
+ "last_error": "last failure",
+ }
+ ]
+
+
+async def test_create_fetch_service_normalizes_and_publishes_yaml_immediately(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, _core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+
+ created = await host.create_fetch_service(
+ {
+ **_local_service(" local-created ", tmp_path),
+ "provider": " LOCAL_FILES ",
+ }
+ )
+
+ assert created["service_id"] == "local-created"
+ assert created["provider"] == "local_files"
+ saved = yaml.safe_load(host._config_path.read_text(encoding="utf-8"))
+ assert [service["service_id"] for service in saved["fetch_services"]] == [
+ "local-created",
+ "local-notes",
+ ]
+
+
+async def test_create_fetch_service_rejects_duplicate_and_unknown_provider(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, _core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ before = host._config_path.read_bytes()
+
+ with pytest.raises(PersonalContext.Error, match="already exists"):
+ await host.create_fetch_service(_local_service("local-notes", tmp_path))
+ unknown = _local_service("unknown-provider", tmp_path)
+ unknown["provider"] = "unknown"
+ with pytest.raises(PersonalContext.Error):
+ await host.create_fetch_service(unknown)
+
+ assert host._config_path.read_bytes() == before
+
+
+async def test_create_fetch_service_enforces_provider_limit_independently(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, _core = fake_host
+ services = [_local_service(f"local-{index:02d}", tmp_path) for index in range(20)]
+ await host.configure(_config_with_services(services))
+ before = host._config_path.read_bytes()
+
+ with pytest.raises(
+ PersonalContext.Error,
+ match="local_files fetch service limit of 20 has been reached",
+ ):
+ await host.create_fetch_service(_local_service("local-20", tmp_path))
+
+ assert host._config_path.read_bytes() == before
+ created = await host.create_fetch_service(_bookmark_service("bookmarks-00"))
+ assert created["provider"] == "browser_bookmarks"
+
+
+async def test_host_configure_cannot_bypass_per_provider_limit(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ services = [_local_service(f"local-{index:02d}", tmp_path) for index in range(21)]
+
+ with pytest.raises(PersonalContext.Error):
+ await host.configure(_config_with_services(services))
+
+ assert core.calls == []
+ assert host._config is None
+ assert host._stored_config is None
+ assert not host._config_path.exists()
+
+
+async def test_create_fetch_service_apply_failure_restores_yaml_memory_and_core(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ old_yaml = host._config_path.read_bytes()
+ old_config = host._config
+ old_stored = deepcopy(host._stored_config)
+ core.set_error = RuntimeError("candidate set failed")
+
+ with pytest.raises(PersonalContext.Error):
+ await host.create_fetch_service(_bookmark_service("bookmarks-00"))
+
+ assert host._config is old_config
+ assert host._stored_config == old_stored
+ assert core.configured == old_config
+ assert host._config_path.read_bytes() == old_yaml
+
+
+async def test_create_fetch_service_cancellation_restores_yaml_memory_and_core(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ old_yaml = host._config_path.read_bytes()
+ old_config = host._config
+ old_stored = deepcopy(host._stored_config)
+ core.set_error = asyncio.CancelledError()
+
+ task = asyncio.create_task(
+ host.create_fetch_service(_bookmark_service("bookmarks-00"))
+ )
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ assert task.cancelled()
+ assert host._config is old_config
+ assert host._stored_config == old_stored
+ assert core.configured == old_config
+ assert host._config_path.read_bytes() == old_yaml
+
+
+async def test_delete_fetch_service_rejects_missing_service_without_changes(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ before = host._config_path.read_bytes()
+ core.calls.clear()
+
+ with pytest.raises(
+ PersonalContext.Error, match="unknown PersonalContext fetch service"
+ ):
+ await host.delete_fetch_service("missing")
+
+ assert host._config_path.read_bytes() == before
+ assert core.calls == []
+
+
[email protected]("state", ["STARTING", "RUNNING", "STOPPING", "FAILED", None])
+async def test_delete_fetch_service_rejects_service_until_explicitly_stopped(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+ state: str | None,
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ before = host._config_path.read_bytes()
+ old_config = host._config
+ old_stored = deepcopy(host._stored_config)
+ old_core_config = core.configured
+ core.cursor_payloads["local-notes"] = b"old-cursor"
+ core.snapshot_result = SimpleNamespace(
+ state="CONFIGURED",
+ fetch_service_states={"local-notes": state} if state is not None else {},
+ )
+ core.calls.clear()
+
+ with pytest.raises(PersonalContext.Error, match="正在执行|请先停止"):
+ await host.delete_fetch_service("local-notes")
+
+ assert host._config_path.read_bytes() == before
+ assert host._config is old_config
+ assert host._stored_config == old_stored
+ assert core.configured is old_core_config
+ assert core.cursor_payloads["local-notes"] == b"old-cursor"
+ assert core.calls == [("snapshot", None)]
+
+
+async def test_delete_fetch_service_removes_config_cursor_and_preserves_context(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ context_page = host._home / "workspace" / "context" / "description.md"
+ source_meta = host._home / "workspace" / "source-meta" / "source.md"
+ context_page.parent.mkdir(parents=True)
+ source_meta.parent.mkdir(parents=True)
+ context_page.write_text("# retained context\n", encoding="utf-8")
+ source_meta.write_text("# retained source\n", encoding="utf-8")
+ core.cursor_payloads["local-notes"] = b"old-cursor"
+ core.snapshot_result = SimpleNamespace(
+ state="CONFIGURED",
+ fetch_service_states={"local-notes": "STOPPED"},
+ )
+ core.calls.clear()
+
+ await host.delete_fetch_service(" local-notes ")
+
+ saved = yaml.safe_load(host._config_path.read_text(encoding="utf-8"))
+ assert saved["fetch_services"] == []
+ assert host._stored_config is not None
+ assert host._stored_config["fetch_services"] == []
+ assert "local-notes" not in core.cursor_payloads
+ assert context_page.read_text(encoding="utf-8") == "# retained context\n"
+ assert source_meta.read_text(encoding="utf-8") == "# retained source\n"
+ assert [name for name, _value in core.calls].count("snapshot") == 1
+ assert [name for name, _value in core.calls].count("remove_fetch_cursor") == 1
+ assert [name for name, _value in core.calls].count("restore_fetch_cursor") == 0
+
+
+async def test_delete_fetch_service_releases_provider_slot_and_recreation_has_no_cursor(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ services = [_local_service(f"local-{index:02d}", tmp_path) for index in range(20)]
+ await host.configure(_config_with_services(services))
+ core.cursor_payloads["local-00"] = b"old-cursor"
+ core.snapshot_result = SimpleNamespace(
+ state="CONFIGURED",
+ fetch_service_states={service["service_id"]: "STOPPED" for service in services},
+ )
+
+ await host.delete_fetch_service("local-00")
+ recreated = await host.create_fetch_service(_local_service("local-00", tmp_path))
+
+ assert recreated["service_id"] == "local-00"
+ assert "local-00" not in core.cursor_payloads
+ assert not any(name == "restore_fetch_cursor" for name, _value in core.calls)
+
+
+async def test_delete_fetch_service_cursor_remove_failure_keeps_configuration(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ old_config = host._config
+ old_stored = deepcopy(host._stored_config)
+ old_yaml = host._config_path.read_bytes()
+ core.snapshot_result = SimpleNamespace(
+ state="CONFIGURED",
+ fetch_service_states={"local-notes": "STOPPED"},
+ )
+ core.remove_cursor_error = RuntimeError("sensitive cursor remove failure")
+
+ with pytest.raises(PersonalContext.Error) as caught:
+ await host.delete_fetch_service("local-notes")
+
+ assert "sensitive cursor remove failure" not in str(caught.value)
+ assert host._config is old_config
+ assert host._stored_config == old_stored
+ assert host._config_path.read_bytes() == old_yaml
+
+
+async def test_delete_fetch_service_apply_failure_restores_cursor_and_config(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ old_config = host._config
+ old_stored = deepcopy(host._stored_config)
+ old_yaml = host._config_path.read_bytes()
+ core.cursor_payloads["local-notes"] = b"old-cursor"
+ core.snapshot_result = SimpleNamespace(
+ state="CONFIGURED",
+ fetch_service_states={"local-notes": "STOPPED"},
+ )
+ core.set_error = RuntimeError("candidate set failure")
+
+ with pytest.raises(PersonalContext.Error):
+ await host.delete_fetch_service("local-notes")
+
+ assert core.cursor_payloads["local-notes"] == b"old-cursor"
+ assert host._config is old_config
+ assert host._stored_config == old_stored
+ assert host._config_path.read_bytes() == old_yaml
+
+
+async def test_delete_fetch_service_cancellation_restores_cursor_and_propagates(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ old_config = host._config
+ old_stored = deepcopy(host._stored_config)
+ old_yaml = host._config_path.read_bytes()
+ core.cursor_payloads["local-notes"] = b"old-cursor"
+ core.snapshot_result = SimpleNamespace(
+ state="CONFIGURED",
+ fetch_service_states={"local-notes": "STOPPED"},
+ )
+ core.set_error = asyncio.CancelledError()
+
+ task = asyncio.create_task(host.delete_fetch_service("local-notes"))
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ assert task.cancelled()
+ assert core.cursor_payloads["local-notes"] == b"old-cursor"
+ assert host._config is old_config
+ assert host._stored_config == old_stored
+ assert host._config_path.read_bytes() == old_yaml
+
+
+async def test_delete_fetch_service_cancellation_wins_when_cursor_restore_fails(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=True, root_dir=tmp_path))
+ old_config = host._config
+ old_stored = deepcopy(host._stored_config)
+ old_yaml = host._config_path.read_bytes()
+ core.cursor_payloads["local-notes"] = b"old-cursor"
+ core.snapshot_result = SimpleNamespace(
+ state="RUNNING",
+ fetch_service_states={"local-notes": "STOPPED"},
+ )
+ core.deactivate_started = asyncio.Event()
+ core.deactivate_release = asyncio.Event()
+ core.restore_cursor_error = RuntimeError("sensitive cursor restore failure")
+
+ task = asyncio.create_task(host.delete_fetch_service("local-notes"))
+ try:
+ await asyncio.wait_for(core.deactivate_started.wait(), timeout=1.0)
+ task.cancel()
+ core.deactivate_release.set()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ finally:
+ core.deactivate_release.set()
+ if not task.done():
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError, PersonalContext.Error):
+ await task
+
+ assert task.cancelled()
+ assert "local-notes" not in core.cursor_payloads
+ assert host._config is old_config
+ assert host._stored_config == old_stored
+ assert host._config_path.read_bytes() == old_yaml
+
+
+async def test_delete_fetch_service_restore_failure_is_reported_explicitly(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ old_yaml = host._config_path.read_bytes()
+ core.cursor_payloads["local-notes"] = b"old-cursor"
+ core.snapshot_result = SimpleNamespace(
+ state="CONFIGURED",
+ fetch_service_states={"local-notes": "STOPPED"},
+ )
+ core.set_error = RuntimeError("candidate set failure")
+ core.restore_cursor_error = RuntimeError("sensitive cursor restore failure")
+
+ with pytest.raises(
+ PersonalContext.Error,
+ match="fetch cursor could not be restored",
+ ) as caught:
+ await host.delete_fetch_service("local-notes")
+
+ assert "sensitive cursor restore failure" not in str(caught.value)
+ assert "local-notes" not in core.cursor_payloads
+ assert host._config_path.read_bytes() == old_yaml
+
+
+async def test_patch_existing_fetch_service_without_changing_identity(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, _core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+
+ result = await host.patch_fetch_service(
+ "local-notes",
+ {"interval_seconds": 10_800.0, "max_items_per_run": 50},
+ )
+
+ assert result["service_id"] == "local-notes"
+ assert result["provider"] == "local_files"
+ assert result["enabled"] is True
+ assert result["interval_seconds"] == 10_800.0
+ assert result["max_items_per_run"] == 50
+
+
[email protected]("field", ["service_id", "provider", "enabled"])
+async def test_patch_fetch_service_rejects_identity_and_switch_fields(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+ field: str,
+) -> None:
+ host, _core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ before = host._config_path.read_bytes()
+
+ with pytest.raises(PersonalContext.Error):
+ await host.patch_fetch_service("local-notes", {field: "changed"})
+
+ assert host._config_path.read_bytes() == before
+
+
+async def test_patch_fetch_service_never_creates_missing_service(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, _core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ before = host._config_path.read_bytes()
+
+ with pytest.raises(
+ PersonalContext.Error, match="unknown PersonalContext fetch service"
+ ):
+ await host.patch_fetch_service(
+ "new-service",
+ {"interval_seconds": 10_800.0},
+ )
+
+ assert host._config_path.read_bytes() == before
+
+
+async def test_get_fetch_run_status_returns_all_or_one_service(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ core.snapshot_result = SimpleNamespace(
+ fetch_service_states={"local-notes": "RUNNING"},
+ fetch_service_errors={},
+ )
+
+ all_status = await host.get_fetch_run_status()
+ one_status = await host.get_fetch_run_status("local-notes")
+
+ assert all_status == {
+ "services": [
+ {
+ "service_id": "local-notes",
+ "state": "RUNNING",
+ "last_error": None,
+ }
+ ]
+ }
+ assert one_status == {
+ "service_id": "local-notes",
+ "state": "RUNNING",
+ "last_error": None,
+ }
+
+
+async def test_set_fetching_updates_global_switch_through_full_restart(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ core.snapshot_result = _FakeStatus()
+ await host.configure(_config(root_dir=tmp_path))
+ core.calls.clear()
+
+ await host.set_fetching(enabled=False)
+
+ assert host._config.fetching_enabled is False
+ saved = yaml.safe_load(
+ (host._home / "personal_context.yaml").read_text(encoding="utf-8")
+ )
+ assert saved["fetching_enabled"] is False
+ assert [name for name, _ in core.calls] == [
+ "snapshot",
+ "deactivate_runtime",
+ "set_configuration",
+ "activate_runtime",
+ ]
+
+
+async def test_set_fetching_updates_only_named_service(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ core.snapshot_result = _FakeStatus()
+ await host.configure(_config(root_dir=tmp_path))
+
+ await host.set_fetching(enabled=False, service_id="local-notes")
+
+ assert host._config.fetching_enabled is True
+ assert host._config.fetch_services[0].enabled is False
+
+
+async def test_set_fetching_rejects_unconfigured_or_unknown_service(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+) -> None:
+ host, _core = fake_host
+ with pytest.raises(PersonalContext.Error):
+ await host.set_fetching(enabled=False)
+ with pytest.raises(PersonalContext.Error):
+ await host.set_fetching(enabled=False, service_id="missing")
+
+
+async def test_run_fetch_delegates_without_modifying_yaml(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ config_path = host._home / "personal_context.yaml"
+ saved = config_path.read_bytes()
+ configured = host._config
+ core.calls.clear()
+
+ result = await host.run_fetch(service_id="local-notes")
+
+ assert result == {
+ "state": "accepted",
+ "service_ids": ["local-notes"],
+ }
+ assert core.calls == [("run_fetch", "local-notes")]
+ assert host._config is configured
+ assert config_path.read_bytes() == saved
+
+
+async def test_run_fetch_is_serialized_with_configuration_operations(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ core.calls.clear()
+ await host._operation_lock.acquire()
+
+ task = asyncio.create_task(host.run_fetch())
+ await asyncio.sleep(0)
+ assert core.calls == []
+
+ host._operation_lock.release()
+ result = await task
+ assert result == {
+ "state": "accepted",
+ "service_ids": ["local-notes"],
+ }
+ assert core.calls == [("run_fetch", None)]
+
+
+async def test_stop_calls_core_and_preserves_configuration(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore], tmp_path: Path
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=True, root_dir=tmp_path))
+ saved = host._config_path.read_bytes()
+ core.calls.clear()
+ await host.stop(timeout_seconds=1.5)
+ assert core.calls == [("deactivate_runtime", 1.5)]
+ assert host._config is not None
+ assert host._config_path.read_bytes() == saved
+ assert yaml.safe_load(saved)["enabled"] is True
+
+
+async def test_start_rejects_oversized_yaml_before_parsing_or_changing_core(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ host, core = fake_host
+ host._home.mkdir(parents=True)
+ oversized = b"#" + b"x" * (4 * 1024 * 1024)
+ host._config_path.write_bytes(oversized)
+ parse_calls = 0
+
+ def record_parse(_text: str) -> object:
+ nonlocal parse_calls
+ parse_calls += 1
+ return {}
+
+ monkeypatch.setattr(host_module.yaml, "safe_load", record_parse)
+
+ with pytest.raises(PersonalContext.Error):
+ await host.start()
+
+ assert core.calls == []
+ assert host._config is None
+ assert host._stored_config is None
+ assert host._config_path.read_bytes() == oversized
+ assert parse_calls == 0
+
+
+async def test_start_bounds_read_when_opened_yaml_grows_after_path_checks(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ host, core = fake_host
+ host._home.mkdir(parents=True)
+ host._config_path.write_text("enabled: false\n", encoding="utf-8")
+ read_sizes: list[int] = []
+ parse_calls = 0
+ original_open = Path.open
+
+ class GrowingHandle:
+ def __init__(self, raw: BinaryIO) -> None:
+ self._raw = raw
+
+ def __enter__(self) -> GrowingHandle:
+ self._raw.__enter__()
+ return self
+
+ def __exit__(
+ self,
+ exc_type: object,
+ exc_value: object,
+ traceback: object,
+ ) -> object:
+ return self._raw.__exit__(exc_type, exc_value, traceback)
+
+ def fileno(self) -> int:
+ return self._raw.fileno()
+
+ def read(self, size: int = -1) -> bytes:
+ read_sizes.append(size)
+ return b"x" * (host_module._MAX_CONFIG_BYTES + 1)
+
+ def growing_open(target: Path, *args: object, **kwargs: object) -> object:
+ raw = original_open(target, *args, **kwargs)
+ mode = kwargs.get("mode", args[0] if args else "r")
+ if target == host._config_path and mode == "rb":
+ return GrowingHandle(cast(BinaryIO, raw))
+ return raw
+
+ def record_parse(_text: str) -> object:
+ nonlocal parse_calls
+ parse_calls += 1
+ return {}
+
+ monkeypatch.setattr(Path, "open", growing_open)
+ monkeypatch.setattr(host_module.yaml, "safe_load", record_parse)
+
+ with pytest.raises(PersonalContext.Error):
+ await host.start()
+
+ assert read_sizes == [host_module._MAX_CONFIG_BYTES + 1]
+ assert parse_calls == 0
+ assert core.calls == []
+
+
+async def test_oversized_serialized_candidate_is_rejected_before_file_or_runtime(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ host, core = fake_host
+ oversized_text = "x" * (4 * 1024 * 1024 + 1)
+ monkeypatch.setattr(
+ host_module.yaml,
+ "safe_dump",
+ lambda *_args, **_kwargs: oversized_text,
+ )
+
+ with pytest.raises(PersonalContext.Error):
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+
+ assert core.calls == []
+ assert not host._home.exists()
+ assert host._config is None
+ assert host._stored_config is None
+
+
+async def test_missing_staged_yaml_is_reported_as_host_error(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ host, core = fake_host
+ monkeypatch.setattr(host_module, "_stage_yaml", lambda *_args: None)
+
+ with pytest.raises(PersonalContext.Error) as caught:
+ await host.set_runtime_enabled(True)
+
+ assert "staging" in str(caught.value).lower()
+ assert core.active is False
+ assert host._config is None
+ assert not (host._home / "personal_context.yaml").exists()
+
+
+async def test_temporary_yaml_write_failure_does_not_call_core(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ host, core = fake_host
+
+ def fail_temporary(*_args: object, **_kwargs: object) -> None:
+ raise OSError("temporary write failed")
+
+ monkeypatch.setattr(
+ "jiuwenswarm.server.personal_context.host_api.tempfile.NamedTemporaryFile",
+ fail_temporary,
+ )
+ with pytest.raises(Exception) as caught:
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ assert core.calls == []
+ assert caught.value.status.name == "CONTEXT_PROACTIVE_FILE_EXECUTION_ERROR"
+ assert not (host._home / "personal_context.yaml").exists()
+
+
+async def test_previous_stop_failure_preserves_old_configuration(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore], tmp_path: Path
+) -> None:
+ host, core = fake_host
+ old_config = _config(enabled=True, root_dir=tmp_path)
+ await host.configure(old_config)
+ old_core_config = host._config
+ old_stored_config = host._stored_config
+ old_yaml = (host._home / "personal_context.yaml").read_bytes()
+ core.calls.clear()
+ core.snapshot_result = SimpleNamespace(state="RUNNING")
+ core.deactivate_error = RuntimeError("stop failed")
+ with pytest.raises(Exception) as caught:
+ await host.configure(_config(enabled=True, root_dir=tmp_path, interval=120.0))
+ assert [name for name, _ in core.calls] == [
+ "snapshot",
+ "deactivate_runtime",
+ "deactivate_runtime",
+ "set_configuration",
+ "activate_runtime",
+ ]
+ assert core.active is True
+ assert host._config == old_core_config
+ assert host._stored_config == old_stored_config
+ assert (host._home / "personal_context.yaml").read_bytes() == old_yaml
+ assert caught.value.status.name == "CONTEXT_PROACTIVE_STATE_INVALID"
+
+
+async def test_partial_previous_stop_failure_restores_active_runtime(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore], tmp_path: Path
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=True, root_dir=tmp_path))
+ old_config = host._config
+ old_stored = host._stored_config
+ old_yaml = host._config_path.read_bytes()
+ core.calls.clear()
+ core.snapshot_result = SimpleNamespace(state="RUNNING")
+ core.deactivate_changes_active_before_error = True
+ core.deactivate_error = RuntimeError("stop failed after state change")
+
+ with pytest.raises(PersonalContext.Error):
+ await host.configure(_config(enabled=True, root_dir=tmp_path, interval=120.0))
+
+ assert [name for name, _ in core.calls] == [
+ "snapshot",
+ "deactivate_runtime",
+ "deactivate_runtime",
+ "set_configuration",
+ "activate_runtime",
+ ]
+ assert core.active is True
+ assert host._config is old_config
+ assert host._stored_config == old_stored
+ assert host._config_path.read_bytes() == old_yaml
+
+
+async def test_partial_previous_stop_cancellation_restores_before_propagating(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore], tmp_path: Path
+) -> None:
+ host, core = fake_host
+ await host.configure(_config(enabled=True, root_dir=tmp_path))
+ old_config = host._config
+ old_stored = host._stored_config
+ old_yaml = host._config_path.read_bytes()
+ core.calls.clear()
+ core.snapshot_result = SimpleNamespace(state="RUNNING")
+ core.deactivate_changes_active_before_error = True
+ core.deactivate_error = asyncio.CancelledError()
+
+ task = asyncio.create_task(
+ host.configure(_config(enabled=True, root_dir=tmp_path, interval=120.0))
+ )
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ assert task.cancelled()
+ assert [name for name, _ in core.calls] == [
+ "snapshot",
+ "deactivate_runtime",
+ "deactivate_runtime",
+ "set_configuration",
+ "activate_runtime",
+ ]
+ assert core.active is True
+ assert host._config is old_config
+ assert host._stored_config == old_stored
+ assert host._config_path.read_bytes() == old_yaml
+
+
+async def test_set_failure_restores_old_configuration_and_active_runtime(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore], tmp_path: Path
+) -> None:
+ host, core = fake_host
+ old_config = _config(enabled=True, root_dir=tmp_path)
+ await host.configure(old_config)
+ old_core_config = host._config
+ old_stored_config = host._stored_config
+ old_yaml = (host._home / "personal_context.yaml").read_bytes()
+ core.calls.clear()
+ core.snapshot_result = SimpleNamespace(state="RUNNING")
+ core.set_error = RuntimeError("set failed")
+ with pytest.raises(Exception) as caught:
+ await host.configure(_config(enabled=True, root_dir=tmp_path, interval=120.0))
+ assert [name for name, _ in core.calls] == [
+ "snapshot",
+ "deactivate_runtime",
+ "set_configuration",
+ "deactivate_runtime",
+ "set_configuration",
+ "activate_runtime",
+ ]
+ assert host._config == old_core_config
+ assert host._stored_config == old_stored_config
+ assert (host._home / "personal_context.yaml").read_bytes() == old_yaml
+ assert caught.value.status.name == "CONTEXT_PROACTIVE_CONFIG_INVALID"
+
+
+async def test_replace_failure_restores_old_configuration_and_active_runtime(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ host, core = fake_host
+ old_config = _config(enabled=True, root_dir=tmp_path)
+ await host.configure(old_config)
+ old_core_config = host._config
+ old_stored_config = host._stored_config
+ old_yaml = (host._home / "personal_context.yaml").read_bytes()
+ core.calls.clear()
+ core.snapshot_result = SimpleNamespace(state="RUNNING")
+
+ def fail_replace(_source: object, _target: object) -> None:
+ raise OSError("replace failed")
+
+ monkeypatch.setattr(
+ "jiuwenswarm.server.personal_context.host_api.os.replace", fail_replace
+ )
+ with pytest.raises(Exception) as caught:
+ await host.configure(_config(enabled=True, root_dir=tmp_path, interval=120.0))
+ assert [name for name, _ in core.calls] == [
+ "snapshot",
+ "deactivate_runtime",
+ "set_configuration",
+ "activate_runtime",
+ "deactivate_runtime",
+ "set_configuration",
+ "activate_runtime",
+ ]
+ assert host._config == old_core_config
+ assert host._stored_config == old_stored_config
+ assert (host._home / "personal_context.yaml").read_bytes() == old_yaml
+ assert caught.value.status.name == "CONTEXT_PROACTIVE_FILE_EXECUTION_ERROR"
+
+
+async def test_new_start_failure_keeps_host_unconfigured(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore], tmp_path: Path
+) -> None:
+ host, core = fake_host
+ core.activate_error = RuntimeError("start failed")
+ with pytest.raises(Exception) as caught:
+ await host.configure(_config(root_dir=tmp_path))
+ assert host._config is None
+ assert host._stored_config is None
+ assert not (host._home / "personal_context.yaml").exists()
+ assert caught.value.status.name == "CONTEXT_PROACTIVE_STATE_INVALID"
+
+
+async def test_stop_rejects_non_positive_timeout_without_calling_core(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+) -> None:
+ host, core = fake_host
+ with pytest.raises(Exception) as caught:
+ await host.stop(timeout_seconds=0)
+ assert core.calls == []
+ assert caught.value.status.name == "CONTEXT_PROACTIVE_RUNTIME_TIMEOUT"
+
+
+async def test_concurrent_operations_are_serialized(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore], tmp_path: Path
+) -> None:
+ host, core = fake_host
+ started = asyncio.Event()
+ release = asyncio.Event()
+ core.deactivate_started = started
+ core.deactivate_release = release
+ await host.configure(_config(enabled=False, root_dir=tmp_path))
+ task = asyncio.create_task(host.stop())
+ configure_task: asyncio.Task[None] | None = None
+ try:
+ await asyncio.wait_for(started.wait(), timeout=1.0)
+ configure_task = asyncio.create_task(
+ host.configure(_config(enabled=False, root_dir=tmp_path, interval=120.0))
+ )
+ await asyncio.sleep(0)
+ assert not configure_task.done()
+ release.set()
+ await task
+ await configure_task
+ finally:
+ release.set()
+ pending = [task]
+ if configure_task is not None:
+ pending.append(configure_task)
+ for pending_task in pending:
+ if not pending_task.done():
+ pending_task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await pending_task
+ assert [name for name, _ in core.calls].count("deactivate_runtime") == 2
diff --git a/tests/unit_tests/personal_context/test_host_graph.py b/tests/unit_tests/personal_context/test_host_graph.py
new file mode 100644
index 0000000000..81fc40fe02
--- /dev/null
+++ b/tests/unit_tests/personal_context/test_host_graph.py
@@ -0,0 +1,108 @@
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+import pytest
+
+from openjiuwen.harness.personal_context.models import RawChangeItem
+from openjiuwen.harness.personal_context.source_metadata import upsert_source_metadata
+
+from jiuwenswarm.server.personal_context.host_api import PersonalContextHostAPI
+
+
+def _write_source(home: Path) -> tuple[str, Path]:
+ source_root = home / "workspace" / "source-meta"
+ source_id = upsert_source_metadata(
+ source_root,
+ RawChangeItem(
+ logical_id="github:pull:42",
+ revision_id="revision-1",
+ operation="upsert",
+ title="GitHub PR 42",
+ content="source body must not be persisted",
+ original_ref="https://github.com/openjiuwen/agent-core/pull/42",
+ metadata={"resource": "pull_request"},
+ ),
+ provider="github",
+ service_id="github-main",
+ observed_at="2026-08-12T00:00:00Z",
+ )
+ return source_id, source_root / f"{source_id}.md"
+
+
+def _link(page: Path, target: Path) -> str:
+ relative = os.path.relpath(target, start=page.parent).replace("\\", "/")
+ return f"[PR 42]({relative})"
+
+
+async def test_graph_is_empty_without_root_description(tmp_path: Path) -> None:
+ host = PersonalContextHostAPI(home=tmp_path / "personal_context")
+ assert await host.get_graph() == {
+ "context_ready": False,
+ "nodes": [],
+ "edges": [],
+ }
+
+
+async def test_host_returns_atomic_source_graph_without_rebuilding_fields(
+ tmp_path: Path,
+) -> None:
+ home = tmp_path / "personal_context"
+ context = home / "workspace" / "context"
+ page = context / "topics" / "agent.md"
+ page.parent.mkdir(parents=True)
+ source_id, source_path = _write_source(home)
+ (context / "description.md").write_text(
+ "# Context\n\n- [Topics](topics/description.md)\n",
+ encoding="utf-8",
+ )
+ (context / "topics" / "description.md").write_text(
+ "# Topics\n\n- [Agent](agent.md)\n",
+ encoding="utf-8",
+ )
+ page.write_text(
+ "# Agent\n\nSee [root](../description.md) and "
+ + _link(page, source_path)
+ + ".\n",
+ encoding="utf-8",
+ )
+
+ graph = await PersonalContextHostAPI(home=home).get_graph()
+
+ assert graph["context_ready"] is True
+ assert {node["id"]: (node["kind"], node["subkind"]) for node in graph["nodes"]} == {
+ "page:description.md": ("directory", "directory.0"),
+ "page:topics/description.md": ("directory", "directory.1"),
+ "page:topics/agent.md": ("document", "document.0"),
+ f"source:{source_id}": ("source", "source.0"),
+ }
+ assert {
+ (edge["source"], edge["target"], edge["kind"]) for edge in graph["edges"]
+ } >= {
+ ("page:description.md", "page:topics/description.md", "contains"),
+ ("page:topics/description.md", "page:topics/agent.md", "contains"),
+ ("page:description.md", "page:topics/description.md", "navigates_to"),
+ ("page:topics/agent.md", f"source:{source_id}", "links_to"),
+ }
+ assert all(edge["kind"] != "derived_from" for edge in graph["edges"])
+
+
+async def test_host_returns_source_metadata_through_shared_page_detail(
+ tmp_path: Path,
+) -> None:
+ home = tmp_path / "personal_context"
+ source_id, source_path = _write_source(home)
+ markdown = source_path.read_text(encoding="utf-8")
+
+ assert await PersonalContextHostAPI(home=home).get_graph_page(
+ f"source:{source_id}"
+ ) == {
+ "node_id": f"source:{source_id}",
+ "title": "GitHub PR 42",
+ "path": f"{source_id}.md",
+ "markdown": markdown,
+ }
diff --git a/tests/unit_tests/personal_context/test_host_rail_smoke.py b/tests/unit_tests/personal_context/test_host_rail_smoke.py
new file mode 100644
index 0000000000..5afbbacef8
--- /dev/null
+++ b/tests/unit_tests/personal_context/test_host_rail_smoke.py
@@ -0,0 +1,90 @@
+"""Minimal real Host/Core/Rail connection smoke test."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+import yaml
+
+from jiuwenswarm.server.personal_context.host_api import PersonalContextHostAPI
+from openjiuwen.core.foundation.llm import AssistantMessage
+from openjiuwen.core.single_agent.rail.base import AgentCallbackContext, ModelCallInputs
+from openjiuwen.harness.prompts import PromptAttachmentKind, PromptAttachmentManager
+from openjiuwen.harness.rails.personal_context import PersonalContextRail
+
+
+async def test_real_host_core_and_rail_connection(tmp_path: Path) -> None:
+ """A configured Host starts Core and the Rail reads the same fixed Context root."""
+
+ home = tmp_path / ".jiuwenswarm" / ".personal_context"
+ source_root = tmp_path / "source"
+ source_root.mkdir()
+ context_root = home / "workspace" / "context"
+ context_root.mkdir(parents=True)
+ (context_root / "description.md").write_text("smoke context", encoding="utf-8")
+
+ host = PersonalContextHostAPI(home=home)
+ config = {
+ "enabled": True,
+ "fetching_enabled": True,
+ "strategy_profile": "rules",
+ "fetch_services": [
+ {
+ "service_id": "smoke-local",
+ "provider": "local_files",
+ "enabled": False,
+ "source": {"root_dir": str(source_root)},
+ "credentials": {},
+ }
+ ],
+ }
+
+ await host.configure(config)
+ try:
+ saved = yaml.safe_load(
+ (home / "personal_context.yaml").read_text(encoding="utf-8")
+ )
+ assert saved["fetch_services"][0]["interval_seconds"] == 10_800.0
+
+ status = await host.get_status()
+ assert status.configured is True
+ assert status.state == "RUNNING"
+ assert status.pipeline_running is True
+
+ manager = PromptAttachmentManager()
+ agent = SimpleNamespace(prompt_attachment_manager=manager)
+ rail = PersonalContextRail(home)
+ rail.init(agent)
+ ctx = AgentCallbackContext(
+ agent=agent,
+ inputs=ModelCallInputs(messages=[AssistantMessage(content="hello")]),
+ session=SimpleNamespace(session_id="smoke-session"),
+ )
+
+ await rail.before_model_call(ctx)
+ attachments = await manager.collect_for_session("smoke-session")
+ assert len(attachments) == 1
+ assert attachments[0].section == "personal_context"
+ assert attachments[0].kind == PromptAttachmentKind.RUNTIME
+ assert "smoke context" in (attachments[0].content or "")
+ await rail.after_model_call(ctx)
+ assert await manager.collect_for_session("smoke-session") == []
+
+ await host.set_runtime_enabled(False)
+ await rail.before_model_call(ctx)
+ assert await manager.collect_for_session("smoke-session") == []
+
+ await host.set_runtime_enabled(True)
+ await rail.before_model_call(ctx)
+ attachments = await manager.collect_for_session("smoke-session")
+ assert len(attachments) == 1
+ assert "smoke context" in (attachments[0].content or "")
+ await rail.after_model_call(ctx)
+ assert await manager.collect_for_session("smoke-session") == []
+ finally:
+ await host.stop(timeout_seconds=5)
+
+ assert (await host.get_status()).state == "STOPPED"
diff --git a/tests/unit_tests/personal_context/test_personal_context_cancellation_static_rules.py b/tests/unit_tests/personal_context/test_personal_context_cancellation_static_rules.py
new file mode 100644
index 0000000000..44c762f307
--- /dev/null
+++ b/tests/unit_tests/personal_context/test_personal_context_cancellation_static_rules.py
@@ -0,0 +1,58 @@
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+import pytest
+
+
+ROOT = Path(__file__).parents[3]
+TARGETS = (
+ (
+ ROOT / "jiuwenswarm/server/personal_context/ws_handler.py",
+ "_notify_runtime_enabled",
+ ),
+ (
+ ROOT / "jiuwenswarm/server/runtime/agent_manager.py",
+ "set_personal_context_runtime_enabled",
+ ),
+ (
+ ROOT / "jiuwenswarm/server/runtime/agent_adapter/interface_deep.py",
+ "refresh_personal_context_rail",
+ ),
+)
+
+
+ ("path", "function_name"),
+ TARGETS,
+ ids=[function_name for _, function_name in TARGETS],
+)
+def test_cancelled_error_is_not_raised_inside_except_handler(
+ path: Path,
+ function_name: str,
+) -> None:
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ functions = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
+ and node.name == function_name
+ ]
+ assert len(functions) == 1, (path, function_name)
+
+ handlers = [
+ node
+ for node in ast.walk(functions[0])
+ if isinstance(node, ast.ExceptHandler)
+ and isinstance(node.type, ast.Attribute)
+ and isinstance(node.type.value, ast.Name)
+ and node.type.value.id == "asyncio"
+ and node.type.attr == "CancelledError"
+ ]
+
+ assert handlers, (path, function_name)
+ assert all(
+ not any(isinstance(statement, ast.Raise) for statement in handler.body)
+ for handler in handlers
+ ), (path, function_name)
diff --git a/tests/unit_tests/test_app_web_handlers.py b/tests/unit_tests/test_app_web_handlers.py
index d28b7c133f..b21b78b3a6 100644
--- a/tests/unit_tests/test_app_web_handlers.py
+++ b/tests/unit_tests/test_app_web_handlers.py
@@ -1162,6 +1162,47 @@ def test_web_does_not_expose_symphony_evolution_rpc_methods():
assert "symphony.evolution_rebuild" not in app_web_handlers._FORWARD_REQ_METHODS
+def test_web_forwards_only_canonical_personal_context_rpc_methods():
+ methods = {
+ "personal_context.runtime.status",
+ "personal_context.runtime.start",
+ "personal_context.runtime.stop",
+ "personal_context.runtime.get_config",
+ "personal_context.runtime.patch_config",
+ "personal_context.runtime.select_model",
+ "personal_context.fetch.list_services",
+ "personal_context.fetch.create_service",
+ "personal_context.fetch.delete_service",
+ "personal_context.fetch.patch_service",
+ "personal_context.fetch.start_service",
+ "personal_context.fetch.stop_service",
+ "personal_context.fetch.start_scheduler",
+ "personal_context.fetch.stop_scheduler",
+ "personal_context.fetch.run_all",
+ "personal_context.fetch.run_one",
+ "personal_context.fetch.get_run_status",
+ "personal_context.fetch.get_authorization_status",
+ "personal_context.fetch.authorize_provider",
+ "personal_context.context.stream_graph",
+ "personal_context.context.search_pages",
+ "personal_context.context.get_node",
+ }
+ forwarded = {
+ method
+ for method in app_web_handlers._FORWARD_REQ_METHODS
+ if method.startswith("personal_context.")
+ }
+ no_local = {
+ method
+ for method in app_web_handlers._FORWARD_NO_LOCAL_HANDLER_METHODS
+ if method.startswith("personal_context.")
+ }
+
+ assert forwarded == methods
+ assert no_local == methods
+ assert len(methods) == 22
+
+
# =====================================================================
# _normalize_feishu_conf 纯函数测试
# =====================================================================
diff --git a/tests/unit_tests/test_personal_context_clean_cut.py b/tests/unit_tests/test_personal_context_clean_cut.py
new file mode 100644
index 0000000000..b99fd01b86
--- /dev/null
+++ b/tests/unit_tests/test_personal_context_clean_cut.py
@@ -0,0 +1,46 @@
+from __future__ import annotations
+
+import importlib.util
+from pathlib import Path
+
+import pytest
+
+from jiuwenswarm.common.schema.message import ReqMethod
+
+
+def test_personal_context_api_inventory_and_legacy_removal() -> None:
+ methods = {
+ item.value for item in ReqMethod if item.value.startswith("personal_context.")
+ }
+ legacy_prefix = "p" + "cs."
+
+ assert len(methods) == 22
+ assert not any(item.value.startswith(legacy_prefix) for item in ReqMethod)
+
+
+def test_personal_context_host_contract() -> None:
+ from jiuwenswarm.server.personal_context import PersonalContextHostAPI
+
+ legacy_module = ".".join(("jiuwenswarm", "server", "proactive" + "_" + "context"))
+
+ assert PersonalContextHostAPI.__name__ == "PersonalContextHostAPI"
+ assert importlib.util.find_spec(legacy_module) is None
+
+
+async def test_legacy_config_file_is_not_read(tmp_path: Path) -> None:
+ from jiuwenswarm.server.personal_context import PersonalContextHostAPI
+
+ home = tmp_path / "home"
+ home.mkdir()
+ legacy_config = home / ("p" + "cs.yaml")
+ legacy_config.write_text("enabled: false\n", encoding="utf-8")
+ host = PersonalContextHostAPI(home=home)
+
+ await host.start()
+ status = await host.get_status()
+
+ assert status.configured is False
+ assert status.state == "CREATED"
+ assert host._config_path == home / "personal_context.yaml"
+ assert not host._config_path.exists()