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): add collection management, GitCode service and context browsing backend (MR !5464, !6356, !6543, plus backend parts of !5709, !6552)
程凯c0cd584508a0
diff --git a/jiuwenswarm/agents/swarm/config_specs.py b/jiuwenswarm/agents/swarm/config_specs.pyindex 39280968bc..4dca8bd366 100644--- a/jiuwenswarm/agents/swarm/config_specs.py+++ b/jiuwenswarm/agents/swarm/config_specs.py@@ -97,6 +97,7 @@ _COMMON_RAIL_NAMES: tuple[str, ...] = (registry.AVATAR_PROMPT,registry.TEAM_WORKSPACE_REPORT_PATH,registry.CONTEXT_PROCESSOR,+ registry.PERSONAL_CONTEXT,registry.PLUGIN_RAILS,registry.SKILL_RETRIEVAL_PROMPT,registry.SYMPHONY_ORCHESTRATION_PROMPT,@@ -142,6 +143,7 @@ _CODE_RAIL_NAMES: tuple[str, ...] = (registry.CODE_AGENT_MODE,registry.STRUCTURED_ASK_USER,registry.CONTEXT_PROCESSOR,+ registry.PERSONAL_CONTEXT,registry.CODE_TASK_PLANNING,registry.CODE_AGENT_RAIL,registry.USER_HOOKS,diff --git a/jiuwenswarm/agents/swarm/providers/member_rails.py b/jiuwenswarm/agents/swarm/providers/member_rails.pyindex 79d3eea1d6..5c95d6aa2f 100644--- a/jiuwenswarm/agents/swarm/providers/member_rails.py+++ b/jiuwenswarm/agents/swarm/providers/member_rails.py@@ -31,6 +31,8 @@ from openjiuwen.agent_teams.rails.team_context import (get_team_backend,)+from openjiuwen.harness.rails.personal_context import PersonalContextRail+from jiuwenswarm.agents.harness.common.plugins.rail_manager import get_rail_managerfrom jiuwenswarm.server.runtime.runtime_scope import RuntimeScopeKeyfrom jiuwenswarm.agents.harness.common.rails.runtime_prompt_rail import (@@ -60,10 +62,12 @@ from jiuwenswarm.agents.harness.team.rails.team_workspace_report_path_rail imporfrom jiuwenswarm.agents.harness.team.team_runtime_inheritance import (_build_context_processor_rail,)+from jiuwenswarm.agents.swarm.context import SwarmBuildContextlogger = logging.getLogger(__name__)+PERSONAL_CONTEXT = "swarm.personal_context"RUNTIME_PROMPT = "swarm.runtime_prompt"TEAM_SKILL_STORAGE_POLICY = "swarm.team_skill_storage_policy"TEAM_SHARED_SKILL_LINK_REFRESH = "swarm.team_shared_skill_link_refresh"@@ -77,6 +81,27 @@ TEAM_PERMISSION_POLICY = "swarm.team_permission_policy"DISABLED_TOOLS = "swarm.disabled_tools"+@harness_element(+ kind=ElementKind.RAIL,+ name=PERSONAL_CONTEXT,+ description="Personal context shared with work/code, gated by the fixed-home Agent-use switch on each model call.",+)+def _build_personal_context_rail(+ params: dict[str, Any],+ context: SwarmBuildContext,+) -> PersonalContextRail | None:+ """Mount even when disabled so live members observe subsequent switch changes."""+ del params, context+ try:+ return PersonalContextRail(Path.home() / ".jiuwenswarm" / ".personal_context")+ except Exception as exc:+ logger.warning(+ "[swarm.personal_context] optional Rail construction failed (%s)",+ type(exc).__name__,+ )+ return None++def _workspace_root(ctx: SwarmBuildContext) -> str | None:"""Resolve the member workspace root path."""workspace = getattr(ctx, "workspace", None)diff --git a/jiuwenswarm/agents/swarm/registry.py b/jiuwenswarm/agents/swarm/registry.pyindex 5833d5946c..cac8b95bdd 100644--- a/jiuwenswarm/agents/swarm/registry.py+++ b/jiuwenswarm/agents/swarm/registry.py@@ -72,6 +72,7 @@ WEB_SEARCH = _tools.WEB_SEARCHWEB_FETCH = _tools.WEB_FETCHVISION = _OJ_VISIONAUDIO = _OJ_AUDIO+PERSONAL_CONTEXT = _member_rails.PERSONAL_CONTEXTRUNTIME_PROMPT = _member_rails.RUNTIME_PROMPTTEAM_SKILL_STORAGE_POLICY = _member_rails.TEAM_SKILL_STORAGE_POLICYTEAM_SHARED_SKILL_LINK_REFRESH = _member_rails.TEAM_SHARED_SKILL_LINK_REFRESH@@ -168,6 +169,7 @@ def register_swarm_providers() -> None:__all__ = [+ "PERSONAL_CONTEXT","register_swarm_providers","SKILL_TOOLKIT","SKILL_RETRIEVAL",diff --git a/jiuwenswarm/common/schema/message.py b/jiuwenswarm/common/schema/message.pyindex 9abb0defd6..91be23f085 100644--- a/jiuwenswarm/common/schema/message.py+++ b/jiuwenswarm/common/schema/message.py@@ -165,8 +165,16 @@ class ReqMethod(Enum):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_START_COLLECTION = (+ "personal_context.runtime.start_collection"+ )+ PERSONAL_CONTEXT_RUNTIME_STOP_COLLECTION = (+ "personal_context.runtime.stop_collection"+ )+ PERSONAL_CONTEXT_RUNTIME_START_AGENT_USE = (+ "personal_context.runtime.start_agent_use"+ )+ PERSONAL_CONTEXT_RUNTIME_STOP_AGENT_USE = "personal_context.runtime.stop_agent_use"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"@@ -176,10 +184,9 @@ class ReqMethod(Enum):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_STOP_RUN = "personal_context.fetch.stop_run"PERSONAL_CONTEXT_FETCH_GET_RUN_STATUS = "personal_context.fetch.get_run_status"PERSONAL_CONTEXT_FETCH_GET_AUTHORIZATION_STATUS = ("personal_context.fetch.get_authorization_status"@@ -188,8 +195,10 @@ class ReqMethod(Enum):"personal_context.fetch.authorize_provider")PERSONAL_CONTEXT_CONTEXT_STREAM_GRAPH = "personal_context.context.stream_graph"+ PERSONAL_CONTEXT_CONTEXT_STREAM_TREE = "personal_context.context.stream_tree"PERSONAL_CONTEXT_CONTEXT_SEARCH_PAGES = "personal_context.context.search_pages"PERSONAL_CONTEXT_CONTEXT_GET_NODE = "personal_context.context.get_node"+ PERSONAL_CONTEXT_CONTEXT_GET_SOURCE = "personal_context.context.get_source"# Plugin management (reuses skills marketplace infrastructure)PLUGINS_LIST = "plugins.list"diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex 8578494476..8550df2fe5 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -698,8 +698,10 @@ _FORWARD_REQ_METHODS = frozenset({"symphony.graph","symphony.plan","personal_context.runtime.status",- "personal_context.runtime.start",- "personal_context.runtime.stop",+ "personal_context.runtime.start_collection",+ "personal_context.runtime.stop_collection",+ "personal_context.runtime.start_agent_use",+ "personal_context.runtime.stop_agent_use","personal_context.runtime.get_config","personal_context.runtime.patch_config","personal_context.runtime.select_model",@@ -709,16 +711,17 @@ _FORWARD_REQ_METHODS = frozenset({"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.stop_run","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.stream_tree","personal_context.context.search_pages","personal_context.context.get_node",+ "personal_context.context.get_source","plugins.list","plugins.install","plugins.uninstall",@@ -832,8 +835,10 @@ _FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset({"symphony.graph","symphony.plan","personal_context.runtime.status",- "personal_context.runtime.start",- "personal_context.runtime.stop",+ "personal_context.runtime.start_collection",+ "personal_context.runtime.stop_collection",+ "personal_context.runtime.start_agent_use",+ "personal_context.runtime.stop_agent_use","personal_context.runtime.get_config","personal_context.runtime.patch_config","personal_context.runtime.select_model",@@ -843,16 +848,17 @@ _FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset({"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.stop_run","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.stream_tree","personal_context.context.search_pages","personal_context.context.get_node",+ "personal_context.context.get_source","plugins.list","plugins.install","plugins.uninstall",diff --git a/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.py b/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.pyindex 189d03001c..724466801a 100644--- a/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.py+++ b/jiuwenswarm/gateway/channel_manager/web/web_ws_transport.py@@ -80,6 +80,10 @@ _WEB_FULL_PAYLOAD_EVENT_TYPES = frozenset("heartbeat.relay","context.usage","context.compression_state",+ "personal_context.context.start",+ "personal_context.context.nodes",+ "personal_context.context.edges",+ "personal_context.context.end","chat.ask_user_question","chat.ask_user_question_expired","chat.subtask_update",@@ -680,6 +684,7 @@ class WebWsTransport(BaseWsChannel):event_name in _WEB_FULL_PAYLOAD_EVENT_TYPESor event_name.startswith("team.")or event_name.startswith("harness.")+ or event_name.startswith("personal_context.context."))@classmethoddiff --git a/jiuwenswarm/server/personal_context/host_api.py b/jiuwenswarm/server/personal_context/host_api.pyindex 89e4d83332..759408480a 100644--- a/jiuwenswarm/server/personal_context/host_api.py+++ b/jiuwenswarm/server/personal_context/host_api.py@@ -14,36 +14,203 @@ import osfrom pathlib import Pathimport statimport tempfile+from collections.abc import Awaitable, Callablefrom typing import NoReturn, cast+import httpximport yamlfrom openjiuwen.harness.personal_context import PersonalContext-from jiuwenswarm.common.config import get_default_models+from jiuwenswarm.common.config import get_config, get_default_models_CONFIG_FILENAME = "personal_context.yaml"_MAX_CONFIG_BYTES = 4 * 1024 * 1024_STOP_TIMEOUT_SECONDS = 30.0+_PERSONAL_CONTEXT_MODEL_MAX_RETRIES = 2+_PAT_VALIDATION_TIMEOUT_SECONDS = 15.0+_MAX_PAT_RESPONSE_BYTES = 1024 * 1024+_REPOSITORY_PAT_FIELDS = {"github": "token", "gitcode": "pat"}+_REPOSITORY_USER_URLS = {+ "github": "https://api.github.com/user",+ "gitcode": "https://api.gitcode.com/api/v5/user",+}+++def _directory_capacity_defaults() -> tuple[int, int]:+ fields = PersonalContext.Config.model_fields+ pages = fields["max_pages_per_directory"].default+ subdirectories = fields["max_subdirectories_per_directory"].default+ if type(pages) is not int or type(subdirectories) is not int:+ raise RuntimeError("PersonalContext directory capacity defaults are invalid")+ return pages, subdirectories+++def _global_embedding_values() -> tuple[str | None, str | None, str | None]:+ try:+ config = get_config() or {}+ except Exception:+ return None, None, None+ embed = config.get("embed") if isinstance(config, dict) else None+ if not isinstance(embed, dict):+ return None, None, None+ model = str(embed.get("embed_model") or "").strip()+ base_url = str(+ embed.get("embed_base_url") or embed.get("embed_api_base") or ""+ ).strip()+ api_key = str(embed.get("embed_api_key") or "").strip()+ return (+ (model, base_url, api_key)+ if model and base_url and api_key+ else (None, None, None)+ )+++def _is_usable_model_entry(entry: object) -> bool:+ """条目是否是可用的默认模型(即能被 agent/balanced 策略实际调用)。"""++ if not isinstance(entry, dict):+ return False+ client = entry.get("model_client_config")+ request = entry.get("model_config_obj")+ if not isinstance(client, dict) or not isinstance(request, dict):+ return False+ return bool(str(client.get("model_name") or "").strip())+++def _model_entry_id(entry: object) -> str | None:+ """生成跨请求稳定的模型标识。++ model_name 通常已是唯一业务标识;加上 provider 可避免不同网关配置同一个+ model_name 时相互覆盖。该 ID 只用于定位当前 models.list 条目,不落 Core。+ """++ if not isinstance(entry, dict):+ return None+ client = entry.get("model_client_config")+ if not isinstance(client, dict):+ return None+ model_name = str(client.get("model_name") or "").strip()+ if not model_name:+ return None+ provider = str(client.get("client_provider") or "").strip().casefold()+ return f"{provider}:{model_name}" if provider else model_name+++def _find_model_index_by_id(model_id: object) -> int | None:+ """按稳定 ID 查找当前下标;ID 不存在或格式非法时返回 None。"""++ if not isinstance(model_id, str) or not model_id:+ return None+ models = get_default_models()+ for index, entry in enumerate(models):+ if _model_entry_id(entry) == model_id:+ return index+ return None+++def _first_usable_model() -> tuple[int | None, str | None]:+ """返回第一个可用模型及其稳定 ID;列表为空或条目不可用时均为 None。++ 环境变量兜底分支会产出一条 model_name 为空的占位条目,它无法用于智能体+ 策略,因此这里按「可用」而非「存在」判断,避免默认值落到坏条目上再报错。+ """++ for index, entry in enumerate(get_default_models()):+ if _is_usable_model_entry(entry):+ return index, _model_entry_id(entry)+ return None, None+++def _first_usable_model_index() -> int | None:+ """兼容旧调用点的第一个可用模型下标。"""++ return _first_usable_model()[0]+++def _model_index_is_usable(model_index: object) -> bool:+ if type(model_index) is not int or model_index < 0:+ return False+ models = get_default_models()+ if model_index >= len(models):+ return False+ return _is_usable_model_entry(models[model_index])+++def _reconcile_model_selection(stored: dict[str, object]) -> None:+ """让「稳定模型 ID + 当前下标 + 采集策略」自洽。+ - model_id 可用:以它为准刷新 model_index,避免 models.list 顺序变化改变选择;+ - 旧 YAML 只有 model_index:沿用当前有效下标并补写 model_id;+ - model_id 失效或下标未设置/已失效:回落到第一个可用模型;一个可用模型都没有则置空,+ 并把依赖模型的 balanced/agent 降级为 rules——Core 要求二者必须同时+ 提供 model_client 与 model_request,否则整份配置直接校验失败。+ """-def _initial_stored_config(*, enabled: bool) -> dict[str, object]:+ if "model_id" in stored and stored.get("model_id") is not None:+ matched_index = _find_model_index_by_id(stored.get("model_id"))+ if matched_index is not None:+ stored["model_index"] = matched_index+ return+ elif _model_index_is_usable(stored.get("model_index")):+ model_index = cast(int, stored["model_index"])+ stored["model_id"] = _model_entry_id(get_default_models()[model_index])+ return++ fallback_index, fallback_id = _first_usable_model()+ fallback = fallback_index+ if fallback is not None:+ stored["model_index"] = fallback+ stored["model_id"] = fallback_id+ return+ stored["model_index"] = None+ stored["model_id"] = None+ if stored.get("strategy_profile") in {"balanced", "agent"}:+ stored["strategy_profile"] = "rules"+++def _default_strategy_and_model() -> tuple[str, int | None, str | None]:+ """默认采集策略与模型:有可用模型则默认第一个模型走智能体,否则模型置空并回退规则模式。++ agent/balanced 策略强依赖模型(Core 校验要求 model_client 与 model_request 同时提供),+ 因此无可用模型时只能回退 rules——否则首次启用会直接抛 invalid configuration。+ """++ model_index, model_id = _first_usable_model()+ if model_index is None:+ return "rules", None, None+ return "agent", model_index, model_id+++def _initial_stored_config(*, collection_enabled: bool) -> dict[str, object]:+ max_pages, max_subdirectories = _directory_capacity_defaults()+ strategy_profile, model_index, model_id = _default_strategy_and_model()return {- "enabled": enabled,- "fetching_enabled": False,- "strategy_profile": "rules",+ "collection_enabled": collection_enabled,+ "agent_use_enabled": False,+ "strategy_profile": strategy_profile,+ "max_pages_per_directory": max_pages,+ "max_subdirectories_per_directory": max_subdirectories,"fetch_services": [],+ "model_index": model_index,+ "model_id": model_id,+ "provider_credentials": {},}def _unconfigured_projection() -> dict[str, object]:+ max_pages, max_subdirectories = _directory_capacity_defaults()+ strategy_profile, model_index, model_id = _default_strategy_and_model()return {"configured": False,- "enabled": False,- "fetching_enabled": False,- "strategy_profile": "rules",- "model_index": None,+ "collection_enabled": False,+ "agent_use_enabled": False,+ "strategy_profile": strategy_profile,+ "max_pages_per_directory": max_pages,+ "max_subdirectories_per_directory": max_subdirectories,+ "model_index": model_index,+ "model_id": model_id,"fetch_services": [],}@@ -254,13 +421,60 @@ def _resolve_model_reference(model_name = str(client.pop("model_name", "")).strip()if not model_name:_raise_host_error("selected JiuwenSwarm model is invalid")+ client["max_retries"] = _PERSONAL_CONTEXT_MODEL_MAX_RETRIESrequest["model"] = model_namereturn client, request+def _normalize_provider_credentials(value: object) -> dict[str, dict[str, str]]:+ if value is None:+ return {}+ if not isinstance(value, dict):+ _raise_host_error("provider_credentials must be an object")+ unknown = set(value) - set(_REPOSITORY_PAT_FIELDS)+ if unknown:+ _raise_host_error("provider_credentials contains an unsupported provider")+ normalized: dict[str, dict[str, str]] = {}+ for provider, raw_credentials in value.items():+ if not isinstance(raw_credentials, dict):+ _raise_host_error(f"{provider} provider credentials must be an object")+ field = _REPOSITORY_PAT_FIELDS[provider]+ if set(raw_credentials) != {field}:+ _raise_host_error(+ f"{provider} provider credentials must contain only {field}"+ )+ secret = raw_credentials[field]+ if not isinstance(secret, str) or not secret.strip():+ _raise_host_error(+ f"{provider} provider credential must be a non-empty string"+ )+ normalized[provider] = {field: secret.strip()}+ return normalized+++def _project_service(service: dict[str, object]) -> dict[str, object]:+ projected = deepcopy(service)+ projected.pop("credentials", None)+ return projected+++def _project_stored_config(stored: dict[str, object]) -> dict[str, object]:+ projected = deepcopy(stored)+ projected.pop("provider_credentials", None)+ services = projected.get("fetch_services", [])+ if not isinstance(services, list) or any(+ not isinstance(service, dict) for service in services+ ):+ _raise_host_error("PersonalContext fetch_services are invalid")+ projected["fetch_services"] = [_project_service(service) for service in services]+ return projected++def _build_core_config(stored: dict[str, object]) -> PersonalContext.Config:raw = deepcopy(stored)+ raw.pop("provider_credentials", None)model_index = raw.pop("model_index", None)+ raw.pop("model_id", None)raw.pop("model_client", None)raw.pop("model_request", None)if model_index is not None:@@ -275,6 +489,31 @@ def _build_core_config(stored: dict[str, object]) -> PersonalContext.Config:_raise_host_error("PersonalContext configuration is invalid", cause=exc)+def _semantic_config_dump(config: PersonalContext.Config) -> dict[str, object]:+ """可比较的配置快照:剔除每次构造都会变的 Core 自动生成字段。"""++ dumped = config.model_dump(mode="json", by_alias=True)+ client = dumped.get("model_client")+ if isinstance(client, dict):+ # Core 的 ModelClientConfig.client_id 是 uuid4 默认值,每次 from_dict 都不同。+ client.pop("client_id", None)+ return dumped+++def _configs_equivalent(+ left: PersonalContext.Config, right: PersonalContext.Config+) -> bool:+ """两份 Core 配置语义是否一致(忽略 volatile 的自动生成字段)。++ 直接比较对象时,只要配置里带 model_client 就永远不等,会让幂等快路径失效,+ 于是每次写配置都会走一遍 deactivate → set → activate 重启运行时。+ """++ if left == right:+ return True+ return _semantic_config_dump(left) == _semantic_config_dump(right)++def _prepare_stored_config(config: dict[str, object],) -> tuple[dict[str, object], PersonalContext.Config]:@@ -283,15 +522,115 @@ def _prepare_stored_config(stored = deepcopy(config)stored.pop("model_client", None)stored.pop("model_request", None)+ provider_credentials = _normalize_provider_credentials(+ stored.pop("provider_credentials", {})+ )+ # 模型不可用时先归一化,再交给 Core 校验;否则会整份配置判为非法。+ _reconcile_model_selection(stored)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"]+ normalized["model_id"] = stored.get("model_id")+ normalized["provider_credentials"] = provider_credentialsreturn normalized, candidate+def _repository_authorization_result(+ provider: str,+ state: str,+ *,+ account: dict[str, str] | None = None,+ error: str | None = None,+) -> dict[str, object]:+ return {+ "provider": provider,+ "state": state,+ "account": deepcopy(account),+ "verification_url": None,+ "expires_at": None,+ "error": error,+ }+++async def _validate_repository_pat(provider: str, secret: str) -> dict[str, str]:+ url = _REPOSITORY_USER_URLS.get(provider)+ if url is None:+ _raise_host_error("unsupported repository provider")+ try:+ async with httpx.AsyncClient(+ timeout=_PAT_VALIDATION_TIMEOUT_SECONDS,+ follow_redirects=False,+ ) as client:+ response = await client.get(+ url,+ headers={+ "Accept": "application/json",+ "Authorization": f"Bearer {secret}",+ },+ )+ except httpx.TimeoutException:+ _raise_host_error("repository provider credential validation timed out")+ except httpx.HTTPError:+ _raise_host_error("repository provider credential validation request failed")+ except Exception:+ _raise_host_error("repository provider credential validation request failed")+ if response.status_code != 200:+ _raise_host_error(+ f"repository provider credential validation returned HTTP {response.status_code}"+ )+ content_length = response.headers.get("Content-Length")+ if content_length is not None:+ try:+ if int(content_length) > _MAX_PAT_RESPONSE_BYTES:+ _raise_host_error(+ "repository provider credential response exceeds the size limit"+ )+ except ValueError:+ _raise_host_error(+ "repository provider credential response has an invalid size"+ )+ content = response.content+ if len(content) > _MAX_PAT_RESPONSE_BYTES:+ _raise_host_error(+ "repository provider credential response exceeds the size limit"+ )+ try:+ payload = response.json()+ except (ValueError, TypeError):+ _raise_host_error("repository provider credential response is invalid")+ if not isinstance(payload, dict):+ _raise_host_error("repository provider credential response is invalid")+ login = payload.get("login") or payload.get("username")+ display_name = payload.get("name") or payload.get("display_name") or login+ if not isinstance(login, str) or not isinstance(display_name, str):+ _raise_host_error("repository provider account response is invalid")+ for value in (login, display_name):+ if (+ not value.strip()+ or len(value) > 256+ or any(ord(character) < 32 for character in value)+ ):+ _raise_host_error("repository provider account response is invalid")+ return {"login": login.strip(), "display_name": display_name.strip()}+++async def _validate_repository_pat_for_write(+ provider: str,+ secret: str,+) -> dict[str, str]:+ try:+ return await _validate_repository_pat(provider, secret)+ except Exception as exc:+ raise _as_host_error(+ exc,+ f"{provider} credential verification failed",+ status_name="CONTEXT_PROACTIVE_CONFIG_INVALID",+ ) from None++class PersonalContextHostAPI:"""The only JiuwenSwarm API for configuring and controlling embedded PersonalContext."""@@ -302,6 +641,20 @@ class PersonalContextHostAPI:self._config: PersonalContext.Config | None = Noneself._stored_config: dict[str, object] | None = Noneself._operation_lock = asyncio.Lock()+ self._fetch_run_stop_lock = asyncio.Lock()++ def _refresh_embedding_configuration(self) -> None:+ model_name, base_url, api_key = _global_embedding_values()+ # Merged Core exposes this Host-owned seam as a protected method.+ self._personal_context._set_embedding_configuration( # pylint: disable=protected-access+ model_name=model_name,+ base_url=base_url,+ api_key=api_key,+ )++ async def _start_collection_with_embedding(self) -> None:+ self._refresh_embedding_configuration()+ await self._personal_context.start_collection()async def configure(self, config: dict[str, object]) -> None:"""Validate, save, and apply one complete configuration."""@@ -324,7 +677,9 @@ class PersonalContextHostAPI:previous = self._configprevious_stored = self._stored_config- same_configuration = previous is not None and previous == candidate+ same_configuration = previous is not None and _configs_equivalent(+ previous, candidate+ )previous_active = Falseif previous is not None:@@ -342,13 +697,17 @@ class PersonalContextHostAPI:exc,"PersonalContext runtime status could not be read",) from None- if same_configuration and previous_active == candidate.enabled:+ if same_configuration and previous_active == candidate.collection_enabled:_publish_yaml(self._config_path, payload)self._stored_config = deepcopy(stored)returntemporary: Path | None = _stage_yaml(self._config_path, payload)- disabling = previous is not None and previous.enabled and not candidate.enabled+ disabling = (+ previous is not None+ and previous.collection_enabled+ and not candidate.collection_enabled+ )disabled_yaml_published = Falserollback_runtime = Falsephase = "stop"@@ -372,8 +731,9 @@ class PersonalContextHostAPI:rollback_runtime = Trueawait self._personal_context.set_configuration(candidate)- if candidate.enabled:+ if candidate.collection_enabled:phase = "activate"+ self._refresh_embedding_configuration()await self._personal_context.activate_runtime()if not disabled_yaml_published:@@ -435,11 +795,76 @@ class PersonalContextHostAPI:finally:_cleanup_temporary(temporary)+ async def _apply_live_update_locked(+ self,+ candidate: PersonalContext.Config,+ stored: dict[str, object],+ payload: bytes,+ *,+ apply: Callable[[], Awaitable[None]],+ rollback: Callable[[], Awaitable[None]],+ publish_before_apply: bool = False,+ ) -> None:+ """Atomically couple one hot Core update with its complete YAML snapshot."""++ if self._stored_config is None:+ _raise_host_error("PersonalContext is not configured")+ previous_payload = _serialize_config(self._stored_config)+ temporary: Path | None = _stage_yaml(self._config_path, payload)+ published = False+ apply_started = False+ try:+ if publish_before_apply:+ if temporary is None:+ _raise_host_error("PersonalContext configuration staging failed")+ _replace_yaml(temporary, self._config_path)+ temporary = None+ published = True+ apply_started = True+ await apply()+ if not published:+ if temporary is None:+ _raise_host_error("PersonalContext configuration staging failed")+ _replace_yaml(temporary, self._config_path)+ temporary = None+ published = True+ self._config = candidate+ self._stored_config = deepcopy(stored)+ except BaseException as exc:+ rollback_error: BaseException | None = None+ if apply_started:+ try:+ await rollback()+ except BaseException as restore_exc:+ rollback_error = restore_exc+ if published:+ try:+ _publish_yaml(self._config_path, previous_payload)+ 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 live configuration could not be restored",+ ) from None+ raise _as_host_error(+ exc,+ "PersonalContext live configuration could not be applied",+ ) 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)+ config = (+ _project_stored_config(self._stored_config)+ if self._stored_config is not None+ else None+ )status = await self._personal_context.snapshot()return {"configured": self._stored_config is not None,@@ -453,7 +878,7 @@ class PersonalContextHostAPI:async with self._operation_lock:if self._stored_config is None:return _unconfigured_projection()- return deepcopy(self._stored_config)+ return _project_stored_config(self._stored_config)async def patch_runtime_config(self,@@ -463,7 +888,11 @@ class PersonalContextHostAPI:if not isinstance(patch, dict):_raise_host_error("patch must be an object")- unknown = set(patch) - {"strategy_profile"}+ unknown = set(patch) - {+ "collection_enabled",+ "agent_use_enabled",+ "strategy_profile",+ }if unknown:_raise_host_error("runtime patch contains unsupported fields")async with self._operation_lock:@@ -477,7 +906,7 @@ class PersonalContextHostAPI:stored,_serialize_config(stored),)- return deepcopy(stored)+ return _project_stored_config(stored)async def select_model(self, model_index: int) -> dict[str, object]:"""Select one current JiuwenSwarm model by its models.list index."""@@ -487,18 +916,23 @@ class PersonalContextHostAPI:async with self._operation_lock:if self._stored_config is None:_raise_host_error("PersonalContext is not configured")+ # 校验放在锁内,避免 models.list 在校验和写入之间发生变化。+ # 显式选择必须拦截;_reconcile_model_selection 会把不可用下标静默回退。+ if not _model_index_is_usable(model_index):+ _raise_host_error("selected JiuwenSwarm model no longer exists")stored = deepcopy(self._stored_config)stored["model_index"] = model_index+ stored["model_id"] = _model_entry_id(get_default_models()[model_index])stored, candidate = _prepare_stored_config(stored)await self._apply_configuration_locked(candidate,stored,_serialize_config(stored),)- return deepcopy(stored)+ return _project_stored_config(stored)- async def set_runtime_enabled(self, enabled: bool) -> dict[str, object]:- """Persist and apply the whole PersonalContext runtime enable switch."""+ async def set_collection_enabled(self, enabled: bool) -> dict[str, object]:+ """Persist and apply the PersonalContext collection switch."""if not isinstance(enabled, bool):_raise_host_error("enabled must be a boolean")@@ -507,39 +941,81 @@ class PersonalContextHostAPI:if self._stored_config is None:if not enabled:return _unconfigured_projection()- stored = _initial_stored_config(enabled=True)+ stored = _initial_stored_config(collection_enabled=True)else:stored = deepcopy(self._stored_config)- stored["enabled"] = enabled+ stored["collection_enabled"] = enabledstored, candidate = _prepare_stored_config(stored)- await self._apply_configuration_locked(+ if first_start:+ await self._apply_configuration_locked(+ candidate,+ stored,+ _serialize_config(stored),+ )+ else:+ await self._apply_live_update_locked(+ candidate,+ stored,+ _serialize_config(stored),+ apply=(+ self._start_collection_with_embedding+ if enabled+ else lambda: self._personal_context.stop_collection(+ timeout_seconds=_STOP_TIMEOUT_SECONDS+ )+ ),+ rollback=(+ (+ lambda: self._personal_context.stop_collection(+ timeout_seconds=_STOP_TIMEOUT_SECONDS+ )+ )+ if enabled+ else self._start_collection_with_embedding+ ),+ publish_before_apply=not enabled,+ )+ result = _project_stored_config(stored)+ return result++ async def set_agent_use_enabled(self, enabled: bool) -> dict[str, object]:+ """Persist the Agent-use switch without creating an initial configuration."""++ if not isinstance(enabled, bool):+ _raise_host_error("enabled must be a boolean")+ async with self._operation_lock:+ if self._stored_config is None:+ _raise_host_error("PersonalContext is not configured")+ stored = deepcopy(self._stored_config)+ stored["agent_use_enabled"] = enabled+ stored, candidate = _prepare_stored_config(stored)+ await self._apply_live_update_locked(candidate,stored,_serialize_config(stored),+ apply=(+ self._personal_context.start_agent_use+ if enabled+ else self._personal_context.stop_agent_use+ ),+ rollback=(+ self._personal_context.stop_agent_use+ if enabled+ else self._personal_context.start_agent_use+ ),)- result = deepcopy(stored)- if first_start:- result["model_index"] = None- return result+ return _project_stored_config(stored)async def list_fetch_services(self) -> list[dict[str, object]]:- """Return every fixed fetch service with current state and last error."""+ """Return every fixed fetch service configuration."""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"]),+ list[dict[str, object]], 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+ return [_project_service(service) for service in services]async def create_fetch_service(self,@@ -571,12 +1047,49 @@ class PersonalContextHostAPI:_raise_host_error(f"{normalized_provider} fetch service limit of 20 has been reached")- services.append(deepcopy(service))+ internal_service = deepcopy(service)+ if normalized_provider in _REPOSITORY_PAT_FIELDS:+ if "credentials" in service:+ _raise_host_error(+ "repository fetch service credentials are managed by the provider authorization"+ )+ provider_credentials = cast(+ dict[str, dict[str, str]],+ stored.get("provider_credentials", {}),+ )+ current = provider_credentials.get(normalized_provider)+ field = _REPOSITORY_PAT_FIELDS[normalized_provider]+ if current is None or field not in current:+ _raise_host_error(+ f"{normalized_provider} must be authorized before creating a fetch service"+ )+ internal_service["credentials"] = {field: current[field]}+ services.append(internal_service)stored, candidate = _prepare_stored_config(stored)- await self._apply_configuration_locked(+ if normalized_provider in _REPOSITORY_PAT_FIELDS:+ current_credentials = cast(+ dict[str, dict[str, str]],+ stored["provider_credentials"],+ )[normalized_provider]+ await _validate_repository_pat_for_write(+ normalized_provider,+ current_credentials[_REPOSITORY_PAT_FIELDS[normalized_provider]],+ )+ created_config = next(+ item+ for item in candidate.fetch_services+ if item.service_id not in existing_ids+ )+ await self._apply_live_update_locked(candidate,stored,_serialize_config(stored),+ apply=lambda: self._personal_context._append_fetch_service_config( # pylint: disable=protected-access+ created_config,+ ),+ rollback=lambda: self._personal_context._remove_fetch_service_config( # pylint: disable=protected-access+ created_config.service_id,+ ),)normalized_services = cast(list[dict[str, object]],@@ -587,7 +1100,7 @@ class PersonalContextHostAPI:for item in normalized_servicesif cast(str, item["service_id"]) not in existing_ids)- return deepcopy(created)+ return _project_service(created)async def delete_fetch_service(self, service_id: str) -> None:"""Remove one stopped service and its cursor while retaining Context files."""@@ -629,7 +1142,11 @@ class PersonalContextHostAPI:"PersonalContext fetch cursor could not be removed",status_name="CONTEXT_PROACTIVE_FILE_EXECUTION_ERROR",) from None+ history_payload: list[dict[str, object]] | None = Nonetry:+ history_payload = self._personal_context.remove_fetch_run_history(+ normalized_id+ )stored["fetch_services"] = [item for item in services if item["service_id"] != normalized_id]@@ -649,6 +1166,13 @@ class PersonalContextHostAPI:)except BaseException as restore_exc:restore_error = restore_exc+ if history_payload is not None:+ try:+ self._personal_context.restore_fetch_run_history(+ normalized_id, history_payload+ )+ except BaseException as restore_exc:+ restore_error = restore_excif isinstance(exc, asyncio.CancelledError):raiseif restore_error is not None:@@ -677,7 +1201,7 @@ class PersonalContextHostAPI:"interval_seconds","max_items_per_run","source",- "credentials",+ "time_range",}if set(patch) - allowed:_raise_host_error("fetch service patch contains unsupported fields")@@ -713,81 +1237,69 @@ class PersonalContextHostAPI:for service in updated_servicesif service["service_id"] == normalized_id)- return deepcopy(updated)+ return _project_service(updated)async def get_fetch_run_status(self,service_id: str | None = None,+ *,+ run_id: str | None = None,) -> dict[str, object]:- """Return current run state and last retained error for fetch services."""-+ """Return a selected round or retained runs grouped by service."""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")+ if run_id is not None:+ if service_id is None or not isinstance(run_id, str) or not run_id.strip():+ _raise_host_error("run_id requires service_id and 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]}+ return await self._personal_context.get_fetch_run_status(+ normalized_id,+ run_id=run_id,+ )- async def set_fetching(+ async def set_fetch_service_enabled(self,- *,+ service_id: str,enabled: bool,- service_id: str | None = None,) -> None:- """Persist and hot-apply the global or one-service fetch switch."""+ """Persist and hot-apply one service's future scheduling 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):+ if 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"+ "PersonalContext configuration must be set before changing a fetch service")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+ 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"] = enabledraw, candidate = _prepare_stored_config(raw)- await self._apply_configuration_locked(+ await self._apply_live_update_locked(candidate,raw,_serialize_config(raw),+ apply=lambda: self._personal_context.set_fetch_service_enabled(+ normalized_id,+ enabled,+ ),+ rollback=lambda: self._personal_context.set_fetch_service_enabled(+ normalized_id,+ not enabled,+ ),)async def run_fetch(@@ -800,10 +1312,37 @@ class PersonalContextHostAPI: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."""+ async def stop_fetch_run(self, service_id: str) -> dict[str, object]:+ """Stop one active fetch round without changing persisted configuration."""- return await self._personal_context.get_graph()+ 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()+ # stop_fetch_run 不修改 Host 配置。它改用独立锁,避免一次 Core 收尾+ # 阻塞 create/patch/delete;Core 内部仍由 _fetch_lock 保护运行任务。+ async with self._fetch_run_stop_lock:+ await self._personal_context.stop_fetch_run(normalized_id)+ return {"ok": True}++ async def get_graph(+ self,+ *,+ root_id: str | None = None,+ depth: int = 3,+ ) -> dict[str, object]:+ """Read one graph slice without starting Core."""++ return await self._personal_context.get_graph(root_id=root_id, depth=depth)++ async def get_tree(+ self,+ *,+ root_id: str | None = None,+ depth: int = 3,+ ) -> dict[str, object]:+ """Read one file-tree slice without starting Core."""++ return await self._personal_context.get_tree(root_id=root_id, depth=depth)async def search_graph(self, query: str) -> dict[str, object]:"""Search the last published Context pages without starting Core."""@@ -815,10 +1354,53 @@ class PersonalContextHostAPI:return await self._personal_context.get_graph_page(node_id)+ async def get_source(self, source_id: str) -> dict[str, object]:+ """Read one structured atomic-source detail without starting Core."""++ return await self._personal_context.get_source(source_id)+async def get_authorization_status(self, provider: str) -> dict[str, object]:- """Read provider authorization status without storing Host-side state."""+ """Read the current provider credential state without exposing credentials."""async with self._operation_lock:+ if not isinstance(provider, str) or not provider.strip():+ _raise_host_error("provider must be a non-empty string")+ normalized_provider = provider.strip().casefold()+ if normalized_provider in _REPOSITORY_PAT_FIELDS:+ if self._stored_config is None:+ return _repository_authorization_result(+ normalized_provider,+ "not_authorized",+ )+ provider_credentials = cast(+ dict[str, dict[str, str]],+ self._stored_config.get("provider_credentials", {}),+ )+ current = provider_credentials.get(normalized_provider)+ field = _REPOSITORY_PAT_FIELDS[normalized_provider]+ if current is None or field not in current:+ return _repository_authorization_result(+ normalized_provider,+ "not_authorized",+ )+ try:+ account = await _validate_repository_pat(+ normalized_provider,+ current[field],+ )+ except Exception:+ return _repository_authorization_result(+ normalized_provider,+ "authorization_failed",+ error="credential verification failed",+ )+ return _repository_authorization_result(+ normalized_provider,+ "authorized",+ account=account,+ )+ if normalized_provider != "feishu":+ _raise_host_error("provider does not support authorization")if self._config is None:_raise_host_error("PersonalContext configuration must be set before provider authorization"@@ -826,7 +1408,9 @@ class PersonalContextHostAPI:result: dict[str, object] | None = Nonecancelled: asyncio.CancelledError | None = Nonetry:- result = await self._personal_context.get_authorization_status(provider)+ result = await self._personal_context.get_authorization_status(+ normalized_provider+ )except asyncio.CancelledError as exc:cancelled = excexcept Exception as exc:@@ -841,16 +1425,74 @@ class PersonalContextHostAPI:)return result- async def authorize_provider(self, provider: str) -> dict[str, object]:+ async def authorize_provider(+ self,+ provider: str,+ credentials: dict[str, object] | None = None,+ ) -> dict[str, object]:"""Check or begin user authorization for a configured provider."""async with self._operation_lock:+ if not isinstance(provider, str) or not provider.strip():+ _raise_host_error("provider must be a non-empty string")+ normalized_provider = provider.strip().casefold()+ if normalized_provider in _REPOSITORY_PAT_FIELDS:+ field = _REPOSITORY_PAT_FIELDS[normalized_provider]+ if not isinstance(credentials, dict) or set(credentials) != {field}:+ _raise_host_error(+ f"{normalized_provider} credentials must contain only {field}"+ )+ secret = credentials[field]+ if not isinstance(secret, str) or not secret.strip():+ _raise_host_error(+ f"{normalized_provider} credential must be a non-empty string"+ )+ normalized_secret = secret.strip()+ account = await _validate_repository_pat_for_write(+ normalized_provider,+ normalized_secret,+ )+ stored = (+ deepcopy(self._stored_config)+ if self._stored_config is not None+ else _initial_stored_config(collection_enabled=False)+ )+ provider_credentials = _normalize_provider_credentials(+ stored.get("provider_credentials", {})+ )+ provider_credentials[normalized_provider] = {field: normalized_secret}+ stored["provider_credentials"] = provider_credentials+ stored, candidate = _prepare_stored_config(stored)+ payload = _serialize_config(stored)+ if self._stored_config is None:+ await self._apply_configuration_locked(candidate, stored, payload)+ else:+ try:+ _publish_yaml(self._config_path, payload)+ except Exception as exc:+ raise _as_host_error(+ exc,+ "PersonalContext provider credential could not be saved",+ status_name="CONTEXT_PROACTIVE_FILE_EXECUTION_ERROR",+ ) from None+ self._stored_config = deepcopy(stored)+ return _repository_authorization_result(+ normalized_provider,+ "authorized",+ account=account,+ )+ if normalized_provider != "feishu":+ _raise_host_error("provider does not support authorization")+ if credentials is not None:+ _raise_host_error("feishu authorization does not accept credentials")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)+ return await self._personal_context.authorize_provider(+ normalized_provider+ )except asyncio.CancelledError:raiseexcept BaseException as exc:@@ -880,9 +1522,10 @@ class PersonalContextHostAPI:self._config = configself._stored_config = storedconfig = self._config- if config is None or not config.enabled:+ if config is None or not config.collection_enabled:returntry:+ self._refresh_embedding_configuration()await self._personal_context.activate_runtime()except BaseException as exc:if isinstance(exc, asyncio.CancelledError):@@ -892,11 +1535,11 @@ class PersonalContextHostAPI:) from Noneasync def is_runtime_enabled(self) -> bool:- """Return the loaded Host switch without reading or parsing YAML."""+ """Return the loaded Agent-use switch without reading or parsing YAML."""async with self._operation_lock:config = self._config- return bool(config is not None and config.enabled)+ return bool(config is not None and config.agent_use_enabled)async def get_status(self) -> PersonalContext.Status:"""Return the Core's bounded, credential-free status snapshot."""@@ -940,7 +1583,8 @@ class PersonalContextHostAPI:self._stored_config = Nonereturnawait self._personal_context.set_configuration(previous)- if was_active and previous.enabled:+ if was_active and previous.collection_enabled:+ self._refresh_embedding_configuration()await self._personal_context.activate_runtime()self._config = previousself._stored_config = deepcopy(previous_stored)diff --git a/jiuwenswarm/server/personal_context/ws_handler.py b/jiuwenswarm/server/personal_context/ws_handler.pyindex 8907be9fa2..cf7902e24d 100644--- a/jiuwenswarm/server/personal_context/ws_handler.py+++ b/jiuwenswarm/server/personal_context/ws_handler.py@@ -32,8 +32,10 @@ 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_START_COLLECTION,+ ReqMethod.PERSONAL_CONTEXT_RUNTIME_STOP_COLLECTION,+ ReqMethod.PERSONAL_CONTEXT_RUNTIME_START_AGENT_USE,+ ReqMethod.PERSONAL_CONTEXT_RUNTIME_STOP_AGENT_USE,ReqMethod.PERSONAL_CONTEXT_RUNTIME_GET_CONFIG,ReqMethod.PERSONAL_CONTEXT_RUNTIME_PATCH_CONFIG,ReqMethod.PERSONAL_CONTEXT_RUNTIME_SELECT_MODEL,@@ -43,16 +45,17 @@ PERSONAL_CONTEXT_REQUEST_METHODS = frozenset(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_STOP_RUN,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_STREAM_TREE,ReqMethod.PERSONAL_CONTEXT_CONTEXT_SEARCH_PAGES,ReqMethod.PERSONAL_CONTEXT_CONTEXT_GET_NODE,+ ReqMethod.PERSONAL_CONTEXT_CONTEXT_GET_SOURCE,})@@ -154,35 +157,51 @@ async def _stream_graph(ws: Any,request: AgentRequest,send_lock: asyncio.Lock,+ *,+ tree: bool = False,) -> None:- graph = await host.get_graph()+ root_id = request.params.get("root_id")+ if root_id is not None and (not isinstance(root_id, str) or not root_id.strip()):+ raise ValueError("root_id must be null or a non-empty string")+ depth = request.params.get("depth", 3)+ if type(depth) is not int or not 1 <= depth <= 10:+ raise ValueError("depth must be an integer between 1 and 10")+ normalized_root = root_id.strip() if isinstance(root_id, str) else None+ if tree:+ graph = await host.get_tree(root_id=normalized_root, depth=depth)+ else:+ graph = await host.get_graph(root_id=normalized_root, depth=depth)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",+ "event_type": "personal_context.context.start","context_ready": bool(graph.get("context_ready")),+ "root_id": normalized_root,+ "depth": depth,}]- 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)- )+ for start in range(0, len(nodes), 200):+ stop = start + 200+ events.append(+ {+ "event_type": "personal_context.context.nodes",+ "nodes": nodes[start:stop],+ }+ )+ for start in range(0, len(edges), 200):+ stop = start + 200+ events.append(+ {+ "event_type": "personal_context.context.edges",+ "edges": edges[start:stop],+ }+ )events.append({- "event_type": "personal_context.graph.end",+ "event_type": "personal_context.context.end","node_count": len(nodes),"edge_count": len(edges),}@@ -213,12 +232,16 @@ async def _execute(params = request.paramsif 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)+ if method == ReqMethod.PERSONAL_CONTEXT_RUNTIME_START_COLLECTION:+ return _payload(await host.set_collection_enabled(True))+ if method == ReqMethod.PERSONAL_CONTEXT_RUNTIME_STOP_COLLECTION:+ return _payload(await host.set_collection_enabled(False))+ if method == ReqMethod.PERSONAL_CONTEXT_RUNTIME_START_AGENT_USE:+ result = await host.set_agent_use_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)+ if method == ReqMethod.PERSONAL_CONTEXT_RUNTIME_STOP_AGENT_USE:+ result = await host.set_agent_use_enabled(False)await _notify_runtime_enabled(runtime_enabled_changed, False)return _payload(result)if method == ReqMethod.PERSONAL_CONTEXT_RUNTIME_GET_CONFIG:@@ -248,35 +271,38 @@ async def _execute(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,+ await host.set_fetch_service_enabled(+ _text(params, "service_id"),+ method == ReqMethod.PERSONAL_CONTEXT_FETCH_START_SERVICE,)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_STOP_RUN:+ return await host.stop_fetch_run(_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"))+ cast(str | None, params.get("service_id")),+ run_id=cast(str | None, params.get("run_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"))+ credentials = params.get("credentials")+ if credentials is not None and not isinstance(credentials, dict):+ raise ValueError("credentials must be an object")+ return await host.authorize_provider(+ _text(params, "provider"),+ credentials=cast(dict[str, object] | None, credentials),+ )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"))+ if method == ReqMethod.PERSONAL_CONTEXT_CONTEXT_GET_SOURCE:+ return await host.get_source(_text(params, "source_id"))raise ValueError("unknown PersonalContext method")@@ -313,12 +339,21 @@ async def handle_personal_context_request("""Execute one parsed PersonalContext request without introducing a PersonalContext wire protocol."""try:- if request.req_method == ReqMethod.PERSONAL_CONTEXT_CONTEXT_STREAM_GRAPH:+ if request.req_method in {+ ReqMethod.PERSONAL_CONTEXT_CONTEXT_STREAM_GRAPH,+ ReqMethod.PERSONAL_CONTEXT_CONTEXT_STREAM_TREE,+ }:if not request.is_stream:- raise ValueError(- "personal_context.context.stream_graph requires is_stream=true"- )- await _stream_graph(host, ws, request, send_lock)+ raise ValueError(f"{request.req_method.value} requires is_stream=true")+ await _stream_graph(+ host,+ ws,+ request,+ send_lock,+ tree=(+ request.req_method == ReqMethod.PERSONAL_CONTEXT_CONTEXT_STREAM_TREE+ ),+ )returnawait _send_result(ws,diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.pyindex fe4c1fc64f..0909e5c108 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py@@ -1171,6 +1171,9 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):mode,)+ self._last_mode = mode+ await self._sync_personal_context_rail(mode)+async def _reconcile_evolution_rails(self) -> None:"""Keep evolution rails disabled for every Code adapter reload."""if (diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex aceed4b644..110b3dcd84 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -10130,11 +10130,12 @@ class JiuWenSwarmDeepAdapter: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+ supported_modes = (+ {"code", "code.normal", "code.plan"}+ if self._is_code_agent+ else {"agent", "agent.fast", "agent.plan"})+ return mode in supported_modes and self._personal_context_runtime_enableddef set_personal_context_runtime_enabled(self, enabled: bool) -> None:"""Store the Host switch snapshot for this adapter and future sessions."""@@ -10167,7 +10168,7 @@ class JiuWenSwarmDeepAdapter:raise cancelledasync def _sync_personal_context_rail(self, mode: str) -> None:- """Register or detach the fixed-path Core Rail for normal agent modes."""+ """Register or detach the shared fixed-path Core Rail for work and code modes."""async with self._personal_context_rail_lock:enabled = self._personal_context_rail_enabled(mode)diff --git a/tests/agents/swarm/test_swarm_assembly.py b/tests/agents/swarm/test_swarm_assembly.pyindex fe3989d160..9984a61afa 100644--- a/tests/agents/swarm/test_swarm_assembly.py+++ b/tests/agents/swarm/test_swarm_assembly.py@@ -203,6 +203,7 @@ _TEAM_SHARED_RAIL_NAMES: frozenset[str] = frozenset(registry.AVATAR_PROMPT,registry.TEAM_WORKSPACE_REPORT_PATH,registry.CONTEXT_PROCESSOR,+ registry.PERSONAL_CONTEXT,registry.PLUGIN_RAILS,registry.SKILL_RETRIEVAL_PROMPT,registry.SYMPHONY_ORCHESTRATION_PROMPT,@@ -523,7 +524,7 @@ def test_build_member_capability_specs_rail_names(assert _TEAM_SHARED_RAIL_NAMES <= rail_namesassert extra_rails <= rail_names- assert len(_TEAM_SHARED_RAIL_NAMES) == 17+ assert len(_TEAM_SHARED_RAIL_NAMES) == 18assert rail_names == expecteddisabled_tools = next(spec for spec in rails_specs if spec.type == registry.DISABLED_TOOLSdiff --git a/tests/unit_tests/agentserver/test_personal_context_rail_registration.py b/tests/unit_tests/agentserver/test_personal_context_rail_registration.pyindex 75d970dce1..97c84d1960 100644--- a/tests/unit_tests/agentserver/test_personal_context_rail_registration.py+++ b/tests/unit_tests/agentserver/test_personal_context_rail_registration.py@@ -310,3 +310,61 @@ class _FakeManagedAgent:self.refresh_count += 1if self.fail_refresh:raise RuntimeError("refresh failed")+[email protected]("normal,plan", [("code.normal", "code.plan")])+async def test_code_modes_use_shared_personal_context_switch_and_cleanup(monkeypatch, normal, plan):+ from jiuwenswarm.server.runtime.agent_adapter.interface_code import JiuwenSwarmCodeAdapter++ agent = _FakeAgent()+ adapter = object.__new__(JiuwenSwarmCodeAdapter)+ adapter.__dict__.update(_adapter(agent, runtime_enabled=False).__dict__)+ adapter._is_code_agent = True+ # Existing unrelated code rails are already registered for this lightweight instance.+ for name in ("_task_planning_rail", "_skill_evolution_rail", "_evolution_interrupt_rail"):+ setattr(adapter, name, None)+ for name in ("_subagent_rail", "_project_memory_rail", "_coding_memory_rail"):+ setattr(adapter, name, object())+ monkeypatch.setattr(interface_deep, "PersonalContextRail", _FakeRail)+ await adapter._update_rails_for_mode(normal)+ assert agent.register_attempts == []+ assert adapter._last_mode == normal+ adapter.set_personal_context_runtime_enabled(True)+ await adapter.refresh_personal_context_rail()+ rail = adapter._personal_context_rail+ assert rail is not None+ await adapter._update_rails_for_mode(plan)+ assert adapter._personal_context_rail is rail+ assert agent.register_attempts == [rail]+ adapter.set_personal_context_runtime_enabled(False)+ await adapter.refresh_personal_context_rail()+ assert adapter._personal_context_rail is None+ 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+ await adapter._sync_personal_context_rail("cleanup")+ assert adapter._personal_context_rail is None+++async def test_code_session_adapters_receive_existing_switch_broadcast(monkeypatch):+ from jiuwenswarm.server.runtime.agent_adapter.interface_code import JiuwenSwarmCodeAdapter++ root = object.__new__(JiuwenSwarmCodeAdapter)+ child = object.__new__(JiuwenSwarmCodeAdapter)+ for adapter in (root, child):+ adapter.__dict__.update(_adapter(_FakeAgent(), runtime_enabled=False).__dict__)+ adapter._is_code_agent = True+ adapter._last_mode = "code.normal"+ root._is_session_scoped_adapter = False+ root._session_adapters = {"code-session": child}+ 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+ assert child._personal_context_rail is not None+ root.set_personal_context_runtime_enabled(False)+ await root.refresh_personal_context_rail()+ assert root._personal_context_rail is None+ assert child._personal_context_rail is Nonediff --git a/tests/unit_tests/agentserver/test_personal_context_websocket_api.py b/tests/unit_tests/agentserver/test_personal_context_websocket_api.pyindex 0ee21999da..4583941daf 100644--- a/tests/unit_tests/agentserver/test_personal_context_websocket_api.py+++ b/tests/unit_tests/agentserver/test_personal_context_websocket_api.py@@ -49,6 +49,11 @@ class _FakeHost:"nodes": [],"edges": [],}+ self.tree: dict[str, object] = {+ "context_ready": True,+ "nodes": [],+ "edges": [],+ }def _record(self, name: str, value: object, result: object) -> object:if self.failure is not None:@@ -59,11 +64,18 @@ class _FakeHost: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]:+ async def set_collection_enabled(self, enabled: bool) -> dict[str, object]:return self._record(- "set_runtime_enabled",+ "set_collection_enabled",enabled,- {"enabled": enabled},+ {"collection_enabled": enabled},+ )++ async def set_agent_use_enabled(self, enabled: bool) -> dict[str, object]:+ return self._record(+ "set_agent_use_enabled",+ enabled,+ {"agent_use_enabled": enabled},)async def get_runtime_config(self) -> dict[str, object]:@@ -115,13 +127,12 @@ class _FakeHost:{"service_id": service_id, **patch},)- async def set_fetching(+ async def set_fetch_service_enabled(self,- *,+ service_id: str,enabled: bool,- service_id: str | None = None,) -> None:- self._record("set_fetching", (enabled, service_id), None)+ self._record("set_fetch_service_enabled", (service_id, enabled), None)async def run_fetch(self,@@ -137,13 +148,18 @@ class _FakeHost:},)+ async def stop_fetch_run(self, service_id: str) -> dict[str, object]:+ return self._record("stop_fetch_run", service_id, {"ok": True})+async def get_fetch_run_status(self,service_id: str | None = None,+ *,+ run_id: str | None = None,) -> dict[str, object]:return self._record("get_fetch_run_status",- service_id,+ (service_id, run_id) if run_id is not None else service_id,{"service_id": service_id, "state": "RUNNING"},)@@ -160,10 +176,14 @@ class _FakeHost:},)- async def authorize_provider(self, provider: str) -> dict[str, object]:+ async def authorize_provider(+ self,+ provider: str,+ credentials: dict[str, object] | None = None,+ ) -> dict[str, object]:return self._record("authorize_provider",- provider,+ (provider, credentials),{"provider": provider,"state": "authorized",@@ -173,8 +193,21 @@ class _FakeHost:},)- async def get_graph(self) -> dict[str, object]:- return self._record("get_graph", None, self.graph)+ async def get_graph(+ self,+ *,+ root_id: str | None = None,+ depth: int = 3,+ ) -> dict[str, object]:+ return self._record("get_graph", (root_id, depth), self.graph)++ async def get_tree(+ self,+ *,+ root_id: str | None = None,+ depth: int = 3,+ ) -> dict[str, object]:+ return self._record("get_tree", (root_id, depth), self.tree)async def search_graph(self, query: str) -> dict[str, object]:return self._record("search_graph", query, {"results": []})@@ -186,6 +219,13 @@ class _FakeHost:{"node_id": node_id, "markdown": "# PersonalContext\n"},)+ async def get_source(self, source_id: str) -> dict[str, object]:+ return self._record(+ "get_source",+ source_id,+ {"source_id": source_id, "title": "Source"},+ )+class _FakeWebSocket:def __init__(self) -> None:@@ -251,15 +291,56 @@ SERVICE_PAYLOAD: dict[str, object] = {"enabled": True,"interval_seconds": 3_600,"max_items_per_run": 100,+ "time_range": {"mode": "all"},"source": {"root_dir": "D:/context"},"credentials": {},}+GITHUB_SERVICE_PAYLOAD: dict[str, object] = {+ "service_id": "github-main",+ "provider": "github",+ "enabled": False,+ "interval_seconds": 3_600,+ "max_items_per_run": 100,+ "time_range": {"mode": "all"},+ "source": {+ "owner": "openjiuwen",+ "repo": "personal-context",+ "resources": ["readme", "issues", "pull_requests", "commits", "code"],+ },+}+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_START_COLLECTION,+ {},+ "set_collection_enabled",+ True,+ None,+ ),+ (+ ReqMethod.PERSONAL_CONTEXT_RUNTIME_STOP_COLLECTION,+ {},+ "set_collection_enabled",+ False,+ None,+ ),+ (+ ReqMethod.PERSONAL_CONTEXT_RUNTIME_START_AGENT_USE,+ {},+ "set_agent_use_enabled",+ True,+ None,+ ),+ (+ ReqMethod.PERSONAL_CONTEXT_RUNTIME_STOP_AGENT_USE,+ {},+ "set_agent_use_enabled",+ False,+ None,+ ),(ReqMethod.PERSONAL_CONTEXT_RUNTIME_GET_CONFIG,{},@@ -312,29 +393,15 @@ PERSONAL_CONTEXT_HOST_CALLS = [(ReqMethod.PERSONAL_CONTEXT_FETCH_START_SERVICE,{"service_id": " github-main "},- "set_fetching",- (True, "github-main"),+ "set_fetch_service_enabled",+ ("github-main", True),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),+ "set_fetch_service_enabled",+ ("github-main", False),None,),(ReqMethod.PERSONAL_CONTEXT_FETCH_RUN_ALL, {}, "run_fetch", None, None),@@ -345,6 +412,13 @@ PERSONAL_CONTEXT_HOST_CALLS = ["github-main",None,),+ (+ ReqMethod.PERSONAL_CONTEXT_FETCH_STOP_RUN,+ {"service_id": "github-main"},+ "stop_fetch_run",+ "github-main",+ {"ok": True},+ ),(ReqMethod.PERSONAL_CONTEXT_FETCH_GET_RUN_STATUS,{"service_id": "github-main"},@@ -369,7 +443,7 @@ PERSONAL_CONTEXT_HOST_CALLS = [ReqMethod.PERSONAL_CONTEXT_FETCH_AUTHORIZE_PROVIDER,{"provider": "feishu"},"authorize_provider",- "feishu",+ ("feishu", None),{"provider": "feishu","state": "authorized",@@ -378,6 +452,19 @@ PERSONAL_CONTEXT_HOST_CALLS = ["error": None,},),+ (+ ReqMethod.PERSONAL_CONTEXT_FETCH_AUTHORIZE_PROVIDER,+ {"provider": "github", "credentials": {"token": "github-canary"}},+ "authorize_provider",+ ("github", {"token": "github-canary"}),+ {+ "provider": "github",+ "state": "authorized",+ "verification_url": None,+ "expires_at": None,+ "error": None,+ },+ ),(ReqMethod.PERSONAL_CONTEXT_CONTEXT_SEARCH_PAGES,{"query": " 主动上下文 "},@@ -392,14 +479,21 @@ PERSONAL_CONTEXT_HOST_CALLS = ["page:topics/personal_context.md",None,),+ (+ ReqMethod.PERSONAL_CONTEXT_CONTEXT_GET_SOURCE,+ {"source_id": "src_abc"},+ "get_source",+ "src_abc",+ {"source_id": "src_abc", "title": "Source"},+ ),]-def test_agentserver_registers_exact_22_personal_context_methods() -> None:+def test_agentserver_registers_canonical_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+ assert len(server_module._PERSONAL_CONTEXT_REQ_METHODS) == 25@pytest.mark.asyncio@@ -437,8 +531,8 @@ async def test_non_graph_methods_call_exact_host_operation(@pytest.mark.parametrize(("method", "enabled"),[- (ReqMethod.PERSONAL_CONTEXT_RUNTIME_START, True),- (ReqMethod.PERSONAL_CONTEXT_RUNTIME_STOP, False),+ (ReqMethod.PERSONAL_CONTEXT_RUNTIME_START_AGENT_USE, True),+ (ReqMethod.PERSONAL_CONTEXT_RUNTIME_STOP_AGENT_USE, False),],)async def test_runtime_switch_notifies_agent_manager_after_host_success(@@ -461,7 +555,7 @@ async def test_runtime_switch_notifies_agent_manager_after_host_success(runtime_enabled_changed=_runtime_changed,)- assert host.calls == [("set_runtime_enabled", enabled)]+ assert host.calls == [("set_agent_use_enabled", enabled)]assert notifications == [(enabled, host.calls)]assert ws.sent[0]["status"] == "succeeded"@@ -479,12 +573,12 @@ async def test_runtime_switch_callback_failure_is_fail_open(await handle_personal_context_request(host,ws,- _request(ReqMethod.PERSONAL_CONTEXT_RUNTIME_START),+ _request(ReqMethod.PERSONAL_CONTEXT_RUNTIME_START_AGENT_USE),asyncio.Lock(),runtime_enabled_changed=_failed_callback,)- assert host.calls == [("set_runtime_enabled", True)]+ assert host.calls == [("set_agent_use_enabled", True)]assert ws.sent[0]["status"] == "succeeded"@@ -522,6 +616,12 @@ async def test_runtime_switch_callback_failure_is_fail_open({"service_id": "local-files-1"},("delete_fetch_service", "local-files-1"),),+ (+ ReqMethod.PERSONAL_CONTEXT_FETCH_STOP_RUN,+ {"service_id": " "},+ {"service_id": "local-files-1"},+ ("stop_fetch_run", "local-files-1"),+ ),(ReqMethod.PERSONAL_CONTEXT_FETCH_GET_AUTHORIZATION_STATUS,{},@@ -540,6 +640,12 @@ async def test_runtime_switch_callback_failure_is_fail_open({"provider": "feishu"},("get_authorization_status", "feishu"),),+ (+ ReqMethod.PERSONAL_CONTEXT_FETCH_AUTHORIZE_PROVIDER,+ {"provider": "github", "credentials": "not-an-object"},+ {"provider": "github", "credentials": {"token": "github-canary"}},+ ("authorize_provider", ("github", {"token": "github-canary"})),+ ),],)async def test_source_management_bad_request_keeps_connection_available(@@ -577,6 +683,28 @@ async def test_source_management_bad_request_keeps_connection_available(assert ws.sent[1]["is_final"] is True+async def test_repository_create_payload_is_public_and_has_no_credentials(+ capture_wire: None,+) -> None:+ _server_instance, host = _server()+ ws = _FakeWebSocket()++ assert "credentials" not in GITHUB_SERVICE_PAYLOAD+ await handle_personal_context_request(+ host,+ ws,+ _request(+ ReqMethod.PERSONAL_CONTEXT_FETCH_CREATE_SERVICE,+ {"service": GITHUB_SERVICE_PAYLOAD},+ ),+ asyncio.Lock(),+ )++ assert host.calls == [("create_fetch_service", GITHUB_SERVICE_PAYLOAD)]+ assert "credentials" not in ws.sent[0]["body"]["result"]++@pytest.mark.asyncioasync def test_select_model_rejects_old_origin_index_parameter(capture_wire: None,@@ -631,11 +759,15 @@ async def test_graph_stream_is_bounded_ordered_and_final(await handle_personal_context_request(host,ws,- _request(ReqMethod.PERSONAL_CONTEXT_CONTEXT_STREAM_GRAPH, is_stream=True),+ _request(+ ReqMethod.PERSONAL_CONTEXT_CONTEXT_STREAM_GRAPH,+ {"root_id": None, "depth": 3},+ is_stream=True,+ ),asyncio.Lock(),)- assert host.calls == [("get_graph", None)]+ assert host.calls == [("get_graph", (None, 3))]assert [frame["sequence"] for frame in ws.sent] == list(range(7))assert [frame["is_final"] for frame in ws.sent] == [False,@@ -651,18 +783,66 @@ async def test_graph_stream_is_bounded_ordered_and_final(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",+ "personal_context.context.start",+ "personal_context.context.nodes",+ "personal_context.context.nodes",+ "personal_context.context.nodes",+ "personal_context.context.edges",+ "personal_context.context.edges",+ "personal_context.context.end",]+ assert events[0]["root_id"] is None+ assert events[0]["depth"] == 3+ assert all(len(event.get("nodes", [])) <= 200 for event in events)+ assert all(len(event.get("edges", [])) <= 200 for event in events)assert events[-1]["node_count"] == 450assert events[-1]["edge_count"] == 250+async def test_tree_stream_passes_root_and_depth_to_host(capture_wire: None) -> None:+ _server_instance, host = _server()+ ws = _FakeWebSocket()++ await handle_personal_context_request(+ host,+ ws,+ _request(+ ReqMethod.PERSONAL_CONTEXT_CONTEXT_STREAM_TREE,+ {"root_id": "page:topics", "depth": 1},+ is_stream=True,+ ),+ asyncio.Lock(),+ )++ assert host.calls == [("get_tree", ("page:topics", 1))]+ assert ws.sent[0]["body"]["delta"]["event_type"] == "personal_context.context.start"+ assert ws.sent[0]["body"]["delta"]["root_id"] == "page:topics"+ assert ws.sent[0]["body"]["delta"]["depth"] == 1+ assert ws.sent[-1]["is_final"] is True+++async def test_graph_rejects_depth_above_contract_limit(capture_wire: None) -> None:+ _server_instance, host = _server()+ ws = _FakeWebSocket()++ await handle_personal_context_request(+ host,+ ws,+ _request(+ ReqMethod.PERSONAL_CONTEXT_CONTEXT_STREAM_GRAPH,+ {"root_id": None, "depth": 11},+ is_stream=True,+ ),+ asyncio.Lock(),+ )++ assert host.calls == []+ assert ws.sent[0]["status"] == "failed"+ assert ws.sent[0]["body"]["details"]["code"] == "BAD_REQUEST"++@pytest.mark.asyncioasync def test_graph_requires_stream_request(capture_wire: None) -> None:server, host = _server()@@ -760,7 +940,7 @@ async def test_personal_context_failure_keeps_connection_and_ordinary_request_avawait server._handle_message(ws,- _canonical("personal_context.runtime.start"),+ _canonical("personal_context.runtime.start_collection"),asyncio.Lock(),)@@ -842,3 +1022,20 @@ async def test_handler_propagates_cancellation(capture_wire: None) -> None:_request(ReqMethod.PERSONAL_CONTEXT_RUNTIME_STATUS),asyncio.Lock(),)+++async def test_run_history_query_forwards_run_id(capture_wire):+ _server_instance, host = _server()+ ws = _FakeWebSocket()+ await handle_personal_context_request(+ host,+ ws,+ _request(+ ReqMethod.PERSONAL_CONTEXT_FETCH_GET_RUN_STATUS,+ {"service_id": "notes", "run_id": "a" * 32},+ ),+ asyncio.Lock(),+ )+ assert host.calls == [("get_fetch_run_status", ("notes", "a" * 32))]+ assert ws.sent[0]["status"] == "succeeded"diff --git a/tests/unit_tests/channel/test_web_channel_personal_context_payload.py b/tests/unit_tests/channel/test_web_channel_personal_context_payload.pynew file mode 100644index 0000000000..d2501891e4--- /dev/null+++ b/tests/unit_tests/channel/test_web_channel_personal_context_payload.py@@ -0,0 +1,63 @@+from __future__ import annotations++import pytest++from jiuwenswarm.common.schema.message import Message+from jiuwenswarm.gateway.channel_manager.web.web_connect import WebChannel+++ ("event_name", "payload"),+ [+ (+ "personal_context.context.start",+ {"event_type": "personal_context.context.start", "context_ready": True},+ ),+ (+ "personal_context.context.nodes",+ {+ "event_type": "personal_context.context.nodes",+ "nodes": [{"id": "page:description.md"}],+ },+ ),+ (+ "personal_context.context.edges",+ {+ "event_type": "personal_context.context.edges",+ "edges": [+ {+ "source": "page:description.md",+ "target": "page:sources/description.md",+ }+ ],+ },+ ),+ (+ "personal_context.context.end",+ {+ "event_type": "personal_context.context.end",+ "node_count": 3,+ "edge_count": 2,+ },+ ),+ ],+)+def test_personal_context_structure_events_preserve_complete_payload(+ event_name: str,+ payload: dict[str, object],+) -> None:+ message = Message(+ id="personal-context-structure",+ type="event",+ channel_id="web",+ session_id="personal-context-session",+ params={},+ timestamp=0.0,+ ok=True,+ payload=payload,+ )++ assert WebChannel._build_event_payload(message, event_name) == {+ **payload,+ "session_id": "personal-context-session",+ }diff --git a/tests/unit_tests/evolution/test_message.py b/tests/unit_tests/evolution/test_message.pyindex 3301ae0ce8..f3f7941bef 100644--- a/tests/unit_tests/evolution/test_message.py+++ b/tests/unit_tests/evolution/test_message.py@@ -35,8 +35,10 @@ class TestReqMethod:}assert methods == {"personal_context.runtime.status",- "personal_context.runtime.start",- "personal_context.runtime.stop",+ "personal_context.runtime.start_collection",+ "personal_context.runtime.stop_collection",+ "personal_context.runtime.start_agent_use",+ "personal_context.runtime.stop_agent_use","personal_context.runtime.get_config","personal_context.runtime.patch_config","personal_context.runtime.select_model",@@ -45,19 +47,21 @@ class TestReqMethod:"personal_context.fetch.delete_service","personal_context.fetch.patch_service","personal_context.fetch.start_service",+ "personal_context.fetch.stop_run","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.stop_run","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.stream_tree","personal_context.context.search_pages","personal_context.context.get_node",+ "personal_context.context.get_source",}- assert len(methods) == 22+ assert len(methods) == 25@staticmethoddef test_session_methods():diff --git a/tests/unit_tests/personal_context/test_closed_class_inventory.py b/tests/unit_tests/personal_context/test_closed_class_inventory.pyindex 73882d2c01..ef5a2d876f 100644--- a/tests/unit_tests/personal_context/test_closed_class_inventory.py+++ b/tests/unit_tests/personal_context/test_closed_class_inventory.py@@ -3,9 +3,9 @@from __future__ import annotationsimport ast+import importlib.utilfrom pathlib import Path-ROOT = Path(__file__).parents[3]HOST = ROOT / "jiuwenswarm" / "server" / "personal_context"LEGACY_PACKAGE = ROOT / "jiuwenswarm" / "server" / "proactive_harness"@@ -13,7 +13,8 @@ LEGACY_PACKAGE = ROOT / "jiuwenswarm" / "server" / "proactive_harness"def _classes(path: Path) -> set[str]:result: set[str] = set()- for file in sorted(path.rglob("*.py")):+ files = [path] if path.is_file() else sorted(path.rglob("*.py"))+ for file in files:tree = ast.parse(file.read_text(encoding="utf-8"))result.update(node.name for node in ast.walk(tree) if isinstance(node, ast.ClassDef)@@ -25,6 +26,16 @@ def test_jiuwen_swarm_declares_only_the_host_class() -> None:assert _classes(HOST) == {"PersonalContextHostAPI"}+def test_embedded_personal_context_has_exactly_eighteen_production_classes() -> None:+ core_spec = importlib.util.find_spec("openjiuwen.harness.personal_context")+ rail_spec = importlib.util.find_spec("openjiuwen.harness.rails.personal_context")+ assert core_spec is not None and core_spec.origin is not None+ assert rail_spec is not None and rail_spec.origin is not None+ core = Path(core_spec.origin).parent+ core_rail = Path(rail_spec.origin)+ assert len(_classes(core) | _classes(core_rail) | _classes(HOST)) == 18++def test_legacy_host_package_is_removed() -> None:assert not any(LEGACY_PACKAGE.rglob("*.py"))diff --git a/tests/unit_tests/personal_context/test_host_api.py b/tests/unit_tests/personal_context/test_host_api.pyindex c14e01d645..27b06a2e40 100644--- a/tests/unit_tests/personal_context/test_host_api.py+++ b/tests/unit_tests/personal_context/test_host_api.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport astimport asyncioimport contextlib+import inspectfrom copy import deepcopyfrom pathlib import Pathfrom types import SimpleNamespace@@ -25,16 +26,41 @@ HOST_API_PATH = (/ "host_api.py")+# 未配置投影的默认策略/模型取决于「本机有没有可用默认模型」,而 get_default_models()+# 底层是 get_config(),每次都重新读盘,且在 settings 初始化前后可能解析到不同的 config.yaml。+# 所以不能用 import 期快照当期望值——那会让断言随运行环境(甚至随同一进程的不同阶段)漂移。+# 需要默认值的用例一律用下面两个 helper 把模型列表钉死。UNCONFIGURED_PROJECTION = {"configured": False,- "enabled": False,- "fetching_enabled": False,+ "collection_enabled": False,+ "agent_use_enabled": False,"strategy_profile": "rules",+ "max_pages_per_directory": 20,+ "max_subdirectories_per_directory": 20,"model_index": None,+ "model_id": None,"fetch_services": [],}+def _model_entry(model_name: str, *, provider: str = "OpenAI") -> dict[str, object]:+ return {+ "model_client_config": {+ "client_provider": provider,+ "api_key": "key",+ "api_base": "https://example.invalid/v1",+ "model_name": model_name,+ },+ "model_config_obj": {"temperature": 0.2},+ }+++def _pin_models(+ monkeypatch: pytest.MonkeyPatch, entries: list[dict[str, object]]+) -> None:+ monkeypatch.setattr(host_module, "get_default_models", lambda: entries)++def _config(*,enabled: bool = True,@@ -44,8 +70,8 @@ def _config() -> dict[str, object]:root = root_dir or Path.cwd()return {- "enabled": enabled,- "fetching_enabled": fetching_enabled,+ "collection_enabled": enabled,+ "agent_use_enabled": fetching_enabled,"strategy_profile": "rules","fetch_services": [{@@ -53,6 +79,7 @@ def _config("provider": "local_files","enabled": True,"interval_seconds": interval,+ "time_range": {"mode": "all"},"source": {"root_dir": str(root)},"credentials": {},}@@ -67,6 +94,7 @@ def _local_service(service_id: str, root_dir: Path) -> dict[str, object]:"enabled": True,"interval_seconds": 60.0,"max_items_per_run": None,+ "time_range": {"mode": "all"},"source": {"root_dir": str(root_dir)},"credentials": {},}@@ -79,17 +107,53 @@ def _bookmark_service(service_id: str) -> dict[str, object]:"enabled": True,"interval_seconds": 60.0,"max_items_per_run": None,+ "time_range": {"mode": "all"},"source": {},"credentials": {},}+def _repository_service(service_id: str, provider: str) -> dict[str, object]:+ return {+ "service_id": service_id,+ "provider": provider,+ "enabled": True,+ "interval_seconds": 60.0,+ "max_items_per_run": None,+ "time_range": {"mode": "all"},+ "source": {+ "owner": "acme",+ "repo": "demo",+ "resources": ["readme", "issues", "pull_requests", "commits", "code"],+ },+ }+++def _repository_config(+ *,+ github_token: str = "github-current",+ gitcode_pat: str = "gitcode-current",+ services: list[dict[str, object]] | None = None,+) -> dict[str, object]:+ return {+ "collection_enabled": False,+ "agent_use_enabled": False,+ "strategy_profile": "rules",+ "model_index": None,+ "provider_credentials": {+ "github": {"token": github_token},+ "gitcode": {"pat": gitcode_pat},+ },+ "fetch_services": services or [],+ }++def _config_with_services(services: list[dict[str, object]],) -> dict[str, object]:return {- "enabled": False,- "fetching_enabled": False,+ "collection_enabled": False,+ "agent_use_enabled": False,"strategy_profile": "rules","fetch_services": services,}@@ -108,6 +172,9 @@ class FakeCore:def __init__(self) -> None:self.calls: list[tuple[str, object]] = []+ self.embedding_configurations: list[+ tuple[str | None, str | None, str | None]+ ] = []self.snapshot_result: object = object()self.snapshot_error: BaseException | None = Noneself.configured: object | None = None@@ -115,6 +182,7 @@ class FakeCore:self.deactivate_error: BaseException | None = Noneself.deactivate_changes_active_before_error = Falseself.set_error: BaseException | None = None+ self.append_service_error: BaseException | None = Noneself.activate_error: BaseException | None = Noneself.activate_started: asyncio.Event | None = Noneself.activate_release: asyncio.Event | None = None@@ -134,6 +202,15 @@ class FakeCore:self.authorization_status_started: asyncio.Event | None = Noneself.authorization_status_release: asyncio.Event | None = None+ def _set_embedding_configuration(+ self,+ *,+ model_name: str | None,+ base_url: str | None,+ api_key: str | None,+ ) -> None:+ self.embedding_configurations.append((model_name, base_url, api_key))+async def set_configuration(self, config: object) -> None:self.calls.append(("set_configuration", config))if self.set_error is not None:@@ -168,6 +245,69 @@ class FakeCore:raise errorself.active = False+ async def start_collection(self) -> None:+ self.calls.append(("start_collection", 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 stop_collection(self, *, timeout_seconds: float = 30.0) -> None:+ self.calls.append(("stop_collection", 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 start_agent_use(self) -> None:+ self.calls.append(("start_agent_use", None))++ async def stop_agent_use(self) -> None:+ self.calls.append(("stop_agent_use", None))++ async def set_fetch_service_enabled(+ self,+ service_id: str,+ enabled: bool,+ ) -> None:+ self.calls.append(("set_fetch_service_enabled", (service_id, enabled)))++ async def _append_fetch_service_config(self, service: object) -> None:+ self.calls.append(("append_fetch_service_config", service))+ assert self.configured is not None+ services = (*self.configured.fetch_services, service)+ self.configured = self.configured.model_copy(+ update={"fetch_services": services}+ )+ if self.append_service_error is not None:+ error = self.append_service_error+ self.append_service_error = None+ raise error++ async def _remove_fetch_service_config(self, service_id: str) -> None:+ self.calls.append(("remove_fetch_service_config", service_id))+ assert self.configured is not None+ services = tuple(+ service+ for service in self.configured.fetch_services+ if service.service_id != service_id+ )+ self.configured = self.configured.model_copy(+ update={"fetch_services": services}+ )+async def snapshot(self) -> object:self.calls.append(("snapshot", None))if self.snapshot_error is not None:@@ -209,6 +349,16 @@ class FakeCore:"service_ids": [service_id or "local-notes"],}+ async def stop_fetch_run(self, service_id: str) -> None:+ self.calls.append(("stop_fetch_run", service_id))++ def remove_fetch_run_history(self, service_id):+ self.calls.append(("remove_fetch_run_history", service_id))+ return [{"run_id": "retained"}]++ def restore_fetch_run_history(self, service_id, records):+ self.calls.append(("restore_fetch_run_history", (service_id, records)))+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:@@ -232,8 +382,22 @@ class FakeCore:else:self.cursor_payloads[service_id] = payload- async def get_graph(self) -> dict[str, object]:- self.calls.append(("get_graph", None))+ async def get_graph(+ self,+ *,+ root_id: str | None = None,+ depth: int = 3,+ ) -> dict[str, object]:+ self.calls.append(("get_graph", (root_id, depth)))+ return {"context_ready": True, "nodes": [], "edges": []}++ async def get_tree(+ self,+ *,+ root_id: str | None = None,+ depth: int = 3,+ ) -> dict[str, object]:+ self.calls.append(("get_tree", (root_id, depth)))return {"context_ready": True, "nodes": [], "edges": []}async def search_graph(self, query: str) -> dict[str, object]:@@ -258,6 +422,10 @@ class FakeCore:"markdown": "# 主动上下文\n",}+ async def get_source(self, source_id: str) -> dict[str, object]:+ self.calls.append(("get_source", source_id))+ return {"source_id": source_id, "title": "来源"}+@pytest.fixturedef fake_host(@@ -269,7 +437,7 @@ def fake_host(return host, fake-def test_host_module_imports_personal_context_from_harness() -> None:+def test_host_module_imports_only_personal_context_from_core() -> None:tree = ast.parse(HOST_API_PATH.read_text(encoding="utf-8"))imported: list[str] = []for node in ast.walk(tree):@@ -281,10 +449,15 @@ def test_host_module_imports_personal_context_from_harness() -> None:assert imported == ["PersonalContext"]+def test_locked_core_supports_live_fetch_service_updates() -> None:+ assert inspect.iscoroutinefunction(PersonalContext._append_fetch_service_config)+ assert inspect.iscoroutinefunction(PersonalContext._remove_fetch_service_config)++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 source.count("if not isinstance(enabled, bool):") == 3assert "type(enabled) is not bool" not in source@@ -318,6 +491,88 @@ def test_constructor_does_not_read_or_write_yaml(tmp_path: Path) -> None:assert host._config is None+ ("global_config", "expected"),+ [+ ({}, (None, None, None)),+ ({"embed": {"embed_model": "model"}}, (None, None, None)),+ (+ {+ "embed": {+ "embed_model": " embedding-model ",+ "embed_base_url": " https://embedding.invalid/v1/embeddings ",+ "embed_api_key": " top-secret ",+ }+ },+ (+ "embedding-model",+ "https://embedding.invalid/v1/embeddings",+ "top-secret",+ ),+ ),+ (+ {+ "embed": {+ "embed_model": "legacy-model",+ "embed_api_base": "https://legacy.invalid/embeddings",+ "embed_api_key": "legacy-secret",+ }+ },+ ("legacy-model", "https://legacy.invalid/embeddings", "legacy-secret"),+ ),+ ],+)+def test_global_embedding_values_require_one_complete_existing_configuration(+ monkeypatch: pytest.MonkeyPatch,+ global_config: dict[str, object],+ expected: tuple[str | None, str | None, str | None],+) -> None:+ monkeypatch.setattr(host_module, "get_config", lambda: deepcopy(global_config))+ assert host_module._global_embedding_values() == expected+++async def test_host_refreshes_global_embedding_before_activation_without_persisting_it(+ fake_host: tuple[PersonalContextHostAPI, FakeCore],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ host, core = fake_host+ values = {+ "embed_model": "embedding-model",+ "embed_base_url": "https://embedding.invalid/v1/embeddings",+ "embed_api_key": "top-secret",+ }+ monkeypatch.setattr(host_module, "get_config", lambda: {"embed": deepcopy(values)})++ await host.configure(_config(enabled=True))++ assert core.embedding_configurations == [+ ("embedding-model", "https://embedding.invalid/v1/embeddings", "top-secret")+ ]+ serialized = host._config_path.read_text(encoding="utf-8")+ core.snapshot_result = _FakeStatus()+ overview = await host.get_overview()+ assert "top-secret" not in serialized+ assert "embedding.invalid" not in serialized+ assert "top-secret" not in str(overview)+ assert "embedding.invalid" not in str(overview)++ await host.stop(timeout_seconds=1)+ values.update(+ {+ "embed_model": "new-model",+ "embed_base_url": "https://new.invalid/embeddings",+ "embed_api_key": "new-secret",+ }+ )+ await host.start()+ assert core.embedding_configurations[-1] == (+ "new-model",+ "https://new.invalid/embeddings",+ "new-secret",+ )++@pytest.mark.asyncioasync def test_start_without_yaml_keeps_host_unconfigured(tmp_path: Path) -> None:home = tmp_path / "personal_context"@@ -330,38 +585,67 @@ async def test_start_without_yaml_keeps_host_unconfigured(tmp_path: Path) -> Non@pytest.mark.asyncio[email protected]("enabled", [False, True])-async def test_runtime_enabled_projection_reads_loaded_configuration([email protected]("legacy_field", ["enabled", "fetching_enabled"])+async def test_start_rejects_yaml_with_legacy_global_switch(+ tmp_path: Path,+ legacy_field: str,+) -> None:+ home = tmp_path / "personal_context"+ home.mkdir()+ raw = _config(enabled=False, root_dir=tmp_path)+ raw[legacy_field] = False+ (home / "personal_context.yaml").write_text(+ yaml.safe_dump(raw, sort_keys=False),+ encoding="utf-8",+ )+ host = PersonalContextHostAPI(home=home)++ with pytest.raises(PersonalContext.Error):+ await host.start()++ assert host._config is None+ assert host._stored_config is None++[email protected]("agent_use_enabled", [False, True])+async def test_agent_use_projection_reads_loaded_configuration(fake_host: tuple[PersonalContextHostAPI, FakeCore],tmp_path: Path,- enabled: bool,+ agent_use_enabled: bool,) -> None:host, _core = fake_hostassert await host.is_runtime_enabled() is False- await host.configure(_config(enabled=enabled, root_dir=tmp_path))+ await host.configure(_config(fetching_enabled=agent_use_enabled, root_dir=tmp_path))- assert await host.is_runtime_enabled() is enabled+ assert await host.is_runtime_enabled() is agent_use_enabled@pytest.mark.asyncioasync def test_unconfigured_projection_and_stop_are_read_only_until_first_start(fake_host: tuple[PersonalContextHostAPI, FakeCore],+ monkeypatch: pytest.MonkeyPatch,) -> None:+ # 钉死「一个可用模型都没有」,断言才是确定的:此时策略必须回落 rules、模型置空。+ _pin_models(monkeypatch, [])host, core = fake_hostassert await host.get_runtime_config() == UNCONFIGURED_PROJECTION- assert await host.set_runtime_enabled(False) == UNCONFIGURED_PROJECTION+ assert await host.set_collection_enabled(False) == UNCONFIGURED_PROJECTIONassert not host._home.exists()assert core.calls == []- started = await host.set_runtime_enabled(True)+ started = await host.set_collection_enabled(True)- assert started["enabled"] is True- assert started["fetching_enabled"] is False+ assert started["collection_enabled"] is True+ assert started["agent_use_enabled"] is Falseassert started["strategy_profile"] == "rules"+ assert started["max_pages_per_directory"] == 20+ assert started["max_subdirectories_per_directory"] == 20assert started["model_index"] is None+ assert started["model_id"] is Noneassert started["fetch_services"] == []assert host._config_path.is_file()assert [name for name, _value in core.calls] == [@@ -371,6 +655,65 @@ async def test_unconfigured_projection_and_stop_are_read_only_until_first_start(assert core.active is True+async def test_unconfigured_projection_defaults_to_first_usable_model(+ fake_host: tuple[PersonalContextHostAPI, FakeCore],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """有可用模型时,未配置投影默认走智能体并指向首个可用模型。"""++ _pin_models(+ monkeypatch,+ [_model_entry("model-a"), _model_entry("model-b")],+ )+ host, _core = fake_host++ projection = await host.get_runtime_config()++ assert projection["strategy_profile"] == "agent"+ assert projection["model_index"] == 0+ assert projection["model_id"] == "openai:model-a"++ # 不可用条目(model_name 为空)必须被跳过,不能当默认值落到坏条目上。+ _pin_models(+ monkeypatch,+ [_model_entry(""), _model_entry("model-b")],+ )++ fallback = await host.get_runtime_config()++ assert fallback["strategy_profile"] == "agent"+ assert fallback["model_index"] == 1+ assert fallback["model_id"] == "openai:model-b"+++async def test_directory_capacity_is_persisted_and_projected_but_not_runtime_patchable(+ fake_host: tuple[PersonalContextHostAPI, FakeCore],+ tmp_path: Path,+) -> None:+ host, _core = fake_host+ config = _config(root_dir=tmp_path)+ config.update(+ max_pages_per_directory=7,+ max_subdirectories_per_directory=9,+ )++ await host.configure(config)++ projected = await host.get_runtime_config()+ assert projected["max_pages_per_directory"] == 7+ assert projected["max_subdirectories_per_directory"] == 9+ persisted = yaml.safe_load(host._config_path.read_text(encoding="utf-8"))+ assert persisted["max_pages_per_directory"] == 7+ assert persisted["max_subdirectories_per_directory"] == 9++ with pytest.raises(PersonalContext.Error):+ await host.patch_runtime_config({"max_pages_per_directory": 8})++ assert await host.get_runtime_config() == projected++@pytest.mark.asyncio@pytest.mark.parametrize("failure_attribute", ["set_error", "activate_error"])async def test_first_start_core_failure_rolls_back_to_unconfigured(@@ -381,7 +724,7 @@ async def test_first_start_core_failure_rolls_back_to_unconfigured(setattr(core, failure_attribute, RuntimeError("first start failed"))with pytest.raises(PersonalContext.Error):- await host.set_runtime_enabled(True)+ await host.set_collection_enabled(True)expected_calls = ["set_configuration", "deactivate_runtime"]if failure_attribute == "activate_error":@@ -406,7 +749,7 @@ async def test_first_start_cancellation_rolls_back_to_unconfigured(core.activate_started = asyncio.Event()core.activate_release = asyncio.Event()- task = asyncio.create_task(host.set_runtime_enabled(True))+ task = asyncio.create_task(host.set_collection_enabled(True))await asyncio.sleep(0)if task.done():await task@@ -439,7 +782,7 @@ async def test_first_start_replace_failure_stops_core_and_removes_temporary_filemonkeypatch.setattr(host_module, "_replace_yaml", fail_replace)with pytest.raises(PersonalContext.Error):- await host.set_runtime_enabled(True)+ await host.set_collection_enabled(True)assert [name for name, _value in core.calls] == ["set_configuration",@@ -467,7 +810,7 @@ async def test_first_start_replace_and_rollback_stop_failure_keeps_core_referencmonkeypatch.setattr(host_module, "_replace_yaml", fail_replace)with pytest.raises(PersonalContext.Error) as caught:- await host.set_runtime_enabled(True)+ await host.set_collection_enabled(True)assert caught.value.status.name == "CONTEXT_PROACTIVE_STATE_INVALID"assert "previous configuration could not be restored" in str(caught.value)@@ -495,7 +838,7 @@ async def test_configure_writes_yaml_and_starts_enabled_core(saved = yaml.safe_load((host._home / "personal_context.yaml").read_text(encoding="utf-8"))- assert saved["enabled"] is True+ assert saved["collection_enabled"] is Trueassert [name for name, _ in core.calls] == ["set_configuration", "activate_runtime"]@@ -610,10 +953,22 @@ async def test_get_graph_delegates_to_core() -> None:host, core = fake_host- result = await host.get_graph()+ result = await host.get_graph(root_id="page:topics/description.md", depth=1)++ assert result == {"context_ready": True, "nodes": [], "edges": []}+ assert core.calls == [("get_graph", ("page:topics/description.md", 1))]+++async def test_get_tree_delegates_to_core(+ fake_host: tuple[PersonalContextHostAPI, FakeCore],+) -> None:+ host, core = fake_host++ result = await host.get_tree(root_id=None, depth=3)assert result == {"context_ready": True, "nodes": [], "edges": []}- assert core.calls == [("get_graph", None)]+ assert core.calls == [("get_tree", (None, 3))]@pytest.mark.asyncio@@ -640,6 +995,18 @@ async def test_get_graph_page_delegates_to_core(assert core.calls == [("get_graph_page", "page:topics/personal_context.md")]+async def test_get_source_delegates_to_core(+ fake_host: tuple[PersonalContextHostAPI, FakeCore],+) -> None:+ host, core = fake_host++ result = await host.get_source("src_abc")++ assert result["source_id"] == "src_abc"+ assert core.calls == [("get_source", "src_abc")]++@pytest.mark.asyncioasync def test_configure_same_semantics_only_replaces_yaml(fake_host: tuple[PersonalContextHostAPI, FakeCore], tmp_path: Path@@ -715,7 +1082,7 @@ async def test_get_status_does_not_wait_for_operation_lock(@pytest.mark.asyncio-async def test_get_overview_returns_full_config_including_credentials(+async def test_get_overview_omits_provider_and_service_credentials(fake_host: tuple[PersonalContextHostAPI, FakeCore],tmp_path: Path,) -> None:@@ -729,16 +1096,515 @@ async def test_get_overview_returns_full_config_including_credentials("resources": ["readme", "issues", "pull_requests", "commits", "code"],}service["credentials"] = {"token": "plain-token"}+ config["provider_credentials"] = {+ "github": {"token": "current-token"},+ "gitcode": {"pat": "current-pat"},+ }core.snapshot_result = _FakeStatus()- await host.configure(config)- overview = await host.get_overview()+ await host.configure(config)+ overview = await host.get_overview()++ assert overview["configured"] is True+ assert "provider_credentials" not in overview["config"]+ assert "credentials" not in overview["config"]["fetch_services"][0]+ assert overview["status"] == {"state": "RUNNING", "configured": True}+ saved = yaml.safe_load(host._config_path.read_text(encoding="utf-8"))+ assert saved["provider_credentials"]["github"]["token"] == "current-token"+ assert saved["fetch_services"][0]["credentials"]["token"] == "plain-token"+ assert core.configured.fetch_services[0].credentials == {"token": "plain-token"}+ assert not hasattr(core.configured, "provider_credentials")+++ "provider_credentials",+ [+ {"github": {"token": ""}},+ {"gitcode": {"pat": ""}},+ {"github": {"pat": "wrong-field"}},+ {"gitcode": {"token": "wrong-field"}},+ {"github": {"token": "ok", "extra": "no"}},+ {"unknown": {"token": "no"}},+ {"github": "not-an-object"},+ ],+)+def test_provider_credentials_reject_invalid_closed_shapes(+ provider_credentials: object,+) -> None:+ config = _repository_config()+ config["provider_credentials"] = provider_credentials++ with pytest.raises(PersonalContext.Error):+ host_module._prepare_stored_config(config)+++async def test_all_public_configuration_projections_are_deep_and_credential_free(+ fake_host: tuple[PersonalContextHostAPI, FakeCore],+ tmp_path: Path,+) -> None:+ host, _core = fake_host+ github = _repository_service("github-old", "github")+ github["credentials"] = {"token": "github-snapshot"}+ await host.configure(_repository_config(services=[github]))++ runtime = await host.get_runtime_config()+ listed = await host.list_fetch_services()+ patched_runtime = await host.patch_runtime_config({"strategy_profile": "rules"})+ created = await host.create_fetch_service(_bookmark_service("bookmarks"))+ patched_service = await host.patch_fetch_service(+ "bookmarks", {"interval_seconds": 120.0}+ )++ for projection in (runtime, patched_runtime):+ assert "provider_credentials" not in projection+ assert all(+ "credentials" not in service for service in projection["fetch_services"]+ )+ assert all("credentials" not in service for service in listed)+ assert "credentials" not in created+ assert "credentials" not in patched_service+ runtime["fetch_services"][0]["source"]["owner"] = "mutated"+ reread = await host.get_runtime_config()+ reread_github = next(+ service+ for service in reread["fetch_services"]+ if service["service_id"] == "github-old"+ )+ assert reread_github["source"]["owner"] == "acme"+ assert (+ host._stored_config["provider_credentials"]["github"]["token"]+ == "github-current"+ )+ stored_github = next(+ service+ for service in host._stored_config["fetch_services"]+ if service["service_id"] == "github-old"+ )+ assert stored_github["credentials"]["token"] == "github-snapshot"++[email protected]("include_current", [False, True])+async def test_start_loads_existing_repository_snapshots_without_network_validation(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ include_current: bool,+) -> None:+ home = tmp_path / "personal_context"+ home.mkdir()+ service = _repository_service("github-old", "github")+ service["credentials"] = {"token": "old-service-token"}+ config = _repository_config(services=[service])+ if not include_current:+ config["provider_credentials"] = {}+ (home / "personal_context.yaml").write_text(+ yaml.safe_dump(config, sort_keys=False),+ encoding="utf-8",+ )+ host = PersonalContextHostAPI(home=home)+ core = FakeCore()+ monkeypatch.setattr(host, "_personal_context", core)++ async def unexpected_validation(_provider: str, _secret: str) -> dict[str, str]:+ raise AssertionError("startup must not validate repository PATs")++ monkeypatch.setattr(+ host_module, "_validate_repository_pat", unexpected_validation, raising=False+ )++ await host.start()++ assert core.configured.fetch_services[0].credentials == {+ "token": "old-service-token"+ }+ assert host._stored_config["fetch_services"][0]["credentials"] == {+ "token": "old-service-token"+ }+++ ("provider", "secret", "url", "payload"),+ [+ (+ "github",+ "github-canary",+ "https://api.github.com/user",+ {"login": "octocat", "name": "Octo Cat", "ignored": "secret"},+ ),+ (+ "gitcode",+ "gitcode-canary",+ "https://api.gitcode.com/api/v5/user",+ {"login": "gitcoder", "name": "Git Coder", "ignored": "secret"},+ ),+ ],+)+async def test_repository_pat_validation_uses_fixed_endpoint_and_bearer(+ monkeypatch: pytest.MonkeyPatch,+ provider: str,+ secret: str,+ url: str,+ payload: dict[str, object],+) -> None:+ calls: list[tuple[str, dict[str, str]]] = []++ class Response:+ status_code = 200+ headers = {"Content-Length": "128", "Content-Type": "application/json"}+ content = b"{}"++ def json(self) -> dict[str, object]:+ return dict(payload)++ class Client:+ def __init__(self, *, timeout: object, follow_redirects: bool) -> None:+ assert timeout is not None+ assert follow_redirects is False++ async def __aenter__(self) -> "Client":+ return self++ async def __aexit__(self, *_args: object) -> None:+ return None++ async def get(self, request_url: str, *, headers: dict[str, str]) -> Response:+ calls.append((request_url, dict(headers)))+ return Response()++ monkeypatch.setattr(host_module.httpx, "AsyncClient", Client)++ account = await host_module._validate_repository_pat(provider, secret)++ assert account == {"login": payload["login"], "display_name": payload["name"]}+ assert calls == [+ (url, {"Accept": "application/json", "Authorization": f"Bearer {secret}"})+ ]+++async def test_repository_pat_first_authorization_creates_minimal_stopped_configuration(+ fake_host: tuple[PersonalContextHostAPI, FakeCore],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ host, core = fake_host+ validations: list[tuple[str, str]] = []++ async def validate(provider: str, secret: str) -> dict[str, str]:+ validations.append((provider, secret))+ return {"login": "account", "display_name": "Account"}++ monkeypatch.setattr(+ host_module, "_validate_repository_pat", validate, raising=False+ )+ # 首次授权会落一份最小未启用配置,其默认策略/模型同样取决于模型列表——钉死才确定。+ _pin_models(monkeypatch, [])++ result = await host.authorize_provider(+ "github", credentials={"token": "first-token"}+ )++ assert result == {+ "provider": "github",+ "state": "authorized",+ "account": {"login": "account", "display_name": "Account"},+ "verification_url": None,+ "expires_at": None,+ "error": None,+ }+ assert validations == [("github", "first-token")]+ assert [name for name, _value in core.calls] == ["set_configuration"]+ saved = yaml.safe_load(host._config_path.read_text(encoding="utf-8"))+ assert saved == {+ "collection_enabled": False,+ "agent_use_enabled": False,+ "strategy_profile": "rules",+ "max_pages_per_directory": 20,+ "max_subdirectories_per_directory": 20,+ "fetch_services": [],+ "model_index": None,+ "model_id": None,+ "provider_credentials": {"github": {"token": "first-token"}},+ }+ assert "provider_credentials" not in await host.get_runtime_config()+++async def test_repository_pat_replacement_only_changes_future_service_snapshots(+ fake_host: tuple[PersonalContextHostAPI, FakeCore],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ host, core = fake_host++ async def validate(provider: str, secret: str) -> dict[str, str]:+ return {"login": f"{provider}-{secret}", "display_name": "Account"}++ monkeypatch.setattr(+ host_module, "_validate_repository_pat", validate, raising=False+ )+ await host.authorize_provider("github", credentials={"token": "old-token"})+ old_public = await host.create_fetch_service(+ _repository_service("github-old", "github")+ )+ old_snapshot = host._stored_config["fetch_services"][0]["credentials"]["token"]+ core.calls.clear()++ await host.authorize_provider("github", credentials={"token": "new-token"})++ assert core.calls == []+ assert old_public.get("credentials") is None+ assert (+ host._stored_config["fetch_services"][0]["credentials"]["token"]+ == old_snapshot+ == "old-token"+ )+ new_public = await host.create_fetch_service(+ _repository_service("github-new", "github")+ )+ snapshots = {+ service["service_id"]: service["credentials"]["token"]+ for service in host._stored_config["fetch_services"]+ }+ assert snapshots == {"github-new": "new-token", "github-old": "old-token"}+ assert "credentials" not in new_public+++async def test_repository_authorization_and_creation_reject_unsafe_credentials(+ fake_host: tuple[PersonalContextHostAPI, FakeCore],+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ host, core = fake_host++ async def validate(_provider: str, _secret: str) -> dict[str, str]:+ raise RuntimeError("validation failed")++ monkeypatch.setattr(+ host_module, "_validate_repository_pat", validate, raising=False+ )+ for provider, credentials in (+ ("github", None),+ ("github", {"pat": "wrong"}),+ ("gitcode", {"token": "wrong"}),+ ("feishu", {"token": "not-allowed"}),+ ):+ with pytest.raises((PersonalContext.Error, TypeError)):+ await host.authorize_provider(provider, credentials=credentials)+ assert core.calls == []++ await host.configure(_config(enabled=False, root_dir=tmp_path))+ service = _repository_service("github-explicit", "github")+ service["credentials"] = {"token": "request-secret"}+ before = host._config_path.read_bytes()+ with pytest.raises(PersonalContext.Error):+ await host.create_fetch_service(service)+ with pytest.raises(PersonalContext.Error):+ await host.create_fetch_service(+ _repository_service("github-no-current", "github")+ )+ assert host._config_path.read_bytes() == before+++async def test_repository_authorization_status_is_live_bounded_and_credential_free(+ fake_host: tuple[PersonalContextHostAPI, FakeCore],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ host, _core = fake_host+ assert await host.get_authorization_status("github") == {+ "provider": "github",+ "state": "not_authorized",+ "account": None,+ "verification_url": None,+ "expires_at": None,+ "error": None,+ }++ should_fail = False++ async def validate(_provider: str, _secret: str) -> dict[str, str]:+ if should_fail:+ raise RuntimeError("sensitive credential/network detail")+ return {"login": "account", "display_name": "Account"}++ monkeypatch.setattr(+ host_module, "_validate_repository_pat", validate, raising=False+ )+ await host.authorize_provider("gitcode", credentials={"pat": "current-pat"})+ authorized = await host.get_authorization_status("gitcode")+ assert authorized["state"] == "authorized"+ assert authorized["account"] == {"login": "account", "display_name": "Account"}+ assert set(authorized) == {+ "provider",+ "state",+ "account",+ "verification_url",+ "expires_at",+ "error",+ }++ should_fail = True+ failed = await host.get_authorization_status("gitcode")+ assert failed["state"] == "authorization_failed"+ assert failed["account"] is None+ assert failed["error"] == "credential verification failed"+ assert "sensitive" not in repr(failed)+++async def test_invalid_or_unpublishable_pat_replacement_preserves_old_state(+ fake_host: tuple[PersonalContextHostAPI, FakeCore],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ host, core = fake_host++ async def validate(_provider: str, secret: str) -> dict[str, str]:+ if secret == "invalid-token":+ raise RuntimeError("invalid secret detail")+ return {"login": "account", "display_name": "Account"}++ monkeypatch.setattr(+ host_module, "_validate_repository_pat", validate, raising=False+ )+ await host.authorize_provider("github", credentials={"token": "old-token"})+ old_yaml = host._config_path.read_bytes()+ old_stored = deepcopy(host._stored_config)+ core.calls.clear()++ with pytest.raises((PersonalContext.Error, RuntimeError)):+ await host.authorize_provider("github", credentials={"token": "invalid-token"})+ assert host._config_path.read_bytes() == old_yaml+ assert host._stored_config == old_stored+ assert core.calls == []++ 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.authorize_provider("github", credentials={"token": "new-token"})+ assert host._config_path.read_bytes() == old_yaml+ assert host._stored_config == old_stored+ assert core.calls == []+ assert list(host._home.glob(".*.tmp")) == []+++async def test_repository_service_revalidation_failure_changes_nothing(+ fake_host: tuple[PersonalContextHostAPI, FakeCore],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ host, core = fake_host+ should_fail = False++ async def validate(_provider: str, _secret: str) -> dict[str, str]:+ if should_fail:+ raise RuntimeError("current PAT is no longer valid")+ return {"login": "account", "display_name": "Account"}++ monkeypatch.setattr(+ host_module, "_validate_repository_pat", validate, raising=False+ )+ await host.authorize_provider("github", credentials={"token": "current-token"})+ old_yaml = host._config_path.read_bytes()+ old_stored = deepcopy(host._stored_config)+ core.calls.clear()+ should_fail = True++ with pytest.raises((PersonalContext.Error, RuntimeError)):+ await host.create_fetch_service(_repository_service("github-failed", "github"))++ assert host._config_path.read_bytes() == old_yaml+ assert host._stored_config == old_stored+ assert core.calls == []+++async def test_manual_service_pat_edit_requires_new_host_start_and_does_not_validate(+ fake_host: tuple[PersonalContextHostAPI, FakeCore],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ host, _core = fake_host++ async def validate(_provider: str, _secret: str) -> dict[str, str]:+ return {"login": "account", "display_name": "Account"}++ monkeypatch.setattr(+ host_module, "_validate_repository_pat", validate, raising=False+ )+ await host.authorize_provider("github", credentials={"token": "current-token"})+ await host.create_fetch_service(_repository_service("github-manual", "github"))+ assert (+ host._stored_config["fetch_services"][0]["credentials"]["token"]+ == "current-token"+ )++ edited = yaml.safe_load(host._config_path.read_text(encoding="utf-8"))+ edited["fetch_services"][0]["credentials"]["token"] = "manual-token"+ host._config_path.write_text(+ yaml.safe_dump(edited, sort_keys=False), encoding="utf-8"+ )+ assert (+ host._stored_config["fetch_services"][0]["credentials"]["token"]+ == "current-token"+ )++ restarted = PersonalContextHostAPI(home=host._home)+ restarted_core = FakeCore()+ monkeypatch.setattr(restarted, "_personal_context", restarted_core)++ async def unexpected_validation(_provider: str, _secret: str) -> dict[str, str]:+ raise AssertionError(+ "startup must not validate manually edited service snapshots"+ )++ monkeypatch.setattr(host_module, "_validate_repository_pat", unexpected_validation)+ await restarted.start()+ assert (+ restarted._stored_config["fetch_services"][0]["credentials"]["token"]+ == "manual-token"+ )+ assert restarted_core.configured.fetch_services[0].credentials == {+ "token": "manual-token"+ }+++async def test_pat_http_failure_does_not_expose_response_or_secret(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ class Response:+ status_code = 401+ headers = {"Content-Length": "64"}+ content = b'{"token":"response-secret","message":"bad"}'++ def json(self) -> dict[str, object]:+ return {"token": "response-secret", "message": "bad"}- assert overview["configured"] is True- assert overview["config"]["fetch_services"][0]["credentials"] == {- "token": "plain-token"- }- assert overview["status"] == {"state": "RUNNING", "configured": True}+ class Client:+ def __init__(self, **_kwargs: object) -> None:+ pass++ async def __aenter__(self) -> "Client":+ return self++ async def __aexit__(self, *_args: object) -> None:+ return None++ async def get(self, _url: str, *, headers: dict[str, str]) -> Response:+ assert headers["Authorization"] == "Bearer request-secret"+ return Response()++ monkeypatch.setattr(host_module.httpx, "AsyncClient", Client)++ with pytest.raises(PersonalContext.Error) as caught:+ await host_module._validate_repository_pat("github", "request-secret")++ serialized = str(caught.value)+ assert "request-secret" not in serialized+ assert "response-secret" not in serialized@pytest.mark.asyncio@@ -774,6 +1640,29 @@ async def test_patch_runtime_configuration_changes_only_strategy_profile(assert after["model_index"] == 0+async def test_patch_runtime_configuration_persists_both_global_switches(+ fake_host: tuple[PersonalContextHostAPI, FakeCore],+ tmp_path: Path,+) -> None:+ host, _core = fake_host+ await host.configure(+ _config(enabled=False, fetching_enabled=False, root_dir=tmp_path)+ )++ after = await host.patch_runtime_config(+ {"collection_enabled": True, "agent_use_enabled": True}+ )++ saved = yaml.safe_load(host._config_path.read_text(encoding="utf-8"))+ assert after["collection_enabled"] is True+ assert after["agent_use_enabled"] is True+ assert saved["collection_enabled"] is True+ assert saved["agent_use_enabled"] is True+ assert "fetching_enabled" not in saved+ assert set(saved).isdisjoint({"enabled", "fetching_enabled"})++@pytest.mark.asyncioasync def test_patch_runtime_configuration_rejects_unknown_field_without_writing(fake_host: tuple[PersonalContextHostAPI, FakeCore],@@ -789,8 +1678,31 @@ async def test_patch_runtime_configuration_rejects_unknown_field_without_writingassert host._config_path.read_bytes() == before+def test_resolve_model_reference_forces_personal_context_transport_retries(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ model_entry = {+ "model_client_config": {+ "client_provider": "OpenAI",+ "api_key": "key",+ "api_base": "https://example.invalid/v1",+ "model_name": "model-a",+ "max_retries": 0,+ },+ "model_config_obj": {"temperature": 0.2},+ }+ monkeypatch.setattr(host_module, "get_default_models", lambda: [model_entry])++ client, request = host_module._resolve_model_reference(0)++ assert client["max_retries"] == 2+ assert request["model"] == "model-a"+ assert model_entry["model_client_config"]["max_retries"] == 0+ assert model_entry["model_client_config"]["model_name"] == "model-a"++@pytest.mark.asyncio-async def test_select_model_persists_only_model_index(+async def test_select_model_persists_index_and_stable_model_id(fake_host: tuple[PersonalContextHostAPI, FakeCore],tmp_path: Path,monkeypatch: pytest.MonkeyPatch,@@ -807,25 +1719,40 @@ async def test_select_model_persists_only_model_index("model_name": "model-a",},"model_config_obj": {"temperature": 0.2},- }+ },+ {+ "model_client_config": {+ "client_provider": "OpenAI",+ "api_key": "key",+ "api_base": "https://example.invalid/v1",+ "model_name": "model-b",+ },+ "model_config_obj": {"temperature": 0.3},+ },],)host, core = fake_hostawait host.configure(_config(enabled=False, root_dir=tmp_path))+ # 配置期已把「首个可用模型」写进 model_index,因此这里必须切到另一个下标,+ # 否则 select_model 是幂等空操作、不会触发 set_configuration。+ assert host._stored_config["model_index"] == 0core.calls.clear()- result = await host.select_model(model_index=0)+ result = await host.select_model(model_index=1)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 result["model_index"] == 1+ assert saved["model_index"] == 1+ assert saved["model_id"] == "openai:model-b"assert "model_origin_index" not in savedassert "model_client" not in savedassert "model_request" not in saved- assert applied.model_request.model_name == "model-a"+ assert applied.model_request.model_name == "model-b"+ assert applied.model_client.max_retries == 2+ assert "max_retries" not in saved@pytest.mark.asyncio@@ -877,25 +1804,42 @@ async def test_select_model_rejects_missing_model_without_writing(@pytest.mark.asyncio-async def test_runtime_model_strategy_requires_selected_model_without_writing(+async def test_runtime_model_strategy_without_usable_model_falls_back_to_rules(fake_host: tuple[PersonalContextHostAPI, FakeCore],tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,) -> None:+ """没有任何可用模型时,策略不能停在 balanced/agent。++ Core 要求 model_client 与 model_request 同时提供,所以写配置时降级为 rules,+ 而不是把整份配置判为非法——一个失效的模型不该卡死整个个人上下文。+ """++ monkeypatch.setattr(host_module, "get_default_models", lambda: [])host, _core = fake_hostawait 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"})+ patched = await host.patch_runtime_config({"strategy_profile": "agent"})- assert host._config_path.read_bytes() == before+ assert patched["strategy_profile"] == "rules"+ assert patched["model_index"] is None+ assert patched["model_id"] is None+ saved = yaml.safe_load(host._config_path.read_text(encoding="utf-8"))+ assert saved["strategy_profile"] == "rules"+ assert saved["model_index"] is None+ assert saved["model_id"] is None@pytest.mark.asyncio-async def test_start_rejects_saved_model_index_when_model_was_removed(+async def test_start_self_heals_saved_model_that_was_removed(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,) -> None:+ """磁盘上存的模型已被删除时,启动不报错:清空下标并把策略降回 rules。++ 否则一个失效的 model_index 会让整份配置校验失败,用户再也起不来。+ """+home = tmp_path / "personal_context"home.mkdir()stored = _config(enabled=True, root_dir=tmp_path)@@ -908,15 +1852,106 @@ async def test_start_rejects_saved_model_index_when_model_was_removed(monkeypatch.setattr(host_module, "get_default_models", lambda: [])host = PersonalContextHostAPI(home=home)- with pytest.raises(PersonalContext.Error):- await host.start()+ await host.start()- assert host._config is None- assert host._stored_config is None+ assert host._stored_config is not None+ assert host._stored_config["strategy_profile"] == "rules"+ assert host._stored_config["model_index"] is None+ assert host._stored_config["model_id"] is None+ assert host._config is not None+ assert host._config.collection_enabled is True+++async def test_start_uses_stable_model_id_after_model_list_reorder(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """models.list 顺序变化后,稳定 ID 必须优先于过期的 model_index。"""++ def _entry(model_name: str) -> dict[str, object]:+ return {+ "model_client_config": {+ "client_provider": "OpenAI",+ "api_key": "key",+ "api_base": "https://example.invalid/v1",+ "model_name": model_name,+ },+ "model_config_obj": {"temperature": 0.2},+ }++ home = tmp_path / "personal_context"+ home.mkdir()+ stored = _config(enabled=True, root_dir=tmp_path)+ stored["strategy_profile"] = "balanced"+ stored["model_index"] = 1+ stored["model_id"] = "openai:model-a"+ (home / "personal_context.yaml").write_text(+ yaml.safe_dump(stored, sort_keys=False),+ encoding="utf-8",+ )+ monkeypatch.setattr(+ host_module,+ "get_default_models",+ lambda: [_entry("model-b"), _entry("model-a")],+ )+ host = PersonalContextHostAPI(home=home)++ await host.start()++ assert host._stored_config is not None+ assert host._stored_config["model_index"] == 1+ assert host._stored_config["model_id"] == "openai:model-a"+ assert host._config is not None+ assert host._config.model_request.model_name == "model-a"+++async def test_start_recovers_when_stable_model_id_is_removed(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """model_id 已删除时不能信任过期下标,必须回退首个可用模型。"""++ def _entry(model_name: str) -> dict[str, object]:+ return {+ "model_client_config": {+ "client_provider": "OpenAI",+ "api_key": "key",+ "api_base": "https://example.invalid/v1",+ "model_name": model_name,+ },+ "model_config_obj": {"temperature": 0.2},+ }++ home = tmp_path / "personal_context"+ home.mkdir()+ stored = _config(enabled=True, root_dir=tmp_path)+ stored["strategy_profile"] = "balanced"+ stored["model_index"] = 1+ stored["model_id"] = "openai:model-removed"+ (home / "personal_context.yaml").write_text(+ yaml.safe_dump(stored, sort_keys=False),+ encoding="utf-8",+ )+ monkeypatch.setattr(+ host_module,+ "get_default_models",+ lambda: [_entry("model-a"), _entry("model-b")],+ )+ host = PersonalContextHostAPI(home=home)++ await host.start()++ assert host._stored_config is not None+ assert host._stored_config["model_index"] == 0+ assert host._stored_config["model_id"] == "openai:model-a"+ assert host._config is not None+ assert host._config.model_request.model_name == "model-a"@pytest.mark.asyncio-async def test_set_runtime_enabled_persists_and_applies_switch(+async def test_set_collection_enabled_persists_and_applies_switch(fake_host: tuple[PersonalContextHostAPI, FakeCore],tmp_path: Path,) -> None:@@ -925,14 +1960,17 @@ async def test_set_runtime_enabled_persists_and_applies_switch(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)+ started = await host.set_collection_enabled(True)+ stopped = await host.set_collection_enabled(False)- assert started["enabled"] is True- assert stopped["enabled"] is False+ assert started["collection_enabled"] is True+ assert stopped["collection_enabled"] is Falsesaved = 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+ assert saved["collection_enabled"] is False+ assert core.calls == [+ ("start_collection", None),+ ("stop_collection", 30.0),+ ]@pytest.mark.asyncio@@ -955,17 +1993,12 @@ async def test_same_enabled_candidate_restarts_stopped_runtime_before_yaml_publimonkeypatch.setattr(host_module, "_replace_yaml", record_replace)- result = await host.set_runtime_enabled(True)+ result = await host.set_collection_enabled(True)- assert result["enabled"] is True+ assert result["collection_enabled"] is Trueassert core.active is Trueassert active_at_replace == [True]- assert [name for name, _ in core.calls] == [- "snapshot",- "deactivate_runtime",- "set_configuration",- "activate_runtime",- ]+ assert core.calls == [("start_collection", None)]@pytest.mark.asyncio@@ -988,29 +2021,22 @@ async def test_same_disabled_candidate_stops_unexpected_active_runtime_before_pumonkeypatch.setattr(host_module, "_replace_yaml", record_replace)- result = await host.set_runtime_enabled(False)+ result = await host.set_collection_enabled(False)- assert result["enabled"] is False+ assert result["collection_enabled"] is Falseassert core.active is False- assert active_at_replace == [False]- assert [name for name, _ in core.calls] == [- "snapshot",- "deactivate_runtime",- "set_configuration",- ]+ assert active_at_replace == [True]+ assert core.calls == [("stop_collection", 30.0)]@pytest.mark.asyncio-async def test_snapshot_failure_aborts_before_staging_or_runtime_changes(+async def test_collection_hot_switch_does_not_depend_on_snapshot(fake_host: tuple[PersonalContextHostAPI, FakeCore],tmp_path: Path,monkeypatch: pytest.MonkeyPatch,) -> None:host, core = fake_hostawait host.configure(_config(enabled=True, root_dir=tmp_path))- old_yaml = host._config_path.read_bytes()- old_config = host._config- old_stored = host._stored_configcore.calls.clear()core.snapshot_error = RuntimeError("sensitive snapshot detail")stage_calls: list[tuple[Path, bytes]] = []@@ -1022,17 +2048,14 @@ async def test_snapshot_failure_aborts_before_staging_or_runtime_changes(monkeypatch.setattr(host_module, "_stage_yaml", record_stage)- with pytest.raises(PersonalContext.Error) as caught:- await host.set_runtime_enabled(False)+ result = await host.set_collection_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 result["collection_enabled"] is False+ assert core.calls == [("stop_collection", 30.0)]+ assert core.active is False+ assert len(stage_calls) == 1+ assert host._config is not None+ assert host._config.collection_enabled is Falseassert list(host._home.glob(".*.tmp")) == []@@ -1047,15 +2070,15 @@ async def test_disable_publishes_false_before_waiting_for_core_stop(core.deactivate_started = asyncio.Event()core.deactivate_release = asyncio.Event()- task = asyncio.create_task(host.set_runtime_enabled(False))+ task = asyncio.create_task(host.set_collection_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 saved_while_waiting["collection_enabled"] is Falseassert host._stored_config is not None- assert host._stored_config["enabled"] is True+ assert host._stored_config["collection_enabled"] is Truecore.deactivate_release.set()stopped = await task@@ -1065,7 +2088,7 @@ async def test_disable_publishes_false_before_waiting_for_core_stop(task.cancel()with contextlib.suppress(asyncio.CancelledError):await task- assert stopped["enabled"] is False+ assert stopped["collection_enabled"] is Falseassert core.active is False@@ -1081,15 +2104,20 @@ async def test_disable_failure_restores_enabled_yaml_memory_and_runtime(old_config = host._configold_stored = deepcopy(host._stored_config)core.calls.clear()- core.set_error = RuntimeError("disabled configuration failed")+ core.deactivate_changes_active_before_error = True+ core.deactivate_error = RuntimeError("collection stop failed")with pytest.raises(PersonalContext.Error):- await host.set_runtime_enabled(False)+ await host.set_collection_enabled(False)assert host._config == old_configassert host._stored_config == old_storedassert host._config_path.read_bytes() == old_yaml- assert yaml.safe_load(old_yaml)["enabled"] is True+ assert yaml.safe_load(old_yaml)["collection_enabled"] is True+ assert core.calls == [+ ("stop_collection", 30.0),+ ("start_collection", None),+ ]assert core.active is Trueassert list(host._home.glob(".*.tmp")) == []@@ -1109,11 +2137,13 @@ async def test_disable_cancellation_restores_enabled_yaml_memory_and_runtime(core.deactivate_started = asyncio.Event()core.deactivate_release = asyncio.Event()- task = asyncio.create_task(host.set_runtime_enabled(False))+ task = asyncio.create_task(host.set_collection_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"]+ yaml.safe_load(host._config_path.read_text(encoding="utf-8"))[+ "collection_enabled"+ ]is False)task.cancel()@@ -1149,7 +2179,7 @@ async def test_runtime_start_failure_rolls_back_file_and_memory(core.activate_error = RuntimeError("start failed")with pytest.raises(PersonalContext.Error):- await host.set_runtime_enabled(True)+ await host.set_collection_enabled(True)assert host._config == old_configassert host._stored_config == old_stored@@ -1169,7 +2199,7 @@ async def test_runtime_operations_reject_unconfigured_host(@pytest.mark.asyncio-async def test_list_fetch_services_combines_config_state_and_error(+async def test_list_fetch_services_returns_configuration_without_runtime_state(fake_host: tuple[PersonalContextHostAPI, FakeCore],tmp_path: Path,) -> None:@@ -1189,12 +2219,11 @@ async def test_list_fetch_services_combines_config_state_and_error("enabled": True,"interval_seconds": 60.0,"max_items_per_run": None,+ "time_range": {"mode": "all"},"source": {"root_dir": str(tmp_path)},- "credentials": {},- "state": "RUNNING",- "last_error": "last failure",}]+ assert core.calls[-1] != ("snapshot", None)@pytest.mark.asyncio@@ -1214,6 +2243,7 @@ async def test_create_fetch_service_normalizes_and_publishes_yaml_immediately(assert created["service_id"] == "local-created"assert created["provider"] == "local_files"+ assert created["time_range"] == {"mode": "all"}saved = yaml.safe_load(host._config_path.read_text(encoding="utf-8"))assert [service["service_id"] for service in saved["fetch_services"]] == ["local-created",@@ -1221,6 +2251,62 @@ async def test_create_fetch_service_normalizes_and_publishes_yaml_immediately(]+async def test_create_fetch_service_hot_appends_without_restarting_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.calls.clear()++ created = await host.create_fetch_service(_bookmark_service("bookmarks-created"))++ assert created["service_id"] == "bookmarks-created"+ assert [name for name, _value in core.calls] == ["append_fetch_service_config"]+ assert all(+ name not in {"deactivate_runtime", "set_configuration", "activate_runtime"}+ for name, _value in core.calls+ )+++async def test_create_and_patch_fetch_service_persist_normalized_time_range(+ fake_host: tuple[PersonalContextHostAPI, FakeCore],+ tmp_path: Path,+) -> None:+ host, _core = fake_host+ await host.configure(_config(enabled=False, root_dir=tmp_path))+ service = _bookmark_service("recent-bookmarks")+ service["time_range"] = {"mode": "recent", "recent_days": 3}++ created = await host.create_fetch_service(service)+ patched = await host.patch_fetch_service(+ "recent-bookmarks",+ {+ "time_range": {+ "mode": "fixed",+ "start_at": "2026-08-01T00:00:00+08:00",+ "end_at": "2026-08-11T00:00:00+08:00",+ }+ },+ )++ assert created["time_range"] == {"mode": "recent", "recent_days": 3}+ assert patched["time_range"] == {+ "mode": "fixed",+ "start_at": "2026-07-31T16:00:00Z",+ "end_at": "2026-08-10T16:00:00Z",+ }+ saved = yaml.safe_load(host._config_path.read_text(encoding="utf-8"))+ saved_service = next(+ item+ for item in saved["fetch_services"]+ if item["service_id"] == "recent-bookmarks"+ )+ assert saved_service["time_range"] == patched["time_range"]++@pytest.mark.asyncioasync def test_create_fetch_service_rejects_duplicate_and_unknown_provider(fake_host: tuple[PersonalContextHostAPI, FakeCore],@@ -1288,7 +2374,7 @@ async def test_create_fetch_service_apply_failure_restores_yaml_memory_and_core(old_yaml = host._config_path.read_bytes()old_config = host._configold_stored = deepcopy(host._stored_config)- core.set_error = RuntimeError("candidate set failed")+ core.append_service_error = RuntimeError("candidate append failed")with pytest.raises(PersonalContext.Error):await host.create_fetch_service(_bookmark_service("bookmarks-00"))@@ -1309,7 +2395,7 @@ async def test_create_fetch_service_cancellation_restores_yaml_memory_and_core(old_yaml = host._config_path.read_bytes()old_config = host._configold_stored = deepcopy(host._stored_config)- core.set_error = asyncio.CancelledError()+ core.append_service_error = asyncio.CancelledError()task = asyncio.create_task(host.create_fetch_service(_bookmark_service("bookmarks-00"))@@ -1404,6 +2490,7 @@ async def test_delete_fetch_service_removes_config_cursor_and_preserves_context(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_run_history") == 1assert [name for name, _value in core.calls].count("remove_fetch_cursor") == 1assert [name for name, _value in core.calls].count("restore_fetch_cursor") == 0@@ -1475,6 +2562,10 @@ async def test_delete_fetch_service_apply_failure_restores_cursor_and_config(with pytest.raises(PersonalContext.Error):await host.delete_fetch_service("local-notes")+ assert (+ "restore_fetch_run_history",+ ("local-notes", [{"run_id": "retained"}]),+ ) in core.callsassert core.cursor_payloads["local-notes"] == b"old-cursor"assert host._config is old_configassert host._stored_config == old_stored@@ -1597,7 +2688,7 @@ async def test_patch_existing_fetch_service_without_changing_identity(@pytest.mark.asyncio[email protected]("field", ["service_id", "provider", "enabled"])[email protected]("field", ["service_id", "provider", "enabled", "credentials"])async def test_patch_fetch_service_rejects_identity_and_switch_fields(fake_host: tuple[PersonalContextHostAPI, FakeCore],tmp_path: Path,@@ -1635,37 +2726,72 @@ async def test_patch_fetch_service_never_creates_missing_service(@pytest.mark.asyncioasync def test_get_fetch_run_status_returns_all_or_one_service(- fake_host: tuple[PersonalContextHostAPI, FakeCore],- tmp_path: Path,-) -> None:+ fake_host, tmp_path, monkeypatch+):+ from unittest.mock import AsyncMock+host, core = fake_hostawait 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 == {+ expected = {"service_id": "local-notes",- "state": "RUNNING",- "last_error": None,+ "runs": [{"run_id": "a" * 32, "run_state": "succeeded"}],}+ query = AsyncMock(return_value=expected)+ monkeypatch.setattr(core, "get_fetch_run_status", query, raising=False)+ assert await host.get_fetch_run_status("local-notes") == expected+ query.assert_awaited_with("local-notes", run_id=None)+ await host.get_fetch_run_status("local-notes", run_id="a" * 32)+ query.assert_awaited_with("local-notes", run_id="a" * 32)+ await host.get_fetch_run_status()+ query.assert_awaited_with(None, run_id=None)+++async def test_get_fetch_run_status_does_not_wait_for_configuration_lock(+ fake_host, tmp_path, monkeypatch+):+ host, core = fake_host+ await host.configure(_config(enabled=False, root_dir=tmp_path))+ expected = {"service_id": "local-notes", "runs": []}+ started = asyncio.Event()++ async def query(service_id, *, run_id=None):+ assert service_id == "local-notes"+ assert run_id is None+ started.set()+ return expected++ monkeypatch.setattr(core, "get_fetch_run_status", query, raising=False)+ await host._operation_lock.acquire()+ try:+ task = asyncio.create_task(host.get_fetch_run_status("local-notes"))+ await asyncio.wait_for(started.wait(), timeout=0.5)+ assert await task == expected+ finally:+ if host._operation_lock.locked():+ host._operation_lock.release()+++ "params",+ [+ {"run_id": "a"},+ {"service_id": "local-notes", "run_id": ""},+ {"service_id": "local-notes", "run_id": 12},+ ],+)+async def test_get_fetch_run_status_rejects_invalid_identity(+ fake_host, tmp_path, params+):+ host, _core = fake_host+ await host.configure(_config(enabled=False, root_dir=tmp_path))+ with pytest.raises(Exception):+ await host.get_fetch_run_status(**params)@pytest.mark.asyncio-async def test_set_fetching_updates_global_switch_through_full_restart(+async def test_set_agent_use_enabled_updates_only_agent_use_switch(fake_host: tuple[PersonalContextHostAPI, FakeCore],tmp_path: Path,) -> None:@@ -1674,23 +2800,18 @@ async def test_set_fetching_updates_global_switch_through_full_restart(await host.configure(_config(root_dir=tmp_path))core.calls.clear()- await host.set_fetching(enabled=False)+ await host.set_agent_use_enabled(False)- assert host._config.fetching_enabled is False+ assert host._config.agent_use_enabled is Falsesaved = 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",- ]+ assert saved["agent_use_enabled"] is False+ assert core.calls == [("stop_agent_use", None)]@pytest.mark.asyncio-async def test_set_fetching_updates_only_named_service(+async def test_set_fetch_service_enabled_updates_only_named_service(fake_host: tuple[PersonalContextHostAPI, FakeCore],tmp_path: Path,) -> None:@@ -1698,21 +2819,26 @@ async def test_set_fetching_updates_only_named_service(core.snapshot_result = _FakeStatus()await host.configure(_config(root_dir=tmp_path))- await host.set_fetching(enabled=False, service_id="local-notes")+ await host.set_fetch_service_enabled("local-notes", False)- assert host._config.fetching_enabled is True+ assert host._config.collection_enabled is True+ assert host._config.agent_use_enabled is Trueassert host._config.fetch_services[0].enabled is False+ assert core.calls[-1] == (+ "set_fetch_service_enabled",+ ("local-notes", False),+ )@pytest.mark.asyncio-async def test_set_fetching_rejects_unconfigured_or_unknown_service(+async def test_set_fetch_service_enabled_rejects_unconfigured_or_unknown_service(fake_host: tuple[PersonalContextHostAPI, FakeCore],) -> None:host, _core = fake_hostwith pytest.raises(PersonalContext.Error):- await host.set_fetching(enabled=False)+ await host.set_fetch_service_enabled("local-notes", False)with pytest.raises(PersonalContext.Error):- await host.set_fetching(enabled=False, service_id="missing")+ await host.set_fetch_service_enabled("missing", False)@pytest.mark.asyncio@@ -1761,6 +2887,73 @@ async def test_run_fetch_is_serialized_with_configuration_operations(assert core.calls == [("run_fetch", None)]+async def test_stop_fetch_run_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.stop_fetch_run(" local-notes ")++ assert result == {"ok": True}+ assert core.calls == [("stop_fetch_run", "local-notes")]+ assert host._config is configured+ assert config_path.read_bytes() == saved+++async def test_stop_fetch_run_does_not_hold_or_wait_for_configuration_lock(+ 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))+ started = asyncio.Event()+ release = asyncio.Event()++ async def stop(service_id: str) -> None:+ assert service_id == "local-notes"+ started.set()+ await release.wait()++ monkeypatch.setattr(core, "stop_fetch_run", stop)+ await host._operation_lock.acquire()+ task = asyncio.create_task(host.stop_fetch_run("local-notes"))+ try:+ await asyncio.wait_for(started.wait(), timeout=0.5)+ release.set()+ assert await task == {"ok": True}+ finally:+ release.set()+ if host._operation_lock.locked():+ host._operation_lock.release()+ if not task.done():+ task.cancel()+ with contextlib.suppress(asyncio.CancelledError):+ await task++[email protected]("service_id", ["", " ", 1, None])+async def test_stop_fetch_run_rejects_invalid_service_id(+ fake_host: tuple[PersonalContextHostAPI, FakeCore],+ service_id: object,+) -> None:+ host, core = fake_host++ with pytest.raises(PersonalContext.Error):+ await host.stop_fetch_run(service_id) # type: ignore[arg-type]++ assert core.calls == []++@pytest.mark.asyncioasync def test_stop_calls_core_and_preserves_configuration(fake_host: tuple[PersonalContextHostAPI, FakeCore], tmp_path: Path@@ -1773,7 +2966,7 @@ async def test_stop_calls_core_and_preserves_configuration(assert core.calls == [("deactivate_runtime", 1.5)]assert host._config is not Noneassert host._config_path.read_bytes() == saved- assert yaml.safe_load(saved)["enabled"] is True+ assert yaml.safe_load(saved)["collection_enabled"] is True@pytest.mark.asyncio@@ -1894,7 +3087,7 @@ async def test_missing_staged_yaml_is_reported_as_host_error(monkeypatch.setattr(host_module, "_stage_yaml", lambda *_args: None)with pytest.raises(PersonalContext.Error) as caught:- await host.set_runtime_enabled(True)+ await host.set_collection_enabled(True)assert "staging" in str(caught.value).lower()assert core.active is Falsediff --git a/tests/unit_tests/personal_context/test_host_graph.py b/tests/unit_tests/personal_context/test_host_graph.pyindex 81fc40fe02..63c8518b4f 100644--- a/tests/unit_tests/personal_context/test_host_graph.py+++ b/tests/unit_tests/personal_context/test_host_graph.py@@ -33,21 +33,19 @@ def _write_source(home: Path) -> tuple[str, Path]:def _link(page: Path, target: Path) -> str:relative = os.path.relpath(target, start=page.parent).replace("\\", "/")- return f"[PR 42]({relative})"+ return f"[来源1]({relative})"@pytest.mark.asyncio-async def test_graph_is_empty_without_root_description(tmp_path: Path) -> None:+async def test_host_graph_and_tree_are_empty_without_context(tmp_path: Path) -> None:host = PersonalContextHostAPI(home=tmp_path / "personal_context")- assert await host.get_graph() == {- "context_ready": False,- "nodes": [],- "edges": [],- }++ assert await host.get_graph() == {"context_ready": False, "nodes": [], "edges": []}+ assert await host.get_tree() == {"context_ready": False, "nodes": [], "edges": []}@pytest.mark.asyncio-async def test_host_returns_atomic_source_graph_without_rebuilding_fields(+async def test_host_delegates_breadth_first_graph_and_tree_slices(tmp_path: Path,) -> None:home = tmp_path / "personal_context"@@ -56,53 +54,39 @@ async def test_host_returns_atomic_source_graph_without_rebuilding_fields(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",+ "# Context\n\n[Topics](topics/description.md)\n",encoding="utf-8",)(context / "topics" / "description.md").write_text(- "# Topics\n\n- [Agent](agent.md)\n",+ "# 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",+ page.write_text("# Agent\n\n" + _link(page, source_path) + "\n", encoding="utf-8")+ host = PersonalContextHostAPI(home=home)++ graph = await host.get_graph(root_id=None, depth=2)+ tree = await host.get_tree(root_id="page:topics/description.md", depth=1)++ assert [node["id"] for node in graph["nodes"]] == [+ "page:description.md",+ "page:topics/description.md",+ ]+ assert [node["id"] for node in tree["nodes"]] == ["page:topics/agent.md"]+ assert all(+ not str(node["id"]).startswith("source:")+ for node in graph["nodes"] + tree["nodes"])-- 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"])+ assert all(source_id not in str(edge) for edge in graph["edges"] + tree["edges"])@pytest.mark.asyncio-async def test_host_returns_source_metadata_through_shared_page_detail(- tmp_path: Path,-) -> None:+async def test_host_exposes_source_detail_separately(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,- }+ source_id, _source_path = _write_source(home)++ detail = await PersonalContextHostAPI(home=home).get_source(source_id)++ assert detail["source_id"] == source_id+ assert detail["title"] == "GitHub PR 42"+ assert detail["service_id"] == "github-main"+ assert "markdown" not in detaildiff --git a/tests/unit_tests/personal_context/test_host_rail_smoke.py b/tests/unit_tests/personal_context/test_host_rail_smoke.pyindex 5afbbacef8..2ecf5db097 100644--- a/tests/unit_tests/personal_context/test_host_rail_smoke.py+++ b/tests/unit_tests/personal_context/test_host_rail_smoke.py@@ -28,14 +28,15 @@ async def test_real_host_core_and_rail_connection(tmp_path: Path) -> None:host = PersonalContextHostAPI(home=home)config = {- "enabled": True,- "fetching_enabled": True,+ "collection_enabled": True,+ "agent_use_enabled": True,"strategy_profile": "rules","fetch_services": [{"service_id": "smoke-local","provider": "local_files","enabled": False,+ "time_range": {"mode": "all"},"source": {"root_dir": str(source_root)},"credentials": {},}@@ -73,11 +74,11 @@ async def test_real_host_core_and_rail_connection(tmp_path: Path) -> None:await rail.after_model_call(ctx)assert await manager.collect_for_session("smoke-session") == []- await host.set_runtime_enabled(False)+ await host.set_agent_use_enabled(False)await rail.before_model_call(ctx)assert await manager.collect_for_session("smoke-session") == []- await host.set_runtime_enabled(True)+ await host.set_agent_use_enabled(True)await rail.before_model_call(ctx)attachments = await manager.collect_for_session("smoke-session")assert len(attachments) == 1diff --git a/tests/unit_tests/personal_context/test_pat_validation.py b/tests/unit_tests/personal_context/test_pat_validation.pynew file mode 100644index 0000000000..48983bad8a--- /dev/null+++ b/tests/unit_tests/personal_context/test_pat_validation.py@@ -0,0 +1,58 @@+"""Repository account validation and cancellation regression coverage."""++import asyncio++import httpx+import pytest++from jiuwenswarm.server.personal_context import host_api++[email protected]("field", ["login", "name"])[email protected]("value", [True, " ", "x" * 257, "bad\x00value"])+async def test_pat_rejects_invalid_account_fields(monkeypatch, field, value):+ payload = {"login": "account", "name": "Account"}+ payload[field] = value+ client_type = httpx.AsyncClient+ transport = httpx.MockTransport(lambda request: httpx.Response(200, json=payload))+ monkeypatch.setattr(+ host_api.httpx,+ "AsyncClient",+ lambda **kwargs: client_type(transport=transport, **kwargs),+ )+ with pytest.raises(+ host_api.PersonalContext.Error, match="account response is invalid"+ ):+ await host_api._validate_repository_pat("github", "test-secret")+++async def test_pat_rejects_invalid_json_without_exposing_body(monkeypatch):+ client_type = httpx.AsyncClient+ transport = httpx.MockTransport(+ lambda request: httpx.Response(200, content=b"invalid-json-private-body")+ )+ monkeypatch.setattr(+ host_api.httpx,+ "AsyncClient",+ lambda **kwargs: client_type(transport=transport, **kwargs),+ )+ with pytest.raises(+ host_api.PersonalContext.Error, match="response is invalid"+ ) as caught:+ await host_api._validate_repository_pat("github", "test-secret")+ assert "private-body" not in str(caught.value)+++async def test_pat_write_preserves_cancellation(monkeypatch):+ cancelled = asyncio.CancelledError()++ async def cancel(provider, secret):+ raise cancelled++ monkeypatch.setattr(host_api, "_validate_repository_pat", cancel)+ with pytest.raises(asyncio.CancelledError) as caught:+ await host_api._validate_repository_pat_for_write("github", "test-secret")+ assert caught.value is cancelleddiff --git a/tests/unit_tests/personal_context/test_team_personal_context.py b/tests/unit_tests/personal_context/test_team_personal_context.pynew file mode 100644index 0000000000..232d6db536--- /dev/null+++ b/tests/unit_tests/personal_context/test_team_personal_context.py@@ -0,0 +1,154 @@+"""Team member assembly reuses the fixed-home PersonalContext Rail and switch."""++from pathlib import Path+from types import SimpleNamespace++import pytest++from openjiuwen.agent_teams.schema.deep_agent_spec import RailSpec+from openjiuwen.core.foundation.llm import AssistantMessage, ToolCall, ToolMessage+from openjiuwen.core.single_agent.rail.base import AgentCallbackContext, ModelCallInputs+from openjiuwen.harness.prompts import PromptAttachmentManager+from openjiuwen.harness.rails.personal_context import PersonalContextRail+from jiuwenswarm.agents.swarm import register_swarm_providers+from jiuwenswarm.agents.swarm.config_specs import build_member_capability_specs+++ "mode",+ [+ "team",+ "code.team",+ "team.plan.normal",+ "team.plan.code",+ "team.work.normal",+ "team.work.plan",+ "team.code.normal",+ "team.code.plan",+ ],+)[email protected]("role", ["leader", "teammate"])+def test_team_personal_context_spec_survives_member_serialization(+ mode, role, tmp_path, monkeypatch+):+ register_swarm_providers()+ specs, _ = build_member_capability_specs({}, mode, role)+ selected = [spec for spec in specs if spec.type == "swarm.personal_context"]+ assert len(selected) == 1+ assert selected[0].params == {}+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))+ restored = RailSpec.model_validate(selected[0].model_dump())+ first = restored.build(language="cn", context=SimpleNamespace())+ second = restored.build(language="cn", context=SimpleNamespace())+ assert isinstance(first, PersonalContextRail)+ assert isinstance(second, PersonalContextRail)+ assert first is not second+ assert first._home == tmp_path / ".jiuwenswarm" / ".personal_context"+ assert second._home == first._home+++async def test_team_existing_and_new_members_follow_shared_switch(+ tmp_path, monkeypatch+):+ import openjiuwen.harness.rails.personal_context as rail_module++ register_swarm_providers()+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))+ home = tmp_path / ".jiuwenswarm" / ".personal_context"+ root = home / "workspace" / "context"+ root.mkdir(parents=True)+ (root / "description.md").write_text("# shared personal context", encoding="utf-8")+ config = home / "personal_context.yaml"+ config.write_text("agent_use_enabled: false\ncollection_enabled: false\n")+ members = []++ def add_member(role):+ specs, _ = build_member_capability_specs(+ {}, "team", "leader" if role == "leader" else "teammate"+ )+ spec = next(spec for spec in specs if spec.type == "swarm.personal_context")+ rail = spec.build(language="cn", context=SimpleNamespace())+ manager = PromptAttachmentManager()+ agent = SimpleNamespace(prompt_attachment_manager=manager)+ rail.init(agent)+ ctx = AgentCallbackContext(+ agent=agent,+ inputs=ModelCallInputs(messages=[AssistantMessage(content="hello")]),+ session=SimpleNamespace(session_id=role),+ )+ members.append((rail, manager, ctx, role))++ for role in ("leader", "teammate"):+ add_member(role)+ for enabled in (False, True, False, True):+ config.write_text(+ f"agent_use_enabled: {str(enabled).lower()}\ncollection_enabled: false\n"+ )+ if enabled and len(members) == 2:+ add_member("dynamic-teammate")+ for rail, manager, ctx, role in members:+ await rail.before_model_call(ctx)+ assert bool(await manager.collect_for_session(role)) is enabled+ config.write_text("agent_use_enabled: false\n")+ monkeypatch.setattr(+ rail_module,+ "_read_description",+ lambda path: pytest.fail("disabled must not read Context"),+ )+ for rail, manager, ctx, role in members:+ await rail.before_model_call(ctx)+ assert await manager.collect_for_session(role) == []+++async def test_team_personal_context_keeps_tool_call_result_adjacency(+ tmp_path, monkeypatch+):+ register_swarm_providers()+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))+ home = tmp_path / ".jiuwenswarm" / ".personal_context"+ root = home / "workspace" / "context"+ root.mkdir(parents=True)+ (home / "personal_context.yaml").write_text("agent_use_enabled: true\n")+ (root / "description.md").write_text("context", encoding="utf-8")+ specs, _ = build_member_capability_specs({}, "code.team", "teammate")+ rail = next(spec for spec in specs if spec.type == "swarm.personal_context").build(+ language="cn", context=SimpleNamespace()+ )+ manager = PromptAttachmentManager()+ agent = SimpleNamespace(prompt_attachment_manager=manager)+ rail.init(agent)+ messages = [+ AssistantMessage(+ content="",+ tool_calls=[+ ToolCall(id="t1", type="function", name="read", arguments="{}")+ ],+ ),+ ToolMessage(content="result", tool_call_id="t1"),+ ]+ ctx = AgentCallbackContext(+ agent=agent,+ inputs=ModelCallInputs(messages=messages),+ session=SimpleNamespace(session_id="member"),+ )+ before = list(messages)+ await rail.before_model_call(ctx)+ assert ctx.inputs.messages == before+ assert len(await manager.collect_for_session("member")) == 1+ await rail.after_model_call(ctx)+ assert await manager.collect_for_session("member") == []+++def test_team_personal_context_factory_failure_does_not_break_member(+ monkeypatch, caplog+):+ from jiuwenswarm.agents.swarm.providers import member_rails++ def fail(_home):+ raise RuntimeError("private-failure-detail")++ monkeypatch.setattr(member_rails, "PersonalContextRail", fail)+ assert member_rails._build_personal_context_rail({}, SimpleNamespace()) is None+ assert "private-failure-detail" not in caplog.textdiff --git a/tests/unit_tests/test_app_web_handlers.py b/tests/unit_tests/test_app_web_handlers.pyindex b21b78b3a6..e4d44c7b9c 100644--- a/tests/unit_tests/test_app_web_handlers.py+++ b/tests/unit_tests/test_app_web_handlers.py@@ -1165,8 +1165,10 @@ def test_web_does_not_expose_symphony_evolution_rpc_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.start_collection",+ "personal_context.runtime.stop_collection",+ "personal_context.runtime.start_agent_use",+ "personal_context.runtime.stop_agent_use","personal_context.runtime.get_config","personal_context.runtime.patch_config","personal_context.runtime.select_model",@@ -1176,16 +1178,17 @@ def test_web_forwards_only_canonical_personal_context_rpc_methods():"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.stop_run","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.stream_tree","personal_context.context.search_pages","personal_context.context.get_node",+ "personal_context.context.get_source",}forwarded = {method@@ -1200,7 +1203,7 @@ def test_web_forwards_only_canonical_personal_context_rpc_methods():assert forwarded == methodsassert no_local == methods- assert len(methods) == 22+ assert len(methods) == 25# =====================================================================diff --git a/tests/unit_tests/test_personal_context_clean_cut.py b/tests/unit_tests/test_personal_context_clean_cut.pyindex b99fd01b86..87819271d0 100644--- a/tests/unit_tests/test_personal_context_clean_cut.py+++ b/tests/unit_tests/test_personal_context_clean_cut.py@@ -13,8 +13,15 @@ def test_personal_context_api_inventory_and_legacy_removal() -> None:item.value for item in ReqMethod if item.value.startswith("personal_context.")}legacy_prefix = "p" + "cs."+ removed_methods = {+ "personal_context.runtime." + "start",+ "personal_context.runtime." + "stop",+ "personal_context.fetch.start_" + "scheduler",+ "personal_context.fetch.stop_" + "scheduler",+ }- assert len(methods) == 22+ assert len(methods) == 25+ assert methods.isdisjoint(removed_methods)assert not any(item.value.startswith(legacy_prefix) for item in ReqMethod)@@ -40,7 +47,10 @@ async def test_legacy_config_file_is_not_read(tmp_path: Path) -> None:await host.start()status = await host.get_status()+ # Ignore the legacy file and wait for explicit user configuration.assert status.configured is Falseassert status.state == "CREATED"+ assert status.collection_enabled is Falseassert host._config_path == home / "personal_context.yaml"assert not host._config_path.exists()+ assert legacy_config.is_file()