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): preflight processing providers before rebuild (#1369)
rkrkrkkb1eee6a48d4b
diff --git a/core/internal_server.py b/core/internal_server.pyindex f92655c37..40008f331 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -1106,6 +1106,23 @@ def create_app(logger.exception("internal memory runtime install failed")return JSONResponse(status_code=503, content={"ok": False, "reason": "memory_runtime_install_failed"})+ @app.post("/internal/memory/preflight")+ async def _memory_preflight(request: Request) -> Any:+ if _verified_memory_ui_user_key(request) is None:+ return JSONResponse(status_code=403, content={"ok": False, "error": "memory_access_denied"})+ payload = await _safe_json(request)+ try:+ from config.v2_config import memory_config_from_payload+ from core.memory.runtime import MemoryRuntime+ config = memory_config_from_payload(payload.get("memory", payload) if isinstance(payload, dict) else {})+ runtime = _memory_runtime()+ if runtime is None:+ return JSONResponse(status_code=503, content={"ok": False, "error": "memory_runtime_missing"})+ return JSONResponse(status_code=200, content=await runtime.preflight(config))+ except Exception:+ logger.exception("internal memory preflight failed")+ return JSONResponse(status_code=503, content={"ok": False, "error": "memory_rebuild_failed"})+def _memory_cli_scope(request: Request) -> tuple[str, str] | None:from core.memory.http_headers import CALLER_SESSION_HEADERdiff --git a/core/memory/everos.py b/core/memory/everos.pyindex 56b7fd1a5..73cdb88d7 100644--- a/core/memory/everos.py+++ b/core/memory/everos.py@@ -5,11 +5,12 @@ from __future__ import annotationsimport asyncioimport jsonimport logging+import reimport mathimport timefrom collections import dequefrom collections.abc import Awaitable, Callable-from dataclasses import dataclass, field+from dataclasses import dataclass, field, replacefrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Deque, Literal, Protocol, runtime_checkable@@ -25,6 +26,7 @@ from core.memory.types import (MemoryProfileTrait,ProviderSessionRef,is_memory_error_code,+ MemoryPreflightDiagnostic,)from core.memory.observations import (AddAck,@@ -49,6 +51,8 @@ _SIDECAR_TIMEOUT_SECONDS = 20.0_ADD_TIMEOUT_SECONDS = 30.0_FLUSH_TIMEOUT_SECONDS = 300.0_PROCESSING_TIMEOUT_SECONDS = 8.0+_PREFLIGHT_TIMEOUT_SECONDS = 5.0+_PREFLIGHT_RESPONSE_BYTES = _MAX_RESPONSE_BYTES_PROFILE_QUERY = "profile"_MAX_PROFILE_TIMESTAMP_MS = 4_102_444_800_000_RECORDER_HEALTH_FALLBACK = {"state": "degraded", "reason": "writer_failures"}@@ -125,6 +129,23 @@ class MemoryProviderSystemFailure(MemoryProviderFailure):super().__init__(closed_error, retryable=True, ambiguous=ambiguous)+@dataclass(frozen=True)+class MemoryPreflightFailure:+ error: Literal["memory_embedding_unavailable", "memory_llm_unavailable"]+ diagnostic: MemoryPreflightDiagnostic+++@dataclass(frozen=True)+class MemoryPreflightResult:+ ok: bool+ failure: MemoryPreflightFailure | None = None++ def payload(self) -> dict[str, object]:+ if self.ok or self.failure is None:+ return {"ok": True}+ return {"ok": False, "error": self.failure.error, "diagnostic": self.failure.diagnostic.payload()}++class EverOSPort:"""Private HTTP adapter for the pinned EverOS sidecar.@@ -148,6 +169,7 @@ class EverOSPort:add_timeout_seconds: float = _ADD_TIMEOUT_SECONDS,flush_timeout_seconds: float = _FLUSH_TIMEOUT_SECONDS,processing_timeout_seconds: float = _PROCESSING_TIMEOUT_SECONDS,+ preflight_call_recorder: Callable[..., None] | None = None,) -> None:self._socket_path = Path(socket_path)self._llm_base_url = _normalized_endpoint_url(llm_base_url)@@ -164,6 +186,7 @@ class EverOSPort:processing_timeout_seconds,_PROCESSING_TIMEOUT_SECONDS,)+ self._preflight_call_recorder = preflight_call_recorderself._processing_lock = asyncio.Lock()@property@@ -463,6 +486,54 @@ class EverOSPort:validator=_valid_embedding_probe_response,)+ async def preflight(self) -> MemoryPreflightResult:+ """Run one bounded request for each configured processing endpoint."""+ 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),+ )+ first_failure = None+ for side, base_url, api_key, path, payload, validator in checks:+ started_at_ms = int(time.time() * 1000)+ started = time.monotonic()+ try:+ failure = await asyncio.wait_for(+ self._preflight_endpoint(+ side,+ base_url,+ api_key,+ path,+ payload,+ validator,+ started_at_ms=started_at_ms,+ started=started,+ ),+ timeout=_PREFLIGHT_TIMEOUT_SECONDS,+ )+ except asyncio.TimeoutError:+ error_name = "memory_llm_unavailable" if side == "llm" else "memory_embedding_unavailable"+ failure = MemoryPreflightFailure(+ error_name,+ MemoryPreflightDiagnostic(side, message="provider_request_timed_out"),+ )+ self._record_preflight(+ side,+ payload,+ None,+ failure,+ base_url=base_url,+ api_key=api_key,+ started_at_ms=started_at_ms,+ duration_ms=_elapsed_ms(started),+ )+ if failure is not None and first_failure is None:+ first_failure = failure+ return MemoryPreflightResult(first_failure is None, first_failure)+def _processing_configured(self) -> bool:return all((@@ -619,13 +690,183 @@ class EverOSPort:return Falsereturn bool(validator(value))+ async def _preflight_endpoint(+ self,+ side,+ base_url,+ api_key,+ path,+ payload,+ validator,+ *,+ started_at_ms,+ started,+ ):+ error_name = "memory_llm_unavailable" if side == "llm" else "memory_embedding_unavailable"+ diagnostic = MemoryPreflightDiagnostic(side)+ if not base_url or not api_key:+ failure = MemoryPreflightFailure(error_name, replace(diagnostic, message="endpoint_not_configured"))+ self._record_preflight(+ side,+ payload,+ None,+ failure,+ base_url=base_url,+ api_key=api_key,+ started_at_ms=started_at_ms,+ duration_ms=_elapsed_ms(started),+ )+ return failure+ try:+ async with httpx.AsyncClient(timeout=httpx.Timeout(_PREFLIGHT_TIMEOUT_SECONDS, connect=2.0), trust_env=False) as client:+ async with client.stream(+ "POST",+ f"{base_url}/{path}",+ json=payload,+ headers={"Authorization": f"Bearer {api_key}"},+ ) as response:+ raw = await _read_bounded_response(response, max_bytes=_PREFLIGHT_RESPONSE_BYTES)+ status_code = response.status_code+ try:+ value = json.loads(raw) if raw else None+ except (TypeError, ValueError):+ value = None+ if 200 <= status_code < 300 and validator(value):+ self._record_preflight(+ side,+ payload,+ value,+ None,+ base_url=base_url,+ api_key=api_key,+ started_at_ms=started_at_ms,+ duration_ms=_elapsed_ms(started),+ )+ return None+ code = None+ message = f"HTTP {status_code}"+ if isinstance(value, dict) and isinstance(value.get("error"), dict):+ error = value["error"]+ code = _bounded_opaque_string(+ _bounded_preflight_message(+ error.get("code"),+ api_key=api_key,+ base_url=base_url,+ )+ )+ message = "provider_error"+ failure = MemoryPreflightFailure(error_name, MemoryPreflightDiagnostic(side, status_code, code, message))+ self._record_preflight(+ side,+ payload,+ value if isinstance(value, dict) else None,+ failure,+ base_url=base_url,+ api_key=api_key,+ started_at_ms=started_at_ms,+ duration_ms=_elapsed_ms(started),+ )+ return failure+ except httpx.TimeoutException:+ failure = MemoryPreflightFailure(error_name, MemoryPreflightDiagnostic(side, message="provider_request_timed_out"))+ self._record_preflight(+ side,+ payload,+ None,+ failure,+ base_url=base_url,+ api_key=api_key,+ started_at_ms=started_at_ms,+ duration_ms=_elapsed_ms(started),+ )+ return failure+ except MemoryProviderFailure:+ failure = MemoryPreflightFailure(+ error_name,+ MemoryPreflightDiagnostic(side, message="provider_response_too_large"),+ )+ self._record_preflight(+ side,+ payload,+ None,+ failure,+ base_url=base_url,+ api_key=api_key,+ started_at_ms=started_at_ms,+ duration_ms=_elapsed_ms(started),+ )+ return failure+ except (httpx.HTTPError, OSError, TypeError, ValueError):+ failure = MemoryPreflightFailure(error_name, MemoryPreflightDiagnostic(side, message="provider_unavailable"))+ self._record_preflight(+ side,+ payload,+ None,+ failure,+ base_url=base_url,+ api_key=api_key,+ started_at_ms=started_at_ms,+ duration_ms=_elapsed_ms(started),+ )+ return failure-async def _read_bounded_response(response: httpx.Response) -> bytes:+ def _record_preflight(+ self,+ side,+ request,+ response,+ failure,+ *,+ base_url,+ api_key,+ started_at_ms,+ duration_ms,+ ) -> None:+ if self._preflight_call_recorder is None:+ return+ try:+ self._preflight_call_recorder(+ side=side,+ request=request,+ response=response,+ failure=failure,+ base_url=base_url,+ api_key=api_key,+ started_at_ms=started_at_ms,+ duration_ms=duration_ms,+ )+ except Exception:+ logger.debug("memory preflight call recorder failed", exc_info=True)+++def _bounded_preflight_message(+ value: object,+ *,+ api_key: str | None = None,+ base_url: str | None = None,+) -> str:+ if not isinstance(value, str):+ return ""+ message = " ".join(value.split())+ if api_key:+ message = message.replace(api_key, "[REDACTED]")+ if base_url:+ message = message.replace(base_url.rstrip("/"), "[URL]")+ message = re.sub(r"https?://[^\s]+", "[URL]", message)+ message = re.sub(r"([?&](?:api[_-]?key|token|secret|password)=)[^&\s]+", r"\1[REDACTED]", message, flags=re.IGNORECASE)+ return message[:512]+++async def _read_bounded_response(+ response: httpx.Response,+ *,+ max_bytes: int = _MAX_RESPONSE_BYTES,+) -> bytes:chunks: list[bytes] = []size = 0async for chunk in response.aiter_bytes():size += len(chunk)- if size > _MAX_RESPONSE_BYTES:+ if size > max_bytes:raise MemoryProviderFailure("memory_provider_response_invalid")chunks.append(chunk)return b"".join(chunks)diff --git a/core/memory/everos_insight/reader.py b/core/memory/everos_insight/reader.pyindex 0775802a0..6d2081dec 100644--- a/core/memory/everos_insight/reader.py+++ b/core/memory/everos_insight/reader.py@@ -162,6 +162,39 @@ class MemoryInsightReader:calls=_source_observation(sections["calls"]),)+ def installation_preflight_calls(self) -> tuple[dict[str, Any], ...]:+ """Project recent installation-level checks without conversation scope."""++ with _read_only(self._paths.call_log_db_path) as conn:+ _validate_provider_call_source(conn)+ rows = conn.execute(+ """+ SELECT id, started_at_ms, duration_ms, kind, stage, model, status,+ error, finish_reason, prompt_tokens, completion_tokens,+ request_json, response_json, request_bytes, response_bytes,+ dropped_before+ FROM provider_call+ WHERE stage = 'processing_preflight'+ AND request_id IS NULL AND strategy_name IS NULL+ AND run_id IS NULL AND attempt IS NULL+ AND memcell_id IS NULL AND app_id IS NULL+ AND project_id IS NULL AND owner_id IS NULL+ AND md_path IS NULL AND entry_id IS NULL+ AND parent_type IS NULL AND parent_id IS NULL+ ORDER BY started_at_ms DESC, id DESC+ LIMIT ?+ """,+ (_MAX_DETAIL_CALLS,),+ ).fetchall()+ return tuple(+ _call_projection(+ row,+ base_urls=self._provider_base_urls,+ exact_values=self._exact_redaction_values,+ )+ for row in rows+ )+def list_entries(self,scope: MemoryReadScope,diff --git a/core/memory/everos_insight/recorder.py b/core/memory/everos_insight/recorder.pyindex a6b4f8d4a..a17ed0e1e 100644--- a/core/memory/everos_insight/recorder.py+++ b/core/memory/everos_insight/recorder.py@@ -11,6 +11,7 @@ import threadingimport timefrom collections import dequefrom collections.abc import Callable, Iterator, Sequence+from uuid import uuid4from contextlib import contextmanagerfrom dataclasses import asdict, dataclass, replacefrom pathlib import Path@@ -572,6 +573,42 @@ def initialize_call_log(db_path: Path) -> None:_initialize_schema(conn)+def record_preflight_call(+ db_path: Path,+ *,+ started_at_ms: int,+ duration_ms: int,+ kind: ProviderKind,+ model: str | None,+ request: dict,+ response: dict | None,+ status: str,+ error: str | None = None,+ provider_base_urls: Sequence[str] = (),+ exact_redaction_values: Sequence[str] = (),+) -> None:+ """Record a parent-side bounded preflight call with its distinct stage."""+ call = ProviderCallInput(+ id=uuid4().hex,+ started_at_ms=started_at_ms,+ duration_ms=duration_ms,+ kind=kind,+ stage="processing_preflight",+ status=status,+ request=request,+ response=response,+ model=model,+ error=error,+ )+ row = normalize_provider_call(call, provider_base_urls=provider_base_urls, exact_redaction_values=exact_redaction_values)+ db_path.parent.mkdir(parents=True, exist_ok=True)+ _validate_directory_chain(db_path.parent)+ os.chmod(db_path.parent, 0o700)+ with _database_connection(db_path) as conn:+ _initialize_schema(conn)+ _write_batch(conn, [row], lambda: False)++def _initialize_schema(conn: sqlite3.Connection) -> None:conn.executescript("""diff --git a/core/memory/process.py b/core/memory/process.pyindex bc3f8912e..859df7533 100644--- a/core/memory/process.py+++ b/core/memory/process.py@@ -40,17 +40,67 @@ from core.memory.confined_filesystem import (required_no_follow_flag,)from core.memory.everos import EverOSPort+from core.memory.secret_scrubber import scrub_textfrom core.memory.types import MemoryErrorCodelogger = logging.getLogger(__name__)++async def _drain_probe_stderr(stream: object) -> bytes:+ tail = bytearray()+ try:+ reader = getattr(stream, "read", None)+ if not callable(reader):+ return b""+ while True:+ chunk = await reader(4096)+ if not chunk:+ break+ tail.extend(chunk if isinstance(chunk, bytes) else str(chunk).encode())+ del tail[:-_PROCESSING_PROBE_STDERR_BYTES]+ except Exception:+ pass+ return bytes(tail)+++async def _probe_stderr_tail(task: asyncio.Task[bytes] | None, *, settings: EverOSProcessSettings) -> str:+ if task is None:+ return ""+ try:+ data = await asyncio.wait_for(asyncio.shield(task), timeout=1.0)+ text = data.decode("utf-8", "replace")+ text = scrub_text(+ text,+ base_urls=tuple(+ value for value in (+ settings.llm_base_url,+ settings.embedding_base_url,+ ) if value+ ),+ exact_values=tuple(+ value for value in (+ settings.llm_api_key,+ settings.embedding_api_key,+ ) if value+ ),+ )+ compact = " ".join(text.split())+ return compact.encode("utf-8")[-_PROCESSING_PROBE_STDERR_BYTES:].decode(+ "utf-8",+ "ignore",+ )+ except Exception:+ task.cancel()+ return ""+_STARTUP_TIMEOUT_SECONDS = 30.0_STOP_TIMEOUT_SECONDS = 10.0_HEALTHY_RESET_SECONDS = 5 * 60.0_RESTART_DELAYS_SECONDS = (1.0, 5.0, 30.0, 120.0)_MAX_CONSECUTIVE_FAILURES = 5_PROCESSING_PROBE_TIMEOUT_SECONDS = 20.0+_PROCESSING_PROBE_STDERR_BYTES = 2048_SOCKET_MODE = 0o600_OWNER_DIR_MODE = 0o700_SAFETY_MONITOR_INTERVAL_SECONDS = 0.2@@ -391,6 +441,7 @@ class _ProcessHost(Protocol):cwd: Path,env: Mapping[str, str],socket_path: Path | None = None,+ capture_stderr: bool = False,) -> asyncio.subprocess.Process: ...def process_group(self, pid: int) -> int | None: ...@@ -616,22 +667,32 @@ class EverOSProcess:if not self._python.is_file() or not _settings_complete(self._settings):return Falsetry:- probe = await self._host.spawn(- _ProcessKind.PROCESSING_PROBE,- self._python,- cwd=self._effective_home,- env=self._child_environment(),- )+ try:+ probe = await self._host.spawn(+ _ProcessKind.PROCESSING_PROBE,+ self._python,+ cwd=self._effective_home,+ env=self._child_environment(),+ capture_stderr=True,+ )+ except TypeError:+ probe = await self._host.spawn(+ _ProcessKind.PROCESSING_PROBE,+ self._python,+ cwd=self._effective_home,+ env=self._child_environment(),+ )except (OSError, ValueError):- logger.warning("EverOS processing probe could not start")+ logger.warning("EverOS processing probe could not start; branch=probe_spawn")return Falseprocess_group = self._host.process_group(probe.pid)owned_processes = self._host.snapshot_tree(probe.pid, process_group)+ stderr = getattr(probe, "stderr", None)+ stderr_task = asyncio.create_task(_drain_probe_stderr(stderr)) if stderr is not None else Nonetry:await asyncio.wait_for(probe.wait(), timeout=_PROCESSING_PROBE_TIMEOUT_SECONDS)except asyncio.TimeoutError:- logger.warning("EverOS processing probe timed out")try:await self._terminate_owned_tree(probe,@@ -640,6 +701,10 @@ class EverOSProcess:)except Exception:logger.warning("EverOS processing probe cleanup failed")+ logger.warning(+ "EverOS processing probe timed out; stderr_tail=%s",+ await _probe_stderr_tail(stderr_task, settings=self._settings),+ )return Falseexcept asyncio.CancelledError:# ``MemoryWorker`` bounds this probe independently. Do not let that@@ -652,6 +717,7 @@ class EverOSProcess:)except Exception:logger.warning("EverOS processing probe cleanup failed")+ await _probe_stderr_tail(stderr_task, settings=self._settings)raisetry:@@ -665,6 +731,14 @@ class EverOSProcess:except Exception:logger.warning("EverOS processing probe cleanup failed")return False+ if probe.returncode != 0:+ logger.warning(+ "EverOS processing probe failed exit_code=%s stderr_tail=%s",+ probe.returncode,+ await _probe_stderr_tail(stderr_task, settings=self._settings),+ )+ else:+ await _probe_stderr_tail(stderr_task, settings=self._settings)return probe.returncode == 0async def _start_locked(self) -> bool:@@ -3429,6 +3503,7 @@ class _SystemProcessHost:cwd: Path,env: Mapping[str, str],socket_path: Path | None = None,+ capture_stderr: bool = False,) -> asyncio.subprocess.Process:if kind is _ProcessKind.CASCADE_REBUILD:arguments = [@@ -3462,7 +3537,7 @@ class _SystemProcessHost:env=dict(env),stdin=asyncio.subprocess.DEVNULL,stdout=asyncio.subprocess.DEVNULL,- stderr=asyncio.subprocess.DEVNULL,+ stderr=asyncio.subprocess.PIPE if capture_stderr else asyncio.subprocess.DEVNULL,start_new_session=True,)diff --git a/core/memory/processing_record.py b/core/memory/processing_record.pyindex 9c4b066a0..e75e071c4 100644--- a/core/memory/processing_record.py+++ b/core/memory/processing_record.py@@ -8,7 +8,7 @@ import timefrom collections.abc import Awaitable, Callable, Mappingfrom dataclasses import dataclassfrom datetime import datetime, timezone-from typing import Literal, TypeVar+from typing import Any, Literal, TypeVarfrom core.memory.everos import ProviderHealthSnapshotfrom core.memory.confined_filesystem import PRIVATE_SQLITE_BUSY_TIMEOUT_SECONDS@@ -24,12 +24,12 @@ from core.memory.types import MemoryFailureLogEntrySourceStatus = Literal["available", "partial", "stale", "unknown", "unavailable"]# One composite read performs an opaque operator lookup, then reads both-# maintenance journals, then fans out over provider health, four local source+# maintenance journals, then fans out over provider health, five local source# surfaces, and maintenance metadata plus a freshness recheck. This is the# controller work bound; the transport retains an additional fixed margin.PROCESSING_RECORD_SQLITE_BOUND_SECONDS = PRIVATE_SQLITE_BUSY_TIMEOUT_SECONDSPROCESSING_RECORD_JOURNAL_SURFACES = 2-PROCESSING_RECORD_SOURCE_SURFACES = 4+PROCESSING_RECORD_SOURCE_SURFACES = 5PROCESSING_RECORD_TRANSPORT_MARGIN_SECONDS = 5.0PROCESSING_RECORD_WORK_TIMEOUT_SECONDS = (PROCESSING_RECORD_SQLITE_BOUND_SECONDS@@ -98,12 +98,19 @@ class MaintenanceProjection:clear_recovery: ClearRecoveryResult | None+@dataclass(frozen=True, slots=True)+class ProviderCheckProjection:+ source: SourceObservation+ items: tuple[dict[str, Any], ...]++@dataclass(frozen=True, slots=True)class ProcessingRecordSummary:runtime: RuntimeHealthProjectionsources: ProcessingSourceObservationsanomalies: AnomalyProjectionmaintenance: MaintenanceProjection+ provider_checks: ProviderCheckProjectionstatus: Literal["ok"] = "ok"@@ -120,6 +127,7 @@ class MemoryProcessingRecordPort:]recorder_health: Callable[[], Mapping[str, str | None]]observe_sources: Callable[[str | None], Awaitable[ProcessingSourceObservations]]+ provider_checks: Callable[[str | None], Awaitable[ProviderCheckProjection]]maintenance: Callable[[str | None, MaintenanceObservation],Awaitable[MaintenanceResult],@@ -255,11 +263,12 @@ class MemoryProcessingRecord:operator_ref,deadline,)- runtime_result, sources, anomalies, maintenance = await asyncio.gather(+ runtime_result, sources, anomalies, maintenance, provider_checks = await asyncio.gather(self._read_runtime(observation.block_reason, deadline),self._read_sources(observation.block_reason, deadline),self._read_durable_anomalies(observation.block_reason, deadline),self._read_maintenance(operator_ref, observation, deadline),+ self._read_provider_checks(observation.block_reason, deadline),)runtime, recorder_anomaly = runtime_resultreturn ProcessingRecordSummary(@@ -267,8 +276,28 @@ class MemoryProcessingRecord:sources=sources,anomalies=self._merge_recorder_anomaly(anomalies, recorder_anomaly),maintenance=maintenance,+ provider_checks=provider_checks,)+ async def _read_provider_checks(+ self,+ maintenance_reason: str | None,+ deadline: float,+ ) -> ProviderCheckProjection:+ try:+ return await _await_before(+ deadline,+ lambda: self._runtime.provider_checks(maintenance_reason),+ )+ except Exception:+ return ProviderCheckProjection(+ source=SourceObservation(+ "unavailable",+ reason="memory_store_unavailable",+ ),+ items=(),+ )+async def _read_runtime(self,maintenance_reason: str | None,diff --git a/core/memory/runtime.py b/core/memory/runtime.pyindex 5ecea170b..4bc123d70 100644--- a/core/memory/runtime.py+++ b/core/memory/runtime.py@@ -13,6 +13,7 @@ from concurrent.futures import TimeoutError as FutureTimeoutErrorfrom collections.abc import AsyncIterator, Awaitable, Callable, Mappingfrom contextlib import asynccontextmanagerfrom dataclasses import asdict, dataclass, replace+from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, TypeVar@@ -35,7 +36,7 @@ from core.memory.everos import (ProviderHealthSnapshot,)from core.memory.everos_insight import MemoryInsightPaths, MemoryInsightReader-from core.memory.everos_insight.recorder import clear_call_log, maintain_call_log+from core.memory.everos_insight.recorder import clear_call_log, maintain_call_log, record_preflight_callfrom core.memory.module import MemoryModule, MemorySessionLifecycleBusyErrorfrom core.memory.operation_lock import MemoryOperationBusy, MemoryOperationLeasefrom core.memory.maintenance import (@@ -66,6 +67,7 @@ from core.memory.processing_record import (MemoryProcessingRecordPort,ProcessingRecordSummary,ProcessingSourceObservations,+ ProviderCheckProjection,RuntimeHealthObservation,RuntimeHealthProjection,SourceObservation,@@ -265,6 +267,10 @@ def _processing_record_payload(summary: ProcessingRecordSummary) -> dict[str, An},"anomalies": _anomaly_projection_payload(summary.anomalies),"maintenance": _maintenance_projection_payload(summary.maintenance),+ "provider_checks": {+ "source": _source_observation_payload(summary.provider_checks.source),+ "items": list(summary.provider_checks.items),+ },}@@ -630,6 +636,7 @@ class MemoryRuntime:failure_log=self._processing_record_failure_log,recorder_health=lambda: dict(self._recorder_health),observe_sources=self._processing_record_sources,+ provider_checks=self._processing_record_provider_checks,maintenance=self._processing_record_maintenance,)@@ -1161,6 +1168,39 @@ class MemoryRuntime:)return observation+ async def _processing_record_provider_checks(+ self,+ maintenance_reason: str | None,+ ) -> ProviderCheckProjection:+ before = self._processing_runtime_snapshot()+ reason = before.local_observation_reason(maintenance_reason)+ if reason is not None:+ return ProviderCheckProjection(+ source=SourceObservation("unavailable", reason=reason),+ items=(),+ )+ reader = self._insight_reader+ if reader is None:+ raise self._unavailable()+ items = await run_blocking(reader.installation_preflight_calls)+ after = self._processing_runtime_snapshot()+ current_reason = after.local_observation_reason(maintenance_reason)+ if after.generation != before.generation or current_reason is not None:+ return ProviderCheckProjection(+ source=SourceObservation(+ "unavailable",+ reason=current_reason or "busy",+ ),+ items=(),+ )+ return ProviderCheckProjection(+ source=SourceObservation(+ "available",+ observed_at=datetime.now(timezone.utc).isoformat(timespec="milliseconds"),+ ),+ items=items,+ )+async def _processing_record_maintenance(self,operator_ref: str | None,@@ -1774,6 +1814,46 @@ class MemoryRuntime:task.add_done_callback(clear_restart)return await asyncio.shield(task)+ async def preflight(self, config: MemoryConfig | None = None) -> dict[str, Any]:+ candidate = deepcopy(config or self._config)+ provider = EverOSPort(+ self._socket_path,+ llm_base_url=candidate.processing.llm.base_url,+ llm_model=candidate.processing.llm.model,+ llm_api_key=candidate.processing.llm.api_key,+ embedding_base_url=candidate.processing.embedding.base_url,+ embedding_model=candidate.processing.embedding.model,+ embedding_api_key=candidate.processing.embedding.api_key,+ preflight_call_recorder=self._record_preflight_call,+ )+ return (await provider.preflight()).payload()++ def _record_preflight_call(+ self,+ *,+ side,+ request,+ response,+ failure,+ base_url=None,+ api_key=None,+ started_at_ms,+ duration_ms,+ ) -> None:+ record_preflight_call(+ 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,+ request=request,+ response=response,+ status="error" if failure is not None else "ok",+ error=failure.diagnostic.message if failure is not None else None,+ provider_base_urls=(base_url,) if base_url else (),+ exact_redaction_values=(api_key,) if api_key else (),+ )+async def rebuild(self) -> dict[str, Any]:"""Join or start one retained embedding-index rebuild over the cascade child."""@@ -1998,8 +2078,10 @@ class MemoryRuntime:self._activation_loop = asyncio.get_running_loop()if not self.available or self._store is None or self._module is None:+ logger.warning("Memory rebuild failed branch=store_unavailable")return {"ok": False, "error": "memory_store_unavailable"}if self._artifact_installing:+ logger.warning("Memory rebuild failed branch=artifact_installing")return {"ok": False, "error": "memory_restart_failed"}if self._rebuild_running() and asyncio.current_task() is not self._rebuild_task:return {"ok": False, "error": "memory_operation_in_progress"}@@ -2139,7 +2221,21 @@ class MemoryRuntime:# failure must leave restart fenced against the same candidate.self._config = deepcopy(candidate)self._restart_config = deepcopy(candidate)- self._configure_insight_reader(self._config)+ if candidate.enabled or _memory_processing_complete(candidate):+ preflight = await self.preflight(candidate)+ else:+ # A disabled, incomplete candidate can be persisted while the+ # operator fills in its providers. An empty root needs no network+ # admission check; data-bearing roots are rejected below.+ preflight = {"ok": True}+ if preflight.get("ok") is not True:+ # Keep the durable candidate and recovery fence visible to every+ # later restart, while the retained sidecar and its reader keep+ # using the active settings until Retry succeeds.+ self._config = deepcopy(candidate)+ self._restart_config = deepcopy(candidate)+ self.module.pause_claims()+ return {**preflight, "result": "failed"}self.module.pause_claims()rebuild_settings = _process_settings(candidate,@@ -2160,6 +2256,7 @@ class MemoryRuntime:except Exception:quiesced = Falseif not quiesced:+ logger.warning("Memory rebuild failed branch=quiesce")self._runtime_error = "memory_rebuild_failed"return {"ok": False,@@ -2171,6 +2268,7 @@ class MemoryRuntime:# run under the claim fence while the old sidecar is still owned.python = await asyncio.to_thread(self._artifact_manager.resolve_python)if python is None:+ logger.warning("Memory rebuild failed branch=artifact_resolution")error = _runtime_error_for_status(await asyncio.to_thread(self._artifact_manager.status))@@ -2197,10 +2295,13 @@ class MemoryRuntime:"result": "failed",}- try:- candidate_healthy = await self._probe_processing(python, candidate)- except Exception:- candidate_healthy = False+ if _memory_processing_complete(candidate):+ try:+ candidate_healthy = await self._probe_processing(python, candidate)+ except Exception:+ candidate_healthy = False+ else:+ candidate_healthy = Trueif not candidate_healthy:self._runtime_error = "memory_rebuild_failed"return {@@ -2964,6 +3065,12 @@ def _rebuild_settings_usable(settings: EverOSProcessSettings) -> bool:)+def _memory_processing_complete(config: MemoryConfig) -> bool:+ """Return whether both configured processing providers can be contacted."""++ return config.processing.llm.complete() and config.processing.embedding.complete()++def _rebuild_public_result(result: RebuildProcessResult) -> dict[str, Any]:"""Map a closed child result to the public rebuild response shape."""diff --git a/core/memory/types.py b/core/memory/types.pyindex d6a5f8d29..97e5cfb65 100644--- a/core/memory/types.py+++ b/core/memory/types.py@@ -38,6 +38,8 @@ MemoryErrorCode = Literal["memory_clear_failed","memory_embedding_rebuild_required","memory_rebuild_failed",+ "memory_embedding_unavailable",+ "memory_llm_unavailable","memory_rebuild_root_busy","memory_factory_reset_failed","memory_repair_failed",@@ -69,6 +71,8 @@ CLOSED_MEMORY_ERROR_CODES = frozenset("memory_clear_failed","memory_embedding_rebuild_required","memory_rebuild_failed",+ "memory_embedding_unavailable",+ "memory_llm_unavailable","memory_rebuild_root_busy","memory_factory_reset_failed","memory_repair_failed",@@ -83,6 +87,22 @@ def is_memory_error_code(value: object) -> bool:return isinstance(value, str) and value in CLOSED_MEMORY_ERROR_CODES+@dataclass(frozen=True)+class MemoryPreflightDiagnostic:+ side: Literal["embedding", "llm"]+ http_status: int | None = None+ provider_error_code: str | None = None+ message: str = "provider unavailable"++ def payload(self) -> dict[str, object]:+ return {+ "side": self.side,+ "http_status": self.http_status,+ "provider_error_code": self.provider_error_code,+ "message": self.message[:512],+ }++@dataclass(frozen=True)class ProviderSessionRef:"""Canonical provider identity persisted by Avibe's Memory outbox."""diff --git a/docs/MEMORY.md b/docs/MEMORY.mdindex ce92c36ad..efa359fd8 100644--- a/docs/MEMORY.md+++ b/docs/MEMORY.md@@ -1,5 +1,14 @@# Memory+## Processing preflight and rebuild recovery++Confirmed embedding identity changes and retained rebuild retries validate the+candidate 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.+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.diff --git a/tests/scenarios/memory_rebuild_recovery/catalog.yaml b/tests/scenarios/memory_rebuild_recovery/catalog.yamlindex 2e03a9d94..5abed5181 100644--- a/tests/scenarios/memory_rebuild_recovery/catalog.yaml+++ b/tests/scenarios/memory_rebuild_recovery/catalog.yaml@@ -13,6 +13,15 @@ status_legend:manual: currently validated only by human regressiongap: not covered yetscenarios:+ - id: MEMORY-REBUILD-301+ name: Candidate preflight rejects unavailable providers without changing durable config+ status: covered+ kind: validation+ layer: scenario+ test: tests/test_ui_memory_routes.py::test_memory_confirmed_preflight_failure_keeps_config_unchanged+ given: A candidate processing identity is submitted+ when: The provider returns a bounded error response+ then: The side-specific error is projected, credentials/raw payloads are absent, and durable configuration is unchanged- id: MEMORY-REBUILD-001name: Confirmed embedding identity write persists intent and reaches a closed rebuild resultstatus: covereddiff --git a/tests/test_internal_client_timeouts.py b/tests/test_internal_client_timeouts.pyindex be220307b..51c49e3b0 100644--- a/tests/test_internal_client_timeouts.py+++ b/tests/test_internal_client_timeouts.py@@ -96,7 +96,7 @@ def test_processing_record_client_covers_identity_journals_and_parallel_sources(+ initial_journal_observation_bound+ max(PROVIDER_READ_TIMEOUT_SECONDS,- 4 * sqlite_bound,+ 5 * sqlite_bound,metadata_and_fresh_observation_bound,))diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex 9aa4df8d5..534631ad5 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -659,6 +659,23 @@ def test_memory_rebuild_requires_signed_ui_operator() -> None:runtime.rebuild.assert_not_awaited()+def test_memory_preflight_requires_signed_ui_operator() -> None:+ runtime = SimpleNamespace(preflight=AsyncMock())+ controller = _build_controller_double()+ controller.memory_runtime = runtime+ app = internal_server.create_app(controller, memory_ui_secret="test-secret")++ async def _exercise() -> httpx.Response:+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:+ return await client.post("/internal/memory/preflight", json={"memory": {}})++ response = asyncio.run(_exercise())+ assert response.status_code == 403+ assert response.json() == {"ok": False, "error": "memory_access_denied"}+ runtime.preflight.assert_not_awaited()++def test_memory_factory_reset_requires_signed_ui_operator() -> None:from core.memory.http_headers import MEMORY_USER_KEY_HEADERfrom core.memory.ui_access import MEMORY_UI_PROOF_HEADERdiff --git a/tests/test_memory_call_log.py b/tests/test_memory_call_log.pyindex a8f032e46..02dfe68d0 100644--- a/tests/test_memory_call_log.py+++ b/tests/test_memory_call_log.py@@ -21,6 +21,7 @@ from core.memory.everos_insight.recorder import (initialize_call_log,maintain_call_log,normalize_provider_call,+ record_preflight_call,)@@ -45,6 +46,30 @@ def _private_db_path(tmp_path: Path) -> Path:return directory / "call-log.db"+def test_preflight_recorder_creates_private_call_log_directory(tmp_path: Path) -> None:+ db_path = tmp_path / "memory" / "call-log" / "call-log.db"+ db_path.parent.parent.mkdir(mode=0o700)++ record_preflight_call(+ db_path,+ started_at_ms=1_700_000_000_000,+ duration_ms=125,+ kind="embedding",+ model="embed",+ request={"model": "embed", "input": "OK"},+ response={"data": [{"embedding": [0.1]}]},+ status="ok",+ )++ assert stat.S_IMODE(db_path.parent.stat().st_mode) == 0o700+ with sqlite3.connect(db_path) as conn:+ assert conn.execute(+ "SELECT started_at_ms, duration_ms, stage FROM provider_call"+ ).fetchall() == [+ (1_700_000_000_000, 125, "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_everos.py b/tests/test_memory_everos.pyindex d63f30846..adcaae401 100644--- a/tests/test_memory_everos.py+++ b/tests/test_memory_everos.py@@ -847,6 +847,150 @@ def test_processing_health_probes_both_authenticated_endpoints() -> None:assert all(request.headers["authorization"].startswith("Bearer ") for request in requests)+def test_processing_preflight_projects_sanitized_provider_error() -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ if request.url.path.endswith("/chat/completions"):+ return httpx.Response(404, json={"error": {"code": "model_not_supported", "message": "secret-key should not leak"}})+ return httpx.Response(200, json={"data": [{"embedding": [0.1]}]})++ async def run():+ return await EverOSPort(+ Path("/tmp/everos.sock"),+ llm_base_url="https://llm.example.test/v1", llm_model="chat", llm_api_key="secret",+ embedding_base_url="https://embed.example.test/v1", embedding_model="embed", embedding_api_key="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_llm_unavailable"+ assert result.failure.diagnostic.http_status == 404+ assert result.failure.diagnostic.provider_error_code == "model_not_supported"+ assert "secret" not in result.failure.diagnostic.message+++def test_processing_preflight_scrubs_provider_error_code() -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 401,+ json={"error": {"code": "https://embed.example.test/v1?api_key=secret"}},+ )++ async def run():+ return await EverOSPort(+ Path("/tmp/everos.sock"),+ llm_base_url="https://llm.example.test/v1",+ llm_model="chat",+ llm_api_key="secret",+ embedding_base_url="https://embed.example.test/v1",+ embedding_model="embed",+ embedding_api_key="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.failure is not None+ assert "https://" not in result.failure.diagnostic.provider_error_code+ assert "secret" not in result.failure.diagnostic.provider_error_code+++def test_processing_preflight_preserves_http_status_for_non_json_errors() -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(502, text="<html>gateway failure</html>")++ async def run():+ return await EverOSPort(+ Path("/tmp/everos.sock"),+ llm_base_url="https://llm.example.test/v1",+ llm_model="chat",+ llm_api_key="secret",+ embedding_base_url="https://embed.example.test/v1",+ embedding_model="embed",+ embedding_api_key="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.failure is not None+ assert result.failure.error == "memory_llm_unavailable"+ assert result.failure.diagnostic.http_status == 502+ assert result.failure.diagnostic.message == "HTTP 502"+++def test_processing_preflight_accepts_large_bounded_embedding_vectors() -> None:+ vector = [0.123456789] * 16_384+ assert len(json.dumps({"data": [{"embedding": vector}]}).encode()) > 64 * 1024++ def handler(request: httpx.Request) -> httpx.Response:+ if request.url.path.endswith("/chat/completions"):+ return httpx.Response(200, json={"choices": [{"message": {"content": "OK"}}]})+ return httpx.Response(200, json={"data": [{"embedding": vector}]})++ async def run():+ return await EverOSPort(+ Path("/tmp/everos.sock"),+ llm_base_url="https://llm.example.test/v1",+ llm_model="chat",+ llm_api_key="secret",+ embedding_base_url="https://embed.example.test/v1",+ embedding_model="embed",+ embedding_api_key="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 True+++def test_processing_preflight_records_actual_call_duration() -> None:+ recorded: list[dict[str, object]] = []++ def handler(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(503, json={"error": {"code": "unavailable"}})++ async def run():+ return await EverOSPort(+ Path("/tmp/everos.sock"),+ llm_base_url="https://llm.example.test/v1",+ llm_model="chat",+ llm_api_key="secret",+ embedding_base_url="https://embed.example.test/v1",+ embedding_model="embed",+ embedding_api_key="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,+ patch("core.memory.everos._elapsed_ms", return_value=321),+ ):+ client_type.side_effect = lambda **kwargs: real_async_client(+ transport=httpx.MockTransport(handler), **kwargs+ )+ result = asyncio.run(run())++ assert result.ok is False+ assert len(recorded) == 2+ assert {item["duration_ms"] for item in recorded} == {321}+ assert all(isinstance(item["started_at_ms"], int) for item in recorded)++def test_processing_health_rejects_llm_probe_without_completion_content() -> None:def handler(request: httpx.Request) -> httpx.Response:if request.url.path.endswith("/chat/completions"):diff --git a/tests/test_memory_insight.py b/tests/test_memory_insight.pyindex 009b359fb..f1f277765 100644--- a/tests/test_memory_insight.py+++ b/tests/test_memory_insight.py@@ -338,6 +338,36 @@ def _insert_call(paths: MemoryInsightPaths, call_id: str, **values: object) -> N)+def test_installation_preflight_calls_exclude_conversation_linked_rows(+ insight_paths: MemoryInsightPaths,+) -> None:+ _insert_call(+ insight_paths,+ "preflight-safe",+ stage="processing_preflight",+ started_at_ms=1_722_816_005_000,+ duration_ms=237,+ status="error",+ error="provider_request_timed_out",+ request_json=_json({"model": "model", "input": "OK"}),+ response_json=None,+ )+ _insert_call(+ insight_paths,+ "preflight-linked",+ stage="processing_preflight",+ memcell_id="mc-private",+ )+ _insert_call(insight_paths, "normal-unlinked", stage="boundary")++ calls = MemoryInsightReader(insight_paths).installation_preflight_calls()++ assert [call["id"] for call in calls] == ["preflight-safe"]+ assert calls[0]["stage"] == "processing_preflight"+ assert calls[0]["duration_ms"] == 237+ assert calls[0]["error"] == "provider_request_timed_out"++def test_list_is_owner_scoped_and_omits_malformed_or_multi_owner(insight_paths: MemoryInsightPaths,) -> None:diff --git a/tests/test_memory_process.py b/tests/test_memory_process.pyindex 9f1ac9860..2278a79e8 100644--- a/tests/test_memory_process.py+++ b/tests/test_memory_process.py@@ -519,6 +519,19 @@ async def test_processing_probe_reaps_child_when_its_caller_is_cancelled(monkeypassert cleanup_calls+async def test_probe_stderr_drain_keeps_only_bounded_tail() -> None:+ reader = asyncio.StreamReader()+ payload = b"head-secret\n" + (b"x" * 100_000) + b"\ntail-marker"+ reader.feed_data(payload)+ reader.feed_eof()++ tail = await memory_process._drain_probe_stderr(reader)++ assert len(tail) <= memory_process._PROCESSING_PROBE_STDERR_BYTES+ assert b"head-secret" not in tail+ assert tail.endswith(b"tail-marker")++async def test_sidecar_stop_signals_isolated_child_group(tmp_path: Path) -> None:child_pid_path = tmp_path / "child.pid"script = (diff --git a/tests/test_memory_processing_record.py b/tests/test_memory_processing_record.pyindex 3de22d1ca..5cfcdb9ad 100644--- a/tests/test_memory_processing_record.py+++ b/tests/test_memory_processing_record.py@@ -28,6 +28,7 @@ from core.memory.processing_record import (MemoryProcessingRecordPort,ProcessingRecordSummary,ProcessingSourceObservations,+ ProviderCheckProjection,RuntimeHealthObservation,RuntimeHealthProjection,SourceObservation,@@ -71,6 +72,10 @@ class _RuntimeObservations:"reason": None,}self.sources = _sources()+ self.provider_checks = ProviderCheckProjection(+ SourceObservation("available", observed_at="checks-now"),+ (),+ )self.maintenance = MaintenanceResult(False, True, None)self.maintenance_observation = MaintenanceObservation(None, None, True)self.operator_refs: list[str | None] = []@@ -136,6 +141,17 @@ class _RuntimeObservations:raise self.maintenance_errorreturn self.maintenance+ async def observe_provider_checks(+ self,+ maintenance_reason: str | None,+ ) -> ProviderCheckProjection:+ if maintenance_reason is not None:+ return ProviderCheckProjection(+ SourceObservation("unavailable", reason=maintenance_reason),+ (),+ )+ return self.provider_checks+def port(self) -> MemoryProcessingRecordPort:return MemoryProcessingRecordPort(resolve_operator=self.resolve_operator,@@ -144,6 +160,7 @@ class _RuntimeObservations:failure_log=self.failure_log,recorder_health=self.recorder_health,observe_sources=self.observe_sources,+ provider_checks=self.observe_provider_checks,maintenance=self.maintenance_payload,)@@ -156,7 +173,7 @@ class _ConcurrentRuntimeObservations(_RuntimeObservations):def _mark_independent_read(self) -> None:self._independent_reads += 1- if self._independent_reads == 3:+ if self._independent_reads == 4:self._independent_reads_started.set()async def observe_health(@@ -181,6 +198,13 @@ class _ConcurrentRuntimeObservations(_RuntimeObservations):self._mark_independent_read()return await super().observe_sources(maintenance_reason)+ async def observe_provider_checks(+ self,+ maintenance_reason: str | None,+ ) -> ProviderCheckProjection:+ self._mark_independent_read()+ return await super().observe_provider_checks(maintenance_reason)+async def maintenance_payload(self,operator_ref: str | None,@@ -345,6 +369,10 @@ async def test_sources_anomalies_and_maintenance_degrade_independently() -> Noneassert summary.runtime.health is not Noneassert summary.sources.capture.reason == "busy"assert summary.sources.calls.status == "available"+ assert summary.provider_checks.source == SourceObservation(+ "available",+ observed_at="checks-now",+ )assert summary.anomalies.source == SourceObservation("unavailable",reason="memory_store_unavailable",@@ -556,6 +584,7 @@ async def test_runtime_serializes_one_composite_and_compatibility_projections("sources","anomalies","maintenance",+ "provider_checks",}assert set(composite["sources"]) == {"everos", "capture", "calls"}assert status == {"status": "ok", **composite["runtime"]}diff --git a/tests/test_memory_runtime.py b/tests/test_memory_runtime.pyindex 07c233d8b..a0861f559 100644--- a/tests/test_memory_runtime.py+++ b/tests/test_memory_runtime.py@@ -103,6 +103,16 @@ def _installed_artifact(**overrides) -> FakeMemoryArtifactManager:return FakeMemoryArtifactManager(**defaults)[email protected](autouse=True)+def _preflight_passes_by_default(monkeypatch: pytest.MonkeyPatch) -> None:+ """Keep runtime lifecycle tests hermetic unless they exercise preflight."""++ async def preflight(self: MemoryRuntime, config: MemoryConfig | None = None):+ return {"ok": True}++ monkeypatch.setattr(MemoryRuntime, "preflight", preflight)++async def test_memory_drain_task_reactivates_recovery_after_an_unexpected_failure(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,@@ -3078,6 +3088,71 @@ async def test_runtime_preflight_failure_keeps_existing_sidecar_running(await memory_runtime_factory.close(runtime)+async def test_runtime_rebuild_preflight_failure_keeps_candidate_fence(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ memory_runtime_factory,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ active = MemoryConfig(enabled=True, processing=_processing_config())+ candidate = replace(+ active,+ processing=replace(+ active.processing,+ embedding=replace(active.processing.embedding, model="embed-v2"),+ ),+ recovery_intent="rebuild",+ )+ V2Config(+ mode="self_host",+ version="v2",+ slack=SlackConfig(bot_token=""),+ runtime=RuntimeConfig(default_cwd="."),+ agents=AgentsConfig(),+ memory=candidate,+ ).save()+ runtime = memory_runtime_factory(+ active,+ artifact_manager=_installed_artifact(),+ effective_home=tmp_path,+ )+ old = FakeEverOSProcess(settings=_settings())+ runtime._process = old++ async def reject_preflight(_config: MemoryConfig | None = None) -> dict[str, object]:+ return {"ok": False, "error": "memory_embedding_unavailable"}++ monkeypatch.setattr(runtime, "preflight", reject_preflight)++ assert await runtime.rebuild() == {+ "ok": False,+ "error": "memory_embedding_unavailable",+ "result": "failed",+ }+ assert runtime._config == candidate+ assert runtime._restart_config == candidate+ assert runtime._process is old+ assert runtime.module._worker._claims_paused is True+ assert runtime._insight_reader is not None+ assert runtime._insight_reader._provider_base_urls == (+ active.processing.llm.base_url,+ active.processing.embedding.base_url,+ )+ assert V2Config.load().memory == candidate++ assert await runtime.rebuild() == {+ "ok": False,+ "error": "memory_embedding_unavailable",+ "result": "failed",+ }+ assert runtime._insight_reader is not None+ assert runtime._insight_reader._provider_base_urls == (+ active.processing.llm.base_url,+ active.processing.embedding.base_url,+ )+ await memory_runtime_factory.close(runtime)++async def test_runtime_passes_call_log_only_to_the_supervised_recorder_child(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,@@ -4228,6 +4303,11 @@ async def test_rebuild_settlement_survives_candidate_activation_failure(effective_home=tmp_path,)monkeypatch.setattr(runtime, "_provider_data_exists_strict", lambda: False)+ monkeypatch.setattr(+ runtime,+ "preflight",+ lambda config=None: asyncio.sleep(0, result={"ok": True}),+ )assert await runtime.rebuild() == {"ok": False,diff --git a/tests/test_ui_memory_routes.py b/tests/test_ui_memory_routes.pyindex ccdd96216..d3a3fb7a3 100644--- a/tests/test_ui_memory_routes.py+++ b/tests/test_ui_memory_routes.py@@ -23,6 +23,31 @@ from vibe import api, internal_client, remote_access, ui_memory_routes, ui_servefrom vibe.ui_server import app+def test_memory_rebuild_result_preserves_closed_preflight_diagnostic() -> None:+ payload, status = ui_memory_routes._memory_rebuild_result(+ {+ "ok": False,+ "error": "memory_embedding_unavailable",+ "result": "failed",+ "diagnostic": {+ "side": "embedding",+ "http_status": 404,+ "provider_error_code": "model_not_supported",+ "message": "unsupported model",+ "raw": "must not cross",+ },+ },+ 409,+ )+ assert status == 409+ assert payload["diagnostic"] == {+ "side": "embedding",+ "http_status": 404,+ "provider_error_code": "model_not_supported",+ "message": "unsupported model",+ }++def _save_config(tmp_path) -> None:V2Config(mode="self_host",@@ -82,6 +107,16 @@ def _local_headers() -> dict[str, str]:return {"Origin": "http://127.0.0.1:15131"}[email protected](autouse=True)+def _preflight_passes_by_default(monkeypatch):+ """Keep legacy route fixtures focused unless a test exercises preflight."""++ async def preflight(*, payload: dict, user_key: str):+ return {"status_code": 200, "body": {"ok": True}}++ monkeypatch.setattr(internal_client, "memory_preflight", preflight)++def test_memory_factory_reset_public_result_keeps_truthful_root_contract() -> None:payload = {"ok": False,@@ -1217,6 +1252,11 @@ def test_memory_confirmed_first_embedding_identity_runs_retained_rebuild(_save_config(tmp_path)observed: list[tuple[str | None, str | None, str | None]] = []+ async def unexpected_preflight(*, payload: dict, user_key: str):+ raise AssertionError("incomplete disabled candidates do not need live preflight")++ monkeypatch.setattr(internal_client, "memory_preflight", unexpected_preflight)+async def rebuild(*, user_key: str):persisted = V2Config.load().memoryobserved.append(@@ -1275,6 +1315,69 @@ def test_memory_confirmed_first_embedding_identity_runs_retained_rebuild(assert persisted.recovery_intent is None+def test_memory_confirmed_preflight_failure_keeps_config_unchanged(monkeypatch, tmp_path) -> None:+ """Scenario: MEMORY-REBUILD-301"""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)+ current = MemoryConfig(+ enabled=False,+ processing=MemoryProcessingConfig(+ llm=MemoryEndpointConfig("https://llm.example.test/v1", "chat", "llm-key"),+ embedding=MemoryEndpointConfig("https://embed.example.test/v1", "embed-v1", "embed-key"),+ ),+ )+ _save_memory(current)+ from config.paths import get_config_path++ config_before = get_config_path().read_bytes()++ async def preflight(*, payload: dict, user_key: str):+ assert user_key == "avibe:local"+ assert payload["memory"]["processing"]["embedding"]["model"] == "embed-v2"+ return {+ "status_code": 409,+ "body": {+ "ok": False,+ "error": "memory_embedding_unavailable",+ "diagnostic": {+ "side": "embedding",+ "http_status": 404,+ "provider_error_code": "model_not_supported",+ "message": "model unavailable",+ },+ },+ }++ monkeypatch.setattr(internal_client, "memory_preflight", preflight)+ client = app.test_client()+ response = client.patch(+ "/api/memory/settings",+ json={+ "processing": {"embedding": {"model": "embed-v2"}},+ "confirm_rebuild": True,+ },+ 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_embedding_unavailable",+ "diagnostic": {+ "side": "embedding",+ "http_status": 404,+ "provider_error_code": "model_not_supported",+ "message": "model unavailable",+ },+ }+ assert get_config_path().read_bytes() == config_before+ persisted = V2Config.load().memory+ assert persisted.processing.embedding.model == "embed-v1"+ assert persisted.recovery_intent is None++def test_memory_first_embedding_api_key_only_does_not_require_rebuild(monkeypatch,tmp_path,@@ -1390,8 +1493,14 @@ def test_memory_confirmed_rebuild_failure_keeps_candidate(monkeypatch, tmp_path)"status_code": 409,"body": {"ok": False,- "error": "memory_rebuild_root_busy",- "result": "root_busy",+ "error": "memory_embedding_unavailable",+ "result": "failed",+ "diagnostic": {+ "side": "embedding",+ "http_status": 404,+ "provider_error_code": "model_not_supported",+ "message": "provider_error",+ },},}@@ -1410,7 +1519,13 @@ def test_memory_confirmed_rebuild_failure_keeps_candidate(monkeypatch, tmp_path)assert response.status_code == 409body = response.get_json()- assert body["error"] == "memory_rebuild_root_busy"+ assert body["error"] == "memory_embedding_unavailable"+ assert body["diagnostic"] == {+ "side": "embedding",+ "http_status": 404,+ "provider_error_code": "model_not_supported",+ "message": "provider_error",+ }assert body["rebuild_required"] is Truepersisted = V2Config.load().memoryassert persisted.processing.embedding.model == "embed-v2"diff --git a/ui/src/components/settings/SettingsMemoryPage.test.tsx b/ui/src/components/settings/SettingsMemoryPage.test.tsxindex 9c2c1e15f..b7286594c 100644--- a/ui/src/components/settings/SettingsMemoryPage.test.tsx+++ b/ui/src/components/settings/SettingsMemoryPage.test.tsx@@ -125,6 +125,7 @@ const readyProcessingRecord = (): MemoryProcessingRecordSummary => ({can_clear: true,clear_recovery: null,},+ provider_checks: { source, items: [] },});const renderPage = () => render(diff --git a/ui/src/components/settings/SettingsMemoryPage.tsx b/ui/src/components/settings/SettingsMemoryPage.tsxindex a0cd9575b..6c4df3f10 100644--- a/ui/src/components/settings/SettingsMemoryPage.tsx+++ b/ui/src/components/settings/SettingsMemoryPage.tsx@@ -324,6 +324,8 @@ export const SettingsMemoryPage: React.FC = () => {failures={processingRecord?.anomalies.items ?? []}recovery={processingRecord?.maintenance.clear_recovery ?? null}logSections={processingRecord?.sources ?? null}+ providerChecks={processingRecord?.provider_checks?.items ?? []}+ providerChecksSource={processingRecord?.provider_checks?.source ?? null}statusLoading={!processingRecordRead.loaded || processingRecordRead.loading}failuresLoading={!processingRecordRead.loaded || processingRecordRead.loading}statusError={processingRecordRead.error}diff --git a/ui/src/components/settings/memory/MemoryLogPanel.tsx b/ui/src/components/settings/memory/MemoryLogPanel.tsxindex 72fc5ff14..6a2bb2385 100644--- a/ui/src/components/settings/memory/MemoryLogPanel.tsx+++ b/ui/src/components/settings/memory/MemoryLogPanel.tsx@@ -259,7 +259,7 @@ const StepRow: React.FC<{ step: MemoryLogStep }> = ({ step }) => {);};-const ProviderCallRow: React.FC<{ call: MemoryProviderCall }> = ({ call }) => {+export const ProviderCallRow: React.FC<{ call: MemoryProviderCall }> = ({ call }) => {const { t } = useTranslation();const [expanded, setExpanded] = useState(false);const succeeded = call.status === 'ok' || call.status === 'success';diff --git a/ui/src/components/settings/memory/MemorySettingsPanel.test.tsx b/ui/src/components/settings/memory/MemorySettingsPanel.test.tsxindex 4adfcf625..93bc6e587 100644--- a/ui/src/components/settings/memory/MemorySettingsPanel.test.tsx+++ b/ui/src/components/settings/memory/MemorySettingsPanel.test.tsx@@ -238,6 +238,84 @@ describe('MemorySettingsPanel', () => {}));});+ it('preserves endpoint drafts after confirmed preflight validation fails', async () => {+ api.saveMemorySettings.mockResolvedValue({+ status: 'failed',+ error: 'memory_embedding_unavailable',+ diagnostic: { message: 'provider_request_timed_out' },+ });+ const onReloadSettings = vi.fn();+ const onReloadMaintenance = vi.fn();+ const user = userEvent.setup();+ render(+ <MemorySettingsPanel+ settings={legacySettings}+ maintenance={null}+ maintenanceError={null}+ dependencyReady+ onSaved={() => undefined}+ onReloadSettings={onReloadSettings}+ onReloadMaintenance={onReloadMaintenance}+ onClearAll={() => undefined}+ clearing={false}+ />,+ );++ const embeddingBaseUrl = screen.getAllByPlaceholderText(+ 'memory.settings.baseUrlPlaceholder',+ )[1] as HTMLInputElement;+ await user.clear(embeddingBaseUrl);+ await user.type(embeddingBaseUrl, 'https://candidate.example.test/v1');+ await user.click(screen.getByRole('button', { name: 'memory.settings.save' }));+ await user.click(await screen.findByRole('button', { name: 'confirm-rebuild' }));++ await waitFor(() => expect(api.saveMemorySettings).toHaveBeenCalled());+ expect(embeddingBaseUrl.value).toBe('https://candidate.example.test/v1');+ expect(onReloadSettings).not.toHaveBeenCalled();+ expect(onReloadMaintenance).not.toHaveBeenCalled();+ expect(+ screen.getByText(+ 'errors.memory_embedding_unavailable: errors.provider_request_timed_out',+ ),+ ).toBeTruthy();+ });++ it('reloads durable rebuild state after post-save preflight fails', async () => {+ api.saveMemorySettings.mockResolvedValue({+ status: 'failed',+ error: 'memory_embedding_unavailable',+ diagnostic: { message: 'provider_request_timed_out' },+ rebuild_required: true,+ });+ const onReloadSettings = vi.fn();+ const onReloadMaintenance = vi.fn();+ const user = userEvent.setup();+ render(+ <MemorySettingsPanel+ settings={legacySettings}+ maintenance={null}+ maintenanceError={null}+ dependencyReady+ onSaved={() => undefined}+ onReloadSettings={onReloadSettings}+ onReloadMaintenance={onReloadMaintenance}+ onClearAll={() => undefined}+ clearing={false}+ />,+ );++ const embeddingBaseUrl = screen.getAllByPlaceholderText(+ 'memory.settings.baseUrlPlaceholder',+ )[1] as HTMLInputElement;+ await user.clear(embeddingBaseUrl);+ await user.type(embeddingBaseUrl, 'https://candidate.example.test/v1');+ await user.click(screen.getByRole('button', { name: 'memory.settings.save' }));+ await user.click(await screen.findByRole('button', { name: 'confirm-rebuild' }));++ await waitFor(() => expect(onReloadSettings).toHaveBeenCalledOnce());+ expect(onReloadMaintenance).toHaveBeenCalledOnce();+ });+it('retains and replays the first embedding identity draft after confirmation', async () => {api.saveMemorySettings.mockResolvedValue({...firstSetupSettings,diff --git a/ui/src/components/settings/memory/MemorySettingsPanel.tsx b/ui/src/components/settings/memory/MemorySettingsPanel.tsxindex 45f99f74f..1e2a9353e 100644--- a/ui/src/components/settings/memory/MemorySettingsPanel.tsx+++ b/ui/src/components/settings/memory/MemorySettingsPanel.tsx@@ -230,14 +230,36 @@ export const MemorySettingsPanel: React.FC<{setConfirmRebuildOpen(false);setPendingPatch(null);} else {- setError(memoryErrorMessage(t, (res as { error?: string })?.error));+ const failure = res as {+ error?: string;+ diagnostic?: {+ message?: string;+ http_status?: number | null;+ provider_error_code?: string | null;+ };+ rebuild_required?: boolean;+ };+ setError(+ memoryErrorMessage(+ t,+ failure.error,+ failure.diagnostic?.message,+ failure.diagnostic?.http_status,+ failure.diagnostic?.provider_error_code,+ ),+ );// Confirmed rebuild keeps the candidate on failure. Exit the confirm// modal so a second click cannot re-submit a now-non-identity patch;// Retry rebuild is the recovery control under the pending marker.setConfirmRebuildOpen(false);setPendingPatch(null);- onReloadSettings();- onReloadMaintenance();+ const validationFailure =+ failure.error === 'memory_embedding_unavailable' ||+ failure.error === 'memory_llm_unavailable';+ if (!validationFailure || failure.rebuild_required === true) {+ onReloadSettings();+ onReloadMaintenance();+ }}} catch {setError(t('memory.settings.saveFailed'));@@ -286,7 +308,15 @@ export const MemorySettingsPanel: React.FC<{onReloadSettings();onReloadMaintenance();} else {- setError(memoryErrorMessage(t, res.error));+ setError(+ memoryErrorMessage(+ t,+ res.error,+ res.diagnostic?.message,+ res.diagnostic?.http_status,+ res.diagnostic?.provider_error_code,+ ),+ );onReloadSettings();onReloadMaintenance();}diff --git a/ui/src/components/settings/memory/MemoryStatusPanel.test.tsx b/ui/src/components/settings/memory/MemoryStatusPanel.test.tsxindex 95ef14ef0..baba8a2a3 100644--- a/ui/src/components/settings/memory/MemoryStatusPanel.test.tsx+++ b/ui/src/components/settings/memory/MemoryStatusPanel.test.tsx@@ -4,7 +4,12 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import { cleanup, render, screen } from '@testing-library/react';import userEvent from '@testing-library/user-event';-import type { MemoryClearRecovery, MemoryFailureLogEntry, MemoryStatus } from '../../../context/ApiContext';+import type {+ MemoryClearRecovery,+ MemoryFailureLogEntry,+ MemoryProviderCall,+ MemoryStatus,+} from '../../../context/ApiContext';import { memoryCascadeHealth } from '../../../test/memoryFixtures';import { MemoryStatusPanel } from './MemoryStatusPanel';@@ -49,6 +54,25 @@ const MANUAL_FAILURE: MemoryFailureLogEntry = {request_id: 'request-7',};+const PREFLIGHT_CALL: MemoryProviderCall = {+ id: 'preflight-1',+ started_at_ms: 1_722_816_005_000,+ duration_ms: 237,+ kind: 'embedding',+ stage: 'processing_preflight',+ model: 'embed-model',+ status: 'error',+ error: 'provider_request_timed_out',+ finish_reason: null,+ prompt_tokens: null,+ completion_tokens: null,+ request: { model: 'embed-model', input: 'OK' },+ response: null,+ request_bytes: 36,+ response_bytes: null,+ dropped_before: 0,+};+const baseProps: React.ComponentProps<typeof MemoryStatusPanel> = {status: STATUS,failures: [],@@ -58,6 +82,12 @@ const baseProps: React.ComponentProps<typeof MemoryStatusPanel> = {capture: { status: 'stale', observed_at: '2026-08-08T11:00:00Z', reason: 'locked' },calls: { status: 'unavailable', observed_at: null, reason: 'malformed' },},+ providerChecks: [],+ providerChecksSource: {+ status: 'available',+ observed_at: '2026-08-08T12:00:00Z',+ reason: null,+ },statusLoading: false,failuresLoading: false,statusError: null,@@ -96,12 +126,20 @@ describe('MemoryStatusPanel', () => {'memory.processingRecord.runtime.cascadeHelpLabel','memory.processingRecord.runtime.recorderHelpLabel','memory.processingRecord.sources.helpLabel',+ 'memory.processingRecord.providerChecks.helpLabel','memory.processingRecord.anomalies.helpLabel',]) {expect(screen.getByRole('button', { name: label })).toBeTruthy();}});+ it('renders installation-level provider checks with their recorded duration', () => {+ render(<MemoryStatusPanel {...baseProps} providerChecks={[PREFLIGHT_CALL]} />);++ expect(screen.getByText('237 ms')).toBeTruthy();+ expect(screen.getByText('memory.log.callStage.processingPreflight')).toBeTruthy();+ });+it('only exposes Repair index when the backend capability is explicitly available', () => {const { rerender } = render(<MemoryStatusPanel {...baseProps} />);expect(screen.queryByRole('button', { name: 'memory.processingRecord.repair.action' })).toBeNull();@@ -196,6 +234,7 @@ describe('MemoryStatusPanel', () => {expect(Array.from(container.querySelectorAll('section')).map((section) => section.getAttribute('aria-labelledby'))).toEqual(['memory-runtime-title','memory-sources-title',+ 'memory-provider-checks-title','memory-anomalies-title',]);// The title now sits inside a flex row (title + InfoHint) within the header div.diff --git a/ui/src/components/settings/memory/MemoryStatusPanel.tsx b/ui/src/components/settings/memory/MemoryStatusPanel.tsxindex ef1f5fa90..5a32ef5db 100644--- a/ui/src/components/settings/memory/MemoryStatusPanel.tsx+++ b/ui/src/components/settings/memory/MemoryStatusPanel.tsx@@ -22,9 +22,11 @@ import type {MemoryFailureLogEntry,MemoryLogSections,MemoryLogSourceStatus,+ MemoryProviderCall,MemoryCascadeHealth,MemoryStatus,} from '../../../context/ApiContext';+import { ProviderCallRow } from './MemoryLogPanel';import { memoryErrorMessage } from '../../../lib/memoryRead';import {formatMemoryStatusRuntimeFact,@@ -214,6 +216,8 @@ export const MemoryStatusPanel: React.FC<{failures: MemoryFailureLogEntry[];recovery: MemoryClearRecovery | null;logSections: MemoryLogSections | null;+ providerChecks: MemoryProviderCall[];+ providerChecksSource: MemoryLogSourceStatus | null;statusLoading: boolean;failuresLoading: boolean;statusError: string | null;@@ -234,6 +238,8 @@ export const MemoryStatusPanel: React.FC<{failures,recovery,logSections,+ providerChecks = [],+ providerChecksSource = null,statusLoading,failuresLoading,statusError,@@ -435,6 +441,36 @@ export const MemoryStatusPanel: React.FC<{</div></section>+ <section className="flex flex-col gap-2" aria-labelledby="memory-provider-checks-title">+ <div>+ <div className="flex items-center gap-1.5">+ <h3 id="memory-provider-checks-title" className="text-[13px] font-semibold text-foreground">+ {t('memory.processingRecord.providerChecks.title')}+ </h3>+ <InfoHint+ label={t('memory.processingRecord.providerChecks.helpLabel')}+ content={t('memory.processingRecord.providerChecks.help')}+ />+ </div>+ <p className="mt-0.5 text-[11.5px] text-muted">+ {t('memory.processingRecord.providerChecks.description')}+ </p>+ </div>+ {providerChecksSource?.status === 'unavailable' ? (+ <div className="rounded-md border border-border bg-surface px-3 py-3 text-[12px] text-muted">+ {t('memory.processingRecord.providerChecks.unavailable')}+ </div>+ ) : providerChecks.length === 0 ? (+ <div className="rounded-md border border-dashed border-border bg-surface px-3 py-3 text-[12px] text-muted">+ {t('memory.processingRecord.providerChecks.empty')}+ </div>+ ) : (+ <div className="flex flex-col gap-2">+ {providerChecks.map((call) => <ProviderCallRow key={call.id} call={call} />)}+ </div>+ )}+ </section>+<section className="flex flex-col gap-2" aria-labelledby="memory-anomalies-title"><div><div className="flex items-center gap-1.5">diff --git a/ui/src/components/settings/memory/memoryLog.ts b/ui/src/components/settings/memory/memoryLog.tsindex 66acdc637..070e067dc 100644--- a/ui/src/components/settings/memory/memoryLog.ts+++ b/ui/src/components/settings/memory/memoryLog.ts@@ -40,6 +40,7 @@ const ENUM_LABEL_KEYS = {embedding: 'embedding',},callStage: {+ processing_preflight: 'processingPreflight',boundary: 'boundary',strategy: 'strategy',cascade: 'cascade',diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 766d67601..ddc69cffe 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -1855,7 +1855,18 @@ export type MemorySettingsPatch = {confirm_rebuild?: boolean;};-export type MemoryFailure = { status: 'failed'; error: string };+export type MemoryFailureDiagnostic = {+ side?: 'embedding' | 'llm';+ http_status?: number | null;+ provider_error_code?: string | null;+ message?: string;+};+export type MemoryFailure = {+ status: 'failed';+ error: string;+ diagnostic?: MemoryFailureDiagnostic;+ rebuild_required?: boolean;+};export type MemorySettingsResult =| (MemorySettings & { runtime?: { ok?: boolean; [key: string]: unknown } })@@ -1940,6 +1951,10 @@ export type MemoryProcessingRecordSummary = {can_clear: boolean;clear_recovery: MemoryClearRecovery | null;};+ provider_checks?: {+ source: MemoryLogSourceStatus;+ items: MemoryProviderCall[];+ };};export type MemoryProcessingRecordResult =@@ -2101,7 +2116,7 @@ export type MemoryRuntimeRestartResult = { ok: true; state?: string } | { ok: faexport type MemoryRuntimeRebuildResult =| { ok: true; result?: string; state?: string }- | { ok: false; error?: string; result?: string };+ | { ok: false; error?: string; result?: string; diagnostic?: MemoryFailureDiagnostic };export type MemoryRuntimeRepairResult =| {diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 0cc32bb76..ccb4af906 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1574,7 +1574,14 @@"memory_rebuild_root_busy": "Another process is using the Memory root. Wait and retry the rebuild.","memory_operation_in_progress": "A Memory operation is already in progress. Wait for it to finish.","memory_factory_reset_failed": "Reinitializing Memory could not finish. Memory data may be partially deleted; retry from Settings → Dependencies.",- "memory_embedding_rebuild_required": "Changing the embedding endpoint or model rebuilds the Memory index. Confirm to continue."+ "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",+ "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.",+ "provider_error": "The provider rejected the request.",+ "endpoint_not_configured": "The provider endpoint is not configured."},"apps": {"title": "Apps",@@ -4057,6 +4064,14 @@"helpLabel": "About data sources","description": "One source being temporarily unavailable doesn't mean Memory is broken."},+ "providerChecks": {+ "title": "Provider checks",+ "help": "These installation-level checks validate the configured language and embedding 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.",+ "unavailable": "Provider checks are temporarily unavailable."+ },"anomalies": {"title": "Issue log","help": "Problems that came up during processing are recorded here. Check each entry's state: Dead, Rejected, and Manual review required entries won't recover automatically.",@@ -4208,6 +4223,7 @@"embedding": "Embedding model"},"callStage": {+ "processingPreflight": "Provider check","boundary": "Request preparation","strategy": "Strategy","cascade": "Building memories",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 157d675ff..13823afdf 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1574,7 +1574,14 @@"memory_rebuild_root_busy": "另一个进程正在使用记忆根目录。请稍后重试重建。","memory_operation_in_progress": "记忆操作正在进行中,请等待完成。","memory_factory_reset_failed": "重新初始化记忆未能完成。记忆数据可能已部分删除;请从「设置 → 依赖」重试。",- "memory_embedding_rebuild_required": "更改 Embedding 端点或模型会重建记忆索引。请确认后继续。"+ "memory_embedding_rebuild_required": "更改 Embedding 端点或模型会重建记忆索引。请确认后继续。",+ "memory_embedding_unavailable": "Embedding 提供商不可用",+ "memory_llm_unavailable": "LLM 提供商不可用",+ "provider_request_timed_out": "提供商请求超时。",+ "provider_response_too_large": "提供商响应超过安全限制。",+ "provider_unavailable": "提供商不可用。",+ "provider_error": "提供商拒绝了请求。",+ "endpoint_not_configured": "尚未配置提供商端点。"},"apps": {"title": "应用",@@ -4057,6 +4064,14 @@"helpLabel": "关于数据来源","description": "某一项暂时不可用,不代表记忆功能出了问题。"},+ "providerChecks": {+ "title": "服务商检查",+ "help": "这些安装级检查用于验证已配置的语言模型和向量模型服务,不会关联到任何对话。",+ "helpLabel": "关于服务商检查",+ "description": "验证记忆设置或重建时最近执行的检查。",+ "empty": "暂无服务商检查记录。",+ "unavailable": "暂时无法读取服务商检查记录。"+ },"anomalies": {"title": "异常记录","help": "处理过程中出现的问题会记录在这里。请查看每条记录的状态:「已放弃」「已拒绝」和「需要人工检查」的记录不会自动恢复。",@@ -4208,6 +4223,7 @@"embedding": "向量模型"},"callStage": {+ "processingPreflight": "服务商检查","boundary": "请求预处理","strategy": "处理策略","cascade": "构建记忆",diff --git a/ui/src/lib/memoryRead.test.ts b/ui/src/lib/memoryRead.test.tsindex 81d92564f..3718dede2 100644--- a/ui/src/lib/memoryRead.test.ts+++ b/ui/src/lib/memoryRead.test.ts@@ -47,8 +47,13 @@ describe('classifyMemoryResult', () => {describe('memoryErrorMessage', () => {- const t = ((key: string, options?: { defaultValue?: string }) =>- key === 'errors.memory_known' ? 'Known failure' : options?.defaultValue ?? key) as never;+ const t = ((key: string, options?: { defaultValue?: string }) => {+ if (key === 'errors.memory_known' || key === 'errors.memory_embedding_unavailable') {+ return 'Known failure';+ }+ if (key === 'errors.provider_request_timed_out') return 'Localized timeout';+ return options?.defaultValue ?? key;+ }) as never;it('translates a known closed code', () => {expect(memoryErrorMessage(t, 'memory_known')).toBe('Known failure');@@ -61,4 +66,16 @@ describe('memoryErrorMessage', () => {it('names an absent code rather than rendering an empty error', () => {expect(memoryErrorMessage(t, null)).toBe('common.unknown');});++ it('appends a provider diagnostic only when one is present', () => {+ expect(+ memoryErrorMessage(+ t,+ 'memory_embedding_unavailable',+ 'provider_request_timed_out',+ 404,+ 'model_not_supported',+ ),+ ).toBe('Known failure: Localized timeout · HTTP 404 · model_not_supported');+ });});diff --git a/ui/src/lib/memoryRead.ts b/ui/src/lib/memoryRead.tsindex 51eaf9eb7..02cfa2c38 100644--- a/ui/src/lib/memoryRead.ts+++ b/ui/src/lib/memoryRead.ts@@ -46,5 +46,18 @@ export function classifyMemoryResult<T>(}/** Map a closed backend error code to its localized message. */-export const memoryErrorMessage = (t: TFunction, code: string | null | undefined): string =>- code ? t(`errors.${code}`, { defaultValue: code }) : t('common.unknown');+export const memoryErrorMessage = (+ t: TFunction,+ code: string | null | undefined,+ message?: string | null,+ httpStatus?: number | null,+ providerErrorCode?: string | null,+): string => {+ const base = code ? t(`errors.${code}`, { defaultValue: code }) : t('common.unknown');+ const details = [+ message ? t(`errors.${message}`, { defaultValue: message }) : '',+ typeof httpStatus === 'number' ? `HTTP ${httpStatus}` : '',+ providerErrorCode || '',+ ].filter(Boolean);+ return details.length > 0 ? `${base}: ${details.join(' · ')}` : base;+};diff --git a/vibe/internal_client.py b/vibe/internal_client.pyindex ce1edc180..5500e4370 100644--- a/vibe/internal_client.py+++ b/vibe/internal_client.py@@ -699,6 +699,16 @@ async def memory_rebuild(timeout=None,)+async def memory_preflight(+ *, payload: dict, user_key: str, socket_path: Optional[Path] = None,+) -> dict[str, Any]:+ path = "/internal/memory/preflight"+ return await _memory_request(+ "POST", path, payload=payload,+ headers=_memory_user_key_headers("POST", path, user_key),+ socket_path=socket_path, timeout=None,+ )+async def memory_factory_reset(*,diff --git a/vibe/ui_memory_routes.py b/vibe/ui_memory_routes.pyindex 51e228c29..94d724016 100644--- a/vibe/ui_memory_routes.py+++ b/vibe/ui_memory_routes.py@@ -211,6 +211,15 @@ def _memory_embedding_configuration_changed(current: V2Config, candidate: V2Conf)+def _memory_preflight_required(candidate: V2Config) -> bool:+ """Require live admission unless a disabled candidate is still incomplete."""++ memory = candidate.memory+ return memory.enabled or (+ memory.processing.llm.complete() and memory.processing.embedding.complete()+ )++def _memory_api_key_only_patch(patch_payload: object) -> bool:"""Return whether this patch changes only one or both provider API keys."""@@ -259,6 +268,14 @@ def _memory_closed_error(payload: dict, *, fallback: str) -> str:return value if is_memory_error_code(value) else fallback+def _memory_preflight_projection(payload: dict) -> dict:+ diagnostic = payload.get("diagnostic")+ if not isinstance(diagnostic, dict):+ return {}+ allowed = {"side", "http_status", "provider_error_code", "message"}+ return {key: diagnostic[key] for key in allowed if key in diagnostic}++def _memory_rebuild_result(payload: dict,status_code: int,@@ -278,7 +295,11 @@ def _memory_rebuild_result(error = payload.get("error")if payload.get("status") == "failed" and status_code >= 500:if isinstance(error, str) and is_memory_error_code(error):- return {"ok": False, "error": error, "result": "failed"}, 503+ public = {"ok": False, "error": error, "result": "failed"}+ diagnostic = _memory_preflight_projection(payload)+ if diagnostic:+ public["diagnostic"] = diagnostic+ return public, 503return protocol_failure, 503result = payload.get("result")@@ -307,6 +328,9 @@ def _memory_rebuild_result(if not isinstance(error, str) or not is_memory_error_code(error):return protocol_failure, 503public["error"] = error+ diagnostic = _memory_preflight_projection(payload)+ if diagnostic:+ public["diagnostic"] = diagnosticreturn public, 503 if status_code >= 500 else 409@@ -480,6 +504,8 @@ def _memory_repair_result(payload: dict, status_code: int) -> tuple[dict, int]:"memory_store_unavailable": 503,"memory_sidecar_unavailable": 503,"memory_repair_failed": 503,+ "memory_embedding_unavailable": 409,+ "memory_llm_unavailable": 409,}.get(error)if expected_status is None or expected_status != status_code:return protocol_failure, 503@@ -765,6 +791,23 @@ async def _apply_memory_settings_patch(return _memory_response(await _settings_ok_payload(saved.memory))recovery_intent = "rebuild" if pending_marker or identity_changed else None++ if identity_changed and confirm_rebuild and _memory_preflight_required(candidate):+ from config.v2_config import memory_config_to_payload+ preflight = await _memory_internal_result(+ lambda: internal_client.memory_preflight(+ payload={"memory": memory_config_to_payload(candidate.memory, include_secrets=True)},+ user_key=user_key,+ )+ )+ if preflight[0].get("ok") is not True:+ failure = dict(preflight[0])+ failure.pop("ok", None)+ failure["status"] = "failed"+ failure["diagnostic"] = _memory_preflight_projection(preflight[0])+ failure_code = preflight[1] if preflight[1] >= 500 else 409+ return _memory_response(failure, status_code=failure_code)+try:# Persist a durable marker before asking the controller to inspect# the root. If Avibe exits in this interval, startup must re-run@@ -802,6 +845,9 @@ async def _apply_memory_settings_patch()payload["status"] = "failed"payload["error"] = error+ diagnostic = _memory_preflight_projection(runtime_payload)+ if diagnostic:+ payload["diagnostic"] = diagnostic# Keep the durable marker projection from latest config. Do not# re-arm Retry after settlement if only activation failed later.return _memory_response(payload, status_code=status_code if status_code >= 400 else 409)