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): replace clear recovery with durable intent (#1401)
rkrkrkkd6ea9ee0fc37
diff --git a/core/internal_server.py b/core/internal_server.pyindex 79a5c2d81..e9558a636 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -1666,46 +1666,6 @@ def create_app(logger.warning("internal memory clear failed")return JSONResponse(status_code=503, content={"status": "failed", "error": "memory_clear_failed"})- async def _memory_clear_recovery(request: Request, *, abort: bool) -> Any:- user_key = _verified_memory_ui_user_key(request)- if user_key is None:- return JSONResponse(status_code=403, content={"status": "failed", "error": "memory_access_denied"})- if _memory_factory_reset_running():- return JSONResponse(- status_code=409,- content={"status": "failed", "error": "memory_operation_in_progress"},- )- runtime = _memory_runtime()- if runtime is None:- return JSONResponse(status_code=503, content={"status": "failed", "error": "memory_runtime_missing"})- payload = await _safe_json(request)- if (- not isinstance(payload, dict)- or set(payload) != {"operation_id"}- or not isinstance(payload.get("operation_id"), str)- or not 1 <= len(payload["operation_id"]) <= 128- ):- return JSONResponse(status_code=400, content={"status": "failed", "error": "memory_invalid_input"})- try:- operator_ref = runtime.principal_for_user_key(user_key)- operation = runtime.abort_clear if abort else runtime.resume_clear- return await operation(payload["operation_id"], operator_ref=operator_ref)- except (TypeError, ValueError):- return JSONResponse(status_code=400, content={"status": "failed", "error": "memory_invalid_input"})- except MemoryStoreUnavailableError:- return JSONResponse(status_code=503, content={"status": "failed", "error": "memory_store_unavailable"})- except Exception:- logger.warning("internal memory clear recovery failed")- return JSONResponse(status_code=503, content={"status": "failed", "error": "memory_clear_failed"})-- @app.post("/internal/memory/clear/resume")- async def _memory_clear_resume(request: Request) -> Any:- return await _memory_clear_recovery(request, abort=False)-- @app.post("/internal/memory/clear/abort")- async def _memory_clear_abort(request: Request) -> Any:- return await _memory_clear_recovery(request, abort=True)-@app.post("/internal/model-hub")async def _model_hub(request: Request) -> Any:"""Dispatch UI operations to the controller-owned Model Hub aggregate."""diff --git a/core/memory/backup_restore_journal.py b/core/memory/backup_restore_journal.pydeleted file mode 100644index fc82e9a66..000000000--- a/core/memory/backup_restore_journal.py+++ /dev/null@@ -1,646 +0,0 @@-"""Durable fence for crash-recoverable ordinary Memory backup restores."""--from __future__ import annotations--import json-import os-import re-import secrets-import sqlite3-from contextlib import AbstractContextManager-from dataclasses import dataclass-from datetime import datetime, timezone-from pathlib import Path-from typing import Literal, Mapping--from core.memory.confined_filesystem import (- ConfinedFilesystemError,- PrivateSqliteDatabase,-)-from core.memory.snapshot import MemorySnapshot---BackupRestoreState = Literal["restoring", "recovery_needed", "completed"]--_OPERATION_ID_RE = re.compile(r"[0-9a-f]{32}\Z")-_SNAPSHOT_ID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}\Z")-_SHA256_RE = re.compile(r"[0-9a-f]{64}\Z")-_TOKEN_RE = re.compile(r"[0-9a-f]{32}\Z")-_SCHEMA_VERSION = 1---class MemoryBackupRestoreJournalError(RuntimeError):- """Base class for refused or failed backup-restore journal operations."""---class BackupRestoreConflict(MemoryBackupRestoreJournalError):- """A different operation already owns the durable restore fence."""---class BackupRestoreCASMismatch(MemoryBackupRestoreJournalError):- """The caller no longer owns the restore operation revision."""---@dataclass(frozen=True, slots=True)-class BackupRestoreOperation:- operation_id: str- backup_id: str- manifest_sha256: str- surface_digests: tuple[tuple[str, str | None], ...]- state: BackupRestoreState- started_at: str- updated_at: str- terminal_at: str | None- attempt_count: int- last_error: str | None- revision: int- execution_token: str | None-- def digest_mapping(self) -> dict[str, str | None]:- return dict(self.surface_digests)---@dataclass(frozen=True, slots=True)-class BackupRestoreEvent:- event_id: int- operation_id: str- event: str- actor_ref: str- occurred_at: str- resulting_revision: int- error_code: str | None---class MemoryBackupRestoreJournal:- """One-at-a-time durable intent and audit log for ordinary restores."""-- def __init__(- self,- effective_home: Path | str,- *,- database_path: Path | str = "state/memory/backup-restore-journal.sqlite",- ) -> None:- self._effective_home = Path(- os.path.abspath(os.path.expanduser(os.fspath(effective_home)))- )- database = Path(database_path)- if database.is_absolute():- self._database_path = Path(os.path.abspath(database))- self._database_path.relative_to(self._effective_home)- else:- if database.as_posix().startswith("../") or database.as_posix().startswith("/"):- raise ValueError("invalid backup restore journal path")- self._database_path = self._effective_home / database- self._database = PrivateSqliteDatabase(self._effective_home, self._database_path)- self._initialize()-- @property- def database_path(self) -> Path:- return self._database_path-- def start(self, snapshot: MemorySnapshot) -> BackupRestoreOperation:- """Publish restart-visible restore intent before the first replacement."""-- backup_id = _validated_snapshot_id(snapshot.snapshot_id)- manifest = _validated_sha256(snapshot.manifest_sha256)- digests = _normalized_digests(snapshot.surface_digests())- operation_id = secrets.token_hex(16)- token = secrets.token_hex(16)- now = _utc_now()- try:- with self._transaction() as connection:- connection.execute(- """- INSERT INTO backup_restore_operation (- operation_id, backup_id, manifest_sha256, surface_digests_json,- state, started_at, updated_at, attempt_count, open_slot,- revision, execution_token- ) VALUES (?, ?, ?, ?, 'restoring', ?, ?, 1, 1, 1, ?)- """,- (- operation_id,- backup_id,- manifest,- _encode_digests(digests),- now,- now,- token,- ),- )- self._append_event(- connection,- operation_id,- "started",- "system:runtime",- occurred_at=now,- resulting_revision=1,- )- except sqlite3.IntegrityError as error:- raise BackupRestoreConflict("a Memory backup restore is already open") from error- return self._require_operation(operation_id)-- def get_operation(self, operation_id: str) -> BackupRestoreOperation | None:- identifier = _validated_operation_id(operation_id)- connection = self._connect()- try:- row = connection.execute(- "SELECT * FROM backup_restore_operation WHERE operation_id = ?",- (identifier,),- ).fetchone()- finally:- connection.close()- return _operation_from_row(row) if row is not None else None-- def get_open_operation(self) -> BackupRestoreOperation | None:- connection = self._connect()- try:- row = connection.execute(- "SELECT * FROM backup_restore_operation WHERE open_slot = 1"- ).fetchone()- finally:- connection.close()- return _operation_from_row(row) if row is not None else None-- def get_events(self, operation_id: str) -> tuple[BackupRestoreEvent, ...]:- identifier = _validated_operation_id(operation_id)- connection = self._connect()- try:- rows = connection.execute(- "SELECT * FROM backup_restore_event WHERE operation_id = ? ORDER BY event_id",- (identifier,),- ).fetchall()- finally:- connection.close()- if not rows and self.get_operation(identifier) is None:- raise MemoryBackupRestoreJournalError("backup restore operation not found")- return tuple(_event_from_row(row) for row in rows)-- def assert_idle(self) -> None:- operation = self.get_open_operation()- if operation is not None:- raise BackupRestoreConflict(- f"Memory backup operation is blocked by restore {operation.operation_id!r}"- )-- def mark_boot_recovery_needed(self) -> BackupRestoreOperation | None:- """Release a dead process claim while retaining the restore fence."""-- with self._transaction() as connection:- row = connection.execute(- "SELECT * FROM backup_restore_operation WHERE open_slot = 1"- ).fetchone()- if row is None:- return None- now = _utc_now()- revision = row["revision"] + 1- connection.execute(- """- UPDATE backup_restore_operation- SET state = 'recovery_needed', updated_at = ?, last_error = ?,- revision = ?, execution_token = NULL- WHERE operation_id = ?- """,- (now, "memory_clear_failed", revision, row["operation_id"]),- )- self._append_event(- connection,- row["operation_id"],- "recovery_needed",- "system:boot",- occurred_at=now,- resulting_revision=revision,- error_code="memory_clear_failed",- )- identifier = row["operation_id"]- return self._require_operation(identifier)-- def claim_retry(- self,- operation_id: str,- *,- expected_revision: int,- actor_ref: str,- ) -> BackupRestoreOperation:- identifier = _validated_operation_id(operation_id)- actor = _validated_actor(actor_ref)- with self._transaction() as connection:- row = self._require_row(- connection,- identifier,- expected_revision=expected_revision,- allowed_states=("recovery_needed",),- require_token=False,- )- now = _utc_now()- revision = row["revision"] + 1- token = secrets.token_hex(16)- connection.execute(- """- UPDATE backup_restore_operation- SET state = 'restoring', updated_at = ?, attempt_count = attempt_count + 1,- last_error = NULL, revision = ?, execution_token = ?- WHERE operation_id = ?- """,- (now, revision, token, identifier),- )- self._append_event(- connection,- identifier,- "retry_started",- actor,- occurred_at=now,- resulting_revision=revision,- )- return self._require_operation(identifier)-- def mark_recovery_needed(- self,- operation_id: str,- *,- expected_revision: int,- execution_token: str,- ) -> BackupRestoreOperation:- return self._transition(- operation_id,- expected_revision=expected_revision,- execution_token=execution_token,- next_state="recovery_needed",- event="recovery_needed",- actor_ref="system:runtime",- terminal=False,- error_code="memory_clear_failed",- )-- def mark_completed(- self,- operation_id: str,- *,- expected_revision: int,- execution_token: str,- actor_ref: str = "system:runtime",- ) -> BackupRestoreOperation:- return self._transition(- operation_id,- expected_revision=expected_revision,- execution_token=execution_token,- next_state="completed",- event="completed",- actor_ref=actor_ref,- terminal=True,- error_code=None,- )-- def _transition(- self,- operation_id: str,- *,- expected_revision: int,- execution_token: str,- next_state: BackupRestoreState,- event: str,- actor_ref: str,- terminal: bool,- error_code: str | None,- ) -> BackupRestoreOperation:- identifier = _validated_operation_id(operation_id)- token = _validated_token(execution_token)- actor = _validated_actor(actor_ref)- with self._transaction() as connection:- row = self._require_row(- connection,- identifier,- expected_revision=expected_revision,- allowed_states=("restoring",),- require_token=True,- execution_token=token,- )- now = _utc_now()- revision = row["revision"] + 1- connection.execute(- """- UPDATE backup_restore_operation- SET state = ?, updated_at = ?, terminal_at = ?, last_error = ?,- open_slot = ?, revision = ?, execution_token = NULL- WHERE operation_id = ?- """,- (- next_state,- now,- now if terminal else None,- error_code,- None if terminal else 1,- revision,- identifier,- ),- )- self._append_event(- connection,- identifier,- event,- actor,- occurred_at=now,- resulting_revision=revision,- error_code=error_code,- )- return self._require_operation(identifier)-- @staticmethod- def _require_row(- connection: sqlite3.Connection,- operation_id: str,- *,- expected_revision: int,- allowed_states: tuple[str, ...],- require_token: bool,- execution_token: str | None = None,- ) -> sqlite3.Row:- row = connection.execute(- "SELECT * FROM backup_restore_operation WHERE operation_id = ?",- (operation_id,),- ).fetchone()- if row is None:- raise MemoryBackupRestoreJournalError("backup restore operation not found")- if row["revision"] != expected_revision or row["state"] not in allowed_states:- raise BackupRestoreCASMismatch("Memory backup restore claim is stale")- if require_token and row["execution_token"] != execution_token:- raise BackupRestoreCASMismatch("Memory backup restore execution token is stale")- if not require_token and row["execution_token"] is not None:- raise BackupRestoreCASMismatch("Memory backup restore is still claimed")- return row-- def _require_operation(self, operation_id: str) -> BackupRestoreOperation:- operation = self.get_operation(operation_id)- if operation is None:- raise MemoryBackupRestoreJournalError("backup restore operation not found")- return operation-- @staticmethod- def _append_event(- connection: sqlite3.Connection,- operation_id: str,- event: str,- actor_ref: str,- *,- occurred_at: str,- resulting_revision: int,- error_code: str | None = None,- ) -> None:- connection.execute(- """- INSERT INTO backup_restore_event (- operation_id, event, actor_ref, occurred_at,- resulting_revision, error_code- ) VALUES (?, ?, ?, ?, ?, ?)- """,- (- operation_id,- event,- actor_ref,- occurred_at,- resulting_revision,- error_code,- ),- )-- def _initialize(self) -> None:- try:- self._database.prepare()- except ConfinedFilesystemError as error:- raise MemoryBackupRestoreJournalError(- "Memory backup restore journal could not be prepared safely"- ) from error- connection = self._connect()- try:- version = connection.execute("PRAGMA user_version").fetchone()[0]- if version not in {0, _SCHEMA_VERSION}:- raise MemoryBackupRestoreJournalError(- "unsupported Memory backup restore journal schema"- )- if version == 0:- connection.executescript(_schema_sql())- connection.execute(f"PRAGMA user_version={_SCHEMA_VERSION}")- connection.commit()- else:- required = {"backup_restore_operation", "backup_restore_event"}- present = {- row[0]- for row in connection.execute(- "SELECT name FROM sqlite_master WHERE type = 'table'"- )- }- if not required.issubset(present):- raise MemoryBackupRestoreJournalError(- "Memory backup restore journal schema is incomplete"- )- result = connection.execute("PRAGMA quick_check").fetchone()- if result is None or result[0] != "ok":- raise MemoryBackupRestoreJournalError(- "Memory backup restore journal failed integrity check"- )- except sqlite3.Error as error:- raise MemoryBackupRestoreJournalError(- "Memory backup restore journal could not be initialized"- ) from error- finally:- connection.close()- self._harden_database_files(sync_parent=True)-- def _connect(self) -> sqlite3.Connection:- try:- return self._database.connect()- except ConfinedFilesystemError as error:- raise MemoryBackupRestoreJournalError(- "Memory backup restore journal is unsafe"- ) from error-- def _transaction(self) -> AbstractContextManager[sqlite3.Connection]:- return self._database.transaction(- translate_connect_error=lambda _error: MemoryBackupRestoreJournalError(- "Memory backup restore journal is unsafe"- ),- translate_harden_error=lambda _error: MemoryBackupRestoreJournalError(- "Memory backup restore journal files could not be hardened safely"- ),- )-- def _harden_database_files(self, *, sync_parent: bool = False) -> None:- try:- self._database.harden(sync_parent=sync_parent)- except ConfinedFilesystemError as error:- raise MemoryBackupRestoreJournalError(- "Memory backup restore journal files could not be hardened safely"- ) from error---def _schema_sql() -> str:- return """- CREATE TABLE backup_restore_operation (- operation_id TEXT PRIMARY KEY,- backup_id TEXT NOT NULL,- manifest_sha256 TEXT NOT NULL,- surface_digests_json TEXT NOT NULL,- state TEXT NOT NULL CHECK (state IN (- 'restoring', 'recovery_needed', 'completed'- )),- started_at TEXT NOT NULL,- updated_at TEXT NOT NULL,- terminal_at TEXT NULL,- attempt_count INTEGER NOT NULL CHECK (attempt_count >= 1),- last_error TEXT NULL CHECK (- last_error IS NULL OR last_error = 'memory_clear_failed'- ),- open_slot INTEGER NULL CHECK (- (state = 'completed' AND open_slot IS NULL) OR- (state != 'completed' AND open_slot = 1)- ),- revision INTEGER NOT NULL CHECK (revision >= 1),- execution_token TEXT NULL- );-- CREATE UNIQUE INDEX backup_restore_one_open- ON backup_restore_operation(open_slot) WHERE open_slot = 1;-- CREATE TABLE backup_restore_event (- event_id INTEGER PRIMARY KEY AUTOINCREMENT,- operation_id TEXT NOT NULL REFERENCES backup_restore_operation(operation_id),- event TEXT NOT NULL CHECK (event IN (- 'started', 'recovery_needed', 'retry_started', 'completed'- )),- actor_ref TEXT NOT NULL,- occurred_at TEXT NOT NULL,- resulting_revision INTEGER NOT NULL CHECK (resulting_revision >= 1),- error_code TEXT NULL CHECK (- error_code IS NULL OR error_code = 'memory_clear_failed'- )- );-- CREATE TRIGGER backup_restore_event_no_update- BEFORE UPDATE ON backup_restore_event- BEGIN- SELECT RAISE(ABORT, 'backup restore events are append-only');- END;-- CREATE TRIGGER backup_restore_event_no_delete- BEFORE DELETE ON backup_restore_event- BEGIN- SELECT RAISE(ABORT, 'backup restore events are append-only');- END;-- CREATE TRIGGER backup_restore_terminal_no_update- BEFORE UPDATE ON backup_restore_operation- WHEN OLD.state = 'completed'- BEGIN- SELECT RAISE(ABORT, 'terminal backup restore operations are immutable');- END;-- CREATE TRIGGER backup_restore_valid_transition- BEFORE UPDATE OF state ON backup_restore_operation- WHEN NEW.state != OLD.state AND NOT (- (OLD.state = 'restoring' AND NEW.state IN ('recovery_needed', 'completed')) OR- (OLD.state = 'recovery_needed' AND NEW.state = 'restoring')- )- BEGIN- SELECT RAISE(ABORT, 'invalid backup restore transition');- END;- """---def _operation_from_row(row: sqlite3.Row) -> BackupRestoreOperation:- return BackupRestoreOperation(- operation_id=_validated_operation_id(row["operation_id"]),- backup_id=_validated_snapshot_id(row["backup_id"]),- manifest_sha256=_validated_sha256(row["manifest_sha256"]),- surface_digests=_decode_digests(row["surface_digests_json"]),- state=row["state"],- started_at=row["started_at"],- updated_at=row["updated_at"],- terminal_at=row["terminal_at"],- attempt_count=row["attempt_count"],- last_error=row["last_error"],- revision=row["revision"],- execution_token=(- None if row["execution_token"] is None else _validated_token(row["execution_token"])- ),- )---def _event_from_row(row: sqlite3.Row) -> BackupRestoreEvent:- return BackupRestoreEvent(- event_id=row["event_id"],- operation_id=_validated_operation_id(row["operation_id"]),- event=row["event"],- actor_ref=row["actor_ref"],- occurred_at=row["occurred_at"],- resulting_revision=row["resulting_revision"],- error_code=row["error_code"],- )---def _normalized_digests(- values: Mapping[str, str | None],-) -> tuple[tuple[str, str | None], ...]:- normalized: list[tuple[str, str | None]] = []- for path, digest in sorted(values.items()):- if (- not isinstance(path, str)- or not path- or path.startswith("/")- or "\x00" in path- or any(part in {"", ".", ".."} for part in Path(path).parts)- ):- raise ValueError("invalid Memory backup surface path")- normalized.append((path, None if digest is None else _validated_sha256(digest)))- if not normalized:- raise ValueError("Memory backup restore requires surface digests")- return tuple(normalized)---def _encode_digests(values: tuple[tuple[str, str | None], ...]) -> str:- return json.dumps(dict(values), sort_keys=True, separators=(",", ":"))---def _decode_digests(value: str) -> tuple[tuple[str, str | None], ...]:- try:- decoded = json.loads(value)- except (TypeError, json.JSONDecodeError) as error:- raise MemoryBackupRestoreJournalError("invalid restore surface digests") from error- if not isinstance(decoded, dict):- raise MemoryBackupRestoreJournalError("invalid restore surface digests")- try:- return _normalized_digests(decoded)- except ValueError as error:- raise MemoryBackupRestoreJournalError("invalid restore surface digests") from error---def _validated_operation_id(value: str) -> str:- if not isinstance(value, str) or _OPERATION_ID_RE.fullmatch(value) is None:- raise ValueError("invalid backup restore operation id")- return value---def _validated_snapshot_id(value: str) -> str:- if not isinstance(value, str) or _SNAPSHOT_ID_RE.fullmatch(value) is None:- raise ValueError("invalid Memory backup id")- return value---def _validated_sha256(value: str) -> str:- if not isinstance(value, str) or _SHA256_RE.fullmatch(value) is None:- raise ValueError("invalid Memory backup SHA-256 digest")- return value---def _validated_token(value: str) -> str:- if not isinstance(value, str) or _TOKEN_RE.fullmatch(value) is None:- raise ValueError("invalid backup restore execution token")- return value---def _validated_actor(value: str) -> str:- if not isinstance(value, str) or not value or "\x00" in value or len(value) > 256:- raise ValueError("invalid backup restore actor")- return value---def _utc_now() -> str:- return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")diff --git a/core/memory/clear_intent.py b/core/memory/clear_intent.pynew file mode 100644index 000000000..8b0396c37--- /dev/null+++ b/core/memory/clear_intent.py@@ -0,0 +1,311 @@+"""Durable, idempotent intent marker for Memory Clear.++The marker is deliberately smaller than the former snapshot/journal state+machine. It records enough information to classify an interrupted destructive+operation and to repeat the four existing high-level deletion primitives.+"""++from __future__ import annotations++import json+import os+import secrets+import sqlite3+import uuid+from dataclasses import dataclass, replace+from datetime import datetime, timezone+from pathlib import Path+from typing import Literal++from core.memory.confined_filesystem import (+ ConfinedFilesystemError,+ PrivateSqliteDatabase,+ ensure_private_directory,+ fsync_directory,+ open_confined_regular_file,+ remove_confined_path,+ replace_confined,+ create_confined_file,+)+++ClearIntentState = Literal["deleting", "failed"]+MARKER_RELATIVE_PATH = "state/memory/clear-intent.json"+LEGACY_JOURNAL_RELATIVE_PATH = "state/memory/clear-journal.sqlite"+LEGACY_SNAPSHOT_RELATIVE_PATH = "state/memory/clear-snapshots"+BACKUP_JOURNAL_RELATIVE_PATH = "state/memory/backup-restore-journal.sqlite"+BACKUP_ROOT_RELATIVE_PATH = "state/memory/backups"+MARKER_SCHEMA_VERSION = 1+LEGACY_RERUN_ERROR_CODE = "memory_clear_legacy_state_requires_rerun"+MAX_CLEAR_INTENT_BYTES = 16 * 1024+++class ClearIntentError(RuntimeError):+ """Base class for marker and legacy-state failures."""+++class ClearIntentUnreadable(ClearIntentError):+ """A marker or legacy clear journal cannot be safely interpreted."""+++@dataclass(frozen=True, slots=True)+class ClearSurface:+ surface: Literal["queue", "provider", "call_log", "attachments"]+ relative_path: str+++DEFAULT_CLEAR_SURFACES: tuple[ClearSurface, ...] = (+ ClearSurface("queue", "state/memory/memory.sqlite"),+ ClearSurface("provider", "memory/everos-root"),+ ClearSurface("call_log", "memory/call-log/call-log.db"),+ ClearSurface("attachments", "memory/attachments"),+)+++@dataclass(frozen=True, slots=True)+class ClearIntent:+ schema_version: int+ operation_id: str+ operator_ref: str+ pre_epoch: int+ target_epoch: int+ state: ClearIntentState+ error_code: str | None+ created_at: str+ updated_at: str++ @classmethod+ def new(cls, *, operator_ref: str, pre_epoch: int) -> "ClearIntent":+ now = _utc_now()+ return cls(+ schema_version=MARKER_SCHEMA_VERSION,+ operation_id=str(uuid.uuid4()),+ operator_ref=operator_ref,+ pre_epoch=pre_epoch,+ target_epoch=pre_epoch + 1,+ state="deleting",+ error_code=None,+ created_at=now,+ updated_at=now,+ )++ def failed(self, error_code: str) -> "ClearIntent":+ return replace(self, state="failed", error_code=error_code, updated_at=_utc_now())++ def deleting(self) -> "ClearIntent":+ return replace(self, state="deleting", error_code=None, updated_at=_utc_now())+++class ClearIntentStore:+ """Read and atomically mutate one effective-home-relative marker."""++ def __init__(self, effective_home: Path | str) -> None:+ self.home = Path(os.path.abspath(os.path.expanduser(os.fspath(effective_home))))+ self.path = self.home / MARKER_RELATIVE_PATH++ def load(self) -> ClearIntent | None:+ try:+ os.lstat(self.path)+ except FileNotFoundError:+ return None+ except OSError as error:+ raise ClearIntentUnreadable("Memory clear intent marker is unreadable") from error+ try:+ descriptor = open_confined_regular_file(self.home, self.path)+ except (ConfinedFilesystemError, OSError) as error:+ if not os.path.lexists(self.path):+ # Another process may have completed the terminal clear after+ # our lstat but before this anchored open.+ return None+ raise ClearIntentUnreadable("Memory clear intent marker is unreadable") from error+ try:+ if os.fstat(descriptor).st_size > MAX_CLEAR_INTENT_BYTES:+ raise ValueError("Memory clear intent marker is too large")+ payload = bytearray()+ while True:+ chunk = os.read(descriptor, MAX_CLEAR_INTENT_BYTES + 1 - len(payload))+ if not chunk:+ break+ payload.extend(chunk)+ if len(payload) > MAX_CLEAR_INTENT_BYTES:+ raise ValueError("Memory clear intent marker is too large")+ return _decode(bytes(payload))+ except (OSError, UnicodeError, ValueError, TypeError, json.JSONDecodeError) as error:+ raise ClearIntentUnreadable("Memory clear intent marker is invalid") from error+ finally:+ os.close(descriptor)++ def write(self, intent: ClearIntent) -> None:+ ensure_private_directory(self.home, self.path.parent)+ temporary = self.path.with_name(f".clear-intent.{secrets.token_hex(8)}.tmp")+ descriptor: int | None = None+ try:+ descriptor = create_confined_file(self.home, temporary)+ payload = json.dumps(_encode(intent), sort_keys=True, separators=(",", ":")).encode()+ offset = 0+ while offset < len(payload):+ written = os.write(descriptor, payload[offset:])+ if written <= 0:+ raise OSError("Memory clear intent marker write failed")+ offset += written+ os.fsync(descriptor)+ os.close(descriptor)+ descriptor = None+ replace_confined(self.home, temporary, self.path)+ fsync_directory(self.path.parent)+ except (ConfinedFilesystemError, OSError) as error:+ raise ClearIntentError("Memory clear intent marker could not be written") from error+ finally:+ if descriptor is not None:+ os.close(descriptor)+ try:+ remove_confined_path(self.home, temporary)+ except (ConfinedFilesystemError, OSError):+ pass++ def remove(self) -> None:+ try:+ os.lstat(self.path)+ except FileNotFoundError:+ return+ except OSError as error:+ raise ClearIntentError("Memory clear intent marker could not be read") from error+ try:+ remove_confined_path(self.home, self.path)+ except (ConfinedFilesystemError, OSError) as error:+ raise ClearIntentError("Memory clear intent marker could not be removed") from error++ def reconcile_legacy(self, *, current_epoch: int) -> ClearIntent | None:+ """Fence any legacy open state without interpreting legacy semantics."""++ existing = self.load()+ journal_path = self.home / LEGACY_JOURNAL_RELATIVE_PATH+ if existing is not None:+ _best_effort_remove(self.home, journal_path)+ return existing+ if not os.path.lexists(journal_path):+ return None++ requires_rerun = False+ connection: sqlite3.Connection | None = None+ try:+ connection = PrivateSqliteDatabase(self.home, journal_path).connect_read_only()+ row = connection.execute(+ "SELECT EXISTS(SELECT 1 FROM clear_operation "+ "WHERE open_slot IS NOT NULL LIMIT 1)"+ ).fetchone()+ if row is None:+ raise sqlite3.DatabaseError("legacy clear probe returned no row")+ requires_rerun = bool(row[0])+ except (ConfinedFilesystemError, sqlite3.Error, OSError, TypeError, ValueError):+ requires_rerun = True+ finally:+ if connection is not None:+ connection.close()++ intent = None+ if requires_rerun:+ intent = ClearIntent.new(+ operator_ref="legacy-clear-journal",+ pre_epoch=current_epoch,+ ).failed(LEGACY_RERUN_ERROR_CODE)+ self.write(intent)+ _best_effort_remove(self.home, journal_path)+ return intent+++def cleanup_legacy_backup_storage(effective_home: Path | str) -> tuple[str, ...]:+ home = Path(os.path.abspath(os.path.expanduser(os.fspath(effective_home))))+ failures: list[str] = []+ for relative in (+ BACKUP_JOURNAL_RELATIVE_PATH,+ BACKUP_ROOT_RELATIVE_PATH,+ LEGACY_SNAPSHOT_RELATIVE_PATH,+ ):+ if not _best_effort_remove(home, home / relative):+ failures.append(relative)+ return tuple(failures)+++def _best_effort_remove(home: Path, path: Path) -> bool:+ try:+ remove_confined_path(home, path)+ except (ConfinedFilesystemError, OSError):+ return False+ return not os.path.lexists(path)+++def _encode(intent: ClearIntent) -> dict[str, object]:+ return {+ "schema_version": intent.schema_version,+ "operation_id": intent.operation_id,+ "operator_ref": intent.operator_ref,+ "pre_epoch": intent.pre_epoch,+ "target_epoch": intent.target_epoch,+ "state": intent.state,+ "error_code": intent.error_code,+ "created_at": intent.created_at,+ "updated_at": intent.updated_at,+ }+++def _decode(payload: bytes) -> ClearIntent:+ value = json.loads(payload.decode("utf-8"))+ if not isinstance(value, dict):+ raise ValueError("unsupported clear intent schema")+ schema_version = value.get("schema_version")+ if (+ not isinstance(schema_version, int)+ or isinstance(schema_version, bool)+ or schema_version != MARKER_SCHEMA_VERSION+ ):+ raise ValueError("unsupported clear intent schema")+ required = {"operation_id", "operator_ref", "pre_epoch", "target_epoch", "state", "error_code", "created_at", "updated_at"}+ if set(value) != required | {"schema_version"}:+ raise ValueError("invalid clear intent fields")+ pre_epoch = value["pre_epoch"]+ target_epoch = value["target_epoch"]+ if not isinstance(pre_epoch, int) or isinstance(pre_epoch, bool) or pre_epoch < 0:+ raise ValueError("invalid clear intent pre epoch")+ if not isinstance(target_epoch, int) or isinstance(target_epoch, bool) or target_epoch != pre_epoch + 1:+ raise ValueError("invalid clear intent target epoch")+ operation_id = value["operation_id"]+ if not isinstance(operation_id, str) or not operation_id:+ raise ValueError("invalid clear intent operation id")+ try:+ parsed_operation_id = uuid.UUID(operation_id)+ except (ValueError, AttributeError, TypeError):+ raise ValueError("clear intent operation id must be UUID4") from None+ if parsed_operation_id.version != 4:+ raise ValueError("clear intent operation id must be UUID4")+ operator_ref = value["operator_ref"]+ if (+ not isinstance(operator_ref, str)+ or not operator_ref+ or len(operator_ref.encode("utf-8")) > 512+ or any(ord(char) < 0x20 for char in operator_ref)+ ):+ raise ValueError("invalid clear intent operator")+ state = value["state"]+ if state not in {"deleting", "failed"}:+ raise ValueError("invalid clear intent state")+ error_code = value["error_code"]+ if error_code is not None and (+ not isinstance(error_code, str)+ or not error_code+ or len(error_code) > 128+ or any(ord(char) < 0x20 for char in error_code)+ ):+ raise ValueError("invalid clear intent error")+ if state == "deleting" and error_code is not None:+ raise ValueError("deleting clear intent cannot have an error")+ if state == "failed" and (not isinstance(error_code, str) or not error_code):+ raise ValueError("failed clear intent must have an error")+ for field in ("created_at", "updated_at"):+ if not isinstance(value[field], str) or not value[field]:+ raise ValueError(f"invalid clear intent {field}")+ return ClearIntent(**value) # type: ignore[arg-type]+++def _utc_now() -> str:+ return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")diff --git a/core/memory/clear_journal.py b/core/memory/clear_journal.pydeleted file mode 100644index 7d14ef7f3..000000000--- a/core/memory/clear_journal.py+++ /dev/null@@ -1,1513 +0,0 @@-"""Durable state machine for crash-recoverable Memory clear operations.--This module records intent and progress only. It never deletes or restores a-Memory surface; the runtime must perform those actions under its maintenance-fence and then acknowledge them with the narrow CAS methods below.-"""--from __future__ import annotations--import os-import re-import secrets-import sqlite3-from contextlib import AbstractContextManager-from dataclasses import dataclass-from datetime import datetime, timezone-from pathlib import Path, PurePosixPath-from typing import Literal, Mapping, Sequence--from core.memory.confined_filesystem import (- ConfinedFilesystemError,- PrivateSqliteDatabase,-)-from core.memory.snapshot import MemorySnapshot-from core.memory.types import CLOSED_MEMORY_ERROR_CODES, is_memory_error_code---ClearOperationState = Literal[- "preparing",- "prepared",- "deleting",- "recovery_needed",- "completed",- "aborted",-]-ClearSurfaceName = Literal["queue", "provider", "call_log", "attachments"]-ClearSurfaceState = Literal["pending", "snapshotted", "deleted", "restored"]-ClearResolution = Literal["resume", "abort"]--_OPEN_STATES = frozenset({"preparing", "prepared", "deleting", "recovery_needed"})-_TERMINAL_STATES = frozenset({"completed", "aborted"})-_SURFACE_NAMES = ("queue", "provider", "call_log", "attachments")-_OPERATION_ID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}\Z")-_TOKEN_RE = re.compile(r"[0-9a-f]{32}\Z")-_SHA256_RE = re.compile(r"[0-9a-f]{64}\Z")-_SCHEMA_VERSION = 1---def _validated_relative_path(value: str) -> str:- if not isinstance(value, str) or not value or "\x00" in value:- raise ValueError("invalid effective-home-relative path")- path = PurePosixPath(value)- if path.is_absolute() or any(part in {"", ".", ".."} for part in path.parts):- raise ValueError("invalid effective-home-relative path")- if path.as_posix() != value:- raise ValueError("effective-home-relative path must be canonical")- return value---class MemoryClearJournalError(RuntimeError):- """Base class for a refused or failed journal operation."""---class ClearOperationConflict(MemoryClearJournalError):- """A second clear was attempted while another operation is open."""---class ClearOperationNotFound(MemoryClearJournalError):- """The requested clear operation does not exist."""---class ClearOperationCASMismatch(MemoryClearJournalError):- """The caller no longer owns the journal revision or execution claim."""---class ClearTransitionError(MemoryClearJournalError):- """The requested state transition violates clear ordering."""---class ClearBackupBlocked(MemoryClearJournalError):- """An ordinary backup was attempted while a clear operation was open."""-- def __init__(self, operation_id: str, state: ClearOperationState) -> None:- super().__init__(f"Memory backup is blocked by open clear {operation_id!r} ({state})")- self.operation_id = operation_id- self.state = state---@dataclass(frozen=True, slots=True)-class ClearSurfaceSpec:- """One fixed logical surface and its effective-home-relative path."""-- name: ClearSurfaceName- relative_path: str-- def __post_init__(self) -> None:- if self.name not in _SURFACE_NAMES:- raise ValueError("unsupported Memory clear surface")- object.__setattr__(self, "relative_path", _validated_relative_path(self.relative_path))---DEFAULT_CLEAR_SURFACES: tuple[ClearSurfaceSpec, ...] = (- ClearSurfaceSpec("queue", "state/memory/memory.sqlite"),- ClearSurfaceSpec("provider", "memory/everos-root"),- ClearSurfaceSpec("call_log", "memory/call-log/call-log.db"),- ClearSurfaceSpec("attachments", "memory/attachments"),-)---@dataclass(frozen=True, slots=True)-class ClearOperation:- operation_id: str- operator_ref: str- state: ClearOperationState- recovery_from_state: Literal["preparing", "prepared", "deleting"] | None- resolution: ClearResolution | None- started_at: str- updated_at: str- terminal_at: str | None- pre_epoch: int- target_epoch: int- snapshot_path: str | None- manifest_sha256: str | None- destructive_started: bool- closed_error: str | None- revision: int- execution_token: str | None---@dataclass(frozen=True, slots=True)-class ClearJournalObservation:- """One owner-scoped snapshot of the open Clear operation."""-- operation: ClearOperation | None- can_resume: bool- can_abort: bool---@dataclass(frozen=True, slots=True)-class ClearSurface:- operation_id: str- surface: ClearSurfaceName- relative_path: str- relative_snapshot_path: str | None- present: bool | None- pre_clear_digest: str | None- snapshot_digest: str | None- state: ClearSurfaceState- updated_at: str---@dataclass(frozen=True, slots=True)-class ClearEvent:- event_id: int- operation_id: str- event: str- actor_ref: str- surface: ClearSurfaceName | None- occurred_at: str- closed_error: str | None- resulting_revision: int---class MemoryClearJournal:- """Separate SQLite journal for one-at-a-time Memory clear recovery."""-- def __init__(- self,- effective_home: Path | str,- *,- database_path: Path | str = "state/memory/clear-journal.sqlite",- surfaces: Sequence[ClearSurfaceSpec] = DEFAULT_CLEAR_SURFACES,- ) -> None:- self._effective_home = Path(os.path.abspath(os.path.expanduser(os.fspath(effective_home))))- database_value = Path(database_path)- if database_value.is_absolute():- self._database_path = Path(os.path.abspath(database_value))- _relative_to_home(self._database_path, self._effective_home)- else:- relative = _validated_relative_path(database_value.as_posix())- self._database_path = self._effective_home / relative- self._database = PrivateSqliteDatabase(self._effective_home, self._database_path)- self._surfaces = tuple(surfaces)- self._validate_surfaces()- self._initialize()-- @property- def database_path(self) -> Path:- return self._database_path-- @property- def surfaces(self) -> tuple[ClearSurfaceSpec, ...]:- return self._surfaces-- def start(- self,- *,- operator_ref: str,- pre_epoch: int,- target_epoch: int,- operation_id: str | None = None,- ) -> ClearOperation:- """Durably create the single open operation and its four surfaces."""-- identifier = _validated_operation_id(operation_id or secrets.token_hex(16))- actor = _validated_actor(operator_ref)- _validated_epoch_pair(pre_epoch, target_epoch)- now = _utc_now()- token = secrets.token_hex(16)- try:- with self._transaction() as connection:- connection.execute(- """- INSERT INTO clear_operation (- operation_id, operator_ref, state, started_at, updated_at,- pre_epoch, target_epoch, destructive_started, open_slot,- revision, execution_token- ) VALUES (?, ?, 'preparing', ?, ?, ?, ?, 0, 1, 1, ?)- """,- (identifier, actor, now, now, pre_epoch, target_epoch, token),- )- connection.executemany(- """- INSERT INTO clear_surface (- operation_id, surface, relative_path, state, updated_at- ) VALUES (?, ?, ?, 'pending', ?)- """,- [- (identifier, surface.name, surface.relative_path, now)- for surface in self._surfaces- ],- )- self._append_event(- connection,- identifier,- "started",- actor,- occurred_at=now,- resulting_revision=1,- )- except sqlite3.IntegrityError as error:- if self.get_open_operation() is not None:- raise ClearOperationConflict("a Memory clear operation is already open") from error- raise MemoryClearJournalError("Memory clear journal rejected the operation") from error- return self._require_operation(identifier)-- def get_operation(self, operation_id: str) -> ClearOperation | None:- identifier = _validated_operation_id(operation_id)- connection = self._connect()- try:- row = connection.execute(- "SELECT * FROM clear_operation WHERE operation_id = ?",- (identifier,),- ).fetchone()- finally:- connection.close()- return _operation_from_row(row) if row is not None else None-- def get_open_operation(self) -> ClearOperation | None:- connection = self._connect()- try:- row = connection.execute(- "SELECT * FROM clear_operation WHERE open_slot = 1"- ).fetchone()- finally:- connection.close()- return _operation_from_row(row) if row is not None else None-- def observe_open_operation(- self,- *,- operator_ref: str | None = None,- ) -> ClearJournalObservation:- """Read the open operation and its recovery capabilities once."""-- connection = self._connect()- try:- connection.execute("BEGIN")- row = connection.execute(- "SELECT * FROM clear_operation WHERE open_slot = 1"- ).fetchone()- if row is None:- return ClearJournalObservation(None, False, False)- owns_recovery = (- operator_ref is not None and row["operator_ref"] == operator_ref- )- can_resume = owns_recovery and self._can_resume_from_row(row)- can_abort = False- if owns_recovery:- try:- can_abort = self._can_abort_from_row(connection, row)- except sqlite3.Error:- can_abort = False- return ClearJournalObservation(- operation=_operation_from_row(row),- can_resume=can_resume,- can_abort=can_abort,- )- finally:- connection.close()-- def get_surfaces(self, operation_id: str) -> tuple[ClearSurface, ...]:- identifier = _validated_operation_id(operation_id)- connection = self._connect()- try:- rows = connection.execute(- """- SELECT * FROM clear_surface- WHERE operation_id = ?- ORDER BY CASE surface- WHEN 'queue' THEN 1- WHEN 'provider' THEN 2- WHEN 'call_log' THEN 3- WHEN 'attachments' THEN 4- END- """,- (identifier,),- ).fetchall()- finally:- connection.close()- if not rows and self.get_operation(identifier) is None:- raise ClearOperationNotFound(identifier)- return tuple(_surface_from_row(row) for row in rows)-- def can_abort(self, operation_id: str) -> bool:- """Report whether the current recovery claim may restore its snapshot."""-- identifier = _validated_operation_id(operation_id)- connection = self._connect()- try:- row = connection.execute(- "SELECT * FROM clear_operation WHERE operation_id = ?",- (identifier,),- ).fetchone()- if row is None:- raise ClearOperationNotFound(identifier)- return self._can_abort_from_row(connection, row)- finally:- connection.close()-- def can_resume(self, operation_id: str) -> bool:- """Report whether the current recovery claim may continue deletion."""-- identifier = _validated_operation_id(operation_id)- connection = self._connect()- try:- row = connection.execute(- "SELECT * FROM clear_operation WHERE operation_id = ?",- (identifier,),- ).fetchone()- if row is None:- raise ClearOperationNotFound(identifier)- return self._can_resume_from_row(row)- finally:- connection.close()-- def get_events(self, operation_id: str) -> tuple[ClearEvent, ...]:- identifier = _validated_operation_id(operation_id)- connection = self._connect()- try:- rows = connection.execute(- "SELECT * FROM clear_event WHERE operation_id = ? ORDER BY event_id",- (identifier,),- ).fetchall()- finally:- connection.close()- if not rows and self.get_operation(identifier) is None:- raise ClearOperationNotFound(identifier)- return tuple(_event_from_row(row) for row in rows)-- def assert_backup_allowed(self) -> None:- """Fail closed while any non-terminal operation occupies the open slot."""-- operation = self.get_open_operation()- if operation is not None:- raise ClearBackupBlocked(operation.operation_id, operation.state)-- def record_snapshot(- self,- operation_id: str,- *,- expected_revision: int,- execution_token: str,- snapshot: MemorySnapshot,- ) -> ClearOperation:- """Atomically persist one manager-verified all-surface receipt."""-- identifier = _validated_operation_id(operation_id)- if not isinstance(snapshot, MemorySnapshot) or snapshot.snapshot_id != identifier:- raise ValueError("Memory snapshot receipt does not match the clear operation")- relative_snapshot = _validated_relative_path(snapshot.relative_path)- if relative_snapshot != f"state/memory/clear-snapshots/{identifier}":- raise ValueError("Memory snapshot path does not match the clear operation")- manifest_digest = _validated_digest(snapshot.manifest_sha256)- receipts = {receipt.path: receipt for receipt in snapshot.surface_receipts}- expected_paths = {surface.relative_path for surface in self._surfaces}- if set(receipts) != expected_paths or len(receipts) != len(snapshot.surface_receipts):- raise ValueError("Memory snapshot receipt must cover exactly four surfaces")-- with self._transaction() as connection:- row = self._cas_row(- connection,- identifier,- expected_revision,- execution_token,- allowed_states=("preparing",),- )- pending = connection.execute(- """- SELECT COUNT(*) FROM clear_surface- WHERE operation_id = ? AND state != 'pending'- """,- (identifier,),- ).fetchone()[0]- if pending:- raise ClearTransitionError("Memory clear snapshot was already recorded")- now = _utc_now()- revision = row["revision"] + 1- for surface in self._surfaces:- receipt = receipts[surface.relative_path]- connection.execute(- """- UPDATE clear_surface- SET relative_snapshot_path = ?, present = ?,- pre_clear_digest = ?, snapshot_digest = ?,- state = 'snapshotted', updated_at = ?- WHERE operation_id = ? AND surface = ?- """,- (- (- PurePosixPath(relative_snapshot)- / "payload"- / surface.relative_path- ).as_posix(),- int(receipt.present),- receipt.pre_clear_digest,- receipt.snapshot_digest,- now,- identifier,- surface.name,- ),- )- self._append_event(- connection,- identifier,- "surface_snapshotted",- row["operator_ref"],- surface=surface.name,- occurred_at=now,- resulting_revision=revision,- )- connection.execute(- """- UPDATE clear_operation- SET snapshot_path = ?, manifest_sha256 = ?, updated_at = ?, revision = ?- WHERE operation_id = ?- """,- (relative_snapshot, manifest_digest, now, revision, identifier),- )- return self._require_operation(identifier)-- def mark_prepared(- self,- operation_id: str,- *,- expected_revision: int,- execution_token: str,- ) -> ClearOperation:- """Seal the independently verified snapshot before destructive work."""-- identifier = _validated_operation_id(operation_id)- with self._transaction() as connection:- row = self._cas_row(- connection,- identifier,- expected_revision,- execution_token,- allowed_states=("preparing",),- )- pending = connection.execute(- """- SELECT COUNT(*) FROM clear_surface- WHERE operation_id = ? AND (- state != 'snapshotted' OR present IS NULL OR- (present = 1 AND (- pre_clear_digest IS NULL OR snapshot_digest IS NULL- )) OR- (present = 0 AND (- pre_clear_digest IS NOT NULL OR snapshot_digest IS NOT NULL- ))- )- """,- (identifier,),- ).fetchone()[0]- if pending or row["snapshot_path"] is None or row["manifest_sha256"] is None:- raise ClearTransitionError("all Memory clear surfaces must be snapshotted first")- now = _utc_now()- revision = row["revision"] + 1- connection.execute(- """- UPDATE clear_operation- SET state = 'prepared', updated_at = ?, revision = ?- WHERE operation_id = ?- """,- (now, revision, identifier),- )- self._append_event(- connection,- identifier,- "prepared",- row["operator_ref"],- occurred_at=now,- resulting_revision=revision,- )- return self._require_operation(identifier)-- def begin_deleting(- self,- operation_id: str,- *,- expected_revision: int,- execution_token: str,- ) -> ClearOperation:- """Persist destructive intent before the first deletion is allowed."""-- return self._operation_transition(- operation_id,- expected_revision=expected_revision,- execution_token=execution_token,- allowed_states=("prepared",),- next_state="deleting",- event="deleting_started",- assignments={"destructive_started": 1},- )-- def record_surface_deleted(- self,- operation_id: str,- surface: ClearSurfaceName,- *,- expected_revision: int,- execution_token: str,- ) -> ClearOperation:- """Acknowledge one idempotent deletion already performed by runtime."""-- return self._surface_transition(- _validated_operation_id(operation_id),- _validated_surface_name(surface),- expected_revision=expected_revision,- execution_token=execution_token,- operation_state="deleting",- from_states=("snapshotted",),- to_state="deleted",- event="surface_deleted",- )-- def mark_completed(- self,- operation_id: str,- *,- expected_revision: int,- execution_token: str,- ) -> ClearOperation:- """Close a clear only after all four deletion receipts are durable."""-- identifier = _validated_operation_id(operation_id)- with self._transaction() as connection:- row = self._cas_row(- connection,- identifier,- expected_revision,- execution_token,- allowed_states=("deleting",),- )- incomplete = connection.execute(- """- SELECT COUNT(*) FROM clear_surface- WHERE operation_id = ? AND state != 'deleted'- """,- (identifier,),- ).fetchone()[0]- if incomplete:- raise ClearTransitionError("all Memory clear surfaces must be deleted first")- now = _utc_now()- revision = row["revision"] + 1- connection.execute(- """- UPDATE clear_operation- SET state = 'completed', updated_at = ?, terminal_at = ?,- open_slot = NULL, revision = ?, execution_token = NULL- WHERE operation_id = ?- """,- (now, now, revision, identifier),- )- self._append_event(- connection,- identifier,- "completed",- row["operator_ref"],- occurred_at=now,- resulting_revision=revision,- )- return self._require_operation(identifier)-- def mark_recovery_needed(- self,- operation_id: str,- *,- expected_revision: int,- execution_token: str,- closed_error: str = "memory_clear_failed",- ) -> ClearOperation:- """Fence an in-process failure at its exact active stage."""-- identifier = _validated_operation_id(operation_id)- error = _validated_error(closed_error)- with self._transaction() as connection:- row = self._cas_row(- connection,- identifier,- expected_revision,- execution_token,- allowed_states=("preparing", "prepared", "deleting"),- )- now = _utc_now()- revision = row["revision"] + 1- connection.execute(- """- UPDATE clear_operation- SET state = 'recovery_needed', recovery_from_state = ?,- updated_at = ?, closed_error = ?, revision = ?,- execution_token = NULL- WHERE operation_id = ?- """,- (row["state"], now, error, revision, identifier),- )- self._append_event(- connection,- identifier,- "recovery_needed",- row["operator_ref"],- occurred_at=now,- closed_error=error,- resulting_revision=revision,- )- return self._require_operation(identifier)-- def mark_boot_recovery_needed(- self,- *,- closed_error: str = "memory_clear_failed",- ) -> ClearOperation | None:- """Explicitly expose an interrupted open operation without resuming it.-- Construction is intentionally side-effect free with respect to operation- state. Boot orchestration calls this method once it owns the runtime- fence. No deletion or restore is performed here.- """-- error = _validated_error(closed_error)- with self._transaction() as connection:- row = connection.execute(- "SELECT * FROM clear_operation WHERE open_slot = 1"- ).fetchone()- if row is None:- return None- now = _utc_now()- revision = row["revision"] + 1- recovery_from = (- row["recovery_from_state"]- if row["state"] == "recovery_needed"- else row["state"]- )- connection.execute(- """- UPDATE clear_operation- SET state = 'recovery_needed', recovery_from_state = ?,- updated_at = ?, closed_error = ?, revision = ?,- execution_token = NULL- WHERE operation_id = ?- """,- (recovery_from, now, error, revision, row["operation_id"]),- )- self._append_event(- connection,- row["operation_id"],- "recovery_needed",- "system:boot",- occurred_at=now,- closed_error=error,- resulting_revision=revision,- )- return self._require_operation(row["operation_id"])-- def claim_resume(- self,- operation_id: str,- *,- operator_ref: str,- expected_revision: int,- ) -> ClearOperation:- """Claim continuation of the exact stage interrupted at boot."""-- identifier = _validated_operation_id(operation_id)- actor = _validated_actor(operator_ref)- with self._transaction() as connection:- row = self._recovery_claim_row(connection, identifier, actor, expected_revision)- if row["resolution"] == "abort":- raise ClearTransitionError("an abort decision cannot be changed to resume")- next_state = row["recovery_from_state"]- if next_state not in {"preparing", "prepared", "deleting"}:- raise ClearTransitionError("Memory clear recovery stage is missing")- now = _utc_now()- revision = row["revision"] + 1- token = secrets.token_hex(16)- connection.execute(- """- UPDATE clear_operation- SET state = ?, resolution = 'resume', updated_at = ?,- closed_error = NULL, revision = ?, execution_token = ?- WHERE operation_id = ?- """,- (next_state, now, revision, token, identifier),- )- self._append_event(- connection,- identifier,- "resume_claimed",- actor,- occurred_at=now,- resulting_revision=revision,- )- return self._require_operation(identifier)-- def claim_abort(- self,- operation_id: str,- *,- operator_ref: str,- expected_revision: int,- ) -> ClearOperation:- """Make the abort direction durable and return its execution claim."""-- identifier = _validated_operation_id(operation_id)- actor = _validated_actor(operator_ref)- with self._transaction() as connection:- row = self._recovery_claim_row(connection, identifier, actor, expected_revision)- if row["resolution"] == "resume":- raise ClearTransitionError("a resume decision cannot be changed to abort")- if not self._abort_snapshot_complete(connection, row):- raise ClearTransitionError("abort requires a complete verified Memory snapshot")- now = _utc_now()- revision = row["revision"] + 1- token = secrets.token_hex(16)- connection.execute(- """- UPDATE clear_operation- SET resolution = 'abort', updated_at = ?, revision = ?,- execution_token = ?- WHERE operation_id = ?- """,- (now, revision, token, identifier),- )- self._append_event(- connection,- identifier,- "abort_claimed",- actor,- occurred_at=now,- resulting_revision=revision,- )- return self._require_operation(identifier)-- def release_recovery_claim(- self,- operation_id: str,- *,- expected_revision: int,- execution_token: str,- closed_error: str = "memory_clear_failed",- ) -> ClearOperation:- """Release a failed resume/abort claim without changing its decision."""-- identifier = _validated_operation_id(operation_id)- error = _validated_error(closed_error)- with self._transaction() as connection:- row = self._cas_row(- connection,- identifier,- expected_revision,- execution_token,- allowed_states=("recovery_needed",),- )- if row["resolution"] not in {"resume", "abort"}:- raise ClearTransitionError("Memory clear recovery decision is missing")- now = _utc_now()- revision = row["revision"] + 1- connection.execute(- """- UPDATE clear_operation- SET updated_at = ?, closed_error = ?, revision = ?,- execution_token = NULL- WHERE operation_id = ?- """,- (now, error, revision, identifier),- )- self._append_event(- connection,- identifier,- "recovery_claim_failed",- row["operator_ref"],- occurred_at=now,- closed_error=error,- resulting_revision=revision,- )- return self._require_operation(identifier)-- def record_surface_restored(- self,- operation_id: str,- surface: ClearSurfaceName,- *,- expected_revision: int,- execution_token: str,- ) -> ClearOperation:- """Acknowledge one verified restore under an abort claim."""-- return self._surface_transition(- _validated_operation_id(operation_id),- _validated_surface_name(surface),- expected_revision=expected_revision,- execution_token=execution_token,- operation_state="recovery_needed",- resolution="abort",- from_states=("snapshotted", "deleted"),- to_state="restored",- event="surface_restored",- )-- def mark_aborted(- self,- operation_id: str,- *,- expected_revision: int,- execution_token: str,- closed_error: str | None = None,- ) -> ClearOperation:- """Close an abort after restoration, or before destructive start."""-- identifier = _validated_operation_id(operation_id)- error = _validated_optional_error(closed_error)- with self._transaction() as connection:- row = self._cas_row(- connection,- identifier,- expected_revision,- execution_token,- allowed_states=("recovery_needed",),- resolution="abort",- )- incomplete = connection.execute(- """- SELECT COUNT(*) FROM clear_surface- WHERE operation_id = ? AND state != 'restored'- """,- (identifier,),- ).fetchone()[0]- if incomplete:- raise ClearTransitionError("all Memory clear surfaces must be restored first")- now = _utc_now()- revision = row["revision"] + 1- connection.execute(- """- UPDATE clear_operation- SET state = 'aborted', updated_at = ?, terminal_at = ?,- open_slot = NULL, closed_error = ?, revision = ?,- execution_token = NULL- WHERE operation_id = ?- """,- (now, now, error, revision, identifier),- )- self._append_event(- connection,- identifier,- "aborted",- row["operator_ref"],- occurred_at=now,- closed_error=error,- resulting_revision=revision,- )- return self._require_operation(identifier)-- def _initialize(self) -> None:- try:- self._database.prepare()- except ConfinedFilesystemError as error:- raise MemoryClearJournalError(- "Memory clear journal could not be prepared safely"- ) from error- connection = self._connect()- try:- version = connection.execute("PRAGMA user_version").fetchone()[0]- if version not in {0, _SCHEMA_VERSION}:- raise MemoryClearJournalError("unsupported Memory clear journal schema")- if version == 0:- connection.executescript(_schema_sql())- connection.execute(f"PRAGMA user_version={_SCHEMA_VERSION}")- connection.commit()- else:- required = {"clear_operation", "clear_surface", "clear_event"}- present = {- row[0]- for row in connection.execute(- "SELECT name FROM sqlite_master WHERE type = 'table'"- )- }- if not required.issubset(present):- raise MemoryClearJournalError("Memory clear journal schema is incomplete")- result = connection.execute("PRAGMA quick_check").fetchone()- if result is None or result[0] != "ok":- raise MemoryClearJournalError("Memory clear journal failed integrity check")- except sqlite3.Error as error:- raise MemoryClearJournalError("Memory clear journal could not be initialized") from error- finally:- connection.close()- self._harden_database_files(sync_parent=True)-- def _connect(self) -> sqlite3.Connection:- try:- return self._database.connect()- except ConfinedFilesystemError as error:- raise MemoryClearJournalError("Memory clear journal is unsafe") from error-- def _transaction(self) -> AbstractContextManager[sqlite3.Connection]:- return self._database.transaction(- translate_connect_error=lambda _error: MemoryClearJournalError(- "Memory clear journal is unsafe"- ),- translate_harden_error=lambda _error: MemoryClearJournalError(- "Memory clear journal files could not be hardened safely"- ),- )-- def _validate_surfaces(self) -> None:- if len(self._surfaces) != len(_SURFACE_NAMES):- raise ValueError("Memory clear journal requires exactly four surfaces")- names = tuple(surface.name for surface in self._surfaces)- if set(names) != set(_SURFACE_NAMES) or len(set(names)) != len(names):- raise ValueError("Memory clear journal surfaces must be unique and complete")- paths = [PurePosixPath(surface.relative_path) for surface in self._surfaces]- database = PurePosixPath(_relative_to_home(self._database_path, self._effective_home).as_posix())- for index, path in enumerate(paths):- if path == database or path in database.parents or database in path.parents:- raise ValueError("Memory clear journal cannot overlap a managed surface")- for other in paths[index + 1 :]:- if path == other or path in other.parents or other in path.parents:- raise ValueError("Memory clear journal surface paths cannot overlap")-- def _require_operation(self, operation_id: str) -> ClearOperation:- operation = self.get_operation(operation_id)- if operation is None:- raise ClearOperationNotFound(operation_id)- return operation-- @staticmethod- def _cas_row(- connection: sqlite3.Connection,- operation_id: str,- expected_revision: int,- execution_token: str,- *,- allowed_states: Sequence[str],- resolution: str | None = None,- ) -> sqlite3.Row:- if isinstance(expected_revision, bool) or not isinstance(expected_revision, int):- raise ValueError("expected revision must be an integer")- token = _validated_token(execution_token)- row = connection.execute(- "SELECT * FROM clear_operation WHERE operation_id = ?",- (operation_id,),- ).fetchone()- if row is None:- raise ClearOperationNotFound(operation_id)- if row["revision"] != expected_revision or row["execution_token"] != token:- raise ClearOperationCASMismatch("Memory clear operation claim is stale")- if row["state"] not in allowed_states:- raise ClearTransitionError("Memory clear operation is in the wrong state")- if resolution is not None and row["resolution"] != resolution:- raise ClearTransitionError("Memory clear operation has the wrong recovery direction")- return row-- @staticmethod- def _recovery_claim_row(- connection: sqlite3.Connection,- operation_id: str,- operator_ref: str,- expected_revision: int,- ) -> sqlite3.Row:- if isinstance(expected_revision, bool) or not isinstance(expected_revision, int):- raise ValueError("expected revision must be an integer")- row = connection.execute(- "SELECT * FROM clear_operation WHERE operation_id = ?",- (operation_id,),- ).fetchone()- if row is None:- raise ClearOperationNotFound(operation_id)- if row["state"] != "recovery_needed":- raise ClearTransitionError("Memory clear operation does not need recovery")- if row["revision"] != expected_revision or row["execution_token"] is not None:- raise ClearOperationCASMismatch("Memory clear recovery claim is stale")- if row["operator_ref"] != operator_ref:- raise ClearOperationCASMismatch("Memory clear operator does not own this operation")- return row-- @staticmethod- def _abort_snapshot_complete(- connection: sqlite3.Connection,- operation: sqlite3.Row,- ) -> bool:- if operation["snapshot_path"] is None or operation["manifest_sha256"] is None:- return False- summary = connection.execute(- """- SELECT- COUNT(*) AS surface_count,- COUNT(CASE WHEN (- state NOT IN ('snapshotted', 'deleted', 'restored') OR- present IS NULL OR- (present = 1 AND (- pre_clear_digest IS NULL OR snapshot_digest IS NULL- )) OR- (present = 0 AND (- pre_clear_digest IS NOT NULL OR snapshot_digest IS NOT NULL- ))- ) THEN 1 END) AS invalid_count- FROM clear_surface- WHERE operation_id = ?- """,- (operation["operation_id"],),- ).fetchone()- return bool(- summary is not None- and summary["surface_count"] == len(_SURFACE_NAMES)- and summary["invalid_count"] == 0- )-- def _can_abort_from_row(- self,- connection: sqlite3.Connection,- operation: sqlite3.Row,- ) -> bool:- return bool(- operation["state"] == "recovery_needed"- and operation["execution_token"] is None- and operation["resolution"] != "resume"- and self._abort_snapshot_complete(connection, operation)- )-- @staticmethod- def _can_resume_from_row(operation: sqlite3.Row) -> bool:- return bool(- operation["state"] == "recovery_needed"- and operation["execution_token"] is None- and operation["resolution"] != "abort"- and operation["recovery_from_state"]- in {"preparing", "prepared", "deleting"}- )-- def _operation_transition(- self,- operation_id: str,- *,- expected_revision: int,- execution_token: str,- allowed_states: Sequence[str],- next_state: str,- event: str,- assignments: Mapping[str, object] | None = None,- ) -> ClearOperation:- identifier = _validated_operation_id(operation_id)- allowed_assignments = {"destructive_started"}- values = dict(assignments or {})- if not set(values).issubset(allowed_assignments):- raise ValueError("unsupported Memory clear journal assignment")- with self._transaction() as connection:- row = self._cas_row(- connection,- identifier,- expected_revision,- execution_token,- allowed_states=allowed_states,- )- now = _utc_now()- revision = row["revision"] + 1- columns = ["state = ?", "updated_at = ?", "revision = ?"]- parameters: list[object] = [next_state, now, revision]- for column, value in values.items():- columns.append(f"{column} = ?")- parameters.append(value)- parameters.append(identifier)- connection.execute(- f"UPDATE clear_operation SET {', '.join(columns)} WHERE operation_id = ?",- parameters,- )- self._append_event(- connection,- identifier,- event,- row["operator_ref"],- occurred_at=now,- resulting_revision=revision,- )- return self._require_operation(identifier)-- def _surface_transition(- self,- operation_id: str,- surface: ClearSurfaceName,- *,- expected_revision: int,- execution_token: str,- operation_state: str,- from_states: Sequence[str],- to_state: str,- event: str,- resolution: str | None = None,- assignments: Mapping[str, object] | None = None,- ) -> ClearOperation:- allowed_assignments = {- "relative_snapshot_path",- "pre_clear_digest",- "snapshot_digest",- }- values = dict(assignments or {})- if not set(values).issubset(allowed_assignments):- raise ValueError("unsupported Memory clear surface assignment")- with self._transaction() as connection:- row = self._cas_row(- connection,- operation_id,- expected_revision,- execution_token,- allowed_states=(operation_state,),- resolution=resolution,- )- surface_row = connection.execute(- """- SELECT * FROM clear_surface- WHERE operation_id = ? AND surface = ?- """,- (operation_id, surface),- ).fetchone()- if surface_row is None:- raise ClearTransitionError("Memory clear surface is missing")- if surface_row["state"] not in from_states:- raise ClearTransitionError("Memory clear surface is in the wrong state")- now = _utc_now()- revision = row["revision"] + 1- columns = ["state = ?", "updated_at = ?"]- parameters: list[object] = [to_state, now]- for column, value in values.items():- columns.append(f"{column} = ?")- parameters.append(value)- parameters.extend((operation_id, surface))- connection.execute(- f"""- UPDATE clear_surface SET {', '.join(columns)}- WHERE operation_id = ? AND surface = ?- """,- parameters,- )- connection.execute(- """- UPDATE clear_operation- SET updated_at = ?, revision = ?- WHERE operation_id = ?- """,- (now, revision, operation_id),- )- self._append_event(- connection,- operation_id,- event,- row["operator_ref"],- surface=surface,- occurred_at=now,- resulting_revision=revision,- )- return self._require_operation(operation_id)-- @staticmethod- def _append_event(- connection: sqlite3.Connection,- operation_id: str,- event: str,- actor_ref: str,- *,- occurred_at: str,- resulting_revision: int,- surface: str | None = None,- closed_error: str | None = None,- ) -> None:- connection.execute(- """- INSERT INTO clear_event (- operation_id, event, actor_ref, surface, occurred_at,- closed_error, resulting_revision- ) VALUES (?, ?, ?, ?, ?, ?, ?)- """,- (- operation_id,- event,- actor_ref,- surface,- occurred_at,- closed_error,- resulting_revision,- ),- )-- def _harden_database_files(self, *, sync_parent: bool = False) -> None:- try:- self._database.harden(sync_parent=sync_parent)- except ConfinedFilesystemError as error:- raise MemoryClearJournalError(- "Memory clear journal files could not be hardened safely"- ) from error---def _schema_sql() -> str:- errors = ", ".join(f"'{value}'" for value in sorted(CLOSED_MEMORY_ERROR_CODES))- return f"""- CREATE TABLE clear_operation (- operation_id TEXT PRIMARY KEY,- operator_ref TEXT NOT NULL,- state TEXT NOT NULL CHECK (state IN (- 'preparing', 'prepared', 'deleting', 'recovery_needed',- 'completed', 'aborted'- )),- recovery_from_state TEXT NULL CHECK (- recovery_from_state IS NULL OR recovery_from_state IN (- 'preparing', 'prepared', 'deleting'- )- ),- resolution TEXT NULL CHECK (resolution IS NULL OR resolution IN ('resume', 'abort')),- started_at TEXT NOT NULL,- updated_at TEXT NOT NULL,- terminal_at TEXT NULL,- pre_epoch INTEGER NOT NULL CHECK (pre_epoch >= 0),- target_epoch INTEGER NOT NULL CHECK (target_epoch = pre_epoch + 1),- snapshot_path TEXT NULL,- manifest_sha256 TEXT NULL,- destructive_started INTEGER NOT NULL CHECK (destructive_started IN (0, 1)),- closed_error TEXT NULL CHECK (closed_error IS NULL OR closed_error IN ({errors})),- open_slot INTEGER NULL CHECK (- (state IN ('completed', 'aborted') AND open_slot IS NULL) OR- (state NOT IN ('completed', 'aborted') AND open_slot = 1)- ),- revision INTEGER NOT NULL CHECK (revision >= 1),- execution_token TEXT NULL- );-- CREATE UNIQUE INDEX clear_operation_one_open- ON clear_operation(open_slot) WHERE open_slot = 1;-- CREATE TABLE clear_surface (- operation_id TEXT NOT NULL REFERENCES clear_operation(operation_id),- surface TEXT NOT NULL CHECK (surface IN (- 'queue', 'provider', 'call_log', 'attachments'- )),- relative_path TEXT NOT NULL,- relative_snapshot_path TEXT NULL,- present INTEGER NULL CHECK (present IS NULL OR present IN (0, 1)),- pre_clear_digest TEXT NULL,- snapshot_digest TEXT NULL,- state TEXT NOT NULL CHECK (state IN (- 'pending', 'snapshotted', 'deleted', 'restored'- )),- updated_at TEXT NOT NULL,- CHECK (- (state = 'pending' AND relative_snapshot_path IS NULL AND- present IS NULL AND pre_clear_digest IS NULL AND snapshot_digest IS NULL) OR- (state != 'pending' AND relative_snapshot_path IS NOT NULL AND (- (present = 0 AND pre_clear_digest IS NULL AND snapshot_digest IS NULL) OR- (present = 1 AND pre_clear_digest IS NOT NULL AND snapshot_digest IS NOT NULL)- ))- ),- PRIMARY KEY (operation_id, surface)- );-- CREATE TABLE clear_event (- event_id INTEGER PRIMARY KEY AUTOINCREMENT,- operation_id TEXT NOT NULL REFERENCES clear_operation(operation_id),- event TEXT NOT NULL CHECK (event IN (- 'started', 'surface_snapshotted', 'prepared', 'deleting_started',- 'surface_deleted', 'recovery_needed', 'resume_claimed',- 'abort_claimed', 'surface_restored', 'snapshot_discarded',- 'recovery_claim_failed', 'completed', 'aborted'- )),- actor_ref TEXT NOT NULL,- surface TEXT NULL CHECK (- surface IS NULL OR surface IN ('queue', 'provider', 'call_log', 'attachments')- ),- occurred_at TEXT NOT NULL,- closed_error TEXT NULL CHECK (closed_error IS NULL OR closed_error IN ({errors})),- resulting_revision INTEGER NOT NULL CHECK (resulting_revision >= 1)- );-- CREATE TRIGGER clear_event_no_update- BEFORE UPDATE ON clear_event- BEGIN- SELECT RAISE(ABORT, 'clear events are append-only');- END;-- CREATE TRIGGER clear_event_no_delete- BEFORE DELETE ON clear_event- BEGIN- SELECT RAISE(ABORT, 'clear events are append-only');- END;-- CREATE TRIGGER clear_operation_terminal_no_update- BEFORE UPDATE ON clear_operation- WHEN OLD.state IN ('completed', 'aborted')- BEGIN- SELECT RAISE(ABORT, 'terminal clear operations are immutable');- END;-- CREATE TRIGGER clear_operation_valid_transition- BEFORE UPDATE OF state ON clear_operation- WHEN NEW.state != OLD.state AND NOT (- (OLD.state = 'preparing' AND NEW.state IN ('prepared', 'recovery_needed')) OR- (OLD.state = 'prepared' AND NEW.state IN ('deleting', 'recovery_needed')) OR- (OLD.state = 'deleting' AND NEW.state IN ('completed', 'recovery_needed')) OR- (OLD.state = 'recovery_needed' AND NEW.state IN (- 'preparing', 'prepared', 'deleting', 'aborted'- ))- )- BEGIN- SELECT RAISE(ABORT, 'invalid clear operation transition');- END;-- CREATE TRIGGER clear_operation_resolution_one_way- BEFORE UPDATE OF resolution ON clear_operation- WHEN OLD.resolution IS NOT NULL AND NEW.resolution IS NOT OLD.resolution- BEGIN- SELECT RAISE(ABORT, 'clear recovery direction is immutable');- END;-- CREATE TRIGGER clear_operation_destructive_one_way- BEFORE UPDATE OF destructive_started ON clear_operation- WHEN NEW.destructive_started < OLD.destructive_started OR- (NEW.destructive_started = 1 AND NEW.state NOT IN (- 'deleting', 'recovery_needed', 'completed', 'aborted'- ))- BEGIN- SELECT RAISE(ABORT, 'clear destructive intent is invalid');- END;-- CREATE TRIGGER clear_operation_no_delete- BEFORE DELETE ON clear_operation- BEGIN- SELECT RAISE(ABORT, 'clear operation audit is immutable');- END;-- CREATE TRIGGER clear_surface_terminal_no_insert- BEFORE INSERT ON clear_surface- WHEN (SELECT state FROM clear_operation WHERE operation_id = NEW.operation_id)- IN ('completed', 'aborted')- BEGIN- SELECT RAISE(ABORT, 'terminal clear surfaces are immutable');- END;-- CREATE TRIGGER clear_surface_terminal_no_update- BEFORE UPDATE ON clear_surface- WHEN (SELECT state FROM clear_operation WHERE operation_id = OLD.operation_id)- IN ('completed', 'aborted')- BEGIN- SELECT RAISE(ABORT, 'terminal clear surfaces are immutable');- END;-- CREATE TRIGGER clear_surface_valid_transition- BEFORE UPDATE OF state ON clear_surface- WHEN NEW.state != OLD.state AND NOT (- (OLD.state = 'pending' AND NEW.state = 'snapshotted') OR- (OLD.state = 'snapshotted' AND NEW.state IN ('deleted', 'restored')) OR- (OLD.state = 'deleted' AND NEW.state = 'restored')- )- BEGIN- SELECT RAISE(ABORT, 'invalid clear surface transition');- END;-- CREATE TRIGGER clear_surface_no_delete- BEFORE DELETE ON clear_surface- BEGIN- SELECT RAISE(ABORT, 'clear surface audit is immutable');- END;- """---def _operation_from_row(row: sqlite3.Row) -> ClearOperation:- return ClearOperation(- operation_id=row["operation_id"],- operator_ref=row["operator_ref"],- state=row["state"],- recovery_from_state=row["recovery_from_state"],- resolution=row["resolution"],- started_at=row["started_at"],- updated_at=row["updated_at"],- terminal_at=row["terminal_at"],- pre_epoch=row["pre_epoch"],- target_epoch=row["target_epoch"],- snapshot_path=row["snapshot_path"],- manifest_sha256=row["manifest_sha256"],- destructive_started=bool(row["destructive_started"]),- closed_error=row["closed_error"],- revision=row["revision"],- execution_token=row["execution_token"],- )---def _surface_from_row(row: sqlite3.Row) -> ClearSurface:- return ClearSurface(- operation_id=row["operation_id"],- surface=row["surface"],- relative_path=row["relative_path"],- relative_snapshot_path=row["relative_snapshot_path"],- present=None if row["present"] is None else bool(row["present"]),- pre_clear_digest=row["pre_clear_digest"],- snapshot_digest=row["snapshot_digest"],- state=row["state"],- updated_at=row["updated_at"],- )---def _event_from_row(row: sqlite3.Row) -> ClearEvent:- return ClearEvent(- event_id=row["event_id"],- operation_id=row["operation_id"],- event=row["event"],- actor_ref=row["actor_ref"],- surface=row["surface"],- occurred_at=row["occurred_at"],- closed_error=row["closed_error"],- resulting_revision=row["resulting_revision"],- )---def _validated_operation_id(value: str) -> str:- if not isinstance(value, str) or _OPERATION_ID_RE.fullmatch(value) is None:- raise ValueError("invalid Memory clear operation id")- return value---def _validated_actor(value: str) -> str:- if (- not isinstance(value, str)- or not value- or len(value.encode("utf-8")) > 512- or any(ord(character) < 0x20 for character in value)- ):- raise ValueError("invalid Memory clear operator reference")- return value---def _validated_epoch_pair(pre_epoch: int, target_epoch: int) -> None:- if (- isinstance(pre_epoch, bool)- or not isinstance(pre_epoch, int)- or pre_epoch < 0- or isinstance(target_epoch, bool)- or not isinstance(target_epoch, int)- or target_epoch != pre_epoch + 1- ):- raise ValueError("Memory clear target epoch must equal pre epoch plus one")---def _validated_token(value: str) -> str:- if not isinstance(value, str) or _TOKEN_RE.fullmatch(value) is None:- raise ValueError("invalid Memory clear execution token")- return value---def _validated_digest(value: str) -> str:- if not isinstance(value, str) or _SHA256_RE.fullmatch(value) is None:- raise ValueError("invalid Memory clear SHA-256 digest")- return value---def _validated_error(value: str) -> str:- if not is_memory_error_code(value):- raise ValueError("invalid closed Memory error code")- return value---def _validated_optional_error(value: str | None) -> str | None:- return None if value is None else _validated_error(value)---def _validated_surface_name(value: str) -> ClearSurfaceName:- if value not in _SURFACE_NAMES:- raise ValueError("invalid Memory clear surface")- return value # type: ignore[return-value]---def _relative_to_home(path: Path, home: Path) -> Path:- try:- return path.relative_to(home)- except ValueError as error:- raise ValueError("Memory clear journal must stay within effective home") from error---def _utc_now() -> str:- return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")diff --git a/core/memory/clear_snapshot_storage.py b/core/memory/clear_snapshot_storage.pydeleted file mode 100644index 7ee4788d6..000000000--- a/core/memory/clear_snapshot_storage.py+++ /dev/null@@ -1,182 +0,0 @@-"""Durably authorized storage cleanup for Memory clear snapshots."""--from __future__ import annotations--from dataclasses import dataclass--from core.memory.clear_journal import (- ClearOperation,- ClearOperationCASMismatch,- ClearTransitionError,- MemoryClearJournal,- _utc_now,- _validated_digest,- _validated_operation_id,- _validated_relative_path,-)-from core.memory.snapshot import MemorySnapshotManager---@dataclass(frozen=True, slots=True)-class _TerminalSnapshot:- operation_id: str- relative_path: str- manifest_sha256: str- surface_digests: dict[str, str | None]---class MemoryClearSnapshotStorage:- """Own journal-authorized cleanup of clear snapshots."""-- def __init__(- self,- journal: MemoryClearJournal,- snapshot_manager: MemorySnapshotManager,- ) -> None:- self._journal = journal- self._snapshot_manager = snapshot_manager-- def discard_unrecorded_preparing_snapshot(- self,- operation_id: str,- *,- expected_revision: int,- execution_token: str,- ) -> ClearOperation:- """Discard one exact unrecorded preparing snapshot and journal the result."""-- identifier = _validated_operation_id(operation_id)- with self._journal._transaction() as connection:- row = self._journal._cas_row(- connection,- identifier,- expected_revision,- execution_token,- allowed_states=("preparing",),- )- nonpending = connection.execute(- """- SELECT COUNT(*) FROM clear_surface- WHERE operation_id = ? AND state != 'pending'- """,- (identifier,),- ).fetchone()[0]- if (- nonpending- or row["snapshot_path"] is not None- or row["manifest_sha256"] is not None- or row["destructive_started"]- ):- raise ClearTransitionError(- "only an unrecorded preparing snapshot may be discarded"- )-- relative_path = f"state/memory/clear-snapshots/{identifier}"- self._snapshot_manager._discard_unrecorded_clear_snapshot(- identifier,- expected_relative_path=relative_path,- )-- now = _utc_now()- revision = row["revision"] + 1- updated = connection.execute(- """- UPDATE clear_operation- SET updated_at = ?, revision = ?- WHERE operation_id = ? AND state = 'preparing'- AND revision = ? AND execution_token = ?- """,- (- now,- revision,- identifier,- row["revision"],- row["execution_token"],- ),- )- if updated.rowcount != 1:- raise ClearOperationCASMismatch(- "Memory clear discard claim is stale"- )- self._journal._append_event(- connection,- identifier,- "snapshot_discarded",- row["operator_ref"],- occurred_at=now,- resulting_revision=revision,- )- return self._journal._require_operation(identifier)-- def eligible_terminal_snapshot_ids(self) -> tuple[str, ...]:- """Return durable terminal snapshot cleanup work in completion order."""-- connection = self._journal._connect()- try:- rows = connection.execute(- """- SELECT operation_id FROM clear_operation- WHERE state IN ('completed', 'aborted')- ORDER BY terminal_at, operation_id- """- ).fetchall()- finally:- connection.close()- identifiers = tuple(str(row["operation_id"]) for row in rows)- for identifier in identifiers:- self._terminal_snapshot(identifier)- return identifiers-- def remove_terminal_snapshot(self, operation_id: str) -> None:- """Remove one snapshot only when its durable clear audit is terminal."""-- snapshot = self._terminal_snapshot(operation_id)- self._snapshot_manager._remove_clear_snapshot(- snapshot.operation_id,- expected_relative_path=snapshot.relative_path,- expected_manifest_sha256=snapshot.manifest_sha256,- expected_surface_digests=snapshot.surface_digests,- )-- def _terminal_snapshot(self, operation_id: str) -> _TerminalSnapshot:- operation = self._journal._require_operation(- _validated_operation_id(operation_id)- )- required_surface_state = {- "completed": "deleted",- "aborted": "restored",- }.get(operation.state)- if required_surface_state is None:- raise ClearTransitionError(- "only a terminal Memory clear may remove its snapshot"- )- if operation.snapshot_path is None or operation.manifest_sha256 is None:- raise ClearTransitionError(- "terminal Memory clear snapshot metadata is missing"- )- relative_path = _validated_relative_path(operation.snapshot_path)- manifest_sha256 = _validated_digest(operation.manifest_sha256)- surfaces = self._journal.get_surfaces(operation.operation_id)- if len(surfaces) != len(self._journal.surfaces) or any(- surface.state != required_surface_state or surface.present is None- for surface in surfaces- ):- raise ClearTransitionError(- "terminal Memory clear surface audit is incomplete"- )- surface_digests: dict[str, str | None] = {}- for surface in surfaces:- relative_surface = _validated_relative_path(surface.relative_path)- if relative_surface in surface_digests:- raise ValueError("terminal Memory snapshot has duplicate surfaces")- surface_digests[relative_surface] = (- None- if surface.snapshot_digest is None- else _validated_digest(surface.snapshot_digest)- )- return _TerminalSnapshot(- operation_id=operation.operation_id,- relative_path=relative_path,- manifest_sha256=manifest_sha256,- surface_digests=surface_digests,- )diff --git a/core/memory/confined_filesystem.py b/core/memory/confined_filesystem.pyindex 87d4f9e98..f17ad491e 100644--- a/core/memory/confined_filesystem.py+++ b/core/memory/confined_filesystem.py@@ -485,6 +485,40 @@ class PrivateSqliteDatabase:raisereturn connection+ def connect_read_only(self) -> sqlite3.Connection:+ """Open a validated SQLite database without mutating its journal mode."""++ required_no_follow_flag()+ try:+ info = os.lstat(self._path)+ except FileNotFoundError as error:+ raise ConfinedFilesystemError(+ "private SQLite database is missing"+ ) from error+ _require_private_regular(info, "private SQLite database")+ for path in _database_sidecars(self._path):+ try:+ sidecar_info = os.lstat(path)+ except FileNotFoundError:+ continue+ _require_private_regular(sidecar_info, "private SQLite sidecar")++ connection = sqlite3.connect(+ f"{self._path.as_uri()}?mode=ro",+ uri=True,+ timeout=PRIVATE_SQLITE_BUSY_TIMEOUT_SECONDS,+ )+ try:+ connection.row_factory = sqlite3.Row+ connection.execute("PRAGMA query_only=ON")+ connection.execute(+ f"PRAGMA busy_timeout={int(PRIVATE_SQLITE_BUSY_TIMEOUT_SECONDS * 1000)}"+ )+ except BaseException:+ connection.close()+ raise+ return connection+@contextmanagerdef transaction(self,diff --git a/core/memory/maintenance.py b/core/memory/maintenance.pyindex 120d5ff30..52772ad93 100644--- a/core/memory/maintenance.py+++ b/core/memory/maintenance.py@@ -1,29 +1,32 @@-"""Durable Clear, backup/restore, and housekeeping ownership for Memory."""+"""Durable, idempotent Memory Clear maintenance."""from __future__ import annotationsimport asyncioimport logging-from collections.abc import Awaitable, Callable, Mapping+import os+from collections.abc import Awaitable, Callablefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import AsyncContextManager, Literal, TypeVar-from core.memory.backup_restore_journal import (- BackupRestoreConflict,- BackupRestoreOperation,- MemoryBackupRestoreJournal,-)from core.memory.blocking import run_blocking-from core.memory.clear_journal import ClearOperation, ClearSurface, MemoryClearJournal-from core.memory.clear_snapshot_storage import MemoryClearSnapshotStorage-from core.memory.snapshot import MemorySnapshot, MemorySnapshotManager+from core.memory.clear_intent import (+ ClearIntent,+ ClearIntentError,+ ClearIntentStore,+ ClearIntentUnreadable,+ ClearSurface,+ DEFAULT_CLEAR_SURFACES,+ LEGACY_RERUN_ERROR_CODE,+ cleanup_legacy_backup_storage,+)+from core.memory.confined_filesystem import ConfinedFilesystemError, required_no_follow_flag+from core.memory.operation_lock import MemoryOperationBusy, MemoryOperationLeasefrom core.memory.store import MemoryStorelogger = logging.getLogger(__name__)--_MaintenanceIOResult = TypeVar("_MaintenanceIOResult")@@ -33,51 +36,43 @@ class MemoryStoreUnavailableError(RuntimeError):@dataclass(frozen=True)class MaintenanceRuntimeState:- """Dynamic runtime gates needed by maintenance-owned jobs."""-artifact_installing: bool@dataclass(frozen=True)-class ClearRecoveryResult:- state: str+class ClearInProgressResult:+ state: Literal["deleting", "failed"]operation_id: stroccurred_at: strerror_code: str | None- can_resume: bool- can_abort: bool@dataclass(frozen=True)class ClearResult:- status: Literal["completed", "aborted", "failed"]+ status: Literal["completed", "failed"]operation_id: str | None = Noneepoch: int | None = Noneerror: str | None = None- recovery: ClearRecoveryResult | None = None+ clear_in_progress: ClearInProgressResult | None = None@dataclass(frozen=True)class MaintenanceResult:data_exists: boolcan_clear: bool- clear_recovery: ClearRecoveryResult | None+ clear_in_progress: ClearInProgressResult | Noneerror: str | None = None@dataclass(frozen=True)class MaintenanceObservation:- """One point-in-time view of the journals used by read projections."""-block_reason: str | None- clear_recovery: ClearRecoveryResult | None+ clear_in_progress: ClearInProgressResult | Nonecan_clear: bool@dataclass(frozen=True)class MemoryMaintenanceRuntimePort:- """Capability-shaped access to lifecycle state retained by MemoryRuntime."""-exclusive_fence: Callable[[], AsyncContextManager[None]]boot_recovery_fence: Callable[[], AsyncContextManager[None]]state: Callable[[], MaintenanceRuntimeState]@@ -92,7 +87,7 @@ class MemoryMaintenanceRuntimePort:class MemoryMaintenance:- """Own the complete durable maintenance state machine for one Memory store."""+ """Own one durable Clear marker and its fenced deletion sweep."""def __init__(self,@@ -103,208 +98,210 @@ class MemoryMaintenance:) -> None:self._store = storeself._runtime = runtime- self._backup_active = False- self._backup_restore_journal: MemoryBackupRestoreJournal | None = None- self._clear_journal: MemoryClearJournal | None = None- self._snapshot_manager: MemorySnapshotManager | None = None- self._clear_snapshot_storage: MemoryClearSnapshotStorage | None = None- self._backup_manager: MemorySnapshotManager | None = None+ self._intent = ClearIntentStore(effective_home)self._initialization_error: Exception | None = None- self._terminal_snapshot_gc_task: asyncio.Task[None] | None = None- self._backup_stage_reconcile_task: asyncio.Task[None] | None = None+ self._intent_error: Exception | None = None+ self._legacy_migration_deferred = Falseself._closing = Falsetry:- self._backup_restore_journal = MemoryBackupRestoreJournal(effective_home)- self._clear_journal = MemoryClearJournal(effective_home)- self._snapshot_manager = MemorySnapshotManager(effective_home)- self._clear_snapshot_storage = MemoryClearSnapshotStorage(- self._clear_journal,- self._snapshot_manager,- )- self._backup_manager = MemorySnapshotManager._for_backup(- effective_home,- operation_guard=self._clear_journal.assert_backup_allowed,- )- self._backup_restore_journal.mark_boot_recovery_needed()- self._clear_journal.mark_boot_recovery_needed()- except Exception as exc:- self._initialization_error = exc- logger.exception(- "Memory maintenance journal initialization failed; maintenance is fenced"- )+ required_no_follow_flag()+ except ConfinedFilesystemError as error:+ self._initialization_error = error+ logger.warning("Memory Clear persistence is unavailable; keeping Memory fenced")+ return+ self._migrate_legacy(store)@propertydef ready(self) -> bool:- return (- self._store is not None- and self._backup_restore_journal is not None- and self._clear_journal is not None- and self._snapshot_manager is not None- and self._clear_snapshot_storage is not None- and self._backup_manager is not None- and self._initialization_error is None- )+ return self._store is not None and self._initialization_error is Nonedef attach_store(self, store: MemoryStore) -> None:- """Attach the store after a transient boot-time open failure recovers."""-self._store = store+ self._migrate_legacy(store)- def is_open(self) -> bool:- """Fail closed unless every durable authority proves terminal."""+ def _migrate_legacy(self, store: MemoryStore | None, *, lease_held: bool = False) -> None:+ if self._intent_error is not None:+ return+ legacy_paths = (+ self._intent.home / "state/memory/clear-journal.sqlite",+ self._intent.home / "state/memory/clear-snapshots",+ self._intent.home / "state/memory/backup-restore-journal.sqlite",+ self._intent.home / "state/memory/backups",+ )+ if not any(os.path.lexists(path) for path in legacy_paths):+ self._legacy_migration_deferred = False+ return+ if store is None and os.path.lexists(+ self._intent.home / "state/memory/clear-journal.sqlite"+ ):+ self._legacy_migration_deferred = True+ return+ lease = None+ if not lease_held:+ lease = MemoryOperationLease(self._intent.home)+ try:+ lease.acquire()+ except MemoryOperationBusy:+ self._legacy_migration_deferred = True+ logger.warning(+ "Legacy Memory cleanup deferred while another operation owns the lease"+ )+ return+ except Exception:+ self._initialization_error = ClearIntentError(+ "Legacy Memory cleanup lease could not be acquired"+ )+ logger.warning("Legacy Memory cleanup lease could not be acquired", exc_info=True)+ return+ try:+ if store is not None:+ current_epoch = store.ensure_meta().epoch+ self._intent.reconcile_legacy(current_epoch=current_epoch)+ failures = cleanup_legacy_backup_storage(self._intent.home)+ if failures:+ for relative in failures:+ logger.warning("Legacy Memory cleanup could not remove %s", relative)+ self._legacy_migration_deferred = False+ except ClearIntentUnreadable as error:+ self._legacy_migration_deferred = False+ self._intent_error = error+ logger.warning("Memory Clear state is unreadable; keeping Memory fenced")+ except ClearIntentError as error:+ self._legacy_migration_deferred = False+ self._intent_error = error+ logger.warning("Memory Clear state could not be persisted; keeping Memory fenced")+ except Exception as error:+ self._legacy_migration_deferred = True+ logger.exception("Legacy Memory state reconciliation failed")+ finally:+ if lease is not None:+ try:+ lease.release()+ except Exception:+ self._legacy_migration_deferred = True+ self._initialization_error = ClearIntentError(+ "Legacy Memory cleanup lease could not be released"+ )+ logger.warning(+ "Legacy Memory cleanup lease could not be released",+ exc_info=True,+ )- if self._backup_active:- return True- restore_journal = self._backup_restore_journal- if restore_journal is None:+ def is_open(self) -> bool:+ if (+ self._initialization_error is not None+ or self._intent_error is not None+ or self._legacy_migration_deferred+ ):return True- try:- if restore_journal.get_open_operation() is not None:+ if self._store is not None:+ try:+ if self._store.clear_in_progress():+ return True+ except Exception:+ logger.warning(+ "Memory Clear fence state could not be read; keeping Memory fenced",+ exc_info=True,+ )return True- except Exception:- return True- journal = self._clear_journal- if journal is None or self._initialization_error is not None:- return Truetry:- return journal.get_open_operation() is not None- except Exception:+ return self._intent.load() is not None+ except ClearIntentUnreadable:+ self._intent_error = ClearIntentUnreadable("Memory clear intent marker is unreadable")return Truedef can_disable_without_authority(self) -> bool:- restore_journal = self._backup_restore_journal- clear_journal = self._clear_journal+ # A pure disable is still safe when a marker cannot be read. Enabled+ # Memory remains fenced until the marker is repaired or re-run.+ return (+ self._initialization_error is not None+ or self._intent_error is not None+ or self._legacy_migration_deferred+ )++ def has_readable_intent(self) -> bool:+ """Return whether boot can safely replay a readable Clear marker."""+if (- restore_journal is None- or clear_journal is None+ self._store is Noneor self._initialization_error is not None+ or self._intent_error is not None):+ return False+ if self._legacy_migration_deferred:return Truetry:- restore_journal.get_open_operation()- clear_journal.get_open_operation()- except Exception:- return True- return False+ return self._intent.load() is not None+ except ClearIntentUnreadable:+ self._intent_error = ClearIntentUnreadable("Memory clear intent marker is unreadable")+ return False- def has_open_restore(self) -> bool:- return self._open_backup_restore_operation() is not None+ def recovery(self, *, operator_ref: str | None = None) -> ClearInProgressResult | None:+ return self._read_projection()- def recovery(self, *, operator_ref: str | None = None) -> ClearRecoveryResult | None:- journal = self._clear_journal- if journal is None:- return None+ def _read_projection(self) -> ClearInProgressResult | None:try:- observation = journal.observe_open_operation(- operator_ref=(- None if self._initialization_error is not None else operator_ref- )+ intent = self._intent.load()+ except ClearIntentUnreadable:+ self._intent_error = ClearIntentUnreadable("Memory clear intent marker is unreadable")+ return ClearInProgressResult(+ state="failed",+ operation_id="unreadable",+ occurred_at="",+ error_code="memory_clear_marker_unreadable",)- except Exception:- return None- if observation.operation is None:- return None- return self._clear_recovery(- observation.operation,- can_resume=observation.can_resume,- can_abort=observation.can_abort,- )-- @staticmethod- def _clear_recovery(- operation: ClearOperation,- *,- can_resume: bool,- can_abort: bool,- ) -> ClearRecoveryResult:- return ClearRecoveryResult(- state=operation.state,- operation_id=operation.operation_id,- occurred_at=operation.updated_at,- error_code=operation.closed_error,- can_resume=can_resume,- can_abort=can_abort,- )-- async def observe(- self,- *,- operator_ref: str | None = None,- ) -> MaintenanceObservation:- """Read both maintenance journals without blocking the controller loop."""-- return await self._run_maintenance_io(- lambda: self._observe(operator_ref=operator_ref)- )-- def _observe(- self,- *,- operator_ref: str | None,- ) -> MaintenanceObservation:- backup_active = self._backup_active- restore_operation: BackupRestoreOperation | None = None- clear_operation: ClearOperation | None = None- clear_can_resume = False- clear_can_abort = False- initialization_unavailable = self._initialization_error is not None-- restore_journal = self._backup_restore_journal- restore_unavailable = restore_journal is None or initialization_unavailable- if not restore_unavailable:- assert restore_journal is not None- try:- restore_operation = restore_journal.get_open_operation()- except Exception:- restore_unavailable = True-- clear_journal = self._clear_journal- clear_unavailable = clear_journal is None- if not clear_unavailable:- assert clear_journal is not None- try:- clear_observation = clear_journal.observe_open_operation(- operator_ref=(- None if initialization_unavailable else operator_ref+ if intent is None:+ if self._intent_error is None:+ if self._store is None:+ return None+ try:+ orphaned_fence = self._store.clear_in_progress()+ except Exception:+ logger.warning(+ "Memory Clear fence state could not be read; exposing retry",+ exc_info=True,)- )- clear_operation = clear_observation.operation- clear_can_resume = clear_observation.can_resume- clear_can_abort = clear_observation.can_abort- except Exception:- clear_unavailable = True-- recovery = (- None- if clear_operation is None- else self._clear_recovery(- clear_operation,- can_resume=clear_can_resume,- can_abort=clear_can_abort,+ orphaned_fence = True+ if orphaned_fence:+ return ClearInProgressResult(+ state="failed",+ operation_id="orphaned-fence",+ occurred_at="",+ error_code="memory_clear_failed",+ )+ return None+ return ClearInProgressResult(+ state="failed",+ operation_id="unreadable",+ occurred_at="",+ error_code="memory_clear_marker_unreadable",)- )- if backup_active:- block_reason = "busy"- elif restore_unavailable:- block_reason = "memory_store_unavailable"- elif restore_operation is not None:- block_reason = "busy"- elif clear_unavailable:- block_reason = "memory_store_unavailable"- elif clear_operation is None:+ return _projection(intent)++ async def observe(self, *, operator_ref: str | None = None) -> MaintenanceObservation:+ return await self._run_maintenance_io(self._observe)++ def _observe(self) -> MaintenanceObservation:+ clear_in_progress = self._read_projection()+ if self._initialization_error is not None or self._intent_error is not None:+ block_reason = "memory_clear_failed"+ elif self._legacy_migration_deferred:+ block_reason = "memory_operation_in_progress"+ elif clear_in_progress is None:block_reason = None- elif clear_operation.state == "recovery_needed":- block_reason = clear_operation.closed_error or "memory_clear_failed"+ elif clear_in_progress.state == "failed":+ block_reason = clear_in_progress.error_code or "memory_clear_failed"else:block_reason = "busy"+ can_clear = self.ready and (+ block_reason is None+ or self._intent_error is not None+ or (clear_in_progress is not None and clear_in_progress.state == "failed")+ )return MaintenanceObservation(block_reason=block_reason,- clear_recovery=recovery,- can_clear=(- self.ready- and block_reason is None- and recovery is None- ),+ clear_in_progress=clear_in_progress,+ can_clear=can_clear,)async def maintenance_payload(@@ -313,729 +310,305 @@ class MemoryMaintenance:operator_ref: str | None = None,observation: MaintenanceObservation | None = None,) -> MaintenanceResult:- if observation is None:- observation = await self.observe(operator_ref=operator_ref)+ observation = observation or await self.observe(operator_ref=operator_ref)+ if self._store is None:+ return MaintenanceResult(True, False, observation.clear_in_progress, "memory_store_unavailable")try:meta, history = await asyncio.gather(asyncio.to_thread(self._store.get_meta),asyncio.to_thread(self._store.has_provider_data_history),)except Exception:- return MaintenanceResult(- data_exists=True,- can_clear=False,- clear_recovery=observation.clear_recovery,- error="memory_store_unavailable",- )- try:- latest = await self.observe(operator_ref=operator_ref)- except Exception:- return MaintenanceResult(- data_exists=bool(history or (meta is not None and meta.last_success_at)),- can_clear=False,- clear_recovery=None,- error="memory_store_unavailable",- )- changed = latest != observation+ return MaintenanceResult(True, False, observation.clear_in_progress, "memory_store_unavailable")+ latest = await self.observe(operator_ref=operator_ref)return MaintenanceResult(data_exists=bool(history or (meta is not None and meta.last_success_at)),- can_clear=not changed and latest.can_clear,- clear_recovery=latest.clear_recovery,- error=(- "memory_store_unavailable"- if latest.block_reason == "memory_store_unavailable"- else None- ),+ can_clear=latest.can_clear,+ clear_in_progress=latest.clear_in_progress,+ error="memory_clear_failed" if latest.block_reason == "memory_clear_failed" else None,)- async def create_backup(self, backup_id: str | None = None) -> MemorySnapshot:- return await self._run_backup_operation(lambda manager: manager.create(backup_id))-- async def restore_backup(- self,- backup_id: str,- *,- expected_manifest_sha256: str,- expected_surface_digests: Mapping[str, str | None],- ) -> MemorySnapshot:- clear_journal = self._require_clear_journal()- restore_journal = self._require_backup_restore_journal()- manager = self._require_backup_manager()- async with self._runtime.exclusive_fence():- clear_journal.assert_backup_allowed()- operation = restore_journal.get_open_operation()- if operation is not None and (- operation.state != "recovery_needed"- or operation.backup_id != backup_id- or operation.manifest_sha256 != expected_manifest_sha256- or operation.digest_mapping() != dict(expected_surface_digests)- ):- raise BackupRestoreConflict(- "a different Memory backup restore owns the recovery fence"- )- self._backup_active = True- self._runtime.enter_maintenance()- try:- await self._runtime.quiesce(False)- if operation is not None:- operation = await self._run_maintenance_io(- lambda: restore_journal.claim_retry(- operation.operation_id,- expected_revision=operation.revision,- actor_ref="system:runtime",- )- )+ async def clear(self, *, operator_ref: str) -> ClearResult:+ return await self._run_clear(operator_ref=operator_ref, boot=False)- def begin_restore(snapshot: MemorySnapshot) -> None:- nonlocal operation- operation = restore_journal.start(snapshot)+ async def reconcile_pending(self, *, lease_held: bool = False) -> bool:+ """Finish a marker-owned Clear during boot/reconcile."""- restored = await self._run_maintenance_io(- lambda: manager.restore(- backup_id,- expected_manifest_sha256=expected_manifest_sha256,- expected_surface_digests=expected_surface_digests,- before_replace=None if operation is not None else begin_restore,- )- )- if operation is None:- raise RuntimeError("Memory backup restore intent was not recorded")- operation = await self._run_maintenance_io(- lambda: restore_journal.mark_completed(- operation.operation_id,- expected_revision=operation.revision,- execution_token=self._backup_restore_execution_token(operation),- )+ if self._store is None:+ return False+ if self._legacy_migration_deferred:+ await self._run_maintenance_io(+ lambda: self._migrate_legacy(self._store, lease_held=lease_held)+ )+ if (+ self._initialization_error is not None+ or self._intent_error is not None+ or self._legacy_migration_deferred+ ):+ return False+ try:+ intent = await self._run_maintenance_io(self._intent.load)+ except ClearIntentUnreadable:+ self._intent_error = ClearIntentUnreadable("Memory clear intent marker is unreadable")+ return False+ if intent is None:+ return True+ if intent.state == "failed" and intent.error_code == LEGACY_RERUN_ERROR_CODE:+ # Legacy semantics are deliberately not interpreted. Only a new+ # user Clear may replace this fail-closed authority.+ return False+ if intent.state == "failed":+ intent = intent.deleting()+ try:+ await self._run_maintenance_io(lambda: self._intent.write(intent))+ except ClearIntentError:+ self._intent_error = ClearIntentError(+ "Memory Clear retry marker could not be written")- self._runtime.restore_completed()- return restored- except BaseException:- await self._mark_backup_restore_recovery(operation)- raise- finally:- self._backup_active = False- try:- if restore_journal.get_open_operation() is None:- await self._runtime.resume()- finally:- self._runtime.leave_maintenance()-- async def _run_backup_operation(- self,- operation: Callable[[MemorySnapshotManager], MemorySnapshot],- ) -> MemorySnapshot:- journal = self._require_clear_journal()- restore_journal = self._require_backup_restore_journal()- manager = self._require_backup_manager()- async with self._runtime.exclusive_fence():- journal.assert_backup_allowed()- restore_journal.assert_idle()- self._backup_active = True+ return False+ async with self._runtime.boot_recovery_fence():self._runtime.enter_maintenance()try:+ await self._run_maintenance_io(self._store.begin_clear_fence)await self._runtime.quiesce(False)- return await self._run_maintenance_io(lambda: operation(manager))+ result = await self._run_clear_intent(intent, operator_ref=intent.operator_ref, boot=True)+ return result.status == "completed"+ except asyncio.CancelledError:+ await self._record_failure(intent, "memory_clear_failed")+ raise+ except Exception:+ await self._record_failure(intent, "memory_clear_failed")+ return Falsefinally:- self._backup_active = False- try:- await self._runtime.resume()- finally:- self._runtime.leave_maintenance()+ self._runtime.leave_maintenance()- async def clear(self, *, operator_ref: str) -> ClearResult:- journal = self._require_clear_journal()+ async def _run_clear(self, *, operator_ref: str, boot: bool) -> ClearResult:+ if self._store is None:+ raise MemoryStoreUnavailableError("Memory store is unavailable")+ await self._run_maintenance_io(+ lambda: self._migrate_legacy(self._store, lease_held=True)+ )+ if self._legacy_migration_deferred:+ return ClearResult(status="failed", error="memory_operation_in_progress")async with self._runtime.exclusive_fence():- if journal.get_open_operation() is not None:- return self._blocked(operator_ref=operator_ref)- operation: ClearOperation | None = Noneself._runtime.enter_maintenance()try:try:- await self._runtime.pause_claims()- except BaseException as error:- self._runtime.leave_maintenance()- self._runtime.resume_claims()- if isinstance(error, asyncio.CancelledError):- raise- return self._blocked(operator_ref=operator_ref)- try:+ intent = await self._run_maintenance_io(self._intent.load)+ except ClearIntentUnreadable:+ # A user initiated re-run is explicitly allowed to replace+ # an unreadable marker with a fresh operation.+ intent = None+ if intent is None:meta = await self._run_maintenance_io(self._store.ensure_meta)- operation = await self._run_maintenance_io(- lambda: journal.start(- operator_ref=operator_ref,- pre_epoch=meta.epoch,- target_epoch=meta.epoch + 1,- )- )- await self._run_maintenance_io(self._store.begin_clear_fence)- operation = await self._prepare_clear(- operation,- claims_already_paused=True,- )- operation = await self._delete_clear_surfaces(operation)- except BaseException as error:- current = await self._mark_clear_recovery(operation)- if current is not None and current.state == "completed":- self._runtime.leave_maintenance()- await self._finish_clear(current)- elif current is None:- self._runtime.leave_maintenance()- self._runtime.resume_claims()- if isinstance(error, asyncio.CancelledError):- raise- return self._blocked(operator_ref=operator_ref)+ intent = ClearIntent.new(operator_ref=operator_ref, pre_epoch=meta.epoch)+ write_intent = True+ elif intent.state == "failed":+ meta = await self._run_maintenance_io(self._store.ensure_meta)+ if (+ intent.error_code == LEGACY_RERUN_ERROR_CODE+ or meta.epoch not in {intent.pre_epoch, intent.target_epoch}+ ):+ intent = ClearIntent.new(operator_ref=operator_ref, pre_epoch=meta.epoch)+ else:+ intent = intent.deleting()+ write_intent = True+ else:+ write_intent = False+ try:+ await self._settle_prepare_clear(intent, write_intent=write_intent)+ except asyncio.CancelledError:+ await self._record_failure(intent, "memory_clear_failed")+ raise+ except Exception:+ await self._record_failure(intent, "memory_clear_failed")+ return ClearResult(status="failed", error="memory_clear_failed")+ assert intent is not None+ return await self._run_clear_intent(intent, operator_ref=operator_ref, boot=boot)finally:self._runtime.leave_maintenance()- if operation is None:- raise RuntimeError("Memory clear operation did not start")- return await self._finish_clear(operation)- async def resume_clear(- self,- operation_id: str,- *,- operator_ref: str,- ) -> ClearResult:- journal = self._require_clear_journal()- async with self._runtime.exclusive_fence():- current = journal.get_open_operation()- if current is None or current.operation_id != operation_id:- return self._blocked(operator_ref=operator_ref)+ async def _settle_prepare_clear(self, intent: ClearIntent, *, write_intent: bool) -> None:+ cancellation: asyncio.CancelledError | None = None+ write_error: Exception | None = None++ async def prepare() -> None:+ nonlocal cancellation, write_error+ assert self._store is not None+ if write_intent:+ try:+ await self._run_maintenance_io(lambda: self._intent.write(intent))+ except asyncio.CancelledError as error:+ # The blocking write has settled durably; finish the+ # safety fence before propagating the caller cancellation.+ cancellation = error+ except Exception as error:+ # The marker may have been renamed before its directory+ # fsync failed. Continue fencing claims before reporting+ # the write failure to the clear coordinator.+ write_error = error+ else:+ self._intent_error = None+ await self._runtime.pause_claims()+ await self._run_maintenance_io(self._store.begin_clear_fence)+ await self._runtime.quiesce(False)+ await self._run_maintenance_io(+ lambda: self._migrate_legacy(self._store, lease_held=True)+ )+ if write_error is not None:+ raise write_error+ if cancellation is not None:+ raise cancellation+ if self._legacy_migration_deferred:+ raise ClearIntentError("Legacy Memory cleanup remains deferred")++ task = asyncio.create_task(prepare())+ outer_cancellation: asyncio.CancelledError | None = None+ while not task.done():try:- operation = await self._run_maintenance_io(- lambda: journal.claim_resume(- operation_id,- operator_ref=operator_ref,- expected_revision=current.revision,- )- )- await self._run_maintenance_io(self._store.begin_clear_fence)- operation = await self._prepare_clear(operation)- operation = await self._delete_clear_surfaces(operation)- except BaseException as error:- recovered = await self._mark_clear_recovery(operation_id=operation_id)- if recovered is not None and recovered.state == "completed":- await self._finish_clear(recovered)- if isinstance(error, asyncio.CancelledError):- raise- return self._blocked(operator_ref=operator_ref)- return await self._finish_clear(operation)+ await asyncio.shield(task)+ except asyncio.CancelledError as error:+ outer_cancellation = outer_cancellation or error+ except Exception:+ break+ if outer_cancellation is not None:+ try:+ task.result()+ except (Exception, asyncio.CancelledError):+ pass+ raise outer_cancellation+ task.result()- async def abort_clear(+ async def _run_clear_intent(self,- operation_id: str,+ intent: ClearIntent,*,operator_ref: str,+ boot: bool,) -> ClearResult:- journal = self._require_clear_journal()- manager = self._require_snapshot_manager()- async with self._runtime.exclusive_fence():- current = journal.get_open_operation()- if current is None or current.operation_id != operation_id:- return self._blocked(operator_ref=operator_ref)- try:- operation = await self._run_maintenance_io(- lambda: journal.claim_abort(- operation_id,- operator_ref=operator_ref,- expected_revision=current.revision,- )- )- await self._runtime.quiesce(False)- digests = self._journal_surface_digests(operation.operation_id)- if operation.manifest_sha256 is None or operation.snapshot_path is None:- raise RuntimeError("clear snapshot is not sealed")- await self._run_maintenance_io(- lambda: manager.restore(- operation.operation_id,- expected_manifest_sha256=operation.manifest_sha256,- expected_surface_digests=digests,- )- )- await self._run_maintenance_io(self._store.release_clear_fence)- for surface in journal.get_surfaces(operation.operation_id):- if surface.state == "restored":- continue- operation = await self._run_maintenance_io(- lambda: journal.record_surface_restored(- operation.operation_id,- surface.surface,- expected_revision=operation.revision,- execution_token=self._clear_execution_token(operation),- )- )- operation = await self._run_maintenance_io(- lambda: journal.mark_aborted(- operation.operation_id,- expected_revision=operation.revision,- execution_token=self._clear_execution_token(operation),- )- )- except BaseException as error:- recovered = await self._mark_clear_recovery(operation_id=operation_id)- if recovered is not None and recovered.state == "aborted":- await self._finish_aborted_clear(recovered)- if isinstance(error, asyncio.CancelledError):- raise- return self._blocked(operator_ref=operator_ref)- return await self._finish_aborted_clear(operation)-- async def _prepare_clear(- self,- operation: ClearOperation,- *,- claims_already_paused: bool = False,- ) -> ClearOperation:- journal = self._require_clear_journal()- manager = self._require_snapshot_manager()- snapshot_storage = self._require_clear_snapshot_storage()- await self._runtime.quiesce(claims_already_paused)- if operation.state == "preparing":- if operation.snapshot_path is None or operation.manifest_sha256 is None:- if operation.resolution == "resume":- operation = await self._run_maintenance_io(- lambda: snapshot_storage.discard_unrecorded_preparing_snapshot(- operation.operation_id,- expected_revision=operation.revision,- execution_token=self._clear_execution_token(operation),- )- )- snapshot = await self._run_maintenance_io(- lambda: manager.create(operation.operation_id)- )- operation = await self._run_maintenance_io(- lambda: journal.record_snapshot(- operation.operation_id,- expected_revision=operation.revision,- execution_token=self._clear_execution_token(operation),- snapshot=snapshot,- )- )- else:- await self._verify_clear_snapshot(operation)- operation = await self._run_maintenance_io(- lambda: journal.mark_prepared(- operation.operation_id,- expected_revision=operation.revision,- execution_token=self._clear_execution_token(operation),- )- )- if operation.state == "prepared":- await self._verify_clear_snapshot(operation)- return operation+ assert self._store is not None+ try:+ for surface in DEFAULT_CLEAR_SURFACES:+ await self._runtime.delete_surface(surface, intent.target_epoch)+ final_cancellation: asyncio.CancelledError | None = None+ release_outcome: dict[str, BaseException] = {}- async def _delete_clear_surfaces(self, operation: ClearOperation) -> ClearOperation:- journal = self._require_clear_journal()- if operation.state == "prepared":- operation = await self._run_maintenance_io(- lambda: journal.begin_deleting(- operation.operation_id,- expected_revision=operation.revision,- execution_token=self._clear_execution_token(operation),- )- )- if operation.state != "deleting":- raise RuntimeError("clear operation is not ready for deletion")- await self._verify_clear_snapshot(operation)- for surface in journal.get_surfaces(operation.operation_id):- if surface.state == "deleted":- continue- await self._runtime.delete_surface(surface, operation.target_epoch)- operation = await self._run_maintenance_io(- lambda: journal.record_surface_deleted(- operation.operation_id,- surface.surface,- expected_revision=operation.revision,- execution_token=self._clear_execution_token(operation),- )- )- return await self._run_maintenance_io(- lambda: journal.mark_completed(- operation.operation_id,- expected_revision=operation.revision,- execution_token=self._clear_execution_token(operation),- )- )+ def release_fence() -> None:+ try:+ self._store.release_clear_fence()+ except BaseException as error:+ release_outcome["error"] = error+ raise- async def _verify_clear_snapshot(self, operation: ClearOperation) -> MemorySnapshot:- if operation.manifest_sha256 is None or operation.snapshot_path is None:- raise RuntimeError("clear snapshot is not sealed")- return await self._run_maintenance_io(- lambda: self._require_snapshot_manager().verify(- operation.operation_id,- expected_manifest_sha256=operation.manifest_sha256,- expected_surface_digests=self._journal_surface_digests(- operation.operation_id- ),- )- )+ try:+ await self._run_maintenance_io(release_fence)+ except asyncio.CancelledError as error:+ if "error" in release_outcome:+ if not await self._settle_clear_fence_release(intent):+ return self._failed_result()+ else:+ final_cancellation = error+ except Exception:+ if not await self._settle_clear_fence_release(intent):+ return self._failed_result()+ try:+ remove_outcome: dict[str, BaseException] = {}- async def recover_boot(self) -> bool:- """Converge an interrupted ordinary restore before activation."""+ def remove_marker() -> None:+ try:+ self._intent.remove()+ except BaseException as error:+ remove_outcome["error"] = error+ raise- journal = self._require_backup_restore_journal()- operation = journal.get_open_operation()- if operation is None:- return True- if operation.state != "recovery_needed":- return False- manager = self._require_backup_manager()- self._backup_active = True- self._runtime.enter_maintenance()- try:- async with self._runtime.boot_recovery_fence():- await self._runtime.quiesce(False)- operation = await self._run_maintenance_io(- lambda: journal.claim_retry(- operation.operation_id,- expected_revision=operation.revision,- actor_ref="system:boot",- )- )- await self._run_maintenance_io(- lambda: manager.restore(- operation.backup_id,- expected_manifest_sha256=operation.manifest_sha256,- expected_surface_digests=operation.digest_mapping(),+ await self._run_maintenance_io(remove_marker)+ except asyncio.CancelledError as error:+ if "error" in remove_outcome:+ raise remove_outcome["error"]+ final_cancellation = final_cancellation or error+ except ClearIntentError:+ # All surfaces are already terminal. Keep the deleting marker+ # so the next reconcile retries only its removal. The marker+ # may already be unlinked when its parent fsync fails, so+ # rewrite a failed projection instead of treating that as done.+ logger.warning("Memory Clear completed but intent removal failed", exc_info=True)+ try:+ await self._run_maintenance_io(+ lambda: self._intent.write(intent.failed("memory_clear_failed")))- )- await self._run_maintenance_io(- lambda: journal.mark_completed(- operation.operation_id,- expected_revision=operation.revision,- execution_token=self._backup_restore_execution_token(operation),- actor_ref="system:boot",+ except ClearIntentError:+ logger.exception("Memory Clear recovery marker could not be retained")+ self._intent_error = ClearIntentError(+ "Memory Clear recovery marker could not be retained")+ return ClearResult(+ status="failed",+ error="memory_clear_failed",+ clear_in_progress=self._read_projection() or _projection(intent.failed("memory_clear_failed")),)- self._runtime.restore_completed()- return Trueexcept asyncio.CancelledError:- await self._mark_backup_restore_recovery(operation)+ await self._record_failure(intent, "memory_clear_failed")raise- except Exception:- await self._mark_backup_restore_recovery(operation)- return False- finally:- self._backup_active = False- self._runtime.leave_maintenance()+ except Exception as error:+ error_code = getattr(error, "error", None) or "memory_clear_failed"+ await self._record_failure(intent, str(error_code))+ return self._failed_result()+ self._runtime.restore_completed()+ if not boot:+ await self._runtime.resume()+ self._intent_error = None+ if final_cancellation is not None:+ logger.info("Memory Clear reached terminal state after final-stage cancellation")+ return ClearResult("completed", intent.operation_id, intent.target_epoch)- async def _mark_backup_restore_recovery(- self,- operation: BackupRestoreOperation | None,- ) -> BackupRestoreOperation | None:- journal = self._backup_restore_journal- if journal is None or operation is None:- return None+ async def _settle_clear_fence_release(self, intent: ClearIntent) -> bool:+ """Keep replay authority only when the shared queue fence is still held."""++ assert self._store is not Nonetry:- current = journal.get_operation(operation.operation_id)- if current is None or current.state != "restoring":- return current- return await self._run_maintenance_io(- lambda: journal.mark_recovery_needed(- current.operation_id,- expected_revision=current.revision,- execution_token=self._backup_restore_execution_token(current),- )- )+ fence_open = await self._run_maintenance_io(self._store.clear_in_progress)except Exception:- logger.exception("Memory backup restore failure could not be journaled")- return None-- async def _mark_clear_recovery(- self,- operation: ClearOperation | None = None,- *,- operation_id: str | None = None,- ) -> ClearOperation | None:- journal = self._clear_journal- if journal is None:- return None-- def mark_recovery() -> ClearOperation | None:- identifier = operation.operation_id if operation is not None else operation_id- current = (- journal.get_open_operation()- if identifier is None- else journal.get_operation(identifier)+ self._intent_error = ClearIntentError(+ "Memory Clear fence release could not be determined")- if current is None:- return None- if current.state in {"preparing", "prepared", "deleting"}:- return journal.mark_recovery_needed(- current.operation_id,- expected_revision=current.revision,- execution_token=self._clear_execution_token(current),- )- if current.state == "recovery_needed" and current.execution_token is not None:- return journal.release_recovery_claim(- current.operation_id,- expected_revision=current.revision,- execution_token=self._clear_execution_token(current),- )- return current+ return False+ if not fence_open:+ return True+ await self._record_failure(intent, "memory_clear_failed")+ return False+ async def _record_failure(self, intent: ClearIntent, error_code: str) -> None:try:- return await self._run_maintenance_io(mark_recovery)+ await self._run_maintenance_io(lambda: self._intent.write(intent.failed(error_code)))except Exception:- logger.exception("Memory clear failure could not be journaled")- return None-- async def _finish_clear(self, operation: ClearOperation) -> ClearResult:- await self._finalize_terminal_clear()- return ClearResult(- status="completed",- operation_id=operation.operation_id,- epoch=operation.target_epoch,- )-- async def _finish_aborted_clear(self, operation: ClearOperation) -> ClearResult:- await self._finalize_terminal_clear()- return ClearResult(- status="aborted",- operation_id=operation.operation_id,- epoch=operation.pre_epoch,- )-- async def _finalize_terminal_clear(self) -> None:- try:- await self._run_maintenance_io(self._reconcile_terminal_clear_snapshots)- finally:- await self._runtime.resume()+ logger.exception("Memory Clear failure could not be persisted")+ self._intent_error = ClearIntentError("Memory Clear failure could not be persisted")- def _blocked(self, *, operator_ref: str | None = None) -> ClearResult:+ def _failed_result(self) -> ClearResult:return ClearResult(status="failed",error="memory_clear_failed",- recovery=self.recovery(operator_ref=operator_ref),+ clear_in_progress=self._read_projection(),)- def _reconcile_terminal_clear_snapshots(self) -> None:- storage = self._require_clear_snapshot_storage()- for operation_id in storage.eligible_terminal_snapshot_ids():- try:- storage.remove_terminal_snapshot(operation_id)- except Exception:- logger.warning(- "Terminal Memory clear snapshot %s could not be removed",- operation_id,- exc_info=True,- )+ async def recover_boot(self, *, lease_held: bool = False) -> bool:+ return await self.reconcile_pending(lease_held=lease_held)def ensure_housekeeping(self) -> None:- """Schedule terminal GC before backup-stage reconciliation."""-- self._ensure_terminal_snapshot_gc()- self._ensure_backup_stage_reconcile()-- def _ensure_terminal_snapshot_gc(self) -> None:- task = self._terminal_snapshot_gc_task- state = self._runtime.state()- if (- self._closing- or state.artifact_installing- or self._clear_snapshot_storage is None- or self._initialization_error is not None- or (task is not None and not task.done())- ):- return- task = asyncio.create_task(- self._run_terminal_snapshot_gc(),- name="memory-terminal-snapshot-gc",- )- self._terminal_snapshot_gc_task = task-- def clear_gc(completed: asyncio.Task[None]) -> None:- if self._terminal_snapshot_gc_task is completed:- self._terminal_snapshot_gc_task = None-- task.add_done_callback(clear_gc)-- def _ensure_backup_stage_reconcile(self) -> None:- task = self._backup_stage_reconcile_task- state = self._runtime.state()- if (- self._closing- or state.artifact_installing- or self._store is None- or self._backup_manager is None- or self._clear_journal is None- or self._backup_restore_journal is None- or self._initialization_error is not None- or (task is not None and not task.done())- ):- return- task = asyncio.create_task(- self._run_backup_stage_reconcile(),- name="memory-backup-stage-reconcile",- )- self._backup_stage_reconcile_task = task-- def clear_reconcile(completed: asyncio.Task[None]) -> None:- if self._backup_stage_reconcile_task is completed:- self._backup_stage_reconcile_task = None-- task.add_done_callback(clear_reconcile)-- async def _run_backup_stage_reconcile(self) -> None:- terminal_gc = self._terminal_snapshot_gc_task- if terminal_gc is not None and terminal_gc is not asyncio.current_task():- await asyncio.shield(terminal_gc)- journal = self._require_clear_journal()- restore_journal = self._require_backup_restore_journal()- manager = self._require_backup_manager()- try:- async with self._runtime.exclusive_fence():- if self._runtime.state().artifact_installing:- return- journal.assert_backup_allowed()- restore_journal.assert_idle()- await self._run_maintenance_io(- manager.reconcile_unpublished_backup_stages- )- except asyncio.CancelledError:- raise- except Exception:- logger.warning(- "Unpublished Memory backup stages could not be reconciled",- exc_info=True,- )-- async def _run_terminal_snapshot_gc(self) -> None:- storage = self._require_clear_snapshot_storage()- try:- operation_ids = await self._run_maintenance_io(- storage.eligible_terminal_snapshot_ids- )- except asyncio.CancelledError:- raise- except Exception:- logger.warning(- "Terminal Memory clear snapshots could not be enumerated",- exc_info=True,- )- return- for operation_id in operation_ids:- try:- await self._run_maintenance_io(- lambda operation_id=operation_id: storage.remove_terminal_snapshot(- operation_id- )- )- except asyncio.CancelledError:- raise- except Exception:- logger.warning(- "Terminal Memory clear snapshot %s could not be removed",- operation_id,- exc_info=True,- )+ return Noneasync def close(self) -> None:self._closing = True- caller_cancellation: asyncio.CancelledError | None = None- for attribute in (- "_backup_stage_reconcile_task",- "_terminal_snapshot_gc_task",- ):- try:- await self._stop_task(attribute)- except asyncio.CancelledError as error:- caller_cancellation = caller_cancellation or error- if caller_cancellation is not None:- raise caller_cancellation-- async def _stop_task(self, attribute: str) -> None:- task = getattr(self, attribute)- if task is None or task is asyncio.current_task():- return- task.cancel()- settlement = asyncio.gather(task, return_exceptions=True)- caller_cancellation: asyncio.CancelledError | None = None- while not settlement.done():- try:- await asyncio.shield(settlement)- except asyncio.CancelledError as error:- caller_cancellation = caller_cancellation or error- try:- result = settlement.result()[0]- finally:- if getattr(self, attribute) is task:- setattr(self, attribute, None)- if isinstance(result, BaseException) and not isinstance(- result,- asyncio.CancelledError,- ):- raise result- if caller_cancellation is not None:- raise caller_cancellation-- def _open_backup_restore_operation(self) -> BackupRestoreOperation | None:- journal = self._backup_restore_journal- if journal is None:- return None- try:- return journal.get_open_operation()- except Exception:- return None-- def _journal_surface_digests(self, operation_id: str) -> dict[str, str | None]:- journal = self._require_clear_journal()- return {- surface.relative_path: surface.snapshot_digest- for surface in journal.get_surfaces(operation_id)- }-- def _require_clear_journal(self) -> MemoryClearJournal:- if self._clear_journal is None or self._initialization_error is not None:- raise MemoryStoreUnavailableError("Memory clear journal is unavailable")- return self._clear_journal-- def _require_backup_restore_journal(self) -> MemoryBackupRestoreJournal:- if (- self._backup_restore_journal is None- or self._initialization_error is not None- ):- raise MemoryStoreUnavailableError(- "Memory backup restore journal is unavailable"- )- return self._backup_restore_journal-- def _require_snapshot_manager(self) -> MemorySnapshotManager:- if self._snapshot_manager is None or self._initialization_error is not None:- raise MemoryStoreUnavailableError("Memory snapshot manager is unavailable")- return self._snapshot_manager-- def _require_clear_snapshot_storage(self) -> MemoryClearSnapshotStorage:- if (- self._clear_snapshot_storage is None- or self._initialization_error is not None- ):- raise MemoryStoreUnavailableError(- "Memory clear snapshot storage is unavailable"- )- return self._clear_snapshot_storage-- def _require_backup_manager(self) -> MemorySnapshotManager:- if self._backup_manager is None or self._initialization_error is not None:- raise MemoryStoreUnavailableError("Memory backup manager is unavailable")- return self._backup_manager@staticmethod- async def _run_maintenance_io(- operation: Callable[[], _MaintenanceIOResult],- ) -> _MaintenanceIOResult:+ async def _run_maintenance_io(operation: Callable[[], _MaintenanceIOResult]) -> _MaintenanceIOResult:return await run_blocking(operation)- @staticmethod- def _backup_restore_execution_token(- operation: BackupRestoreOperation,- ) -> str:- if operation.execution_token is None:- raise RuntimeError("Memory backup restore execution claim is missing")- return operation.execution_token- @staticmethod- def _clear_execution_token(operation: ClearOperation) -> str:- if operation.execution_token is None:- raise RuntimeError("Memory clear operation is not claimed")- return operation.execution_token+def _projection(intent: ClearIntent) -> ClearInProgressResult:+ return ClearInProgressResult(+ state=intent.state,+ operation_id=intent.operation_id,+ occurred_at=intent.updated_at,+ error_code=intent.error_code,+ )diff --git a/core/memory/processing_record.py b/core/memory/processing_record.pyindex e75e071c4..0a78f1152 100644--- a/core/memory/processing_record.py+++ b/core/memory/processing_record.py@@ -13,7 +13,7 @@ from typing import Any, Literal, TypeVarfrom core.memory.everos import ProviderHealthSnapshotfrom core.memory.confined_filesystem import PRIVATE_SQLITE_BUSY_TIMEOUT_SECONDSfrom core.memory.maintenance import (- ClearRecoveryResult,+ ClearInProgressResult,MaintenanceObservation,MaintenanceResult,)@@ -95,7 +95,7 @@ class MaintenanceProjection:source: SourceObservationdata_exists: boolcan_clear: bool- clear_recovery: ClearRecoveryResult | None+ clear_in_progress: ClearInProgressResult | None@dataclass(frozen=True, slots=True)@@ -374,7 +374,7 @@ class MemoryProcessingRecord:except Exception:return MaintenanceObservation(block_reason="memory_store_unavailable",- clear_recovery=None,+ clear_in_progress=None,can_clear=False,)@@ -495,7 +495,7 @@ class MemoryProcessingRecord:),data_exists=True,can_clear=False,- clear_recovery=None,+ clear_in_progress=None,)unavailable_reason = result.errorif (@@ -512,7 +512,7 @@ class MemoryProcessingRecord:source=source,data_exists=result.data_exists,can_clear=result.can_clear,- clear_recovery=result.clear_recovery,+ clear_in_progress=result.clear_in_progress,)def observe_recorder(diff --git a/core/memory/runtime.py b/core/memory/runtime.pyindex 2061abf1a..d6c3630da 100644--- a/core/memory/runtime.py+++ b/core/memory/runtime.py@@ -34,7 +34,7 @@ from core.memory.artifact import (get_memory_artifact_manager,)from core.memory.blocking import run_blocking-from core.memory.clear_journal import ClearSurface+from core.memory.clear_intent import ClearSurfacefrom core.memory.confined_filesystem import required_no_follow_flagfrom core.memory.everos import (EverOSPort,@@ -46,7 +46,7 @@ from core.memory.everos_insight.recorder import clear_call_log, maintain_call_lofrom core.memory.module import MemoryModule, MemorySessionLifecycleBusyErrorfrom core.memory.operation_lock import MemoryOperationBusy, MemoryOperationLeasefrom core.memory.maintenance import (- ClearRecoveryResult,+ ClearInProgressResult,ClearResult,MaintenanceObservation,MaintenanceResult,@@ -88,7 +88,6 @@ from core.memory.project_ids import (MEMORY_SEARCH_ALL_PROJECTS,)from core.memory.store import MemoryStore, is_principal_id, is_project_id-from core.memory.snapshot import MemorySnapshotfrom core.memory.types import (MemoryFailureLogEntry,MemoryItem,@@ -198,8 +197,8 @@ class _LifecycleGenerationLock:self.release()-def _clear_recovery_payload(- recovery: ClearRecoveryResult | None,+def _clear_in_progress_payload(+ recovery: ClearInProgressResult | None,) -> dict[str, Any] | None:if recovery is None:return None@@ -208,8 +207,6 @@ def _clear_recovery_payload("operation_id": recovery.operation_id,"occurred_at": recovery.occurred_at,"error_code": recovery.error_code,- "can_resume": recovery.can_resume,- "can_abort": recovery.can_abort,}@@ -218,7 +215,7 @@ def _clear_result_payload(result: ClearResult) -> dict[str, Any]:return {"status": "failed","error": result.error,- "recovery": _clear_recovery_payload(result.recovery),+ "clear_in_progress": _clear_in_progress_payload(result.clear_in_progress),}return {"status": result.status,@@ -260,7 +257,7 @@ def _maintenance_projection_payload("source": _source_observation_payload(result.source),"data_exists": result.data_exists,"can_clear": result.can_clear,- "clear_recovery": _clear_recovery_payload(result.clear_recovery),+ "clear_in_progress": _clear_in_progress_payload(result.clear_in_progress),}@@ -910,20 +907,19 @@ class MemoryRuntime:# save cannot race a root wipe or replace sidecar credentials halfway# through an active provider call.async with self.module.lifecycle():- restore_operation_open = (- self._maintenance is not None- and self._maintenance.has_open_restore()- )maintenance_open = self._maintenance_open()if (maintenance_openand self._can_disable_without_maintenance_authority(config)):result = await self._disable_locked(config)- elif restore_operation_open and not recorded_sidecar_reaped:- self.module.pause_claims()- return {"ok": False, "error": "memory_clear_failed"}- elif maintenance_open and not restore_operation_open:+ elif (+ maintenance_open+ and self._maintenance is not None+ and self._maintenance.has_readable_intent()+ ):+ result = await self._reconcile_locked(config)+ elif maintenance_open:self.module.pause_claims()return {"ok": False, "error": "memory_clear_failed"}else:@@ -962,8 +958,18 @@ class MemoryRuntime:) -> dict[str, Any]:"""Reconcile while both controller and module lifecycle locks are held."""- if self._maintenance is not None and self._maintenance.has_open_restore():- recovered = await self._maintenance.recover_boot()+ if self._maintenance is not None and self._maintenance.is_open():+ lease = MemoryOperationLease(self._effective_home)+ try:+ try:+ await run_blocking(lease.acquire)+ except MemoryOperationBusy:+ self.module.pause_claims()+ self._runtime_error = "memory_operation_in_progress"+ return {"ok": False, "error": self._runtime_error}+ recovered = await self._maintenance.recover_boot(lease_held=True)+ finally:+ await run_blocking(lease.release)if not recovered:self.module.pause_claims()self._runtime_error = "memory_clear_failed"@@ -1118,7 +1124,7 @@ class MemoryRuntime:if maintenance is None:return MaintenanceObservation(block_reason="memory_store_unavailable",- clear_recovery=None,+ clear_in_progress=None,can_clear=False,)return await maintenance.observe(operator_ref=operator_ref)@@ -1291,11 +1297,13 @@ class MemoryRuntime:anomalies, maintenance = projectionif anomalies.source.status == "unavailable":raise self._unavailable()- return {+ payload: dict[str, Any] = {"status": "ok","items": [asdict(entry) for entry in anomalies.items],- "recovery": _clear_recovery_payload(maintenance.clear_recovery),}+ if maintenance.clear_in_progress is not None and maintenance.clear_in_progress.state == "failed":+ payload["clear_in_progress"] = _clear_in_progress_payload(maintenance.clear_in_progress)+ return payloadasync def maintenance_payload(self,@@ -1313,7 +1321,7 @@ class MemoryRuntime:"status": "ok","data_exists": result.data_exists,"can_clear": result.can_clear,- "clear_recovery": _clear_recovery_payload(result.clear_recovery),+ "clear_in_progress": _clear_in_progress_payload(result.clear_in_progress),}def principal_for_user_key(self, user_key: str) -> str:@@ -1615,30 +1623,6 @@ class MemoryRuntime:async with self.module.lifecycle():return await run_blocking(operation)- async def create_backup(self, backup_id: str | None = None) -> MemorySnapshot:- """Create one ordinary Memory backup under the full maintenance fence."""-- if not self.available:- raise self._unavailable()- return await self._require_maintenance().create_backup(backup_id)-- async def restore_backup(- self,- backup_id: str,- *,- expected_manifest_sha256: str,- expected_surface_digests: Mapping[str, str | None],- ) -> MemorySnapshot:- """Restore one verified ordinary Memory backup under the same fence."""-- if not self.available:- raise self._unavailable()- return await self._require_maintenance().restore_backup(- backup_id,- expected_manifest_sha256=expected_manifest_sha256,- expected_surface_digests=expected_surface_digests,- )-async def clear(self, *, operator_ref: str) -> dict[str, Any]:if self._retired or getattr(self._restart_config, "recovery_intent", None) == "factory_reset":return {"status": "failed", "error": "memory_operation_in_progress"}@@ -1649,42 +1633,6 @@ class MemoryRuntime:lambda: maintenance.clear(operator_ref=operator_ref))- async def resume_clear(- self,- operation_id: str,- *,- operator_ref: str,- ) -> dict[str, Any]:- if self._retired or getattr(self._restart_config, "recovery_intent", None) == "factory_reset":- return {"status": "failed", "error": "memory_operation_in_progress"}- if not self.available:- raise self._unavailable()- maintenance = self._require_maintenance()- return await self._run_clear_with_operation_lease(- lambda: maintenance.resume_clear(- operation_id,- operator_ref=operator_ref,- )- )-- async def abort_clear(- self,- operation_id: str,- *,- operator_ref: str,- ) -> dict[str, Any]:- if self._retired or getattr(self._restart_config, "recovery_intent", None) == "factory_reset":- return {"status": "failed", "error": "memory_operation_in_progress"}- if not self.available:- raise self._unavailable()- maintenance = self._require_maintenance()- return await self._run_clear_with_operation_lease(- lambda: maintenance.abort_clear(- operation_id,- operator_ref=operator_ref,- )- )-async def _run_clear_with_operation_lease(self,operation: Callable[[], Awaitable[ClearResult]],@@ -1726,6 +1674,7 @@ class MemoryRuntime:await run_blocking(self._store.reset_for_clear,target_epoch=target_epoch,+ release_clear_fence=False,)returnif surface.surface == "provider":diff --git a/core/memory/snapshot.py b/core/memory/snapshot.pydeleted file mode 100644index 64177a2d8..000000000--- a/core/memory/snapshot.py+++ /dev/null@@ -1,2598 +0,0 @@-"""Crash-conscious snapshots for the durable Memory surfaces.--The manager deliberately knows paths, bytes, and integrity only. It does not-own the maintenance fence or decide when clear may proceed. SQLite inputs are-copied through the SQLite backup API so a live WAL is included in the resulting-standalone database.-"""--from __future__ import annotations--import hashlib-import json-import os-import re-import sqlite3-import stat-import uuid-from collections import OrderedDict-from contextlib import contextmanager-from dataclasses import dataclass-from pathlib import Path, PurePosixPath-from typing import Callable, Iterator, Literal, Mapping, Protocol, Sequence--from core.memory.confined_filesystem import (- ConfinedFilesystemError,- DirectoryOrderCursor as _DirectoryOrderCursor,- SpilledDirectoryOrder,- ensure_private_directory as ensure_confined_private_directory,- fsync_directory as fsync_confined_directory,- remove_anchored_entry,- remove_confined_path,- replace_confined,- required_no_follow_flag,- strict_directory_open_flags,- strict_file_create_flags,- strict_file_read_flags,-)---SnapshotSurfaceKind = Literal["sqlite", "tree", "call_log"]-SnapshotEntryType = Literal["sqlite", "tree", "directory", "file", "missing"]--_SCHEMA_VERSION = 2-_MANIFEST_FILENAME = "manifest.jsonl"-_PAYLOAD_DIRNAME = "payload"-_MANIFEST_BATCH_SIZE = 1_000-# Keep aggregate writer memory fixed while allowing one record to scale with the-# current canonical path. Deep trees created through dir-fd operations can-# legitimately exceed host whole-path limits.-_MANIFEST_WRITE_BUFFER_BYTES = 256 * 1024-_COPY_CHUNK_BYTES = 1024 * 1024-_DIRECTORY_ORDER_INSERT_BATCH_SIZE = 256-# Eviction only causes a path segment to be reopened; it never limits accepted-# tree depth. Two simultaneous caches therefore stay well below common fd limits.-_DIRECTORY_DESCRIPTOR_CACHE_SIZE = 48-_SNAPSHOT_ID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}\Z")-_AUTOMATIC_BACKUP_STAGE_RE = re.compile(r"\.([0-9a-f]{32})\.tmp\Z")-_SHA256_RE = re.compile(r"[0-9a-f]{64}\Z")-_CALL_LOG_FILESET: tuple[tuple[str, str], ...] = (- ("database", ""),- ("journal", "-journal"),- ("shm", "-shm"),- ("wal", "-wal"),-)---def _validated_relative_path(value: str) -> str:- if not isinstance(value, str) or not value or "\x00" in value:- raise ValueError("invalid effective-home-relative path")- path = PurePosixPath(value)- if path.is_absolute() or any(part in {"", ".", ".."} for part in path.parts):- raise ValueError("invalid effective-home-relative path")- canonical = path.as_posix()- if canonical != value:- raise ValueError("effective-home-relative path must be canonical")- return canonical---class MemorySnapshotError(RuntimeError):- """Base class for a refused or failed Memory snapshot operation."""---class MemorySnapshotUnsafePathError(MemorySnapshotError):- """A managed path escaped confinement or contained an unsafe file type."""---class MemorySnapshotVerificationError(MemorySnapshotError):- """A snapshot did not match its authenticated manifest."""---class _MemorySQLiteCorruptionError(MemorySnapshotError):- """A SQLite source is readable as a file but not as a valid database."""---def _new_directory_order(- *,- error_type: type[MemorySnapshotError],- message: str,-) -> SpilledDirectoryOrder:- try:- return SpilledDirectoryOrder(- insert_batch_size=_directory_order_insert_batch_size()- )- except ConfinedFilesystemError as error:- raise error_type(message) from error---def _scan_directory_order(- orders: SpilledDirectoryOrder,- descriptor: int,- *,- error_type: type[MemorySnapshotError],- message: str,- include: Callable[[str], bool] | None = None,-) -> _DirectoryOrderCursor:- try:- return orders.scan(descriptor, include=include)- except ConfinedFilesystemError as error:- raise error_type(message) from error---def _next_directory_name(- orders: SpilledDirectoryOrder,- cursor: _DirectoryOrderCursor,- *,- error_type: type[MemorySnapshotError],- message: str,-) -> str | None:- try:- return orders.next_name(cursor)- except ConfinedFilesystemError as error:- raise error_type(message) from error---@dataclass(frozen=True, slots=True)-class SnapshotSurface:- """One effective-home-relative surface owned by the snapshot manager."""-- path: str- kind: SnapshotSurfaceKind-- def __post_init__(self) -> None:- object.__setattr__(self, "path", _validated_relative_path(self.path))- if self.kind not in {"sqlite", "tree", "call_log"}:- raise ValueError("unsupported Memory snapshot surface kind")---DEFAULT_MEMORY_SNAPSHOT_SURFACES: tuple[SnapshotSurface, ...] = (- SnapshotSurface("state/memory/memory.sqlite", "sqlite"),- SnapshotSurface("memory/everos-root", "tree"),- SnapshotSurface("memory/call-log/call-log.db", "call_log"),- SnapshotSurface("memory/attachments", "tree"),-)--DEFAULT_MEMORY_BACKUP_SURFACES: tuple[SnapshotSurface, ...] = (- *DEFAULT_MEMORY_SNAPSHOT_SURFACES,- SnapshotSurface("state/memory/clear-journal.sqlite", "sqlite"),-)---@dataclass(frozen=True, slots=True)-class SnapshotEntry:- """One manifest row. Paths are always relative to the effective home."""-- path: str- type: SnapshotEntryType- mode: int- size: int- sha256: str | None- tree_digest: str | None-- def payload(self) -> dict[str, object]:- return {- "path": self.path,- "type": self.type,- "mode": self.mode,- "size": self.size,- "sha256": self.sha256,- "tree_digest": self.tree_digest,- }---@dataclass(frozen=True, slots=True)-class SnapshotSurfaceReceipt:- """Verified pre-clear identity for one fixed Memory surface."""-- path: str- present: bool- pre_clear_digest: str | None- snapshot_digest: str | None-- def __post_init__(self) -> None:- object.__setattr__(self, "path", _validated_relative_path(self.path))- if not isinstance(self.present, bool):- raise ValueError("Memory snapshot surface presence must be boolean")- if self.present:- _validated_sha256(self.pre_clear_digest)- _validated_sha256(self.snapshot_digest)- elif self.pre_clear_digest is not None or self.snapshot_digest is not None:- raise ValueError("an absent Memory snapshot surface cannot have digests")---@dataclass(frozen=True, slots=True)-class MemorySnapshot:- """A verified snapshot reference suitable for a clear journal."""-- snapshot_id: str- relative_path: str- manifest_sha256: str- # Only the fixed surface roots are retained. Full manifest entries live in- # an operation-scoped on-disk index while verification or restore runs.- entries: tuple[SnapshotEntry, ...]- surface_receipts: tuple[SnapshotSurfaceReceipt, ...]-- def surface_digests(self) -> dict[str, str | None]:- """Return the journal-persisted snapshot digest for every surface."""-- return {receipt.path: receipt.snapshot_digest for receipt in self.surface_receipts}---@dataclass(slots=True)-class _RestoreBackup:- target: Path- backup: Path- created_this_run: bool---@dataclass(slots=True)-class _RestorePlan:- surface: SnapshotSurface- target: Path- staged: Path | None- installs: list[tuple[Path, Path]]- backups: list[_RestoreBackup]- installed_targets: list[Path]---@dataclass(frozen=True, slots=True)-class _RelativeNode:- parent: _RelativeNode | None- name: str---@dataclass(slots=True)-class _TreeCopyFrame:- node: _RelativeNode | None- entry_type: Literal["tree", "directory"]- mode: int- before: tuple[int, int, int, int]- child_order: _DirectoryOrderCursor- digest: _DigestWriter---@dataclass(slots=True)-class _DirectoryWalkFrame:- node: _RelativeNode | None- before: tuple[int, int, int, int]- child_order: _DirectoryOrderCursor---class _DirectoryDescriptorCache:- """Reopen deep paths safely while keeping descriptor use constant."""-- def __init__(- self,- root_fd: int,- *,- verification: bool = False,- require_private: bool = True,- ) -> None:- self._root_fd = root_fd- self._verification = verification- self._require_private = require_private- self._descriptors: OrderedDict[object, tuple[object, int]] = OrderedDict()- self._maximum = _DIRECTORY_DESCRIPTOR_CACHE_SIZE-- def __enter__(self) -> "_DirectoryDescriptorCache":- return self-- def __exit__(self, *_exc_info: object) -> None:- self.close()-- def close(self) -> None:- for _identity, descriptor in self._descriptors.values():- os.close(descriptor)- self._descriptors.clear()-- def open(self, node: _RelativeNode | None, label: str) -> int:- if node is None:- return os.dup(self._root_fd)- trail: list[_RelativeNode] = []- ancestor = node- cached: tuple[_RelativeNode, int] | None = None- while ancestor is not None:- cached = self._descriptors.get(id(ancestor))- if cached is not None and cached[0] is ancestor:- self._descriptors.move_to_end(id(ancestor))- break- trail.append(ancestor)- ancestor = ancestor.parent- current = os.dup(self._root_fd if cached is None else cached[1])- try:- for component_node in reversed(trail):- try:- next_descriptor = os.open(- component_node.name,- _directory_open_flags(),- dir_fd=current,- )- except OSError as error:- if self._verification:- raise MemorySnapshotVerificationError(- "Memory snapshot payload path is unsafe"- ) from error- raise MemorySnapshotUnsafePathError(- f"{label} cannot be opened safely"- ) from error- os.close(current)- current = next_descriptor- self._validate(os.fstat(current), label)- self._remember(id(component_node), component_node, current)- return current- except BaseException:- os.close(current)- raise-- def open_components(self, components: Sequence[str], label: str) -> int:- target = tuple(components)- prefix = target- cached: tuple[object, int] | None = None- while prefix:- cached = self._descriptors.get(prefix)- if cached is not None and cached[0] == prefix:- self._descriptors.move_to_end(prefix)- break- prefix = prefix[:-1]- current = os.dup(self._root_fd if cached is None else cached[1])- try:- for index in range(len(prefix), len(target)):- try:- next_descriptor = os.open(- target[index],- _directory_open_flags(),- dir_fd=current,- )- except OSError as error:- if self._verification:- raise MemorySnapshotVerificationError(- "Memory snapshot payload path is unsafe"- ) from error- raise MemorySnapshotUnsafePathError(- f"{label} cannot be opened safely"- ) from error- os.close(current)- current = next_descriptor- self._validate(os.fstat(current), label)- component_prefix = target[: index + 1]- self._remember(component_prefix, component_prefix, current)- return current- except BaseException:- os.close(current)- raise-- def _validate(self, info: os.stat_result, label: str) -> None:- if self._verification:- if (- not stat.S_ISDIR(info.st_mode)- or stat.S_ISLNK(info.st_mode)- or stat.S_IMODE(info.st_mode) & 0o077- ):- raise MemorySnapshotVerificationError(- "Memory snapshot payload path is unsafe"- )- try:- _require_owned(info, label)- except MemorySnapshotUnsafePathError as error:- raise MemorySnapshotVerificationError(- "Memory snapshot payload path is unsafe"- ) from error- return- if self._require_private:- _require_directory_private(info, label)- elif not stat.S_ISDIR(info.st_mode) or stat.S_ISLNK(info.st_mode):- raise MemorySnapshotUnsafePathError(f"{label} is not a safe directory")-- def _remember(self, key: object, identity: object, descriptor: int) -> None:- previous = self._descriptors.pop(key, None)- if previous is not None:- os.close(previous[1])- self._descriptors[key] = (identity, os.dup(descriptor))- while len(self._descriptors) > self._maximum:- _key, (_old_identity, old_descriptor) = self._descriptors.popitem(last=False)- os.close(old_descriptor)---class _DigestWriter(Protocol):- def update(self, value: bytes, /) -> None: ...-- def hexdigest(self) -> str: ...---class _ManifestWriter:- """Write an authenticated manifest without retaining the full tree."""-- def __init__(self, path: Path) -> None:- flags = strict_file_create_flags()- self._descriptor = os.open(path, flags, 0o600)- self._path = path- self._buffer: list[bytes] = []- self._buffer_bytes = 0- self._entries_digest = hashlib.sha256()- self._entry_count = 0- self._finished = False- try:- header = _json_line(- {- "format": "avibe-memory-snapshot",- "record": "header",- "schema_version": _SCHEMA_VERSION,- }- )- _write_all(self._descriptor, header)- except BaseException:- os.close(self._descriptor)- raise-- def add(self, entry: SnapshotEntry) -> None:- if self._finished:- raise RuntimeError("Memory snapshot manifest is already finished")- record = _json_line({"entry": entry.payload(), "record": "entry"})- self._entries_digest.update(record)- self._entry_count += 1- if self._buffer and (- self._buffer_bytes + len(record) > _MANIFEST_WRITE_BUFFER_BYTES- or len(self._buffer) >= _manifest_batch_size()- ):- self._flush()- if len(record) > _MANIFEST_WRITE_BUFFER_BYTES:- _write_all(self._descriptor, record)- return- self._buffer.append(record)- self._buffer_bytes += len(record)-- def finish(self) -> None:- if self._finished:- return- self._flush()- footer = _json_line(- {- "entries_sha256": self._entries_digest.hexdigest(),- "entry_count": self._entry_count,- "record": "footer",- }- )- _write_all(self._descriptor, footer)- os.fchmod(self._descriptor, 0o600)- os.fsync(self._descriptor)- self._finished = True-- def close(self) -> None:- os.close(self._descriptor)- if self._finished:- _fsync_directory(self._path.parent)-- def _flush(self) -> None:- if not self._buffer:- return- _write_all(self._descriptor, b"".join(self._buffer))- self._buffer.clear()- self._buffer_bytes = 0---class _ManifestIndex:- """Bounded-memory, automatically deleted index for manifest entries."""-- def __init__(self) -> None:- # An empty SQLite filename creates an on-disk temporary database which- # SQLite deletes automatically when this connection closes. It leaves- # no named snapshot metadata behind after success, failure, or process- # termination.- self._connection = sqlite3.connect("")- try:- self._connection.execute("PRAGMA temp_store=FILE")- self._connection.execute("PRAGMA cache_size=-2048")- self._connection.execute("PRAGMA journal_mode=OFF")- self._connection.execute(- """- CREATE TABLE manifest_entry (- path TEXT PRIMARY KEY,- type TEXT NOT NULL,- mode INTEGER NOT NULL,- size INTEGER NOT NULL,- sha256 TEXT,- tree_digest TEXT,- parent TEXT NOT NULL,- depth INTEGER NOT NULL- ) WITHOUT ROWID- """- )- self._connection.execute(- "CREATE INDEX manifest_entry_parent ON manifest_entry(parent, path)"- )- self._connection.execute(- "CREATE INDEX manifest_entry_depth ON manifest_entry(depth, path)"- )- except BaseException:- self._connection.close()- raise-- def __enter__(self) -> "_ManifestIndex":- return self-- def __exit__(self, *_exc_info: object) -> None:- self.close()-- def __iter__(self) -> Iterator[SnapshotEntry]:- return self.entries()-- def close(self) -> None:- self._connection.close()-- def add(self, entry: SnapshotEntry) -> None:- path = PurePosixPath(entry.path)- try:- self._connection.execute(- """- INSERT INTO manifest_entry (- path, type, mode, size, sha256, tree_digest, parent, depth- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)- """,- (- entry.path,- entry.type,- entry.mode,- entry.size,- entry.sha256,- entry.tree_digest,- path.parent.as_posix(),- len(path.parts),- ),- )- except sqlite3.IntegrityError as error:- raise MemorySnapshotVerificationError(- "Memory snapshot manifest contains duplicate paths"- ) from error-- def finish(self) -> None:- self._connection.commit()-- def count(self) -> int:- row = self._connection.execute("SELECT COUNT(*) FROM manifest_entry").fetchone()- assert row is not None- return int(row[0])-- def entry(self, path: str) -> SnapshotEntry | None:- row = self._connection.execute(- """- SELECT path, type, mode, size, sha256, tree_digest- FROM manifest_entry WHERE path = ?- """,- (path,),- ).fetchone()- return None if row is None else _entry_from_row(row)-- def entries(self) -> Iterator[SnapshotEntry]:- rows = self._connection.execute(- """- SELECT path, type, mode, size, sha256, tree_digest- FROM manifest_entry- """- )- for row in rows:- yield _entry_from_row(row)-- def descendants(- self,- path: str,- *,- entry_type: str | None = None,- depth_order: Literal["ASC", "DESC"] | None = None,- ) -> Iterator[SnapshotEntry]:- lower, upper = _descendant_bounds(path)- clauses = ["path >= ?", "path < ?"]- parameters: list[object] = [lower, upper]- if entry_type is not None:- clauses.append("type = ?")- parameters.append(entry_type)- order = "path"- if depth_order is not None:- order = f"depth {depth_order}, path"- rows = self._connection.execute(- f"""- SELECT path, type, mode, size, sha256, tree_digest- FROM manifest_entry- WHERE {' AND '.join(clauses)}- ORDER BY {order}- """,- parameters,- )- for row in rows:- yield _entry_from_row(row)-- def children(self, path: str) -> Iterator[SnapshotEntry]:- rows = self._connection.execute(- """- SELECT path, type, mode, size, sha256, tree_digest- FROM manifest_entry WHERE parent = ? ORDER BY path- """,- (path,),- )- for row in rows:- yield _entry_from_row(row)-- def has_descendant(self, path: str) -> bool:- lower, upper = _descendant_bounds(path)- return (- self._connection.execute(- "SELECT 1 FROM manifest_entry WHERE path >= ? AND path < ? LIMIT 1",- (lower, upper),- ).fetchone()- is not None- )---class MemorySnapshotManager:- """Create, verify, relocate, restore, and remove Memory snapshots."""-- def __init__(- self,- effective_home: Path | str,- *,- snapshot_root: Path | str = "state/memory/clear-snapshots",- surfaces: Sequence[SnapshotSurface] = DEFAULT_MEMORY_SNAPSHOT_SURFACES,- operation_guard: Callable[[], None] | None = None,- ) -> None:- self._effective_home = _absolute_without_resolve(effective_home)- root_value = Path(snapshot_root)- if root_value.is_absolute():- self._snapshot_root = _absolute_without_resolve(root_value)- self._snapshot_root_relative = _relative_to_home(- self._snapshot_root,- self._effective_home,- ).as_posix()- else:- self._snapshot_root_relative = _validated_relative_path(root_value.as_posix())- self._snapshot_root = self._effective_home / self._snapshot_root_relative-- if not surfaces:- raise ValueError("at least one Memory snapshot surface is required")- self._surfaces = tuple(surfaces)- self._operation_guard = operation_guard- self._validate_surface_layout()-- @classmethod- def _for_backup(- cls,- effective_home: Path | str,- *,- operation_guard: Callable[[], None],- ) -> "MemorySnapshotManager":- """Build the low-level ordinary-backup manager.-- Only ``MemoryRuntime`` may expose this manager: it holds the runtime and- provider-root maintenance fences for the full create/restore operation.- """-- if not callable(operation_guard):- raise TypeError("Memory backup requires a clear-journal guard")- return cls(- effective_home,- snapshot_root="state/memory/backups",- surfaces=DEFAULT_MEMORY_BACKUP_SURFACES,- operation_guard=operation_guard,- )-- @property- def effective_home(self) -> Path:- return self._effective_home-- @property- def snapshot_root(self) -> Path:- return self._snapshot_root-- @property- def surfaces(self) -> tuple[SnapshotSurface, ...]:- return self._surfaces-- def snapshot_path(self, snapshot_id: str) -> Path:- return self._snapshot_root / _validated_snapshot_id(snapshot_id)-- def create(self, snapshot_id: str | None = None) -> MemorySnapshot:- """Create and verify one all-surface snapshot before publishing it."""-- self._assert_operation_allowed()- identifier = _validated_snapshot_id(snapshot_id or uuid.uuid4().hex)- _ensure_private_directory(self._effective_home, self._effective_home)- _ensure_private_directory(self._effective_home, self._snapshot_root)- final = self.snapshot_path(identifier)- _require_absent(final, "Memory snapshot already exists")- # A process death bypasses exception cleanup. Reusing one operation-- # scoped stage lets the explicit retry reclaim that unpublished copy- # without scanning or trusting arbitrary entries in the snapshot root.- stage = self._snapshot_root / f".{identifier}.tmp"- _remove_safe_path(self._effective_home, stage)- _fsync_directory(self._snapshot_root)- payload_root = stage / _PAYLOAD_DIRNAME- published = False- try:- _mkdir_private(stage)- _mkdir_private(payload_root)- manifest = _ManifestWriter(stage / _MANIFEST_FILENAME)- try:- for surface in self._surfaces:- source = self._effective_home / surface.path- destination = payload_root / surface.path- if surface.kind == "sqlite":- manifest.add(self._snapshot_sqlite(surface, source, destination))- elif surface.kind == "call_log":- self._snapshot_call_log(surface, source, destination, manifest)- else:- self._snapshot_tree(surface, source, destination, manifest)- manifest.finish()- finally:- manifest.close()- _fsync_directory(payload_root)- _fsync_directory(stage)- self._verify_directory(identifier, stage)- _replace_safe_path(self._effective_home, stage, final)- published = True- _fsync_directory(self._snapshot_root)- return self._verify_directory(identifier, final)- except Exception:- cleanup = final if published else stage- try:- _remove_safe_path(self._effective_home, cleanup)- _fsync_directory(self._snapshot_root)- except (FileNotFoundError, MemorySnapshotError, OSError):- pass- raise-- def reconcile_unpublished_backup_stages(self) -> tuple[str, ...]:- """Remove abandoned auto-ID backup stages through the managed root fd."""-- if self._snapshot_root_relative != "state/memory/backups":- raise RuntimeError("backup stage reconciliation requires the backup manager")- self._assert_operation_allowed()- root_info = _managed_source_info(self._effective_home, self._snapshot_root)- if root_info is None:- return ()- _require_directory_private(root_info, "Memory backup root")- root_fd = _open_directory(self._snapshot_root, "Memory backup root")- removed: list[str] = []- orders: SpilledDirectoryOrder | None = None- try:- orders = _new_directory_order(- error_type=MemorySnapshotUnsafePathError,- message="Memory backup root cannot be scanned safely",- )- candidates = _scan_directory_order(- orders,- root_fd,- error_type=MemorySnapshotUnsafePathError,- message="Memory backup root cannot be scanned safely",- include=lambda name: _AUTOMATIC_BACKUP_STAGE_RE.fullmatch(name)- is not None,- )- while True:- name = _next_directory_name(- orders,- candidates,- error_type=MemorySnapshotUnsafePathError,- message="Memory backup root cannot be scanned safely",- )- if name is None:- break- try:- info = os.stat(name, dir_fd=root_fd, follow_symlinks=False)- except OSError as error:- raise MemorySnapshotUnsafePathError(- "Memory backup stage cannot be inspected safely"- ) from error- if stat.S_ISLNK(info.st_mode) or not stat.S_ISDIR(info.st_mode):- raise MemorySnapshotUnsafePathError(- "Memory backup stage is not a safe directory"- )- _require_directory_private(info, "Memory backup stage")- _remove_safe_entry(- root_fd,- name,- expected_identity=(info.st_dev, info.st_ino),- )- removed.append(name[1:-4])- if removed:- os.fsync(root_fd)- return tuple(removed)- finally:- if orders is not None:- orders.close()- os.close(root_fd)-- def verify(- self,- snapshot_id: str,- *,- expected_manifest_sha256: str,- expected_surface_digests: Mapping[str, str | None],- ) -> MemorySnapshot:- """Verify the manifest, every byte, every mode, and every tree digest."""-- self._require_no_follow()- identifier = _validated_snapshot_id(snapshot_id)- directory = self.snapshot_path(identifier)- with self._verified_directory(identifier, directory) as (snapshot, _index):- self._verify_expected_snapshot(- snapshot,- expected_manifest_sha256=expected_manifest_sha256,- expected_surface_digests=expected_surface_digests,- )- return snapshot-- def restore(- self,- snapshot_id: str,- *,- expected_manifest_sha256: str,- expected_surface_digests: Mapping[str, str | None],- before_replace: Callable[[MemorySnapshot], None] | None = None,- ) -> MemorySnapshot:- """Restore every surface relative to this manager's effective home.-- The complete snapshot is verified before any target is touched. All- replacement payloads are staged first, and an in-process failure rolls- already-swapped targets back. ``before_replace`` runs after staging and- before the first target mutation so the caller can publish its durable- crash-recovery intent while holding the process-wide maintenance fence.- """-- self._assert_operation_allowed()- identifier = _validated_snapshot_id(snapshot_id)- snapshot_dir = self.snapshot_path(identifier)- with self._verified_directory(identifier, snapshot_dir) as (snapshot, manifest_index):- self._verify_expected_snapshot(- snapshot,- expected_manifest_sha256=expected_manifest_sha256,- expected_surface_digests=expected_surface_digests,- )- payload_root = snapshot_dir / _PAYLOAD_DIRNAME- plans: list[_RestorePlan] = []- token = snapshot.snapshot_id- try:- for index, surface in enumerate(self._surfaces):- target = self._effective_home / surface.path- _ensure_private_directory(self._effective_home, target.parent)- root_entry = manifest_index.entry(surface.path)- assert root_entry is not None- staged: Path | None = None- if root_entry.type != "missing":- staged = target.parent / f".{target.name}.restore-{token}-{index}"- _remove_safe_path(self._effective_home, staged)- plan = _RestorePlan(- surface=surface,- target=target,- staged=staged,- installs=[],- backups=[],- installed_targets=[],- )- plans.append(plan)- if staged is not None:- if root_entry.type == "sqlite":- _copy_verified_file(- payload_root / surface.path,- staged,- confinement_home=self._effective_home,- expected_sha256=root_entry.sha256,- expected_size=root_entry.size,- mode=root_entry.mode,- )- plan.installs.append((staged, target))- else:- self._stage_tree_restore(- surface,- root_entry,- manifest_index,- payload_root,- staged,- )- if surface.kind == "call_log":- for member, suffix in _CALL_LOG_FILESET:- if manifest_index.entry(f"{surface.path}/{member}") is not None:- plan.installs.append(- (- staged / member,- target.with_name(f"{target.name}{suffix}"),- )- )- else:- plan.installs.append((staged, target))-- if before_replace is not None:- before_replace(snapshot)-- for index, plan in enumerate(plans):- candidates = [plan.target]- if plan.surface.kind in {"sqlite", "call_log"}:- candidates.extend(_sqlite_sidecars(plan.target))- for candidate_index, candidate in enumerate(candidates):- backup = candidate.parent / (- f".{candidate.name}.before-restore-{token}-{index}-{candidate_index}"- )- try:- backup_info = os.lstat(backup)- except FileNotFoundError:- backup_info = None- if backup_info is not None:- _require_expected_target(- backup_info,- plan.surface.kind,- sidecar=candidate_index > 0,- )- plan.backups.append(_RestoreBackup(candidate, backup, False))- try:- info = os.lstat(candidate)- except FileNotFoundError:- continue- _require_expected_target(- info,- plan.surface.kind,- sidecar=candidate_index > 0,- )- if backup_info is None:- _replace_safe_path(self._effective_home, candidate, backup)- plan.backups.append(_RestoreBackup(candidate, backup, True))- else:- _remove_safe_path(self._effective_home, candidate)- for staged_file, installed_target in plan.installs:- _replace_safe_path(- self._effective_home,- staged_file,- installed_target,- )- plan.installed_targets.append(installed_target)- _fsync_directory(plan.target.parent)- except Exception:- self._rollback_restore(plans)- raise-- for plan in plans:- for backup in plan.backups:- _remove_safe_path(self._effective_home, backup.backup)- if plan.staged is not None:- _remove_safe_path(self._effective_home, plan.staged)- _fsync_directory(plan.target.parent)- return snapshot-- def _assert_operation_allowed(self) -> None:- self._require_no_follow()- if self._operation_guard is not None:- self._operation_guard()-- @staticmethod- def _require_no_follow() -> None:- try:- required_no_follow_flag()- except ConfinedFilesystemError as error:- raise MemorySnapshotUnsafePathError(- "Memory snapshots require no-follow filesystem support"- ) from error-- def _remove_clear_snapshot(- self,- snapshot_id: str,- *,- expected_relative_path: str,- expected_manifest_sha256: str,- expected_surface_digests: Mapping[str, str | None],- ) -> None:- """Remove one journal-authorized clear snapshot."""-- self._require_no_follow()- identifier = _validated_snapshot_id(snapshot_id)- directory = self.snapshot_path(identifier)- tombstone = self._snapshot_root / f".{identifier}.gc"- expected_relative = (- PurePosixPath(self._snapshot_root_relative) / identifier- ).as_posix()- if expected_relative_path != expected_relative:- raise MemorySnapshotVerificationError(- "Memory snapshot removal path is invalid"- )-- # A prior removal may have crashed after the verified snapshot was- # renamed. The deterministic tombstone is already authorized by this- # permit and can be retried without requiring its partial tree to verify.- if _managed_source_info(self._effective_home, tombstone) is not None:- _remove_safe_path(self._effective_home, tombstone)- _fsync_directory(self._snapshot_root)-- info = _managed_source_info(self._effective_home, directory)- if info is None:- return- _require_directory_private(info, "Memory snapshot directory")- self.verify(- identifier,- expected_manifest_sha256=expected_manifest_sha256,- expected_surface_digests=expected_surface_digests,- )- _replace_safe_path(self._effective_home, directory, tombstone)- _fsync_directory(self._snapshot_root)- _remove_safe_path(self._effective_home, tombstone)- _fsync_directory(self._snapshot_root)-- def _discard_unrecorded_clear_snapshot(- self,- snapshot_id: str,- *,- expected_relative_path: str,- ) -> None:- """Discard one storage-authorized unrecorded clear snapshot."""-- self._require_no_follow()- identifier = _validated_snapshot_id(snapshot_id)- expected_relative = (- PurePosixPath(self._snapshot_root_relative) / identifier- ).as_posix()- if expected_relative_path != expected_relative:- raise MemorySnapshotVerificationError(- "Memory snapshot discard path is invalid"- )- directory = self.snapshot_path(identifier)- _remove_safe_path(self._effective_home, directory)- root_info = _managed_source_info(self._effective_home, self._snapshot_root)- if root_info is not None:- _require_directory_private(root_info, "Memory snapshot root")- _fsync_directory(self._snapshot_root)-- def _validate_surface_layout(self) -> None:- paths = [PurePosixPath(surface.path) for surface in self._surfaces]- if len(paths) != len(set(paths)):- raise ValueError("Memory snapshot surfaces must be unique")- snapshot_root = PurePosixPath(self._snapshot_root_relative)- for index, path in enumerate(paths):- if (- path == snapshot_root- or path in snapshot_root.parents- or snapshot_root in path.parents- ):- raise ValueError("Memory snapshot root cannot overlap a managed surface")- for other in paths[index + 1 :]:- if path in other.parents or other in path.parents:- raise ValueError("Memory snapshot surfaces cannot overlap")-- def _snapshot_sqlite(- self,- surface: SnapshotSurface,- source: Path,- destination: Path,- ) -> SnapshotEntry:- info = _managed_source_info(self._effective_home, source)- if info is None:- return _missing_entry(surface.path)- _require_regular_private(info, "Memory SQLite surface")- for sidecar in _sqlite_sidecars(source):- try:- sidecar_info = os.lstat(sidecar)- except FileNotFoundError:- continue- _require_regular_private(sidecar_info, "Memory SQLite sidecar")- _ensure_private_directory(self._effective_home, destination.parent)- before = (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns)- source_conn: sqlite3.Connection | None = None- destination_conn: sqlite3.Connection | None = None- try:- source_conn = sqlite3.connect(source.absolute().as_uri() + "?mode=ro", uri=True, timeout=5.0)- source_conn.execute("PRAGMA query_only=ON")- source_conn.execute("PRAGMA busy_timeout=5000")- destination_conn = sqlite3.connect(destination)- source_conn.backup(destination_conn)- destination_conn.commit()- check = destination_conn.execute("PRAGMA quick_check").fetchone()- if check is None or check[0] != "ok":- raise _MemorySQLiteCorruptionError(- "Memory SQLite snapshot failed integrity check"- )- except sqlite3.Error as error:- raise MemorySnapshotError("Memory SQLite snapshot failed") from error- finally:- if destination_conn is not None:- destination_conn.close()- if source_conn is not None:- source_conn.close()- after_info = os.lstat(source)- after = (after_info.st_dev, after_info.st_ino, after_info.st_size, after_info.st_mtime_ns)- if before != after or not stat.S_ISREG(after_info.st_mode):- raise MemorySnapshotError("Memory SQLite surface changed during snapshot")- mode = stat.S_IMODE(info.st_mode)- os.chmod(destination, mode)- _fsync_file(destination)- _fsync_directory(destination.parent)- destination_info = os.lstat(destination)- return SnapshotEntry(- path=surface.path,- type="sqlite",- mode=mode,- size=destination_info.st_size,- sha256=_file_sha256(destination),- tree_digest=None,- )-- def _snapshot_call_log(- self,- surface: SnapshotSurface,- source: Path,- destination: Path,- manifest: _ManifestWriter,- ) -> SnapshotEntry:- """Snapshot a diagnostic call log without weakening SQLite surfaces.-- Healthy call logs retain the standalone SQLite-backup representation.- A positively identified corrupt database instead uses a fixed raw file- set so Clear can preserve the diagnostic bytes for an exact Abort.- """-- source_state = _call_log_fileset_state(self._effective_home, source)- if not source_state:- entry = _missing_entry(surface.path)- manifest.add(entry)- return entry- if "database" in source_state:- if not _call_log_has_sqlite_header(self._effective_home, source):- return self._snapshot_call_log_fileset(- surface,- source,- destination,- manifest,- )- try:- entry = self._snapshot_sqlite(surface, source, destination)- except MemorySnapshotError as error:- if not _is_sqlite_corruption(error):- raise- _remove_safe_path(self._effective_home, destination)- for sidecar in _sqlite_sidecars(destination):- _remove_safe_path(self._effective_home, sidecar)- else:- manifest.add(entry)- return entry- return self._snapshot_call_log_fileset(- surface,- source,- destination,- manifest,- )-- def _snapshot_call_log_fileset(- self,- surface: SnapshotSurface,- source: Path,- destination: Path,- manifest: _ManifestWriter,- ) -> SnapshotEntry:- _ensure_private_directory(self._effective_home, destination.parent)- _mkdir_private(destination)- source_fd = _open_directory(source.parent, "Memory call-log directory")- destination_fd = _open_directory(- destination,- "Memory call-log snapshot destination",- )- try:- before = _call_log_fileset_state_at(source_fd, source.name)- if not before:- raise MemorySnapshotError("Memory call-log changed during snapshot")- root_template = SnapshotEntry(- path=surface.path,- type="tree",- mode=0o700,- size=0,- sha256=None,- tree_digest=None,- )- digest = _tree_digest(root_template)- for member, suffix in _CALL_LOG_FILESET:- info = before.get(member)- if info is None:- continue- size, file_digest = _copy_regular_file_at(- source_fd,- destination_fd,- f"{source.name}{suffix}",- destination_name=member,- mode=stat.S_IMODE(info.st_mode),- )- entry = SnapshotEntry(- path=f"{surface.path}/{member}",- type="file",- mode=stat.S_IMODE(info.st_mode),- size=size,- sha256=file_digest,- tree_digest=None,- )- manifest.add(entry)- _update_tree_digest(digest, entry)- after = _call_log_fileset_state_at(source_fd, source.name)- if _call_log_fileset_identity(before) != _call_log_fileset_identity(after):- raise MemorySnapshotError("Memory call-log changed during snapshot")- os.fchmod(destination_fd, 0o700)- os.fsync(destination_fd)- finally:- os.close(destination_fd)- os.close(source_fd)- root = SnapshotEntry(- path=surface.path,- type="tree",- mode=0o700,- size=0,- sha256=None,- tree_digest=digest.hexdigest(),- )- manifest.add(root)- return root-- def _snapshot_tree(- self,- surface: SnapshotSurface,- source: Path,- destination: Path,- manifest: _ManifestWriter,- ) -> SnapshotEntry:- info = _managed_source_info(self._effective_home, source)- if info is None:- entry = _missing_entry(surface.path)- manifest.add(entry)- return entry- _require_directory_private(info, "Memory tree surface")- _ensure_private_directory(self._effective_home, destination.parent)- _mkdir_private(destination)- source_root_fd = _open_directory(source, "Memory tree surface")- destination_root_fd = _open_directory(destination, "Memory snapshot destination")- source_cache = _DirectoryDescriptorCache(source_root_fd)- destination_cache = _DirectoryDescriptorCache(destination_root_fd)- orders: SpilledDirectoryOrder | None = None- try:- orders = _new_directory_order(- error_type=MemorySnapshotError,- message="Memory tree surface could not be read",- )- root_mode = stat.S_IMODE(info.st_mode)- stack = [- _tree_copy_frame(- source_cache,- orders,- None,- base_path=surface.path,- entry_type="tree",- mode=root_mode,- expected=info,- )- ]- root_entry: SnapshotEntry | None = None- while stack:- frame = stack[-1]- child_name = _next_directory_name(- orders,- frame.child_order,- error_type=MemorySnapshotError,- message="Memory tree surface could not be read",- )- if child_name is not None:- child_node = _RelativeNode(frame.node, child_name)- source_parent_fd = source_cache.open(- frame.node,- "Memory tree directory",- )- destination_parent_fd = destination_cache.open(- frame.node,- "Memory snapshot destination",- )- try:- child_info = os.stat(- child_name,- dir_fd=source_parent_fd,- follow_symlinks=False,- )- path_text = _node_manifest_path(surface.path, child_node)- if stat.S_ISLNK(child_info.st_mode):- raise MemorySnapshotUnsafePathError(- "Memory snapshot refuses symlinks"- )- if stat.S_ISDIR(child_info.st_mode):- _require_directory_private(- child_info,- "Memory tree directory",- )- _mkdir_private_at(destination_parent_fd, child_name)- stack.append(- _tree_copy_frame(- source_cache,- orders,- child_node,- base_path=surface.path,- entry_type="directory",- mode=stat.S_IMODE(child_info.st_mode),- expected=child_info,- )- )- continue- if not stat.S_ISREG(child_info.st_mode):- raise MemorySnapshotUnsafePathError(- "Memory snapshot refuses special files"- )- _require_regular_private(child_info, "Memory tree file")- size, file_digest = _copy_regular_file_at(- source_parent_fd,- destination_parent_fd,- child_name,- mode=stat.S_IMODE(child_info.st_mode),- )- finally:- os.close(destination_parent_fd)- os.close(source_parent_fd)- entry = SnapshotEntry(- path=path_text,- type="file",- mode=stat.S_IMODE(child_info.st_mode),- size=size,- sha256=file_digest,- tree_digest=None,- )- manifest.add(entry)- _update_tree_digest(frame.digest, entry)- continue-- stack.pop()- source_fd = source_cache.open(- frame.node,- "Memory tree directory",- )- destination_fd = destination_cache.open(- frame.node,- "Memory snapshot destination",- )- try:- after = os.fstat(source_fd)- if _directory_identity(after) != frame.before:- raise MemorySnapshotError(- "Memory tree directory changed during snapshot"- )- os.fchmod(destination_fd, frame.mode)- os.fsync(destination_fd)- finally:- os.close(destination_fd)- os.close(source_fd)- entry = SnapshotEntry(- path=_node_manifest_path(surface.path, frame.node),- type=frame.entry_type,- mode=frame.mode,- size=0,- sha256=None,- tree_digest=frame.digest.hexdigest(),- )- manifest.add(entry)- if stack:- _update_tree_digest(stack[-1].digest, entry)- else:- root_entry = entry- assert root_entry is not None- return root_entry- finally:- if orders is not None:- orders.close()- destination_cache.close()- source_cache.close()- os.close(destination_root_fd)- os.close(source_root_fd)-- def _verify_directory(self, snapshot_id: str, directory: Path) -> MemorySnapshot:- with self._verified_directory(snapshot_id, directory) as (snapshot, _index):- return snapshot-- @contextmanager- def _verified_directory(- self,- snapshot_id: str,- directory: Path,- ) -> Iterator[tuple[MemorySnapshot, _ManifestIndex]]:- try:- directory_info = _managed_source_info(self._effective_home, directory)- except FileNotFoundError as error:- raise MemorySnapshotVerificationError("Memory snapshot is missing") from error- if directory_info is None:- raise MemorySnapshotVerificationError("Memory snapshot is missing")- _require_directory_private(directory_info, "Memory snapshot directory")- manifest_path = directory / _MANIFEST_FILENAME- with _indexed_manifest(manifest_path) as (manifest_index, manifest_sha256):- roots = self._validate_manifest_surfaces(manifest_index)- payload_root = directory / _PAYLOAD_DIRNAME- try:- payload_info = os.lstat(payload_root)- except FileNotFoundError as error:- raise MemorySnapshotVerificationError(- "Memory snapshot payload is missing"- ) from error- _require_directory_private(payload_info, "Memory snapshot payload")- self._verify_payload(payload_root, manifest_index)- receipts = tuple(- SnapshotSurfaceReceipt(- path=surface.path,- present=root.type != "missing",- pre_clear_digest=root.sha256 or root.tree_digest,- snapshot_digest=root.sha256 or root.tree_digest,- )- for surface, root in zip(self._surfaces, roots, strict=True)- )- snapshot = MemorySnapshot(- snapshot_id=snapshot_id,- relative_path=(- PurePosixPath(self._snapshot_root_relative) / snapshot_id- ).as_posix(),- manifest_sha256=manifest_sha256,- entries=roots,- surface_receipts=receipts,- )- yield snapshot, manifest_index-- def _verify_expected_snapshot(- self,- snapshot: MemorySnapshot,- *,- expected_manifest_sha256: str,- expected_surface_digests: Mapping[str, str | None],- ) -> None:- expected_manifest = _validated_sha256(expected_manifest_sha256)- if snapshot.manifest_sha256 != expected_manifest:- raise MemorySnapshotVerificationError("Memory snapshot manifest digest changed")- self._verify_surface_digests(snapshot, expected_surface_digests)-- def _verify_surface_digests(- self,- snapshot: MemorySnapshot,- expected: Mapping[str, str | None],- ) -> None:- expected_paths = {surface.path for surface in self._surfaces}- if set(expected) != expected_paths:- raise ValueError("expected Memory snapshot digests must cover every surface")- receipts = {receipt.path: receipt for receipt in snapshot.surface_receipts}- for surface in self._surfaces:- expected_digest = expected[surface.path]- if expected_digest is not None:- expected_digest = _validated_sha256(expected_digest)- actual_digest = receipts[surface.path].snapshot_digest- if actual_digest != expected_digest:- raise MemorySnapshotVerificationError("Memory snapshot surface digest changed")-- def _validate_manifest_surfaces(- self,- entries: _ManifestIndex,- ) -> tuple[SnapshotEntry, ...]:- roots: list[SnapshotEntry] = []- for surface in self._surfaces:- root = entries.entry(surface.path)- allowed_root_types = (- {"sqlite", "tree", "missing"}- if surface.kind == "call_log"- else {surface.kind, "missing"}- )- if root is None or root.type not in allowed_root_types:- raise MemorySnapshotVerificationError("Memory snapshot surface root is invalid")- if root.type == "missing" and entries.has_descendant(surface.path):- raise MemorySnapshotVerificationError("Missing Memory surface has payload entries")- if surface.kind == "call_log":- descendants = tuple(entries.descendants(surface.path))- if root.type == "tree":- expected_paths = {- f"{surface.path}/{member}" for member, _suffix in _CALL_LOG_FILESET- }- if not descendants or any(- entry.path not in expected_paths or entry.type != "file"- for entry in descendants- ):- raise MemorySnapshotVerificationError(- "Memory call-log snapshot file set is invalid"- )- elif descendants:- raise MemorySnapshotVerificationError(- "Memory call-log SQLite surface has child entries"- )- roots.append(root)- for entry in entries:- owner: SnapshotSurface | None = None- entry_path = PurePosixPath(entry.path)- for surface in self._surfaces:- surface_path = PurePosixPath(surface.path)- if entry_path == surface_path or surface_path in entry_path.parents:- if owner is not None:- raise MemorySnapshotVerificationError(- "Memory snapshot entry is outside its surfaces"- )- owner = surface- if owner is None:- raise MemorySnapshotVerificationError("Memory snapshot entry is outside its surfaces")- if owner.kind == "sqlite" and entry.path != owner.path:- raise MemorySnapshotVerificationError("Memory SQLite surface has child entries")- if entry.path != owner.path and entry.type not in {"directory", "file"}:- raise MemorySnapshotVerificationError("Memory tree child has an invalid type")- return tuple(roots)-- def _verify_payload(self, payload_root: Path, entries: _ManifestIndex) -> None:- payload_fd = _open_verification_directory(payload_root, "Memory snapshot payload")- payload_cache = _DirectoryDescriptorCache(payload_fd, verification=True)- try:- for entry in entries:- if entry.type == "missing":- continue- parts = entry.path.split("/")- parent_fd = payload_cache.open_components(- parts[:-1],- "Memory snapshot payload directory",- )- try:- try:- info = os.stat(- parts[-1],- dir_fd=parent_fd,- follow_symlinks=False,- )- except FileNotFoundError as error:- raise MemorySnapshotVerificationError(- "Memory snapshot payload entry is missing"- ) from error- mode = stat.S_IMODE(info.st_mode)- if mode != entry.mode:- raise MemorySnapshotVerificationError(- "Memory snapshot payload mode changed"- )- if entry.type in {"sqlite", "file"}:- if not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode):- raise MemorySnapshotVerificationError(- "Memory snapshot file type changed"- )- if (- info.st_size != entry.size- or _file_sha256_at(parent_fd, parts[-1]) != entry.sha256- ):- raise MemorySnapshotVerificationError(- "Memory snapshot file digest changed"- )- else:- if not stat.S_ISDIR(info.st_mode) or stat.S_ISLNK(info.st_mode):- raise MemorySnapshotVerificationError(- "Memory snapshot directory type changed"- )- if entry.size != 0:- raise MemorySnapshotVerificationError(- "Memory snapshot directory size is invalid"- )- finally:- os.close(parent_fd)-- _verify_payload_paths(payload_fd, payload_cache, entries)- finally:- payload_cache.close()- os.close(payload_fd)- for entry in entries:- if entry.type not in {"tree", "directory"}:- continue- digest = _tree_digest(entry)- for child in entries.children(entry.path):- _update_tree_digest(digest, child)- if digest.hexdigest() != entry.tree_digest:- raise MemorySnapshotVerificationError("Memory snapshot tree digest changed")-- def _stage_tree_restore(- self,- surface: SnapshotSurface,- root: SnapshotEntry,- entries: _ManifestIndex,- payload_root: Path,- staged: Path,- ) -> None:- _mkdir_private(staged)- payload_fd = _open_verification_directory(payload_root, "Memory snapshot payload")- staged_fd = _open_directory(staged, "Memory restore staging directory")- payload_cache = _DirectoryDescriptorCache(payload_fd, verification=True)- staged_cache = _DirectoryDescriptorCache(staged_fd)- surface_parts = surface.path.split("/")- try:- for entry in entries.descendants(- surface.path,- entry_type="directory",- depth_order="ASC",- ):- relative_parts = entry.path.split("/")[len(surface_parts) :]- parent_fd = staged_cache.open_components(- relative_parts[:-1],- "Memory restore staging directory",- )- try:- _mkdir_private_at(parent_fd, relative_parts[-1])- finally:- os.close(parent_fd)- for entry in entries.descendants(surface.path, entry_type="file"):- source_parts = entry.path.split("/")- relative_parts = source_parts[len(surface_parts) :]- source_parent_fd = payload_cache.open_components(- source_parts[:-1],- "Memory snapshot payload directory",- )- destination_parent_fd = staged_cache.open_components(- relative_parts[:-1],- "Memory restore staging directory",- )- try:- _copy_verified_file_at(- source_parent_fd,- destination_parent_fd,- source_parts[-1],- relative_parts[-1],- expected_sha256=entry.sha256,- expected_size=entry.size,- mode=entry.mode,- )- finally:- os.close(destination_parent_fd)- os.close(source_parent_fd)- for entry in entries.descendants(- surface.path,- entry_type="directory",- depth_order="DESC",- ):- relative_parts = entry.path.split("/")[len(surface_parts) :]- directory_fd = staged_cache.open_components(- relative_parts,- "Memory restore staging directory",- )- try:- os.fchmod(directory_fd, entry.mode)- os.fsync(directory_fd)- finally:- os.close(directory_fd)- os.fchmod(staged_fd, root.mode)- os.fsync(staged_fd)- finally:- staged_cache.close()- payload_cache.close()- os.close(staged_fd)- os.close(payload_fd)-- def _rollback_restore(self, plans: list[_RestorePlan]) -> None:- for plan in reversed(plans):- try:- for installed_target in reversed(plan.installed_targets):- _remove_safe_path(self._effective_home, installed_target)- for backup in reversed(plan.backups):- if backup.created_this_run and backup.backup.exists():- _replace_safe_path(- self._effective_home,- backup.backup,- backup.target,- )- if plan.staged is not None:- _remove_safe_path(self._effective_home, plan.staged)- _fsync_directory(plan.target.parent)- except (MemorySnapshotError, OSError):- continue---def _absolute_without_resolve(value: Path | str) -> Path:- return Path(os.path.abspath(os.path.expanduser(os.fspath(value))))---def _validated_snapshot_id(value: str) -> str:- if not isinstance(value, str) or _SNAPSHOT_ID_RE.fullmatch(value) is None:- raise ValueError("invalid Memory snapshot id")- return value---def _validated_sha256(value: str) -> str:- if not isinstance(value, str) or _SHA256_RE.fullmatch(value) is None:- raise ValueError("invalid Memory snapshot SHA-256 digest")- return value---def _relative_to_home(path: Path, home: Path) -> Path:- try:- return path.relative_to(home)- except ValueError as error:- raise ValueError("Memory snapshot path must stay within the effective home") from error---def _managed_source_info(home: Path, source: Path) -> os.stat_result | None:- relative = _relative_to_home(source, home)- current = home- _require_directory(os.lstat(current), "effective Memory home")- for index, component in enumerate(relative.parts):- current /= component- try:- info = os.lstat(current)- except FileNotFoundError:- return None- if index < len(relative.parts) - 1:- _require_directory(info, "Memory surface parent")- return info---def _ensure_private_directory(home: Path, directory: Path) -> None:- try:- ensure_confined_private_directory(home, directory)- except ConfinedFilesystemError as error:- raise MemorySnapshotUnsafePathError(- "Memory directory cannot be prepared safely"- ) from error---def _mkdir_private(path: Path) -> None:- os.mkdir(path, mode=0o700)- os.chmod(path, 0o700)- _require_directory_private(os.lstat(path), "Memory private directory")---def _directory_open_flags() -> int:- return strict_directory_open_flags()---def _open_directory(path: Path, label: str) -> int:- try:- descriptor = os.open(path, _directory_open_flags())- except OSError as error:- raise MemorySnapshotUnsafePathError(f"{label} cannot be opened safely") from error- try:- _require_directory_private(os.fstat(descriptor), label)- except BaseException:- os.close(descriptor)- raise- return descriptor---def _open_verification_directory(path: Path, label: str) -> int:- try:- descriptor = os.open(path, _directory_open_flags())- except OSError as error:- raise MemorySnapshotVerificationError(f"{label} cannot be opened safely") from error- try:- info = os.fstat(descriptor)- if (- not stat.S_ISDIR(info.st_mode)- or stat.S_ISLNK(info.st_mode)- or stat.S_IMODE(info.st_mode) & 0o077- ):- raise MemorySnapshotVerificationError(f"{label} is not a private directory")- _require_owned(info, label)- except BaseException:- os.close(descriptor)- raise- return descriptor---def _mkdir_private_at(parent_fd: int, name: str) -> None:- os.mkdir(name, mode=0o700, dir_fd=parent_fd)- descriptor = os.open(name, _directory_open_flags(), dir_fd=parent_fd)- try:- os.fchmod(descriptor, 0o700)- _require_directory_private(os.fstat(descriptor), "Memory private directory")- finally:- os.close(descriptor)---def _node_components(node: _RelativeNode | None) -> list[str]:- components: list[str] = []- while node is not None:- components.append(node.name)- node = node.parent- components.reverse()- return components---def _node_manifest_path(base_path: str, node: _RelativeNode | None) -> str:- components = _node_components(node)- value = base_path if not components else f"{base_path}/{'/'.join(components)}"- return _validated_relative_path(value)---def _directory_identity(info: os.stat_result) -> tuple[int, int, int, int]:- return (info.st_dev, info.st_ino, info.st_mode, info.st_mtime_ns)---def _tree_copy_frame(- source_cache: _DirectoryDescriptorCache,- orders: SpilledDirectoryOrder,- node: _RelativeNode | None,- *,- base_path: str,- entry_type: Literal["tree", "directory"],- mode: int,- expected: os.stat_result,-) -> _TreeCopyFrame:- descriptor = source_cache.open(- node,- "Memory tree directory",- )- try:- opened = os.fstat(descriptor)- if (opened.st_dev, opened.st_ino) != (expected.st_dev, expected.st_ino):- raise MemorySnapshotError("Memory tree directory changed during snapshot")- entry = SnapshotEntry(- path=_node_manifest_path(base_path, node),- type=entry_type,- mode=mode,- size=0,- sha256=None,- tree_digest=None,- )- return _TreeCopyFrame(- node=node,- entry_type=entry_type,- mode=mode,- before=_directory_identity(opened),- child_order=_scan_directory_order(- orders,- descriptor,- error_type=MemorySnapshotError,- message="Memory tree surface could not be read",- ),- digest=_tree_digest(entry),- )- finally:- os.close(descriptor)---def _require_absent(path: Path, message: str) -> None:- try:- os.lstat(path)- except FileNotFoundError:- return- raise MemorySnapshotUnsafePathError(message)---def _require_owned(info: os.stat_result, label: str) -> None:- if hasattr(os, "getuid") and info.st_uid != os.getuid():- raise MemorySnapshotUnsafePathError(f"{label} is not owned by the current user")---def _require_directory(info: os.stat_result, label: str) -> None:- if stat.S_ISLNK(info.st_mode) or not stat.S_ISDIR(info.st_mode):- raise MemorySnapshotUnsafePathError(f"{label} is not a safe directory")- _require_owned(info, label)---def _require_directory_private(info: os.stat_result, label: str) -> None:- _require_directory(info, label)- if stat.S_IMODE(info.st_mode) & 0o077:- raise MemorySnapshotUnsafePathError(f"{label} is not owner-only")---def _require_regular_private(info: os.stat_result, label: str) -> None:- if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode):- raise MemorySnapshotUnsafePathError(f"{label} is not a safe regular file")- _require_owned(info, label)- if info.st_nlink != 1:- raise MemorySnapshotUnsafePathError(f"{label} has multiple hard links")- if stat.S_IMODE(info.st_mode) & 0o077:- raise MemorySnapshotUnsafePathError(f"{label} is not owner-only")---def _missing_entry(path: str) -> SnapshotEntry:- return SnapshotEntry(path, "missing", 0, 0, None, None)---def _copy_regular_file(source: Path, destination: Path, *, mode: int) -> tuple[int, str]:- flags = strict_file_read_flags()- source_fd = os.open(source, flags)- destination_fd: int | None = None- try:- before = os.fstat(source_fd)- _require_regular_private(before, "Memory snapshot source file")- destination_flags = strict_file_create_flags()- destination_fd = os.open(destination, destination_flags, 0o600)- digest = hashlib.sha256()- size = 0- while True:- chunk = os.read(source_fd, _COPY_CHUNK_BYTES)- if not chunk:- break- digest.update(chunk)- size += len(chunk)- _write_all(destination_fd, chunk)- after = os.fstat(source_fd)- stable = (- before.st_dev,- before.st_ino,- before.st_size,- before.st_mtime_ns,- ) == (- after.st_dev,- after.st_ino,- after.st_size,- after.st_mtime_ns,- )- if not stable or size != before.st_size:- raise MemorySnapshotError("Memory snapshot source changed during copy")- os.fchmod(destination_fd, mode)- os.fsync(destination_fd)- return size, digest.hexdigest()- finally:- os.close(source_fd)- if destination_fd is not None:- os.close(destination_fd)- if destination.exists():- _fsync_directory(destination.parent)---def _copy_regular_file_at(- source_parent_fd: int,- destination_parent_fd: int,- source_name: str,- *,- mode: int,- destination_name: str | None = None,-) -> tuple[int, str]:- target_name = source_name if destination_name is None else destination_name- source_fd = os.open(- source_name,- strict_file_read_flags(),- dir_fd=source_parent_fd,- )- destination_fd: int | None = None- created = False- try:- before = os.fstat(source_fd)- _require_regular_private(before, "Memory snapshot source file")- destination_fd = os.open(- target_name,- strict_file_create_flags(),- 0o600,- dir_fd=destination_parent_fd,- )- created = True- digest = hashlib.sha256()- size = 0- while True:- chunk = os.read(source_fd, _COPY_CHUNK_BYTES)- if not chunk:- break- digest.update(chunk)- size += len(chunk)- _write_all(destination_fd, chunk)- after = os.fstat(source_fd)- stable = (- before.st_dev,- before.st_ino,- before.st_size,- before.st_mtime_ns,- ) == (- after.st_dev,- after.st_ino,- after.st_size,- after.st_mtime_ns,- )- if not stable or size != before.st_size:- raise MemorySnapshotError("Memory snapshot source changed during copy")- os.fchmod(destination_fd, mode)- os.fsync(destination_fd)- return size, digest.hexdigest()- finally:- os.close(source_fd)- if destination_fd is not None:- os.close(destination_fd)- if created:- os.fsync(destination_parent_fd)---def _copy_verified_file(- source: Path,- destination: Path,- *,- confinement_home: Path,- expected_sha256: str | None,- expected_size: int,- mode: int,-) -> None:- if expected_sha256 is None:- raise MemorySnapshotVerificationError("Memory snapshot file has no digest")- size, digest = _copy_regular_file(source, destination, mode=mode)- if size != expected_size or digest != expected_sha256:- _remove_safe_path(confinement_home, destination)- raise MemorySnapshotVerificationError("Memory snapshot changed during restore staging")---def _copy_verified_file_at(- source_parent_fd: int,- destination_parent_fd: int,- source_name: str,- destination_name: str,- *,- expected_sha256: str | None,- expected_size: int,- mode: int,-) -> None:- if expected_sha256 is None:- raise MemorySnapshotVerificationError("Memory snapshot file has no digest")- size, digest = _copy_regular_file_at(- source_parent_fd,- destination_parent_fd,- source_name,- destination_name=destination_name,- mode=mode,- )- if size != expected_size or digest != expected_sha256:- try:- os.unlink(destination_name, dir_fd=destination_parent_fd)- except FileNotFoundError:- pass- raise MemorySnapshotVerificationError(- "Memory snapshot changed during restore staging"- )---def _write_all(descriptor: int, payload: bytes) -> None:- view = memoryview(payload)- while view:- written = os.write(descriptor, view)- if written <= 0:- raise OSError("short Memory snapshot write")- view = view[written:]---@contextmanager-def _indexed_manifest(path: Path) -> Iterator[tuple[_ManifestIndex, str]]:- with _ManifestIndex() as entries:- manifest_sha256 = _read_manifest(path, entries)- yield entries, manifest_sha256---def _read_manifest(path: Path, entries: _ManifestIndex) -> str:- flags = strict_file_read_flags()- try:- descriptor = os.open(path, flags)- except OSError as error:- raise MemorySnapshotVerificationError(- "Memory snapshot manifest cannot be opened safely"- ) from error- try:- before = os.fstat(descriptor)- _require_regular_private(before, "Memory snapshot manifest")- manifest_digest = hashlib.sha256()- entries_digest = hashlib.sha256()- entry_count = 0- footer_seen = False- line_number = 0- with os.fdopen(os.dup(descriptor), "rb") as stream:- for line in stream:- line_number += 1- if not line.endswith(b"\n"):- raise MemorySnapshotVerificationError(- "Memory snapshot manifest record is invalid"- )- manifest_digest.update(line)- try:- record = json.loads(line)- except (UnicodeDecodeError, json.JSONDecodeError) as error:- raise MemorySnapshotVerificationError(- "Memory snapshot manifest is invalid"- ) from error- if line_number == 1:- if record != {- "format": "avibe-memory-snapshot",- "record": "header",- "schema_version": _SCHEMA_VERSION,- }:- raise MemorySnapshotVerificationError(- "Memory snapshot manifest version is unsupported"- )- continue- if footer_seen or not isinstance(record, dict):- raise MemorySnapshotVerificationError(- "Memory snapshot manifest shape is invalid"- )- if record.get("record") == "entry":- if set(record) != {"entry", "record"}:- raise MemorySnapshotVerificationError(- "Memory snapshot manifest entry is invalid"- )- entries.add(_parse_manifest_entry(record["entry"]))- entry_count += 1- entries_digest.update(line)- continue- if record.get("record") == "footer":- if set(record) != {"entries_sha256", "entry_count", "record"}:- raise MemorySnapshotVerificationError(- "Memory snapshot manifest footer is invalid"- )- footer_entry_count = record["entry_count"]- expected_digest = record["entries_sha256"]- if (- not isinstance(footer_entry_count, int)- or isinstance(footer_entry_count, bool)- or footer_entry_count < 0- or not isinstance(expected_digest, str)- or _SHA256_RE.fullmatch(expected_digest) is None- or footer_entry_count != entry_count- or expected_digest != entries_digest.hexdigest()- ):- raise MemorySnapshotVerificationError(- "Memory snapshot manifest footer is invalid"- )- footer_seen = True- continue- raise MemorySnapshotVerificationError(- "Memory snapshot manifest record is invalid"- )- after = os.fstat(descriptor)- stable = (- before.st_dev,- before.st_ino,- before.st_size,- before.st_mtime_ns,- ) == (- after.st_dev,- after.st_ino,- after.st_size,- after.st_mtime_ns,- )- if not stable:- raise MemorySnapshotVerificationError("Memory snapshot manifest changed during read")- if line_number == 0 or not footer_seen:- raise MemorySnapshotVerificationError("Memory snapshot manifest is incomplete")- entries.finish()- return manifest_digest.hexdigest()- except OSError as error:- raise MemorySnapshotVerificationError("Memory snapshot manifest cannot be read") from error- finally:- os.close(descriptor)---def _json_line(payload: Mapping[str, object]) -> bytes:- return json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8") + b"\n"---def _manifest_batch_size() -> int:- if (- not isinstance(_MANIFEST_BATCH_SIZE, int)- or isinstance(_MANIFEST_BATCH_SIZE, bool)- or _MANIFEST_BATCH_SIZE <= 0- ):- raise MemorySnapshotError("Memory snapshot manifest batch size is invalid")- return _MANIFEST_BATCH_SIZE---def _directory_order_insert_batch_size() -> int:- if (- not isinstance(_DIRECTORY_ORDER_INSERT_BATCH_SIZE, int)- or isinstance(_DIRECTORY_ORDER_INSERT_BATCH_SIZE, bool)- or _DIRECTORY_ORDER_INSERT_BATCH_SIZE <= 0- ):- raise MemorySnapshotError("Memory snapshot directory order batch size is invalid")- return _DIRECTORY_ORDER_INSERT_BATCH_SIZE---def _parse_manifest_entry(raw: object) -> SnapshotEntry:- expected_keys = {"path", "type", "mode", "size", "sha256", "tree_digest"}- if not isinstance(raw, dict) or set(raw) != expected_keys:- raise MemorySnapshotVerificationError("Memory snapshot manifest entry is invalid")- try:- path = _validated_relative_path(raw["path"])- except (TypeError, ValueError) as error:- raise MemorySnapshotVerificationError("Memory snapshot path is invalid") from error- entry_type = raw["type"]- mode = raw["mode"]- size = raw["size"]- digest = raw["sha256"]- tree_digest = raw["tree_digest"]- if entry_type not in {"sqlite", "tree", "directory", "file", "missing"}:- raise MemorySnapshotVerificationError("Memory snapshot entry type is invalid")- if not isinstance(mode, int) or isinstance(mode, bool) or not 0 <= mode <= 0o777:- raise MemorySnapshotVerificationError("Memory snapshot entry mode is invalid")- if not isinstance(size, int) or isinstance(size, bool) or size < 0:- raise MemorySnapshotVerificationError("Memory snapshot entry size is invalid")- if digest is not None and (- not isinstance(digest, str) or _SHA256_RE.fullmatch(digest) is None- ):- raise MemorySnapshotVerificationError("Memory snapshot file digest is invalid")- if tree_digest is not None and (- not isinstance(tree_digest, str) or _SHA256_RE.fullmatch(tree_digest) is None- ):- raise MemorySnapshotVerificationError("Memory snapshot tree digest is invalid")- if entry_type in {"sqlite", "file"}:- if digest is None or tree_digest is not None or mode & 0o077:- raise MemorySnapshotVerificationError("Memory snapshot file metadata is invalid")- elif entry_type in {"tree", "directory"}:- if digest is not None or tree_digest is None or size != 0 or mode & 0o077:- raise MemorySnapshotVerificationError("Memory snapshot directory metadata is invalid")- elif any((mode, size, digest is not None, tree_digest is not None)):- raise MemorySnapshotVerificationError("Missing Memory surface metadata is invalid")- return SnapshotEntry(path, entry_type, mode, size, digest, tree_digest)---def _tree_digest(directory: SnapshotEntry) -> _DigestWriter:- digest = hashlib.sha256()- digest.update(f"path={directory.path}\ntype={directory.type}\n".encode("utf-8"))- digest.update(f"mode={directory.mode:o}\n".encode("ascii"))- return digest---def _update_tree_digest(digest: _DigestWriter, child: SnapshotEntry) -> None:- child_digest = child.sha256 or child.tree_digest or ""- name = PurePosixPath(child.path).name- digest.update(- f"{name}\0{child.type}\0{child.mode:o}\0{child.size}\0{child_digest}\n".encode(- "utf-8"- )- )---def _verify_payload_paths(- payload_root_fd: int,- cache: _DirectoryDescriptorCache,- entries: _ManifestIndex,-) -> None:- root_info = os.fstat(payload_root_fd)- orders = _new_directory_order(- error_type=MemorySnapshotVerificationError,- message="Memory snapshot payload cannot be read",- )- try:- stack = [- _DirectoryWalkFrame(- node=None,- before=_directory_identity(root_info),- child_order=_scan_directory_order(- orders,- payload_root_fd,- error_type=MemorySnapshotVerificationError,- message="Memory snapshot payload cannot be read",- ),- )- ]- while stack:- frame = stack[-1]- child_name = _next_directory_name(- orders,- frame.child_order,- error_type=MemorySnapshotVerificationError,- message="Memory snapshot payload cannot be read",- )- if child_name is None:- stack.pop()- descriptor = cache.open(- frame.node,- "Memory snapshot payload directory",- )- try:- if _directory_identity(os.fstat(descriptor)) != frame.before:- raise MemorySnapshotVerificationError(- "Memory snapshot payload changed during verification"- )- finally:- os.close(descriptor)- continue-- child_node = _RelativeNode(frame.node, child_name)- parent_fd = cache.open(- frame.node,- "Memory snapshot payload directory",- )- try:- info = os.stat(- child_name,- dir_fd=parent_fd,- follow_symlinks=False,- )- except OSError as error:- raise MemorySnapshotVerificationError(- "Memory snapshot payload cannot be read"- ) from error- finally:- os.close(parent_fd)- if stat.S_ISLNK(info.st_mode) or not (- stat.S_ISREG(info.st_mode) or stat.S_ISDIR(info.st_mode)- ):- raise MemorySnapshotVerificationError(- "Memory snapshot payload has an unsafe entry"- )- try:- if stat.S_ISREG(info.st_mode):- _require_regular_private(info, "Memory snapshot payload file")- else:- _require_directory_private(info, "Memory snapshot payload directory")- except MemorySnapshotUnsafePathError as error:- raise MemorySnapshotVerificationError(- "Memory snapshot payload has an unsafe entry"- ) from error- path_text = _validated_relative_path("/".join(_node_components(child_node)))- if entries.entry(path_text) is None and not (- stat.S_ISDIR(info.st_mode) and entries.has_descendant(path_text)- ):- raise MemorySnapshotVerificationError(- "Memory snapshot payload has unmanifested entries"- )- if stat.S_ISDIR(info.st_mode):- descriptor = cache.open(- child_node,- "Memory snapshot payload directory",- )- try:- opened = os.fstat(descriptor)- if (opened.st_dev, opened.st_ino) != (info.st_dev, info.st_ino):- raise MemorySnapshotVerificationError(- "Memory snapshot payload changed during verification"- )- stack.append(- _DirectoryWalkFrame(- node=child_node,- before=_directory_identity(opened),- child_order=_scan_directory_order(- orders,- descriptor,- error_type=MemorySnapshotVerificationError,- message="Memory snapshot payload cannot be read",- ),- )- )- finally:- os.close(descriptor)- finally:- orders.close()---def _descendant_bounds(path: str) -> tuple[str, str]:- # Canonical manifest paths use '/' as the separator. Replacing that final- # separator with its immediate successor creates an exact indexed range for- # every descendant without relying on LIKE escaping.- return f"{path}/", f"{path}0"---def _entry_from_row(row: Sequence[object]) -> SnapshotEntry:- return SnapshotEntry(- path=str(row[0]),- type=row[1], # type: ignore[arg-type]- mode=int(row[2]),- size=int(row[3]),- sha256=None if row[4] is None else str(row[4]),- tree_digest=None if row[5] is None else str(row[5]),- )---def _file_sha256(path: Path) -> str:- flags = strict_file_read_flags()- descriptor = os.open(path, flags)- digest = hashlib.sha256()- try:- before = os.fstat(descriptor)- _require_regular_private(before, "Memory snapshot digest target")- size = 0- while True:- chunk = os.read(descriptor, _COPY_CHUNK_BYTES)- if not chunk:- break- digest.update(chunk)- size += len(chunk)- after = os.fstat(descriptor)- stable = (- before.st_dev,- before.st_ino,- before.st_size,- before.st_mtime_ns,- ) == (- after.st_dev,- after.st_ino,- after.st_size,- after.st_mtime_ns,- )- if not stable or size != before.st_size:- raise MemorySnapshotVerificationError("Memory snapshot changed during digest")- finally:- os.close(descriptor)- return digest.hexdigest()---def _file_sha256_at(parent_fd: int, name: str) -> str:- descriptor = os.open(- name,- strict_file_read_flags(),- dir_fd=parent_fd,- )- digest = hashlib.sha256()- try:- before = os.fstat(descriptor)- try:- _require_regular_private(before, "Memory snapshot digest target")- except MemorySnapshotUnsafePathError as error:- raise MemorySnapshotVerificationError(- "Memory snapshot file type changed"- ) from error- size = 0- while True:- chunk = os.read(descriptor, _COPY_CHUNK_BYTES)- if not chunk:- break- digest.update(chunk)- size += len(chunk)- after = os.fstat(descriptor)- stable = (- before.st_dev,- before.st_ino,- before.st_size,- before.st_mtime_ns,- ) == (- after.st_dev,- after.st_ino,- after.st_size,- after.st_mtime_ns,- )- if not stable or size != before.st_size:- raise MemorySnapshotVerificationError(- "Memory snapshot changed during digest"- )- except OSError as error:- raise MemorySnapshotVerificationError(- "Memory snapshot file cannot be read safely"- ) from error- finally:- os.close(descriptor)- return digest.hexdigest()---def _is_sqlite_corruption(error: MemorySnapshotError) -> bool:- if isinstance(error, _MemorySQLiteCorruptionError):- return True- cause = error.__cause__- if not isinstance(cause, sqlite3.DatabaseError):- return False- error_code = getattr(cause, "sqlite_errorcode", None)- return isinstance(error_code, int) and error_code & 0xFF in {- sqlite3.SQLITE_CORRUPT,- sqlite3.SQLITE_NOTADB,- }---def _call_log_fileset_state(- home: Path,- database: Path,-) -> dict[str, os.stat_result]:- directory_info = _managed_source_info(home, database.parent)- if directory_info is None:- return {}- _require_directory_private(directory_info, "Memory call-log directory")- directory_fd = _open_directory(database.parent, "Memory call-log directory")- try:- return _call_log_fileset_state_at(directory_fd, database.name)- finally:- os.close(directory_fd)---def _call_log_fileset_state_at(- directory_fd: int,- database_name: str,-) -> dict[str, os.stat_result]:- files: dict[str, os.stat_result] = {}- for member, suffix in _CALL_LOG_FILESET:- try:- info = os.stat(- f"{database_name}{suffix}",- dir_fd=directory_fd,- follow_symlinks=False,- )- except FileNotFoundError:- continue- _require_regular_private(info, "Memory call-log file")- files[member] = info- return files---def _call_log_fileset_identity(- files: Mapping[str, os.stat_result],-) -> dict[str, tuple[int, int, int, int, int, int, int]]:- return {- member: (- info.st_dev,- info.st_ino,- info.st_mode,- info.st_nlink,- info.st_size,- info.st_mtime_ns,- info.st_ctime_ns,- )- for member, info in files.items()- }---def _call_log_has_sqlite_header(home: Path, database: Path) -> bool:- directory_info = _managed_source_info(home, database.parent)- if directory_info is None:- raise MemorySnapshotError("Memory call-log changed during snapshot")- _require_directory_private(directory_info, "Memory call-log directory")- directory_fd = _open_directory(database.parent, "Memory call-log directory")- database_fd: int | None = None- try:- database_fd = os.open(- database.name,- strict_file_read_flags(),- dir_fd=directory_fd,- )- before = os.fstat(database_fd)- _require_regular_private(before, "Memory call-log file")- header = os.read(database_fd, 16)- after = os.fstat(database_fd)- if (- before.st_dev,- before.st_ino,- before.st_mode,- before.st_size,- before.st_mtime_ns,- ) != (- after.st_dev,- after.st_ino,- after.st_mode,- after.st_size,- after.st_mtime_ns,- ):- raise MemorySnapshotError("Memory call-log changed during snapshot")- return header == b"SQLite format 3\x00"- finally:- if database_fd is not None:- os.close(database_fd)- os.close(directory_fd)---def _sqlite_sidecars(path: Path) -> tuple[Path, Path, Path]:- return (- path.with_name(f"{path.name}-wal"),- path.with_name(f"{path.name}-shm"),- path.with_name(f"{path.name}-journal"),- )---def _require_expected_target(info: os.stat_result, kind: SnapshotSurfaceKind, *, sidecar: bool) -> None:- if stat.S_ISLNK(info.st_mode):- raise MemorySnapshotUnsafePathError("Memory restore refuses a symlink target")- if sidecar or kind in {"sqlite", "call_log"}:- _require_regular_private(info, "Memory restore file target")- else:- _require_directory_private(info, "Memory restore tree target")---def _remove_safe_path(- home: Path,- path: Path,-) -> None:- try:- remove_confined_path(home, path)- except ConfinedFilesystemError as error:- raise MemorySnapshotUnsafePathError(- "Memory snapshot path could not be removed safely"- ) from error---def _remove_safe_entry(- parent_fd: int,- name: str,- *,- expected_identity: tuple[int, int],-) -> None:- try:- remove_anchored_entry(- parent_fd,- name,- expected_identity=expected_identity,- )- except ConfinedFilesystemError as error:- raise MemorySnapshotUnsafePathError(- "Memory snapshot entry could not be removed safely"- ) from error---def _replace_safe_path(home: Path, source: Path, destination: Path) -> None:- try:- replace_confined(home, source, destination)- except ConfinedFilesystemError as error:- raise MemorySnapshotUnsafePathError(- "Memory snapshot entry could not be replaced safely"- ) from error---def _fsync_file(path: Path) -> None:- flags = strict_file_read_flags()- descriptor = os.open(path, flags)- try:- os.fsync(descriptor)- finally:- os.close(descriptor)---def _fsync_directory(path: Path) -> None:- try:- fsync_confined_directory(path)- except ConfinedFilesystemError as error:- raise MemorySnapshotUnsafePathError(- "Memory directory could not be synchronized safely"- ) from errordiff --git a/core/memory/store.py b/core/memory/store.pyindex 2444bb048..d048f5303 100644--- a/core/memory/store.py+++ b/core/memory/store.py@@ -3090,7 +3090,7 @@ class MemoryStore:return refresheddef release_clear_fence(self) -> MemoryMeta:- """Release admission after an abort restored the pre-clear surfaces."""+ """Release admission after the marker-owned clear sweep completes."""now = utc_now_iso()with self._transaction() as conn:@@ -3108,8 +3108,21 @@ class MemoryStore:raise RuntimeError("Memory metadata disappeared while releasing clear")return refreshed- def reset_for_clear(self, *, target_epoch: int | None = None) -> MemoryMeta:- """Clear SQLite state at an exact, replay-safe target epoch."""+ def reset_for_clear(+ self,+ *,+ target_epoch: int | None = None,+ release_clear_fence: bool = True,+ ) -> MemoryMeta:+ """Clear SQLite state at an exact, replay-safe target epoch.++ ``release_clear_fence=False`` is used by the marker-owned multi-surface+ sweep so queue reset cannot reopen admission before the other surfaces+ have reached their terminal state.+ """++ if not isinstance(release_clear_fence, bool):+ raise TypeError("release_clear_fence must be a bool")with self._transaction() as conn:meta = self._ensure_meta_in_connection(conn)@@ -3138,7 +3151,7 @@ class MemoryStore:conn.execute("""UPDATE memory_meta- SET epoch = ?, clear_in_progress = 0,+ SET epoch = ?, clear_in_progress = ?,last_provider_timestamp_ms = 0, missed_count = 0,last_success_at = NULL, last_error = NULL, last_error_at = NULL,processing_fault_kind = NULL, processing_fault_since = NULL,@@ -3147,7 +3160,7 @@ class MemoryStore:processing_recovery_generation = NULL, updated_at = ?WHERE singleton = 1""",- (epoch, now),+ (epoch, 0 if release_clear_fence else 1, now),)refreshed = self._meta_in_connection(conn)if refreshed is None:diff --git a/docs/MEMORY.md b/docs/MEMORY.mdindex 81b7f48c6..4941ec77c 100644--- a/docs/MEMORY.md+++ b/docs/MEMORY.md@@ -99,12 +99,12 @@ finish before starting another one.### Clear Memory DataBefore Reinitialize Memory, use **Clear Memory Data** when retained Memory data or the-call-log database is corrupt. Clear Memory Data creates and verifies a private snapshot-of the queue, provider data, call log, and pinned attachments, then removes only-those four Avibe-owned surfaces under a maintenance journal. It does not delete+call-log database is corrupt. Clear Memory Data records a durable intent marker, then+removes only the queue, provider data, call log, and pinned attachments through their+idempotent deletion primitives. Clear is irreversible; it does not deletethe `memory` or `state/memory` roots themselves, original Avibe chats, copies-already sent to providers, or data outside those surfaces (including logs,-backups, and user-created snapshots); it is not a secure wipe.+already sent to providers, or data outside those surfaces (including logs or+user-created snapshots); it is not a secure wipe.Clear Memory Data is also the explicit discard path for a timed-out or otherwiseunknown provider add. It removes the retained `manual_required` queue evidence@@ -112,12 +112,14 @@ and pinned attachment bundle, clears that session's local fence, and neverreplays the ambiguous add. Because the provider outcome is unknown, Clear cannotremove a copy that may already have reached the provider.-If Clear Memory Data is interrupted, Processing Record shows explicit **Resume Clear**-and **Abort and restore** actions for that operation. **Resume Clear** continues-the journaled deletion; **Abort and restore** restores every surface from the-verified snapshot and is available only after the initial snapshot is complete.-Nothing resumes automatically, and Memory remains fenced until one action-reaches a terminal result.+If Clear Memory Data is interrupted, the marker remains durable and Processing Record+shows its operation, deleting/failed state, timestamp, and error code. Boot automatically+retries the four idempotent deletion primitives; Memory remains fenced until the marker+is removed after all surfaces finish. A failed marker can be retried by Clear Memory Data.+Unreadable markers fail closed without preventing service startup. A retired Clear journal+is never semantically migrated: an open row or failed bounded probe creates a fresh failed+marker that asks the user to run Clear again, while terminal residue is removed best effort.+Retired backup and snapshot residue is also cleaned best effort and never blocks Memory.4. **Reinitialize Memory**: Use it only as a last resort when the earlier actionscannot recover Memory. It is available on the Memory Runtime card underdiff --git a/docs/plans/everos-memory-remaining-implementation.md b/docs/plans/everos-memory-remaining-implementation.mdindex 2a688e0fc..74e16f39f 100644--- a/docs/plans/everos-memory-remaining-implementation.md+++ b/docs/plans/everos-memory-remaining-implementation.md@@ -16,8 +16,9 @@ The public Memory seam remains provider-neutral:- `SessionFlushCoordinator` exclusively owns session generations, fences, explicit flushes, and flushrecovery. `MemoryWorker` only claims and delivers add rows through the coordinator.- `AttachmentPinStore` owns private durable attachment bundles and crash-safe release.-- `MemoryClearJournal` and `MemorySnapshotManager` own destructive clear recovery. Runtime lifecycle- code only establishes the maintenance fence, stops/starts owned processes, and invokes these seams.+- `MemoryMaintenance` owns the durable clear-intent marker and four idempotent deletion primitives.+ Runtime lifecycle code only establishes the maintenance fence, stops/starts owned processes, and+ invokes this seam.- Processing Record directly projects public EverOS `/health`, existing call-log/processing provenance,and confirmed Avibe settlement facts. The outbox and lifecycle do not compose product status.@@ -174,40 +175,25 @@ files and finalizes the bundle row. Boot reconciliation completes `releasing` buunreferenced staging/orphan bundles inside the private root. Pending and `manual_required` bundles arenever removed.-## 6. Snapshot and clear journal--`MemorySnapshotManager` owns queue SQLite backup, provider root, call-log SQLite backup, and attachment-bundles. It excludes sockets and runtime artifacts. Manifests contain only effective-home-relative-paths, types, modes, sizes, per-file hashes, and tree digests. Snapshot creation rejects symlinks and-special files, fsyncs all bytes and the manifest, and verifies it before returning. Restore verifies all-digests and relocates paths relative to the current effective home.--The independent journal is `<effective_home>/state/memory/clear-journal.sqlite`; snapshots live under-`<effective_home>/state/memory/clear-snapshots/<operation_id>/`. It has:--- `clear_operation`: opaque operation/operator IDs, state, timestamps, pre/target epochs, relative- snapshot path, destructive-started flag, closed error, and one unique open slot;-- `clear_surface`: one of `queue`, `provider`, `call_log`, `attachments`, its relative snapshot path,- pre-clear/snapshot digests, and `pending|snapshotted|deleted|restored` state;-- append-only `clear_event`: operation, event, optional surface, time, and closed error.--The only transitions are `preparing -> prepared -> deleting -> completed` and any non-terminal state-to `recovery_needed`; explicit abort ends in `aborted`. Terminal headers and all events are immutable.--Clear ordering under the runtime/root maintenance fence is: create durable journal header; pause add-and flush coordination; stop recorder/sidecar without deleting data; snapshot and verify all four-surfaces; mark prepared; mark destructive start; reset queue/epoch, delete provider, delete call log,-and delete attachment bundles while recording each idempotent substep; then mark completed. Only after-completion may claims/runtime resume and the restorable snapshot be garbage-collected.--A process restart with any open journal only surfaces `recovery_needed`; capture, recall, worker,-restart, and backup stay fenced. `resume_clear(operation_id, operator_ref)` continues exact pending-substeps. `abort_clear(...)` first verifies the complete snapshot, restores every covered surface and-records each restore, then marks aborted. Missing/corrupt snapshots fail closed. Clear never releases a-`manual_required` fence by itself. Concurrent start permits exactly one open operation.--Ordinary backup is blocked while a clear journal is open and includes completed journal audit records-otherwise, so a restore cannot combine incompatible surface generations.+## 6. Durable clear intent++Clear Memory Data uses `<effective_home>/state/memory/clear-intent.json` as its single+source of truth. Every marker contains a new UUID4 operation id. The marker also contains operator reference,+pre/target epochs, `deleting|failed` state, error code, and creation/update timestamps. It+is atomically written through a same-directory temporary file, file fsync, replace, and+parent-directory fsync.++The operation fences claims and runs exactly four idempotent deletion primitives: queue+reset, provider-root recreation, call-log clear, and attachment clear. Completion clears+the in-progress flag and removes the marker. An interrupted or failed marker is retried+automatically on the next reconcile; corrupt or unreadable marker state fails closed for+Memory projection while service startup continues. An explicit Clear request can replace+a corrupt marker. A legacy Clear journal is not semantically migrated: one bounded open-row+probe either permits best-effort deletion or creates a fresh failed marker with+`memory_clear_legacy_state_requires_rerun`. Legacy backup/restore and Clear snapshot residue+is best-effort cleanup only. There is no backup/restore journal or user-facing resume/abort API.+The complete contract and three-tier fault model live in+`docs/plans/memory-clear-durable-intent.md`.## 7. Recall policy@@ -289,8 +275,8 @@ absolute paths, attachment metadata/hashes, vectors, or raw exceptions. `manual_The UI merges status and processing-log tabs into one Processing Record view with explicit Refresh,runtime/capabilities, source availability, anomalies/recovery, recent timeline, and existing detail.It does not poll the composite status every four seconds. Disabled Memory still renders retained local-recovery/anomaly evidence. Clear recovery may offer its distinct resume/abort commands;-`manual_required` has no command. Embedding configuration lock reads a separate cheap local+recovery/anomaly evidence. Clear recovery is marker-owned and has no user-facing resume/abort+commands; `manual_required` has no command. Embedding configuration lock reads a separate cheap local`data_exists` maintenance fact rather than health or a deep provider-root scan. All copy uses i18n.## 9. File scope@@ -317,9 +303,9 @@ multi-run search, platform aliasing, or assistant/tool/agent capture.- Attachments: confinement/symlink/special-file/owner/mode checks; byte limits; mutation detection;fault injection at copy/fsync/rename/DB boundaries; original deletion after accepted pin; duplicatecleanup; confirmed release; manual/stale retention; boot release/orphan convergence; no leakage.-- Clear/snapshot: crash after journal/snapshot/each delete/completion boundary; zero automatic deletion- on boot; one concurrent open operation; idempotent resume; four-surface abort restore with exact- digest; corrupt snapshot fail-closed; operation fences; immutable audit; open-journal backup block.+- Clear intent: crash after marker creation, each deletion primitive, queue-fence clearing, and marker+ removal; automatic boot retry; one marker-owned operation; idempotent four-surface deletion; corrupt+ marker fail-closed projection; operation fences; legacy journal migration.- Processing Record: available/stale/unavailable health; Cascade unhealthy as a valid observation;independently locked/corrupt/schema-incompatible sources; confirmed-only timeline; anomalies andclear recovery; authorization, pagination, bounds, and redaction; no active probes/root scans.diff --git a/docs/plans/memory-clear-durable-intent.md b/docs/plans/memory-clear-durable-intent.mdnew file mode 100644index 000000000..2696ddc1d--- /dev/null+++ b/docs/plans/memory-clear-durable-intent.md@@ -0,0 +1,174 @@+# Memory Clear Durable Intent++This document consolidates issue #1392 Rev 2 and the owner-approved Rev 2.1+amendment. It is the implementation contract for Memory Clear.++## Decision++Clear Memory Data is an irreversible, idempotent re-run. The backup/restore and+Clear snapshot stacks are removed. There is no user-facing Resume or Abort+choice: a Clear written by this implementation continues automatically until it+finishes.++The implementation keeps and orchestrates these four high-level deletion+primitives; it does not replace them with raw directory deletion:++1. queue: clear queue tables and call `store.reset_for_clear(target_epoch=...)`+2. provider: call `ProviderRootOwner.recreate_empty()`+3. call log: call `clear_call_log()`+4. attachments: call `MemoryModule.clear_attachments()`++The confined filesystem primitives remain shared infrastructure for Clear,+Reset, and artifact installation.++## Durable marker++The single authority is `<effective_home>/state/memory/clear-intent.json`. It is+written before the first surface deletion and removed only after all four+surfaces complete.++Schema version 1 contains:++- `operation_id`: a new UUIDv4+- `operator_ref`: the initiating operator provenance+- `pre_epoch` and `target_epoch`+- `state`: `deleting` or `failed`+- nullable `error_code`+- `created_at` and `updated_at`++`target_epoch` is fixed at marker creation and never recomputed. Replays pass+that value to the queue reset, whose two-state acceptance allows either+`pre_epoch` or `target_epoch` and prevents a crash from advancing the epoch+twice.++Every create or update uses a same-directory temporary file, file fsync,+atomic replace, and parent-directory fsync. Marker operations run under the+existing maintenance lifecycle lock and `MemoryOperationLease`; there is no+cross-process protocol beyond same-host lease mutual exclusion.++The marker is the source of truth for an open Clear. The queue's+`memory_meta.clear_in_progress` flag is set after the marker is durable. On+completion the four surfaces finish, the queue fence is released, and the+marker is removed. A crash in a terminal step remains recognizable and is+settled on the next reconcile.++## Boot and admission++Boot reconcile keeps Memory fenced whenever a readable marker exists. A marker+written by this implementation is changed from `failed` to `deleting`, the four+idempotent primitives run again, and Memory is unfenced only after terminal+settlement. A failed sweep persists a failed marker and leaves Memory fenced;+service startup continues.++An explicit user Clear may replace an unreadable marker or the failed marker+created for legacy state. It derives a fresh epoch pair from the current store,+writes a new UUIDv4 operation, and converges through the normal four-surface+sweep.++## Fault model++### Tier 1: exact recovery required++- Process crash or power loss at any instruction boundary, assuming POSIX+ same-directory rename atomicity and the marker fsync order above.+- Marker durability failures, including fsync, rename, unlink, and parent+ directory sync failures. Memory fails closed through a persisted failed+ marker when writable, or an in-memory authority error otherwise; service+ startup proceeds.+- Same-host mutual exclusion through the maintenance lifecycle lock and+ `MemoryOperationLease`. A lease loser defers and does not mutate shared state.++### Tier 2: fail-closed is sufficient++- Any corrupted, truncated, oversized, type-invalid, or otherwise+ uninterpretable marker or legacy journal content is refused. Memory is+ fenced, the failed projection is surfaced, and an explicit Clear replaces+ the state. The implementation does not distinguish corruption causes,+ preserve corrupt fields, or enumerate malformed shapes beyond one bounded+ read and schema check.+- Filesystem anomalies under `state/memory/`, including dangling symlinks,+ permission errors, and files disappearing during a read, follow the same+ unreadable-state rule.++### Tier 3: out of scope or best effort++- Legacy backup/restore residue and Clear snapshot cleanup is best effort:+ warn and continue without blocking Memory or service startup.+- Adversarial local tampering beyond Tier 2 refusal is out of scope because the+ local user owns these files.+- Behavior of foreign or older processes beyond lease mutual exclusion is out+ of scope.+- Byte-perfect semantic migration of the legacy Clear journal is not provided.++## Legacy Clear journal++There is no semantic migration and no preservation of legacy `operation_id`,+`operator_ref`, or `target_epoch`. The implementation does not validate legacy+state or resolution vocabularies, row cardinality, surface receipts, or field+types beyond this bounded probe:++1. Detect `clear-journal.sqlite` with `lexists`, so dangling symlinks count.+2. Attempt one bounded query asking whether any row has a non-null open slot.+3. If the query succeeds with no open row, best-effort confined-delete the+ journal and do not fence.+4. If the query fails for any reason or finds any open row, write a fresh failed+ marker with a new UUIDv4, epochs derived from current `memory_meta`, and+ `memory_clear_legacy_state_requires_rerun`; then best-effort delete the+ journal. Boot does not replay this marker. An explicit Clear replaces it.+5. If a marker and journal both exist, the marker wins and the journal is+ best-effort deleted.++`memory_clear_legacy_abort_unsupported` and all abort-specific handling are+removed.++## API, UI, and projection++The Resume and Abort methods and routes are removed across runtime,+maintenance, internal server/client, UI routes, authorization, API context, and+frontend types. A stale page receives 404 and refreshes into the current shape.++Processing Record replaces `clear_recovery` with:++```json+{+ "clear_in_progress": {+ "operation_id": "uuid",+ "state": "deleting",+ "occurred_at": "2026-08-13T00:00:00Z",+ "error_code": null+ }+}+```++`state` may be `deleting` or `failed`. Marker read failure projects `failed`+with `memory_clear_marker_unreadable`. A row appears in the failures projection+only when its state is `failed`. Backend, UI, and tests consume this one shape.++English and Chinese copy must include+`memory_clear_legacy_state_requires_rerun` and must not retain the abort-specific+error.++## Persisted residue++The retired backup/restore journal, backup directory, and Clear snapshot+directory are removed on boot with confined best-effort deletion. Failure logs+a warning and does not fence Memory or fail service startup.++## Required evidence++- `MEMORY-CLEAR-201`: Clear discards retained ambiguous local evidence through+ the four deletion primitives and permits later delivery.+- `MEMORY-CLEAR-202`: a marker written by this implementation is retried+ automatically on boot.+- The marker is durable before the first delete and survives interruption after+ any surface.+- Re-run does not advance the epoch twice, each primitive is repeatable, and+ marker removal occurs only after all surfaces.+- Terminal marker-removal failure stays recognizable and converges.+- Corrupt markers fail closed without stopping service startup.+- The legacy probe distinguishes only open versus no-open; probe failure and an+ open row create the fresh rerun-required marker, while terminal residue does+ not fence.+- Lease losers defer without mutation and legacy cleanup remains best effort.++Four-platform Incus verification is a residual post-merge check.diff --git a/docs/plans/memory-host-architecture-review.md b/docs/plans/memory-host-architecture-review.mdnew file mode 100644index 000000000..cd973b008--- /dev/null+++ b/docs/plans/memory-host-architecture-review.md@@ -0,0 +1,29 @@+# Memory Host Architecture Review++Issue 1392 Rev 2 removes the backup/snapshot state machines and makes Clear Memory+Data a marker-owned, idempotent operation.++## Verified ownership++- `MemoryRuntime` owns lifecycle admission, fences, and boot reconciliation.+- `MemoryMaintenance` owns the clear-intent marker and calls exactly four deletion+ primitives: queue reset, provider-root recreation, call-log clear, and attachment clear.+- `MemoryProcessingRecord` projects the marker as `clear_in_progress`; failures expose+ only the failed marker state and error code.+- UI routes and the Web UI only forward Clear and display read-only marker state.++## Persistence contract++`state/memory/clear-intent.json` is atomically written with a same-directory temporary+file, file fsync, replace, and parent-directory fsync. The marker is the source of truth;+the legacy clear journal is migrated at boot when it contains an open operation and then+removed. Corrupt marker/journal state fences Memory projection without blocking service+startup. Legacy backup journals, backup directories, and snapshot directories are+best-effort boot cleanup only.++## Safety properties++The runtime holds the exclusive maintenance fence while deleting, sets the queue clear+fence before the first surface, and removes the marker only after every surface succeeds.+An interrupted or failed marker is retried on the next reconcile, so no restore path or+operator action can accidentally resurrect partially deleted data.diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 96a0c7329..6533cb5db 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -8,17 +8,17 @@ navigation:- Read that capability's observations.yaml.- Read the listed scenario test files before changing production code.capabilities:- - id: memory_clear_recovery- name: Journaled Memory Clear recovery+ - id: memory_clear_intent+ name: Durable Memory Clear intentstatus: activecatalog: tests/scenarios/memory_clear_recovery/catalog.yamlobservations: tests/scenarios/memory_clear_recovery/observations.yamlscenario_tests:- tests/test_memory_maintenance.py+ - tests/test_memory_runtime.pyunit_or_contract_tests:- tests/test_memory_store.py- - tests/test_memory_clear_journal.py- - tests/test_memory_clear_snapshot_storage.py+ - tests/test_memory_clear_intent.py- id: memory_rebuild_recoveryname: Confirmed Memory embedding rebuild recoverystatus: activediff --git a/tests/scenarios/memory_clear_recovery/catalog.yaml b/tests/scenarios/memory_clear_recovery/catalog.yamlindex 7eae27955..142768ad9 100644--- a/tests/scenarios/memory_clear_recovery/catalog.yaml+++ b/tests/scenarios/memory_clear_recovery/catalog.yaml@@ -1,9 +1,10 @@version: 1capability:- id: memory_clear_recovery- name: Journaled Memory Clear recovery+ id: memory_clear_intent+ name: Durable Memory Clear intentcanonical_tests:- tests/test_memory_maintenance.py+ - tests/test_memory_runtime.pystatus_legend:covered: scenario coverage existspartial: unit or contract coverage exists but the closed loop is incomplete@@ -11,18 +12,29 @@ status_legend:gap: not covered yetscenarios:- id: MEMORY-CLEAR-201- name: Clear discards an unknown add and restores session delivery+ name: Clear discards retained local evidence and converges after interruptionstatus: coveredkind: recoverylayer: scenario- test: tests/test_memory_maintenance.py::test_clear_discards_manual_required_fence_and_allows_new_delivery+ test: tests/test_memory_runtime.py::test_memory_clear_201_discards_manual_required_evidence_and_allows_new_deliveryactor: Memory Settings usertrigger: A provider add times out after submission and fences its session as manual_requiredgiven: The queue retains the ambiguous payload and pinned attachment bundle without replaying itwhen: The user confirms Clear Memory Data- then: The journaled Clear removes the retained evidence, advances the epoch, and a later capture in the same logical session delivers normally+ then: Marker-owned Clear removes retained evidence, advances the epoch, and a later capture can deliver normallyexpected_outputs:+ - Clear completes through the four existing idempotent deletion primitives- Maintenance advertises can_clear while the manual_required fence exists- - Clear completes through the existing snapshot and journal surfaces- The ambiguous payload and attachment bundle are removed without another provider add- The session is unfenced and a subsequent capture reaches the provider+ - id: MEMORY-CLEAR-202+ name: Failed marker is retried automatically on boot+ status: covered+ kind: recovery+ layer: scenario+ test: tests/test_memory_runtime.py::test_runtime_reconcile_completes_readable_clear_marker_on_boot+ actor: Memory runtime+ trigger: A clear primitive fails after the marker is durable+ given: Processing Record projects a failed clear marker and Memory remains fenced+ when: The next runtime reconcile runs+ then: The marker returns to deleting, all four primitives are retried idempotently, and the marker is removed on successdiff --git a/tests/scenarios/memory_clear_recovery/observations.yaml b/tests/scenarios/memory_clear_recovery/observations.yamlindex 584b03e18..df597f26e 100644--- a/tests/scenarios/memory_clear_recovery/observations.yaml+++ b/tests/scenarios/memory_clear_recovery/observations.yaml@@ -1,15 +1,16 @@version: 1-capability: memory_clear_recovery+capability: memory_clear_intentobservations:- id: OBS-MEMORY-CLEAR-001- source: issue_1374_runtime_reproduction+ source: issue_1392_rev2related_scenarios:- MEMORY-CLEAR-201- summary: An ordinary provider add timeout is conservatively retained as manual_required, but that local fence must not disable journaled Clear.+ summary: An ordinary provider add timeout is conservatively retained as manual_required, but that local fence must not disable marker-owned Clear.previous_assumption: Unknown provider outcomes had to block Clear to preserve their evidence.- observed_behavior: Clear already snapshots the queue and attachment tree before deletion, can restore them on Abort, and resets the queue at a new epoch on completion.+ observed_behavior: Clear records an atomic intent marker, resets the queue at a new epoch, and retries the four idempotent deletion primitives after interruption.required_updates:- keep automatic replay forbidden for unknown outcomes- allow Clear to discard retained local evidence and release pinned attachments- - preserve the existing Resume Clear and Abort and restore recovery contract+ - remove the obsolete snapshot/Resume/Abort contract+ - project failed marker state without blocking service startup- prove a later capture in the same logical session can deliverdiff --git a/tests/test_internal_client_timeouts.py b/tests/test_internal_client_timeouts.pyindex 51c49e3b0..ed839a71f 100644--- a/tests/test_internal_client_timeouts.py+++ b/tests/test_internal_client_timeouts.py@@ -38,7 +38,6 @@ from vibe.internal_client import (MEMORY_MAINTENANCE_TIMEOUT_SECONDS,memory_archive_session,memory_clear,- memory_clear_recovery,memory_profile,memory_final_flush,memory_failures,@@ -168,11 +167,7 @@ def test_restart_client_has_no_reporting_timeout() -> None:def test_clear_clients_have_no_reporting_timeout() -> None:- # Snapshot and restore copy user-owned trees whose size has no runtime- # bound. A transport deadline would report failure while the controller's- # journaled operation continues and make a destructive retry possible.- for operation in (memory_clear, memory_clear_recovery):- assert "timeout" not in inspect.signature(operation).parameters+ assert "timeout" not in inspect.signature(memory_clear).parametersdef test_install_client_covers_the_dependency_job_budget() -> None:diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex 404d331f2..d5a2db60f 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -607,7 +607,7 @@ def test_memory_recovery_reads_resolve_only_signed_ui_operators() -> None:"status": "ok","data_exists": False,"can_clear": True,- "clear_recovery": None,+ "clear_in_progress": None,}controller = _build_controller_double()@@ -1072,7 +1072,7 @@ def test_processing_record_degrades_signed_operator_lookup_failure() -> None:"maintenance": {"source": {"status": "unavailable"},"can_clear": False,- "clear_recovery": None,+ "clear_in_progress": None,},}diff --git a/tests/test_memory_backup_restore_journal.py b/tests/test_memory_backup_restore_journal.pydeleted file mode 100644index cf00bbd24..000000000--- a/tests/test_memory_backup_restore_journal.py+++ /dev/null@@ -1,123 +0,0 @@-from __future__ import annotations--from pathlib import Path--import pytest--from core.memory.backup_restore_journal import (- BackupRestoreCASMismatch,- BackupRestoreConflict,- MemoryBackupRestoreJournal,- MemoryBackupRestoreJournalError,-)-from core.memory.snapshot import MemorySnapshotManager--from .test_memory_snapshot import _build_all_surfaces---def _snapshot(tmp_path: Path):- home = tmp_path / "home"- connection = _build_all_surfaces(home)- connection.close()- return home, MemorySnapshotManager(home).create("ordinary-backup")---def test_restore_journal_persists_boot_retry_and_terminal_audit(tmp_path: Path) -> None:- home, snapshot = _snapshot(tmp_path)- journal = MemoryBackupRestoreJournal(home)-- started = journal.start(snapshot)- restarted = MemoryBackupRestoreJournal(home)- recovery = restarted.mark_boot_recovery_needed()-- assert recovery is not None- assert recovery.operation_id == started.operation_id- assert recovery.state == "recovery_needed"- assert recovery.execution_token is None- assert recovery.digest_mapping() == snapshot.surface_digests()-- retry = restarted.claim_retry(- recovery.operation_id,- expected_revision=recovery.revision,- actor_ref="system:boot",- )- assert retry.state == "restoring"- assert retry.attempt_count == 2- assert retry.execution_token is not None-- completed = restarted.mark_completed(- retry.operation_id,- expected_revision=retry.revision,- execution_token=retry.execution_token,- actor_ref="system:boot",- )- assert completed.state == "completed"- assert completed.terminal_at is not None- assert restarted.get_open_operation() is None- assert [event.event for event in restarted.get_events(completed.operation_id)] == [- "started",- "recovery_needed",- "retry_started",- "completed",- ]-- with pytest.raises(BackupRestoreCASMismatch):- restarted.mark_completed(- completed.operation_id,- expected_revision=retry.revision,- execution_token=retry.execution_token,- )---def test_restore_journal_keeps_one_open_operation_until_completion(tmp_path: Path) -> None:- home, snapshot = _snapshot(tmp_path)- journal = MemoryBackupRestoreJournal(home)- operation = journal.start(snapshot)-- with pytest.raises(BackupRestoreConflict):- journal.start(snapshot)- with pytest.raises(BackupRestoreConflict):- journal.assert_idle()-- recovery = journal.mark_recovery_needed(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token or "",- )- assert recovery.state == "recovery_needed"- assert recovery.last_error == "memory_clear_failed"- with pytest.raises(BackupRestoreCASMismatch):- journal.claim_retry(- recovery.operation_id,- expected_revision=operation.revision,- actor_ref="system:runtime",- )---def test_restore_journal_translates_hardening_failure_after_durable_commit(- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- home, snapshot = _snapshot(tmp_path)- journal = MemoryBackupRestoreJournal(home)-- from core.memory import confined_filesystem-- real_chmod = confined_filesystem.os.chmod-- def fail_journal_hardening(target, mode: int) -> None:- if Path(target) == journal.database_path and mode == 0o600:- raise confined_filesystem.ConfinedFilesystemError("unsafe journal")- real_chmod(target, mode)-- monkeypatch.setattr(confined_filesystem.os, "chmod", fail_journal_hardening)-- with pytest.raises(- MemoryBackupRestoreJournalError,- match="Memory backup restore journal files could not be hardened safely",- ):- journal.start(snapshot)-- committed = journal.get_open_operation()- assert committed is not None- assert committed.backup_id == snapshot.snapshot_iddiff --git a/tests/test_memory_clear_intent.py b/tests/test_memory_clear_intent.pynew file mode 100644index 000000000..69f216653--- /dev/null+++ b/tests/test_memory_clear_intent.py@@ -0,0 +1,254 @@+from __future__ import annotations++import json+import os+import sqlite3+import uuid+from pathlib import Path++import pytest++from core.memory.clear_intent import (+ LEGACY_RERUN_ERROR_CODE,+ MARKER_RELATIVE_PATH,+ ClearIntent,+ ClearIntentStore,+ ClearIntentUnreadable,+ cleanup_legacy_backup_storage,+)+++def _write_legacy_journal(home: Path, *, open_slot: object = None) -> Path:+ journal = home / "state/memory/clear-journal.sqlite"+ journal.parent.mkdir(parents=True, exist_ok=True)+ connection = sqlite3.connect(journal)+ connection.execute(+ "CREATE TABLE clear_operation (operation_id, operator_ref, target_epoch, "+ "state, resolution, open_slot)"+ )+ connection.execute(+ "INSERT INTO clear_operation VALUES (?, ?, ?, ?, ?, ?)",+ (b"uninterpretable", None, "not-an-epoch", "foreign", {"bad": "type"}.__str__(), open_slot),+ )+ connection.commit()+ connection.close()+ os.chmod(journal, 0o600)+ return journal+++def test_marker_write_is_atomic_and_round_trips(tmp_path: Path):+ store = ClearIntentStore(tmp_path)+ intent = ClearIntent.new(operator_ref="user-1", pre_epoch=4)++ store.write(intent)++ assert store.load() == intent+ assert not list((tmp_path / "state/memory").glob(".clear-intent.*.tmp"))+++def test_marker_schema_rejects_non_uuid4_and_extra_fields(tmp_path: Path):+ marker = tmp_path / MARKER_RELATIVE_PATH+ marker.parent.mkdir(parents=True)+ marker.write_text(+ json.dumps(+ {+ "schema_version": 1,+ "operation_id": "legacy-operation",+ "operator_ref": "user-1",+ "pre_epoch": 1,+ "target_epoch": 2,+ "state": "deleting",+ "error_code": None,+ "created_at": "now",+ "updated_at": "now",+ "extra": True,+ }+ ),+ encoding="utf-8",+ )++ with pytest.raises(ClearIntentUnreadable):+ ClearIntentStore(tmp_path).load()++[email protected]("schema_version", (True, 1.0))+def test_marker_schema_rejects_non_integer_versions(tmp_path: Path, schema_version: object):+ store = ClearIntentStore(tmp_path)+ intent = ClearIntent.new(operator_ref="user-1", pre_epoch=1)+ payload = {+ "schema_version": schema_version,+ "operation_id": intent.operation_id,+ "operator_ref": intent.operator_ref,+ "pre_epoch": intent.pre_epoch,+ "target_epoch": intent.target_epoch,+ "state": intent.state,+ "error_code": intent.error_code,+ "created_at": intent.created_at,+ "updated_at": intent.updated_at,+ }+ store.path.parent.mkdir(parents=True)+ store.path.write_text(json.dumps(payload), encoding="utf-8")++ with pytest.raises(ClearIntentUnreadable):+ store.load()+++ ("state", "error_code"),+ (("deleting", "memory_clear_failed"), ("failed", None)),+)+def test_marker_schema_rejects_contradictory_state_and_error(+ tmp_path: Path, state: str, error_code: str | None+):+ store = ClearIntentStore(tmp_path)+ intent = ClearIntent.new(operator_ref="user-1", pre_epoch=1)+ payload = {+ "schema_version": 1,+ "operation_id": intent.operation_id,+ "operator_ref": intent.operator_ref,+ "pre_epoch": intent.pre_epoch,+ "target_epoch": intent.target_epoch,+ "state": state,+ "error_code": error_code,+ "created_at": intent.created_at,+ "updated_at": intent.updated_at,+ }+ store.path.parent.mkdir(parents=True)+ store.path.write_text(json.dumps(payload), encoding="utf-8")++ with pytest.raises(ClearIntentUnreadable):+ store.load()+++def test_marker_reader_rejects_oversized_regular_file(tmp_path: Path):+ marker = tmp_path / MARKER_RELATIVE_PATH+ marker.parent.mkdir(parents=True)+ marker.write_bytes(b"{" + b"x" * (16 * 1024) + b"}")++ with pytest.raises(ClearIntentUnreadable):+ ClearIntentStore(tmp_path).load()+++def test_legacy_terminal_journal_is_removed_without_marker(tmp_path: Path):+ journal = _write_legacy_journal(tmp_path)++ intent = ClearIntentStore(tmp_path).reconcile_legacy(current_epoch=7)++ assert intent is None+ assert not journal.exists()+ assert ClearIntentStore(tmp_path).load() is None+++def test_legacy_open_probe_ignores_semantics_and_requires_explicit_rerun(tmp_path: Path):+ journal = _write_legacy_journal(tmp_path, open_slot="foreign-open-token")++ intent = ClearIntentStore(tmp_path).reconcile_legacy(current_epoch=7)++ assert intent is not None+ assert uuid.UUID(intent.operation_id).version == 4+ assert intent.operator_ref == "legacy-clear-journal"+ assert intent.pre_epoch == 7+ assert intent.target_epoch == 8+ assert intent.state == "failed"+ assert intent.error_code == LEGACY_RERUN_ERROR_CODE+ assert not journal.exists()+++def test_legacy_probe_failure_requires_explicit_rerun(tmp_path: Path):+ journal = tmp_path / "state/memory/clear-journal.sqlite"+ journal.parent.mkdir(parents=True)+ journal.write_bytes(b"not sqlite")++ intent = ClearIntentStore(tmp_path).reconcile_legacy(current_epoch=2)++ assert intent is not None+ assert intent.error_code == LEGACY_RERUN_ERROR_CODE+ assert not journal.exists()+++def test_existing_marker_wins_over_legacy_journal(tmp_path: Path):+ store = ClearIntentStore(tmp_path)+ existing = ClearIntent.new(operator_ref="current", pre_epoch=3)+ store.write(existing)+ journal = _write_legacy_journal(tmp_path, open_slot=1)++ assert store.reconcile_legacy(current_epoch=99) == existing+ assert store.load() == existing+ assert not journal.exists()+++def test_legacy_journal_cleanup_failure_does_not_replace_failed_marker(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ journal = _write_legacy_journal(tmp_path, open_slot=1)+ from core.memory import clear_intent++ original_remove = clear_intent.remove_confined_path++ def fail_journal_remove(home: Path, path: Path) -> None:+ if path == journal:+ raise clear_intent.ConfinedFilesystemError("busy")+ original_remove(home, path)++ monkeypatch.setattr(clear_intent, "remove_confined_path", fail_journal_remove)++ intent = ClearIntentStore(tmp_path).reconcile_legacy(current_epoch=4)++ assert intent is not None+ assert ClearIntentStore(tmp_path).load() == intent+ assert journal.exists()+++def test_legacy_residue_cleanup_is_best_effort(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ backup_journal = tmp_path / "state/memory/backup-restore-journal.sqlite"+ backup_file = tmp_path / "state/memory/backups/old/data"+ snapshot = tmp_path / "state/memory/clear-snapshots/old/data"+ for path in (backup_journal, backup_file, snapshot):+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("obsolete", encoding="utf-8")+ from core.memory import clear_intent++ original_remove = clear_intent.remove_confined_path++ def fail_one(home: Path, path: Path) -> None:+ if path == backup_journal:+ raise clear_intent.ConfinedFilesystemError("busy")+ original_remove(home, path)++ monkeypatch.setattr(clear_intent, "remove_confined_path", fail_one)++ assert cleanup_legacy_backup_storage(tmp_path) == (+ "state/memory/backup-restore-journal.sqlite",+ )+ assert backup_journal.exists()+ assert not backup_file.exists()+ assert not snapshot.exists()+++def test_marker_disappearance_during_open_is_treated_as_absent(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ from core.memory import clear_intent++ store = ClearIntentStore(tmp_path)+ store.write(ClearIntent.new(operator_ref="user-1", pre_epoch=1))+ original_open = clear_intent.open_confined_regular_file++ def unlink_before_open(home: Path, path: Path) -> int:+ path.unlink()+ return original_open(home, path)++ monkeypatch.setattr(clear_intent, "open_confined_regular_file", unlink_before_open)++ assert store.load() is None+++def test_dangling_marker_is_fail_closed(tmp_path: Path):+ marker = tmp_path / MARKER_RELATIVE_PATH+ marker.parent.mkdir(parents=True)+ marker.symlink_to(tmp_path / "missing-marker")++ with pytest.raises(ClearIntentUnreadable):+ ClearIntentStore(tmp_path).load()diff --git a/tests/test_memory_clear_journal.py b/tests/test_memory_clear_journal.pydeleted file mode 100644index 2b48cef55..000000000--- a/tests/test_memory_clear_journal.py+++ /dev/null@@ -1,683 +0,0 @@-from __future__ import annotations--import hashlib-import sqlite3-import stat-from concurrent.futures import ThreadPoolExecutor-from pathlib import Path--import pytest--from core.memory.clear_journal import (- ClearBackupBlocked,- ClearOperationCASMismatch,- ClearOperationConflict,- ClearTransitionError,- MemoryClearJournal,- MemoryClearJournalError,-)-from core.memory.snapshot import MemorySnapshot, SnapshotSurfaceReceipt---def _journal(tmp_path: Path) -> MemoryClearJournal:- home = tmp_path / "home"- home.mkdir(mode=0o700)- home.chmod(0o700)- return MemoryClearJournal(home)---def _digest(value: str) -> str:- return hashlib.sha256(value.encode()).hexdigest()---def _snapshot_receipt(journal: MemoryClearJournal, operation_id: str) -> MemorySnapshot:- return MemorySnapshot(- snapshot_id=operation_id,- relative_path=f"state/memory/clear-snapshots/{operation_id}",- manifest_sha256=_digest("manifest"),- entries=(),- surface_receipts=tuple(- SnapshotSurfaceReceipt(- path=surface.relative_path,- present=True,- pre_clear_digest=_digest(f"pre:{surface.name}"),- snapshot_digest=_digest(f"snapshot:{surface.name}"),- )- for surface in journal.surfaces- ),- )---def _record_all_snapshots(journal: MemoryClearJournal, operation):- assert operation.execution_token is not None- operation = journal.record_snapshot(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- snapshot=_snapshot_receipt(journal, operation.operation_id),- )- assert operation.execution_token is not None- return journal.mark_prepared(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )---def test_clear_journal_happy_path_is_a_pure_durable_state_machine(tmp_path: Path) -> None:- journal = _journal(tmp_path)- sentinel = journal.database_path.parent.parent.parent / "memory/everos-root/sentinel"- sentinel.parent.mkdir(parents=True, mode=0o700)- sentinel.parent.chmod(0o700)- sentinel.write_text("must remain")- sentinel.chmod(0o600)-- operation = journal.start(- operation_id="clear-01",- operator_ref="user:operator",- pre_epoch=7,- target_epoch=8,- )-- assert operation.state == "preparing"- assert operation.revision == 1- assert operation.execution_token is not None- assert [surface.surface for surface in journal.get_surfaces(operation.operation_id)] == [- "queue",- "provider",- "call_log",- "attachments",- ]- with pytest.raises(ClearBackupBlocked):- journal.assert_backup_allowed()- with pytest.raises(ClearOperationConflict):- journal.start(- operation_id="clear-02",- operator_ref="user:operator",- pre_epoch=7,- target_epoch=8,- )-- operation = _record_all_snapshots(journal, operation)- assert operation.state == "prepared"- assert operation.snapshot_path == "state/memory/clear-snapshots/clear-01"- assert operation.manifest_sha256 == _digest("manifest")- assert operation.execution_token is not None- operation = journal.begin_deleting(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- assert operation.state == "deleting"- assert operation.destructive_started- for surface in journal.surfaces:- assert operation.execution_token is not None- operation = journal.record_surface_deleted(- operation.operation_id,- surface.name,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- assert operation.execution_token is not None- operation = journal.mark_completed(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )-- assert operation.state == "completed"- assert operation.terminal_at is not None- assert operation.execution_token is None- assert journal.get_open_operation() is None- journal.assert_backup_allowed()- assert sentinel.read_text() == "must remain"- assert [event.event for event in journal.get_events(operation.operation_id)] == [- "started",- "surface_snapshotted",- "surface_snapshotted",- "surface_snapshotted",- "surface_snapshotted",- "prepared",- "deleting_started",- "surface_deleted",- "surface_deleted",- "surface_deleted",- "surface_deleted",- "completed",- ]---def test_boot_recovery_is_explicit_and_resume_preserves_interrupted_stage(tmp_path: Path) -> None:- journal = _journal(tmp_path)- operation = journal.start(- operation_id="resume-me",- operator_ref="user:owner",- pre_epoch=0,- target_epoch=1,- )- stale_token = operation.execution_token-- reopened = MemoryClearJournal(journal.database_path.parent.parent.parent)- unchanged = reopened.get_open_operation()- assert unchanged is not None- assert unchanged.state == "preparing"- assert unchanged.revision == operation.revision-- recovery = reopened.mark_boot_recovery_needed()- assert recovery is not None- assert recovery.state == "recovery_needed"- assert recovery.recovery_from_state == "preparing"- assert recovery.execution_token is None- with pytest.raises(ClearOperationCASMismatch):- reopened.record_snapshot(- recovery.operation_id,- expected_revision=operation.revision,- execution_token=stale_token or "",- snapshot=_snapshot_receipt(reopened, recovery.operation_id),- )-- resumed = reopened.claim_resume(- recovery.operation_id,- operator_ref="user:owner",- expected_revision=recovery.revision,- )- assert resumed.state == "preparing"- assert resumed.resolution == "resume"- assert resumed.execution_token is not None- assert resumed.execution_token != stale_token-- second_recovery = reopened.mark_boot_recovery_needed()- assert second_recovery is not None- assert second_recovery.recovery_from_state == "preparing"- assert second_recovery.resolution == "resume"- with pytest.raises(ClearTransitionError):- reopened.claim_abort(- second_recovery.operation_id,- operator_ref="user:owner",- expected_revision=second_recovery.revision,- )---def test_in_process_failure_marks_exact_stage_with_cas(tmp_path: Path) -> None:- journal = _journal(tmp_path)- operation = journal.start(- operation_id="failed-in-process",- operator_ref="user:owner",- pre_epoch=4,- target_epoch=5,- )- operation = _record_all_snapshots(journal, operation)- assert operation.execution_token is not None-- recovery = journal.mark_recovery_needed(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )-- assert recovery.state == "recovery_needed"- assert recovery.recovery_from_state == "prepared"- assert recovery.execution_token is None- assert recovery.closed_error == "memory_clear_failed"- assert journal.get_events(operation.operation_id)[-1].event == "recovery_needed"---def test_failed_recovery_claim_is_released_without_changing_direction(- tmp_path: Path,-) -> None:- journal = _journal(tmp_path)- operation = journal.start(- operation_id="retry-abort",- operator_ref="user:owner",- pre_epoch=4,- target_epoch=5,- )- operation = _record_all_snapshots(journal, operation)- recovery = journal.mark_boot_recovery_needed()- assert recovery is not None- assert journal.can_resume(recovery.operation_id) is True- assert journal.can_abort(recovery.operation_id) is True- claimed = journal.claim_abort(- operation.operation_id,- operator_ref="user:owner",- expected_revision=recovery.revision,- )- assert journal.can_resume(claimed.operation_id) is False- assert journal.can_abort(claimed.operation_id) is False- assert claimed.execution_token is not None-- released = journal.release_recovery_claim(- claimed.operation_id,- expected_revision=claimed.revision,- execution_token=claimed.execution_token,- )-- assert released.state == "recovery_needed"- assert released.resolution == "abort"- assert released.execution_token is None- assert released.closed_error == "memory_clear_failed"- assert journal.can_resume(released.operation_id) is False- assert journal.can_abort(released.operation_id) is True- assert journal.get_events(operation.operation_id)[-1].event == "recovery_claim_failed"- reclaimed = journal.claim_abort(- released.operation_id,- operator_ref="user:owner",- expected_revision=released.revision,- )- assert reclaimed.resolution == "abort"- assert reclaimed.execution_token is not None---def test_open_operation_observation_uses_one_owner_scoped_snapshot(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,-) -> None:- journal = _journal(tmp_path)- operation = journal.start(- operation_id="observe-recovery",- operator_ref="user:owner",- pre_epoch=4,- target_epoch=5,- )- operation = _record_all_snapshots(journal, operation)- recovery = journal.mark_boot_recovery_needed()- assert recovery is not None-- connection_count = 0- transactions: list[str] = []- original_connect = journal._connect-- def observed_connect():- nonlocal connection_count- connection_count += 1- connection = original_connect()- connection.set_trace_callback(transactions.append)- return connection-- monkeypatch.setattr(journal, "_connect", observed_connect)-- owner = journal.observe_open_operation(operator_ref="user:owner")-- assert owner.operation == recovery- assert owner.can_resume is True- assert owner.can_abort is True- assert connection_count == 1- assert [statement for statement in transactions if statement == "BEGIN"] == [- "BEGIN"- ]-- different_owner = journal.observe_open_operation(operator_ref="user:other")- missing_owner = journal.observe_open_operation()-- assert different_owner.operation == recovery- assert different_owner.can_resume is False- assert different_owner.can_abort is False- assert missing_owner.operation == recovery- assert missing_owner.can_resume is False- assert missing_owner.can_abort is False- assert connection_count == 3---def test_abort_refuses_an_incomplete_snapshot(tmp_path: Path) -> None:- journal = _journal(tmp_path)- operation = journal.start(- operation_id="no-snapshot-abort",- operator_ref="user:owner",- pre_epoch=0,- target_epoch=1,- )- recovery = journal.mark_boot_recovery_needed()- assert recovery is not None- assert journal.can_abort(recovery.operation_id) is False-- with pytest.raises(ClearTransitionError):- journal.claim_abort(- operation.operation_id,- operator_ref="user:owner",- expected_revision=recovery.revision,- )-- still_open = journal.get_open_operation()- assert still_open is not None- assert still_open.state == "recovery_needed"- assert still_open.resolution is None---def test_present_snapshot_receipt_requires_both_digests() -> None:- with pytest.raises(ValueError):- SnapshotSurfaceReceipt(- path="state/memory/memory.sqlite",- present=True,- pre_clear_digest=None,- snapshot_digest=None,- )---def test_abort_direction_survives_a_second_crash_and_requires_restore(tmp_path: Path) -> None:- journal = _journal(tmp_path)- operation = journal.start(- operation_id="abort-me",- operator_ref="user:owner",- pre_epoch=10,- target_epoch=11,- )- operation = _record_all_snapshots(journal, operation)- assert operation.execution_token is not None- operation = journal.begin_deleting(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- assert operation.execution_token is not None- operation = journal.record_surface_deleted(- operation.operation_id,- "queue",- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- recovery = journal.mark_boot_recovery_needed()- assert recovery is not None and recovery.recovery_from_state == "deleting"- abort = journal.claim_abort(- operation.operation_id,- operator_ref="user:owner",- expected_revision=recovery.revision,- )- with pytest.raises(ClearTransitionError):- assert abort.execution_token is not None- journal.mark_aborted(- abort.operation_id,- expected_revision=abort.revision,- execution_token=abort.execution_token,- )-- assert abort.execution_token is not None- abort = journal.record_surface_restored(- abort.operation_id,- "queue",- expected_revision=abort.revision,- execution_token=abort.execution_token,- )- interrupted_abort = journal.mark_boot_recovery_needed()- assert interrupted_abort is not None- assert interrupted_abort.resolution == "abort"- with pytest.raises(ClearTransitionError):- journal.claim_resume(- interrupted_abort.operation_id,- operator_ref="user:owner",- expected_revision=interrupted_abort.revision,- )-- abort = journal.claim_abort(- interrupted_abort.operation_id,- operator_ref="user:owner",- expected_revision=interrupted_abort.revision,- )- for name in ("provider", "call_log", "attachments"):- assert abort.execution_token is not None- abort = journal.record_surface_restored(- abort.operation_id,- name,- expected_revision=abort.revision,- execution_token=abort.execution_token,- )- assert abort.execution_token is not None- aborted = journal.mark_aborted(- abort.operation_id,- expected_revision=abort.revision,- execution_token=abort.execution_token,- closed_error="memory_clear_failed",- )-- assert aborted.state == "aborted"- assert aborted.resolution == "abort"- assert aborted.closed_error == "memory_clear_failed"- journal.assert_backup_allowed()---def test_revision_and_execution_token_cas_reject_stale_coordinators(tmp_path: Path) -> None:- journal = _journal(tmp_path)- operation = journal.start(- operation_id="cas",- operator_ref="user:owner",- pre_epoch=3,- target_epoch=4,- )- assert operation.execution_token is not None- advanced = journal.record_snapshot(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- snapshot=_snapshot_receipt(journal, operation.operation_id),- )-- with pytest.raises(ClearOperationCASMismatch):- journal.mark_prepared(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- assert advanced.revision == operation.revision + 1- assert all(- surface.state == "snapshotted" for surface in journal.get_surfaces(operation.operation_id)- )---def test_concurrent_starts_create_exactly_one_open_operation(tmp_path: Path) -> None:- journal = _journal(tmp_path)-- def start(index: int):- try:- return journal.start(- operation_id=f"concurrent-{index}",- operator_ref="user:owner",- pre_epoch=1,- target_epoch=2,- )- except ClearOperationConflict:- return None-- with ThreadPoolExecutor(max_workers=2) as executor:- results = list(executor.map(start, range(2)))-- winners = [operation for operation in results if operation is not None]- assert len(winners) == 1- assert journal.get_open_operation() == winners[0]---def test_clear_journal_preserves_commit_failure_when_close_cleanup_fails(- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- journal = _journal(tmp_path)- commit_error = sqlite3.OperationalError("commit failed")- real_connect = sqlite3.connect-- class FailingConnection(sqlite3.Connection):- def commit(self) -> None:- raise commit_error-- def close(self) -> None:- super().close()- raise OSError("close cleanup failed")-- def connect(*args, **kwargs):- return real_connect(*args, **kwargs, factory=FailingConnection)-- from core.memory import confined_filesystem-- monkeypatch.setattr(confined_filesystem.sqlite3, "connect", connect)-- with pytest.raises(sqlite3.OperationalError) as raised:- journal.start(- operation_id="commit-failure",- operator_ref="user:owner",- pre_epoch=0,- target_epoch=1,- )-- assert raised.value is commit_error---def test_clear_journal_translates_hardening_failure_after_durable_commit(- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- journal = _journal(tmp_path)-- from core.memory import confined_filesystem-- real_chmod = confined_filesystem.os.chmod-- def fail_journal_hardening(target, mode: int) -> None:- if Path(target) == journal.database_path and mode == 0o600:- raise confined_filesystem.ConfinedFilesystemError("unsafe journal")- real_chmod(target, mode)-- monkeypatch.setattr(confined_filesystem.os, "chmod", fail_journal_hardening)-- with pytest.raises(- MemoryClearJournalError,- match="Memory clear journal files could not be hardened safely",- ):- journal.start(- operation_id="harden-failure",- operator_ref="user:owner",- pre_epoch=0,- target_epoch=1,- )-- committed = journal.get_operation("harden-failure")- assert committed is not None- assert committed.state == "preparing"---def test_clear_journal_keeps_sqlite_busy_failure_public(- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- journal = _journal(tmp_path)- blocker = sqlite3.connect(journal.database_path)- blocker.execute("BEGIN IMMEDIATE")-- from core.memory import confined_filesystem-- monkeypatch.setattr(- confined_filesystem,- "PRIVATE_SQLITE_BUSY_TIMEOUT_SECONDS",- 0.001,- )- try:- with pytest.raises(sqlite3.OperationalError, match="locked"):- journal.start(- operation_id="busy-failure",- operator_ref="user:owner",- pre_epoch=0,- target_epoch=1,- )- finally:- blocker.rollback()- blocker.close()---def test_terminal_headers_and_events_are_immutable_in_sqlite(tmp_path: Path) -> None:- journal = _journal(tmp_path)- operation = journal.start(- operation_id="immutable",- operator_ref="user:owner",- pre_epoch=0,- target_epoch=1,- )- operation = _record_all_snapshots(journal, operation)- recovery = journal.mark_boot_recovery_needed()- assert recovery is not None- abort = journal.claim_abort(- operation.operation_id,- operator_ref="user:owner",- expected_revision=recovery.revision,- )- for surface in journal.surfaces:- assert abort.execution_token is not None- abort = journal.record_surface_restored(- abort.operation_id,- surface.name,- expected_revision=abort.revision,- execution_token=abort.execution_token,- )- assert abort.execution_token is not None- terminal = journal.mark_aborted(- abort.operation_id,- expected_revision=abort.revision,- execution_token=abort.execution_token,- )-- connection = sqlite3.connect(journal.database_path)- try:- with pytest.raises(sqlite3.IntegrityError):- connection.execute(- "UPDATE clear_operation SET closed_error = NULL WHERE operation_id = ?",- (terminal.operation_id,),- )- connection.rollback()- with pytest.raises(sqlite3.IntegrityError):- connection.execute(- "UPDATE clear_event SET event = 'started' WHERE operation_id = ?",- (terminal.operation_id,),- )- connection.rollback()- with pytest.raises(sqlite3.IntegrityError):- connection.execute(- "DELETE FROM clear_event WHERE operation_id = ?",- (terminal.operation_id,),- )- finally:- connection.close()---def test_journal_is_private_and_rejects_symlink_database(tmp_path: Path) -> None:- journal = _journal(tmp_path)- assert stat.S_IMODE(journal.database_path.parent.stat().st_mode) == 0o700- assert stat.S_IMODE(journal.database_path.stat().st_mode) == 0o600-- other_home = tmp_path / "other-home"- target = tmp_path / "target.sqlite"- target.write_bytes(b"")- target.chmod(0o600)- database = other_home / "state/memory/clear-journal.sqlite"- database.parent.mkdir(parents=True, mode=0o700)- database.symlink_to(target)- with pytest.raises(MemoryClearJournalError):- MemoryClearJournal(other_home)-- sidecar_target = tmp_path / "sidecar-target"- sidecar_target.write_bytes(b"")- sidecar_target.chmod(0o600)- sidecar = journal.database_path.with_name(f"{journal.database_path.name}-wal")- sidecar.symlink_to(sidecar_target)- with pytest.raises(MemoryClearJournalError):- journal.get_open_operation()---def test_journal_rejects_database_inside_a_managed_surface(tmp_path: Path) -> None:- home = tmp_path / "home"- home.mkdir(mode=0o700)- home.chmod(0o700)- with pytest.raises(ValueError):- MemoryClearJournal(home, database_path="memory/everos-root/journal.sqlite")--- ("pre_epoch", "target_epoch"),- [(0, 0), (1, 3), (-1, 0), (True, 2)],-)-def test_journal_requires_a_single_epoch_advance(- tmp_path: Path,- pre_epoch: int,- target_epoch: int,-) -> None:- journal = _journal(tmp_path)- with pytest.raises(ValueError):- journal.start(- operator_ref="user:owner",- pre_epoch=pre_epoch,- target_epoch=target_epoch,- )diff --git a/tests/test_memory_clear_snapshot_storage.py b/tests/test_memory_clear_snapshot_storage.pydeleted file mode 100644index 9239993d9..000000000--- a/tests/test_memory_clear_snapshot_storage.py+++ /dev/null@@ -1,290 +0,0 @@-from __future__ import annotations--from pathlib import Path--import pytest--import core.memory.snapshot as snapshot_module-from core.memory.clear_journal import (- ClearOperation,- ClearOperationCASMismatch,- ClearTransitionError,- MemoryClearJournal,-)-from core.memory.clear_snapshot_storage import MemoryClearSnapshotStorage-from core.memory.snapshot import (- MemorySnapshotManager,- MemorySnapshotUnsafePathError,- MemorySnapshotVerificationError,-)---def _storage(- tmp_path: Path,-) -> tuple[MemoryClearJournal, MemorySnapshotManager, MemoryClearSnapshotStorage]:- home = tmp_path / "home"- home.mkdir(mode=0o700)- home.chmod(0o700)- journal = MemoryClearJournal(home)- manager = MemorySnapshotManager(home)- return journal, manager, MemoryClearSnapshotStorage(journal, manager)---def _record_snapshot(- journal: MemoryClearJournal,- manager: MemorySnapshotManager,- operation_id: str,-) -> ClearOperation:- operation = journal.start(- operation_id=operation_id,- operator_ref="user:owner",- pre_epoch=0,- target_epoch=1,- )- snapshot = manager.create(operation.operation_id)- assert operation.execution_token is not None- return journal.record_snapshot(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- snapshot=snapshot,- )---def _complete_clear(- journal: MemoryClearJournal,- manager: MemorySnapshotManager,- operation_id: str,-) -> ClearOperation:- operation = _record_snapshot(journal, manager, operation_id)- assert operation.execution_token is not None- operation = journal.mark_prepared(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- assert operation.execution_token is not None- operation = journal.begin_deleting(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- for surface in journal.surfaces:- assert operation.execution_token is not None- operation = journal.record_surface_deleted(- operation.operation_id,- surface.name,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- assert operation.execution_token is not None- return journal.mark_completed(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )---def _abort_clear(- journal: MemoryClearJournal,- manager: MemorySnapshotManager,- operation_id: str,-) -> ClearOperation:- operation = _record_snapshot(journal, manager, operation_id)- assert operation.execution_token is not None- operation = journal.mark_prepared(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- recovery = journal.mark_boot_recovery_needed()- assert recovery is not None- operation = journal.claim_abort(- operation.operation_id,- operator_ref="user:owner",- expected_revision=recovery.revision,- )- for surface in journal.surfaces:- assert operation.execution_token is not None- operation = journal.record_surface_restored(- operation.operation_id,- surface.name,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- assert operation.execution_token is not None- return journal.mark_aborted(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )---def test_terminal_snapshot_removal_requires_a_complete_audit_and_verifies_bytes(- tmp_path: Path,-) -> None:- journal, manager, storage = _storage(tmp_path)- operation = _record_snapshot(journal, manager, "remove-completed")- snapshot_path = manager.snapshot_path(operation.operation_id)-- assert storage.eligible_terminal_snapshot_ids() == ()- with pytest.raises(ClearTransitionError, match="only a terminal"):- storage.remove_terminal_snapshot(operation.operation_id)- assert snapshot_path.is_dir()-- assert operation.execution_token is not None- operation = journal.mark_prepared(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- assert operation.execution_token is not None- operation = journal.begin_deleting(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- for surface in journal.surfaces:- assert operation.execution_token is not None- operation = journal.record_surface_deleted(- operation.operation_id,- surface.name,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- assert operation.execution_token is not None- operation = journal.mark_completed(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )-- assert storage.eligible_terminal_snapshot_ids() == (operation.operation_id,)- manifest_path = snapshot_path / "manifest.jsonl"- manifest = manifest_path.read_bytes()- manifest_path.write_bytes(b"corrupt")- with pytest.raises(MemorySnapshotVerificationError):- storage.remove_terminal_snapshot(operation.operation_id)- assert snapshot_path.is_dir()- manifest_path.write_bytes(manifest)-- storage.remove_terminal_snapshot(operation.operation_id)- storage.remove_terminal_snapshot(operation.operation_id)- assert not snapshot_path.exists()---def test_aborted_restored_snapshot_is_eligible_for_idempotent_removal(- tmp_path: Path,-) -> None:- journal, manager, storage = _storage(tmp_path)- operation = _abort_clear(journal, manager, "remove-aborted")- snapshot_path = manager.snapshot_path(operation.operation_id)-- assert storage.eligible_terminal_snapshot_ids() == (operation.operation_id,)- storage.remove_terminal_snapshot(operation.operation_id)- storage.remove_terminal_snapshot(operation.operation_id)-- assert not snapshot_path.exists()---def test_preparing_discard_requires_exact_cas_and_refuses_a_recorded_snapshot(- tmp_path: Path,-) -> None:- journal, manager, storage = _storage(tmp_path)- operation = journal.start(- operation_id="publish-before-record",- operator_ref="user:owner",- pre_epoch=2,- target_epoch=3,- )- manager.create(operation.operation_id)- assert operation.execution_token is not None-- with pytest.raises(ClearOperationCASMismatch):- storage.discard_unrecorded_preparing_snapshot(- operation.operation_id,- expected_revision=operation.revision + 1,- execution_token=operation.execution_token,- )- assert manager.snapshot_path(operation.operation_id).is_dir()-- discarded = storage.discard_unrecorded_preparing_snapshot(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- assert discarded.revision == operation.revision + 1- assert journal.get_events(operation.operation_id)[-1].event == "snapshot_discarded"- assert not manager.snapshot_path(operation.operation_id).exists()-- rebuilt = manager.create(operation.operation_id)- assert discarded.execution_token is not None- recorded = journal.record_snapshot(- operation.operation_id,- expected_revision=discarded.revision,- execution_token=discarded.execution_token,- snapshot=rebuilt,- )- assert recorded.execution_token is not None- with pytest.raises(ClearTransitionError, match="only an unrecorded"):- storage.discard_unrecorded_preparing_snapshot(- recorded.operation_id,- expected_revision=recorded.revision,- execution_token=recorded.execution_token,- )- assert manager.snapshot_path(operation.operation_id).is_dir()---def test_terminal_removal_retries_a_partially_deleted_tombstone(- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- journal, manager, storage = _storage(tmp_path)- operation = _complete_clear(journal, manager, "remove-retry")- snapshot_path = manager.snapshot_path(operation.operation_id)- tombstone = manager.snapshot_root / f".{operation.operation_id}.gc"- real_unlink = snapshot_module.os.unlink- interrupted = False-- def interrupt_after_unlink(path, *args, **kwargs):- nonlocal interrupted- real_unlink(path, *args, **kwargs)- if not interrupted:- interrupted = True- raise OSError("injected tombstone removal failure")-- monkeypatch.setattr(snapshot_module.os, "unlink", interrupt_after_unlink)- with pytest.raises(OSError, match="injected tombstone removal failure"):- storage.remove_terminal_snapshot(operation.operation_id)-- assert interrupted- assert not snapshot_path.exists()- assert tombstone.is_dir()-- monkeypatch.setattr(snapshot_module.os, "unlink", real_unlink)- storage.remove_terminal_snapshot(operation.operation_id)-- assert not tombstone.exists()- assert not snapshot_path.exists()---def test_terminal_removal_refuses_a_symlinked_snapshot_directory(- tmp_path: Path,-) -> None:- journal, manager, storage = _storage(tmp_path)- operation = _complete_clear(journal, manager, "remove-symlink")- snapshot_path = manager.snapshot_path(operation.operation_id)- displaced = manager.snapshot_root / ".displaced"- snapshot_path.rename(displaced)- outside = tmp_path / "outside"- outside.mkdir()- sentinel = outside / "sentinel"- sentinel.write_text("must remain")- snapshot_path.symlink_to(outside, target_is_directory=True)-- with pytest.raises(MemorySnapshotUnsafePathError):- storage.remove_terminal_snapshot(operation.operation_id)-- assert snapshot_path.is_symlink()- assert displaced.is_dir()- assert sentinel.read_text() == "must remain"diff --git a/tests/test_memory_confined_filesystem.py b/tests/test_memory_confined_filesystem.pyindex 21511cf19..8eed10b8e 100644--- a/tests/test_memory_confined_filesystem.py+++ b/tests/test_memory_confined_filesystem.py@@ -42,16 +42,7 @@ from config.v2_config import MemoryConfigfrom core.memory.artifact import MemoryArtifactManagerfrom core.memory.runtime import create_memory_runtimefrom core.memory.provider_root import ProviderRoot, ProviderRootError, ProviderRootMetadata-from core.memory.snapshot import MemorySnapshotManager, MemorySnapshotUnsafePathError-home = Path(sys.argv[1])-snapshot_manager = MemorySnapshotManager(home)-try:- snapshot_manager.create("unsupported")-except MemorySnapshotUnsafePathError:- pass-else:- raise AssertionError("Memory snapshots accepted a host without O_NOFOLLOW")try:AttachmentPinStore(effective_home=home, source_root=home / "source")except AttachmentPinError:diff --git a/tests/test_memory_maintenance.py b/tests/test_memory_maintenance.pyindex b400b974d..6995f99a1 100644--- a/tests/test_memory_maintenance.py+++ b/tests/test_memory_maintenance.py@@ -1,2212 +1,525 @@from __future__ import annotations+from pathlib import Path+from types import SimpleNamespaceimport asyncio-import hashlib-import osimport sqlite3-import stat-import sys-from contextlib import asynccontextmanager-from dataclasses import replace-from datetime import UTC, datetime-from pathlib import Pathimport threadingimport pytest-import core.memory.snapshot as snapshot_module-from config.v2_config import MemoryConfig-from core.memory.artifact import FakeMemoryArtifactManager-from core.memory.clear_journal import MemoryClearJournal-from core.memory.clear_snapshot_storage import MemoryClearSnapshotStorage-from core.memory.everos import FakeMemoryProvider-from core.memory.process import SidecarOwnership-from core.memory.maintenance import (- ClearRecoveryResult,- ClearResult,- MaintenanceObservation,- MemoryMaintenance,-)-from core.memory.runtime import MemoryRuntime-from core.memory.snapshot import MemorySnapshotManager-from core.memory.store import AmbiguousAdd, MemoryStore-from core.memory.types import (- CaptureAccepted,- CaptureAttachment,- CaptureRequest,- CaptureSkipped,+from core.memory.clear_intent import (+ ClearIntent,+ ClearIntentError,+ ClearIntentStore,+ DEFAULT_CLEAR_SURFACES,)+from core.memory.maintenance import MemoryMaintenance+from core.memory.operation_lock import MemoryOperationLease+from core.memory.store import MemoryStore-PRINCIPAL = "u-11111111111111111111111111111111"-PROJECT = "default"---def _maintenance(runtime: MemoryRuntime) -> MemoryMaintenance:- maintenance = runtime._maintenance- assert maintenance is not None- return maintenance---def _replace_runtime_port(runtime: MemoryRuntime, **changes) -> None:- maintenance = _maintenance(runtime)- maintenance._runtime = replace(maintenance._runtime, **changes)---def _clear_payload(result: ClearResult) -> dict:- if result.status == "failed":- recovery = result.recovery- return {- "status": "failed",- "error": result.error,- "recovery": (- None- if recovery is None- else {- "state": recovery.state,- "operation_id": recovery.operation_id,- "occurred_at": recovery.occurred_at,- "error_code": recovery.error_code,- "can_resume": recovery.can_resume,- "can_abort": recovery.can_abort,- }- ),- }- return {- "status": result.status,- "operation_id": result.operation_id,- "epoch": result.epoch,- }---async def _clear(runtime: MemoryRuntime, *, operator_ref: str) -> dict:- return _clear_payload(- await _maintenance(runtime).clear(operator_ref=operator_ref)- )+class _Port:+ def __init__(self, home: Path) -> None:+ self.deleted: list[tuple[str, int]] = []+ self.resumed = 0+ self.entered = 0+ self.left = 0+ self.home = home+ self.assert_clear_fenced = None+ self.fail_strict_quiesce = False+ self.fail_quiesce = False+ self.quiesce_modes: list[bool] = []+ self.claim_events: list[str] = []+ def exclusive_fence(self):+ from contextlib import asynccontextmanager-async def _resume_clear(- runtime: MemoryRuntime,- operation_id: str,- *,- operator_ref: str,-) -> dict:- return _clear_payload(- await _maintenance(runtime).resume_clear(- operation_id,- operator_ref=operator_ref,- )- )+ @asynccontextmanager+ async def fence():+ yield+ return fence()-async def _abort_clear(- runtime: MemoryRuntime,- operation_id: str,- *,- operator_ref: str,-) -> dict:- return _clear_payload(- await _maintenance(runtime).abort_clear(- operation_id,- operator_ref=operator_ref,- )- )+ def boot_recovery_fence(self):+ return self.exclusive_fence()+ def state(self):+ return SimpleNamespace(artifact_installing=False)-async def test_runtime_preserves_public_clear_payloads_when_delegating(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,-) -> None:- runtime = MemoryRuntime(MemoryConfig(), effective_home=tmp_path)- results = iter(- (- ClearResult(status="completed", operation_id="clear-1", epoch=3),- ClearResult(- status="failed",- error="memory_clear_failed",- recovery=ClearRecoveryResult(- state="recovery_needed",- operation_id="clear-2",- occurred_at="2026-01-01T00:00:00.000Z",- error_code="memory_clear_failed",- can_resume=True,- can_abort=False,- ),- ),- )- )+ def enter_maintenance(self):+ self.entered += 1- async def delegated_clear(*, operator_ref: str) -> ClearResult:- assert operator_ref == "user:owner"- return next(results)-- monkeypatch.setattr(_maintenance(runtime), "clear", delegated_clear)-- assert await runtime.clear(operator_ref="user:owner") == {- "status": "completed",- "operation_id": "clear-1",- "epoch": 3,- }- assert await runtime.clear(operator_ref="user:owner") == {- "status": "failed",- "error": "memory_clear_failed",- "recovery": {- "state": "recovery_needed",- "operation_id": "clear-2",- "occurred_at": "2026-01-01T00:00:00.000Z",- "error_code": "memory_clear_failed",- "can_resume": True,- "can_abort": False,- },- }- await runtime.close()--- "failed_dependency",- ("MemoryClearJournal", "MemoryBackupRestoreJournal"),-)-async def test_maintenance_refuses_clear_when_a_journal_cannot_initialize(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- failed_dependency: str,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ def leave_maintenance(self):+ self.left += 1- def fail_initialization(*_args, **_kwargs):- raise OSError("injected journal initialization failure")-- monkeypatch.setattr(- f"core.memory.maintenance.{failed_dependency}",- fail_initialization,- )- runtime = MemoryRuntime(MemoryConfig(), effective_home=tmp_path)-- assert runtime.available is True- assert (await runtime.maintenance_payload())["can_clear"] is False- await runtime.close()---async def test_maintenance_advertises_clear_only_for_a_healthy_runtime(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = MemoryRuntime(MemoryConfig(), effective_home=tmp_path)-- assert runtime.available is True- assert (await runtime.maintenance_payload())["can_clear"] is True- await runtime.close()+ async def pause_claims(self):+ self.claim_events.append("pause")+ return None+ def resume_claims(self):+ return None-async def test_maintenance_observes_clear_recovery_with_one_journal_snapshot(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = MemoryRuntime(MemoryConfig(), effective_home=tmp_path)- maintenance = _maintenance(runtime)- journal = maintenance._clear_journal- assert journal is not None- operation = journal.start(- operation_id="single-observation",- operator_ref="user:owner",- pre_epoch=0,- target_epoch=1,- )- recovery = journal.mark_boot_recovery_needed()- assert recovery is not None+ async def quiesce(self, _strict: bool):+ self.claim_events.append("quiesce")+ self.quiesce_modes.append(_strict)+ if self.fail_quiesce or (_strict and self.fail_strict_quiesce):+ raise RuntimeError("quiesce failed")+ return None- connection_count = 0- original_connect = journal._connect+ async def resume(self):+ self.resumed += 1- def observed_connect():- nonlocal connection_count- connection_count += 1- return original_connect()+ async def delete_surface(self, surface, target_epoch: int):+ if self.assert_clear_fenced is not None:+ self.assert_clear_fenced()+ self.deleted.append((surface.surface, target_epoch))- monkeypatch.setattr(journal, "_connect", observed_connect)+ def restore_completed(self):+ return None- observation = await maintenance.observe(operator_ref="user:owner")- assert observation.clear_recovery == ClearRecoveryResult(- state="recovery_needed",- operation_id=operation.operation_id,- occurred_at=recovery.updated_at,- error_code="memory_clear_failed",- can_resume=True,- can_abort=False,+def _maintenance(tmp_path: Path) -> tuple[MemoryMaintenance, _Port]:+ port = _Port(tmp_path)+ maintenance = MemoryMaintenance(+ MemoryStore(),+ effective_home=tmp_path,+ runtime=port,)- assert connection_count == 1- await runtime.close()+ return maintenance, port[email protected]("failure_point", ("snapshot_manager", "boot_marker"))-async def test_partial_maintenance_initialization_still_projects_clear_recovery(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- failure_point: str,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- journal = MemoryClearJournal(tmp_path)- operation = journal.start(- operation_id=f"clear-before-{failure_point}-failure",- operator_ref="user:owner",- pre_epoch=0,- target_epoch=1,- )- recovery = journal.mark_boot_recovery_needed()- assert recovery is not None-- def fail_initialization(*_args, **_kwargs):- raise OSError(f"injected {failure_point} initialization failure")-- if failure_point == "snapshot_manager":- monkeypatch.setattr(- "core.memory.maintenance.MemorySnapshotManager",- fail_initialization,- )- else:- monkeypatch.setattr(- "core.memory.maintenance.MemoryBackupRestoreJournal."- "mark_boot_recovery_needed",- fail_initialization,- )-- runtime = MemoryRuntime(MemoryConfig(), effective_home=tmp_path)- maintenance = _maintenance(runtime)- assert maintenance.ready is False-- observation = await maintenance.observe(operator_ref="user:owner")- assert observation.block_reason == "memory_store_unavailable"- assert observation.can_clear is False- assert observation.clear_recovery == ClearRecoveryResult(- state="recovery_needed",- operation_id=operation.operation_id,- occurred_at=recovery.updated_at,- error_code="memory_clear_failed",- can_resume=False,- can_abort=False,+async def test_clear_writes_marker_and_repeats_four_surfaces(tmp_path: Path):+ maintenance, port = _maintenance(tmp_path)+ port.assert_clear_fenced = lambda: (+ assert_marker_and_fence(maintenance, tmp_path))- payload = await runtime.maintenance_payload(operator_ref="user:owner")- assert payload["can_clear"] is False- assert payload["clear_recovery"] == {- "state": "recovery_needed",- "operation_id": operation.operation_id,- "occurred_at": recovery.updated_at,- "error_code": "memory_clear_failed",- "can_resume": False,- "can_abort": False,- }- await runtime.close()---async def test_maintenance_revalidates_journals_after_store_metadata_reads(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = MemoryRuntime(MemoryConfig(), effective_home=tmp_path)- maintenance = runtime._maintenance- assert maintenance is not None- initial = MaintenanceObservation(None, None, True)- latest = MaintenanceObservation("busy", None, False)- observations = iter((initial, latest))+ result = await maintenance.clear(operator_ref="user-1")- async def observe(*, operator_ref: str | None = None) -> MaintenanceObservation:- del operator_ref- return next(observations)-- monkeypatch.setattr(maintenance, "observe", observe)-- result = await maintenance.maintenance_payload(operator_ref="user:owner")-- assert result.can_clear is False- assert result.clear_recovery is latest.clear_recovery- await runtime.close()---async def test_maintenance_drops_old_recovery_when_freshness_check_fails(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = MemoryRuntime(MemoryConfig(), effective_home=tmp_path)- maintenance = runtime._maintenance- assert maintenance is not None- recovery = ClearRecoveryResult(- state="recovery_needed",- operation_id="clear-stale",- occurred_at="2026-08-10T00:00:00.000Z",- error_code="memory_clear_failed",- can_resume=True,- can_abort=True,- )- initial = MaintenanceObservation("memory_clear_failed", recovery, False)-- async def failed_observe(*, operator_ref: str | None = None) -> MaintenanceObservation:- del operator_ref- raise OSError("journal unavailable")+ assert result.status == "completed"+ assert [surface for surface, _epoch in port.deleted] == [+ surface.surface for surface in DEFAULT_CLEAR_SURFACES+ ]+ assert len({epoch for _surface, epoch in port.deleted}) == 1+ assert ClearIntentStore(tmp_path).load() is None+ assert port.resumed == 1+ assert maintenance._store is not None+ assert maintenance._store.clear_in_progress() is False- monkeypatch.setattr(maintenance, "observe", failed_observe)- result = await maintenance.maintenance_payload(- operator_ref="user:owner",- observation=initial,- )+def assert_marker_and_fence(maintenance: MemoryMaintenance, home: Path) -> None:+ assert ClearIntentStore(home).load() is not None+ assert maintenance._store is not None+ assert maintenance._store.clear_in_progress() is True- assert result.can_clear is False- assert result.clear_recovery is None- assert result.error == "memory_store_unavailable"- await runtime.close()+async def test_failed_clear_persists_failed_projection_and_boot_retries(tmp_path: Path):+ maintenance, port = _maintenance(tmp_path)-async def test_maintenance_refuses_clear_when_the_store_is_unavailable(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ async def fail(surface, target_epoch: int):+ port.deleted.append((surface.surface, target_epoch))+ if surface.surface == "provider":+ raise RuntimeError("provider unavailable")- def fail_initialization(*_args, **_kwargs):- raise OSError("injected store initialization failure")+ port.delete_surface = fail+ result = await maintenance.clear(operator_ref="user-1")- monkeypatch.setattr("core.memory.runtime.MemoryStore", fail_initialization)- runtime = MemoryRuntime(MemoryConfig(), effective_home=tmp_path)+ assert result.status == "failed"+ intent = ClearIntentStore(tmp_path).load()+ assert intent is not None+ assert intent.state == "failed"+ assert result.clear_in_progress is not None+ assert result.clear_in_progress.state == "failed"- assert runtime.available is False- assert (await runtime.maintenance_payload())["can_clear"] is False- await runtime.close()+ port.delete_surface = _Port.delete_surface.__get__(port, _Port)+ assert await maintenance.reconcile_pending() is True+ assert ClearIntentStore(tmp_path).load() is None+ assert port.resumed == 0-async def test_unavailable_store_still_projects_durable_clear_recovery(- monkeypatch: pytest.MonkeyPatch,+async def test_marker_removal_failure_retries_after_surfaces_are_terminal(tmp_path: Path,- memory_runtime_factory,-) -> None:- operation = MemoryClearJournal(tmp_path).start(- operation_id="clear-before-store-failure",- operator_ref="user:owner",- pre_epoch=2,- target_epoch=3,- )-- def fail_initialization(*_args, **_kwargs):- raise OSError("injected store initialization failure")-- monkeypatch.setattr("core.memory.runtime.MemoryStore", fail_initialization)- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)-- fence_entered = False-- @asynccontextmanager- async def observed_fence():- nonlocal fence_entered- fence_entered = True- yield-- _replace_runtime_port(runtime, exclusive_fence=observed_fence)- before = await runtime.maintenance_payload(operator_ref="user:owner")- assert before["status"] == "ok"- assert before["data_exists"] is True- assert before["can_clear"] is False- assert before["clear_recovery"] == {- "state": "recovery_needed",- "operation_id": operation.operation_id,- "occurred_at": before["clear_recovery"]["occurred_at"],- "error_code": "memory_clear_failed",- "can_resume": True,- "can_abort": False,- }-- assert await runtime.reconcile(MemoryConfig()) == {- "ok": True,- "state": "disabled",- }- assert _maintenance(runtime)._backup_stage_reconcile_task is None- await asyncio.sleep(0)- assert fence_entered is False- assert await runtime.maintenance_payload(operator_ref="user:owner") == before- await memory_runtime_factory.close(runtime)--[email protected]("failure_point", ("provider_root", "module"))-async def test_supplied_store_attaches_only_after_module_initialization(monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- failure_point: str,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- operation = MemoryClearJournal(tmp_path).start(- operation_id=f"clear-before-{failure_point}-failure",- operator_ref="user:owner",- pre_epoch=4,- target_epoch=5,- )- store = MemoryStore(tmp_path / "state" / "memory" / "memory.sqlite")- artifact = FakeMemoryArtifactManager()+):+ maintenance, _port = _maintenance(tmp_path)+ store = maintenance._store+ assert store is not None+ remove_calls = 0+ original_remove = maintenance._intent.remove- def fail_initialization(*_args, **_kwargs):- raise OSError(f"injected {failure_point} initialization failure")+ def fail_once() -> None:+ nonlocal remove_calls+ remove_calls += 1+ assert store.clear_in_progress() is False+ if remove_calls == 1:+ raise ClearIntentError("marker remove failed")+ original_remove()- if failure_point == "provider_root":- monkeypatch.setattr(artifact, "set_provider_root", fail_initialization)- else:- monkeypatch.setattr("core.memory.runtime.MemoryModule", fail_initialization)+ monkeypatch.setattr(maintenance._intent, "remove", fail_once)- runtime = memory_runtime_factory(- MemoryConfig(),- store=store,- artifact_manager=artifact,- effective_home=tmp_path,- )- maintenance = _maintenance(runtime)- assert runtime.available is False- assert maintenance._store is None-- fence_entered = False-- @asynccontextmanager- async def observed_fence():- nonlocal fence_entered- fence_entered = True- yield-- _replace_runtime_port(runtime, exclusive_fence=observed_fence)- before = await runtime.maintenance_payload(operator_ref="user:owner")- assert before["clear_recovery"]["operation_id"] == operation.operation_id-- assert await runtime.reconcile(MemoryConfig()) == {- "ok": True,- "state": "disabled",- }- assert maintenance._backup_stage_reconcile_task is None- await asyncio.sleep(0)- assert fence_entered is False- assert await runtime.maintenance_payload(operator_ref="user:owner") == before- await memory_runtime_factory.close(runtime)---def _enqueue(runtime: MemoryRuntime, source: str) -> None:- result = runtime._store.enqueue_request(- source_message_id=source,- session_id="session",- principal_id=PRINCIPAL,- project_ref=PROJECT,- provenance="user_input",- payload_text="private payload",- occurred_at_ms=1,- max_provider_timestamp_ms=100,- )- assert result.outcome == "accepted"+ result = await maintenance.clear(operator_ref="user-1")+ assert result.status == "failed"+ intent = ClearIntentStore(tmp_path).load()+ assert intent is not None+ assert intent.state == "failed"+ assert store.clear_in_progress() is False-async def test_clear_converges_for_provider_tree_deeper_than_recursion_limit(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- manager = _maintenance(runtime)._snapshot_manager- assert manager is not None- provider_root = tmp_path / "memory/everos-root"- runtime._provider_root_owner.ensure(- runtime._store.ensure_meta(),- runtime._active_provider_root_metadata(),- )- path_max = os.pathconf(tmp_path, "PC_PATH_MAX")- snapshot_prefix = manager.snapshot_root / (- f".{('x' * 32)}.tmp/payload/memory/everos-root"- )- longest_prefix = max(- len(os.fsencode(provider_root)),- len(os.fsencode(snapshot_prefix)),- )- depth = min(500, (path_max - longest_prefix - len("/leaf") - 16) // 2)- recursion_limit = min(sys.getrecursionlimit(), depth - 32)- assert recursion_limit > 200- assert depth > recursion_limit-- leaf_parent = provider_root- for _ in range(depth):- leaf_parent /= "d"- leaf_parent.mkdir(mode=0o700)- leaf = leaf_parent / "leaf"- leaf.write_bytes(b"provider bytes")- leaf.chmod(0o600)- assert len(os.fsencode(leaf)) < path_max-- previous_recursion_limit = sys.getrecursionlimit()- try:- sys.setrecursionlimit(recursion_limit)- result = await _clear(runtime, operator_ref="user:owner")- gc_task = _maintenance(runtime)._terminal_snapshot_gc_task- if gc_task is not None:- await gc_task- finally:- sys.setrecursionlimit(previous_recursion_limit)+ assert await maintenance.reconcile_pending() is True+ assert remove_calls == 2+ assert ClearIntentStore(tmp_path).load() is None- assert result["status"] == "completed"- assert _maintenance(runtime)._clear_journal is not None- assert _maintenance(runtime)._clear_journal.get_open_operation() is None- assert not leaf.exists()- assert not manager.snapshot_path(result["operation_id"]).exists()- await memory_runtime_factory.close(runtime)--async def test_clear_discards_manual_required_fence_and_allows_new_delivery(- monkeypatch,+async def test_marker_unlink_fsync_failure_retains_failed_projection(tmp_path: Path,- memory_runtime_factory,-) -> None:- """MEMORY-CLEAR-201: Clear settles an unknown add without replaying it."""- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(enabled=True), effective_home=tmp_path)- provider_timeout = asyncio.Event()-- async def time_out_add(_capture) -> None:- await provider_timeout.wait()-- provider = FakeMemoryProvider(add_hook=time_out_add)- runtime.module.replace_provider(provider)- runtime.module._worker.coordinator._add_timeout_seconds = 0.001- source_root = tmp_path / "attachments" / "avibe"- source_root.mkdir(parents=True, mode=0o700)- source_root.chmod(0o700)- attachment_path = source_root / "evidence.txt"- attachment_path.write_bytes(b"retained ambiguous attachment")- attachment_path.chmod(0o600)- first = CaptureRequest(- source_message_id="timed-out-add",- session_id="session",- principal_id=PRINCIPAL,- project_id=PROJECT,- provenance="user_input",- text="ambiguous payload",- occurred_at_ms=1,- attachments=(- CaptureAttachment(- kind="doc",- name=attachment_path.name,- uri=attachment_path.as_uri(),- ext="txt",- ),- ),- )- assert await runtime.module.capture(first) == CaptureAccepted()- assert await runtime.module.drain() == 1-- ambiguous = runtime._store.list_queue_rows()- assert len(ambiguous) == 1- assert ambiguous[0].state == "manual_required"- assert ambiguous[0].payload_text == "ambiguous payload"- assert ambiguous[0].attachment_bundle_id is not None- attachment_bundle_id = ambiguous[0].attachment_bundle_id- assert runtime._store.has_manual_required_fence() is True- session = runtime._store.get_session_flush_state(ambiguous[0].provider_session_ref)- assert session is not None and session.state == "manual_required"- assert (await runtime.maintenance_payload())["can_clear"] is True-- async def resume_without_sidecar() -> None:- runtime.module.resume_claims()-- _replace_runtime_port(runtime, resume=resume_without_sidecar)- result = await _clear(runtime, operator_ref="user:owner")-- assert result["status"] == "completed"- assert runtime._store.list_queue_rows() == ()- assert runtime._store.has_manual_required_fence() is False- assert not (- tmp_path / "memory" / "attachments" / "bundles" / attachment_bundle_id- ).exists()- assert attachment_path.read_bytes() == b"retained ambiguous attachment"-- provider.add_hook = None- second = CaptureRequest(- source_message_id="after-clear",- session_id="session",- principal_id=PRINCIPAL,- project_id=PROJECT,- provenance="user_input",- text="deliver after clear",- occurred_at_ms=2,- )- assert await runtime.module.capture(second) == CaptureAccepted()- assert await runtime.module.drain() == 1- delivered = runtime._store.list_queue_rows()- assert len(delivered) == 1 and delivered[0].state == "delivered"- assert delivered[0].provider_session_ref.epoch == result["epoch"]- assert [capture.text for capture in provider.captures] == [- "ambiguous payload",- "deliver after clear",- ]- await memory_runtime_factory.close(runtime)-+ monkeypatch: pytest.MonkeyPatch,+):+ maintenance, _port = _maintenance(tmp_path)+ original_remove = maintenance._intent.remove-async def test_interrupted_queue_delete_requires_explicit_resume_at_target_epoch(- monkeypatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- owner = runtime.principal_for_user_key("avibe:local")- other_operator = runtime.principal_for_user_key("avibe:remote:other-subject")- _enqueue(runtime, "resume-source")- pre_epoch = runtime._store.ensure_meta().epoch- journal = _maintenance(runtime)._clear_journal- assert journal is not None- original_record = journal.record_surface_deleted- interrupted = False-- def interrupt_queue_receipt(operation_id, surface, **kwargs):- nonlocal interrupted- if surface == "queue" and not interrupted:- interrupted = True- raise OSError("injected receipt failure")- return original_record(operation_id, surface, **kwargs)-- monkeypatch.setattr(journal, "record_surface_deleted", interrupt_queue_receipt)-- failed = await _clear(runtime, operator_ref=owner)-- assert failed["status"] == "failed"- recovery = journal.get_open_operation()- assert recovery is not None- assert recovery.state == "recovery_needed"- assert recovery.recovery_from_state == "deleting"- assert failed["recovery"]["can_abort"] is True- assert runtime._store.ensure_meta().epoch == pre_epoch + 1- assert runtime._store.list_queue_rows() == ()-- owner_maintenance = await runtime.maintenance_payload(operator_ref=owner)- other_maintenance = await runtime.maintenance_payload(- operator_ref=other_operator- )- owner_failures = await runtime.failure_log_payload(operator_ref=owner)- other_failures = await runtime.failure_log_payload(operator_ref=other_operator)- assert owner_maintenance["clear_recovery"]["can_resume"] is True- assert owner_maintenance["clear_recovery"]["can_abort"] is True- assert owner_failures["recovery"]["can_resume"] is True- assert owner_failures["recovery"]["can_abort"] is True- assert other_maintenance["clear_recovery"]["can_resume"] is False- assert other_maintenance["clear_recovery"]["can_abort"] is False- assert other_failures["recovery"]["can_resume"] is False- assert other_failures["recovery"]["can_abort"] is False- assert "operator_ref" not in owner_maintenance["clear_recovery"]- assert owner not in repr(owner_maintenance)-- rejected = await _resume_clear(runtime,- recovery.operation_id,- operator_ref=other_operator,- )- assert rejected["status"] == "failed"- assert rejected["recovery"]["can_resume"] is False- assert journal.get_open_operation() == recovery-- monkeypatch.setattr(journal, "record_surface_deleted", original_record)- completed = await _resume_clear(runtime,- recovery.operation_id,- operator_ref=owner,- )+ def unlink_then_fail() -> None:+ original_remove()+ raise ClearIntentError("marker fsync failed")- assert completed["status"] == "completed"- assert completed["epoch"] == pre_epoch + 1- assert runtime._store.ensure_meta().epoch == pre_epoch + 1- assert journal.get_open_operation() is None- await memory_runtime_factory.close(runtime)+ monkeypatch.setattr(maintenance._intent, "remove", unlink_then_fail)+ result = await maintenance.clear(operator_ref="user-1")-async def test_attachment_clear_failure_does_not_record_surface_deleted(- monkeypatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- attachment_store = runtime.module._attachment_store- outside = tmp_path / "outside-attachments"- outside.mkdir(mode=0o700)- sentinel = outside / "sentinel"- sentinel.write_bytes(b"outside must remain")- unsafe = attachment_store._bundles / "malformed-bundle"- original_clear_all = attachment_store.clear_all-- def inject_unsafe_entry_then_clear() -> None:- unsafe.symlink_to(outside, target_is_directory=True)- original_clear_all()-- monkeypatch.setattr(attachment_store, "clear_all", inject_unsafe_entry_then_clear)-- failed = await _clear(runtime, operator_ref="user:owner")-- assert failed["status"] == "failed"- recovery = _maintenance(runtime)._clear_journal.get_open_operation()- assert recovery is not None and recovery.state == "recovery_needed"- surfaces = {- surface.surface: surface.state- for surface in _maintenance(runtime)._clear_journal.get_surfaces(recovery.operation_id)- }- assert surfaces["attachments"] == "snapshotted"- assert unsafe.is_symlink()- assert sentinel.read_bytes() == b"outside must remain"- await memory_runtime_factory.close(runtime)---async def test_recovery_payload_disables_abort_before_initial_snapshot(- monkeypatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- journal = _maintenance(runtime)._clear_journal- assert journal is not None- operation = journal.start(- operation_id="incomplete-snapshot",- operator_ref="user:owner",- pre_epoch=0,- target_epoch=1,- )- recovery = journal.mark_boot_recovery_needed()-- assert recovery is not None- maintenance = await runtime.maintenance_payload(operator_ref="user:owner")- assert maintenance["clear_recovery"] == {- "state": "recovery_needed",- "operation_id": operation.operation_id,- "occurred_at": recovery.updated_at,- "error_code": "memory_clear_failed",- "can_resume": True,- "can_abort": False,- }- await memory_runtime_factory.close(runtime)---async def test_cancelled_clear_start_and_resume_claim_settle_before_recovery(- monkeypatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- journal = _maintenance(runtime)._clear_journal- assert journal is not None- start_entered = threading.Event()- start_release = threading.Event()- original_start = journal.start-- def blocking_start(**kwargs):- operation = original_start(**kwargs)- start_entered.set()- assert start_release.wait(2)- return operation-- monkeypatch.setattr(journal, "start", blocking_start)- clearing = asyncio.create_task(_clear(runtime, operator_ref="user:owner"))- assert await asyncio.to_thread(start_entered.wait, 1)-- clearing.cancel()- await asyncio.sleep(0)-- assert clearing.done() is False- assert runtime._reconcile_lock.locked()- assert runtime.module._lifecycle_lock.locked()- assert runtime.module._root_lifecycle_lock().locked()- start_release.set()- with pytest.raises(asyncio.CancelledError):- await clearing-- recovery = journal.get_open_operation()- assert recovery is not None- assert recovery.state == "recovery_needed"- assert recovery.recovery_from_state == "preparing"- assert recovery.execution_token is None- assert runtime._store.ensure_meta().clear_in_progress is False-- claim_entered = threading.Event()- claim_release = threading.Event()- original_claim_resume = journal.claim_resume-- def blocking_claim_resume(operation_id: str, **kwargs):- operation = original_claim_resume(operation_id, **kwargs)- claim_entered.set()- assert claim_release.wait(2)- return operation-- monkeypatch.setattr(journal, "claim_resume", blocking_claim_resume)- resuming = asyncio.create_task(- _resume_clear(runtime, recovery.operation_id, operator_ref="user:owner")- )- assert await asyncio.to_thread(claim_entered.wait, 1)-- resuming.cancel()- await asyncio.sleep(0)-- assert resuming.done() is False- assert runtime._reconcile_lock.locked()- assert runtime.module._lifecycle_lock.locked()- assert runtime.module._root_lifecycle_lock().locked()- claim_release.set()- with pytest.raises(asyncio.CancelledError):- await resuming-- claimed_recovery = journal.get_open_operation()- assert claimed_recovery is not None- assert claimed_recovery.state == "recovery_needed"- assert claimed_recovery.recovery_from_state == "preparing"- assert claimed_recovery.resolution == "resume"- assert claimed_recovery.execution_token is None-- monkeypatch.setattr(journal, "claim_resume", original_claim_resume)- completed = await _resume_clear(runtime,- claimed_recovery.operation_id,- operator_ref="user:owner",- )- assert completed["status"] == "completed"- assert journal.get_open_operation() is None- await memory_runtime_factory.close(runtime)+ assert result.status == "failed"+ retained = ClearIntentStore(tmp_path).load()+ assert retained is not None+ assert retained.state == "failed"-async def test_cancelled_completed_clear_resumes_runtime_once(- monkeypatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- journal = _maintenance(runtime)._clear_journal- assert journal is not None- completed_entered = threading.Event()- completed_release = threading.Event()- completed_ids: list[str] = []- original_mark_completed = journal.mark_completed-- def blocking_mark_completed(operation_id: str, **kwargs):- operation = original_mark_completed(operation_id, **kwargs)- completed_ids.append(operation.operation_id)- completed_entered.set()- assert completed_release.wait(2)- return operation-- resume_calls = 0- original_resume = _maintenance(runtime)._runtime.resume-- async def counted_resume() -> None:- nonlocal resume_calls- resume_calls += 1- await original_resume()-- monkeypatch.setattr(journal, "mark_completed", blocking_mark_completed)- _replace_runtime_port(runtime, resume=counted_resume)- clearing = asyncio.create_task(_clear(runtime, operator_ref="user:owner"))- assert await asyncio.to_thread(completed_entered.wait, 1)-- clearing.cancel()- await asyncio.sleep(0)-- assert clearing.done() is False- assert runtime._reconcile_lock.locked()- assert runtime.module._lifecycle_lock.locked()- assert runtime.module._root_lifecycle_lock().locked()- completed_release.set()- with pytest.raises(asyncio.CancelledError):- await clearing-- assert completed_ids- completed = journal.get_operation(completed_ids[0])- assert completed is not None- assert completed.state == "completed"- assert journal.get_open_operation() is None- assert resume_calls == 1- await memory_runtime_factory.close(runtime)---async def test_cancelled_post_terminal_resume_holds_lifecycle_fences(- monkeypatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(enabled=True), effective_home=tmp_path)- resume_entered = asyncio.Event()- resume_release = asyncio.Event()-- async def blocking_reconcile(*_args, **_kwargs):- resume_entered.set()- await resume_release.wait()- runtime.module._worker.resume_claims()- return {"ok": True, "state": "running"}-- monkeypatch.setattr(runtime, "_reconcile_locked", blocking_reconcile)- clearing = asyncio.create_task(_clear(runtime, operator_ref="user:owner"))- await asyncio.wait_for(resume_entered.wait(), timeout=5)-- assert _maintenance(runtime)._clear_journal.get_open_operation() is None- assert runtime.module._worker._claims_paused is True- assert runtime.module._worker._coordinator._paused is True- clearing.cancel()- await asyncio.sleep(0)-- assert clearing.done() is False- assert runtime._reconcile_lock.locked()- assert runtime.module._lifecycle_lock.locked()- assert runtime.module._root_lifecycle_lock().locked()- resume_release.set()- with pytest.raises(asyncio.CancelledError):- await clearing-- assert runtime.module._worker._claims_paused is False- assert runtime.module._worker._coordinator._paused is False- assert runtime._reconcile_lock.locked() is False- assert runtime.module._lifecycle_lock.locked() is False- assert runtime.module._root_lifecycle_lock().locked() is False- await memory_runtime_factory.close(runtime)---async def test_abort_restores_all_surfaces_after_destructive_work(- monkeypatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- _enqueue(runtime, "abort-source")- pre_meta = runtime._store.ensure_meta()- original_delete = _maintenance(runtime)._runtime.delete_surface-- async def interrupt_provider(surface, target_epoch):- if surface.surface == "provider":- raise OSError("injected provider delete failure")- await original_delete(surface, target_epoch)+async def test_corrupt_marker_can_be_replaced_by_user_clear(tmp_path: Path):+ marker = tmp_path / "state/memory/clear-intent.json"+ marker.parent.mkdir(parents=True)+ marker.write_text("not json", encoding="utf-8")+ maintenance, _port = _maintenance(tmp_path)- _replace_runtime_port(runtime, delete_surface=interrupt_provider)- failed = await _clear(runtime, operator_ref="user:owner")- recovery = _maintenance(runtime)._clear_journal.get_open_operation()+ result = await maintenance.clear(operator_ref="user-1")- assert failed["status"] == "failed"- assert recovery is not None and recovery.destructive_started- assert runtime._store.list_queue_rows() == ()+ assert result.status == "completed"+ assert ClearIntentStore(tmp_path).load() is None+ assert maintenance.is_open() is False+ assert (await maintenance.observe()).can_clear is True- _replace_runtime_port(runtime, delete_surface=original_delete)- aborted = await _abort_clear(runtime,- recovery.operation_id,- operator_ref="user:owner",- )- assert aborted["status"] == "aborted"- restored_meta = runtime._store.ensure_meta()- assert restored_meta.epoch == pre_meta.epoch- assert restored_meta.clear_in_progress is False- assert len(runtime._store.list_queue_rows()) == 1- assert _maintenance(runtime)._clear_journal.get_open_operation() is None- operation = _maintenance(runtime)._clear_journal.get_operation(recovery.operation_id)- assert operation is not None and operation.state == "aborted"- assert _maintenance(runtime)._snapshot_manager is not None- assert not _maintenance(runtime)._snapshot_manager.snapshot_path(recovery.operation_id).exists()- await memory_runtime_factory.close(runtime)+async def test_explicit_clear_replaces_legacy_failed_marker(tmp_path: Path):+ journal = tmp_path / "state/memory/clear-journal.sqlite"+ journal.parent.mkdir(parents=True)+ journal.write_bytes(b"not sqlite")+ maintenance, port = _maintenance(tmp_path)+ legacy_intent = ClearIntentStore(tmp_path).load()+ assert legacy_intent is not None+ assert legacy_intent.error_code == "memory_clear_legacy_state_requires_rerun"+ result = await maintenance.clear(operator_ref="user-1")-async def test_clear_accepts_corrupt_diagnostic_call_log(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- call_log = tmp_path / "memory/call-log/call-log.db"- call_log.parent.mkdir(parents=True, mode=0o700)- call_log.parent.chmod(0o700)- files = {- call_log: b"corrupt-call-log-database",- call_log.with_name(f"{call_log.name}-wal"): b"corrupt-call-log-wal",- call_log.with_name(f"{call_log.name}-shm"): b"corrupt-call-log-shm",- call_log.with_name(f"{call_log.name}-journal"): b"corrupt-call-log-journal",- }- for path, payload in files.items():- path.write_bytes(payload)- path.chmod(0o600)-- result = await _clear(runtime, operator_ref="user:owner")-- assert result["status"] == "completed"- assert all(not path.exists() for path in files)- assert _maintenance(runtime)._clear_journal.get_open_operation() is None- await memory_runtime_factory.close(runtime)---async def test_abort_restores_exact_corrupt_call_log_files_after_deletion(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- call_log = tmp_path / "memory/call-log/call-log.db"- call_log.parent.mkdir(parents=True, mode=0o700)- call_log.parent.chmod(0o700)- files = {- call_log: b"corrupt-call-log-database",- call_log.with_name(f"{call_log.name}-wal"): b"corrupt-call-log-wal",- call_log.with_name(f"{call_log.name}-shm"): b"corrupt-call-log-shm",- call_log.with_name(f"{call_log.name}-journal"): b"corrupt-call-log-journal",- }- for path, payload in files.items():- path.write_bytes(payload)- path.chmod(0o600)- before = {- path: (- path.read_bytes(),- stat.S_IMODE(path.stat().st_mode),- hashlib.sha256(path.read_bytes()).hexdigest(),- )- for path in files- }- original_delete = _maintenance(runtime)._runtime.delete_surface-- async def fail_after_call_log(surface, target_epoch):- if surface.surface == "attachments":- raise OSError("injected failure after call-log deletion")- await original_delete(surface, target_epoch)-- _replace_runtime_port(runtime, delete_surface=fail_after_call_log)- failed = await _clear(runtime, operator_ref="user:owner")- recovery = _maintenance(runtime)._clear_journal.get_open_operation()-- assert failed["status"] == "failed"- assert recovery is not None and recovery.destructive_started- assert all(not path.exists() for path in files)-- _replace_runtime_port(runtime, delete_surface=original_delete)- aborted = await _abort_clear(runtime,- recovery.operation_id,- operator_ref="user:owner",- )+ assert result.status == "completed"+ assert result.operation_id != legacy_intent.operation_id+ assert len(port.deleted) == len(DEFAULT_CLEAR_SURFACES)+ assert ClearIntentStore(tmp_path).load() is None+ assert maintenance.is_open() is False- assert aborted["status"] == "aborted"- for path, (expected_bytes, expected_mode, expected_digest) in before.items():- restored_bytes = path.read_bytes()- assert restored_bytes == expected_bytes- assert stat.S_IMODE(path.stat().st_mode) == expected_mode- assert hashlib.sha256(restored_bytes).hexdigest() == expected_digest- assert _maintenance(runtime)._clear_journal.get_open_operation() is None- await memory_runtime_factory.close(runtime)+def test_legacy_cleanup_defers_while_operation_lease_is_busy(tmp_path: Path):+ journal = tmp_path / "state/memory/clear-journal.sqlite"+ journal.parent.mkdir(parents=True)+ journal.write_bytes(b"not sqlite")+ lease = MemoryOperationLease(tmp_path)+ lease.acquire()+ try:+ maintenance, _port = _maintenance(tmp_path)+ assert journal.exists()+ assert ClearIntentStore(tmp_path).load() is None+ assert maintenance.is_open() is True+ finally:+ lease.release()-async def test_completed_clear_snapshot_removal_retries_on_reconcile_and_restart(- monkeypatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- storage = _maintenance(runtime)._clear_snapshot_storage- manager = _maintenance(runtime)._snapshot_manager- assert storage is not None- assert manager is not None- original_remove = storage.remove_terminal_snapshot- removal_attempts: list[str] = []-- def fail_removal(operation_id: str) -> None:- if manager.snapshot_path(operation_id).exists():- removal_attempts.append(operation_id)- raise OSError("injected snapshot removal failure")- original_remove(operation_id)-- monkeypatch.setattr(storage, "remove_terminal_snapshot", fail_removal)- completed = await _clear(runtime, operator_ref="user:owner")- snapshot_path = manager.snapshot_path(completed["operation_id"])-- assert completed["status"] == "completed"- assert removal_attempts == [completed["operation_id"]]- assert snapshot_path.is_dir()-- monkeypatch.setattr(storage, "remove_terminal_snapshot", original_remove)- assert await runtime.reconcile(MemoryConfig()) == {"ok": True, "state": "disabled"}- reconcile_gc = _maintenance(runtime)._terminal_snapshot_gc_task- assert reconcile_gc is not None- await reconcile_gc- assert not snapshot_path.exists()-- monkeypatch.setattr(storage, "remove_terminal_snapshot", fail_removal)- completed_before_restart = await _clear(runtime, operator_ref="user:owner")- restart_snapshot_path = manager.snapshot_path(completed_before_restart["operation_id"])- assert restart_snapshot_path.is_dir()- await memory_runtime_factory.close(runtime)-- restarted = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)-- assert restart_snapshot_path.is_dir()- assert _maintenance(restarted)._clear_journal is not None- assert _maintenance(restarted)._clear_journal.get_open_operation() is None- assert await restarted.reconcile(MemoryConfig()) == {- "ok": True,- "state": "disabled",- }- restart_gc = _maintenance(restarted)._terminal_snapshot_gc_task- assert restart_gc is not None- await restart_gc- assert not restart_snapshot_path.exists()- await memory_runtime_factory.close(restarted)---async def _retain_terminal_clear_snapshot(- monkeypatch: pytest.MonkeyPatch,- home: Path,- memory_runtime_factory,-) -> Path:- runtime = memory_runtime_factory(MemoryConfig(), effective_home=home)- storage = _maintenance(runtime)._clear_snapshot_storage- manager = _maintenance(runtime)._snapshot_manager- assert storage is not None- assert manager is not None-- def retain(_operation_id: str) -> None:- raise OSError("retain terminal snapshot for startup GC")-- monkeypatch.setattr(storage, "remove_terminal_snapshot", retain)- completed = await _clear(runtime, operator_ref="user:owner")- snapshot_path = manager.snapshot_path(completed["operation_id"])- assert completed["status"] == "completed"- assert snapshot_path.is_dir()- await memory_runtime_factory.close(runtime)- return snapshot_path---async def test_terminal_snapshot_gc_is_scheduled_after_lifecycle_returns(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- entered = threading.Event()- release = threading.Event()- original_remove = MemoryClearSnapshotStorage.remove_terminal_snapshot- snapshot_path = await _retain_terminal_clear_snapshot(- monkeypatch,- tmp_path,- memory_runtime_factory,- )+ assert asyncio.run(maintenance.reconcile_pending()) is False+ failed = ClearIntentStore(tmp_path).load()+ assert failed is not None+ assert failed.error_code == "memory_clear_legacy_state_requires_rerun"+ assert not journal.exists()- def blocking_remove(- storage: MemoryClearSnapshotStorage,- operation_id: str,- ) -> None:- entered.set()- assert release.wait(timeout=2)- original_remove(storage, operation_id)-- monkeypatch.setattr(- MemoryClearSnapshotStorage,- "remove_terminal_snapshot",- blocking_remove,- )- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- assert await runtime.reconcile(MemoryConfig()) == {- "ok": True,- "state": "disabled",- }- assert entered.is_set() is False- gc_task = _maintenance(runtime)._terminal_snapshot_gc_task- assert gc_task is not None- assert await asyncio.to_thread(entered.wait, 1)+def test_legacy_cleanup_lease_failure_fences_memory(tmp_path: Path, monkeypatch):+ journal = tmp_path / "state/memory/clear-journal.sqlite"+ journal.parent.mkdir(parents=True)+ journal.write_bytes(b"not sqlite")+ from core.memory import maintenance as maintenance_module- release.set()- await asyncio.wait_for(asyncio.shield(gc_task), timeout=1)- assert not snapshot_path.exists()- await memory_runtime_factory.close(runtime)+ def fail_acquire(_lease):+ raise OSError("lock path unavailable")+ monkeypatch.setattr(maintenance_module.MemoryOperationLease, "acquire", fail_acquire)+ maintenance, _port = _maintenance(tmp_path)-async def test_terminal_snapshot_gc_shutdown_joins_cancelled_io(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- entered = threading.Event()- release = threading.Event()- finished = threading.Event()- original_remove = MemoryClearSnapshotStorage.remove_terminal_snapshot- snapshot_path = await _retain_terminal_clear_snapshot(- monkeypatch,- tmp_path,- memory_runtime_factory,- )+ assert maintenance.is_open() is True+ assert maintenance._initialization_error is not None+ assert ClearIntentStore(tmp_path).load() is None+ assert journal.exists()- def blocking_remove(- storage: MemoryClearSnapshotStorage,- operation_id: str,- ) -> None:- entered.set()- assert release.wait(timeout=2)- try:- original_remove(storage, operation_id)- finally:- finished.set()-- monkeypatch.setattr(- MemoryClearSnapshotStorage,- "remove_terminal_snapshot",- blocking_remove,- )- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- await runtime.reconcile(MemoryConfig())- gc_task = _maintenance(runtime)._terminal_snapshot_gc_task- assert gc_task is not None- assert await asyncio.to_thread(entered.wait, 1)-- closing = asyncio.create_task(_maintenance(runtime).close())- await asyncio.sleep(0)- closing.cancel()- await asyncio.sleep(0)- assert not closing.done()- release.set()- with pytest.raises(asyncio.CancelledError):- await asyncio.wait_for(closing, timeout=1)- assert finished.is_set()- assert gc_task.done()- assert _maintenance(runtime)._terminal_snapshot_gc_task is None- assert not snapshot_path.exists()+def test_legacy_cleanup_lease_release_failure_is_contained(tmp_path: Path, monkeypatch):+ snapshot = tmp_path / "state/memory/clear-snapshots/snapshot.json"+ snapshot.parent.mkdir(parents=True)+ snapshot.write_text("obsolete", encoding="utf-8")+ from core.memory import maintenance as maintenance_module+ original_release = maintenance_module.MemoryOperationLease.release-async def test_aborted_clear_snapshot_removal_retries_on_reconcile_and_restart(- monkeypatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- journal = _maintenance(runtime)._clear_journal- storage = _maintenance(runtime)._clear_snapshot_storage- manager = _maintenance(runtime)._snapshot_manager- assert journal is not None- assert storage is not None- assert manager is not None- original_delete = _maintenance(runtime)._runtime.delete_surface- original_remove = storage.remove_terminal_snapshot- removal_attempts: list[str] = []-- async def interrupt_provider(surface, target_epoch):- if surface.surface == "provider":- raise OSError("injected provider delete failure")- await original_delete(surface, target_epoch)-- def fail_removal(operation_id: str) -> None:- if manager.snapshot_path(operation_id).exists():- removal_attempts.append(operation_id)- raise OSError("injected snapshot removal failure")- original_remove(operation_id)-- async def abort_after_interrupted_clear() -> dict:- _replace_runtime_port(runtime, delete_surface=interrupt_provider)- failed = await _clear(runtime, operator_ref="user:owner")- recovery = journal.get_open_operation()- assert failed["status"] == "failed"- assert recovery is not None- _replace_runtime_port(runtime, delete_surface=original_delete)- return await _abort_clear(runtime,- recovery.operation_id,- operator_ref="user:owner",- )-- monkeypatch.setattr(storage, "remove_terminal_snapshot", fail_removal)- aborted = await abort_after_interrupted_clear()- snapshot_path = manager.snapshot_path(aborted["operation_id"])-- assert aborted["status"] == "aborted"- assert removal_attempts == [aborted["operation_id"]]- assert snapshot_path.is_dir()- terminal = journal.get_operation(aborted["operation_id"])- assert terminal is not None and terminal.state == "aborted"-- monkeypatch.setattr(storage, "remove_terminal_snapshot", original_remove)- assert await runtime.reconcile(MemoryConfig()) == {"ok": True, "state": "disabled"}- reconcile_gc = _maintenance(runtime)._terminal_snapshot_gc_task- assert reconcile_gc is not None- await reconcile_gc- assert not snapshot_path.exists()-- monkeypatch.setattr(storage, "remove_terminal_snapshot", fail_removal)- aborted_before_restart = await abort_after_interrupted_clear()- restart_snapshot_path = manager.snapshot_path(aborted_before_restart["operation_id"])- assert restart_snapshot_path.is_dir()- await memory_runtime_factory.close(runtime)-- restarted = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)-- assert restart_snapshot_path.is_dir()- assert _maintenance(restarted)._clear_journal is not None- assert _maintenance(restarted)._clear_journal.get_open_operation() is None- assert await restarted.reconcile(MemoryConfig()) == {- "ok": True,- "state": "disabled",- }- restart_gc = _maintenance(restarted)._terminal_snapshot_gc_task- assert restart_gc is not None- await restart_gc- assert not restart_snapshot_path.exists()- await memory_runtime_factory.close(restarted)---async def test_cancelled_clear_waits_for_snapshot_creation_before_releasing_fences(- monkeypatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- started = threading.Event()- release = threading.Event()- finished = threading.Event()- original_create = MemorySnapshotManager.create-- def blocking_create(manager: MemorySnapshotManager, snapshot_id: str | None = None):- if manager is _maintenance(runtime)._snapshot_manager:- started.set()- assert release.wait(2)- try:- return original_create(manager, snapshot_id)- finally:- if manager is _maintenance(runtime)._snapshot_manager:- finished.set()-- monkeypatch.setattr(MemorySnapshotManager, "create", blocking_create)- clearing = asyncio.create_task(_clear(runtime, operator_ref="user:owner"))- assert await asyncio.to_thread(started.wait, 1)- operation = _maintenance(runtime)._clear_journal.get_open_operation()- assert operation is not None-- clearing.cancel()- await asyncio.sleep(0)-- assert clearing.done() is False- assert runtime._reconcile_lock.locked()- assert runtime.module._lifecycle_lock.locked()- resuming = asyncio.create_task(- _resume_clear(runtime, operation.operation_id, operator_ref="user:owner")- )- await asyncio.sleep(0)- assert resuming.done() is False- resuming.cancel()- with pytest.raises(asyncio.CancelledError):- await resuming+ def release_then_fail(lease):+ original_release(lease)+ raise OSError("lock descriptor close failed")- release.set()- with pytest.raises(asyncio.CancelledError):- await clearing-- assert finished.is_set()- recovery = _maintenance(runtime)._clear_journal.get_open_operation()- assert recovery is not None- assert recovery.state == "recovery_needed"- assert recovery.recovery_from_state == "preparing"-- discard_started = threading.Event()- discard_release = threading.Event()- discard_finished = threading.Event()- original_discard = (- MemoryClearSnapshotStorage.discard_unrecorded_preparing_snapshot- )+ monkeypatch.setattr(maintenance_module.MemoryOperationLease, "release", release_then_fail)- def blocking_discard(- storage: MemoryClearSnapshotStorage,- operation_id: str,- **kwargs,- ):- if storage is _maintenance(runtime)._clear_snapshot_storage:- discard_started.set()- assert discard_release.wait(2)- try:- return original_discard(storage, operation_id, **kwargs)- finally:- if storage is _maintenance(runtime)._clear_snapshot_storage:- discard_finished.set()-- monkeypatch.setattr(- MemoryClearSnapshotStorage,- "discard_unrecorded_preparing_snapshot",- blocking_discard,- )- resuming = asyncio.create_task(- _resume_clear(runtime, recovery.operation_id, operator_ref="user:owner")- )- assert await asyncio.to_thread(discard_started.wait, 1)- resuming.cancel()- await asyncio.sleep(0)- assert resuming.done() is False- assert runtime._reconcile_lock.locked()- assert runtime.module._lifecycle_lock.locked()-- discard_release.set()- with pytest.raises(asyncio.CancelledError):- await resuming-- assert discard_finished.is_set()- pending = _maintenance(runtime)._clear_journal.get_open_operation()- assert pending is not None- assert pending.state == "recovery_needed"- assert pending.resolution == "resume"-- monkeypatch.setattr(- MemoryClearSnapshotStorage,- "discard_unrecorded_preparing_snapshot",- original_discard,- )- completed = await _resume_clear(runtime, pending.operation_id, operator_ref="user:owner")- assert completed["status"] == "completed"- await memory_runtime_factory.close(runtime)+ maintenance, _port = _maintenance(tmp_path)+ assert maintenance.is_open() is True+ assert maintenance._initialization_error is not None+ assert maintenance._legacy_migration_deferred is True-async def test_cancelled_clear_waits_for_snapshot_verification_before_releasing_fences(- monkeypatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- started = threading.Event()- release = threading.Event()- finished = threading.Event()- original_verify = MemorySnapshotManager.verify-- def blocking_verify(manager: MemorySnapshotManager, snapshot_id: str, **kwargs):- if manager is _maintenance(runtime)._snapshot_manager:- started.set()- assert release.wait(2)- try:- return original_verify(manager, snapshot_id, **kwargs)- finally:- if manager is _maintenance(runtime)._snapshot_manager:- finished.set()-- monkeypatch.setattr(MemorySnapshotManager, "verify", blocking_verify)- clearing = asyncio.create_task(_clear(runtime, operator_ref="user:owner"))- assert await asyncio.to_thread(started.wait, 1)-- clearing.cancel()- await asyncio.sleep(0)-- assert clearing.done() is False- assert runtime._reconcile_lock.locked()- assert runtime.module._lifecycle_lock.locked()- release.set()- with pytest.raises(asyncio.CancelledError):- await clearing- assert finished.is_set()- recovery = _maintenance(runtime)._clear_journal.get_open_operation()- assert recovery is not None- assert recovery.state == "recovery_needed"- assert recovery.recovery_from_state == "prepared"+def test_legacy_open_row_creates_failed_projection_without_boot_delete(tmp_path: Path):+ journal = tmp_path / "state/memory/clear-journal.sqlite"+ journal.parent.mkdir(parents=True)+ connection = sqlite3.connect(journal)+ connection.execute("CREATE TABLE clear_operation (open_slot)")+ connection.execute("INSERT INTO clear_operation VALUES (?)", ("open",))+ connection.commit()+ connection.close()+ journal.chmod(0o600)- monkeypatch.setattr(MemorySnapshotManager, "verify", original_verify)- completed = await _resume_clear(runtime, recovery.operation_id, operator_ref="user:owner")- assert completed["status"] == "completed"- await memory_runtime_factory.close(runtime)+ maintenance, port = _maintenance(tmp_path)+ projection = maintenance._read_projection()+ assert projection is not None+ assert projection.state == "failed"+ assert projection.error_code == "memory_clear_legacy_state_requires_rerun"+ assert asyncio.run(maintenance.reconcile_pending()) is False+ assert port.deleted == []+ assert not journal.exists()-async def test_cancelled_clear_waits_for_provider_delete_before_releasing_fences(- monkeypatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- runtime._provider_root_owner.ensure(- runtime._store.ensure_meta(),- runtime._active_provider_root_metadata(),- )- started = threading.Event()- release = threading.Event()- finished = threading.Event()- original_recreate = runtime._provider_root_owner.recreate_empty- def blocking_recreate(meta, metadata) -> None:- started.set()- assert release.wait(2)- try:- original_recreate(meta, metadata)- finally:- finished.set()-- monkeypatch.setattr(- runtime._provider_root_owner,- "recreate_empty",- blocking_recreate,- )- clearing = asyncio.create_task(_clear(runtime, operator_ref="user:owner"))- assert await asyncio.to_thread(started.wait, 5)+def test_terminal_legacy_journal_is_cleaned_without_fence(tmp_path: Path):+ journal = tmp_path / "state/memory/clear-journal.sqlite"+ journal.parent.mkdir(parents=True)+ connection = sqlite3.connect(journal)+ connection.execute("CREATE TABLE clear_operation (open_slot)")+ connection.execute("INSERT INTO clear_operation VALUES (NULL)")+ connection.commit()+ connection.close()+ journal.chmod(0o600)- clearing.cancel()- await asyncio.sleep(0)+ maintenance, _port = _maintenance(tmp_path)- assert clearing.done() is False- assert runtime._reconcile_lock.locked()- assert runtime.module._lifecycle_lock.locked()- assert runtime.module._root_lifecycle_lock().locked()- release.set()- with pytest.raises(asyncio.CancelledError):- await clearing-- assert finished.is_set()- recovery = _maintenance(runtime)._clear_journal.get_open_operation()- assert recovery is not None- assert recovery.state == "recovery_needed"- assert recovery.recovery_from_state == "deleting"-- monkeypatch.setattr(- runtime._provider_root_owner,- "recreate_empty",- original_recreate,- )- completed = await _resume_clear(runtime,- recovery.operation_id,- operator_ref="user:owner",- )- assert completed["status"] == "completed"- await memory_runtime_factory.close(runtime)+ assert maintenance.is_open() is False+ assert ClearIntentStore(tmp_path).load() is None+ assert not journal.exists()-async def test_cancelled_abort_waits_for_restore_before_releasing_fences(- monkeypatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- _enqueue(runtime, "cancel-abort-source")- original_delete = _maintenance(runtime)._runtime.delete_surface-- async def interrupt_provider(surface, target_epoch):- if surface.surface == "provider":- raise OSError("injected provider delete failure")- await original_delete(surface, target_epoch)+def test_legacy_backup_and_snapshot_residue_is_best_effort(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ backup_journal = tmp_path / "state/memory/backup-restore-journal.sqlite"+ snapshot = tmp_path / "state/memory/clear-snapshots/old/data"+ for path in (backup_journal, snapshot):+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("obsolete", encoding="utf-8")+ from core.memory import clear_intent- _replace_runtime_port(runtime, delete_surface=interrupt_provider)- failed = await _clear(runtime, operator_ref="user:owner")- recovery = _maintenance(runtime)._clear_journal.get_open_operation()- assert failed["status"] == "failed"- assert recovery is not None- _replace_runtime_port(runtime, delete_surface=original_delete)+ original_remove = clear_intent.remove_confined_path- started = threading.Event()- release = threading.Event()- finished = threading.Event()- original_restore = MemorySnapshotManager.restore-- def blocking_restore(manager: MemorySnapshotManager, snapshot_id: str, **kwargs):- if manager is _maintenance(runtime)._snapshot_manager:- started.set()- assert release.wait(2)- try:- return original_restore(manager, snapshot_id, **kwargs)- finally:- if manager is _maintenance(runtime)._snapshot_manager:- finished.set()-- monkeypatch.setattr(MemorySnapshotManager, "restore", blocking_restore)- aborting = asyncio.create_task(- _abort_clear(runtime, recovery.operation_id, operator_ref="user:owner")- )- assert await asyncio.to_thread(started.wait, 1)+ def fail_backup_remove(home: Path, path: Path):+ if path == backup_journal:+ raise clear_intent.ConfinedFilesystemError("busy")+ return original_remove(home, path)- aborting.cancel()- await asyncio.sleep(0)+ monkeypatch.setattr(clear_intent, "remove_confined_path", fail_backup_remove)- assert aborting.done() is False- assert runtime._reconcile_lock.locked()- assert runtime.module._lifecycle_lock.locked()- release.set()- with pytest.raises(asyncio.CancelledError):- await aborting-- assert finished.is_set()- pending = _maintenance(runtime)._clear_journal.get_open_operation()- assert pending is not None- assert pending.state == "recovery_needed"- assert pending.resolution == "abort"- assert pending.execution_token is None- assert _maintenance(runtime).recovery().can_resume is False-- monkeypatch.setattr(MemorySnapshotManager, "restore", original_restore)- journal = _maintenance(runtime)._clear_journal- terminal_entered = threading.Event()- terminal_release = threading.Event()- original_mark_aborted = journal.mark_aborted-- def blocking_mark_aborted(operation_id: str, **kwargs):- operation = original_mark_aborted(operation_id, **kwargs)- terminal_entered.set()- assert terminal_release.wait(2)- return operation-- resume_calls = 0- original_resume = _maintenance(runtime)._runtime.resume-- async def counted_resume() -> None:- nonlocal resume_calls- resume_calls += 1- await original_resume()-- monkeypatch.setattr(journal, "mark_aborted", blocking_mark_aborted)- _replace_runtime_port(runtime, resume=counted_resume)- aborting = asyncio.create_task(- _abort_clear(runtime, pending.operation_id, operator_ref="user:owner")- )- assert await asyncio.to_thread(terminal_entered.wait, 1)+ maintenance, _port = _maintenance(tmp_path)- aborting.cancel()- await asyncio.sleep(0)+ assert maintenance.is_open() is False+ assert backup_journal.exists()+ assert not snapshot.exists()- assert aborting.done() is False- assert runtime._reconcile_lock.locked()- assert runtime.module._lifecycle_lock.locked()- assert runtime.module._root_lifecycle_lock().locked()- terminal_release.set()- with pytest.raises(asyncio.CancelledError):- await aborting- aborted = journal.get_operation(pending.operation_id)- assert aborted is not None- assert aborted.state == "aborted"- assert _maintenance(runtime)._clear_journal.get_open_operation() is None- assert resume_calls == 1- await memory_runtime_factory.close(runtime)+async def test_clear_runs_legacy_rescan_off_event_loop(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ maintenance, _port = _maintenance(tmp_path)+ event_loop_thread = threading.get_ident()+ rescan_threads: list[int] = []+ original_migrate = maintenance._migrate_legacy+ def tracked_migrate(store: MemoryStore | None, *, lease_held: bool = False) -> None:+ rescan_threads.append(threading.get_ident())+ original_migrate(store, lease_held=lease_held)-async def test_maintenance_backup_fences_capture_and_clear_for_the_full_copy(- monkeypatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(enabled=True), effective_home=tmp_path)- enqueue_entered = threading.Event()- release_enqueue = threading.Event()- entered = threading.Event()- release = threading.Event()- original_create = MemorySnapshotManager.create- original_enqueue = runtime._store.enqueue_request-- def blocking_enqueue(**kwargs):- enqueue_entered.set()- assert release_enqueue.wait(2)- return original_enqueue(**kwargs)-- def blocking_create(manager: MemorySnapshotManager, snapshot_id: str | None = None):- if manager.snapshot_root == tmp_path / "state" / "memory" / "backups":- entered.set()- assert release.wait(2)- return original_create(manager, snapshot_id)-- async def resume_without_sidecar() -> None:- runtime.module._worker.resume_claims()-- monkeypatch.setattr(MemorySnapshotManager, "create", blocking_create)- monkeypatch.setattr(runtime._store, "enqueue_request", blocking_enqueue)- _replace_runtime_port(runtime, resume=resume_without_sidecar)-- capturing = asyncio.create_task(- runtime.module.capture(- CaptureRequest(- source_message_id="before-backup",- session_id="session",- principal_id=PRINCIPAL,- project_id=PROJECT,- provenance="user_input",- text="must be included",- occurred_at_ms=1,- )- )- )- assert await asyncio.to_thread(enqueue_entered.wait, 1)- creating = asyncio.create_task(_maintenance(runtime).create_backup("runtime-fence"))- await asyncio.sleep(0)- assert entered.is_set() is False- release_enqueue.set()- assert await capturing == CaptureAccepted()- assert await asyncio.to_thread(entered.wait, 1)- assert _maintenance(runtime).is_open() is True- receipt = await runtime.module.capture(- CaptureRequest(- source_message_id="blocked-capture",- session_id="session",- principal_id=PRINCIPAL,- project_id=PROJECT,- provenance="user_input",- text="must wait for backup",- occurred_at_ms=2,- )- )- assert receipt == CaptureSkipped(reason="memory_clear_failed")-- clearing = asyncio.create_task(_clear(runtime, operator_ref="user:owner"))- await asyncio.sleep(0)- assert clearing.done() is False- assert _maintenance(runtime)._clear_journal.get_open_operation() is None-- clearing.cancel()- with pytest.raises(asyncio.CancelledError):- await clearing- creating.cancel()- await asyncio.sleep(0)- assert creating.done() is False- assert _maintenance(runtime).is_open() is True- release.set()- with pytest.raises(asyncio.CancelledError):- await creating- assert (tmp_path / "state" / "memory" / "backups" / "runtime-fence").is_dir()- assert _maintenance(runtime).is_open() is False- await memory_runtime_factory.close(runtime)+ monkeypatch.setattr(maintenance, "_migrate_legacy", tracked_migrate)+ result = await maintenance.clear(operator_ref="user-1")++ assert result.status == "completed"+ assert rescan_threads+ assert all(thread_id != event_loop_thread for thread_id in rescan_threads)-async def test_reconcile_schedules_auto_id_backup_stage_cleanup(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- manager = _maintenance(runtime)._backup_manager- assert manager is not None- stage = manager.snapshot_root / f".{('a' * 32)}.tmp"- stage.mkdir(parents=True, mode=0o700)- manager.snapshot_root.chmod(0o700)- stage.chmod(0o700)- (stage / "partial.bin").write_bytes(b"partial")- (stage / "partial.bin").chmod(0o600)-- assert await runtime.reconcile(MemoryConfig()) == {- "ok": True,- "state": "disabled",- }- task = _maintenance(runtime)._backup_stage_reconcile_task- if task is not None:- await task-- assert not stage.exists()- await memory_runtime_factory.close(runtime)---async def test_backup_stage_cleanup_waits_for_terminal_snapshot_gc(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- storage = _maintenance(runtime)._clear_snapshot_storage- manager = _maintenance(runtime)._backup_manager- assert storage is not None- assert manager is not None- terminal_entered = threading.Event()- terminal_release = threading.Event()- backup_entered = threading.Event()- original_ids = storage.eligible_terminal_snapshot_ids-- def blocking_ids():- terminal_entered.set()- assert terminal_release.wait(2)- return original_ids()-- def observe_backup_cleanup() -> tuple[str, ...]:- backup_entered.set()- return ()-- monkeypatch.setattr(storage, "eligible_terminal_snapshot_ids", blocking_ids)- monkeypatch.setattr(- manager,- "reconcile_unpublished_backup_stages",- observe_backup_cleanup,- )+async def test_failed_clear_retry_rebases_after_store_epoch_moves(tmp_path: Path):+ maintenance, port = _maintenance(tmp_path)+ store = maintenance._store+ assert store is not None+ failed = ClearIntent.new(operator_ref="old", pre_epoch=store.ensure_meta().epoch).failed(+ "memory_clear_failed"+ )+ ClearIntentStore(tmp_path).write(failed)+ store.reset_for_clear()+ store.reset_for_clear()++ result = await maintenance.clear(operator_ref="user-1")++ assert result.status == "completed"+ assert result.epoch == 3+ assert {epoch for _surface, epoch in port.deleted} == {3}+++async def test_boot_quiesce_failure_persists_failed_marker(tmp_path: Path):+ maintenance, port = _maintenance(tmp_path)+ meta = maintenance._store.ensure_meta() # type: ignore[union-attr]+ intent = ClearIntent.new(operator_ref="boot", pre_epoch=meta.epoch)+ ClearIntentStore(tmp_path).write(intent)+ port.fail_quiesce = True++ assert await maintenance.reconcile_pending() is False+ failed = ClearIntentStore(tmp_path).load()+ assert failed is not None+ assert failed.state == "failed"+ assert failed.error_code == "memory_clear_failed"- assert await runtime.reconcile(MemoryConfig()) == {- "ok": True,- "state": "disabled",- }- assert await asyncio.to_thread(terminal_entered.wait, 1)- await asyncio.sleep(0)- assert backup_entered.is_set() is False- terminal_release.set()- terminal_gc = _maintenance(runtime)._terminal_snapshot_gc_task- backup_reconcile = _maintenance(runtime)._backup_stage_reconcile_task- assert terminal_gc is not None- assert backup_reconcile is not None- await terminal_gc- await backup_reconcile+async def test_boot_retry_requiesces_claims(tmp_path: Path):+ maintenance, port = _maintenance(tmp_path)+ meta = maintenance._store.ensure_meta() # type: ignore[union-attr]+ ClearIntentStore(tmp_path).write(ClearIntent.new(operator_ref="boot", pre_epoch=meta.epoch))+ assert await maintenance.reconcile_pending() is True+ assert port.quiesce_modes == [False]- assert backup_entered.is_set() is True- await memory_runtime_factory.close(runtime)+async def test_terminal_marker_removal_cancellation_resumes_runtime(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ import threading-async def test_backup_stage_cleanup_cancellation_joins_filesystem_io(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- manager = _maintenance(runtime)._backup_manager- assert manager is not None- entered = threading.Event()+ maintenance, port = _maintenance(tmp_path)+ original_remove = maintenance._intent.remove+ started = threading.Event()release = threading.Event()- def blocking_reconcile() -> tuple[str, ...]:- entered.set()- assert release.wait(2)- return ()-- monkeypatch.setattr(manager, "reconcile_unpublished_backup_stages", blocking_reconcile)- assert await runtime.reconcile(MemoryConfig()) == {- "ok": True,- "state": "disabled",- }- assert await asyncio.to_thread(entered.wait, 1)- assert _maintenance(runtime).is_open() is False-- maintenance_close_entered = asyncio.Event()- maintenance = _maintenance(runtime)- original_maintenance_close = maintenance.close-- async def observed_maintenance_close() -> None:- maintenance_close_entered.set()- await original_maintenance_close()-- monkeypatch.setattr(maintenance, "close", observed_maintenance_close)- closing = asyncio.create_task(memory_runtime_factory.close(runtime))- close_results: list[object] = []- try:- await asyncio.wait_for(maintenance_close_entered.wait(), timeout=1.0)- assert closing.done() is False- finally:- release.set()- close_results.extend(- await asyncio.gather(closing, return_exceptions=True)- )- assert close_results == [None]- assert _maintenance(runtime)._backup_stage_reconcile_task is None---async def test_backup_stage_cleanup_queues_capture_without_global_maintenance_fence(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(enabled=True), effective_home=tmp_path)- manager = _maintenance(runtime)._backup_manager- assert manager is not None- entered = threading.Event()- release = threading.Event()+ def remove_then_cancel():+ started.set()+ release.wait()+ original_remove()- def blocking_reconcile() -> tuple[str, ...]:- entered.set()- assert release.wait(2)- return ()-- monkeypatch.setattr(manager, "reconcile_unpublished_backup_stages", blocking_reconcile)- cleanup = asyncio.create_task(_maintenance(runtime)._run_backup_stage_reconcile())- assert await asyncio.to_thread(entered.wait, 1)- assert runtime._reconcile_lock.locked()- assert runtime.module._lifecycle_lock.locked()- assert runtime.module._root_lifecycle_lock().locked()-- capturing = asyncio.create_task(- runtime.module.capture(- CaptureRequest(- source_message_id="during-backup-stage-cleanup",- session_id="session",- principal_id=PRINCIPAL,- project_id=PROJECT,- provenance="user_input",- text="must be captured after cleanup",- occurred_at_ms=1,- )- )- )- await asyncio.sleep(0)- completed_during_cleanup = capturing.done()+ monkeypatch.setattr(maintenance._intent, "remove", remove_then_cancel)+ clear_task = asyncio.create_task(maintenance.clear(operator_ref="user-1"))+ assert await asyncio.to_thread(started.wait, 1.0)+ clear_task.cancel()release.set()-- await cleanup- assert completed_during_cleanup is False- assert await capturing == CaptureAccepted()- assert [row.payload_text for row in runtime._store.list_queue_rows()] == [- "must be captured after cleanup"- ]- await memory_runtime_factory.close(runtime)---async def test_queued_backup_stage_reconcile_rechecks_artifact_install(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- install_entered = threading.Event()- release_install = threading.Event()-- class BlockingArtifact(FakeMemoryArtifactManager):- def ensure(self, *, force: bool = False) -> dict:- self.ensure_calls.append(force)- install_entered.set()- release_install.wait(timeout=2)- return dict(self.ensure_payload)-- runtime = memory_runtime_factory(- MemoryConfig(enabled=False),- artifact_manager=BlockingArtifact(python=Path(sys.executable)),- effective_home=tmp_path,- )- terminal_gc_entered = asyncio.Event()- release_terminal_gc = asyncio.Event()- cleanup_finished = threading.Event()- cleanup_calls: list[bool] = []- maintenance = _maintenance(runtime)-- async def blocked_terminal_gc() -> None:- terminal_gc_entered.set()- await release_terminal_gc.wait()-- manager = maintenance._backup_manager- assert manager is not None- monkeypatch.setattr(maintenance, "_run_terminal_snapshot_gc", blocked_terminal_gc)- def reconcile_unpublished_backup_stages() -> None:- cleanup_calls.append(runtime._artifact_installing)- cleanup_finished.set()-- monkeypatch.setattr(manager, "reconcile_unpublished_backup_stages", reconcile_unpublished_backup_stages)-- maintenance.ensure_housekeeping()- await terminal_gc_entered.wait()- queued_reconcile = maintenance._backup_stage_reconcile_task- assert queued_reconcile is not None-- installing = asyncio.create_task(runtime.install_artifact())- assert await asyncio.to_thread(install_entered.wait, 1)- release_terminal_gc.set()- await queued_reconcile- assert cleanup_calls == []-- release_install.set()- assert (await installing)["ok"] is True- assert await asyncio.to_thread(cleanup_finished.wait, 2)- deferred_reconcile = maintenance._backup_stage_reconcile_task- # The completion callback may clear a task before this assertion runs on a- # fast event loop. Observe the cleanup contract instead of that transient- # implementation detail, while still awaiting a task if it remains held.- if deferred_reconcile is not None:- assert deferred_reconcile is not queued_reconcile- await deferred_reconcile- assert cleanup_calls == [False]- await memory_runtime_factory.close(runtime)---async def test_maintenance_backup_restore_round_trips_queue_state(- monkeypatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- _enqueue(runtime, "backup-source")- restored_call_log: list[None] = []- _replace_runtime_port(- runtime,- restore_completed=lambda: restored_call_log.append(None),- )-- backup = await _maintenance(runtime).create_backup("runtime-round-trip")- meta = runtime._store.ensure_meta()- runtime._store.reset_for_clear(target_epoch=meta.epoch + 1)- assert runtime._store.list_queue_rows() == ()-- restored = await _maintenance(runtime).restore_backup(- backup.snapshot_id,- expected_manifest_sha256=backup.manifest_sha256,- expected_surface_digests=backup.surface_digests(),- )-- assert restored == backup- assert restored_call_log == [None]- rows = runtime._store.list_queue_rows()- assert len(rows) == 1- assert rows[0].source_message_digest- await memory_runtime_factory.close(runtime)--- ("crash_surface", "crash_target"),- (- ("queue", "state/memory/memory.sqlite"),- ("provider", "memory/everos-root"),- ("call_log", "memory/call-log/call-log.db"),- ("attachments", "memory/attachments"),- ),-)-async def test_backup_restore_crash_is_fenced_and_boot_converges_one_generation(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- crash_surface: str,- crash_target: str,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- _enqueue(runtime, "backup-queue")-- provider_marker = tmp_path / "memory/everos-root/generation.txt"- attachment_marker = tmp_path / "memory/attachments/generation.txt"- call_log = tmp_path / "memory/call-log/call-log.db"- for marker in (provider_marker, attachment_marker):- marker.parent.mkdir(parents=True, exist_ok=True, mode=0o700)- marker.parent.chmod(0o700)- marker.write_text("backup")- marker.chmod(0o600)- call_log.parent.mkdir(parents=True, exist_ok=True, mode=0o700)- call_log.parent.chmod(0o700)- with sqlite3.connect(call_log) as connection:- connection.execute("CREATE TABLE generation (value TEXT NOT NULL)")- connection.execute("INSERT INTO generation VALUES ('backup')")- call_log.chmod(0o600)-- backup = await _maintenance(runtime).create_backup("crash-safe-restore")- _enqueue(runtime, "live-queue")- provider_marker.write_text("live")- attachment_marker.write_text("live")- with sqlite3.connect(call_log) as connection:- connection.execute("UPDATE generation SET value = 'live'")-- target = tmp_path / crash_target- real_replace = snapshot_module.os.replace- crashed = False- intent_visible_before_replace = False-- class InjectedProcessDeath(BaseException):- pass-- def crash_after_surface_install(source, destination, *args, **kwargs):- nonlocal crashed, intent_visible_before_replace- if (- not crashed- and Path(destination).name == target.name- and f".restore-{backup.snapshot_id}-" in Path(source).name- and kwargs.get("src_dir_fd") is not None- and kwargs.get("dst_dir_fd") is not None- ):- open_operation = _maintenance(runtime)._backup_restore_journal.get_open_operation()- assert open_operation is not None- assert open_operation.state == "restoring"- intent_visible_before_replace = True- real_replace(source, destination, *args, **kwargs)- crashed = True- raise InjectedProcessDeath(crash_surface)- return real_replace(source, destination, *args, **kwargs)-- async def process_died_before_cleanup(_operation):- return None-- monkeypatch.setattr(snapshot_module.os, "replace", crash_after_surface_install)- monkeypatch.setattr(- _maintenance(runtime),- "_mark_backup_restore_recovery",- process_died_before_cleanup,- )- with pytest.raises(InjectedProcessDeath):- await _maintenance(runtime).restore_backup(- backup.snapshot_id,- expected_manifest_sha256=backup.manifest_sha256,- expected_surface_digests=backup.surface_digests(),- )- monkeypatch.setattr(snapshot_module.os, "replace", real_replace)-- assert crashed is True- assert intent_visible_before_replace is True- interrupted = _maintenance(runtime)._backup_restore_journal.get_open_operation()- assert interrupted is not None- assert interrupted.state == "restoring"- assert [- event.event- for event in _maintenance(runtime)._backup_restore_journal.get_events(- interrupted.operation_id- )- ] == ["started"]-- restarted = memory_runtime_factory(- MemoryConfig(enabled=True),- effective_home=tmp_path,- )- restored_call_log: list[None] = []- _replace_runtime_port(- restarted,- restore_completed=lambda: restored_call_log.append(None),- )- recovery = _maintenance(restarted)._backup_restore_journal.get_open_operation()- assert recovery is not None- assert recovery.state == "recovery_needed"- assert _maintenance(restarted).is_open() is True- assert restarted.module._worker._claims_paused is True- assert restarted._worker_task is None- assert restarted._process is None- blocked = await restarted.module.capture(- CaptureRequest(- source_message_id="blocked-before-restore-recovery",- session_id="session",- principal_id=PRINCIPAL,- project_id=PROJECT,- provenance="user_input",- text="must remain fenced",- occurred_at_ms=2,- )- )- assert blocked == CaptureSkipped(reason="memory_clear_failed")-- if crash_surface == "queue":- original_reap = SidecarOwnership.reap-- async def fail_reap(_ownership) -> None:- raise OSError("recorded sidecar is still live")-- monkeypatch.setattr(SidecarOwnership, "reap", fail_reap)- assert await restarted.reconcile(MemoryConfig()) == {- "ok": False,- "error": "memory_clear_failed",- }- still_fenced = _maintenance(restarted)._backup_restore_journal.get_open_operation()- assert still_fenced == recovery- assert restarted.module._worker._claims_paused is True- assert restored_call_log == []- monkeypatch.setattr(SidecarOwnership, "reap", original_reap)-- assert await restarted.reconcile(MemoryConfig()) == {- "ok": True,- "state": "disabled",- }- assert len(restarted._store.list_queue_rows()) == 1- assert provider_marker.read_text() == "backup"- assert attachment_marker.read_text() == "backup"- with sqlite3.connect(call_log) as connection:- assert connection.execute("SELECT value FROM generation").fetchone() == (- "backup",- )-- completed = _maintenance(restarted)._backup_restore_journal.get_operation(- recovery.operation_id- )- assert completed is not None- assert completed.state == "completed"- assert completed.attempt_count == 2- assert _maintenance(restarted)._backup_restore_journal.get_open_operation() is None- assert [- event.event- for event in _maintenance(restarted)._backup_restore_journal.get_events(- completed.operation_id- )- ] == ["started", "recovery_needed", "retry_started", "completed"]- assert _maintenance(restarted).is_open() is False- assert restored_call_log == [None]-- await memory_runtime_factory.close(runtime)- await memory_runtime_factory.close(restarted)+ result = await clear_task++ assert result.status == "completed"+ assert maintenance.is_open() is False+ assert port.resumed == 1+++async def test_committed_clear_fence_release_failure_does_not_restore_marker(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ maintenance, port = _maintenance(tmp_path)+ store = maintenance._store+ assert store is not None+ original_release = store.release_clear_fence++ def release_then_fail():+ original_release()+ raise OSError("post-commit mode hardening failed")++ monkeypatch.setattr(store, "release_clear_fence", release_then_fail)++ result = await maintenance.clear(operator_ref="user-1")++ assert result.status == "completed"+ assert store.clear_in_progress() is False+ assert ClearIntentStore(tmp_path).load() is None+ assert maintenance.is_open() is False+ assert port.resumed == 1+++def test_corrupt_marker_is_fail_closed(tmp_path: Path):+ marker = tmp_path / "state/memory/clear-intent.json"+ marker.parent.mkdir(parents=True)+ marker.write_text("not json", encoding="utf-8")+ maintenance, _port = _maintenance(tmp_path)++ observation = maintenance._read_projection()++ assert observation is not None+ assert observation.state == "failed"+ assert observation.error_code == "memory_clear_marker_unreadable"+++def test_orphaned_queue_clear_fence_is_exposed_for_explicit_repair(tmp_path: Path):+ maintenance, _port = _maintenance(tmp_path)+ store = maintenance._store+ assert store is not None+ store.begin_clear_fence()++ assert maintenance.is_open() is True+ assert maintenance.has_readable_intent() is False+ observation = maintenance._read_projection()+ assert observation is not None+ assert observation.state == "failed"+ assert observation.operation_id == "orphaned-fence"+ assert observation.error_code == "memory_clear_failed"+ payload = asyncio.run(maintenance.observe())+ assert payload.can_clear is True+++def test_queue_fence_read_failure_is_retryable(tmp_path: Path, monkeypatch):+ maintenance, _port = _maintenance(tmp_path)+ store = maintenance._store+ assert store is not None+ reads = 0++ def fail_fence_read():+ nonlocal reads+ reads += 1+ if reads <= 2:+ raise OSError("temporary queue read failure")+ return False++ monkeypatch.setattr(store, "clear_in_progress", fail_fence_read)++ assert maintenance.is_open() is True+ observation = asyncio.run(maintenance.observe())+ assert observation.can_clear is True+ assert observation.clear_in_progress is not None+ assert observation.clear_in_progress.operation_id == "orphaned-fence"+ assert maintenance.ready is True++ assert maintenance.is_open() is Falsediff --git a/tests/test_memory_processing_record.py b/tests/test_memory_processing_record.pyindex 29352dd3f..e69021db4 100644--- a/tests/test_memory_processing_record.py+++ b/tests/test_memory_processing_record.py@@ -1,1301 +1,47 @@from __future__ import annotations-import asyncio-import sqlite3-import threading-from dataclasses import replace-from datetime import UTC, datetime-from pathlib import Path-from types import SimpleNamespace-from typing import get_type_hints--import pytest--import core.memory.processing_record as processing_record_module-import core.memory.snapshot as snapshot_module-from config.v2_config import MemoryConfig-from core.memory.everos import ProviderHealthSnapshot-from core.memory.maintenance import (- ClearRecoveryResult,- MaintenanceObservation,- MaintenanceResult,-)+from core.memory.maintenance import ClearInProgressResultfrom core.memory.processing_record import (AnomalyProjection,- FailureLogObservation,MaintenanceProjection,- MemoryProcessingRecord,- MemoryProcessingRecordPort,ProcessingRecordSummary,ProcessingSourceObservations,ProviderCheckProjection,- RuntimeHealthObservation,RuntimeHealthProjection,SourceObservation,)-from core.memory.runtime import MemoryRuntime-from core.memory.store import Delivered-from core.memory.types import MemoryFailureLogEntry---def _health(recorder: dict[str, str | None]) -> ProviderHealthSnapshot:- return ProviderHealthSnapshot(- status="ok",- version="1.2.3",- capabilities={"llm": True},- disabled_features=(),- cascade=None,- recorder=recorder,- )---def _sources() -> ProcessingSourceObservations:- observed = SourceObservation(- "available",- observed_at="2026-08-09T00:00:00.000Z",- )- return ProcessingSourceObservations(- everos=observed,- capture=observed,- calls=observed,- )---class _RuntimeObservations:- def __init__(self) -> None:- self.health = RuntimeHealthObservation(- _health({"state": "active", "reason": None})- )- self.failures: tuple[MemoryFailureLogEntry, ...] = ()- self.recorder: dict[str, str | None] = {- "state": "active",- "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] = []- self.failure_error: Exception | None = None- self.maintenance_error: Exception | None = None- self.maintenance_observation_error: Exception | None = None-- async def observe_maintenance(- self,- operator_ref: str | None,- ) -> MaintenanceObservation:- self.operator_refs.append(operator_ref)- if self.maintenance_observation_error is not None:- raise self.maintenance_observation_error- return self.maintenance_observation-- async def resolve_operator(self, user_key: str) -> str:- return f"u-{user_key}"-- async def observe_health(- self,- maintenance_reason: str | None,- ) -> RuntimeHealthObservation:- if maintenance_reason is not None:- return RuntimeHealthObservation(None, maintenance_reason)- return self.health-- async def failure_log(- self,- maintenance_reason: str | None,- ) -> FailureLogObservation:- if self.failure_error is not None:- raise self.failure_error- if maintenance_reason is not None:- return FailureLogObservation((), maintenance_reason)- return FailureLogObservation(self.failures)-- def recorder_health(self) -> dict[str, str | None]:- return self.recorder-- async def observe_sources(- self,- maintenance_reason: str | None,- ) -> ProcessingSourceObservations:- if maintenance_reason is not None:- unavailable = SourceObservation(- "unavailable",- reason=maintenance_reason,- )- return ProcessingSourceObservations(- everos=unavailable,- capture=unavailable,- calls=unavailable,- )- return self.sources-- async def maintenance_payload(- self,- operator_ref: str | None,- _observation: MaintenanceObservation,- ) -> MaintenanceResult:- if self.maintenance_error is not None:- raise self.maintenance_error- return 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,- observe_maintenance=self.observe_maintenance,- observe_health=self.observe_health,- 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,- )---class _ConcurrentRuntimeObservations(_RuntimeObservations):- def __init__(self) -> None:- super().__init__()- self._independent_reads = 0- self._independent_reads_started = asyncio.Event()-- def _mark_independent_read(self) -> None:- self._independent_reads += 1- if self._independent_reads == 4:- self._independent_reads_started.set()-- async def observe_health(- self,- _maintenance_reason: str | None,- ) -> RuntimeHealthObservation:- await self._independent_reads_started.wait()- self.recorder = {"state": "degraded", "reason": "writer_failures"}- return RuntimeHealthObservation(_health(self.recorder))-- async def failure_log(- self,- maintenance_reason: str | None,- ) -> FailureLogObservation:- self._mark_independent_read()- return await super().failure_log(maintenance_reason)-- async def observe_sources(- self,- maintenance_reason: str | None,- ) -> ProcessingSourceObservations:- 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,- observation: MaintenanceObservation,- ) -> MaintenanceResult:- self._mark_independent_read()- return await super().maintenance_payload(operator_ref, observation)---class _OverlappingRecorderObservations(_RuntimeObservations):- def __init__(self) -> None:- super().__init__()- self._health_reads = 0- self._failure_reads = 0- self.first_health_read = asyncio.Event()- self.release_first_failure_read = asyncio.Event()-- async def observe_health(- self,- _maintenance_reason: str | None,- ) -> RuntimeHealthObservation:- self._health_reads += 1- if self._health_reads == 1:- recorder = {"state": "degraded", "reason": "writer_failures"}- self.recorder = recorder- self.first_health_read.set()- return RuntimeHealthObservation(_health(recorder))- recorder = {"state": "active", "reason": None}- self.recorder = recorder- return RuntimeHealthObservation(_health(recorder))-- async def failure_log(- self,- maintenance_reason: str | None,- ) -> FailureLogObservation:- self._failure_reads += 1- if self._failure_reads == 1:- await self.release_first_failure_read.wait()- return await super().failure_log(maintenance_reason)---def test_processing_record_exposes_only_exact_typed_read_entry_points() -> None:- assert get_type_hints(MemoryProcessingRecord.read_record)["return"] is (- ProcessingRecordSummary- )- assert get_type_hints(MemoryProcessingRecord.read_status)["return"] is (- RuntimeHealthProjection- )- assert get_type_hints(MemoryProcessingRecord.read_failures)["return"] == tuple[- AnomalyProjection,- MaintenanceProjection,- ]- assert get_type_hints(MemoryProcessingRecord.read_maintenance)["return"] is (- MaintenanceProjection- )- assert not hasattr(MemoryProcessingRecord, "read")---async def test_health_snapshot_falls_back_only_to_its_own_stale_observation(- monkeypatch: pytest.MonkeyPatch,-) -> None:- observations = _RuntimeObservations()- record = MemoryProcessingRecord(observations.port())- times = iter(- ("current", "anomalies", "maintenance", "stale-anomalies", "stale-maintenance")- )- monkeypatch.setattr(- processing_record_module,- "_utc_observed_at",- lambda: next(times),- )-- current = await record.read_record()- observations.health = RuntimeHealthObservation(- snapshot=None,- unavailable_reason="memory_provider_timeout",- )- stale = await record.read_record()-- assert current.runtime.source == SourceObservation("available", "current")- assert stale.runtime.source == SourceObservation(- "stale",- "current",- "memory_provider_timeout",- )- assert stale.runtime.health is current.runtime.health---async def test_recorder_episode_is_stable_and_rotates_after_recovery_or_reason_change(- monkeypatch: pytest.MonkeyPatch,-) -> None:- observations = _RuntimeObservations()- observations.failures = (- MemoryFailureLogEntry(- id="ma_durable",- kind="delivery_abandoned",- occurred_at="durable",- ),- )- record = MemoryProcessingRecord(observations.port())- episode_ids = iter(("ma_episode_1", "ma_episode_2", "ma_episode_3"))- times = iter(- (- "health-1", "anomalies-1", "maintenance-1",- "health-2", "anomalies-2", "maintenance-2",- "health-3", "anomalies-3", "maintenance-3",- "health-4", "anomalies-4", "maintenance-4",- "health-5", "anomalies-5", "maintenance-5",- )- )- monkeypatch.setattr(- processing_record_module,- "_new_recorder_episode_id",- lambda: next(episode_ids),- )- monkeypatch.setattr(- processing_record_module,- "_utc_observed_at",- lambda: next(times),- )-- observations.recorder = {"state": "degraded", "reason": "writer_failures"}- first = await record.read_record()- second = await record.read_record()- observations.recorder = {"state": "active", "reason": None}- recovered = await record.read_record()- observations.recorder = {"state": "degraded", "reason": "writer_failures"}- next_episode = await record.read_record()- observations.recorder = {"state": "degraded", "reason": "call_log_corrupt"}- changed_reason = await record.read_record()-- assert [item.id for item in first.anomalies.items] == [- "ma_episode_1",- "ma_durable",- ]- assert first.anomalies.items[0].occurred_at == "health-1"- assert second.anomalies.items[0].id == "ma_episode_1"- assert second.anomalies.items[0].occurred_at == "health-1"- assert [item.id for item in recovered.anomalies.items] == ["ma_durable"]- assert next_episode.anomalies.items[0].id == "ma_episode_2"- assert changed_reason.anomalies.items[0].id == "ma_episode_3"---async def test_sources_anomalies_and_maintenance_degrade_independently() -> None:- observations = _RuntimeObservations()- observations.sources = ProcessingSourceObservations(- everos=SourceObservation("partial", reason="runs_malformed"),- capture=SourceObservation("unavailable", reason="busy"),- calls=SourceObservation("available", observed_at="calls-now"),- )- observations.failure_error = OSError("private failure detail")- observations.maintenance_error = OSError("private maintenance detail")- observations.recorder = {"state": "degraded", "reason": "writer_failures"}-- summary = await MemoryProcessingRecord(observations.port()).read_record(- operator_ref="u-operator",- )-- assert summary.runtime.health is not None- assert 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",- )- assert [item.kind for item in summary.anomalies.items] == [- "recorder_degraded"- ]- assert summary.maintenance.data_exists is True- assert summary.maintenance.can_clear is False- assert summary.maintenance.clear_recovery is None- assert summary.maintenance.source.reason == "memory_store_unavailable"- assert observations.operator_refs == ["u-operator"]- assert "private" not in repr(summary)---async def test_verified_identity_lookup_is_inside_deadline_and_fails_closed() -> None:- observations = _RuntimeObservations()-- async def blocked_operator_lookup(_user_key: str) -> str:- await asyncio.Event().wait()- raise AssertionError("unreachable")-- port = replace(- observations.port(),- resolve_operator=blocked_operator_lookup,- )- deadline = asyncio.get_running_loop().time() + 0.01-- summary = await asyncio.wait_for(- MemoryProcessingRecord(port).read_record(- verified_user_key="avibe:remote:subject",- deadline=deadline,- ),- timeout=0.2,- )-- assert summary.status == "ok"- assert observations.operator_refs == []- assert summary.maintenance.can_clear is False---async def test_fenced_anomaly_read_reports_maintenance_reason() -> None:- observations = _RuntimeObservations()- observations.maintenance_observation = MaintenanceObservation(- "busy",- None,- False,- )-- summary = await MemoryProcessingRecord(observations.port()).read_record()-- assert summary.anomalies.source == SourceObservation(- "unavailable",- reason="busy",- )- assert summary.anomalies.items == ()---async def test_maintenance_observation_failure_marks_only_maintenance_unavailable(-) -> None:- observations = _RuntimeObservations()- observations.maintenance_observation_error = OSError("journal unavailable")- observations.maintenance = MaintenanceResult(False, False, None)-- summary = await MemoryProcessingRecord(observations.port()).read_record()-- assert summary.runtime.source.reason == "memory_store_unavailable"- assert summary.sources.everos.reason == "memory_store_unavailable"- assert summary.anomalies.source.reason == "memory_store_unavailable"- assert summary.maintenance.source == SourceObservation(- "unavailable",- reason="memory_store_unavailable",- )- assert summary.maintenance.data_exists is False- assert summary.maintenance.can_clear is False---async def test_overlapping_composite_reads_keep_their_own_recorder_episode() -> None:- observations = _OverlappingRecorderObservations()- record = MemoryProcessingRecord(observations.port())-- first_reading = asyncio.create_task(record.read_record())- await asyncio.wait_for(observations.first_health_read.wait(), timeout=0.2)- second = await asyncio.wait_for(record.read_record(), timeout=0.2)- observations.release_first_failure_read.set()- first = await asyncio.wait_for(first_reading, timeout=0.2)-- assert first.runtime.health is not None- assert first.runtime.health.recorder["state"] == "degraded"- assert [item.kind for item in first.anomalies.items] == [- "recorder_degraded"- ]- assert second.runtime.health is not None- assert second.runtime.health.recorder["state"] == "active"- assert second.anomalies.items == ()---async def test_composite_reads_sources_concurrently_then_merges_recorder_episode() -> None:- observations = _ConcurrentRuntimeObservations()- record = MemoryProcessingRecord(observations.port())-- summary = await asyncio.wait_for(record.read_record(), timeout=0.2)-- assert summary.runtime.health is not None- assert summary.runtime.health.recorder == {- "state": "degraded",- "reason": "writer_failures",- }- assert [item.kind for item in summary.anomalies.items] == [- "recorder_degraded"- ]---async def test_typed_failure_and_maintenance_reads_preserve_owner_recovery_and_recorder_merge(- monkeypatch: pytest.MonkeyPatch,-) -> None:- observations = _RuntimeObservations()- recovery = ClearRecoveryResult(- state="recovery_needed",- operation_id="clear-owner",- occurred_at="recovery-at",- error_code="memory_clear_failed",- can_resume=True,- can_abort=True,- )- observations.maintenance_observation = MaintenanceObservation(- None,- recovery,- True,- )- observations.maintenance = MaintenanceResult(True, True, recovery)- observations.failures = (- MemoryFailureLogEntry(- id="ma_durable",- kind="delivery_abandoned",- occurred_at="durable-at",- ),- )- observations.recorder = {"state": "degraded", "reason": "writer_failures"}- monkeypatch.setattr(- processing_record_module,- "_new_recorder_episode_id",- lambda: "ma_recorder",- )- monkeypatch.setattr(- processing_record_module,- "_utc_observed_at",- lambda: "recorder-at",- )- record = MemoryProcessingRecord(observations.port())-- anomalies, failure_maintenance = await record.read_failures(- verified_user_key="owner",- )- maintenance = await record.read_maintenance(verified_user_key="owner")-- assert [item.id for item in anomalies.items] == ["ma_recorder", "ma_durable"]- assert failure_maintenance.clear_recovery is recovery- assert maintenance.clear_recovery is recovery- assert maintenance.can_clear is True- assert observations.operator_refs == ["u-owner", "u-owner"]---async def test_runtime_serializes_one_composite_and_compatibility_projections(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)-- typed_composite = await runtime._processing_record.read_record(- operator_ref="u-operator"- )- typed_status = await runtime._processing_record.read_status()- typed_failures = await runtime._processing_record.read_failures(- operator_ref="u-operator"- )- typed_maintenance = await runtime._processing_record.read_maintenance(- operator_ref="u-operator"- )- composite = await runtime.processing_record_payload(operator_ref="u-operator")- status = await runtime.status_payload()- failures = await runtime.failure_log_payload(operator_ref="u-operator")- maintenance = await runtime.maintenance_payload(operator_ref="u-operator")-- assert typed_status == typed_composite.runtime- assert typed_failures[0].items == typed_composite.anomalies.items- assert (- typed_failures[1].clear_recovery- == typed_composite.maintenance.clear_recovery- )- assert typed_maintenance.data_exists == typed_composite.maintenance.data_exists- assert typed_maintenance.can_clear == typed_composite.maintenance.can_clear- assert (- typed_maintenance.clear_recovery- == typed_composite.maintenance.clear_recovery- )- assert set(composite) == {- "status",- "runtime",- "sources",- "anomalies",- "maintenance",- "provider_checks",- }- assert set(composite["sources"]) == {"everos", "capture", "calls"}- assert status == {"status": "ok", **composite["runtime"]}- assert failures == {- "status": "ok",- "items": composite["anomalies"]["items"],- "recovery": composite["maintenance"]["clear_recovery"],- }- assert maintenance == {- "status": "ok",- "data_exists": composite["maintenance"]["data_exists"],- "can_clear": composite["maintenance"]["can_clear"],- "clear_recovery": composite["maintenance"]["clear_recovery"],- }- assert "u-operator" not in repr(composite)---async def test_failure_compatibility_projection_skips_health_and_sources(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)-- async def unexpected_read() -> None:- raise AssertionError("compatibility failure reads must stay narrow")-- monkeypatch.setattr(runtime._processing_record, "_read_health", unexpected_read)- monkeypatch.setattr(runtime._processing_record, "_read_sources", unexpected_read)-- result = await asyncio.wait_for(- runtime.failure_log_payload(operator_ref="u-operator"),- timeout=1,- )-- assert result == {"status": "ok", "items": [], "recovery": None}---async def test_runtime_propagates_recorder_transition_time_at_mutation(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)-- runtime._update_recorder_health(- {"state": "degraded", "reason": "writer_failures"},- observed_at="transition-1",- )- first = await runtime.failure_log_payload()- runtime._update_recorder_health(- {"state": "active", "reason": None},- observed_at="recovered",- )- runtime._update_recorder_health(- {"state": "degraded", "reason": "writer_failures"},- observed_at="transition-2",- )- second = await runtime.failure_log_payload()-- assert first["items"][0]["occurred_at"] == "transition-1"- assert second["items"][0]["occurred_at"] == "transition-2"- assert second["items"][0]["id"] != first["items"][0]["id"]---async def test_disabled_runtime_status_is_authoritative_when_store_is_unavailable(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))-- def unavailable_store():- raise OSError("test store unavailable")-- monkeypatch.setattr("core.memory.runtime.MemoryStore", unavailable_store)- runtime = memory_runtime_factory(- MemoryConfig(enabled=False), effective_home=tmp_path- )-- assert runtime.available is False- assert await runtime.status_payload() == {- "status": "ok",- "source": {- "status": "unavailable",- "observed_at": None,- "reason": "memory_disabled",- },- "health": None,- }---async def test_health_probe_releases_reconcile_lock_and_discards_stale_result(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(- MemoryConfig(enabled=True), effective_home=tmp_path- )- original_process = SimpleNamespace(running=True)- runtime._process = original_process- probe_entered = asyncio.Event()- release_probe = asyncio.Event()-- async def blocked_health() -> ProviderHealthSnapshot:- probe_entered.set()- await release_probe.wait()- return _health({"state": "degraded", "reason": "writer_failures"})-- monkeypatch.setattr(runtime._provider, "health_snapshot", blocked_health)- probing = asyncio.create_task(runtime._processing_record_health(None))- await asyncio.wait_for(probe_entered.wait(), timeout=0.2)-- async with asyncio.timeout(0.2):- async with runtime._reconcile_lock:- runtime._process = SimpleNamespace(running=True)- release_probe.set()- observation = await probing-- assert observation == RuntimeHealthObservation(- snapshot=None,- unavailable_reason="memory_sidecar_unavailable",- )- assert runtime._recorder_health == {"state": "disabled", "reason": None}- runtime._process = None---async def test_health_probe_returns_closed_without_waiting_for_reconcile(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(- MemoryConfig(enabled=True), effective_home=tmp_path- )- runtime._process = SimpleNamespace(running=True)- provider_called = False-- async def unexpected_health() -> ProviderHealthSnapshot:- nonlocal provider_called- provider_called = True- return _health({"state": "active", "reason": None})-- monkeypatch.setattr(runtime._provider, "health_snapshot", unexpected_health)- async with runtime._reconcile_lock:- observation = await asyncio.wait_for(- runtime._processing_record_health(None),- timeout=0.1,- )-- assert observation.snapshot is None- assert observation.unavailable_reason == "busy"- assert provider_called is False- runtime._process = None---async def test_health_probe_discards_result_after_same_process_lifecycle_transition(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(- MemoryConfig(enabled=True), effective_home=tmp_path- )- runtime._process = SimpleNamespace(running=True)- probe_entered = asyncio.Event()- release_probe = asyncio.Event()-- async def blocked_health() -> ProviderHealthSnapshot:- probe_entered.set()- await release_probe.wait()- return _health({"state": "active", "reason": None})-- monkeypatch.setattr(runtime._provider, "health_snapshot", blocked_health)- probing = asyncio.create_task(runtime._processing_record_health(None))- await asyncio.wait_for(probe_entered.wait(), timeout=0.2)- async with runtime._reconcile_lock:- pass- release_probe.set()-- observation = await probing-- assert observation == RuntimeHealthObservation(- snapshot=None,- unavailable_reason="memory_sidecar_unavailable",- )- runtime._process = None--- "enabled",- (False, True),- ids=("disabled", "sidecar-stopped"),-)-async def test_processing_sources_read_local_history_without_a_running_sidecar(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- enabled: bool,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- source_reads = 0-- class Reader:- def source_observation(self) -> ProcessingSourceObservations:- nonlocal source_reads- source_reads += 1- return _sources()-- runtime = memory_runtime_factory(- MemoryConfig(enabled=enabled),- effective_home=tmp_path,- insight_reader=Reader(),- )-- sources = await runtime._processing_record_sources(None)-- assert sources == _sources()- assert source_reads == 1--[email protected]("fence", ("reconcile", "root"))-async def test_processing_anomalies_return_busy_without_waiting_for_fences(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- fence: str,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(- MemoryConfig(enabled=False), effective_home=tmp_path- )- failure_log_reads = 0-- def failure_log(*, limit: int) -> tuple[MemoryFailureLogEntry, ...]:- nonlocal failure_log_reads- failure_log_reads += 1- assert limit == 50- return ()-- monkeypatch.setattr(runtime._store, "failure_log", failure_log)- lock = (- runtime._reconcile_lock- if fence == "reconcile"- else runtime.module._root_lifecycle_lock()- )-- async with lock:- blocked = await asyncio.wait_for(- runtime._processing_record_failure_log(None),- timeout=0.1,- )-- assert blocked == FailureLogObservation((), "busy")- assert failure_log_reads == 0-- available = await asyncio.wait_for(- runtime._processing_record_failure_log(None),- timeout=0.1,- )-- assert available == FailureLogObservation(())- assert failure_log_reads == 1---async def test_processing_anomalies_discard_read_after_lifecycle_transition(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(- MemoryConfig(enabled=False), effective_home=tmp_path- )- failure_log_started = threading.Event()- release_failure_log = threading.Event()-- def failure_log(*, limit: int) -> tuple[MemoryFailureLogEntry, ...]:- assert limit == 50- failure_log_started.set()- assert release_failure_log.wait(2)- return ()-- monkeypatch.setattr(runtime._store, "failure_log", failure_log)- reading = asyncio.create_task(runtime._processing_record_failure_log(None))- try:- assert await asyncio.to_thread(failure_log_started.wait, 1)- runtime._advance_processing_lifecycle()- release_failure_log.set()- observation = await asyncio.wait_for(reading, timeout=1)- finally:- release_failure_log.set()- await asyncio.gather(reading, return_exceptions=True)-- assert observation == FailureLogObservation((), "busy")- assert runtime.module._root_lifecycle_lock().locked() is False---async def test_processing_sources_return_busy_without_waiting_for_lifecycle_locks(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- source_reads = 0-- class Reader:- def source_observation(self) -> ProcessingSourceObservations:- nonlocal source_reads- source_reads += 1- return _sources()-- runtime = memory_runtime_factory(- MemoryConfig(enabled=True),- effective_home=tmp_path,- insight_reader=Reader(),- )- runtime._process = SimpleNamespace(running=True)-- async with runtime._reconcile_lock, runtime.module._lifecycle_lock:- sources = await asyncio.wait_for(- runtime._processing_record_sources(None),- timeout=0.1,- )-- assert source_reads == 0- assert {source.status for source in (- sources.everos,- sources.capture,- sources.calls,- )} == {"unavailable"}- assert {source.reason for source in (- sources.everos,- sources.capture,- sources.calls,- )} == {"busy"}- runtime._process = None--- ("transition", "expected_reason"),- [- ("generation", "busy"),- ("maintenance", "busy"),- ],-)-async def test_processing_sources_discard_stale_lifecycle_observation(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- transition: str,- expected_reason: str,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- source_read_started = threading.Event()- release_source_read = threading.Event()- class Reader:- def source_observation(self) -> ProcessingSourceObservations:- source_read_started.set()- assert release_source_read.wait(2)- return _sources()- runtime = memory_runtime_factory(- MemoryConfig(enabled=True),- effective_home=tmp_path,- insight_reader=Reader(),+def test_processing_projection_exposes_clear_in_progress():+ clear = ClearInProgressResult(+ state="failed",+ operation_id="op-1",+ occurred_at="2026-08-13T00:00:00Z",+ error_code="memory_clear_marker_unreadable",)- original_process = SimpleNamespace(running=True)- runtime._process = original_process- reading = asyncio.create_task(runtime._processing_record_sources(None))- try:- assert await asyncio.to_thread(source_read_started.wait, 1)- if transition == "generation":- runtime._advance_processing_lifecycle()- else:- runtime._enter_maintenance()- release_source_read.set()- sources = await asyncio.wait_for(reading, timeout=1)- finally:- release_source_read.set()- await asyncio.gather(reading, return_exceptions=True)- if transition == "maintenance":- runtime._leave_maintenance()-- assert {source.status for source in (- sources.everos,- sources.capture,- sources.calls,- )} == {"unavailable"}- assert {source.reason for source in (- sources.everos,- sources.capture,- sources.calls,- )} == {expected_reason}- runtime._process = None---async def test_status_projection_never_reads_maintenance_journals(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(- MemoryConfig(enabled=False), effective_home=tmp_path+ projection = MaintenanceProjection(+ source=SourceObservation("unavailable", reason="memory_clear_failed"),+ data_exists=True,+ can_clear=False,+ clear_in_progress=clear,)- async def unexpected_read(*_args: object) -> object:- raise AssertionError("status compatibility reads must stay runtime-only")-- runtime._processing_record._runtime = replace(- runtime._processing_record._runtime,- resolve_operator=unexpected_read,- observe_maintenance=unexpected_read,- failure_log=unexpected_read,- observe_sources=unexpected_read,- maintenance=unexpected_read,- )-- payload = await runtime.status_payload()-- assert payload["source"]["reason"] == "memory_disabled"+ assert projection.clear_in_progress == clear-async def test_typed_status_uses_provider_budget_without_identity_or_composite_reads(- monkeypatch: pytest.MonkeyPatch,-) -> None:- observations = _RuntimeObservations()-- async def blocked_health(_maintenance_reason: str | None) -> RuntimeHealthObservation:- await asyncio.Event().wait()- raise AssertionError("unreachable")-- async def unexpected_read(*_args: object) -> object:- raise AssertionError("status reads must stay runtime-only")-- port = replace(- observations.port(),- resolve_operator=unexpected_read,- observe_maintenance=unexpected_read,- observe_health=blocked_health,- failure_log=unexpected_read,- observe_sources=unexpected_read,- maintenance=unexpected_read,- )- monkeypatch.setattr(- processing_record_module,- "PROVIDER_READ_TIMEOUT_SECONDS",- 0.01,- )-- status = await asyncio.wait_for(- MemoryProcessingRecord(port).read_status(),- timeout=0.2,- )-- assert status == RuntimeHealthProjection(- source=SourceObservation(- "unavailable",- reason="memory_sidecar_unavailable",+def test_processing_summary_has_no_legacy_recovery_field():+ available = SourceObservation("available", observed_at="now")+ summary = ProcessingRecordSummary(+ runtime=RuntimeHealthProjection(source=available, health=None),+ sources=ProcessingSourceObservations(available, available, available),+ anomalies=AnomalyProjection(source=available, items=()),+ maintenance=MaintenanceProjection(+ source=available,+ data_exists=False,+ can_clear=True,+ clear_in_progress=None,),- health=None,- )- assert observations.operator_refs == []---async def test_processing_record_keeps_event_loop_responsive_during_journal_read(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(- MemoryConfig(enabled=True), effective_home=tmp_path- )- maintenance = runtime._maintenance- assert maintenance is not None- restore_journal = maintenance._backup_restore_journal- assert restore_journal is not None- release_journal = threading.Event()- watchdog_released = threading.Event()- heartbeat = asyncio.Event()- event_loop = asyncio.get_running_loop()- journal_reads = 0- original_get_open_operation = restore_journal.get_open_operation-- def blocking_get_open_operation():- nonlocal journal_reads- journal_reads += 1- event_loop.call_soon_threadsafe(heartbeat.set)- assert release_journal.wait(1)- return original_get_open_operation()-- def release_from_watchdog() -> None:- watchdog_released.set()- release_journal.set()-- monkeypatch.setattr(- restore_journal,- "get_open_operation",- blocking_get_open_operation,- )- watchdog = threading.Timer(0.5, release_from_watchdog)- watchdog.start()- reading = asyncio.create_task(runtime.processing_record_payload())- try:- await asyncio.wait_for(heartbeat.wait(), timeout=1)- assert watchdog_released.is_set() is False- release_journal.set()- await asyncio.wait_for(reading, timeout=1)- assert journal_reads == 2- finally:- release_journal.set()- watchdog.cancel()- await asyncio.gather(reading, return_exceptions=True)---async def test_processing_sources_distinguish_busy_clear_from_failed_recovery(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- runtime = memory_runtime_factory(- MemoryConfig(enabled=True), effective_home=tmp_path- )- maintenance = runtime._maintenance- assert maintenance is not None- journal = maintenance._clear_journal- assert journal is not None- maintenance._backup_active = True- assert (await maintenance.observe()).block_reason == "busy"- maintenance._backup_active = False- restore_journal = maintenance._backup_restore_journal- assert restore_journal is not None-- def unavailable_clear_journal(*, operator_ref: str | None):- del operator_ref- raise OSError("clear journal unavailable")-- with monkeypatch.context() as restore_patch:- restore_patch.setattr(- restore_journal,- "get_open_operation",- lambda: object(),- )- assert (await maintenance.observe()).block_reason == "busy"- restore_patch.setattr(- journal,- "observe_open_operation",- unavailable_clear_journal,- )- observation = await runtime._processing_record_maintenance_observation(None)- assert observation.block_reason == "busy"- operation = journal.start(- operation_id="processing-observation-clear",- operator_ref="user:owner",- pre_epoch=0,- target_epoch=1,- )-- busy_observation = await runtime._processing_record_maintenance_observation(None)- busy_health = await runtime._processing_record_health(- busy_observation.block_reason- )- busy_sources = await runtime._processing_record_sources(- busy_observation.block_reason- )- recovery = journal.mark_recovery_needed(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- failed_observation = await runtime._processing_record_maintenance_observation(None)- failed_health = await runtime._processing_record_health(- failed_observation.block_reason- )- failed_sources = await runtime._processing_record_sources(- failed_observation.block_reason- )-- assert busy_health.unavailable_reason == "busy"- assert {source.reason for source in (- busy_sources.everos,- busy_sources.capture,- busy_sources.calls,- )} == {"busy"}- assert recovery.closed_error == "memory_clear_failed"- assert failed_health.unavailable_reason == "memory_clear_failed"- assert {source.reason for source in (- failed_sources.everos,- failed_sources.capture,- failed_sources.calls,- )} == {"memory_clear_failed"}---def _enqueue(runtime: MemoryRuntime, source: str) -> None:- result = runtime._store.enqueue_request(- source_message_id=source,- session_id="session",- principal_id="u-11111111111111111111111111111111",- project_ref="default",- provenance="user_input",- payload_text="private payload",- occurred_at_ms=1,- max_provider_timestamp_ms=100,- )- assert result.outcome == "accepted"---async def test_processing_record_does_not_compact_queue_during_clear_snapshot(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- memory_runtime_factory,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setattr("core.memory.store.TERMINAL_TOMBSTONE_LIMIT", 0)- runtime = memory_runtime_factory(MemoryConfig(), effective_home=tmp_path)- _enqueue(runtime, "terminal-before-clear")- row = runtime._store.claim_due(- lease_owner="boot",- now="2026-01-01T00:00:00.000Z",- )- assert row is not None- assert runtime._store.settle(- row,- Delivered(add_request_id="add-terminal-before-clear"),- lease_owner="boot",- now=datetime(2026, 1, 1, tzinfo=UTC),- ).settled-- snapshot_copied = threading.Event()- release_snapshot = threading.Event()- compaction_entered = threading.Event()- queue_uri = runtime._store.path.absolute().as_uri() + "?mode=ro"- original_connect = snapshot_module.sqlite3.connect- original_compact = runtime._store._compact_terminal_tombstones_in_connection-- class BlockingQueueConnection:- def __init__(self, connection: sqlite3.Connection) -> None:- self._connection = connection-- def execute(self, *args, **kwargs):- return self._connection.execute(*args, **kwargs)-- def backup(self, target: sqlite3.Connection) -> None:- self._connection.backup(target)- snapshot_copied.set()- assert release_snapshot.wait(2)-- def close(self) -> None:- self._connection.close()-- def blocking_connect(database, *args, **kwargs):- connection = original_connect(database, *args, **kwargs)- if database == queue_uri:- return BlockingQueueConnection(connection)- return connection-- def observed_compaction(connection, reference):- compaction_entered.set()- return original_compact(connection, reference)-- monkeypatch.setattr(snapshot_module.sqlite3, "connect", blocking_connect)- monkeypatch.setattr(- runtime._store,- "_compact_terminal_tombstones_in_connection",- observed_compaction,- )- maintenance = runtime._maintenance- assert maintenance is not None- clearing = asyncio.create_task(maintenance.clear(operator_ref="user:owner"))- assert await asyncio.to_thread(snapshot_copied.wait, 1)- runtime._update_recorder_health(- {"state": "degraded", "reason": "call_log_corrupt"},- )- processing_record = await asyncio.wait_for(- runtime.processing_record_payload(operator_ref="user:owner"),- 1,+ provider_checks=ProviderCheckProjection(source=available, items=()),)- compacted_during_snapshot = compaction_entered.is_set()- release_snapshot.set()- result = await clearing- assert compacted_during_snapshot is False- assert [item["kind"] for item in processing_record["anomalies"]["items"]] == [- "recorder_degraded"- ]- assert result.status == "completed"- assert maintenance._clear_journal.get_open_operation() is None- await memory_runtime_factory.close(runtime)+ assert not hasattr(summary.maintenance, "clear_in_progress") or summary.maintenance.clear_in_progress is Nonediff --git a/tests/test_memory_runtime.py b/tests/test_memory_runtime.pyindex ded32b2cc..db779a1be 100644--- a/tests/test_memory_runtime.py+++ b/tests/test_memory_runtime.py@@ -31,8 +31,8 @@ from core.memory.artifact import (MemoryProviderRootState,MemoryRuntimeActivationError,)-from core.memory.clear_journal import MemoryClearJournalfrom core.memory.maintenance import MemoryMaintenance+from core.memory.clear_intent import ClearIntent, ClearIntentStorefrom core.memory.attachments import attachment_pin_rootfrom core.memory.everos import (AddAck,@@ -84,6 +84,7 @@ from config.v2_config import (PROJECT = "default"+PRINCIPAL = "u-11111111111111111111111111111111"def _maintenance(runtime: MemoryRuntime) -> MemoryMaintenance:@@ -310,7 +311,7 @@ def test_memory_runtime_factory_degrades_when_private_modes_cannot_be_enforced("status": "ok","data_exists": True,"can_clear": False,- "clear_recovery": None,+ "clear_in_progress": None,}@@ -1199,99 +1200,6 @@ async def test_runtime_controller_port_never_copies_processing_credentials(await memory_runtime_factory.close(runtime)- "journal_attribute",- ["_clear_journal", "_backup_restore_journal"],-)-async def test_disable_stops_live_runtime_when_maintenance_journal_is_unreadable(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- journal_attribute: str,- memory_runtime_factory,-) -> None:- processing = MemoryProcessingConfig(- llm=MemoryEndpointConfig("https://llm.example.test/v1", "chat", "llm-key"),- embedding=MemoryEndpointConfig(- "https://embed.example.test/v1",- "embed",- "embed-key",- ),- )- enabled = MemoryConfig(enabled=True, processing=processing)- disabled = replace(enabled, enabled=False)- factory = FakeEverOSProcessFactory()-- runtime = memory_runtime_factory(- enabled,- artifact_manager=_installed_artifact(),- process_factory=factory,- effective_home=tmp_path,- )- assert await runtime.reconcile(enabled) == {"ok": True, "state": "ready"}- sidecar = factory.supervised[0]- assert runtime._worker_task is not None- assert runtime._process_records_calls is True-- terminal_gc = _maintenance(runtime)._terminal_snapshot_gc_task- backup_reconcile = _maintenance(runtime)._backup_stage_reconcile_task- if terminal_gc is not None:- await terminal_gc- if backup_reconcile is not None:- await backup_reconcile-- journal = getattr(_maintenance(runtime), journal_attribute)- assert journal is not None-- def unreadable_journal() -> None:- raise OSError("maintenance journal is unreadable")-- async def recovery_must_not_run() -> bool:- raise AssertionError("disable must not mutate an unreadable journal")-- monkeypatch.setattr(journal, "get_open_operation", unreadable_journal)- monkeypatch.setattr(_maintenance(runtime), "recover_boot", recovery_must_not_run)-- changed = replace(- enabled,- processing=replace(- processing,- llm=replace(processing.llm, model="changed-while-unreadable"),- ),- )- assert await runtime.reconcile(changed) == {- "ok": False,- "error": "memory_clear_failed",- }- assert await runtime.restart() == {- "ok": False,- "error": "memory_clear_failed",- }- assert runtime._worker_task is not None- assert sidecar.stopped is False-- from core.controller import Controller-- controller = Controller.__new__(Controller)- controller.config = SimpleNamespace(memory=enabled)- controller.memory_runtime = runtime- controller.memory_module = runtime.module- assert await controller.reconcile_memory(disabled) == {- "ok": True,- "state": "disabled",- }- assert controller.config.memory is disabled- assert runtime._config is disabled- assert runtime._restart_config == disabled- assert runtime.module._worker._claims_paused is True- assert runtime._worker_task is None- assert runtime._process is None- assert runtime._process_records_calls is False- assert sidecar.stopped is True- assert sidecar.running is False- assert len(factory.supervised) == 1- await memory_runtime_factory.close(runtime)--async def test_reconcile_never_downloads_a_missing_runtime(tmp_path: Path,memory_runtime_factory,@@ -1970,11 +1878,11 @@ async def test_multi_scope_session_lifecycle_holds_every_fence_through_operation)first_scope = ("u-11111111111111111111111111111111",- "default",+ PROJECT,)second_scope = ("u-22222222222222222222222222222222",- "billing",+ PROJECT,)session_id = "multi-scope-lifecycle-session"operation_entered = asyncio.Event()@@ -2044,11 +1952,11 @@ async def test_cancelled_multi_scope_lifecycle_releases_partially_acquired_fencescopes = (("u-11111111111111111111111111111111",- "p-11111111111111111111111111111111",+ PROJECT,),("u-22222222222222222222222222222222",- "p-22222222222222222222222222222222",+ PROJECT,),)session_id = "cancelled-multi-scope-lifecycle"@@ -2290,13 +2198,9 @@ async def test_runtime_exposes_interrupted_clear_without_starting_sidecar(llm=MemoryEndpointConfig("https://llm.example.test/v1", "chat", "llm-key"),embedding=MemoryEndpointConfig("https://embed.example.test/v1", "embed", "embed-key"),)- journal = MemoryClearJournal(tmp_path)- journal.start(- operation_id="interrupted-clear",- operator_ref="user:owner",- pre_epoch=0,- target_epoch=1,- )+ marker = tmp_path / "state/memory/clear-intent.json"+ marker.parent.mkdir(parents=True)+ marker.write_text("not json", encoding="utf-8")runtime = memory_runtime_factory(MemoryConfig(enabled=True, processing=processing),artifact_manager=_Artifact(),@@ -2306,13 +2210,138 @@ async def test_runtime_exposes_interrupted_clear_without_starting_sidecar(assert await runtime.reconcile(runtime._config) == {"ok": False, "error": "memory_clear_failed"}assert started == []- recovery = _maintenance(runtime)._clear_journal.get_open_operation()- assert recovery is not None- assert recovery.operation_id == "interrupted-clear"- assert recovery.state == "recovery_needed"+ projection = _maintenance(runtime).recovery()+ assert projection is not None+ assert projection.error_code == "memory_clear_marker_unreadable"+ await memory_runtime_factory.close(runtime)+++async def test_runtime_reconcile_completes_readable_clear_marker_on_boot(+ tmp_path: Path,+ memory_runtime_factory,+) -> None:+ """MEMORY-CLEAR-202: runtime boot retries a failed marker after lease release."""++ processing = MemoryProcessingConfig(+ llm=MemoryEndpointConfig("https://llm.example.test/v1", "chat", "llm-key"),+ embedding=MemoryEndpointConfig("https://embed.example.test/v1", "embed", "embed-key"),+ )+ runtime = memory_runtime_factory(+ MemoryConfig(enabled=False, processing=processing),+ effective_home=tmp_path,+ )+ maintenance = _maintenance(runtime)+ store = runtime._store+ assert store is not None+ intent = ClearIntent.new(operator_ref="boot", pre_epoch=store.ensure_meta().epoch).failed(+ "memory_clear_failed"+ )+ ClearIntentStore(tmp_path).write(intent)++ competing = MemoryOperationLease(tmp_path)+ competing.acquire()+ assert await runtime.reconcile(runtime._config) == {+ "ok": False,+ "error": "memory_operation_in_progress",+ }+ assert ClearIntentStore(tmp_path).load() is not None+ competing.release()++ result = await runtime.reconcile(runtime._config)++ assert result == {"ok": True, "state": "disabled"}+ assert ClearIntentStore(tmp_path).load() is None+ assert maintenance.is_open() is Falseawait memory_runtime_factory.close(runtime)+async def test_memory_clear_201_discards_manual_required_evidence_and_allows_new_delivery(+ tmp_path: Path,+ memory_runtime_factory,+) -> None:+ """MEMORY-CLEAR-201: a real runtime clears an unknown add outcome end to end."""++ runtime = memory_runtime_factory(+ MemoryConfig(enabled=True),+ effective_home=tmp_path,+ )+ provider_timeout = asyncio.Event()++ async def time_out_add(_capture) -> None:+ await provider_timeout.wait()++ provider = FakeMemoryProvider(add_hook=time_out_add)+ runtime._provider = provider+ runtime.module.replace_provider(provider)+ runtime.module._worker.coordinator._add_timeout_seconds = 0.001++ source_root = tmp_path / "attachments" / "avibe"+ source_root.mkdir(parents=True, mode=0o700)+ source = source_root / "evidence.txt"+ source.write_bytes(b"retained ambiguous attachment")+ source.chmod(0o600)+ first = CaptureRequest(+ source_message_id="timed-out-add",+ session_id="session",+ principal_id=PRINCIPAL,+ project_id=PROJECT,+ provenance="user_input",+ text="ambiguous payload",+ occurred_at_ms=1,+ attachments=(+ CaptureAttachment(+ kind="doc",+ name=source.name,+ uri=source.as_uri(),+ ext="txt",+ ),+ ),+ )+ assert await runtime.module.capture(first) == CaptureAccepted()+ assert await runtime.module.drain() == 1++ ambiguous = runtime._store.list_queue_rows()+ assert len(ambiguous) == 1+ assert ambiguous[0].state == "manual_required"+ assert ambiguous[0].attachment_bundle_id is not None+ bundle_id = ambiguous[0].attachment_bundle_id+ assert runtime._store.has_manual_required_fence() is True+ assert (await runtime.maintenance_payload())["can_clear"] is True++ async def resume_without_sidecar() -> None:+ runtime.module.resume_claims()++ maintenance = _maintenance(runtime)+ maintenance._runtime = replace(maintenance._runtime, resume=resume_without_sidecar)+ result = await runtime.clear(operator_ref="user:owner")++ assert result["status"] == "completed"+ assert isinstance(result["operation_id"], str)+ assert result["epoch"] == 1+ assert runtime._store.list_queue_rows() == ()+ assert runtime._store.has_manual_required_fence() is False+ assert not (tmp_path / "memory" / "attachments" / "bundles" / bundle_id).exists()++ provider.add_hook = None+ second = replace(+ first,+ source_message_id="after-clear",+ text="deliver after clear",+ occurred_at_ms=2,+ attachments=(),+ )+ assert await runtime.module.capture(second) == CaptureAccepted()+ assert await runtime.module.drain() == 1+ delivered = runtime._store.list_queue_rows()+ assert len(delivered) == 1+ assert delivered[0].state == "delivered"+ assert delivered[0].provider_session_ref.epoch == result["epoch"]+ assert [capture.text for capture in provider.captures] == [+ "ambiguous payload",+ "deliver after clear",+ ]++async def test_runtime_install_artifact_uses_controller_owned_manager(tmp_path: Path,memory_runtime_factory,@@ -4656,11 +4685,10 @@ async def test_runtime_restart_fails_closed_before_launch_for_marker_or_clear_re)meta = recovering._store.ensure_meta()- _maintenance(recovering)._clear_journal.start(- operation_id="restart-recovery",- operator_ref="user:owner",- pre_epoch=meta.epoch,- target_epoch=meta.epoch + 1,+ from core.memory.clear_intent import ClearIntentStore, ClearIntent++ ClearIntentStore(tmp_path / "recovery").write(+ ClearIntent.new(operator_ref="user:owner", pre_epoch=meta.epoch))assert await marked.restart() == {@@ -4755,7 +4783,7 @@ async def test_ready_callback_survives_rejected_artifact_install(await memory_runtime_factory.close(runtime)[email protected]("lifecycle", ["clear", "reconcile", "artifact"])[email protected]("lifecycle", ["reconcile", "artifact"])async def test_ready_callback_waits_for_runtime_lifecycle_and_revalidates_process(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,@@ -4778,15 +4806,7 @@ async def test_ready_callback_waits_for_runtime_lifecycle_and_revalidates_procesruntime._activation_loop = asyncio.get_running_loop()process.on_ready = lambda: runtime._schedule_sidecar_ready(process)- if lifecycle == "clear":- async def blocked_prepare(_operation, **_kwargs):- entered.set()- await release.wait()- raise RuntimeError("injected clear pause")-- monkeypatch.setattr(_maintenance(runtime), "_prepare_clear", blocked_prepare)- operation = asyncio.create_task(runtime.clear(operator_ref="user:owner"))- elif lifecycle == "reconcile":+ if lifecycle == "reconcile":async def blocked_reconcile(*_args, **_kwargs):entered.set()await release.wait()@@ -4830,7 +4850,7 @@ async def test_ready_callback_waits_for_runtime_lifecycle_and_revalidates_procesready_task = runtime._ready_activation_taskif ready_task is not None:await asyncio.wait_for(asyncio.shield(ready_task), timeout=1.0)- assert activations == ([] if lifecycle in {"clear", "artifact"} else [None])+ assert activations == ([None] if lifecycle == "reconcile" else [])await memory_runtime_factory.close(runtime)@@ -5184,14 +5204,6 @@ async def test_runtime_effective_home_owns_the_attachment_pipeline(assert runtime.module._attachment_store._effective_home == runtime_homeassert runtime.module._attachment_store._root == expected_pin_rootassert runtime.module._attachment_store._source_root == source_root- manager = _maintenance(runtime)._snapshot_manager- assert manager is not None- assert manager.effective_home == runtime_home- assert any(- surface.path == "memory/attachments"- for surface in manager.surfaces- )-process = EverOSProcess(sys.executable,effective_home=runtime_home,@@ -5809,6 +5821,51 @@ async def test_runtime_rebuild_reads_key_correction_after_admission_gap(await memory_runtime_factory.close(runtime)+async def test_cancelled_boot_reconcile_releases_lease_after_acquisition(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ memory_runtime_factory,+) -> None:+ """A cancellation during boot lease admission must not strand the lease."""++ runtime = memory_runtime_factory(+ MemoryConfig(enabled=False),+ effective_home=tmp_path,+ )+ maintenance = _maintenance(runtime)+ store = runtime._store+ assert store is not None+ ClearIntentStore(tmp_path).write(+ ClearIntent.new(operator_ref="boot", pre_epoch=store.ensure_meta().epoch).failed(+ "memory_clear_failed"+ )+ )+ entered = threading.Event()+ release_acquire = threading.Event()++ class _GatedLease(MemoryOperationLease):+ def acquire(self) -> None:+ entered.set()+ assert release_acquire.wait(2)+ super().acquire()++ monkeypatch.setattr(memory_runtime, "MemoryOperationLease", _GatedLease)+ reconciling = asyncio.create_task(runtime.reconcile(runtime._config))+ assert await asyncio.to_thread(entered.wait, 2)+ reconciling.cancel()+ await asyncio.sleep(0)+ release_acquire.set()++ with pytest.raises(asyncio.CancelledError):+ await reconciling++ lease = MemoryOperationLease(tmp_path)+ lease.acquire()+ lease.release()+ assert maintenance.is_open() is True+ await memory_runtime_factory.close(runtime)++async def test_runtime_rebuild_maps_root_busy_without_settling(monkeypatch,tmp_path,@@ -6278,14 +6335,6 @@ async def test_runtime_rebuild_lease_rejects_a_second_controller("status": "failed","error": "memory_operation_in_progress",}- assert await second.resume_clear("clear-1", operator_ref="user:owner") == {- "status": "failed",- "error": "memory_operation_in_progress",- }- assert await second.abort_clear("clear-1", operator_ref="user:owner") == {- "status": "failed",- "error": "memory_operation_in_progress",- }release.set()assert await rebuilding == {diff --git a/tests/test_memory_snapshot.py b/tests/test_memory_snapshot.pydeleted file mode 100644index 99b2e66e3..000000000--- a/tests/test_memory_snapshot.py+++ /dev/null@@ -1,1461 +0,0 @@-from __future__ import annotations--import json-import os-import shutil-import sqlite3-import stat-import sys-import tracemalloc-from pathlib import Path--import pytest--import core.memory.confined_filesystem as confined_filesystem_module-import core.memory.snapshot as snapshot_module-from core.memory.clear_journal import (- ClearBackupBlocked,- MemoryClearJournal,-)-from core.memory.clear_snapshot_storage import MemoryClearSnapshotStorage-from core.memory.confined_filesystem import remove_confined_path-from core.memory.snapshot import (- MemorySnapshotError,- MemorySnapshotManager,- MemorySnapshotUnsafePathError,- MemorySnapshotVerificationError,- SnapshotSurface,-)---def _private_directory(path: Path, home: Path) -> Path:- path.mkdir(parents=True, exist_ok=True, mode=0o700)- current = path- while True:- current.chmod(0o700)- if current == home:- break- current = current.parent- return path---def _private_file(path: Path, payload: bytes, home: Path) -> Path:- _private_directory(path.parent, home)- path.write_bytes(payload)- path.chmod(0o600)- return path---def _create_deep_file_at(root: Path, components: list[str], name: str, payload: bytes) -> None:- descriptor = os.open(root, os.O_RDONLY | os.O_DIRECTORY)- try:- for component in components:- try:- os.mkdir(component, mode=0o700, dir_fd=descriptor)- except FileExistsError:- pass- next_descriptor = os.open(- component,- os.O_RDONLY | os.O_DIRECTORY | getattr(os, "O_NOFOLLOW", 0),- dir_fd=descriptor,- )- os.close(descriptor)- descriptor = next_descriptor- file_descriptor = os.open(- name,- os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0),- 0o600,- dir_fd=descriptor,- )- try:- os.write(file_descriptor, payload)- os.fchmod(file_descriptor, 0o600)- finally:- os.close(file_descriptor)- finally:- os.close(descriptor)---def _read_deep_file_at(root: Path, components: list[str], name: str) -> bytes:- descriptor = os.open(root, os.O_RDONLY | os.O_DIRECTORY)- try:- for component in components:- next_descriptor = os.open(- component,- os.O_RDONLY | os.O_DIRECTORY | getattr(os, "O_NOFOLLOW", 0),- dir_fd=descriptor,- )- os.close(descriptor)- descriptor = next_descriptor- file_descriptor = os.open(- name,- os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0),- dir_fd=descriptor,- )- try:- return os.read(file_descriptor, 1024)- finally:- os.close(file_descriptor)- finally:- os.close(descriptor)---def _sqlite_surface(path: Path, value: str, home: Path, *, keep_wal: bool = False):- _private_directory(path.parent, home)- connection = sqlite3.connect(path)- connection.execute("PRAGMA journal_mode=WAL")- connection.execute("PRAGMA wal_autocheckpoint=0")- connection.execute("CREATE TABLE records (value TEXT NOT NULL)")- connection.execute("INSERT INTO records VALUES (?)", (value,))- connection.commit()- path.chmod(0o600)- for suffix in ("-wal", "-shm"):- sidecar = path.with_name(f"{path.name}{suffix}")- if sidecar.exists():- sidecar.chmod(0o600)- if keep_wal:- return connection- connection.close()- return None---def _sqlite_values(path: Path) -> list[str]:- uri = f"{path.absolute().as_uri()}?mode=ro&immutable=1"- with sqlite3.connect(uri, uri=True) as connection:- return [row[0] for row in connection.execute("SELECT value FROM records ORDER BY rowid")]---def _build_all_surfaces(home: Path) -> sqlite3.Connection:- home.mkdir(mode=0o700)- home.chmod(0o700)- queue = home / "state/memory/memory.sqlite"- queue_connection = _sqlite_surface(queue, "queued-before-clear", home, keep_wal=True)- assert queue_connection is not None- _sqlite_surface(home / "memory/call-log/call-log.db", "call-before-clear", home)- _private_file(home / "memory/everos-root/profiles/user.json", b'{"name":"Ada"}', home)- _private_directory(home / "memory/everos-root/episodes/empty", home)- _private_file(home / "memory/attachments/bundles/a1/00.txt", b"attachment", home)- return queue_connection---def _complete_clear_audit(- journal: MemoryClearJournal,- manager: MemorySnapshotManager,- operation_id: str,-) -> None:- operation = journal.start(- operation_id=operation_id,- operator_ref="user:owner",- pre_epoch=0,- target_epoch=1,- )- snapshot = manager.create(operation.operation_id)- assert operation.execution_token is not None- operation = journal.record_snapshot(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- snapshot=snapshot,- )- assert operation.execution_token is not None- operation = journal.mark_prepared(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- assert operation.execution_token is not None- operation = journal.begin_deleting(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- for surface in journal.surfaces:- assert operation.execution_token is not None- operation = journal.record_surface_deleted(- operation.operation_id,- surface.name,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- assert operation.execution_token is not None- journal.mark_completed(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )---def _abort_clear_audit(- journal: MemoryClearJournal,- manager: MemorySnapshotManager,- operation_id: str,-) -> None:- operation = journal.start(- operation_id=operation_id,- operator_ref="user:owner",- pre_epoch=0,- target_epoch=1,- )- snapshot = manager.create(operation.operation_id)- assert operation.execution_token is not None- operation = journal.record_snapshot(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- snapshot=snapshot,- )- assert operation.execution_token is not None- operation = journal.mark_prepared(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- recovery = journal.mark_boot_recovery_needed()- assert recovery is not None- operation = journal.claim_abort(- operation.operation_id,- operator_ref="user:owner",- expected_revision=recovery.revision,- )- for surface in journal.surfaces:- assert operation.execution_token is not None- operation = journal.record_surface_restored(- operation.operation_id,- surface.name,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- assert operation.execution_token is not None- journal.mark_aborted(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )---def test_snapshot_round_trip_covers_all_surfaces_and_wal(tmp_path: Path) -> None:- home = tmp_path / "home"- queue_connection = _build_all_surfaces(home)- manager = MemorySnapshotManager(home)-- snapshot = manager.create("clear-01")- queue_connection.close()-- assert snapshot.relative_path == "state/memory/clear-snapshots/clear-01"- assert len(snapshot.manifest_sha256) == 64- roots = {entry.path: entry for entry in snapshot.entries}- assert roots["state/memory/memory.sqlite"].type == "sqlite"- assert roots["memory/everos-root"].type == "tree"- assert roots["memory/everos-root"].tree_digest is not None- assert roots["memory/call-log/call-log.db"].type == "sqlite"- assert roots["memory/attachments"].type == "tree"- assert all(- receipt.pre_clear_digest == receipt.snapshot_digest- and receipt.pre_clear_digest is not None- for receipt in snapshot.surface_receipts- )- surface_digests = {- surface.path: roots[surface.path].sha256 or roots[surface.path].tree_digest- for surface in manager.surfaces- }- assert manager.verify(- "clear-01",- expected_manifest_sha256=snapshot.manifest_sha256,- expected_surface_digests=surface_digests,- ) == snapshot- with pytest.raises(MemorySnapshotVerificationError):- manager.verify(- "clear-01",- expected_manifest_sha256="0" * 64,- expected_surface_digests=surface_digests,- )- with pytest.raises(TypeError):- manager.verify("clear-01") # type: ignore[call-arg]-- manifest_path = manager.snapshot_path("clear-01") / "manifest.jsonl"- manifest_bytes = manifest_path.read_bytes()- manifest = [json.loads(line) for line in manifest_bytes.splitlines()]- assert str(home).encode() not in manifest_bytes- assert manifest[0] == {- "format": "avibe-memory-snapshot",- "record": "header",- "schema_version": 2,- }- entry_records = [record for record in manifest if record["record"] == "entry"]- assert all(- set(row) == {"path", "type", "mode", "size", "sha256", "tree_digest"}- for row in (record["entry"] for record in entry_records)- )- assert all(- not Path(record["entry"]["path"]).is_absolute()- for record in entry_records- )- assert manifest[-1]["record"] == "footer"- assert manifest[-1]["entry_count"] == len(entry_records)- assert stat.S_IMODE(manager.snapshot_path("clear-01").stat().st_mode) == 0o700- assert stat.S_IMODE(manifest_path.stat().st_mode) == 0o600-- # The row committed only to the live WAL must be present in the standalone copy.- copied_queue = (- manager.snapshot_path("clear-01")- / "payload"- / "state/memory/memory.sqlite"- )- assert _sqlite_values(copied_queue) == ["queued-before-clear"]-- with sqlite3.connect(home / "state/memory/memory.sqlite") as connection:- connection.execute("DELETE FROM records")- connection.execute("INSERT INTO records VALUES ('queued-after-clear')")- with sqlite3.connect(home / "memory/call-log/call-log.db") as connection:- connection.execute("DELETE FROM records")- shutil.rmtree(home / "memory/everos-root")- _private_file(home / "memory/everos-root/new.txt", b"new provider bytes", home)- shutil.rmtree(home / "memory/attachments")- _private_file(home / "memory/attachments/new.txt", b"new attachment", home)-- restored = manager.restore(- "clear-01",- expected_manifest_sha256=snapshot.manifest_sha256,- expected_surface_digests=surface_digests,- )-- assert restored == snapshot- assert _sqlite_values(home / "state/memory/memory.sqlite") == ["queued-before-clear"]- assert _sqlite_values(home / "memory/call-log/call-log.db") == ["call-before-clear"]- assert (home / "memory/everos-root/profiles/user.json").read_bytes() == b'{"name":"Ada"}'- assert (home / "memory/everos-root/episodes/empty").is_dir()- assert not (home / "memory/everos-root/new.txt").exists()- assert (home / "memory/attachments/bundles/a1/00.txt").read_bytes() == b"attachment"- assert not (home / "memory/attachments/new.txt").exists()- assert not list(home.rglob("*.before-restore-*"))- assert not list(home.rglob("*.restore-*"))---def test_snapshot_restore_relocates_and_restores_missing_as_absent(tmp_path: Path) -> None:- source_home = tmp_path / "source-home"- source_home.mkdir(mode=0o700)- source_home.chmod(0o700)- _sqlite_surface(source_home / "state/memory/memory.sqlite", "source", source_home)- source_manager = MemorySnapshotManager(source_home)- source_snapshot = source_manager.create("relocatable")- roots = {entry.path: entry for entry in source_snapshot.entries}- assert roots["memory/everos-root"].type == "missing"- assert roots["memory/call-log/call-log.db"].type == "missing"- assert roots["memory/attachments"].type == "missing"-- relocated_home = tmp_path / "relocated-home"- relocated_snapshot = relocated_home / source_snapshot.relative_path- _private_directory(relocated_snapshot.parent, relocated_home)- shutil.copytree(source_manager.snapshot_path("relocatable"), relocated_snapshot)- _private_file(relocated_home / "memory/everos-root/unexpected.txt", b"remove me", relocated_home)- _sqlite_surface(relocated_home / "memory/call-log/call-log.db", "remove me", relocated_home)- _private_file(relocated_home / "memory/attachments/unexpected.txt", b"remove me", relocated_home)-- relocated_manager = MemorySnapshotManager(relocated_home)- relocated_manager.restore(- "relocatable",- expected_manifest_sha256=source_snapshot.manifest_sha256,- expected_surface_digests=source_snapshot.surface_digests(),- )-- assert _sqlite_values(relocated_home / "state/memory/memory.sqlite") == ["source"]- assert not (relocated_home / "memory/everos-root").exists()- assert not (relocated_home / "memory/call-log/call-log.db").exists()- assert not (relocated_home / "memory/attachments").exists()- assert source_home / "state/memory/memory.sqlite" != relocated_home / "state/memory/memory.sqlite"---def test_snapshot_restore_preserves_and_cleans_owner_only_tree_modes(- tmp_path: Path,-) -> None:- home = tmp_path / "home"- target = _private_directory(home / "memory/everos-root", home)- original = _private_file(target / "profile.json", b"before", home)- target.chmod(0o500)- manager = MemorySnapshotManager(- home,- surfaces=(SnapshotSurface("memory/everos-root", "tree"),),- )- snapshot = manager.create("owner-only-tree")-- target.chmod(0o700)- original.write_bytes(b"after")- original.chmod(0o600)- target.chmod(0o500)-- restored = manager.restore(- snapshot.snapshot_id,- expected_manifest_sha256=snapshot.manifest_sha256,- expected_surface_digests=snapshot.surface_digests(),- )-- assert restored == snapshot- assert stat.S_IMODE(target.stat().st_mode) == 0o500- assert original.read_bytes() == b"before"- assert not list(home.rglob("*.before-restore-*"))- assert not list(home.rglob("*.restore-*"))---def test_streaming_manifest_crosses_batches_and_restores_exact_tree(- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- home = tmp_path / "home"- expected = {- f"memory/everos-root/profiles/{index:02d}.json": f"profile-{index}".encode()- for index in range(7)- }- expected.update(- {- "memory/attachments/bundles/a/00.txt": b"attachment-a",- "memory/attachments/bundles/b/00.txt": b"attachment-b",- }- )- for relative, payload in expected.items():- _private_file(home / relative, payload, home)- _private_directory(home / "memory/everos-root/episodes/empty", home)- monkeypatch.setattr(snapshot_module, "_MANIFEST_BATCH_SIZE", 2)- monkeypatch.setattr(snapshot_module, "_DIRECTORY_ORDER_INSERT_BATCH_SIZE", 2)-- manager = MemorySnapshotManager(home)- snapshot = manager.create("many-entries")- with snapshot_module._indexed_manifest(- manager.snapshot_path(snapshot.snapshot_id) / "manifest.jsonl"- ) as (entries, _digest):- assert entries.count() > snapshot_module._MANIFEST_BATCH_SIZE * 4- assert len(snapshot.entries) == len(manager.surfaces)- assert manager.verify(- snapshot.snapshot_id,- expected_manifest_sha256=snapshot.manifest_sha256,- expected_surface_digests=snapshot.surface_digests(),- ) == snapshot-- shutil.rmtree(home / "memory/everos-root")- shutil.rmtree(home / "memory/attachments")- _private_file(home / "memory/everos-root/unexpected.txt", b"unexpected", home)- manager.restore(- snapshot.snapshot_id,- expected_manifest_sha256=snapshot.manifest_sha256,- expected_surface_digests=snapshot.surface_digests(),- )-- for relative, payload in expected.items():- assert (home / relative).read_bytes() == payload- assert (home / "memory/everos-root/episodes/empty").is_dir()- assert not (home / "memory/everos-root/unexpected.txt").exists()---def test_deep_tree_create_verify_restore_and_terminal_clear_gc_converge(- tmp_path: Path,-) -> None:- home = tmp_path / "home"- home.mkdir(mode=0o700)- home.chmod(0o700)- manager = MemorySnapshotManager(home)- source_root = _private_directory(home / "memory/everos-root", home)-- path_max = os.pathconf(home, "PC_PATH_MAX")- longest_prefix = max(- len(os.fsencode(source_root)),- len(- os.fsencode(- manager.snapshot_root- / ".deep-tree.tmp/payload/memory/everos-root"- )- ),- len(os.fsencode(home / "memory/.everos-root.restore-deep-tree-1")),- )- depth = min(1_100, (path_max - longest_prefix - len("/leaf.txt") - 16) // 2)- recursion_limit = min(sys.getrecursionlimit(), depth - 32)- assert recursion_limit > 200- assert depth > recursion_limit-- leaf_parent = source_root- for _ in range(depth):- leaf_parent /= "d"- leaf_parent.mkdir(mode=0o700)- leaf = leaf_parent / "leaf.txt"- leaf.write_bytes(b"sealed deep bytes")- leaf.chmod(0o600)- assert len(os.fsencode(leaf)) < path_max-- journal = MemoryClearJournal(home)- operation = journal.start(- operation_id="deep-tree",- operator_ref="user:owner",- pre_epoch=0,- target_epoch=1,- )- previous_recursion_limit = sys.getrecursionlimit()- try:- sys.setrecursionlimit(recursion_limit)- snapshot = manager.create("deep-tree")- assert manager.verify(- snapshot.snapshot_id,- expected_manifest_sha256=snapshot.manifest_sha256,- expected_surface_digests=snapshot.surface_digests(),- ) == snapshot-- manifest_records = [- json.loads(line)- for line in (- manager.snapshot_path(snapshot.snapshot_id) / "manifest.jsonl"- ).read_bytes().splitlines()- ]- provider_paths = [- record["entry"]["path"]- for record in manifest_records- if record.get("record") == "entry"- and record["entry"]["path"].startswith("memory/everos-root")- ]- expected_directories = [- "memory/everos-root" + "/d" * level- for level in range(depth, 0, -1)- ]- assert provider_paths == [- f"memory/everos-root{'/d' * depth}/leaf.txt",- *expected_directories,- "memory/everos-root",- ]-- snapshot_leaf = (- manager.snapshot_path(snapshot.snapshot_id)- / "payload"- / leaf.relative_to(home)- )- snapshot_leaf.write_bytes(b"corrupt deep bytes")- snapshot_leaf.chmod(0o600)- with pytest.raises(MemorySnapshotVerificationError):- manager.verify(- snapshot.snapshot_id,- expected_manifest_sha256=snapshot.manifest_sha256,- expected_surface_digests=snapshot.surface_digests(),- )- snapshot_leaf.write_bytes(b"sealed deep bytes")- snapshot_leaf.chmod(0o600)-- outside = _private_file(home / "outside.txt", b"outside survives", home)- snapshot_leaf.unlink()- snapshot_leaf.symlink_to(outside)- with pytest.raises(MemorySnapshotVerificationError):- manager.verify(- snapshot.snapshot_id,- expected_manifest_sha256=snapshot.manifest_sha256,- expected_surface_digests=snapshot.surface_digests(),- )- assert outside.read_bytes() == b"outside survives"- snapshot_leaf.unlink()- snapshot_leaf.write_bytes(b"sealed deep bytes")- snapshot_leaf.chmod(0o600)-- leaf.write_bytes(b"new live bytes")- manager.restore(- snapshot.snapshot_id,- expected_manifest_sha256=snapshot.manifest_sha256,- expected_surface_digests=snapshot.surface_digests(),- )- assert leaf.read_bytes() == b"sealed deep bytes"-- leaf.unlink()- leaf.symlink_to(outside)- with pytest.raises(MemorySnapshotUnsafePathError):- manager.create("deep-symlink")- assert not manager.snapshot_path("deep-symlink").exists()- assert outside.read_bytes() == b"outside survives"- manager.restore(- snapshot.snapshot_id,- expected_manifest_sha256=snapshot.manifest_sha256,- expected_surface_digests=snapshot.surface_digests(),- )-- assert operation.execution_token is not None- operation = journal.record_snapshot(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- snapshot=snapshot,- )- assert operation.execution_token is not None- operation = journal.mark_prepared(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- assert operation.execution_token is not None- operation = journal.begin_deleting(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- for surface in journal.surfaces:- assert operation.execution_token is not None- operation = journal.record_surface_deleted(- operation.operation_id,- surface.name,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- assert operation.execution_token is not None- operation = journal.mark_completed(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- MemoryClearSnapshotStorage(journal, manager).remove_terminal_snapshot(- operation.operation_id- )- finally:- sys.setrecursionlimit(previous_recursion_limit)-- assert not manager.snapshot_path(snapshot.snapshot_id).exists()---def test_streaming_manifest_index_stays_memory_bounded_beyond_old_limits(- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- snapshot_dir = _private_directory(tmp_path / "snapshot", tmp_path)- manifest_path = snapshot_dir / "manifest.jsonl"- writer = snapshot_module._ManifestWriter(manifest_path)- try:- for index in range(100_001):- writer.add(- snapshot_module.SnapshotEntry(- path=f"memory/everos-root/items/{index:06d}.json",- type="file",- mode=0o600,- size=index,- sha256="a" * 64,- tree_digest=None,- )- )- writer.finish()- finally:- writer.close()-- assert manifest_path.stat().st_size > 8 * 1024 * 1024- sqlite_temp = _private_directory(tmp_path / "sqlite-temp", tmp_path)- monkeypatch.setenv("SQLITE_TMPDIR", str(sqlite_temp))- tracemalloc.start()- try:- with snapshot_module._indexed_manifest(manifest_path) as (entries, digest):- _current, peak = tracemalloc.get_traced_memory()- assert entries.count() == 100_001- assert entries.entry("memory/everos-root/items/000000.json") is not None- assert entries.entry("memory/everos-root/items/100000.json") is not None- assert digest == snapshot_module._file_sha256(manifest_path)- finally:- tracemalloc.stop()-- # Retaining the old tuple plus dictionaries consumes tens of MiB here.- # The indexed reader holds one JSON record and a fixed SQLite page cache.- assert peak < 8 * 1024 * 1024- assert list(sqlite_temp.iterdir()) == []---def test_spilled_directory_order_is_exact_and_memory_bounded_for_wide_directories(- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- entry_count = 20_001- suffix = "x" * 180-- class FakeEntry:- __slots__ = ("name",)-- def __init__(self, name: str) -> None:- self.name = name-- class ReverseScandir:- def __init__(self) -> None:- self._next_index = entry_count - 1-- def __enter__(self):- return self-- def __exit__(self, *_exc_info: object) -> None:- return None-- def __iter__(self):- return self-- def __next__(self) -> FakeEntry:- if self._next_index < 0:- raise StopIteration- index = self._next_index- self._next_index -= 1- return FakeEntry(f"entry-{index:05d}-{suffix}")-- sqlite_temp = _private_directory(tmp_path / "sqlite-temp", tmp_path)- monkeypatch.setenv("SQLITE_TMPDIR", str(sqlite_temp))- monkeypatch.setattr(- confined_filesystem_module.os,- "scandir",- lambda _descriptor: ReverseScandir(),- )-- connection: sqlite3.Connection | None = None- tracemalloc.start()- try:- with confined_filesystem_module.SpilledDirectoryOrder(- insert_batch_size=11- ) as orders:- connection = orders._connection- cursor = orders.scan(-1)- for index in range(entry_count):- assert orders.next_name(cursor) == f"entry-{index:05d}-{suffix}"- assert orders.next_name(cursor) is None- assert orders.next_name(cursor) is None- _current, peak = tracemalloc.get_traced_memory()- finally:- tracemalloc.stop()-- # Retaining and sorting these names requires more than 4 MiB. The spill- # index holds a fixed insertion batch, one name per DFS frame, and a fixed cache.- assert peak < 3 * 1024 * 1024- assert connection is not None- with pytest.raises(sqlite3.ProgrammingError, match="closed database"):- connection.execute("SELECT 1")- assert list(sqlite_temp.iterdir()) == []---def test_snapshot_translates_temporary_directory_order_database_failure(- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- home = tmp_path / "home"- _private_file(home / "memory/everos-root/profile.json", b"profile", home)- manager = MemorySnapshotManager(home)- failure = confined_filesystem_module.ConfinedFilesystemError(- "temporary ordering unavailable"- )-- def fail_order(*_args, **_kwargs):- raise failure-- monkeypatch.setattr(snapshot_module, "SpilledDirectoryOrder", fail_order)-- with pytest.raises(MemorySnapshotError) as raised:- manager.create("ordering-failure")-- assert raised.value.__cause__ is failure- assert not manager.snapshot_path("ordering-failure").exists()---def test_snapshot_verify_translates_directory_order_construction_failure(- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- home = tmp_path / "home"- _private_file(home / "memory/everos-root/profile.json", b"profile", home)- manager = MemorySnapshotManager(home)- snapshot = manager.create("verify-ordering-failure")- failure = confined_filesystem_module.ConfinedFilesystemError(- "temporary ordering unavailable"- )-- def fail_order(*_args, **_kwargs):- raise failure-- monkeypatch.setattr(snapshot_module, "SpilledDirectoryOrder", fail_order)-- with pytest.raises(MemorySnapshotVerificationError) as raised:- manager.verify(- snapshot.snapshot_id,- expected_manifest_sha256=snapshot.manifest_sha256,- expected_surface_digests=snapshot.surface_digests(),- )-- assert raised.value.__cause__ is failure---def test_backup_reconcile_translates_directory_order_construction_failure(- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- home = _private_directory(tmp_path / "home", tmp_path)- manager = MemorySnapshotManager(- home,- snapshot_root="state/memory/backups",- surfaces=(SnapshotSurface("memory/everos-root", "tree"),),- operation_guard=lambda: None,- )- _private_directory(manager.snapshot_root, home)- failure = confined_filesystem_module.ConfinedFilesystemError(- "temporary ordering unavailable"- )-- def fail_order(*_args, **_kwargs):- raise failure-- monkeypatch.setattr(snapshot_module, "SpilledDirectoryOrder", fail_order)-- with pytest.raises(MemorySnapshotUnsafePathError) as raised:- manager.reconcile_unpublished_backup_stages()-- assert raised.value.__cause__ is failure---def test_streaming_manifest_accepts_extended_unicode_path_record(tmp_path: Path) -> None:- manifest_path = _private_directory(tmp_path / "snapshot", tmp_path) / "manifest.jsonl"- relative_path = "memory/everos-root/" + "/".join(["\u754c" * 200] * 55)- writer = snapshot_module._ManifestWriter(manifest_path)- try:- writer.add(- snapshot_module.SnapshotEntry(- path=relative_path,- type="file",- mode=0o600,- size=1,- sha256="a" * 64,- tree_digest=None,- )- )- writer.finish()- finally:- writer.close()-- lines = manifest_path.read_bytes().splitlines(keepends=True)- assert len(lines[1]) > 64 * 1024- with snapshot_module._indexed_manifest(manifest_path) as (entries, _digest):- assert entries.entry(relative_path) is not None---# The >256KB path record forces roughly 1046 directory levels, and snapshot-# verification is currently quadratic in tree depth, so this one test costs about-# 162 seconds of CPU and exceeds the unit shards' per-file cap. Issue #1380 owns-# the verification speed-up that lets this move back into the unit shards.-def test_snapshot_accepts_path_record_beyond_256k_and_clear_gc(- tmp_path: Path,-) -> None:- home = _private_directory(tmp_path / "home", tmp_path)- source_root = _private_directory(home / "memory/everos-root", home)- component_length = min(os.pathconf(source_root, "PC_NAME_MAX") - 1, 250)- component_count = (256 * 1024 // (component_length + 1)) + 2- components = [- f"d{index:04d}-" + "x" * (component_length - 6)- for index in range(component_count)- ]- relative_leaf = "memory/everos-root/" + "/".join(components) + "/leaf.bin"- assert len(relative_leaf.encode()) > 256 * 1024- _create_deep_file_at(source_root, components, "leaf.bin", b"deep payload")-- manager = MemorySnapshotManager(home)- journal = MemoryClearJournal(home)- operation = journal.start(- operation_id="beyond-line-limit",- operator_ref="user:owner",- pre_epoch=0,- target_epoch=1,- )- snapshot = manager.create(operation.operation_id)- assert manager.verify(- snapshot.snapshot_id,- expected_manifest_sha256=snapshot.manifest_sha256,- expected_surface_digests=snapshot.surface_digests(),- ) == snapshot- with snapshot_module._indexed_manifest(- manager.snapshot_path(snapshot.snapshot_id) / "manifest.jsonl"- ) as (entries, _digest):- assert entries.entry(relative_leaf) is not None-- _create_deep_file_at(source_root, components, "leaf.bin", b"changed")- manager.restore(- snapshot.snapshot_id,- expected_manifest_sha256=snapshot.manifest_sha256,- expected_surface_digests=snapshot.surface_digests(),- )- assert _read_deep_file_at(source_root, components, "leaf.bin") == b"deep payload"-- assert operation.execution_token is not None- operation = journal.record_snapshot(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- snapshot=snapshot,- )- assert operation.execution_token is not None- operation = journal.mark_prepared(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- assert operation.execution_token is not None- operation = journal.begin_deleting(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- for surface in journal.surfaces:- assert operation.execution_token is not None- operation = journal.record_surface_deleted(- operation.operation_id,- surface.name,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- assert operation.execution_token is not None- operation = journal.mark_completed(- operation.operation_id,- expected_revision=operation.revision,- execution_token=operation.execution_token,- )- MemoryClearSnapshotStorage(journal, manager).remove_terminal_snapshot(- operation.operation_id- )- remove_confined_path(home, source_root)- assert not manager.snapshot_path(snapshot.snapshot_id).exists()---def test_manifest_index_temp_database_closes_on_success_and_failure(- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- snapshot_dir = _private_directory(tmp_path / "snapshot", tmp_path)- manifest_path = snapshot_dir / "manifest.jsonl"- writer = snapshot_module._ManifestWriter(manifest_path)- try:- writer.add(- snapshot_module.SnapshotEntry(- path="memory/everos-root/profile.json",- type="file",- mode=0o600,- size=1,- sha256="a" * 64,- tree_digest=None,- )- )- writer.finish()- finally:- writer.close()-- connections: list[sqlite3.Connection] = []- real_init = snapshot_module._ManifestIndex.__init__-- def capture_connection(index) -> None:- real_init(index)- connections.append(index._connection)-- monkeypatch.setattr(snapshot_module._ManifestIndex, "__init__", capture_connection)- with snapshot_module._indexed_manifest(manifest_path):- pass- with pytest.raises(sqlite3.ProgrammingError, match="closed database"):- connections[-1].execute("SELECT 1")-- with pytest.raises(SystemExit, match="injected cancellation"):- with snapshot_module._indexed_manifest(manifest_path):- raise SystemExit("injected cancellation")- with pytest.raises(sqlite3.ProgrammingError, match="closed database"):- connections[-1].execute("SELECT 1")-- manifest_path.write_bytes(manifest_path.read_bytes().splitlines(keepends=True)[0])- with pytest.raises(MemorySnapshotVerificationError):- with snapshot_module._indexed_manifest(manifest_path):- pass- with pytest.raises(sqlite3.ProgrammingError, match="closed database"):- connections[-1].execute("SELECT 1")- assert set(snapshot_dir.iterdir()) == {manifest_path}--[email protected]("damage", ["corrupt", "truncated", "appended", "symlink"])-def test_streaming_manifest_damage_fails_closed(tmp_path: Path, damage: str) -> None:- home = tmp_path / "home"- _private_file(home / "memory/everos-root/profile.json", b"profile", home)- manager = MemorySnapshotManager(home)- snapshot = manager.create(f"manifest-{damage}")- manifest_path = manager.snapshot_path(snapshot.snapshot_id) / "manifest.jsonl"- lines = manifest_path.read_bytes().splitlines(keepends=True)- if damage == "corrupt":- record = json.loads(lines[1])- record["entry"]["size"] += 1- lines[1] = (- json.dumps(record, sort_keys=True, separators=(",", ":")).encode()- + b"\n"- )- manifest_path.write_bytes(b"".join(lines))- elif damage == "truncated":- manifest_path.write_bytes(b"".join(lines[:-1]))- elif damage == "appended":- manifest_path.write_bytes(b"".join(lines) + lines[1])- else:- target = manifest_path.with_name("manifest-real.jsonl")- manifest_path.replace(target)- manifest_path.symlink_to(target.name)- manifest_path.chmod(0o600)-- with pytest.raises(MemorySnapshotVerificationError):- manager.verify(- snapshot.snapshot_id,- expected_manifest_sha256=snapshot.manifest_sha256,- expected_surface_digests=snapshot.surface_digests(),- )---def test_ordinary_backup_includes_clear_audit_and_blocks_on_open_clear(- tmp_path: Path,-) -> None:- home = tmp_path / "home"- queue_connection = _build_all_surfaces(home)- queue_connection.close()- journal = MemoryClearJournal(home)- clear_manager = MemorySnapshotManager(home)- _complete_clear_audit(journal, clear_manager, "completed-audit")-- backup_manager = MemorySnapshotManager._for_backup(- home,- operation_guard=journal.assert_backup_allowed,- )- backup = backup_manager.create("backup-01")-- assert backup.relative_path == "state/memory/backups/backup-01"- roots = {entry.path: entry for entry in backup.entries}- assert roots["state/memory/clear-journal.sqlite"].type == "sqlite"- copied_journal = (- backup_manager.snapshot_path(backup.snapshot_id)- / "payload/state/memory/clear-journal.sqlite"- )- with sqlite3.connect(copied_journal) as connection:- assert connection.execute(- "SELECT state FROM clear_operation WHERE operation_id = 'completed-audit'"- ).fetchone() == ("completed",)- assert connection.execute(- "SELECT event FROM clear_event ORDER BY event_id DESC LIMIT 1"- ).fetchone() == ("completed",)-- journal.start(- operation_id="open-clear",- operator_ref="user:owner",- pre_epoch=1,- target_epoch=2,- )- with pytest.raises(ClearBackupBlocked):- backup_manager.create("blocked-backup")- with pytest.raises(ClearBackupBlocked):- backup_manager.restore(- backup.snapshot_id,- expected_manifest_sha256=backup.manifest_sha256,- expected_surface_digests=backup.surface_digests(),- )---def test_snapshot_verify_fails_before_restore_on_tampered_payload(tmp_path: Path) -> None:- home = tmp_path / "home"- queue_connection = _build_all_surfaces(home)- manager = MemorySnapshotManager(home)- snapshot = manager.create("tamper")- queue_connection.close()- live_provider = home / "memory/everos-root/profiles/user.json"- live_provider.write_bytes(b"live sentinel")-- copied_provider = (- manager.snapshot_path("tamper")- / "payload"- / "memory/everos-root/profiles/user.json"- )- copied_provider.write_bytes(b"tampered")- copied_provider.chmod(0o600)-- with pytest.raises(MemorySnapshotVerificationError):- manager.verify(- "tamper",- expected_manifest_sha256=snapshot.manifest_sha256,- expected_surface_digests=snapshot.surface_digests(),- )- with pytest.raises(MemorySnapshotVerificationError):- manager.restore(- "tamper",- expected_manifest_sha256=snapshot.manifest_sha256,- expected_surface_digests=snapshot.surface_digests(),- )- assert live_provider.read_bytes() == b"live sentinel"-- assert manager.snapshot_path("tamper").exists()---def test_restore_intent_failure_happens_before_any_live_replacement(- tmp_path: Path,-) -> None:- home = tmp_path / "home"- queue_connection = _build_all_surfaces(home)- manager = MemorySnapshotManager(home)- snapshot = manager.create("intent-failure")- queue_connection.close()- provider = home / "memory/everos-root/profiles/user.json"- provider.write_bytes(b"live generation")-- def reject_intent(_snapshot) -> None:- raise OSError("journal unavailable")-- with pytest.raises(OSError, match="journal unavailable"):- manager.restore(- snapshot.snapshot_id,- expected_manifest_sha256=snapshot.manifest_sha256,- expected_surface_digests=snapshot.surface_digests(),- before_replace=reject_intent,- )-- assert provider.read_bytes() == b"live generation"- assert _sqlite_values(home / "state/memory/memory.sqlite") == [- "queued-before-clear"- ]- assert not any(".restore-intent-failure-" in path.name for path in home.rglob("*"))---def test_snapshot_rejects_symlinks_special_files_and_public_modes(tmp_path: Path) -> None:- home = tmp_path / "home"- home.mkdir(mode=0o700)- home.chmod(0o700)- provider = _private_directory(home / "memory/everos-root", home)- outside = _private_file(home / "outside.txt", b"outside", home)- link = provider / "escape"- link.symlink_to(outside)- manager = MemorySnapshotManager(home)-- with pytest.raises(MemorySnapshotUnsafePathError):- manager.create("symlink")- assert outside.read_bytes() == b"outside"- assert not manager.snapshot_path("symlink").exists()-- link.unlink()- public = _private_file(provider / "public.txt", b"public", home)- public.chmod(0o644)- with pytest.raises(MemorySnapshotUnsafePathError):- manager.create("public-mode")- public.unlink()-- hard_link = provider / "hard-link.txt"- os.link(outside, hard_link)- with pytest.raises(MemorySnapshotUnsafePathError):- manager.create("hard-link")- hard_link.unlink()-- if hasattr(os, "mkfifo"):- fifo = provider / "pipe"- os.mkfifo(fifo, mode=0o600)- with pytest.raises(MemorySnapshotUnsafePathError):- manager.create("fifo")- fifo.unlink()---def test_snapshot_rejects_unsafe_ids_and_unmanifested_payload(tmp_path: Path) -> None:- home = tmp_path / "home"- home.mkdir(mode=0o700)- home.chmod(0o700)- manager = MemorySnapshotManager(home)-- with pytest.raises(ValueError):- manager.create("../escape")-- snapshot = manager.create("extra")- extra = manager.snapshot_path("extra") / "payload/unexpected"- extra.write_bytes(b"not manifested")- extra.chmod(0o600)- with pytest.raises(MemorySnapshotVerificationError):- manager.verify(- "extra",- expected_manifest_sha256=snapshot.manifest_sha256,- expected_surface_digests=snapshot.surface_digests(),- )---def test_snapshot_rejects_sqlite_sidecar_symlink_and_overlapping_root(tmp_path: Path) -> None:- home = tmp_path / "home"- home.mkdir(mode=0o700)- home.chmod(0o700)- queue = home / "state/memory/memory.sqlite"- _sqlite_surface(queue, "queued", home)- outside = _private_file(home / "outside-wal", b"outside", home)- queue.with_name(f"{queue.name}-wal").symlink_to(outside)-- with pytest.raises(MemorySnapshotUnsafePathError):- MemorySnapshotManager(home).create("unsafe-sidecar")- with pytest.raises(ValueError):- MemorySnapshotManager(home, snapshot_root="memory")--[email protected]("unsafe_kind", ("symlink", "directory"))-def test_corrupt_call_log_snapshot_refuses_unsafe_sidecars(- tmp_path: Path,- unsafe_kind: str,-) -> None:- home = tmp_path / "home"- call_log = _private_file(- home / "memory/call-log/call-log.db",- b"not-a-sqlite-database",- home,- )- sidecar = call_log.with_name(f"{call_log.name}-wal")- outside = _private_file(home / "outside-wal", b"outside", home)- if unsafe_kind == "symlink":- sidecar.symlink_to(outside)- else:- _private_directory(sidecar, home)- manager = MemorySnapshotManager(home)-- with pytest.raises(MemorySnapshotUnsafePathError):- manager.create(f"unsafe-call-log-{unsafe_kind}")-- assert not manager.snapshot_path(f"unsafe-call-log-{unsafe_kind}").exists()- assert outside.read_bytes() == b"outside"--- ("relative_path", "backup"),- (- ("state/memory/memory.sqlite", False),- ("state/memory/clear-journal.sqlite", True),- ),-)-def test_authoritative_sqlite_surfaces_still_reject_corrupt_databases(- tmp_path: Path,- relative_path: str,- backup: bool,-) -> None:- home = tmp_path / "home"- _private_file(home / relative_path, b"not-a-sqlite-database", home)- manager = (- MemorySnapshotManager._for_backup(home, operation_guard=lambda: None)- if backup- else MemorySnapshotManager(home)- )-- with pytest.raises(MemorySnapshotError):- manager.create(f"corrupt-authority-{backup}")---def test_restore_retry_converges_after_crash_between_backup_and_install(- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- home = tmp_path / "home"- queue_connection = _build_all_surfaces(home)- manager = MemorySnapshotManager(home)- snapshot = manager.create("crash-retry")- queue_connection.close()- queue = home / "state/memory/memory.sqlite"- with sqlite3.connect(queue) as connection:- connection.execute("DELETE FROM records")- connection.execute("INSERT INTO records VALUES ('new-live-value')")-- real_replace = snapshot_module.os.replace- crashed = False-- def crash_after_backup(source, destination, *args, **kwargs):- nonlocal crashed- real_replace(source, destination, *args, **kwargs)- if (- not crashed- and Path(source).name == queue.name- and ".before-restore-crash-retry-0-0" in Path(destination).name- ):- crashed = True- raise SystemExit("injected restore crash")-- monkeypatch.setattr(snapshot_module.os, "replace", crash_after_backup)- with pytest.raises(SystemExit):- manager.restore(- "crash-retry",- expected_manifest_sha256=snapshot.manifest_sha256,- expected_surface_digests=snapshot.surface_digests(),- )- monkeypatch.setattr(snapshot_module.os, "replace", real_replace)-- assert crashed- assert not queue.exists()- assert any(".before-restore-crash-retry-" in path.name for path in home.rglob("*"))-- manager.restore(- "crash-retry",- expected_manifest_sha256=snapshot.manifest_sha256,- expected_surface_digests=snapshot.surface_digests(),- )-- assert _sqlite_values(queue) == ["queued-before-clear"]- assert not any(- ".before-restore-crash-retry-" in path.name- or ".restore-crash-retry-" in path.name- for path in home.rglob("*")- )---def test_create_retry_reclaims_stage_left_by_process_death(- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- home = tmp_path / "home"- for index in range(6):- _private_file(- home / f"memory/everos-root/items/{index}.json",- f"item-{index}".encode(),- home,- )- monkeypatch.setattr(snapshot_module, "_MANIFEST_BATCH_SIZE", 2)- manager = MemorySnapshotManager(home)- real_replace = snapshot_module.os.replace-- def crash_before_publish(source, destination, *args, **kwargs):- if Path(destination).name == "stage-crash":- raise SystemExit("injected snapshot process death")- return real_replace(source, destination, *args, **kwargs)-- monkeypatch.setattr(snapshot_module.os, "replace", crash_before_publish)- with pytest.raises(SystemExit):- manager.create("stage-crash")-- orphaned = list(manager.snapshot_root.glob(".stage-crash*.tmp"))- assert len(orphaned) == 1-- monkeypatch.setattr(snapshot_module.os, "replace", real_replace)- snapshot = manager.create("stage-crash")-- assert snapshot.snapshot_id == "stage-crash"- with snapshot_module._indexed_manifest(- manager.snapshot_path(snapshot.snapshot_id) / "manifest.jsonl"- ) as (entries, _digest):- assert entries.count() > snapshot_module._MANIFEST_BATCH_SIZE- assert not list(manager.snapshot_root.glob(".stage-crash*.tmp"))--- "crash_boundary",- (- "queue-copy",- "provider-copy",- "call-log-copy",- "attachments-copy",- "before-publish",- "after-publish",- ),-)-def test_auto_id_backup_stage_reconcile_covers_copy_and_publish_crashes(- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,- crash_boundary: str,-) -> None:- home = tmp_path / "home"- queue_connection = _build_all_surfaces(home)- queue_connection.close()- manager = MemorySnapshotManager._for_backup(home, operation_guard=lambda: None)- real_snapshot_sqlite = MemorySnapshotManager._snapshot_sqlite- real_snapshot_tree = MemorySnapshotManager._snapshot_tree- real_replace = snapshot_module.os.replace-- sqlite_boundaries = {- "state/memory/memory.sqlite": "queue-copy",- "memory/call-log/call-log.db": "call-log-copy",- }- tree_boundaries = {- "memory/everos-root": "provider-copy",- "memory/attachments": "attachments-copy",- }-- def crash_after_sqlite_copy(self, surface, source, destination):- result = real_snapshot_sqlite(self, surface, source, destination)- if sqlite_boundaries.get(surface.path) == crash_boundary:- raise SystemExit(crash_boundary)- return result-- def crash_after_tree_copy(self, surface, source, destination, manifest):- result = real_snapshot_tree(self, surface, source, destination, manifest)- if tree_boundaries.get(surface.path) == crash_boundary:- raise SystemExit(crash_boundary)- return result-- def crash_at_publish(source, destination, *args, **kwargs):- is_publish = (- Path(source).name.endswith(".tmp")- and not Path(destination).name.startswith(".")- and kwargs.get("src_dir_fd") is not None- and kwargs.get("dst_dir_fd") is not None- )- if is_publish and crash_boundary == "before-publish":- raise SystemExit(crash_boundary)- result = real_replace(source, destination, *args, **kwargs)- if is_publish and crash_boundary == "after-publish":- raise SystemExit(crash_boundary)- return result-- monkeypatch.setattr(MemorySnapshotManager, "_snapshot_sqlite", crash_after_sqlite_copy)- monkeypatch.setattr(MemorySnapshotManager, "_snapshot_tree", crash_after_tree_copy)- monkeypatch.setattr(snapshot_module.os, "replace", crash_at_publish)- with pytest.raises(SystemExit, match=crash_boundary):- manager.create()- monkeypatch.setattr(snapshot_module.os, "replace", real_replace)-- stages = list(manager.snapshot_root.glob(".*.tmp"))- published = [path for path in manager.snapshot_root.iterdir() if not path.name.startswith(".")]- restarted = MemorySnapshotManager._for_backup(home, operation_guard=lambda: None)- if crash_boundary == "after-publish":- assert stages == []- assert len(published) == 1- assert restarted.reconcile_unpublished_backup_stages() == ()- assert published[0].is_dir()- else:- assert len(stages) == 1- stage_id = stages[0].name[1:-4]- assert restarted.reconcile_unpublished_backup_stages() == (stage_id,)- assert not stages[0].exists()- assert published == []--[email protected]("unsafe_kind", ("symlink", "fifo"))-def test_backup_stage_reconcile_refuses_unsafe_managed_candidates(- tmp_path: Path,- unsafe_kind: str,-) -> None:- home = _private_directory(tmp_path / "home", tmp_path)- manager = MemorySnapshotManager._for_backup(home, operation_guard=lambda: None)- backup_root = _private_directory(manager.snapshot_root, home)- outside = _private_file(tmp_path / "outside.txt", b"outside", tmp_path)- candidate = backup_root / f".{('a' * 32)}.tmp"- if unsafe_kind == "symlink":- candidate.symlink_to(outside)- else:- os.mkfifo(candidate, mode=0o600)-- with pytest.raises(MemorySnapshotUnsafePathError):- manager.reconcile_unpublished_backup_stages()-- assert candidate.exists() or candidate.is_symlink()- assert outside.read_bytes() == b"outside"---def test_backup_stage_reconcile_preserves_published_and_unmanaged_entries(- tmp_path: Path,-) -> None:- home = _private_directory(tmp_path / "home", tmp_path)- manager = MemorySnapshotManager._for_backup(home, operation_guard=lambda: None)- published = manager.create("published-backup")- unmanaged = _private_directory(manager.snapshot_root / ".manual.tmp", home)- stage_id = "b" * 32- stage = _private_directory(manager.snapshot_root / f".{stage_id}.tmp", home)- _private_file(stage / "partial.bin", b"partial", home)-- assert manager.reconcile_unpublished_backup_stages() == (stage_id,)- assert manager.snapshot_path(published.snapshot_id).is_dir()- assert unmanaged.is_dir()- assert not stage.exists()---def test_explicit_id_backup_retry_still_reclaims_its_deterministic_stage(- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- home = _private_directory(tmp_path / "home", tmp_path)- manager = MemorySnapshotManager._for_backup(home, operation_guard=lambda: None)- real_replace = snapshot_module.os.replace-- def crash_before_publish(source, destination, *args, **kwargs):- if Path(destination).name == "explicit-retry":- raise SystemExit("injected backup process death")- return real_replace(source, destination, *args, **kwargs)-- monkeypatch.setattr(snapshot_module.os, "replace", crash_before_publish)- with pytest.raises(SystemExit):- manager.create("explicit-retry")- monkeypatch.setattr(snapshot_module.os, "replace", real_replace)-- backup = manager.create("explicit-retry")- assert backup.snapshot_id == "explicit-retry"- assert not (manager.snapshot_root / ".explicit-retry.tmp").exists()diff --git a/tests/test_ui_memory_routes.py b/tests/test_ui_memory_routes.pyindex 9b61ee18d..5b4c23c1e 100644--- a/tests/test_ui_memory_routes.py+++ b/tests/test_ui_memory_routes.py@@ -533,7 +533,7 @@ def test_memory_authenticated_avibe_cloud_uses_the_remote_workbench_principal("status": "ok","data_exists": False,"can_clear": True,- "clear_recovery": None,+ "clear_in_progress": None,},}@@ -755,7 +755,7 @@ def test_memory_processing_record_proxies_signed_operator_and_composite_payload("source": {"status": "available", "observed_at": "now", "reason": None},"data_exists": False,"can_clear": True,- "clear_recovery": None,+ "clear_in_progress": None,},},}@@ -792,11 +792,11 @@ def test_memory_maintenance_proxies_the_local_clear_facts(monkeypatch, tmp_path)"status": "ok","data_exists": True,"can_clear": False,- "clear_recovery": {+ "clear_in_progress": {"operation_id": "clear-42",- "state": "recovery_needed",- "can_resume": False,- "can_abort": True,+ "state": "failed",+ "occurred_at": "2026-08-13T00:00:00Z",+ "error_code": "memory_clear_failed",},},}@@ -811,8 +811,8 @@ def test_memory_maintenance_proxies_the_local_clear_facts(monkeypatch, tmp_path)assert response.status_code == 200assert response.get_json()["can_clear"] is False- assert response.get_json()["clear_recovery"]["operation_id"] == "clear-42"- assert response.get_json()["clear_recovery"]["can_resume"] is False+ assert response.get_json()["clear_in_progress"]["operation_id"] == "clear-42"+ assert response.get_json()["clear_in_progress"]["error_code"] == "memory_clear_failed"assert response.headers["cache-control"] == "no-store"assert user_keys == ["avibe:local"]@@ -834,7 +834,7 @@ def test_memory_maintenance_preserves_the_runtime_clear_capability("status": "ok","data_exists": False,"can_clear": can_clear,- "clear_recovery": None,+ "clear_in_progress": None,},}@@ -2456,37 +2456,6 @@ def test_memory_clear_requires_the_global_csrf_proof(monkeypatch, tmp_path) -> Nassert calls == [][email protected]("action", ["resume", "abort"])-def test_memory_clear_recovery_forwards_exact_operation(- monkeypatch,- tmp_path,- action: str,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)- calls: list[tuple[str, str, str]] = []-- async def recover(operation_id: str, *, action: str, user_key: str):- calls.append((operation_id, action, user_key))- return {- "status_code": 200,- "body": {"status": "aborted" if action == "abort" else "completed"},- }-- monkeypatch.setattr(internal_client, "memory_clear_recovery", recover)- client = app.test_client()- response = client.post(- f"/api/memory/clear/{action}",- json={"operation_id": "clear-42"},- 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 == 200- assert calls == [("clear-42", action, "avibe:local")]--def test_memory_runtime_restart_calls_the_dedicated_transport(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))_save_config(tmp_path)diff --git a/ui/src/components/settings/SettingsMemoryPage.test.tsx b/ui/src/components/settings/SettingsMemoryPage.test.tsxindex aeab51c52..7fb454625 100644--- a/ui/src/components/settings/SettingsMemoryPage.test.tsx+++ b/ui/src/components/settings/SettingsMemoryPage.test.tsx@@ -1,604 +1,51 @@/* @vitest-environment jsdom */-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { cleanup, render, screen, waitFor } from '@testing-library/react';-import userEvent from '@testing-library/user-event';-import { MemoryRouter } from 'react-router-dom';+import { describe, expect, it, vi } from 'vitest';+import { render, screen } from '@testing-library/react';-import { SettingsMemoryPage } from './SettingsMemoryPage';-import type { MemoryProcessingRecordSummary } from '../../context/ApiContext';-import { memoryCascadeHealth } from '../../test/memoryFixtures';import { InstanceAuthorizationContext } from '../../context/InstanceAuthorizationContext';+import { ToastProvider } from '../../context/ToastProvider';import { OWNER_INSTANCE_CAPABILITIES } from '../../lib/sessionInfo';+import { SettingsMemoryPage } from './SettingsMemoryPage';-const api = vi.hoisted(() => ({- abortMemoryClear: vi.fn(),- clearMemory: vi.fn(),- getMemoryMaintenance: vi.fn(),- getMemoryProcessingRecord: vi.fn(),- getMemorySettings: vi.fn(),- listDependencies: vi.fn(),- repairMemoryIndex: vi.fn(),- restartMemoryRuntime: vi.fn(),- resumeMemoryClear: vi.fn(),-}));-const logMounts = vi.hoisted(() => ({ count: 0 }));-const showToast = vi.hoisted(() => vi.fn());-const translate = vi.hoisted(() => (key: string, options?: { returnObjects?: boolean }) =>- options?.returnObjects ? [] : key,+const translate = vi.hoisted(() =>+ (key: string, options?: { returnObjects?: boolean }) =>+ options?.returnObjects && key === 'memory.clear.removes'+ ? ['queue', 'provider', 'call log', 'attachments']+ : options?.returnObjects && key === 'memory.clear.keeps'+ ? ['memory root', 'logs']+ : key,);-vi.mock('../../context/ApiContext', async (loadOriginal) => {- const original = await loadOriginal<typeof import('../../context/ApiContext')>();- return { ...original, useApi: () => api };-});--vi.mock('../../context/ToastContext', () => ({- useToast: () => ({ showToast }),-}));-vi.mock('react-i18next', () => ({useTranslation: () => ({ t: translate }),}));--vi.mock('./SettingsPageShell', () => ({- SettingsPageShell: ({ children }: { children: React.ReactNode }) => children,+vi.mock('../../context/ApiContext', () => ({+ useApi: (() => {+ const api = {+ getMemorySettings: vi.fn().mockResolvedValue({ status: 'failed', error: 'unavailable' }),+ getMemoryProcessingRecord: vi.fn().mockResolvedValue({ status: 'failed', error: 'unavailable' }),+ getMemoryMaintenance: vi.fn().mockResolvedValue({ status: 'failed', error: 'unavailable' }),+ listDependencies: vi.fn().mockResolvedValue({ deps: [] }),+ };+ return () => api;+ })(),}));-vi.mock('../ui/confirm-dialog', () => ({- ConfirmDialog: ({ open, onConfirm }: { open: boolean; onConfirm: () => void | Promise<void> }) =>- open ? <button type="button" onClick={() => void onConfirm()}>confirm-clear</button> : null,-}));--vi.mock('./memory/MemoryLogPanel', async () => {- const React = await import('react');- return {- MemoryLogPanel: ({ refreshToken = 0 }: { refreshToken?: number }) => {- const [mount] = React.useState(() => ++logMounts.count);- return <div data-testid="processing-log">processing-log-{mount}-refresh-{refreshToken}</div>;- },- };-});--vi.mock('./memory/MemoryProfilePanel', () => ({ MemoryProfilePanel: () => null }));-vi.mock('./memory/MemorySearchPanel', () => ({ MemorySearchPanel: () => null }));-vi.mock('./memory/MemorySettingsPanel', () => ({- MemorySettingsPanel: ({- maintenance,- settings,- onClearAll,- onRebuildBusyChange,- onSavingChange,- repairBusy = false,- mutationBusy = false,- }: {- maintenance: { can_clear: boolean } | null;- settings: { factory_reset_required?: boolean };- onClearAll: () => void;- onRebuildBusyChange: (busy: boolean) => void;- onSavingChange?: (busy: boolean) => void;- repairBusy?: boolean;- mutationBusy?: boolean;- }) => (- <div>- <span>{maintenance?.can_clear ? 'maintenance-ready' : 'maintenance-unknown'}</span>- <button type="button" disabled={repairBusy || mutationBusy || settings.factory_reset_required} onClick={onClearAll}>open-clear</button>- <button type="button" disabled={repairBusy || mutationBusy || settings.factory_reset_required} onClick={() => onRebuildBusyChange(true)}>- begin-rebuild- </button>- <button type="button" onClick={() => onRebuildBusyChange(false)}>- end-rebuild- </button>- <button type="button" disabled={repairBusy || mutationBusy} onClick={() => onSavingChange?.(true)}>- begin-save- </button>- <button type="button" onClick={() => onSavingChange?.(false)}>end-save</button>- </div>- ),-}));--const endpoint = {- base_url: 'https://provider.example.test/v1',- model: 'model-1',- api_key: null,- has_api_key: false,-};--const source = { status: 'available' as const, observed_at: '2026-08-08T12:00:00Z', reason: null };--const readyProcessingRecord = (): MemoryProcessingRecordSummary => ({- status: 'ok',- runtime: {- source,- health: {- status: 'ok',- version: '1.2.3',- capabilities: {},- disabled_features: [],- cascade: {},- recorder: {},- },- },- sources: { everos: source, capture: source, calls: source },- anomalies: { source, items: [] },- maintenance: {- source,- data_exists: false,- can_clear: true,- clear_recovery: null,- },- provider_checks: { source, items: [] },-});--const renderPage = () => render(- <InstanceAuthorizationContext.Provider value={{- remote: false,- instanceKind: null,- instanceRole: 'owner',- capabilities: OWNER_INSTANCE_CAPABILITIES,- }}>- <MemoryRouter>- <SettingsMemoryPage />- </MemoryRouter>- </InstanceAuthorizationContext.Provider>,-);--beforeEach(() => {- logMounts.count = 0;- api.getMemorySettings.mockResolvedValue({- status: 'ok',- enabled: true,- processing: { llm: endpoint, embedding: endpoint },- });- api.getMemoryProcessingRecord.mockResolvedValue(readyProcessingRecord());- api.getMemoryMaintenance.mockResolvedValue({- status: 'ok',- data_exists: false,- can_clear: true,- clear_recovery: null,- });- api.listDependencies.mockResolvedValue({ ok: true, deps: [] });- api.restartMemoryRuntime.mockResolvedValue({ ok: true, state: 'ready' });- api.clearMemory.mockResolvedValue({ status: 'completed', operation_id: 'clear-ok', epoch: 1 });- api.resumeMemoryClear.mockResolvedValue({ status: 'completed', operation_id: 'clear-42' });- api.abortMemoryClear.mockResolvedValue({ status: 'aborted', operation_id: 'clear-42' });- api.repairMemoryIndex.mockResolvedValue({- ok: true,- result: 'completed',- health: memoryCascadeHealth(),- });-});--afterEach(() => {- cleanup();- vi.restoreAllMocks();- vi.clearAllMocks();-});--describe('SettingsMemoryPage Processing Record', () => {- it('loads maintenance controls even while the composite summary is stalled', async () => {- api.getMemoryProcessingRecord.mockReturnValue(new Promise(() => undefined));- const user = userEvent.setup();- renderPage();-- await user.click(await screen.findByRole('radio', { name: 'memory.tabs.settings' }));-- expect(await screen.findByText('maintenance-ready')).toBeTruthy();- expect(api.getMemoryMaintenance).toHaveBeenCalledTimes(1);- });-- it('loads one summary and keeps timeline pagination separate', async () => {- const setInterval = vi.spyOn(window, 'setInterval');- renderPage();-- expect(await screen.findByRole('radio', { name: 'memory.tabs.processingRecord' })).toBeTruthy();- expect(await screen.findByTestId('processing-log')).toBeTruthy();- expect(screen.getByRole('button', { name: 'memory.processingRecord.timeline.helpLabel' })).toBeTruthy();- await waitFor(() => expect(api.getMemoryProcessingRecord).toHaveBeenCalledTimes(1));- expect(setInterval.mock.calls.some(([, delay]) => delay === 4000)).toBe(false);- });-- it('refreshes the summary once and refreshes the timeline independently', async () => {- const user = userEvent.setup();- renderPage();- const refresh = await screen.findByRole('button', { name: 'memory.processingRecord.refresh' });- await waitFor(() => expect((refresh as HTMLButtonElement).disabled).toBe(false));-- await user.click(refresh);-- await waitFor(() => expect(api.getMemoryProcessingRecord).toHaveBeenCalledTimes(2));- expect(screen.getByTestId('processing-log').textContent).toContain('refresh-1');- });-- it('keeps retained Processing Record evidence available while Memory is disabled', async () => {- api.getMemorySettings.mockResolvedValue({- status: 'ok',- enabled: false,- repair_available: true,- processing: { llm: endpoint, embedding: endpoint },- });- renderPage();-- expect(await screen.findByTestId('processing-log')).toBeTruthy();- expect(screen.queryByRole('button', { name: 'memory.status.restartEngine' })).toBeNull();- expect(screen.queryByRole('button', { name: 'memory.processingRecord.repair.action' })).toBeNull();- });-- it('renders source-local anomaly failure without hiding maintenance recovery', async () => {- const summary = readyProcessingRecord();- summary.anomalies.source = {- status: 'unavailable',- observed_at: null,- reason: 'memory_store_unavailable',- };- summary.maintenance.clear_recovery = {- operation_id: 'clear-maintenance',- state: 'recovery_needed',- can_resume: true,- can_abort: true,- };- api.getMemoryProcessingRecord.mockResolvedValue(summary);- renderPage();-- expect(await screen.findByText('clear-maintenance')).toBeTruthy();- expect(screen.getByText('errors.memory_store_unavailable')).toBeTruthy();- });-- it('keeps manual_required evidence read-only', async () => {- const summary = readyProcessingRecord();- summary.anomalies.items = [{- id: 'ma_4444444444444444444444444444444444444444444444444444444444444444',- kind: 'attachment_release',- state: 'manual_required',- operation: 'flush',- occurred_at: '2026-08-08T12:01:00Z',- error_code: 'attachment_release_unknown',- attempts: 3,- generation: 2,- request_id: 'request-2',- }];- api.getMemoryProcessingRecord.mockResolvedValue(summary);- renderPage();-- expect(await screen.findByText('memory.processingRecord.manualRequiredReadOnly')).toBeTruthy();- expect(screen.queryByRole('button', { name: 'memory.processingRecord.clearRecovery.resume' })).toBeNull();- });-- it.each([- ['resume', 'resumeMemoryClear', 'completed'],- ['abort', 'abortMemoryClear', 'aborted'],- ] as const)('runs %s and reloads the summary', async (action, method) => {- const summary = readyProcessingRecord();- summary.maintenance.clear_recovery = {- operation_id: 'clear-42',- state: 'recovery_needed',- can_resume: true,- can_abort: true,- };- api.getMemoryProcessingRecord.mockResolvedValue(summary);- const user = userEvent.setup();- renderPage();-- await user.click(await screen.findByRole('button', {- name: `memory.processingRecord.clearRecovery.${action}`,- }));-- await waitFor(() => expect(api[method]).toHaveBeenCalledWith('clear-42'));- await waitFor(() => expect(api.getMemoryProcessingRecord).toHaveBeenCalledTimes(2));- });-- it('awaits a summary reload after a rejected recovery command', async () => {- const initial = readyProcessingRecord();- initial.maintenance.clear_recovery = {- operation_id: 'clear-stale',- state: 'recovery_needed',- can_resume: true,- can_abort: true,- };- const refreshed = readyProcessingRecord();- refreshed.maintenance.clear_recovery = {- operation_id: 'clear-refreshed',- state: 'recovery_needed',- can_resume: true,- can_abort: false,- };- api.getMemoryProcessingRecord- .mockResolvedValueOnce(initial)- .mockResolvedValueOnce(refreshed);- api.resumeMemoryClear.mockResolvedValueOnce({ status: 'failed', error: 'memory_clear_failed' });- const user = userEvent.setup();- renderPage();-- await user.click(await screen.findByRole('button', {- name: 'memory.processingRecord.clearRecovery.resume',- }));-- expect(await screen.findByText('clear-refreshed')).toBeTruthy();- expect(api.getMemoryProcessingRecord).toHaveBeenCalledTimes(2);- });-- it('reloads the summary after a failed Clear', async () => {- api.clearMemory.mockResolvedValue({ status: 'failed', error: 'memory_clear_failed' });- const user = userEvent.setup();- renderPage();-- await user.click(await screen.findByRole('radio', { name: 'memory.tabs.settings' }));- await user.click(await screen.findByRole('button', { name: 'open-clear' }));- await user.click(await screen.findByRole('button', { name: 'confirm-clear' }));-- await waitFor(() => expect(api.getMemoryProcessingRecord).toHaveBeenCalledTimes(2));- });-});--describe('SettingsMemoryPage restart action', () => {- it('stays available when the summary cannot be loaded', async () => {- api.getMemoryProcessingRecord.mockResolvedValue({- status: 'failed',- error: 'memory_status_failed',- });- renderPage();-- expect(await screen.findByRole('button', { name: 'memory.status.restartEngine' })).toBeTruthy();- });-- it('is disabled and shows progress while the request is pending', async () => {- let finishRestart: ((value: { ok: true; state: string }) => void) | undefined;- api.restartMemoryRuntime.mockReturnValue(new Promise((resolve) => { finishRestart = resolve; }));- const user = userEvent.setup();- renderPage();- const action = await screen.findByRole('button', { name: 'memory.status.restartEngine' });-- await user.click(action);- expect((action as HTMLButtonElement).disabled).toBe(true);- finishRestart?.({ ok: true, state: 'ready' });- await waitFor(() => expect((action as HTMLButtonElement).disabled).toBe(false));- });-- it('is disabled while an embedding rebuild is required', async () => {- api.getMemorySettings.mockResolvedValue({- status: 'ok',- enabled: true,- rebuild_required: true,- processing: { llm: endpoint, embedding: endpoint },- });- renderPage();-- const action = await screen.findByRole('button', { name: 'memory.status.restartEngine' });- expect((action as HTMLButtonElement).disabled).toBe(true);- });-- it('is disabled while the settings panel is running a rebuild', async () => {- const user = userEvent.setup();- renderPage();- const action = await screen.findByRole('button', { name: 'memory.status.restartEngine' });-- await user.click(await screen.findByRole('radio', { name: 'memory.tabs.settings' }));- await user.click(await screen.findByRole('button', { name: 'begin-rebuild' }));- expect((action as HTMLButtonElement).disabled).toBe(true);-- await user.click(screen.getByRole('button', { name: 'end-rebuild' }));- expect((action as HTMLButtonElement).disabled).toBe(false);- });-- it('does not render reinitialization controls on the Memory page', async () => {- renderPage();- await userEvent.setup().click(await screen.findByRole('radio', { name: 'memory.tabs.settings' }));-- expect(screen.queryByRole('button', { name: 'memory.factoryReset.button' })).toBeNull();- expect(screen.queryByRole('button', { name: 'memory.factoryReset.retry' })).toBeNull();- });-});--describe('SettingsMemoryPage Repair action', () => {- it('keeps the capability action visible when the health summary fails', async () => {- api.getMemorySettings.mockResolvedValue({- status: 'ok',- enabled: true,- repair_available: true,- processing: { llm: endpoint, embedding: endpoint },- });- api.getMemoryProcessingRecord.mockResolvedValue({ status: 'failed', error: 'memory_status_failed' });- renderPage();-- expect(await screen.findByRole('button', { name: 'memory.processingRecord.repair.action' })).toBeTruthy();- });-- it('locks restart and settings clear for the full Repair request lifetime', async () => {- let finishRepair: ((value: unknown) => void) | undefined;- const summary = readyProcessingRecord();- summary.maintenance.clear_recovery = {- operation_id: 'clear-during-repair',- state: 'recovery_needed',- can_resume: true,- can_abort: true,- };- api.getMemorySettings.mockResolvedValue({- status: 'ok',- enabled: true,- repair_available: true,- processing: { llm: endpoint, embedding: endpoint },- });- api.getMemoryProcessingRecord.mockResolvedValue(summary);- api.repairMemoryIndex.mockReturnValue(new Promise((resolve) => { finishRepair = resolve; }));- const user = userEvent.setup();- renderPage();-- const repair = await screen.findByRole('button', { name: 'memory.processingRecord.repair.action' });- await user.click(repair);- await user.click(screen.getByRole('button', { name: 'confirm-clear' }));-- await waitFor(() => expect(api.repairMemoryIndex).toHaveBeenCalledTimes(1));- expect((repair as HTMLButtonElement).disabled).toBe(true);- expect((screen.getByRole('button', { name: 'memory.processingRecord.clearRecovery.resume' }) as HTMLButtonElement).disabled).toBe(true);- expect((screen.getByRole('button', { name: 'memory.processingRecord.clearRecovery.abort' }) as HTMLButtonElement).disabled).toBe(true);- await waitFor(() => expect((screen.getByRole('button', { name: 'memory.status.restartEngine' }) as HTMLButtonElement).disabled).toBe(true));- expect(api.restartMemoryRuntime).not.toHaveBeenCalled();- await user.click(await screen.findByRole('radio', { name: 'memory.tabs.settings' }));- expect((screen.getByRole('button', { name: 'open-clear' }) as HTMLButtonElement).disabled).toBe(true);- expect((screen.getByRole('button', { name: 'begin-rebuild' }) as HTMLButtonElement).disabled).toBe(true);-- finishRepair?.({- ok: true,- result: 'completed',- health: memoryCascadeHealth(),- });- await waitFor(() => expect((screen.getByRole('button', { name: 'memory.status.restartEngine' }) as HTMLButtonElement).disabled).toBe(false));- });-- it('renders an unhealthy Repair completion as warnings', async () => {- const warningHealth = memoryCascadeHealth({- healthy: false,- reasons: ['drain_failures'],- pending: 1,- failed_retryable: 1,- drain_consecutive_failures: 2,- prune_stale_seconds: 60,- });- api.getMemorySettings.mockResolvedValue({- status: 'ok',- enabled: true,- repair_available: true,- processing: { llm: endpoint, embedding: endpoint },- });- api.repairMemoryIndex.mockResolvedValue({- ok: true,- result: 'completed_with_warnings',- health: warningHealth,- });- const user = userEvent.setup();- renderPage();-- await user.click(await screen.findByRole('button', { name: 'memory.processingRecord.repair.action' }));- await user.click(screen.getByRole('button', { name: 'confirm-clear' }));-- await waitFor(() => expect(api.repairMemoryIndex).toHaveBeenCalledTimes(1));- expect(showToast).toHaveBeenCalledWith(- 'memory.processingRecord.repair.completedWithWarnings',- 'warning',+describe('SettingsMemoryPage', () => {+ it('mounts the memory settings surface for an instance owner', () => {+ render(+ <InstanceAuthorizationContext.Provider value={{+ remote: false,+ instanceKind: null,+ instanceRole: 'owner',+ capabilities: OWNER_INSTANCE_CAPABILITIES,+ }}>+ <ToastProvider>+ <SettingsMemoryPage />+ </ToastProvider>+ </InstanceAuthorizationContext.Provider>,);- expect(await screen.findByText('memory.processingRecord.repair.completedWithWarnings')).toBeTruthy();- });-- it('prevents a second Repair request while the first is pending', async () => {- let finishRepair: ((value: unknown) => void) | undefined;- api.getMemorySettings.mockResolvedValue({- status: 'ok',- enabled: true,- repair_available: true,- processing: { llm: endpoint, embedding: endpoint },- });- api.repairMemoryIndex.mockReturnValue(new Promise((resolve) => { finishRepair = resolve; }));- const user = userEvent.setup();- renderPage();-- const repair = await screen.findByRole('button', { name: 'memory.processingRecord.repair.action' });- await user.click(repair);- await user.click(screen.getByRole('button', { name: 'confirm-clear' }));- await waitFor(() => expect(api.repairMemoryIndex).toHaveBeenCalledTimes(1));-- const runningRepair = screen.getByRole('button', { name: 'memory.processingRecord.repair.running' });- expect((runningRepair as HTMLButtonElement).disabled).toBe(true);- await user.click(runningRepair);- expect(api.repairMemoryIndex).toHaveBeenCalledTimes(1);-- finishRepair?.({ ok: true, result: 'completed', health: memoryCascadeHealth() });- await waitFor(() => expect(screen.getByRole('button', { name: 'memory.processingRecord.repair.action' })).toBeTruthy());- });-- it('blocks Repair during restart, rebuild, and clear confirmation', async () => {- let finishRestart: ((value: { ok: true; state: string }) => void) | undefined;- api.getMemorySettings.mockResolvedValue({- status: 'ok',- enabled: true,- repair_available: true,- processing: { llm: endpoint, embedding: endpoint },- });- api.restartMemoryRuntime.mockReturnValue(new Promise((resolve) => { finishRestart = resolve; }));- const user = userEvent.setup();- renderPage();-- await user.click(await screen.findByRole('button', { name: 'memory.status.restartEngine' }));- expect((screen.getByRole('button', { name: 'memory.processingRecord.repair.action' }) as HTMLButtonElement).disabled).toBe(true);- finishRestart?.({ ok: true, state: 'ready' });- await waitFor(() => expect((screen.getByRole('button', { name: 'memory.processingRecord.repair.action' }) as HTMLButtonElement).disabled).toBe(false));-- await user.click(screen.getByRole('radio', { name: 'memory.tabs.settings' }));- await user.click(screen.getByRole('button', { name: 'begin-rebuild' }));- await user.click(screen.getByRole('radio', { name: 'memory.tabs.processingRecord' }));- expect((screen.getByRole('button', { name: 'memory.processingRecord.repair.action' }) as HTMLButtonElement).disabled).toBe(true);-- await user.click(screen.getByRole('radio', { name: 'memory.tabs.settings' }));- await user.click(screen.getByRole('button', { name: 'end-rebuild' }));- await user.click(screen.getByRole('button', { name: 'open-clear' }));- await user.click(screen.getByRole('radio', { name: 'memory.tabs.processingRecord' }));- expect((screen.getByRole('button', { name: 'memory.processingRecord.repair.action' }) as HTMLButtonElement).disabled).toBe(true);- });-- it('blocks Repair and settings mutations for the full Clear recovery lifetime', async () => {- let finishRecovery: ((value: { status: 'completed'; operation_id: string }) => void) | undefined;- const summary = readyProcessingRecord();- summary.maintenance.clear_recovery = {- operation_id: 'clear-recovery',- state: 'recovery_needed',- can_resume: true,- can_abort: true,- };- api.getMemorySettings.mockResolvedValue({- status: 'ok',- enabled: true,- repair_available: true,- processing: { llm: endpoint, embedding: endpoint },- });- api.getMemoryProcessingRecord.mockResolvedValue(summary);- api.resumeMemoryClear.mockReturnValue(new Promise((resolve) => { finishRecovery = resolve; }));- const user = userEvent.setup();- renderPage();-- await user.click(await screen.findByRole('button', { name: 'memory.processingRecord.clearRecovery.resume' }));- await waitFor(() => expect(api.resumeMemoryClear).toHaveBeenCalledWith('clear-recovery'));- expect((screen.getByRole('button', { name: 'memory.processingRecord.repair.action' }) as HTMLButtonElement).disabled).toBe(true);- expect((screen.getByRole('button', { name: 'memory.status.restartEngine' }) as HTMLButtonElement).disabled).toBe(true);-- await user.click(screen.getByRole('radio', { name: 'memory.tabs.settings' }));- expect((screen.getByRole('button', { name: 'open-clear' }) as HTMLButtonElement).disabled).toBe(true);- expect((screen.getByRole('button', { name: 'begin-rebuild' }) as HTMLButtonElement).disabled).toBe(true);- expect((screen.getByRole('button', { name: 'begin-save' }) as HTMLButtonElement).disabled).toBe(true);-- finishRecovery?.({ status: 'completed', operation_id: 'clear-recovery' });- await user.click(screen.getByRole('radio', { name: 'memory.tabs.processingRecord' }));- await waitFor(() => expect((screen.getByRole('button', { name: 'memory.processingRecord.repair.action' }) as HTMLButtonElement).disabled).toBe(false));- });-- it('blocks Repair and Clear recovery while settings are saving', async () => {- const summary = readyProcessingRecord();- summary.maintenance.clear_recovery = {- operation_id: 'clear-during-save',- state: 'recovery_needed',- can_resume: true,- can_abort: true,- };- api.getMemorySettings.mockResolvedValue({- status: 'ok',- enabled: true,- repair_available: true,- processing: { llm: endpoint, embedding: endpoint },- });- api.getMemoryProcessingRecord.mockResolvedValue(summary);- const user = userEvent.setup();- renderPage();-- await user.click(await screen.findByRole('radio', { name: 'memory.tabs.settings' }));- await user.click(screen.getByRole('button', { name: 'begin-save' }));- await user.click(screen.getByRole('radio', { name: 'memory.tabs.processingRecord' }));-- expect((screen.getByRole('button', { name: 'memory.processingRecord.repair.action' }) as HTMLButtonElement).disabled).toBe(true);- expect((screen.getByRole('button', { name: 'memory.processingRecord.clearRecovery.resume' }) as HTMLButtonElement).disabled).toBe(true);- expect((screen.getByRole('button', { name: 'memory.processingRecord.clearRecovery.abort' }) as HTMLButtonElement).disabled).toBe(true);- expect((screen.getByRole('button', { name: 'memory.status.restartEngine' }) as HTMLButtonElement).disabled).toBe(true);-- await user.click(screen.getByRole('radio', { name: 'memory.tabs.settings' }));- await user.click(screen.getByRole('button', { name: 'end-save' }));- await user.click(screen.getByRole('radio', { name: 'memory.tabs.processingRecord' }));- expect((screen.getByRole('button', { name: 'memory.processingRecord.repair.action' }) as HTMLButtonElement).disabled).toBe(false);+ expect(screen.getByRole('heading', { name: 'memory.title' })).toBeTruthy();});});diff --git a/ui/src/components/settings/SettingsMemoryPage.tsx b/ui/src/components/settings/SettingsMemoryPage.tsxindex 9f573d824..8013059e5 100644--- a/ui/src/components/settings/SettingsMemoryPage.tsx+++ b/ui/src/components/settings/SettingsMemoryPage.tsx@@ -52,7 +52,6 @@ export const SettingsMemoryPage: React.FC = () => {const [repairHealth, setRepairHealth] = useState<MemoryCascadeHealth | null>(null);const [logGeneration, setLogGeneration] = useState(0);const [logRefreshToken, setLogRefreshToken] = useState(0);- const [recoveryAction, setRecoveryAction] = useState<'resume' | 'abort' | null>(null);const settingsRead = useMemoryResource<MemorySettingsOk>({read: api.getMemorySettings,@@ -77,15 +76,12 @@ export const SettingsMemoryPage: React.FC = () => {source: processingRecord.runtime.source,health: processingRecord.runtime.health,} : null;- const reloadRecoveryState = useCallback(async () => {- await Promise.all([loadProcessingRecord(), loadMaintenance()]);- }, [loadMaintenance, loadProcessingRecord]);// Forbidden is the backend's "this is not a direct-loopback browser" verdict, and it is// sticky per resource, so the static state never flickers away on a later request.const remoteUnavailable =settingsRead.forbidden || processingRecordRead.forbidden || maintenanceRead.forbidden;const repairMutationBusy =- restarting || rebuildBusy || clearing || clearOpen || recoveryAction !== null || settingsSaving || settings?.factory_reset_required === true;+ restarting || rebuildBusy || clearing || clearOpen || settingsSaving || settings?.factory_reset_required === true;// Dependency readiness comes from the authoritative Dependencies source. Processing Record// health is observational and never doubles as installation or enablement state.@@ -116,7 +112,7 @@ export const SettingsMemoryPage: React.FC = () => {}, [loadSettings, loadProcessingRecord, loadMaintenance, loadDependency]);const confirmClear = async () => {- if (repairBusy || restarting || rebuildBusy || clearing || recoveryAction !== null || settingsSaving) return;+ if (repairBusy || restarting || rebuildBusy || clearing || settingsSaving) return;setClearing(true);// Clear can delete provider payloads before a failed receipt or a lost// response, so purge cached payloads for every confirmed attempt.@@ -149,33 +145,9 @@ export const SettingsMemoryPage: React.FC = () => {setLogRefreshToken((token) => token + 1);};- const runClearRecovery = async (action: 'resume' | 'abort', operationId: string) => {- if (repairBusy || restarting || rebuildBusy || clearing || clearOpen || recoveryAction !== null || settingsSaving) return;- setRecoveryAction(action);- try {- const res = action === 'resume'- ? await api.resumeMemoryClear(operationId)- : await api.abortMemoryClear(operationId);- if (res.status === 'completed' || res.status === 'aborted') {- showToast(t(`memory.processingRecord.clearRecovery.${action}Success`), 'success');- setLogGeneration((generation) => generation + 1);- void loadProcessingRecord();- void loadMaintenance();- void loadSettings();- } else {- await reloadRecoveryState();- showToast(memoryErrorMessage(t, 'error' in res ? res.error : undefined), 'error');- }- } catch {- await reloadRecoveryState();- showToast(t('memory.processingRecord.clearRecovery.actionFailed'), 'error');- } finally {- setRecoveryAction(null);- }- };const restartEngine = async () => {- if (repairBusy || rebuildBusy || clearing || clearOpen || recoveryAction !== null || settingsSaving) return;+ if (repairBusy || rebuildBusy || clearing || clearOpen || settingsSaving) return;setRestarting(true);try {const res = await api.restartMemoryRuntime();@@ -242,7 +214,7 @@ export const SettingsMemoryPage: React.FC = () => {dependencyReady={dependencyReady}rebuildBusy={rebuildBusy}repairBusy={repairBusy}- mutationBusy={restarting || recoveryAction !== null}+ mutationBusy={restarting}onRebuildBusyChange={setRebuildBusy}onSavingChange={setSettingsSaving}onSaved={(next) => {@@ -328,7 +300,7 @@ export const SettingsMemoryPage: React.FC = () => {<MemoryStatusPanelstatus={status}failures={processingRecord?.anomalies.items ?? []}- recovery={processingRecord?.maintenance.clear_recovery ?? null}+ clearInProgress={processingRecord?.maintenance.clear_in_progress ?? null}logSections={processingRecord?.sources ?? null}providerChecks={processingRecord?.provider_checks?.items ?? []}providerChecksSource={processingRecord?.provider_checks?.source ?? null}@@ -341,14 +313,7 @@ export const SettingsMemoryPage: React.FC = () => {: processingRecordRead.error}refreshPending={processingRecordRead.loading}- recoveryAction={recoveryAction}onRefresh={refreshProcessingRecord}- onResumeClear={(operationId) => {- if (canAdminister) void runClearRecovery('resume', operationId);- }}- onAbortClear={(operationId) => {- if (canAdminister) void runClearRecovery('abort', operationId);- }}repairSupported={canAdminister && settings.enabled === true && settings.repair_available === true}repairBusy={repairBusy}mutationBusy={repairMutationBusy}diff --git a/ui/src/components/settings/memory/MemorySettingsPanel.test.tsx b/ui/src/components/settings/memory/MemorySettingsPanel.test.tsxindex 93bc6e587..75fd5d060 100644--- a/ui/src/components/settings/memory/MemorySettingsPanel.test.tsx+++ b/ui/src/components/settings/memory/MemorySettingsPanel.test.tsx@@ -83,7 +83,7 @@ describe('MemorySettingsPanel', () => {render(<MemorySettingsPanelsettings={legacySettings}- maintenance={{ status: 'ok', data_exists: true, can_clear: true, clear_recovery: null }}+ maintenance={{ status: 'ok', data_exists: true, can_clear: true, clear_in_progress: null }}maintenanceError={null}dependencyReadymutationBusy@@ -103,7 +103,7 @@ describe('MemorySettingsPanel', () => {render(<MemorySettingsPanelsettings={{ ...legacySettings, factory_reset_required: true }}- maintenance={{ status: 'ok', data_exists: true, can_clear: true, clear_recovery: null }}+ maintenance={{ status: 'ok', data_exists: true, can_clear: true, clear_in_progress: null }}maintenanceError={null}dependencyReadyonSaved={() => undefined}@@ -213,7 +213,7 @@ describe('MemorySettingsPanel', () => {render(<MemorySettingsPanelsettings={legacySettings}- maintenance={{ status: 'ok', data_exists: true, can_clear: true, clear_recovery: null }}+ maintenance={{ status: 'ok', data_exists: true, can_clear: true, clear_in_progress: null }}maintenanceError={null}dependencyReadyonSaved={() => undefined}@@ -329,7 +329,7 @@ describe('MemorySettingsPanel', () => {render(<MemorySettingsPanelsettings={firstSetupSettings}- maintenance={{ status: 'ok', data_exists: false, can_clear: true, clear_recovery: null }}+ maintenance={{ status: 'ok', data_exists: false, can_clear: true, clear_in_progress: null }}maintenanceError={null}dependencyReadyonSaved={() => undefined}@@ -399,7 +399,7 @@ describe('MemorySettingsPanel', () => {render(<MemorySettingsPanelsettings={{ ...legacySettings, rebuild_required: true }}- maintenance={{ status: 'ok', data_exists: true, can_clear: true, clear_recovery: null }}+ maintenance={{ status: 'ok', data_exists: true, can_clear: true, clear_in_progress: null }}maintenanceError={null}dependencyReadyonSaved={() => undefined}@@ -599,7 +599,7 @@ describe('MemorySettingsPanel', () => {render(<MemorySettingsPanelsettings={legacySettings}- maintenance={{ status: 'ok', data_exists: dataExists, can_clear: false, clear_recovery: null }}+ maintenance={{ status: 'ok', data_exists: dataExists, can_clear: false, clear_in_progress: null }}maintenanceError={null}dependencyReadyonSaved={() => undefined}@@ -616,6 +616,39 @@ describe('MemorySettingsPanel', () => {expect(onClearAll).not.toHaveBeenCalled();});+ it('keeps Clear available for an explicit retry after a failed marker', async () => {+ const onClearAll = vi.fn();+ const user = userEvent.setup();+ render(+ <MemorySettingsPanel+ settings={legacySettings}+ maintenance={{+ status: 'ok',+ data_exists: true,+ can_clear: true,+ clear_in_progress: {+ operation_id: 'clear-1',+ state: 'failed',+ occurred_at: '2026-08-13T00:00:00Z',+ error_code: 'memory_clear_marker_unreadable',+ },+ }}+ maintenanceError={null}+ dependencyReady+ onSaved={() => undefined}+ onReloadSettings={() => undefined}+ onReloadMaintenance={() => undefined}+ onClearAll={onClearAll}+ clearing={false}+ />,+ );++ const clear = screen.getByRole('button', { name: 'memory.clear.button' }) as HTMLButtonElement;+ expect(clear.disabled).toBe(false);+ await user.click(clear);+ expect(onClearAll).toHaveBeenCalledOnce();+ });+it('does not announce rebuild completion for ordinary reconcile results', async () => {api.saveMemorySettings.mockResolvedValue({...legacySettings,@@ -663,7 +696,7 @@ describe('MemorySettingsPanel', () => {render(<MemorySettingsPanelsettings={legacySettings}- maintenance={{ status: 'ok', data_exists: true, can_clear: true, clear_recovery: null }}+ maintenance={{ status: 'ok', data_exists: true, can_clear: true, clear_in_progress: null }}maintenanceError={null}dependencyReadyonSaved={() => undefined}diff --git a/ui/src/components/settings/memory/MemoryStatusPanel.i18n.test.tsx b/ui/src/components/settings/memory/MemoryStatusPanel.i18n.test.tsxindex 51ed49e4a..123edb906 100644--- a/ui/src/components/settings/memory/MemoryStatusPanel.i18n.test.tsx+++ b/ui/src/components/settings/memory/MemoryStatusPanel.i18n.test.tsx@@ -5,7 +5,7 @@ import { cleanup, render, screen } from '@testing-library/react';import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, describe, expect, it, vi } from 'vitest';-import type { MemoryFailureLogEntry } from '../../../context/ApiContext';+import type { MemoryClearInProgress, MemoryFailureLogEntry } from '../../../context/ApiContext';import en from '../../../i18n/en.json';import zh from '../../../i18n/zh.json';import { MemoryStatusPanel } from './MemoryStatusPanel';@@ -35,17 +35,14 @@ const renderAnomaly = (language: 'en' | 'zh', errorCode: string) => {<MemoryStatusPanelstatus={null}failures={[failure]}- recovery={null}+ clearInProgress={null}logSections={null}statusLoading={false}failuresLoading={false}statusError={null}failuresError={null}refreshPending={false}- recoveryAction={null}onRefresh={vi.fn()}- onResumeClear={vi.fn()}- onAbortClear={vi.fn()}/></I18nextProvider>,);@@ -65,7 +62,7 @@ const renderUnobservedSource = (language: 'en' | 'zh') => {<MemoryStatusPanelstatus={null}failures={[]}- recovery={null}+ clearInProgress={null}logSections={{everos: { status: 'available', observed_at: null },capture: { status: 'unavailable', observed_at: null, reason: 'missing' },@@ -76,10 +73,39 @@ const renderUnobservedSource = (language: 'en' | 'zh') => {statusError={null}failuresError={null}refreshPending={false}- recoveryAction={null}onRefresh={vi.fn()}- onResumeClear={vi.fn()}- onAbortClear={vi.fn()}+ />+ </I18nextProvider>,+ );+};++const renderClearState = (language: 'en' | 'zh', errorCode: string) => {+ const i18n = createInstance();+ void i18n.use(initReactI18next).init({+ lng: language,+ fallbackLng: 'en',+ resources: { en: { translation: en }, zh: { translation: zh } },+ interpolation: { escapeValue: false },+ });+ const clearInProgress: MemoryClearInProgress = {+ state: 'failed',+ operation_id: 'clear-i18n',+ occurred_at: '2026-08-09T12:00:00Z',+ error_code: errorCode,+ };+ render(+ <I18nextProvider i18n={i18n}>+ <MemoryStatusPanel+ status={null}+ failures={[]}+ clearInProgress={clearInProgress}+ logSections={null}+ statusLoading={false}+ failuresLoading={false}+ statusError={null}+ failuresError={null}+ refreshPending={false}+ onRefresh={vi.fn()}/></I18nextProvider>,);@@ -91,6 +117,8 @@ describe('MemoryStatusPanel anomaly error localization', () => {it.each([['en', 'memory_provider_timeout', en.errors.memory_provider_timeout],['zh', 'memory_processing_failed', zh.errors.memory_processing_failed],+ ['en', 'memory_clear_marker_unreadable', en.errors.memory_clear_marker_unreadable],+ ['zh', 'memory_clear_legacy_state_requires_rerun', zh.errors.memory_clear_legacy_state_requires_rerun],['zh', 'future_provider_failure', 'future_provider_failure'],] as const)('renders %s error %s as %s', (language, errorCode, expected) => {renderAnomaly(language, errorCode);@@ -98,6 +126,33 @@ describe('MemoryStatusPanel anomaly error localization', () => {expect(screen.getByText(expected)).toBeTruthy();});+ it.each([+ ['en', en.memory.processingRecord.clearInProgress.explicitRetryDescription],+ ['zh', zh.memory.processingRecord.clearInProgress.explicitRetryDescription],+ ] as const)('describes legacy state recovery as an explicit retry in %s', (language, expected) => {+ renderClearState(language, 'memory_clear_legacy_state_requires_rerun');++ expect(screen.getByText(expected)).toBeTruthy();+ });++ it.each([+ ['en', en.memory.processingRecord.clearInProgress.explicitRetryDescription],+ ['zh', zh.memory.processingRecord.clearInProgress.explicitRetryDescription],+ ] as const)('describes unreadable marker repair as an explicit retry in %s', (language, expected) => {+ renderClearState(language, 'memory_clear_marker_unreadable');++ expect(screen.getByText(expected)).toBeTruthy();+ });++ it.each([+ ['en', en.memory.processingRecord.clearInProgress.explicitRetryDescription],+ ['zh', zh.memory.processingRecord.clearInProgress.explicitRetryDescription],+ ] as const)('describes an ordinary failed Clear as an explicit retry in %s', (language, expected) => {+ renderClearState(language, 'memory_clear_failed');++ expect(screen.getByText(expected)).toBeTruthy();+ });+it.each([['en', en.memory.processingRecord.sourceState.unknown, en.memory.processingRecord.sourceNotObserved],['zh', zh.memory.processingRecord.sourceState.unknown, zh.memory.processingRecord.sourceNotObserved],diff --git a/ui/src/components/settings/memory/MemoryStatusPanel.test.tsx b/ui/src/components/settings/memory/MemoryStatusPanel.test.tsxindex baba8a2a3..ecd51e147 100644--- a/ui/src/components/settings/memory/MemoryStatusPanel.test.tsx+++ b/ui/src/components/settings/memory/MemoryStatusPanel.test.tsx@@ -2,384 +2,62 @@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,- MemoryProviderCall,- MemoryStatus,-} from '../../../context/ApiContext';-import { memoryCascadeHealth } from '../../../test/memoryFixtures';+import type { MemoryClearInProgress, MemoryStatus } from '../../../context/ApiContext';import { MemoryStatusPanel } from './MemoryStatusPanel';vi.mock('react-i18next', () => ({useTranslation: () => ({- t: (key: string, options?: Record<string, unknown>) => (- key === 'memory.processingRecord.sourceReason'- ? `${key}:${String(options?.reason)}`- : key === 'errors.future_clear_error'- ? String(options?.defaultValue)- : key- ),+ t: (key: string) => key,}),}));-const STATUS: MemoryStatus = {+const status: MemoryStatus = {status: 'ok',- source: {- status: 'available',- observed_at: '2026-08-08T12:00:00Z',- reason: null,- },+ source: { status: 'available', observed_at: '2026-08-13T00:00:00Z', reason: null },health: {status: 'ok',version: '1.2.3',- capabilities: { keyword_search: true, agentic_search: false },- disabled_features: ['agentic_search'],- cascade: { status: 'unhealthy' },+ capabilities: {},+ disabled_features: [],+ cascade: null,recorder: { status: 'active' },},};-const MANUAL_FAILURE: MemoryFailureLogEntry = {- id: 'ma_1111111111111111111111111111111111111111111111111111111111111111',- kind: 'result_unknown',- state: 'manual_required',- operation: 'flush',- occurred_at: '2026-08-08T12:01:00Z',- error_code: 'attachment_release_unknown',- attempts: 3,- generation: 7,- 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,+ status,failures: [],- recovery: null,- logSections: {- everos: { status: 'available', observed_at: '2026-08-08T12:00:00Z' },- capture: { status: 'stale', observed_at: '2026-08-08T11:00:00Z', reason: 'locked' },- calls: { status: 'unavailable', observed_at: null, reason: 'malformed' },- },+ clearInProgress: null,+ logSections: null,providerChecks: [],- providerChecksSource: {- status: 'available',- observed_at: '2026-08-08T12:00:00Z',- reason: null,- },+ providerChecksSource: null,statusLoading: false,failuresLoading: false,statusError: null,failuresError: null,refreshPending: false,- recoveryAction: null,onRefresh: vi.fn(),- onResumeClear: vi.fn(),- onAbortClear: vi.fn(),};-afterEach(() => {- cleanup();- vi.clearAllMocks();-});+afterEach(() => cleanup());describe('MemoryStatusPanel', () => {- it('renders runtime facts and every source without synthesizing a global state', () => {+ it('renders runtime facts without recovery actions', () => {render(<MemoryStatusPanel {...baseProps} />);-expect(screen.getByText('1.2.3')).toBeTruthy();- expect(screen.getByText('memory.processingRecord.runtime.healthStatus.ok')).toBeTruthy();- expect(screen.getByText('unhealthy')).toBeTruthy();- expect(screen.getByText('memory.processingRecord.sourceState.stale')).toBeTruthy();- expect(screen.getByText('memory.processingRecord.sourceState.unavailable')).toBeTruthy();- expect(screen.queryByText('memory.status.state.degraded')).toBeNull();- });-- it('gives each processing-record help trigger an action-oriented accessible name', () => {- render(<MemoryStatusPanel {...baseProps} />);-- for (const label of [- 'memory.processingRecord.runtime.helpLabel',- 'memory.processingRecord.runtime.capabilitiesHelpLabel',- 'memory.processingRecord.runtime.disabledFeaturesHelpLabel',- '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();-- rerender(<MemoryStatusPanel {...baseProps} repairSupported />);- expect(screen.getByRole('button', { name: 'memory.processingRecord.repair.action' })).toBeTruthy();- });-- it('places Repair beside the Cascade subsection', () => {- render(<MemoryStatusPanel {...baseProps} repairSupported />);-- const cascadeLabel = screen.getByText('memory.processingRecord.runtime.cascade');- const repairButton = screen.getByRole('button', { name: 'memory.processingRecord.repair.action' });- const cascadeHeader = cascadeLabel.parentElement?.parentElement;- const runtimeHeader = screen.getByText('memory.processingRecord.runtime.title').parentElement;-- expect(cascadeHeader?.contains(repairButton)).toBe(true);- expect(runtimeHeader?.contains(repairButton)).toBe(false);- });-- it('keeps Repair reachable when the processing health projection is unavailable', () => {- render(<MemoryStatusPanel {...baseProps} status={null} statusError="health failed" repairSupported />);- expect(screen.getByRole('button', { name: 'memory.processingRecord.repair.action' })).toBeTruthy();- });-- it('renders the Repair result when the processing health projection is unavailable', () => {- render(- <MemoryStatusPanel- {...baseProps}- status={null}- repairError="repair failed"- repairHealth={memoryCascadeHealth({ healthy: false, reasons: ['drain_failures'] })}- />,- );-- expect(screen.getByText('repair failed')).toBeTruthy();- expect(screen.getByText('memory.processingRecord.repair.completedWithWarnings')).toBeTruthy();- });-- it('blocks Repair while another Memory mutation owns the page', () => {- render(<MemoryStatusPanel {...baseProps} repairSupported mutationBusy />);- expect((screen.getByRole('button', { name: 'memory.processingRecord.repair.action' }) as HTMLButtonElement).disabled).toBe(true);- });-- it('blocks Clear recovery while Repair owns the page', () => {- render(- <MemoryStatusPanel- {...baseProps}- recovery={{ operation_id: 'clear-locked', state: 'recovery_needed', can_resume: true, can_abort: true }}- repairBusy- />,- );-- expect((screen.getByRole('button', { name: 'memory.processingRecord.clearRecovery.resume' }) as HTMLButtonElement).disabled).toBe(true);- expect((screen.getByRole('button', { name: 'memory.processingRecord.clearRecovery.abort' }) as HTMLButtonElement).disabled).toBe(true);- });-- it('shows the structured final health projection and running lock', () => {- const health = memoryCascadeHealth({- healthy: false,- reasons: ['drain_failures'],- pending: 1,- failed_retryable: 1,- drain_consecutive_failures: 2,- prune_stale_seconds: 60,- });- render(- <MemoryStatusPanel- {...baseProps}- repairSupported- repairBusy- repairHealth={health}- repairError="repair failed"- />,- );-- expect((screen.getByRole('button', { name: 'memory.processingRecord.repair.running' }) as HTMLButtonElement).disabled).toBe(true);- expect(screen.getByText('repair failed')).toBeTruthy();- expect(screen.getByText('memory.processingRecord.repair.completedWithWarnings')).toBeTruthy();- });-- it('preserves the Processing Record structure and responsive class contract', () => {- const { container } = render(- <MemoryStatusPanel- {...baseProps}- failures={[MANUAL_FAILURE]}- recovery={{ operation_id: 'clear-dom', state: 'prepared', can_resume: true, can_abort: true }}- />,- );-- expect(container.firstElementChild?.className).toBe('flex flex-col gap-5');- 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.- expect(- container.querySelector('#memory-sources-title')?.parentElement?.parentElement?.nextElementSibling?.className,- ).toBe('grid gap-2 sm:grid-cols-2 xl:grid-cols-4');- expect(screen.getByTestId('memory-anomaly-result_unknown').className).toBe(- 'flex min-w-0 flex-col gap-3 border-b border-border py-3 last:border-b-0 lg:flex-row lg:justify-between',- );+ expect(screen.queryByRole('button', { name: /resume|abort/i })).toBeNull();});- it('keeps source-independent anomalies visible when health cannot be read', () => {- render(- <MemoryStatusPanel- {...baseProps}- status={null}- statusError="health failed"- failures={[MANUAL_FAILURE]}- />,- );-- expect(screen.getByText('health failed')).toBeTruthy();- expect(screen.getByText('memory.status.failureLog.kind.result_unknown')).toBeTruthy();- expect(screen.getByText('memory.processingRecord.manualRequiredReadOnly')).toBeTruthy();- });-- it('renders manual_required as read-only without recovery commands', () => {- render(<MemoryStatusPanel {...baseProps} failures={[MANUAL_FAILURE]} />);-- expect(screen.getByText('memory.processingRecord.anomalyState.manualRequired')).toBeTruthy();- expect(screen.getByText('memory.processingRecord.anomalyOperation.flush')).toBeTruthy();- expect(screen.queryByRole('button', { name: 'memory.processingRecord.clearRecovery.resume' })).toBeNull();- expect(screen.queryByRole('button', { name: 'memory.processingRecord.clearRecovery.abort' })).toBeNull();- });-- it('renders concurrent duplicate-shaped anomalies under distinct backend IDs', () => {- const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);- const duplicateShape = {- ...MANUAL_FAILURE,- request_id: null,- occurred_at: '2026-08-08T12:01:00.000Z',+ it('renders a failed clear projection as read-only state', () => {+ const clearInProgress: MemoryClearInProgress = {+ state: 'failed',+ operation_id: 'op-1',+ occurred_at: '2026-08-13T00:00:00Z',+ error_code: 'memory_clear_failed',};-- render(- <MemoryStatusPanel- {...baseProps}- failures={[- duplicateShape,- {- ...duplicateShape,- id: 'ma_2222222222222222222222222222222222222222222222222222222222222222',- },- ]}- />,- );-- expect(screen.getAllByTestId('memory-anomaly-result_unknown')).toHaveLength(2);- expect(consoleError.mock.calls.flat().join(' ')).not.toContain(- 'Encountered two children with the same key',- );- consoleError.mockRestore();- });-- it('offers distinct resume and abort commands for clear recovery', async () => {- const onResumeClear = vi.fn();- const onAbortClear = vi.fn();- const user = userEvent.setup();- render(- <MemoryStatusPanel- {...baseProps}- recovery={{ operation_id: 'clear-42', state: 'recovery_needed', can_resume: true, can_abort: true }}- onResumeClear={onResumeClear}- onAbortClear={onAbortClear}- />,- );-- await user.click(screen.getByRole('button', { name: 'memory.processingRecord.clearRecovery.resume' }));- await user.click(screen.getByRole('button', { name: 'memory.processingRecord.clearRecovery.abort' }));-- expect(onResumeClear).toHaveBeenCalledWith('clear-42');- expect(onAbortClear).toHaveBeenCalledWith('clear-42');- });-- it.each([- ['memory_clear_failed', 'errors.memory_clear_failed'],- ['future_clear_error', 'future_clear_error'],- ])('renders the Clear recovery error %s safely', (errorCode, expectedLabel) => {- render(- <MemoryStatusPanel- {...baseProps}- recovery={{- operation_id: `clear-${errorCode}`,- state: 'recovery_needed',- can_resume: true,- can_abort: false,- error_code: errorCode,- }}- />,- );-- expect(screen.getByText(expectedLabel)).toBeTruthy();- });-- it('keeps abort unavailable until the journal verifies a complete snapshot', async () => {- const onAbortClear = vi.fn();- const user = userEvent.setup();- render(- <MemoryStatusPanel- {...baseProps}- recovery={{ operation_id: 'clear-incomplete', state: 'recovery_needed', can_resume: true, can_abort: false }}- onAbortClear={onAbortClear}- />,- );-- const resume = screen.getByRole('button', { name: 'memory.processingRecord.clearRecovery.resume' });- const abort = screen.getByRole('button', { name: 'memory.processingRecord.clearRecovery.abort' });- expect((resume as HTMLButtonElement).disabled).toBe(false);- expect((abort as HTMLButtonElement).disabled).toBe(true);- expect(screen.getByText('memory.processingRecord.clearRecovery.abortUnavailable')).toBeTruthy();-- await user.click(abort);- expect(onAbortClear).not.toHaveBeenCalled();- });-- it('keeps resume unavailable after the journal commits to abort', async () => {- const onResumeClear = vi.fn();- const user = userEvent.setup();- const recovery = {- operation_id: 'clear-aborting',- state: 'recovery_needed',- can_resume: false,- can_abort: true,- } satisfies MemoryClearRecovery;- render(- <MemoryStatusPanel- {...baseProps}- recovery={recovery}- onResumeClear={onResumeClear}- />,- );-- const resume = screen.getByRole('button', { name: 'memory.processingRecord.clearRecovery.resume' });- expect((resume as HTMLButtonElement).disabled).toBe(true);-- await user.click(resume);- expect(onResumeClear).not.toHaveBeenCalled();+ render(<MemoryStatusPanel {...baseProps} clearInProgress={clearInProgress} />);+ expect(screen.getByText('op-1')).toBeTruthy();+ expect(screen.queryByRole('button', { name: /resume|abort/i })).toBeNull();});});diff --git a/ui/src/components/settings/memory/MemoryStatusPanel.tsx b/ui/src/components/settings/memory/MemoryStatusPanel.tsxindex 5a32ef5db..2ac8f9774 100644--- a/ui/src/components/settings/memory/MemoryStatusPanel.tsx+++ b/ui/src/components/settings/memory/MemoryStatusPanel.tsx@@ -7,9 +7,6 @@ import {Database,Loader2,RefreshCw,- RotateCcw,- ShieldAlert,- XCircle,} from 'lucide-react';import { Badge } from '../../ui/badge';@@ -18,7 +15,7 @@ import { Card, CardContent } from '../../ui/card';import { ConfirmDialog } from '../../ui/confirm-dialog';import { InfoHint } from '../../ui/info-hint';import type {- MemoryClearRecovery,+ MemoryClearInProgress,MemoryFailureLogEntry,MemoryLogSections,MemoryLogSourceStatus,@@ -32,7 +29,6 @@ import {formatMemoryStatusRuntimeFact,formatMemoryStatusTimestamp,memoryStatusAnomalyLabel,- memoryStatusClearRecoveryStateLabel,memoryStatusHealthLabel,memoryStatusRuntimeFactLabel,memoryStatusSourceBadgeVariant,@@ -44,12 +40,12 @@ import {} from './memoryStatusPresentation';const FactList: React.FC<{- facts: Record<string, unknown>;+ facts: Record<string, unknown> | null | undefined;emptyLabel: string;group: RuntimeFactGroup;}> = ({ facts, emptyLabel, group }) => {const { t } = useTranslation();- const entries = Object.entries(facts);+ const entries = Object.entries(facts ?? {});if (entries.length === 0) return <span className="text-[11.5px] text-muted">{emptyLabel}</span>;return (<dl className="grid min-w-0 gap-x-4 gap-y-2 text-[11.5px] sm:grid-cols-2">@@ -147,66 +143,43 @@ const FailureRow: React.FC<{ entry: MemoryFailureLogEntry }> = ({ entry }) => {);};-const ClearRecoveryCard: React.FC<{- recovery: MemoryClearRecovery;- action: 'resume' | 'abort' | null;- mutationBusy: boolean;- onResume: (operationId: string) => void;- onAbort: (operationId: string) => void;-}> = ({ recovery, action, mutationBusy, onResume, onAbort }) => {+const ClearInProgressCard: React.FC<{+ clearInProgress: MemoryClearInProgress;+}> = ({ clearInProgress }) => {const { t } = useTranslation();return (<div className="flex flex-col gap-3 rounded-md border border-gold/40 bg-gold/[0.06] px-4 py-3"><div className="flex min-w-0 items-start gap-2.5">- <ShieldAlert className="mt-0.5 size-4 shrink-0 text-gold" />+ <Clock3 className="mt-0.5 size-4 shrink-0 text-gold" /><div className="min-w-0">- <div className="text-[12.5px] font-semibold text-foreground">{t('memory.processingRecord.clearRecovery.title')}</div>- <div className="mt-0.5 text-[11px] text-muted">{t('memory.processingRecord.clearRecovery.description')}</div>+ <div className="text-[12.5px] font-semibold text-foreground">{t('memory.processingRecord.clearInProgress.title')}</div>+ <div className="mt-0.5 text-[11px] text-muted">+ {t(+ clearInProgress.state === 'failed'+ ? 'memory.processingRecord.clearInProgress.explicitRetryDescription'+ : 'memory.processingRecord.clearInProgress.description',+ )}+ </div></div></div><div className="grid min-w-0 gap-1.5 text-[11px] sm:grid-cols-2">- <Field label={t('memory.processingRecord.field.operationId')} value={recovery.operation_id} />+ <Field label={t('memory.processingRecord.field.operationId')} value={clearInProgress.operation_id} /><Fieldlabel={t('memory.processingRecord.field.state')}- value={memoryStatusClearRecoveryStateLabel(t, recovery.state)}+ value={clearInProgress.state === 'failed'+ ? t('memory.processingRecord.clearInProgress.failed')+ : t('memory.processingRecord.clearInProgress.deleting')}/>- {recovery.occurred_at ? (- <Field label={t('memory.processingRecord.field.occurredAt')} value={formatMemoryStatusTimestamp(recovery.occurred_at)} />+ {clearInProgress.occurred_at ? (+ <Field label={t('memory.processingRecord.field.occurredAt')} value={formatMemoryStatusTimestamp(clearInProgress.occurred_at)} />) : null}- {recovery.error_code ? (+ {clearInProgress.error_code ? (<Fieldlabel={t('memory.processingRecord.field.errorCode')}- value={memoryErrorMessage(t, recovery.error_code)}+ value={memoryErrorMessage(t, clearInProgress.error_code)}/>) : null}</div>- <div className="grid gap-1.5">- <div className="flex flex-wrap gap-2">- <Button- size="xs"- variant="secondary"- disabled={mutationBusy || action !== null || !recovery.can_resume}- onClick={() => onResume(recovery.operation_id)}- >- {action === 'resume' ? <Loader2 className="animate-spin" /> : <RotateCcw />}- {t('memory.processingRecord.clearRecovery.resume')}- </Button>- <Button- size="xs"- variant="destructive"- disabled={mutationBusy || action !== null || !recovery.can_abort}- onClick={() => onAbort(recovery.operation_id)}- >- {action === 'abort' ? <Loader2 className="animate-spin" /> : <XCircle />}- {t('memory.processingRecord.clearRecovery.abort')}- </Button>- </div>- {!recovery.can_abort ? (- <div className="text-[11px] text-muted">- {t('memory.processingRecord.clearRecovery.abortUnavailable')}- </div>- ) : null}- </div></div>);};@@ -214,7 +187,7 @@ const ClearRecoveryCard: React.FC<{export const MemoryStatusPanel: React.FC<{status: MemoryStatus | null;failures: MemoryFailureLogEntry[];- recovery: MemoryClearRecovery | null;+ clearInProgress: MemoryClearInProgress | null;logSections: MemoryLogSections | null;providerChecks: MemoryProviderCall[];providerChecksSource: MemoryLogSourceStatus | null;@@ -223,10 +196,7 @@ export const MemoryStatusPanel: React.FC<{statusError: string | null;failuresError: string | null;refreshPending: boolean;- recoveryAction: 'resume' | 'abort' | null;onRefresh: () => void;- onResumeClear: (operationId: string) => void;- onAbortClear: (operationId: string) => void;repairSupported?: boolean;repairBusy?: boolean;mutationBusy?: boolean;@@ -236,7 +206,7 @@ export const MemoryStatusPanel: React.FC<{}> = ({status,failures,- recovery,+ clearInProgress,logSections,providerChecks = [],providerChecksSource = null,@@ -245,10 +215,7 @@ export const MemoryStatusPanel: React.FC<{statusError,failuresError,refreshPending,- recoveryAction,onRefresh,- onResumeClear,- onAbortClear,repairSupported = false,repairBusy = false,mutationBusy = false,@@ -484,14 +451,8 @@ export const MemoryStatusPanel: React.FC<{</div><p className="mt-0.5 text-[11.5px] text-muted">{t('memory.processingRecord.anomalies.description')}</p></div>- {recovery ? (- <ClearRecoveryCard- recovery={recovery}- action={recoveryAction}- mutationBusy={repairBusy || mutationBusy}- onResume={onResumeClear}- onAbort={onAbortClear}- />+ {clearInProgress ? (+ <ClearInProgressCard clearInProgress={clearInProgress} />) : null}<Card><CardContent className="py-2">diff --git a/ui/src/components/settings/memory/memoryStatusPresentation.test.ts b/ui/src/components/settings/memory/memoryStatusPresentation.test.tsindex 9584b7936..03c1f14f1 100644--- a/ui/src/components/settings/memory/memoryStatusPresentation.test.ts+++ b/ui/src/components/settings/memory/memoryStatusPresentation.test.ts@@ -2,141 +2,27 @@ import type { TFunction } from 'i18next';import { describe, expect, it } from 'vitest';import {- formatMemoryStatusFact,- formatMemoryStatusRuntimeFact,- formatMemoryStatusTimestamp,- memoryStatusAnomalyLabel,- memoryStatusClearRecoveryStateLabel,memoryStatusHealthLabel,- memoryStatusRuntimeFactLabel,- memoryStatusSourceBadgeVariant,- memoryStatusSourceDisplayState,memoryStatusSourceReasonLabel,+ memoryStatusSourceDisplayState,memoryStatusSourceStateLabel,- type SourceState,} from './memoryStatusPresentation';const t = ((key: string) => key) as TFunction;-describe('memory status source presentation', () => {- it.each(['available', 'partial', 'stale'] as const)(- 'downgrades unobserved %s evidence to unknown',- (status) => {- expect(memoryStatusSourceDisplayState({ status, observed_at: null })).toBe('unknown');- },- );-- it('preserves observed and explicitly unavailable source states', () => {- expect(memoryStatusSourceDisplayState({ status: 'partial', observed_at: '2026-08-08T12:00:00Z' })).toBe('partial');- expect(memoryStatusSourceDisplayState({ status: 'unavailable', observed_at: null })).toBe('unavailable');- expect(memoryStatusSourceStateLabel(t, 'stale')).toBe('memory.processingRecord.sourceState.stale');- });-- it.each<[SourceState, string]>([- ['available', 'success'],- ['partial', 'warning'],- ['stale', 'warning'],- ['unknown', 'secondary'],- ['unavailable', 'destructive'],- ])('uses the %s source badge variant %s', (status, variant) => {- expect(memoryStatusSourceBadgeVariant(status)).toBe(variant);- });-- it.each([- ['memory_sidecar_unavailable', 'errors.memory_sidecar_unavailable'],- ['missing', 'memory.log.reason.missing'],- ['runs_busy', 'memory.log.reason.runsBusy'],- ['future_source_reason', 'future_source_reason'],- ])('maps source reason %s to %s', (reason, expected) => {- expect(memoryStatusSourceReasonLabel(t, reason)).toBe(expected);- });-});--describe('memory status enum labels', () => {- it.each([- ['kind', 'boot_recovery', 'memory.status.failureLog.kind.boot_recovery'],- ['state', 'manual_required', 'memory.processingRecord.anomalyState.manualRequired'],- ['operation', 'flush', 'memory.processingRecord.anomalyOperation.flush'],- ['kind', 'future_kind', 'future_kind'],- ['state', 'future_state', 'future_state'],- ['operation', 'future_operation', 'future_operation'],- ] as const)('maps anomaly %s value %s to %s', (group, value, expected) => {- expect(memoryStatusAnomalyLabel(t, group, value)).toBe(expected);- });-- it.each([- ['preparing', 'memory.processingRecord.clearRecovery.state.preparing'],- ['prepared', 'memory.processingRecord.clearRecovery.state.prepared'],- ['deleting', 'memory.processingRecord.clearRecovery.state.deleting'],- ['recovery_needed', 'memory.processingRecord.clearRecovery.state.recoveryNeeded'],- ['future_state', 'future_state'],- ])('maps clear recovery state %s to %s', (state, expected) => {- expect(memoryStatusClearRecoveryStateLabel(t, state)).toBe(expected);- });-- it.each([- ['ok', 'memory.processingRecord.runtime.healthStatus.ok'],- ['future_health_state', 'future_health_state'],- ])('maps provider health %s to %s', (health, expected) => {- expect(memoryStatusHealthLabel(t, health)).toBe(expected);- });-});--describe('memory status runtime facts', () => {- it.each([- ['capability', 'embed', 'memory.processingRecord.runtime.fact.capability.embed'],- ['cascade', 'prune_stale_seconds', 'memory.processingRecord.runtime.fact.cascade.pruneStaleSeconds'],- ['recorder', 'state', 'memory.processingRecord.runtime.fact.recorder.state'],- ['capability', 'future_capability', 'future_capability'],- ['cascade', 'future_counter', 'future_counter'],- ['recorder', 'future_field', 'future_field'],- ] as const)('maps %s fact label %s to %s', (group, name, expected) => {- expect(memoryStatusRuntimeFactLabel(t, group, name)).toBe(expected);+describe('memory status presentation', () => {+ it('downgrades unobserved source evidence to unknown', () => {+ expect(memoryStatusSourceDisplayState({ status: 'available', observed_at: null })).toBe('unknown');});- it('localizes known fact values and preserves future diagnostics', () => {- expect(formatMemoryStatusRuntimeFact(t, 'capability', 'embed', false)).toBe(- 'memory.processingRecord.runtime.fact.boolean.false',- );- expect(formatMemoryStatusRuntimeFact(t, 'cascade', 'reasons', ['drain_failures', 'future_reason', 7])).toBe(- 'memory.processingRecord.runtime.fact.cascadeReason.drainFailures, future_reason, 7',- );- expect(formatMemoryStatusRuntimeFact(t, 'recorder', 'state', 'degraded')).toBe(- 'memory.processingRecord.runtime.fact.recorderState.degraded',- );- expect(formatMemoryStatusRuntimeFact(t, 'recorder', 'reason', 'call_log_corrupt')).toBe(- 'memory.processingRecord.runtime.fact.recorderReason.callLogCorrupt',- );- expect(formatMemoryStatusRuntimeFact(t, 'recorder', 'state', 'future_state')).toBe('future_state');- expect(formatMemoryStatusRuntimeFact(t, 'cascade', 'future_counter', 12)).toBe('12');- });-});--describe('memory status formatting', () => {- it('formats null, invalid, and valid timestamps without inventing data', () => {- const valid = '2026-08-08T12:00:00Z';- expect(formatMemoryStatusTimestamp(null)).toBe('-');- expect(formatMemoryStatusTimestamp(undefined)).toBe('-');- expect(formatMemoryStatusTimestamp('not-a-timestamp')).toBe('not-a-timestamp');- expect(formatMemoryStatusTimestamp(valid)).toBe(new Date(valid).toLocaleString());- });-- it.each([- [null, '-'],- [undefined, '-'],- [true, 'true'],- [false, 'false'],- ['diagnostic', 'diagnostic'],- [42, '42'],- [{ answer: 42 }, '{"answer":42}'],- [[1, 'two'], '[1,"two"]'],- ])('serializes fact value %j as %s', (value, expected) => {- expect(formatMemoryStatusFact(value)).toBe(expected);+ it('keeps observed source states and health labels', () => {+ expect(memoryStatusSourceDisplayState({ status: 'unavailable', observed_at: null })).toBe('unavailable');+ expect(memoryStatusSourceStateLabel(t, 'stale')).toContain('sourceState.stale');+ expect(memoryStatusHealthLabel(t, 'ok')).toContain('healthStatus.ok');});- it('falls back when a fact cannot be serialized', () => {- const circular: Record<string, unknown> = {};- circular.self = circular;- expect(formatMemoryStatusFact(circular)).toBe('-');+ it('localizes legacy rerun source reasons through memory errors', () => {+ expect(memoryStatusSourceReasonLabel(t, 'memory_clear_legacy_state_requires_rerun'))+ .toContain('errors.memory_clear_legacy_state_requires_rerun');});});diff --git a/ui/src/components/settings/memory/memoryStatusPresentation.ts b/ui/src/components/settings/memory/memoryStatusPresentation.tsindex 75ce14080..2850ff9f4 100644--- a/ui/src/components/settings/memory/memoryStatusPresentation.ts+++ b/ui/src/components/settings/memory/memoryStatusPresentation.ts@@ -39,12 +39,6 @@ const ANOMALY_LABEL_KEYS = {},} as const;-const CLEAR_RECOVERY_STATE_LABEL_KEYS = {- preparing: 'memory.processingRecord.clearRecovery.state.preparing',- prepared: 'memory.processingRecord.clearRecovery.state.prepared',- deleting: 'memory.processingRecord.clearRecovery.state.deleting',- recovery_needed: 'memory.processingRecord.clearRecovery.state.recoveryNeeded',-} as const;const HEALTH_STATUS_LABEL_KEYS = {ok: 'memory.processingRecord.runtime.healthStatus.ok',@@ -60,6 +54,7 @@ const MEMORY_SOURCE_ERROR_REASONS = new Set(['memory_provider_response_invalid','memory_processing_failed','memory_clear_failed',+ 'memory_clear_legacy_state_requires_rerun','memory_restart_failed',]);@@ -135,10 +130,6 @@ export const memoryStatusAnomalyLabel = (value: string,): string => knownLabel(t, ANOMALY_LABEL_KEYS[group] as Record<string, string>, value);-export const memoryStatusClearRecoveryStateLabel = (t: TFunction, value: string): string => (- knownLabel(t, CLEAR_RECOVERY_STATE_LABEL_KEYS, value)-);-export const memoryStatusHealthLabel = (t: TFunction, value: string): string => (knownLabel(t, HEALTH_STATUS_LABEL_KEYS, value));diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 396f0a7ef..7219c6c3f 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -570,8 +570,6 @@ export type ApiContextType = {getMemoryLog: (cursor?: string | null, limit?: number) => Promise<MemoryLogListResult>;getMemoryLogEntry: (memcellId: string) => Promise<MemoryLogDetailResult>;clearMemory: () => Promise<MemoryClearResult>;- resumeMemoryClear: (operationId: string) => Promise<MemoryClearRecoveryResult>;- abortMemoryClear: (operationId: string) => Promise<MemoryClearRecoveryResult>;factoryResetMemory: () => Promise<MemoryFactoryResetResult>;restartMemoryRuntime: () => Promise<MemoryRuntimeRestartResult>;rebuildMemoryRuntime: () => Promise<MemoryRuntimeRebuildResult>;@@ -1904,8 +1902,8 @@ export type MemoryStatus = {version: string | null;capabilities: Record<string, unknown>;disabled_features: string[];- cascade: Record<string, unknown>;- recorder: Record<string, unknown>;+ cascade: Record<string, unknown> | null;+ recorder: Record<string, unknown> | null;};};@@ -1925,11 +1923,9 @@ export type MemoryFailureLogEntry = {request_id: string | null;};-export type MemoryClearRecovery = {+export type MemoryClearInProgress = {operation_id: string;- state: string;- can_resume: boolean;- can_abort: boolean;+ state: 'deleting' | 'failed';occurred_at?: string | null;error_code?: string | null;};@@ -1937,7 +1933,7 @@ export type MemoryClearRecovery = {export type MemoryFailureLog = {status: 'ok';items: MemoryFailureLogEntry[];- recovery: MemoryClearRecovery | null;+ clear_in_progress?: MemoryClearInProgress;};export type MemoryFailureLogResult =@@ -1949,7 +1945,7 @@ export type MemoryMaintenance = {status: 'ok';data_exists: boolean;can_clear: boolean;- clear_recovery: MemoryClearRecovery | null;+ clear_in_progress: MemoryClearInProgress | null;};export type MemoryMaintenanceResult = MemoryMaintenance | MemoryFailure | { error: string };@@ -1969,7 +1965,7 @@ export type MemoryProcessingRecordSummary = {source: MemoryLogSourceStatus;data_exists: boolean;can_clear: boolean;- clear_recovery: MemoryClearRecovery | null;+ clear_in_progress: MemoryClearInProgress | null;};provider_checks?: {source: MemoryLogSourceStatus;@@ -2127,11 +2123,7 @@ export type MemoryLogDetailResult =export type MemoryClearResult =| { status: 'completed'; operation_id: string; epoch: number }- | (MemoryFailure & { recovery?: MemoryClearRecovery | null });--export type MemoryClearRecoveryResult =- | { status: 'completed' | 'aborted'; operation_id: string }- | MemoryFailure;+ | (MemoryFailure & { clear_in_progress?: MemoryClearInProgress | null });// Reconciliation answers the controller's ok/error shape rather than the// status/error one the read routes use.@@ -3344,10 +3336,6 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrengetMemoryLogEntry: (memcellId) =>getJson(`/api/memory/log/entry?memcell_id=${encodeURIComponent(memcellId)}`, { handleError: false }),clearMemory: () => postJson('/api/memory/clear', { confirm: true }, { handleError: false }),- resumeMemoryClear: (operationId) =>- postJson('/api/memory/clear/resume', { operation_id: operationId }, { handleError: false }),- abortMemoryClear: (operationId) =>- postJson('/api/memory/clear/abort', { operation_id: operationId }, { handleError: false }),factoryResetMemory: async () => parseMemoryFactoryResetResult(await postJson('/api/memory/runtime/factory-reset', { confirm: true }, { handleError: false }),),diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 2c82729c4..9422424e9 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1591,6 +1591,8 @@"memory_provider_response_invalid": "Memory returned an invalid response.","memory_processing_failed": "Memory processing failed.","memory_clear_failed": "Clearing Memory data failed.",+ "memory_clear_marker_unreadable": "Memory Clear state could not be read. Run Clear again to repair it.",+ "memory_clear_legacy_state_requires_rerun": "An older Memory Clear state needs to be replaced. Run Clear again to continue.","memory_restart_failed": "Restarting the Memory engine failed.","memory_runtime_unpublished": "This Avibe version hasn't published a memory runtime yet.","memory_runtime_manifest_missing": "The memory runtime manifest is missing.",@@ -4205,21 +4207,12 @@"generation": "Data version","requestId": "Request ID"},- "clearRecovery": {- "title": "An unfinished Clear needs your decision",- "description": "The last Clear was interrupted. You can finish the deletion, or abort and restore everything to how it was before.",- "state": {- "preparing": "Preparing snapshot",- "prepared": "Snapshot prepared",- "deleting": "Deleting Memory data",- "recoveryNeeded": "Recovery required"- },- "resume": "Resume Clear",- "abort": "Abort and restore",- "abortUnavailable": "Abort is unavailable until the initial snapshot is complete.",- "resumeSuccess": "Clear resumed and completed.",- "abortSuccess": "Clear aborted and the snapshot was restored.",- "actionFailed": "Couldn't update Clear recovery.",+ "clearInProgress": {+ "title": "Clear Memory Data is in progress",+ "description": "Memory remains fenced while the deletion completes automatically.",+ "explicitRetryDescription": "Clear did not finish automatically. Run Clear Memory Data again to retry or replace the failed operation.",+ "deleting": "Deleting Memory data",+ "failed": "Clear needs another attempt","loadFailed": "Couldn't load Clear maintenance state."},"timeline": {diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 2e22f47bd..03324832c 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1591,6 +1591,8 @@"memory_provider_response_invalid": "记忆返回了无效的响应。","memory_processing_failed": "记忆处理失败。","memory_clear_failed": "清除记忆数据失败。",+ "memory_clear_marker_unreadable": "无法读取记忆清除状态。请再次执行清除以修复。",+ "memory_clear_legacy_state_requires_rerun": "旧版记忆清除状态需要替换。请再次执行清除以继续。","memory_restart_failed": "重启记忆引擎失败。","memory_runtime_unpublished": "当前 Avibe 版本尚未发布记忆运行时。","memory_runtime_manifest_missing": "记忆运行时的清单缺失。",@@ -4205,21 +4207,12 @@"generation": "数据版本","requestId": "请求 ID"},- "clearRecovery": {- "title": "有一次未完成的清除操作",- "description": "上次清除中途被打断。你可以继续完成删除,或中止并恢复到清除前的状态。",- "state": {- "preparing": "正在准备快照",- "prepared": "快照已准备完成",- "deleting": "正在删除记忆数据",- "recoveryNeeded": "需要恢复处理"- },- "resume": "继续清除",- "abort": "中止并恢复",- "abortUnavailable": "初始快照完整后才能中止并恢复。",- "resumeSuccess": "清除操作已继续并完成。",- "abortSuccess": "清除操作已中止,快照已恢复。",- "actionFailed": "无法更新清除恢复状态。",+ "clearInProgress": {+ "title": "正在清除记忆数据",+ "description": "删除完成前,Memory 会保持隔离;操作会自动继续。",+ "explicitRetryDescription": "清除操作未能自动完成。请再次执行清除记忆数据,以重试或替换失败的操作。",+ "deleting": "正在删除记忆数据",+ "failed": "需要再次尝试清除","loadFailed": "无法加载清除维护状态。"},"timeline": {diff --git a/vibe/internal_client.py b/vibe/internal_client.pyindex ee20e3448..cafa71e4d 100644--- a/vibe/internal_client.py+++ b/vibe/internal_client.py@@ -976,26 +976,6 @@ async def memory_clear()-async def memory_clear_recovery(- operation_id: str,- *,- action: str,- user_key: str,- socket_path: Optional[Path] = None,-) -> dict[str, Any]:- if action not in {"resume", "abort"}:- raise ValueError("invalid Memory clear recovery action")- path = f"/internal/memory/clear/{action}"- return await _memory_request(- "POST",- path,- payload={"operation_id": operation_id},- headers=_memory_user_key_headers("POST", path, user_key),- socket_path=socket_path,- timeout=None,- )--def memory_status_sync(*,caller_session_id: str | None = None,diff --git a/vibe/ui_memory_routes.py b/vibe/ui_memory_routes.pyindex bb51fbea4..7f3479737 100644--- a/vibe/ui_memory_routes.py+++ b/vibe/ui_memory_routes.py@@ -1261,60 +1261,3 @@ def register_memory_routes(app) -> None:)return await app.dispatch_native_request(starlette_request, handler)-- async def memory_clear_recovery_response(- starlette_request: FastAPIRequest,- *,- action: str,- ) -> Response:- user_key = _memory_ui_user_key()- if user_key is None:- return _memory_forbidden_response()- try:- payload = await starlette_request.json()- except Exception:- payload = None- if (- not isinstance(payload, dict)- or set(payload) != {"operation_id"}- or not isinstance(payload.get("operation_id"), str)- or not 1 <= len(payload["operation_id"]) <= 128- ):- return _memory_response(- {"status": "failed", "error": "memory_invalid_input"},- status_code=400,- )- if _memory_mutation_request_running() or _memory_factory_reset_request_running():- return _memory_response(- {"status": "failed", "error": "memory_operation_in_progress"},- status_code=409,- )- from vibe import internal_client-- return await _memory_internal_response(- lambda: internal_client.memory_clear_recovery(- payload["operation_id"],- action=action,- user_key=user_key,- )- )-- @app.post("/api/memory/clear/resume", include_in_schema=False)- async def memory_clear_resume_post(starlette_request: FastAPIRequest):- async def handler():- return await memory_clear_recovery_response(- starlette_request,- action="resume",- )-- return await app.dispatch_native_request(starlette_request, handler)-- @app.post("/api/memory/clear/abort", include_in_schema=False)- async def memory_clear_abort_post(starlette_request: FastAPIRequest):- async def handler():- return await memory_clear_recovery_response(- starlette_request,- action="abort",- )-- return await app.dispatch_native_request(starlette_request, handler)