Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(memory): configure EverOS reranking endpoint (#1407)
rkrkrkk64abade47aa7
diff --git a/config/v2_config.py b/config/v2_config.pyindex d1ade0cc1..8efd3a6e0 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -852,6 +852,8 @@ def _recovery_section_for_error(error: BaseException) -> Optional[str]:match = re.search(r"Config '([^']+)'", message)if match:path = match.group(1)+ if path.startswith("memory.processing.rerank"):+ return "memory.rerank"if path == "platform":return "platforms"if path.startswith("agents."):@@ -861,6 +863,8 @@ def _recovery_section_for_error(error: BaseException) -> Optional[str]:return path.split(".", 1)[0]lowered = message.lower()+ if "memory rerank endpoint" in lowered:+ return "memory.rerank"if "unsupported enabled platform" in lowered:return "platforms"for platform_id in supported_platform_ids():@@ -904,6 +908,13 @@ def _reset_recoverable_config_section(payload: dict, section: str) -> bool:loss-avoiding recovery path, and the original file is backed up first."""+ if section == "memory.rerank":+ memory = payload.get("memory")+ processing = memory.get("processing") if isinstance(memory, dict) else None+ if not isinstance(processing, dict):+ return False+ processing.pop("rerank", None)+ return Trueif section == "runtime":# Keep this in sync with ``V2Config.default``. RuntimeConfig has a# required cwd, so an empty object would make the recovery loop fail a@@ -1403,10 +1414,19 @@ class MemoryEndpointConfig:class MemoryProcessingConfig:llm: MemoryEndpointConfig = field(default_factory=MemoryEndpointConfig)embedding: MemoryEndpointConfig = field(default_factory=MemoryEndpointConfig)+ rerank: Optional[MemoryEndpointConfig] = Nonedef validate(self) -> None:self.llm.validate(name="llm")self.embedding.validate(name="embedding")+ if self.rerank is not None:+ self.rerank.validate(name="rerank")+ if not any((self.rerank.base_url, self.rerank.model, self.rerank.api_key)):+ self.rerank = None+ elif not self.rerank.complete():+ raise ValueError(+ "Memory rerank endpoint must include base_url, model, and api_key"+ )@dataclass@@ -1542,12 +1562,15 @@ def memory_config_to_payload("has_api_key": bool(key),}+ processing = {+ "llm": endpoint_payload(memory.processing.llm),+ "embedding": endpoint_payload(memory.processing.embedding),+ }+ if memory.processing.rerank is not None:+ processing["rerank"] = endpoint_payload(memory.processing.rerank)payload = {"enabled": memory.enabled,- "processing": {- "llm": endpoint_payload(memory.processing.llm),- "embedding": endpoint_payload(memory.processing.embedding),- },+ "processing": processing,"diagnostics": {"log_provider_calls": memory.diagnostics.log_provider_calls,},@@ -1581,6 +1604,12 @@ def memory_config_from_payload(payload: object) -> MemoryConfig:processing_payload.get("embedding", {}),name="memory.processing.embedding",)+ rerank_payload = None+ if "rerank" in processing_payload:+ rerank_payload = _optional_memory_object(+ processing_payload["rerank"],+ name="memory.processing.rerank",+ )diagnostics_payload = _optional_memory_object(payload.get("diagnostics", {}),name="memory.diagnostics",@@ -1615,6 +1644,13 @@ def memory_config_from_payload(payload: object) -> MemoryConfig:embedding=MemoryEndpointConfig(**_filter_dataclass_fields(MemoryEndpointConfig, embedding_payload)),+ rerank=(+ MemoryEndpointConfig(+ **_filter_dataclass_fields(MemoryEndpointConfig, rerank_payload)+ )+ if rerank_payload is not None+ else None+ ),),diagnostics=MemoryDiagnosticsConfig(**_filter_dataclass_fields(diff --git a/core/memory/everos.py b/core/memory/everos.pyindex 73cdb88d7..ebad33f0d 100644--- a/core/memory/everos.py+++ b/core/memory/everos.py@@ -131,7 +131,11 @@ class MemoryProviderSystemFailure(MemoryProviderFailure):@dataclass(frozen=True)class MemoryPreflightFailure:- error: Literal["memory_embedding_unavailable", "memory_llm_unavailable"]+ error: Literal[+ "memory_embedding_unavailable",+ "memory_llm_unavailable",+ "memory_rerank_unavailable",+ ]diagnostic: MemoryPreflightDiagnostic@@ -164,6 +168,9 @@ class EverOSPort:embedding_base_url: str | None = None,embedding_model: str | None = None,embedding_api_key: str | None = None,+ rerank_base_url: str | None = None,+ rerank_model: str | None = None,+ rerank_api_key: str | None = None,processing_health_check: Callable[[], Awaitable[bool]] | None = None,sidecar_timeout_seconds: float = _SIDECAR_TIMEOUT_SECONDS,add_timeout_seconds: float = _ADD_TIMEOUT_SECONDS,@@ -178,6 +185,9 @@ class EverOSPort:self._embedding_base_url = _normalized_endpoint_url(embedding_base_url)self._embedding_model = _optional_string(embedding_model)self._embedding_api_key = _optional_string(embedding_api_key)+ self._rerank_base_url = _normalized_endpoint_url(rerank_base_url)+ self._rerank_model = _optional_string(rerank_model)+ self._rerank_api_key = _optional_string(rerank_api_key)self._processing_health_check = processing_health_checkself._sidecar_timeout_seconds = _positive_timeout(sidecar_timeout_seconds, _SIDECAR_TIMEOUT_SECONDS)self._add_timeout_seconds = _positive_timeout(add_timeout_seconds, _ADD_TIMEOUT_SECONDS)@@ -467,7 +477,7 @@ class EverOSPort:return Falseif not self._processing_configured():return False- return await self._probe_processing_endpoint(+ healthy = await self._probe_processing_endpoint(base_url=self._llm_base_url,api_key=self._llm_api_key,path="chat/completions",@@ -485,17 +495,37 @@ class EverOSPort:payload={"model": self._embedding_model, "input": "memory health check"},validator=_valid_embedding_probe_response,)+ if not healthy or not self._rerank_configured():+ return healthy+ return await self._probe_processing_endpoint(+ base_url=self._rerank_base_url,+ api_key=self._rerank_api_key,+ path=self._rerank_model or "",+ payload={"queries": ["OK"], "documents": ["OK"]},+ validator=_valid_rerank_probe_response,+ )async def preflight(self) -> MemoryPreflightResult:"""Run one bounded request for each configured processing endpoint."""- checks = (+ checks = [("llm", self._llm_base_url, self._llm_api_key, "chat/completions", {"model": self._llm_model, "messages": [{"role": "user", "content": "OK"}], "max_tokens": 1, "temperature": 0,}, _valid_chat_probe_response),("embedding", self._embedding_base_url, self._embedding_api_key, "embeddings", {"model": self._embedding_model, "input": "OK",}, _valid_embedding_probe_response),- )+ ]+ if self._rerank_configured():+ checks.append(+ (+ "rerank",+ self._rerank_base_url,+ self._rerank_api_key,+ self._rerank_model or "",+ {"queries": ["OK"], "documents": ["OK"]},+ _valid_rerank_probe_response,+ )+ )first_failure = Nonefor side, base_url, api_key, path, payload, validator in checks:started_at_ms = int(time.time() * 1000)@@ -515,7 +545,7 @@ class EverOSPort:timeout=_PREFLIGHT_TIMEOUT_SECONDS,)except asyncio.TimeoutError:- error_name = "memory_llm_unavailable" if side == "llm" else "memory_embedding_unavailable"+ error_name = _preflight_error_name(side)failure = MemoryPreflightFailure(error_name,MemoryPreflightDiagnostic(side, message="provider_request_timed_out"),@@ -546,6 +576,9 @@ class EverOSPort:))+ def _rerank_configured(self) -> bool:+ return all((self._rerank_base_url, self._rerank_model, self._rerank_api_key))+async def _search_data(self,principal_id: str,@@ -702,9 +735,9 @@ class EverOSPort:started_at_ms,started,):- error_name = "memory_llm_unavailable" if side == "llm" else "memory_embedding_unavailable"+ error_name = _preflight_error_name(side)diagnostic = MemoryPreflightDiagnostic(side)- if not base_url or not api_key:+ if not base_url or not api_key or not path:failure = MemoryPreflightFailure(error_name, replace(diagnostic, message="endpoint_not_configured"))self._record_preflight(side,@@ -825,8 +858,14 @@ class EverOSPort:if self._preflight_call_recorder is None:returntry:+ model = {+ "llm": self._llm_model,+ "embedding": self._embedding_model,+ "rerank": self._rerank_model,+ }.get(side)self._preflight_call_recorder(side=side,+ model=model,request=request,response=response,failure=failure,@@ -1117,6 +1156,35 @@ def _valid_embedding_probe_response(value: Any) -> bool:)+def _valid_rerank_probe_response(value: Any) -> bool:+ if not isinstance(value, dict):+ return False+ scores = value.get("scores")+ return (+ isinstance(scores, list)+ and len(scores) == 1+ and isinstance(scores[0], list)+ and len(scores[0]) == 1+ and isinstance(scores[0][0], (int, float))+ and not isinstance(scores[0][0], bool)+ and math.isfinite(scores[0][0])+ )+++def _preflight_error_name(+ side: Literal["llm", "embedding", "rerank"],+) -> Literal[+ "memory_llm_unavailable",+ "memory_embedding_unavailable",+ "memory_rerank_unavailable",+]:+ return {+ "llm": "memory_llm_unavailable",+ "embedding": "memory_embedding_unavailable",+ "rerank": "memory_rerank_unavailable",+ }[side]++def _optional_string(value: str | None) -> str | None:if not isinstance(value, str):return None@@ -1155,11 +1223,16 @@ def _provider_health_snapshot(payload: dict[str, Any] | None) -> ProviderHealthSif not _safe_health_token(version, max_bytes=64, allow_dot=True):return Nonecapabilities = payload.get("capabilities")- capability_keys = {"llm", "embed", "rerank", "multimodal_llm", "parser"}+ required_capabilities = {"llm", "embed", "rerank", "multimodal_llm", "parser"}if (not isinstance(capabilities, dict)- or set(capabilities) != capability_keys- or any(type(capabilities[key]) is not bool for key in capability_keys)+ or not required_capabilities.issubset(capabilities)+ or len(capabilities) > 32+ or any(+ not _safe_health_token(key, max_bytes=64)+ or type(value) is not bool+ for key, value in capabilities.items()+ )):return Nonedisabled = payload.get("disabled_features")@@ -1178,7 +1251,7 @@ def _provider_health_snapshot(payload: dict[str, Any] | None) -> ProviderHealthSreturn ProviderHealthSnapshot(status="ok",version=version,- capabilities={key: capabilities[key] for key in sorted(capability_keys)},+ capabilities={key: capabilities[key] for key in sorted(capabilities)},disabled_features=tuple(disabled),cascade=cascade,recorder=recorder,diff --git a/core/memory/everos_insight/patches.py b/core/memory/everos_insight/patches.pyindex 156157f7a..fb3c2b78f 100644--- a/core/memory/everos_insight/patches.py+++ b/core/memory/everos_insight/patches.py@@ -596,6 +596,7 @@ def _provider_base_urls() -> tuple[str, ...]:"EVEROS_LLM__BASE_URL","EVEROS_MULTIMODAL__BASE_URL","EVEROS_EMBEDDING__BASE_URL",+ "EVEROS_RERANK__BASE_URL",)if (value := os.environ.get(name)))@@ -610,6 +611,7 @@ def _provider_api_keys() -> tuple[str, ...]:"EVEROS_LLM__API_KEY","EVEROS_MULTIMODAL__API_KEY","EVEROS_EMBEDDING__API_KEY",+ "EVEROS_RERANK__API_KEY",)if (value := os.environ.get(name)))diff --git a/core/memory/everos_insight/recorder.py b/core/memory/everos_insight/recorder.pyindex a17ed0e1e..d7b172743 100644--- a/core/memory/everos_insight/recorder.py+++ b/core/memory/everos_insight/recorder.py@@ -27,7 +27,7 @@ from core.memory.confined_filesystem import (JsonPrimitive: TypeAlias = None | bool | int | float | strJsonValue: TypeAlias = JsonPrimitive | list["JsonValue"] | dict[str, "JsonValue"]-ProviderKind: TypeAlias = Literal["llm", "multimodal_llm", "embedding"]+ProviderKind: TypeAlias = Literal["llm", "multimodal_llm", "embedding", "rerank"]_ATTACHMENT_OMITTED = "[ATTACHMENT_OMITTED]"_LLM_MESSAGE_BYTES = 16 * 1024@@ -831,7 +831,7 @@ def _validate_call(call: ProviderCallInput) -> None:value = getattr(call, name)if not isinstance(value, str) or not value:raise ValueError(f"{name} must be a non-empty string")- if call.kind not in {"llm", "multimodal_llm", "embedding"}:+ if call.kind not in {"llm", "multimodal_llm", "embedding", "rerank"}:raise ValueError("unsupported provider call kind")for name in ("started_at_ms", "duration_ms", "dropped_before"):value = getattr(call, name)diff --git a/core/memory/process.py b/core/memory/process.pyindex 64a2b66ae..27d13e503 100644--- a/core/memory/process.py+++ b/core/memory/process.py@@ -76,12 +76,14 @@ async def _probe_stderr_tail(task: asyncio.Task[bytes] | None, *, settings: Evervalue for value in (settings.llm_base_url,settings.embedding_base_url,+ settings.rerank_base_url,) if value),exact_values=tuple(value for value in (settings.llm_api_key,settings.embedding_api_key,+ settings.rerank_api_key,) if value),)@@ -130,6 +132,9 @@ class EverOSProcessSettings:embedding_base_url: str | None = Noneembedding_model: str | None = Noneembedding_api_key: str | None = field(default=None, repr=False)+ rerank_base_url: str | None = None+ rerank_model: str | None = None+ rerank_api_key: str | None = field(default=None, repr=False)timezone: str | None = Nonecall_log_db_path: Path | None = None@@ -2390,7 +2395,7 @@ def _write_memory_child_config("",))- _validate_generated_config(everos_contents, ome_contents, timezone_name)+ _validate_generated_config(everos_contents, ome_contents, timezone_name, settings)for path, contents in ((generated / "everos.toml", everos_contents),(generated / "ome.toml", ome_contents),@@ -2434,6 +2439,9 @@ def _memory_child_environment("EVEROS_EMBEDDING__BASE_URL": settings.embedding_base_url,"EVEROS_EMBEDDING__MODEL": settings.embedding_model,"EVEROS_EMBEDDING__API_KEY": settings.embedding_api_key,+ "EVEROS_RERANK__BASE_URL": settings.rerank_base_url,+ "EVEROS_RERANK__MODEL": settings.rerank_model,+ "EVEROS_RERANK__API_KEY": settings.rerank_api_key,}env.update({key: value for key, value in optional.items() if value is not None})if settings.call_log_db_path is not None:@@ -3433,17 +3441,32 @@ def _local_iana_timezone() -> str:return "UTC"-def _validate_generated_config(everos_contents: str, ome_contents: str, timezone: str) -> None:+def _validate_generated_config(+ everos_contents: str,+ ome_contents: str,+ timezone: str,+ settings: EverOSProcessSettings,+) -> None:try:everos = tomllib.loads(everos_contents)ome = tomllib.loads(ome_contents)except tomllib.TOMLDecodeError as exc:raise RuntimeError("invalid generated EverOS config") from exc+ rerank_settings = (+ settings.rerank_base_url,+ settings.rerank_model,+ settings.rerank_api_key,+ )+ if any(rerank_settings) and not all(rerank_settings):+ raise RuntimeError("Generated EverOS config received partial rerank settings")if (everos.get("memory", {}).get("timezone") != timezoneor everos.get("memorize", {}).get("mode") != "chat"+ # EverOS 1.2.3 gives env settings precedence over TOML. Keep these+ # blank so configured rerank values have one child-process source.or everos.get("rerank", {}).get("model") != ""or everos.get("rerank", {}).get("base_url") != ""+ or "api_key" in everos.get("rerank", {})or ome.get("strategies", {}).get("reflect_episodes", {}).get("enabled") is not Falseor ome.get("strategies", {}).get("extract_foresight", {}).get("enabled") is not False):diff --git a/core/memory/runtime.py b/core/memory/runtime.pyindex d6c3630da..54431099c 100644--- a/core/memory/runtime.py+++ b/core/memory/runtime.py@@ -740,11 +740,13 @@ class MemoryRuntime:if self._store is None:self._insight_reader = Nonereturn+ rerank = config.processing.rerankbase_urls = tuple(valuefor value in (config.processing.llm.base_url,config.processing.embedding.base_url,+ rerank.base_url if rerank else None,)if value)@@ -753,6 +755,7 @@ class MemoryRuntime:for value in (config.processing.llm.api_key,config.processing.embedding.api_key,+ rerank.api_key if rerank else None,)if value)@@ -1919,6 +1922,9 @@ class MemoryRuntime:embedding_base_url=candidate.processing.embedding.base_url,embedding_model=candidate.processing.embedding.model,embedding_api_key=candidate.processing.embedding.api_key,+ rerank_base_url=(candidate.processing.rerank.base_url if candidate.processing.rerank else None),+ rerank_model=(candidate.processing.rerank.model if candidate.processing.rerank else None),+ rerank_api_key=(candidate.processing.rerank.api_key if candidate.processing.rerank else None),preflight_call_recorder=self._record_preflight_call,)return (await provider.preflight()).payload()@@ -1927,6 +1933,7 @@ class MemoryRuntime:self,*,side,+ model=None,request,response,failure,@@ -1939,8 +1946,8 @@ class MemoryRuntime:self._call_log_db_path,started_at_ms=started_at_ms,duration_ms=duration_ms,- kind="embedding" if side == "embedding" else "llm",- model=request.get("model") if isinstance(request, dict) else None,+ kind=side,+ model=model,request=request,response=response,status="error" if failure is not None else "ok",@@ -3126,6 +3133,7 @@ class MemoryRuntime:def _provider_kwargs(config: MemoryConfig) -> dict[str, str | None]:+ rerank = config.processing.rerankreturn {"llm_base_url": config.processing.llm.base_url,"llm_model": config.processing.llm.model,@@ -3133,6 +3141,9 @@ def _provider_kwargs(config: MemoryConfig) -> dict[str, str | None]:"embedding_base_url": config.processing.embedding.base_url,"embedding_model": config.processing.embedding.model,"embedding_api_key": config.processing.embedding.api_key,+ "rerank_base_url": rerank.base_url if rerank else None,+ "rerank_model": rerank.model if rerank else None,+ "rerank_api_key": rerank.api_key if rerank else None,}diff --git a/core/memory/sidecar.py b/core/memory/sidecar.pyindex 14072b6e3..61c4f63f3 100644--- a/core/memory/sidecar.py+++ b/core/memory/sidecar.py@@ -375,6 +375,9 @@ def _processing_healthy_from_child_environment() -> bool:embedding_base_url=os.environ.get("EVEROS_EMBEDDING__BASE_URL"),embedding_model=os.environ.get("EVEROS_EMBEDDING__MODEL"),embedding_api_key=os.environ.get("EVEROS_EMBEDDING__API_KEY"),+ rerank_base_url=os.environ.get("EVEROS_RERANK__BASE_URL"),+ rerank_model=os.environ.get("EVEROS_RERANK__MODEL"),+ rerank_api_key=os.environ.get("EVEROS_RERANK__API_KEY"),)return asyncio.run(provider.processing_healthy())diff --git a/core/memory/types.py b/core/memory/types.pyindex ded179b64..021d992d7 100644--- a/core/memory/types.py+++ b/core/memory/types.py@@ -40,6 +40,7 @@ MemoryErrorCode = Literal["memory_rebuild_failed","memory_embedding_unavailable","memory_llm_unavailable",+ "memory_rerank_unavailable","memory_rebuild_root_busy","memory_factory_reset_failed","memory_repair_failed",@@ -73,6 +74,7 @@ CLOSED_MEMORY_ERROR_CODES = frozenset("memory_rebuild_failed","memory_embedding_unavailable","memory_llm_unavailable",+ "memory_rerank_unavailable","memory_rebuild_root_busy","memory_factory_reset_failed","memory_repair_failed",@@ -89,7 +91,7 @@ def is_memory_error_code(value: object) -> bool:@dataclass(frozen=True)class MemoryPreflightDiagnostic:- side: Literal["embedding", "llm"]+ side: Literal["embedding", "llm", "rerank"]http_status: int | None = Noneprovider_error_code: str | None = Nonemessage: str = "provider unavailable"diff --git a/docs/MEMORY.md b/docs/MEMORY.mdindex 4941ec77c..f425c11f5 100644--- a/docs/MEMORY.md+++ b/docs/MEMORY.md@@ -4,15 +4,25 @@Confirmed embedding identity changes and retained rebuild retries validate thecandidate with one bounded chat request and one bounded embeddings request-before the active sidecar is quiesced. Provider failures identify the side,-HTTP status, provider code, and a sanitized message; the durable candidate and-rebuild intent remain available for Retry. Ordinary runtime restart keeps its-existing behavior.+before the active sidecar is quiesced. When the optional reranking endpoint is+configured, preflight also makes one bounded reranking request. Provider+failures identify the side, HTTP status, provider code, and a sanitized+message; the durable candidate and rebuild intent remain available for Retry.+Ordinary runtime restart keeps its existing behavior.Avibe Memory distills eligible Workbench and private-IM messages into aper-user profile, episodes, and facts. Open **Settings > Memory** to inspect itsProcessing Record, current profile, search results, and settings.+## Optional reranking endpoint++The third processing endpoint in **Settings > Memory** is optional. Configure+its Base URL, model, and API key together to let the pinned Memory runtime use+its reranking capability; changing a configured endpoint is admitted by the+same bounded preflight before it is saved. Leave all three fields empty to keep+the standard Memory search tier. Removing the saved reranking endpoint clears+all three values and does not rebuild the embedding index.+## Processing RecordThe Processing Record combines a direct, bounded EverOS health projection with@@ -41,13 +51,13 @@ legacy `memory.diagnostics.log_provider_calls` field is still accepted when anolder config file is loaded, but its value is normalized to `true` and there isno settings switch to turn recording off.-Avibe retains bounded, scrubbed LLM, multimodal-LLM, and embedding request and-response fields used during Memory processing. It does not store embedding-vectors, attachment bytes, raw sidecar stdout/stderr, or unrelated Search and-Get calls. Secrets, configured provider URLs, and absolute local paths are-scrubbed, and large fields are truncated or replaced with omission markers.-Diagnostic payloads can still contain sensitive conversation text; treat access-to the operator log accordingly.+Avibe retains bounded, scrubbed LLM, multimodal-LLM, embedding, and reranking+request and response fields used during Memory processing. It does not store+embedding vectors, attachment bytes, raw sidecar stdout/stderr, or unrelated+Search and Get calls. Secrets, configured provider URLs, and absolute local+paths are scrubbed, and large fields are truncated or replaced with omission+markers. Diagnostic payloads can still contain sensitive conversation text;+treat access to the operator log accordingly.Rows remain readable until normal expiry or Clear Memory Data. Retention runs whileMemory is disabled as well: rows expire after 14 days and only the newest 5,000diff --git a/docs/MEMORY_ZH.md b/docs/MEMORY_ZH.mdindex 27a7fd5ba..bd910d3dc 100644--- a/docs/MEMORY_ZH.md+++ b/docs/MEMORY_ZH.md@@ -3,6 +3,17 @@Avibe 记忆会把符合条件的 Workbench 和私聊消息提炼为按用户隔离的画像、事件与事实。在**设置 > 记忆**中可以查看状态、当前画像、搜索结果、设置和处理日志。+## 处理预检与可选重排序端点++确认更改 Embedding 端点标识或重试待处理的重建前,Avibe 会分别执行一次有界的聊天+请求和 Embedding 请求。配置可选重排序端点后,预检还会执行一次有界的重排序请求。+提供方失败会显示对应端点、HTTP 状态、提供方错误码和经过脱敏的信息。++**设置 > 记忆**中的第三个处理端点是可选项。要启用固定 Memory Runtime 的重排序能力,+必须同时填写 Base URL、模型和 API Key;添加或更改端点会在保存前执行同样的有界预检。+三个字段全部留空时会继续使用标准记忆搜索层级。移除已保存的重排序端点会清除这三个值,+但不会重建 Embedding 索引。+## 处理日志「日志」标签页是安装运维者视图,会展示所有有效项目和用户。每条记录及详情都会@@ -21,7 +32,7 @@ Avibe 记忆会把符合条件的 Workbench 和私聊消息提炼为按用户隔`memory.diagnostics.log_provider_calls` 字段仍会被兼容加载,但会被规范化为 `true`,设置页不再提供关闭开关。-Avibe 会保留记忆处理过程中 LLM、多模态 LLM 和 Embedding 调用里经过脱敏且有+Avibe 会保留记忆处理过程中 LLM、多模态 LLM、Embedding 和重排序调用里经过脱敏且有大小限制的请求与响应字段。它不会存储 Embedding 向量、附件字节、sidecar 原始stdout/stderr,也不会记录无关的 Search 和 Get 调用。密钥、已配置的提供方 URL 和本机绝对路径会被脱敏;过大的字段会截断或替换为省略标记。诊断负载仍可能包含敏感对话文本,diff --git a/docs/plans/memory-rerank-agentic-enablement.md b/docs/plans/memory-rerank-agentic-enablement.mdnew file mode 100644index 000000000..b6e304d51--- /dev/null+++ b/docs/plans/memory-rerank-agentic-enablement.md@@ -0,0 +1,187 @@+# Memory: enable EverOS rerank (Tier 3) and agentic search++Status: approved by owner 2026-08-14. This document is the source of truth for+the two delivery PRs below. Update it when scope changes materially.++Evidence baseline: Avibe `master @ 7fe4d19f`; pinned EverOS `1.2.3`+(`core/memory/artifact.py:55`). Related decision record:+`docs/memory-everos-reuse-audit.md` (recovery workstream — separate scope).++## Background++Avibe currently pins EverOS at capability **Tier 2** (`[llm]` + `[embedding]`)+and deliberately fails closed on everything above it:++- Every search request hardcodes `enable_llm_rerank: False`+ (`core/memory/everos.py`), and the in-sidecar guard rejects any other value+ (`core/memory/sidecar.py::_validate_search`).+- The generated `everos.toml` blanks `[rerank].model` / `[rerank].base_url`,+ and `_validate_generated_config` asserts they stay blank+ (`core/memory/process.py`). No rerank credentials exist in `MemoryConfig`.+- `method: "agentic"` is unreachable through three independent gates:+ `EverOSPort.agentic_budget_enforced` is a constant `False`+ (`core/memory/everos.py`), `MemoryModule.recall` /+ `resolve_recall_mode` return `memory_capability_unavailable`+ (`core/memory/module.py`), and the sidecar `method` allowlist is+ `{keyword, vector, hybrid}` (`core/memory/sidecar.py`).++EverOS official guidance (docs verified in the EverOS 1.2.3 source tree,+`docs/api.md`, `EVEROS_INTEGRATION_zh.md`, `CHANGELOG.md`):++- Configuring `[rerank]` upgrades the sidecar to **Tier 3**, which unlocks+ `method=agentic`. Tier upgrades require a sidecar restart. `GET /health`+ reports `capabilities.rerank` and a `disabled_features` list+ (`agentic_search` appears there when rerank is absent).+- Recommended usage ladder: hybrid defaults first; `agentic` is reserved for+ complex, decomposable queries (slow/expensive: 1 LLM sufficiency call always,+ +1 LLM multi-query call and 3 parallel retrievals when round 1 is judged+ insufficient, plus 1–2 cross-encoder rerank batches; the episode path also+ reads the cluster snapshot and fetches the full owner corpus).+- **Key nuance:** Avibe's searches are all `user_id`-owned episode/profile+ lookups. For that owner kind, `enable_llm_rerank` is a documented no-op+ (agent_case/agent_skill fusion only) and the automatic cross-encoder hybrid+ lane applies only to agent skills. Therefore the only rerank-quality payoff+ for Avibe's current usage is **`method=agentic`** (which runs its own+ internal cross-encoder rerank loop).+- Agent-side agentic was broken before 1.2.2 and stabilized exactly at 1.2.3+ (skill-shaped rerank passage fix) — the pinned version is the first safe one.++## Goal++1. Add an optional third memory endpoint (**rerank**) to product config and+ plumb it into the EverOS sidecar so it starts at Tier 3 when configured.+2. Open a bounded, opt-in **agentic** recall path for agent callers via the+ `vibe memory search` CLI, keeping `hybrid` the default everywhere.++## Owner decisions (2026-08-14)++1. **Provider-neutral rerank config.** Three user-filled fields+ (`base_url`, `model`, `api_key`) exactly like the existing `llm` /+ `embedding` endpoints. No provider preset, no default vendor.+2. **Agentic exposure = CLI only.** Agents choose the mode per query, guided+ by system-prompt wording ("complex multi-hop recall only"). The Web UI+ memory search stays hybrid-only for now.+3. **Budget gate resolved Avibe-side.** No upstream budget contract exists in+ EverOS 1.2.3. Avibe enforces a wall-clock timeout (≤ 30 s, matching the+ existing `RecallPolicy` budget validation in `core/memory/types.py`) on+ agentic requests and records round telemetry (EverOS logs+ `agentic_search_decision round=round1|round2`). `agentic_budget_enforced`+ becomes true once that enforcement is real.++## Out of scope++- `enable_llm_rerank: true` (no-op for user-owned memories; revisit only if+ agent_id-owned memories are adopted). The sidecar guard keeps rejecting it.+- The EverOS knowledge subsystem.+- UI-initiated agentic search.+- Any change to memorize/flush/rebuild/recovery behavior+ (`docs/plans/memory-rebuild-and-recovery-ladder.md` owns that).++## Delivery plan — two sequential PRs++PR2 starts only after PR1 merges (both touch `core/memory/everos.py` and+`core/memory/runtime.py`; sequencing avoids contract drift and merge risk).++### PR1 — rerank endpoint config + Tier 3 unlock++Scope (indicative files):++- `config/v2_config.py`: `MemoryProcessingConfig` gains an **optional**+ `rerank: MemoryEndpointConfig` (same field names/limits as `llm` /+ `embedding`). Memory may be enabled without it (stays Tier 2). A partially+ filled rerank endpoint is a validation error. Persisted-shape rule applies:+ config files written by released versions (no `rerank` key) must load+ unchanged; add load fixtures.+- `core/memory/runtime.py` (`_provider_kwargs` / `_process_settings`) and+ `core/memory/process.py`: pass rerank settings through+ `EverOSProcessSettings`; inject `EVEROS_RERANK__BASE_URL`,+ `EVEROS_RERANK__MODEL`, `EVEROS_RERANK__API_KEY` into the child env only+ when configured (mirror the llm/embedding pattern; api_key never touches+ disk).+- `core/memory/process.py` generated-config: when rerank is **not**+ configured, keep the current blanked `[rerank]` section (explicit Tier 2).+ When configured, the generated toml + env must deterministically yield a+ constructable reranker — verify EverOS toml/env precedence in the pinned+ wheel and, if toml wins over env for non-secret keys, write the configured+ `model`/`base_url` into the generated `[rerank]` section (api_key stays+ env-only). Update `_validate_generated_config` to assert consistency with+ the persisted product config instead of asserting always-blank.+- `core/memory/everos.py` health parsing: the current strict equality on the+ 5-key capability set must tolerate EverOS's typed+ `capabilities`/`disabled_features` health shape without flipping healthy+ sidecars to `memory_provider_response_invalid`. Surface `rerank` capability+ and `agentic_search` disabled/enabled state to the existing UI status+ labels (`ui/.../memoryStatusPresentation.ts` already has both labels).+- UI: memory settings page gains the third (optional) endpoint form,+ reusing the existing endpoint form pattern; all strings via+ `ui/src/i18n/en.json` + `zh.json`.+- Preflight: if a rerank endpoint is configured, extend the existing+ endpoint preflight pattern with a rerank probe consistent with how+ llm/embedding are probed; a missing rerank endpoint must not degrade any+ existing Tier 2 behavior.++Acceptance (PR1):++- With no rerank config: byte-identical generated toml/env versus master+ (regression fixture), all existing memory flows unchanged, health shows+ rerank capability false / agentic_search disabled without erroring.+- With rerank configured (fake/stub endpoint in tests): child env carries the+ three `EVEROS_RERANK__*` vars; generated-config validation passes; health+ snapshot reports `rerank: true`.+- Older persisted config without the `rerank` key loads and saves cleanly.+- `agents.*`-style config save reconciliation still applies (rolling refresh+ path; no second restart requirement).++### PR2 — bounded agentic recall path (after PR1 merges)++Scope (indicative files):++- `core/memory/everos.py`: `_search_data` accepts `method="agentic"`; apply a+ per-request wall-clock timeout (≤ 30 s) for agentic calls;+ `agentic_budget_enforced` returns true iff timeout enforcement is active.+ `enable_llm_rerank` stays `False` in every request body.+- `core/memory/sidecar.py` `_validate_search`: add `"agentic"` to the method+ allowlist; keep every other guard (including `enable_llm_rerank is False`).+- `core/memory/module.py` / `core/memory/types.py`: `resolve_recall_mode`+ routes `agentic` → available only when health reports the capability+ (rerank + llm + embed present, `agentic_search` not disabled); otherwise+ fail closed with `memory_capability_unavailable` exactly as today.+- `core/memory/runtime.py`: keep `_recall_all_projects` rejecting agentic+ (`--project all` + agentic stays unsupported).+- `vibe/internal_client.py` + `core/internal_server.py` + `vibe/cli.py`:+ `vibe memory search --mode {hybrid|keyword|vector|agentic}` (default+ `hybrid`). Parser-backed contract tests required — injected system-prompt+ CLI examples are live callers (see AGENTS.md §7).+- `core/system_prompt_injection.py`: extend the memory CLI guidance with one+ sentence: agentic mode is for complex, multi-hop recall only; default stays+ hybrid.+- Telemetry: log/record agentic usage and result (at minimum: mode, duration,+ success/timeout) so the round-2 rate and latency can be measured from logs.++Acceptance (PR2):++- Rerank unconfigured → `--mode agentic` returns the existing+ `memory_capability_unavailable` error surface (never an EverOS 422 leaking+ through, never a hang).+- Rerank configured (stubbed sidecar in tests) → agentic request reaches the+ sidecar with `method="agentic"`, `enable_llm_rerank=False`, and times out+ cleanly at the budget with a typed error.+- Default CLI behavior byte-identical to master (`hybrid`, limit 8).+- Behavioral deltas documented in user docs: agentic episodes return empty+ `atomic_facts`; with unlimited `top_k` EverOS caps agent kinds at 10.+- `--project all --mode agentic` rejected with a clear error.++## Contracts frozen for both lanes++- Config field names: `memory.processing.rerank.{base_url,model,api_key}`+ (optional section), identical semantics/limits to the existing+ `MemoryEndpointConfig`.+- Child env names: `EVEROS_RERANK__BASE_URL`, `EVEROS_RERANK__MODEL`,+ `EVEROS_RERANK__API_KEY`.+- Recall mode vocabulary: `auto | keyword | vector | hybrid | agentic`+ (existing `RecallMode`); CLI flag `--mode`, default `hybrid`.+- Sidecar request shape: unchanged key set; `method` allowlist grows by+ `"agentic"` in PR2 only; `enable_llm_rerank` remains hard-`False`.+- Agentic budget: wall-clock ≤ 30 s, enforced in `EverOSPort`.++Deviations from these contracts route through the PM, never lane-to-lane.diff --git a/tests/test_memory_call_log.py b/tests/test_memory_call_log.pyindex 02dfe68d0..70607d169 100644--- a/tests/test_memory_call_log.py+++ b/tests/test_memory_call_log.py@@ -70,6 +70,26 @@ def test_preflight_recorder_creates_private_call_log_directory(tmp_path: Path) -]+def test_preflight_recorder_accepts_rerank_provider_kind(tmp_path: Path) -> None:+ db_path = _private_db_path(tmp_path)++ record_preflight_call(+ db_path,+ started_at_ms=1_700_000_000_000,+ duration_ms=125,+ kind="rerank",+ model="rerank-model",+ request={"queries": ["OK"], "documents": ["OK"]},+ response={"scores": [[0.9]]},+ status="ok",+ )++ with sqlite3.connect(db_path) as conn:+ assert conn.execute("SELECT kind, stage FROM provider_call").fetchall() == [+ ("rerank", "processing_preflight")+ ]++def test_normalize_provider_call_scrubs_every_serialized_column() -> None:secret = "sk-super-secret-value"unprefixed_secret = "plain-provider-credential"diff --git a/tests/test_memory_config.py b/tests/test_memory_config.pyindex a9a6e2d9c..83a6935f7 100644--- a/tests/test_memory_config.py+++ b/tests/test_memory_config.py@@ -123,6 +123,88 @@ def test_memory_config_round_trips_and_hides_keys(tmp_path) -> None:assert projected["memory"]["diagnostics"] == {"log_provider_calls": True}+def test_released_memory_config_without_rerank_loads_and_saves_without_shape_churn(+ tmp_path,+) -> None:+ config = V2Config.from_payload(+ _payload({"enabled": True, "processing": _complete_processing()})+ )++ assert config.memory.processing.rerank is None+ config.save(tmp_path / "config.json")++ stored = json.loads((tmp_path / "config.json").read_text(encoding="utf-8"))+ assert "rerank" not in stored["memory"]["processing"]+ assert V2Config.load(tmp_path / "config.json").memory.processing.rerank is None+++def test_disk_load_degrades_only_a_malformed_optional_rerank_section(tmp_path) -> None:+ processing = _complete_processing()+ processing["rerank"] = {+ "base_url": "https://rerank.example.test/v1/inference",+ "model": "rerank-model",+ }+ payload = _payload(+ {+ "enabled": True,+ "recovery_intent": "rebuild",+ "processing": processing,+ }+ )+ config_path = tmp_path / "config.json"+ config_path.write_text(json.dumps(payload), encoding="utf-8")++ loaded = V2Config.load(config_path)++ assert loaded.memory.enabled is True+ assert loaded.memory.processing.llm.model == "chat"+ assert loaded.memory.processing.embedding.model == "embed"+ assert loaded.memory.processing.rerank is None+ assert loaded.memory.recovery_intent == "rebuild"+ assert any("memory.rerank" in warning for warning in loaded.load_warnings)+ assert "rerank" in json.loads(config_path.read_text(encoding="utf-8"))["memory"]["processing"]+++def test_memory_rerank_round_trips_without_projecting_its_key(tmp_path) -> None:+ processing = _complete_processing()+ processing["rerank"] = {+ "base_url": "https://rerank.example.test/v1/inference",+ "model": "rerank-model",+ "api_key": "rerank-secret",+ }+ config = V2Config.from_payload(+ _payload({"enabled": True, "processing": processing})+ )+ config.save(tmp_path / "config.json")++ stored = json.loads((tmp_path / "config.json").read_text(encoding="utf-8"))+ projected = config_to_payload(config)["memory"]["processing"]["rerank"]+ assert stored["memory"]["processing"]["rerank"]["api_key"] == "rerank-secret"+ assert projected == {+ "base_url": "https://rerank.example.test/v1/inference",+ "model": "rerank-model",+ "api_key": None,+ "has_api_key": True,+ }++[email protected]("missing", ["base_url", "model", "api_key"])+def test_memory_config_rejects_partially_filled_rerank(missing: str) -> None:+ processing = _complete_processing()+ rerank = {+ "base_url": "https://rerank.example.test/v1/inference",+ "model": "rerank-model",+ "api_key": "rerank-secret",+ }+ rerank.pop(missing)+ processing["rerank"] = rerank++ with pytest.raises(ValueError, match="Memory rerank endpoint must include"):+ V2Config.from_payload(+ _payload({"enabled": False, "processing": processing})+ )++@pytest.mark.parametrize("memory",[diff --git a/tests/test_memory_everos.py b/tests/test_memory_everos.pyindex b4000f184..82c66351d 100644--- a/tests/test_memory_everos.py+++ b/tests/test_memory_everos.py@@ -76,6 +76,50 @@ def _health_envelope(recorder) -> dict:}+ ("rerank", "disabled_features"),+ [(False, ["agentic_search"]), (True, [])],+)+def test_health_accepts_additive_typed_capabilities_and_surfaces_rerank_state(+ rerank: bool,+ disabled_features: list[str],+) -> None:+ payload = _health_envelope({"state": "active", "reason": None})+ payload["capabilities"]["future_capability"] = False+ payload["capabilities"]["rerank"] = rerank+ payload["disabled_features"] = disabled_features++ def handler(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json=payload)++ async def run():+ return await EverOSPort(Path("/tmp/everos.sock")).health_snapshot()++ with _sidecar_transport(handler):+ snapshot = asyncio.run(run())++ assert snapshot.capabilities["rerank"] is rerank+ assert snapshot.capabilities["future_capability"] is False+ assert snapshot.disabled_features == tuple(disabled_features)+++def test_health_rejects_a_truncated_core_capability_set() -> None:+ payload = _health_envelope({"state": "active", "reason": None})+ del payload["capabilities"]["parser"]++ def handler(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json=payload)++ async def run():+ return await EverOSPort(Path("/tmp/everos.sock")).health_snapshot()++ with _sidecar_transport(handler):+ with pytest.raises(MemoryProviderFailure) as raised:+ asyncio.run(run())++ assert raised.value.error == "memory_provider_response_invalid"++def test_add_and_flush_are_separate_and_parse_provider_envelopes() -> None:requests: list[tuple[str, dict]] = []@@ -872,6 +916,92 @@ def test_processing_preflight_projects_sanitized_provider_error() -> None:assert "secret" not in result.failure.diagnostic.message+def test_processing_preflight_probes_configured_rerank_endpoint() -> None:+ requests: list[httpx.Request] = []+ recorded: list[dict[str, object]] = []++ def handler(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ if request.url.path.endswith("/chat/completions"):+ return httpx.Response(200, json={"choices": [{"message": {"content": "OK"}}]})+ if request.url.path.endswith("/embeddings"):+ return httpx.Response(200, json={"data": [{"embedding": [0.1]}]})+ return httpx.Response(200, json={"scores": [[0.9]]})++ async def run():+ return await EverOSPort(+ Path("/tmp/everos.sock"),+ llm_base_url="https://llm.example.test/v1",+ llm_model="chat",+ llm_api_key="llm-secret",+ embedding_base_url="https://embed.example.test/v1",+ embedding_model="embed",+ embedding_api_key="embedding-secret",+ rerank_base_url="https://rerank.example.test/v1/inference",+ rerank_model="Qwen/Qwen3-Reranker-4B",+ rerank_api_key="rerank-secret",+ preflight_call_recorder=lambda **kwargs: recorded.append(kwargs),+ ).preflight()++ real_async_client = httpx.AsyncClient+ with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ client_type.side_effect = lambda **kwargs: real_async_client(+ transport=httpx.MockTransport(handler), **kwargs+ )+ result = asyncio.run(run())++ assert result.ok is True+ assert [request.url.path for request in requests] == [+ "/v1/chat/completions",+ "/v1/embeddings",+ "/v1/inference/Qwen/Qwen3-Reranker-4B",+ ]+ assert json.loads(requests[-1].content) == {+ "queries": ["OK"],+ "documents": ["OK"],+ }+ assert requests[-1].headers["authorization"] == "Bearer rerank-secret"+ assert recorded[-1]["model"] == "Qwen/Qwen3-Reranker-4B"+ assert "model" not in recorded[-1]["request"]+++def test_processing_preflight_returns_typed_rerank_failure() -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ if request.url.path.endswith("/chat/completions"):+ return httpx.Response(200, json={"choices": [{"message": {"content": "OK"}}]})+ if request.url.path.endswith("/embeddings"):+ return httpx.Response(200, json={"data": [{"embedding": [0.1]}]})+ return httpx.Response(401, json={"error": {"code": "invalid_key"}})++ async def run():+ return await EverOSPort(+ Path("/tmp/everos.sock"),+ llm_base_url="https://llm.example.test/v1",+ llm_model="chat",+ llm_api_key="llm-secret",+ embedding_base_url="https://embed.example.test/v1",+ embedding_model="embed",+ embedding_api_key="embedding-secret",+ rerank_base_url="https://rerank.example.test/v1/inference",+ rerank_model="rerank-model",+ rerank_api_key="rerank-secret",+ ).preflight()++ real_async_client = httpx.AsyncClient+ with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ client_type.side_effect = lambda **kwargs: real_async_client(+ transport=httpx.MockTransport(handler), **kwargs+ )+ result = asyncio.run(run())++ assert result.ok is False+ assert result.failure is not None+ assert result.failure.error == "memory_rerank_unavailable"+ assert result.failure.diagnostic.side == "rerank"+ assert result.failure.diagnostic.http_status == 401+ assert result.failure.diagnostic.provider_error_code == "invalid_key"++def test_processing_preflight_scrubs_provider_error_code() -> None:def handler(request: httpx.Request) -> httpx.Response:return httpx.Response(diff --git a/tests/test_memory_process.py b/tests/test_memory_process.pyindex 81f34284b..ef2c4eee1 100644--- a/tests/test_memory_process.py+++ b/tests/test_memory_process.py@@ -287,12 +287,30 @@ def test_sidecar_child_environment_is_allowlisted_and_generated_config_has_no_keprocess = EverOSProcess(sys.executable,effective_home=tmp_path,- settings=_settings(),+ settings=replace(_settings(), timezone="UTC"),)process._prepare_owned_directories()process._write_generated_config()environment = process._child_environment()generated = (tmp_path / "memory" / "generated" / "everos.toml").read_text(encoding="utf-8")+ expected_generated = "\n".join(+ (+ "# Generated by Avibe. No API keys are stored here.",+ "[memory]",+ 'timezone = "UTC"',+ "",+ "[memorize]",+ 'mode = "chat"',+ "",+ "[rerank]",+ 'model = ""',+ 'base_url = ""',+ "",+ "[multimodal]",+ f'file_uri_allow_dirs = ["{attachment_pin_root(tmp_path)}"]',+ "",+ )+ )assert environment["EVEROS_LLM__API_KEY"] == "llm-secret"assert environment["EVEROS_MULTIMODAL__BASE_URL"] == environment["EVEROS_LLM__BASE_URL"]@@ -302,15 +320,47 @@ def test_sidecar_child_environment_is_allowlisted_and_generated_config_has_no_keattachment_pin_root(tmp_path))assert environment["EVEROS_EMBEDDING__API_KEY"] == "embedding-secret"+ assert not any(key.startswith("EVEROS_RERANK__") for key in environment)assert "HTTP_PROXY" not in environmentassert "SSL_CERT_FILE" not in environmentassert "llm-secret" not in generatedassert "embedding-secret" not in generatedassert "rerank" in generated+ assert '[rerank]\nmodel = ""\nbase_url = ""' in generated+ assert generated == expected_generatedassert str(attachment_pin_root(tmp_path)) in generatedassert "AVIBE_MEMORY_CALL_LOG_DB" not in environment+def test_configured_rerank_stays_env_only_when_env_overrides_toml(tmp_path: Path) -> None:+ settings = replace(+ _settings(),+ timezone="UTC",+ rerank_base_url="https://rerank.example.test/v1/inference",+ rerank_model="Qwen/Qwen3-Reranker-4B",+ rerank_api_key="rerank-secret",+ )+ process = EverOSProcess(+ sys.executable,+ effective_home=tmp_path,+ settings=settings,+ )+ process._prepare_owned_directories()+ process._write_generated_config()++ environment = process._child_environment()+ generated = (tmp_path / "memory" / "generated" / "everos.toml").read_text(+ encoding="utf-8"+ )+ parsed = memory_process.tomllib.loads(generated)++ assert environment["EVEROS_RERANK__BASE_URL"] == settings.rerank_base_url+ assert environment["EVEROS_RERANK__MODEL"] == settings.rerank_model+ assert environment["EVEROS_RERANK__API_KEY"] == "rerank-secret"+ assert parsed["rerank"] == {"model": "", "base_url": ""}+ assert "rerank-secret" not in generated++def test_sidecar_child_home_preparation_hardens_every_created_directory(tmp_path: Path,) -> None:diff --git a/tests/test_memory_runtime.py b/tests/test_memory_runtime.pyindex db779a1be..8dff08923 100644--- a/tests/test_memory_runtime.py+++ b/tests/test_memory_runtime.py@@ -3365,6 +3365,44 @@ async def test_runtime_reconciliation_restarts_sidecar_with_fresh_child_settingsawait memory_runtime_factory.close(runtime)+async def test_runtime_reconciliation_rolls_sidecar_for_rerank_configuration(+ memory_runtime_factory,+) -> None:+ factory = FakeEverOSProcessFactory()+ processing = MemoryProcessingConfig(+ llm=MemoryEndpointConfig("https://llm.example.test/v1", "chat", "llm-key"),+ embedding=MemoryEndpointConfig(+ "https://embed.example.test/v1", "embed", "embed-key"+ ),+ )+ initial = MemoryConfig(enabled=True, processing=processing)+ runtime = memory_runtime_factory(+ initial,+ artifact_manager=_installed_artifact(),+ process_factory=factory,+ )+ assert (await runtime.reconcile(initial))["ok"] is True++ configured = replace(+ initial,+ processing=replace(+ processing,+ rerank=MemoryEndpointConfig(+ "https://rerank.example.test/v1/inference",+ "Qwen/Qwen3-Reranker-4B",+ "rerank-key",+ ),+ ),+ )+ assert (await runtime.reconcile(configured))["ok"] is True++ assert len(factory.supervised) == 2+ assert factory.supervised[0].stopped is True+ assert factory.supervised[1].settings.rerank_model == "Qwen/Qwen3-Reranker-4B"+ assert factory.supervised[1].settings.rerank_api_key == "rerank-key"+ await memory_runtime_factory.close(runtime)++async def test_runtime_preflight_failure_keeps_existing_sidecar_running(monkeypatch,memory_runtime_factory,diff --git a/tests/test_memory_sidecar.py b/tests/test_memory_sidecar.pyindex cd6a1b06d..796c1196b 100644--- a/tests/test_memory_sidecar.py+++ b/tests/test_memory_sidecar.py@@ -499,6 +499,9 @@ def test_processing_probe_builds_the_adapter_from_child_environment_only(monkeypmonkeypatch.setenv("EVEROS_EMBEDDING__BASE_URL", "https://embed.example.test/v1")monkeypatch.setenv("EVEROS_EMBEDDING__MODEL", "embed-model")monkeypatch.setenv("EVEROS_EMBEDDING__API_KEY", "embedding-secret")+ monkeypatch.setenv("EVEROS_RERANK__BASE_URL", "https://rerank.example.test/v1/inference")+ monkeypatch.setenv("EVEROS_RERANK__MODEL", "rerank-model")+ monkeypatch.setenv("EVEROS_RERANK__API_KEY", "rerank-secret")monkeypatch.setattr(everos, "EverOSPort", _Provider)assert _processing_healthy_from_child_environment() is True@@ -510,4 +513,7 @@ def test_processing_probe_builds_the_adapter_from_child_environment_only(monkeyp"embedding_base_url": "https://embed.example.test/v1","embedding_model": "embed-model","embedding_api_key": "embedding-secret",+ "rerank_base_url": "https://rerank.example.test/v1/inference",+ "rerank_model": "rerank-model",+ "rerank_api_key": "rerank-secret",}diff --git a/tests/test_ui_memory_routes.py b/tests/test_ui_memory_routes.pyindex 5b4c23c1e..1d4a61c0d 100644--- a/tests/test_ui_memory_routes.py+++ b/tests/test_ui_memory_routes.py@@ -62,6 +62,64 @@ def test_memory_rebuild_result_preserves_closed_preflight_diagnostic() -> None:}+def test_memory_settings_patch_accepts_optional_complete_rerank_endpoint() -> None:+ current = V2Config(+ mode="self_host",+ version="v2",+ slack=SlackConfig(bot_token=""),+ runtime=RuntimeConfig(default_cwd="."),+ agents=AgentsConfig(),+ )+ target, confirm_rebuild = ui_memory_routes._memory_settings_patch(+ current,+ {+ "processing": {+ "rerank": {+ "base_url": "https://rerank.example.test/v1/inference",+ "model": "rerank-model",+ "api_key": "rerank-secret",+ }+ }+ },+ )+ candidate = ui_memory_routes._memory_candidate_config(current, target)++ assert confirm_rebuild is False+ assert candidate.memory.processing.rerank == MemoryEndpointConfig(+ "https://rerank.example.test/v1/inference",+ "rerank-model",+ "rerank-secret",+ )+++def test_memory_settings_key_clear_removes_the_optional_rerank_endpoint() -> None:+ current = V2Config(+ mode="self_host",+ version="v2",+ slack=SlackConfig(bot_token=""),+ runtime=RuntimeConfig(default_cwd="."),+ agents=AgentsConfig(),+ memory=MemoryConfig(+ enabled=False,+ processing=MemoryProcessingConfig(+ rerank=MemoryEndpointConfig(+ "https://rerank.example.test/v1/inference",+ "rerank-model",+ "rerank-secret",+ )+ ),+ ),+ )++ target, _confirm_rebuild = ui_memory_routes._memory_settings_patch(+ current,+ {"processing": {"rerank": {"api_key": None}}},+ )+ candidate = ui_memory_routes._memory_candidate_config(current, target)++ assert candidate.memory.processing.rerank is None++def _save_config(tmp_path) -> None:V2Config(mode="self_host",@@ -81,6 +139,85 @@ def _save_memory(memory: MemoryConfig) -> V2Config:)+def test_enabled_rerank_change_runs_typed_preflight_before_persisting(+ monkeypatch,+ tmp_path,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)+ _save_memory(+ MemoryConfig(+ enabled=True,+ processing=MemoryProcessingConfig(+ llm=MemoryEndpointConfig(+ "https://llm.example.test/v1", "chat", "llm-key"+ ),+ embedding=MemoryEndpointConfig(+ "https://embed.example.test/v1", "embed", "embed-key"+ ),+ ),+ )+ )+ from config.paths import get_config_path++ config_before = get_config_path().read_bytes()++ async def preflight(*, payload: dict, user_key: str):+ rerank = payload["memory"]["processing"]["rerank"]+ assert user_key == "avibe:local"+ assert rerank["model"] == "rerank-model"+ assert rerank["api_key"] == "rerank-secret"+ return {+ "status_code": 409,+ "body": {+ "ok": False,+ "error": "memory_rerank_unavailable",+ "diagnostic": {+ "side": "rerank",+ "http_status": 401,+ "provider_error_code": "invalid_key",+ "message": "provider_error",+ },+ },+ }++ async def unexpected_reconcile():+ pytest.fail("failed rerank admission must not reconcile or persist")++ monkeypatch.setattr(internal_client, "memory_preflight", preflight)+ monkeypatch.setattr(internal_client, "reconcile_memory", unexpected_reconcile)+ client = app.test_client()+ response = client.patch(+ "/api/memory/settings",+ json={+ "processing": {+ "rerank": {+ "base_url": "https://rerank.example.test/v1/inference",+ "model": "rerank-model",+ "api_key": "rerank-secret",+ }+ }+ },+ headers=csrf_headers(client, "http://127.0.0.1:15131"),+ base_url="http://127.0.0.1:15131",+ environ_base={"REMOTE_ADDR": "127.0.0.1"},+ )++ assert response.status_code == 409+ assert response.get_json() == {+ "status": "failed",+ "error": "memory_rerank_unavailable",+ "diagnostic": {+ "side": "rerank",+ "http_status": 401,+ "provider_error_code": "invalid_key",+ "message": "provider_error",+ },+ }+ assert get_config_path().read_bytes() == config_before+ assert V2Config.load().memory.processing.rerank is None++def _save_remote_config(tmp_path) -> V2Config:_save_config(tmp_path)config = V2Config.load()diff --git a/ui/src/components/settings/memory/MemoryLogPanel.test.tsx b/ui/src/components/settings/memory/MemoryLogPanel.test.tsxindex b0a36fffc..398d402a5 100644--- a/ui/src/components/settings/memory/MemoryLogPanel.test.tsx+++ b/ui/src/components/settings/memory/MemoryLogPanel.test.tsx@@ -402,6 +402,8 @@ describe('Memory Log bounded helpers and static states', () => {expect(memoryLogEnumLabel(translate as never, 'reason', 'runs_missing')).toBe('memory.log.reason.runsMissing');expect(memoryLogEnumLabel(translate as never, 'status', 'ok')).toBe('memory.log.status.ok');+ expect(memoryLogEnumLabel(translate as never, 'callKind', 'rerank'))+ .toBe('memory.log.callKind.rerank');expect(memoryLogEnumLabel(translate as never, 'status', 'future_status')).toBe('future_status');});});diff --git a/ui/src/components/settings/memory/MemorySettingsPanel.test.tsx b/ui/src/components/settings/memory/MemorySettingsPanel.test.tsxindex 75fd5d060..6f09780e1 100644--- a/ui/src/components/settings/memory/MemorySettingsPanel.test.tsx+++ b/ui/src/components/settings/memory/MemorySettingsPanel.test.tsx@@ -79,6 +79,26 @@ afterEach(() => {});describe('MemorySettingsPanel', () => {+ it('renders the optional reranking endpoint for released settings without it', () => {+ render(+ <MemorySettingsPanel+ settings={legacySettings}+ maintenance={null}+ maintenanceError={null}+ dependencyReady+ onSaved={() => undefined}+ onReloadSettings={() => undefined}+ onReloadMaintenance={() => undefined}+ onClearAll={() => undefined}+ clearing={false}+ />,+ );++ expect(screen.getByText('memory.settings.rerankTitle')).not.toBeNull();+ expect(screen.getAllByPlaceholderText('memory.settings.baseUrlPlaceholder')).toHaveLength(3);+ expect(screen.getAllByPlaceholderText('memory.settings.modelPlaceholder')).toHaveLength(3);+ });+it('locks settings mutations while the page owns another mutation', () => {render(<MemorySettingsPaneldiff --git a/ui/src/components/settings/memory/MemorySettingsPanel.tsx b/ui/src/components/settings/memory/MemorySettingsPanel.tsxindex e78488225..d34186334 100644--- a/ui/src/components/settings/memory/MemorySettingsPanel.tsx+++ b/ui/src/components/settings/memory/MemorySettingsPanel.tsx@@ -26,6 +26,13 @@ import { isMemoryOk, memoryErrorMessage } from '../../../lib/memoryRead';type MemorySettingsOk = Extract<MemorySettingsResult, { status: 'ok' }>;+const EMPTY_ENDPOINT: MemoryEndpointConfig = {+ base_url: null,+ model: null,+ api_key: null,+ has_api_key: false,+};+const EndpointFields: React.FC<{title: string;help: string;@@ -36,6 +43,7 @@ const EndpointFields: React.FC<{disabled: boolean;identityHint?: string;canClearKey: boolean;+ clearKeyLabel?: string;}> = ({title,help,@@ -46,8 +54,10 @@ const EndpointFields: React.FC<{disabled,identityHint,canClearKey,+ clearKeyLabel,}) => {const { t } = useTranslation();+ const clearLabel = clearKeyLabel ?? t('memory.settings.clearKeyLabel');return (<div className="flex flex-col gap-3 rounded-xl border border-border bg-surface p-4"><div className="flex items-center gap-2">@@ -100,7 +110,7 @@ const EndpointFields: React.FC<{type="button"role="checkbox"aria-checked={draft.clearKey}- aria-label={t('memory.settings.clearKeyLabel')}+ aria-label={clearLabel}disabled={disabled}onClick={() => onChange({ ...draft, clearKey: !draft.clearKey, apiKey: '' })}className="mt-0.5 flex w-fit items-center gap-2 text-[11.5px] text-muted disabled:cursor-not-allowed disabled:opacity-50"@@ -111,7 +121,7 @@ const EndpointFields: React.FC<{disabled={disabled}className="size-3.5"/>- {t('memory.settings.clearKeyLabel')}+ {clearLabel}</button>) : null}</div>@@ -164,6 +174,7 @@ export const MemorySettingsPanel: React.FC<{const [enabledDraft, setEnabledDraft] = useState(settings.enabled);const [llmDraft, setLlmDraft] = useState<EndpointDraft>(() => draftFromConfig(settings.processing.llm));const [embeddingDraft, setEmbeddingDraft] = useState<EndpointDraft>(() => draftFromConfig(settings.processing.embedding));+ const [rerankDraft, setRerankDraft] = useState<EndpointDraft>(() => draftFromConfig(settings.processing.rerank ?? EMPTY_ENDPOINT));const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);const [confirmRebuildOpen, setConfirmRebuildOpen] = useState(false);@@ -174,6 +185,7 @@ export const MemorySettingsPanel: React.FC<{setEnabledDraft(settings.enabled);setLlmDraft(draftFromConfig(settings.processing.llm));setEmbeddingDraft(draftFromConfig(settings.processing.embedding));+ setRerankDraft(draftFromConfig(settings.processing.rerank ?? EMPTY_ENDPOINT));}, [settings]);const rebuildRequired = settings.rebuild_required === true;@@ -196,10 +208,18 @@ export const MemorySettingsPanel: React.FC<{allowClear,false,);- if (llmPatch || embeddingPatch) {+ const rerankPatch = buildEndpointPatch(+ rerankDraft,+ settings.processing.rerank ?? EMPTY_ENDPOINT,+ allowClear,+ false,+ true,+ );+ if (llmPatch || embeddingPatch || rerankPatch) {patch.processing = {};if (llmPatch) patch.processing.llm = llmPatch;if (embeddingPatch) patch.processing.embedding = embeddingPatch;+ if (rerankPatch) patch.processing.rerank = rerankPatch;}return patch;};@@ -255,7 +275,8 @@ export const MemorySettingsPanel: React.FC<{setPendingPatch(null);const validationFailure =failure.error === 'memory_embedding_unavailable' ||- failure.error === 'memory_llm_unavailable';+ failure.error === 'memory_llm_unavailable' ||+ failure.error === 'memory_rerank_unavailable';if (!validationFailure || failure.rebuild_required === true) {onReloadSettings();onReloadMaintenance();@@ -386,6 +407,19 @@ export const MemorySettingsPanel: React.FC<{canClearKey={canClearKeys}/>+ <EndpointFields+ title={t('memory.settings.rerankTitle')}+ help={t('memory.settings.rerankHelp')}+ helpLabel={t('memory.settings.rerankHelpLabel')}+ draft={rerankDraft}+ original={settings.processing.rerank ?? EMPTY_ENDPOINT}+ onChange={setRerankDraft}+ disabled={busy}+ identityHint={t('memory.settings.rerankIdentityHint')}+ canClearKey={canClearKeys}+ clearKeyLabel={t('memory.settings.rerankClearLabel')}+ />+{error ? (<div className="rounded-xl border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive-ink">{error}</div>) : null}diff --git a/ui/src/components/settings/memory/memoryLog.ts b/ui/src/components/settings/memory/memoryLog.tsindex 070e067dc..aa51e6ece 100644--- a/ui/src/components/settings/memory/memoryLog.ts+++ b/ui/src/components/settings/memory/memoryLog.ts@@ -38,6 +38,7 @@ const ENUM_LABEL_KEYS = {llm: 'llm',multimodal_llm: 'multimodalLlm',embedding: 'embedding',+ rerank: 'rerank',},callStage: {processing_preflight: 'processingPreflight',diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 685d5da99..7967323bb 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -1845,6 +1845,7 @@ export type MemoryEndpointConfig = {export type MemoryProcessingConfig = {llm: MemoryEndpointConfig;embedding: MemoryEndpointConfig;+ rerank?: MemoryEndpointConfig;};export type MemorySettings = {@@ -1870,12 +1871,13 @@ export type MemorySettingsPatch = {processing?: {llm?: MemoryEndpointPatch;embedding?: MemoryEndpointPatch;+ rerank?: MemoryEndpointPatch;};confirm_rebuild?: boolean;};export type MemoryFailureDiagnostic = {- side?: 'embedding' | 'llm';+ side?: 'embedding' | 'llm' | 'rerank';http_status?: number | null;provider_error_code?: string | null;message?: string;diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 9422424e9..c92d6b1d1 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1606,6 +1606,7 @@"memory_embedding_rebuild_required": "Changing the embedding endpoint or model rebuilds the Memory index. Confirm to continue.","memory_embedding_unavailable": "The embedding provider is unavailable","memory_llm_unavailable": "The LLM provider is unavailable",+ "memory_rerank_unavailable": "The reranking provider is unavailable","provider_request_timed_out": "The provider request timed out.","provider_response_too_large": "The provider response exceeded the safety limit.","provider_unavailable": "The provider is unavailable.",@@ -4170,7 +4171,7 @@},"providerChecks": {"title": "Provider checks",- "help": "These installation-level checks validate the configured language and embedding providers. They are not attached to any conversation.",+ "help": "These installation-level checks validate the configured language, embedding, and optional reranking providers. They are not attached to any conversation.","helpLabel": "About provider checks","description": "Recent checks made while validating Memory settings or a rebuild.","empty": "No provider checks recorded.",@@ -4320,7 +4321,8 @@"callKind": {"llm": "Language model","multimodalLlm": "Multimodal model",- "embedding": "Embedding model"+ "embedding": "Embedding model",+ "rerank": "Reranking model"},"callStage": {"processingPreflight": "Provider check",@@ -4361,6 +4363,10 @@"embeddingTitle": "Embedding model","embeddingHelp": "Memory uses this model to index memories so you can search them. Changing the embedding endpoint or model requires rebuilding the index.","embeddingHelpLabel": "About the embedding model",+ "rerankTitle": "Reranking model (optional)",+ "rerankHelp": "Memory uses this model to score search results for advanced recall. Enter a reranking base URL, model name, and API key to enable it.",+ "rerankHelpLabel": "About the reranking model",+ "rerankClearLabel": "Remove reranking endpoint","baseUrl": "Base URL","baseUrlPlaceholder": "https://api.example.com/v1","model": "Model",@@ -4395,7 +4401,8 @@"retryingRebuild": "Rebuilding…","rebuildCompleted": "Memory index rebuild completed.","rebuildFailed": "Memory index rebuild failed.",- "embeddingIdentityHint": "Changing the embedding endpoint or model rebuilds the local index. Your memories are kept."+ "embeddingIdentityHint": "Changing the embedding endpoint or model rebuilds the local index. Your memories are kept.",+ "rerankIdentityHint": "Leave all three fields empty to keep the standard Memory search tier."},"clear": {"button": "Clear Memory Data",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 03324832c..572942c4b 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1606,6 +1606,7 @@"memory_embedding_rebuild_required": "更改 Embedding 端点或模型会重建记忆索引。请确认后继续。","memory_embedding_unavailable": "Embedding 提供商不可用","memory_llm_unavailable": "LLM 提供商不可用",+ "memory_rerank_unavailable": "重排序服务商不可用","provider_request_timed_out": "提供商请求超时。","provider_response_too_large": "提供商响应超过安全限制。","provider_unavailable": "提供商不可用。",@@ -4170,7 +4171,7 @@},"providerChecks": {"title": "服务商检查",- "help": "这些安装级检查用于验证已配置的语言模型和向量模型服务,不会关联到任何对话。",+ "help": "这些安装级检查用于验证已配置的语言模型、向量模型和可选重排序服务,不会关联到任何对话。","helpLabel": "关于服务商检查","description": "验证记忆设置或重建时最近执行的检查。","empty": "暂无服务商检查记录。",@@ -4320,7 +4321,8 @@"callKind": {"llm": "语言模型","multimodalLlm": "多模态模型",- "embedding": "向量模型"+ "embedding": "向量模型",+ "rerank": "重排序模型"},"callStage": {"processingPreflight": "服务商检查",@@ -4361,6 +4363,10 @@"embeddingTitle": "向量模型(Embedding)","embeddingHelp": "记忆功能用这个模型为记忆建立索引,让你可以搜索记忆。更改向量模型接口地址或模型后需要重建索引。","embeddingHelpLabel": "关于向量模型",+ "rerankTitle": "重排序模型(可选)",+ "rerankHelp": "记忆功能用这个模型为高级召回结果评分。填写重排序接口地址、模型名称和 API Key 后即可启用。",+ "rerankHelpLabel": "关于重排序模型",+ "rerankClearLabel": "移除重排序端点","baseUrl": "Base URL","baseUrlPlaceholder": "https://api.example.com/v1","model": "模型",@@ -4395,7 +4401,8 @@"retryingRebuild": "正在重建…","rebuildCompleted": "记忆索引重建完成。","rebuildFailed": "记忆索引重建失败。",- "embeddingIdentityHint": "更改向量模型接口地址或模型会重建本地索引,已有记忆不会丢失。"+ "embeddingIdentityHint": "更改向量模型接口地址或模型会重建本地索引,已有记忆不会丢失。",+ "rerankIdentityHint": "三个字段全部留空时,记忆功能会继续使用标准搜索层级。"},"clear": {"button": "清理记忆数据",diff --git a/ui/src/lib/memorySettings.test.ts b/ui/src/lib/memorySettings.test.tsindex a46f1fa11..0c97c5271 100644--- a/ui/src/lib/memorySettings.test.ts+++ b/ui/src/lib/memorySettings.test.ts@@ -77,4 +77,24 @@ describe('buildEndpointPatch', () => {model: 'changed-model',});});++ it('removes every field when clearing an optional endpoint', () => {+ expect(buildEndpointPatch(+ {+ baseUrl: 'https://rerank.example.test/v1/inference',+ model: 'rerank-model',+ apiKey: '',+ clearKey: true,+ },+ {+ base_url: 'https://rerank.example.test/v1/inference',+ model: 'rerank-model',+ api_key: null,+ has_api_key: true,+ },+ true,+ false,+ true,+ )).toEqual({ api_key: null, base_url: null, model: null });+ });});diff --git a/ui/src/lib/memorySettings.ts b/ui/src/lib/memorySettings.tsindex 4bf710bd2..7fba1ef4f 100644--- a/ui/src/lib/memorySettings.ts+++ b/ui/src/lib/memorySettings.ts@@ -37,6 +37,7 @@ export function buildEndpointPatch(original: MemoryEndpointConfig,allowClear: boolean,identityLocked = false,+ clearEndpoint = false,): MemoryEndpointPatch | undefined {const patch: MemoryEndpointPatch = {};let changed = false;@@ -58,6 +59,10 @@ export function buildEndpointPatch(changed = true;} else if (draft.clearKey && allowClear) {patch.api_key = null;+ if (clearEndpoint) {+ patch.base_url = null;+ patch.model = null;+ }changed = true;}return changed ? patch : undefined;diff --git a/vibe/ui_memory_routes.py b/vibe/ui_memory_routes.pyindex 7f3479737..9ba03297b 100644--- a/vibe/ui_memory_routes.py+++ b/vibe/ui_memory_routes.py@@ -157,23 +157,38 @@ def _memory_settings_patch(current: V2Config, patch_payload: object) -> tuple[diif not isinstance(confirm_rebuild, bool):raise ValueError("invalid_memory_patch")target = memory_config_to_payload(current.memory, include_secrets=True)- for endpoint in ("llm", "embedding"):- target["processing"][endpoint].pop("has_api_key", None)+ endpoints = ("llm", "embedding", "rerank")+ for endpoint in endpoints:+ if endpoint in target["processing"]:+ target["processing"][endpoint].pop("has_api_key", None)if "enabled" in patch_payload:if not isinstance(patch_payload["enabled"], bool):raise ValueError("invalid_memory_patch")target["enabled"] = patch_payload["enabled"]processing_patch = patch_payload.get("processing")if processing_patch is not None:- if not isinstance(processing_patch, dict) or not set(processing_patch).issubset({"llm", "embedding"}):+ if not isinstance(processing_patch, dict) or not set(processing_patch).issubset(endpoints):raise ValueError("invalid_memory_patch")- for endpoint in ("llm", "embedding"):+ for endpoint in endpoints:endpoint_patch = processing_patch.get(endpoint)if endpoint_patch is None:continueif not isinstance(endpoint_patch, dict) or not set(endpoint_patch).issubset({"base_url", "model", "api_key"}):raise ValueError("invalid_memory_patch")- target["processing"][endpoint].update(endpoint_patch)+ target["processing"].setdefault(+ endpoint,+ {"base_url": None, "model": None, "api_key": None},+ ).update(endpoint_patch)+ if (+ endpoint == "rerank"+ and set(endpoint_patch) == {"api_key"}+ and endpoint_patch["api_key"] in {None, ""}+ ):+ target["processing"][endpoint] = {+ "base_url": None,+ "model": None,+ "api_key": None,+ }explicit_key_clear = any(endpoint_patch.get("api_key") in {None, ""}@@ -211,6 +226,18 @@ def _memory_embedding_configuration_changed(current: V2Config, candidate: V2Conf)+def _memory_rerank_configuration_changed(current: V2Config, candidate: V2Config) -> bool:+ """Return whether the optional reranking provider configuration changed."""++ def endpoint_values(config: V2Config) -> tuple[str | None, str | None, str | None]:+ endpoint = config.memory.processing.rerank+ if endpoint is None:+ return (None, None, None)+ return (endpoint.base_url, endpoint.model, endpoint.api_key)++ return endpoint_values(current) != endpoint_values(candidate)++def _memory_preflight_required(candidate: V2Config) -> bool:"""Require live admission unless a disabled candidate is still incomplete."""@@ -228,7 +255,7 @@ def _memory_api_key_only_patch(patch_payload: object) -> bool:processing = patch_payload.get("processing")if not isinstance(processing, dict) or not processing:return False- if not set(processing).issubset({"llm", "embedding"}):+ if not set(processing).issubset({"llm", "embedding", "rerank"}):return Falsereturn all(isinstance(endpoint, dict) and set(endpoint) == {"api_key"}@@ -251,7 +278,7 @@ def _memory_factory_reset_repair_patch(patch_payload: object) -> bool:processing = patch_payload.get("processing")if not isinstance(processing, dict) or not processing:return False- if not set(processing).issubset({"llm", "embedding"}):+ if not set(processing).issubset({"llm", "embedding", "rerank"}):return Falsereturn all(isinstance(endpoint, dict)@@ -506,6 +533,7 @@ def _memory_repair_result(payload: dict, status_code: int) -> tuple[dict, int]:"memory_repair_failed": 503,"memory_embedding_unavailable": 409,"memory_llm_unavailable": 409,+ "memory_rerank_unavailable": 409,}.get(error)if expected_status is None or expected_status != status_code:return protocol_failure, 503@@ -712,6 +740,7 @@ async def _apply_memory_settings_patch(target_payload, confirm_rebuild = _memory_settings_patch(current, patch_payload)candidate = _memory_candidate_config(current, target_payload)identity_changed = _memory_embedding_configuration_changed(current, candidate)+ rerank_changed = _memory_rerank_configuration_changed(current, candidate)pending_marker = current.memory.recovery_intent == "rebuild"pending_factory_reset = current.memory.recovery_intent == "factory_reset"except (TypeError, ValueError):@@ -792,7 +821,13 @@ async def _apply_memory_settings_patch(recovery_intent = "rebuild" if pending_marker or identity_changed else None- if identity_changed and confirm_rebuild and _memory_preflight_required(candidate):+ rerank_preflight = (+ rerank_changed and candidate.memory.processing.rerank is not None+ )+ if (+ ((identity_changed and confirm_rebuild) or rerank_preflight)+ and _memory_preflight_required(candidate)+ ):from config.v2_config import memory_config_to_payloadpreflight = await _memory_internal_result(lambda: internal_client.memory_preflight(