Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

feat(memory): add processed episode listing core (#1437)

rkrkrkkff6743ef7e2b
diff --git a/core/memory/__init__.py b/core/memory/__init__.py
index 637d7022c..f7cb6f157 100644
--- a/core/memory/__init__.py
+++ b/core/memory/__init__.py
@@ -12,6 +12,9 @@ from core.memory.types import (
MemoryItem,
MemoryItems,
MemoryKind,
+ MemoryListItem,
+ MemoryListPage,
+ MemoryListResult,
MemoryProfile,
MemoryProfileExplicitInfo,
MemoryProfileTrait,
@@ -35,6 +38,9 @@ __all__ = [
"MemoryItem",
"MemoryItems",
"MemoryKind",
+ "MemoryListItem",
+ "MemoryListPage",
+ "MemoryListResult",
"MemoryModule",
"MemoryProfile",
"MemoryProfileExplicitInfo",
diff --git a/core/memory/everos.py b/core/memory/everos.py
index cc2b43cd3..76d231c31 100644
--- a/core/memory/everos.py
+++ b/core/memory/everos.py
@@ -21,6 +21,8 @@ from core.memory.types import (
CaptureAttachment,
MemoryErrorCode,
MemoryItem,
+ MemoryListItem,
+ MemoryListPage,
MemoryProfile,
MemoryProfileExplicitInfo,
MemoryProfileTrait,
@@ -58,6 +60,8 @@ _PROCESSING_TIMEOUT_SECONDS = 8.0
_PREFLIGHT_TIMEOUT_SECONDS = 5.0
_PREFLIGHT_RESPONSE_BYTES = _MAX_RESPONSE_BYTES
_PROFILE_QUERY = "profile"
+_MAX_LIST_PAGE_SIZE = 20
+_EVEROS_EXACT_SORT_WINDOW = 20_000
_MAX_PROFILE_TIMESTAMP_MS = 4_102_444_800_000
_RECORDER_HEALTH_FALLBACK = {"state": "degraded", "reason": "writer_failures"}
_RECORDER_HEALTH_REASONS = {
@@ -461,6 +465,47 @@ class EverOSPort:
# principal, and a field here is whichever concurrent read finished last.
return () if profile is None else (profile,)
+ async def list_episodes(
+ self,
+ principal_id: str,
+ project_id: str,
+ page: int,
+ page_size: int,
+ ) -> MemoryListPage:
+ """Return one strictly projected EverOS episode page."""
+
+ if (
+ isinstance(page, bool)
+ or not isinstance(page, int)
+ or page < 1
+ or isinstance(page_size, bool)
+ or not isinstance(page_size, int)
+ or not 1 <= page_size <= _MAX_LIST_PAGE_SIZE
+ ):
+ raise MemoryProviderFailure("memory_invalid_input", retryable=False)
+ body = await self._sidecar_request(
+ "POST",
+ "/api/v2/memory/get",
+ {
+ "user_id": principal_id,
+ "app_id": _APP_ID,
+ "project_id": project_id,
+ "memory_type": "episode",
+ "page": page,
+ "page_size": page_size,
+ "sort_by": "timestamp",
+ "sort_order": "desc",
+ },
+ require_json=True,
+ )
+ return _map_episode_page(
+ body,
+ principal_id=principal_id,
+ project_id=project_id,
+ page=page,
+ page_size=page_size,
+ )
+
async def health(self) -> bool:
try:
await self.health_snapshot()
@@ -1027,6 +1072,144 @@ def _map_search_items(
return tuple(items)
+def _map_episode_page(
+ body: dict[str, Any] | None,
+ *,
+ principal_id: str,
+ project_id: str,
+ page: int,
+ page_size: int,
+) -> MemoryListPage:
+ """Validate the pinned EverOS `/get` envelope before projection."""
+
+ if not isinstance(body, dict) or set(body) != {"request_id", "data"}:
+ raise MemoryProviderFailure("memory_provider_response_invalid")
+ request_id = _strict_receipt_id(body.get("request_id"))
+ data = body.get("data")
+ data_keys = {
+ "episodes",
+ "profiles",
+ "agent_cases",
+ "agent_skills",
+ "total_count",
+ "count",
+ }
+ if (
+ not request_id
+ or not isinstance(data, dict)
+ or set(data) != data_keys
+ or not _is_bounded_json_value(data)
+ ):
+ raise MemoryProviderFailure("memory_provider_response_invalid")
+ episodes = data.get("episodes")
+ total_count = data.get("total_count")
+ count = data.get("count")
+ if (
+ not isinstance(episodes, list)
+ or len(episodes) > page_size
+ or any(data.get(key) != [] for key in ("profiles", "agent_cases", "agent_skills"))
+ or isinstance(total_count, bool)
+ or not isinstance(total_count, int)
+ or total_count < 0
+ or isinstance(count, bool)
+ or not isinstance(count, int)
+ or count != len(episodes)
+ or total_count < count
+ or count != min(
+ page_size,
+ max(total_count - (page - 1) * page_size, 0),
+ )
+ ):
+ raise MemoryProviderFailure("memory_provider_response_invalid")
+
+ items = tuple(
+ _map_list_episode(
+ episode,
+ principal_id=principal_id,
+ project_id=project_id,
+ )
+ for episode in episodes
+ )
+ if len({item.id for item in items}) != len(items):
+ raise MemoryProviderFailure("memory_provider_response_invalid")
+ timestamps = tuple(
+ datetime.fromisoformat(item.timestamp.replace("Z", "+00:00"))
+ for item in items
+ )
+ if any(
+ next_timestamp > timestamp
+ for timestamp, next_timestamp in zip(timestamps, timestamps[1:])
+ ):
+ raise MemoryProviderFailure("memory_provider_response_invalid")
+ warnings = (
+ ("memory_list_truncated",)
+ if total_count > _EVEROS_EXACT_SORT_WINDOW
+ else ()
+ )
+ return MemoryListPage(
+ items=items,
+ page=page,
+ page_size=page_size,
+ count=count,
+ total_count=total_count,
+ warnings=warnings,
+ )
+
+
+def _map_list_episode(
+ value: Any,
+ *,
+ principal_id: str,
+ project_id: str,
+) -> MemoryListItem:
+ item_keys = {
+ "id",
+ "user_id",
+ "app_id",
+ "project_id",
+ "session_id",
+ "timestamp",
+ "sender_ids",
+ "summary",
+ "subject",
+ "episode",
+ "type",
+ }
+ if not isinstance(value, dict) or set(value) != item_keys:
+ raise MemoryProviderFailure("memory_provider_response_invalid")
+ item_id = _strict_receipt_id(value.get("id"))
+ session_id = _strict_receipt_id(value.get("session_id"))
+ sender_ids = value.get("sender_ids")
+ subject = _safe_list_text(value.get("subject"), allow_empty=True)
+ summary = _safe_list_text(value.get("summary"), allow_empty=True)
+ episode = _safe_list_text(value.get("episode"), allow_empty=False)
+ timestamp = _record_timestamp(value.get("timestamp"))
+ if (
+ not item_id
+ or not session_id
+ or value.get("user_id") != principal_id
+ or value.get("app_id") != _APP_ID
+ or value.get("project_id") != project_id
+ or value.get("type") != "Conversation"
+ or not isinstance(sender_ids, list)
+ or len(sender_ids) > _MAX_RESPONSE_COLLECTION
+ or any(not _strict_receipt_id(sender_id) for sender_id in sender_ids)
+ or subject is None
+ or summary is None
+ or episode is None
+ or timestamp is None
+ ):
+ raise MemoryProviderFailure("memory_provider_response_invalid")
+ return MemoryListItem(
+ id=item_id,
+ subject=subject,
+ summary=summary,
+ body=episode,
+ timestamp=timestamp,
+ project=project_id,
+ )
+
+
def _map_profile_item(data: dict[str, Any], *, principal_id: str) -> MemoryItem | None:
profiles = data.get("profiles", [])
if not isinstance(profiles, list) or len(profiles) > _MAX_RESPONSE_COLLECTION:
@@ -1155,7 +1338,24 @@ def _safe_text(value: Any) -> str | None:
if not isinstance(value, str):
return None
text = value.strip()
- if not text or len(text.encode("utf-8")) > _MAX_ITEM_BYTES:
+ raw = _utf8_bytes(text)
+ if not text or raw is None or len(raw) > _MAX_ITEM_BYTES:
+ return None
+ if any(ord(character) < 32 and character not in {"\n", "\t", "\r"} for character in text):
+ return None
+ return text
+
+
+def _safe_list_text(value: Any, *, allow_empty: bool) -> str | None:
+ if not isinstance(value, str):
+ return None
+ text = value.strip()
+ raw = _utf8_bytes(text)
+ if (
+ (not allow_empty and not text)
+ or raw is None
+ or len(raw) > _MAX_ITEM_BYTES
+ ):
return None
if any(ord(character) < 32 and character not in {"\n", "\t", "\r"} for character in text):
return None
@@ -1184,11 +1384,33 @@ def _record_date(*records: dict[str, Any]) -> str | None:
return None
+def _record_timestamp(value: Any) -> str | None:
+ if isinstance(value, int) and not isinstance(value, bool):
+ try:
+ instant = datetime.fromtimestamp(value / 1000, tz=timezone.utc)
+ except (OverflowError, OSError, ValueError):
+ return None
+ elif isinstance(value, str) and len(value) <= 128:
+ try:
+ instant = datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
+ if instant.tzinfo is None:
+ return None
+ instant = instant.astimezone(timezone.utc)
+ except (OverflowError, ValueError):
+ return None
+ else:
+ return None
+ return instant.isoformat().replace("+00:00", "Z")
+
+
def _is_bounded_json_value(value: Any, *, depth: int = 0) -> bool:
if depth > _MAX_RESPONSE_DEPTH:
return False
- if value is None or isinstance(value, (str, bool)):
- return not isinstance(value, str) or len(value.encode("utf-8")) <= _MAX_ITEM_BYTES
+ if value is None or isinstance(value, bool):
+ return True
+ if isinstance(value, str):
+ raw = _utf8_bytes(value)
+ return raw is not None and len(raw) <= _MAX_ITEM_BYTES
if isinstance(value, (int, float)):
return not isinstance(value, float) or math.isfinite(value)
if isinstance(value, list):
@@ -1198,7 +1420,8 @@ def _is_bounded_json_value(value: Any, *, depth: int = 0) -> bool:
if isinstance(value, dict):
return len(value) <= _MAX_RESPONSE_COLLECTION and all(
isinstance(key, str)
- and len(key.encode("utf-8")) <= 128
+ and (raw := _utf8_bytes(key)) is not None
+ and len(raw) <= 128
and _is_bounded_json_value(item, depth=depth + 1)
for key, item in value.items()
)
@@ -1269,7 +1492,9 @@ def _optional_string(value: str | None) -> str | None:
def _bounded_opaque_string(value: object, *, max_bytes: int = 128) -> str | None:
if not isinstance(value, str):
return None
- raw = value.encode("utf-8")
+ raw = _utf8_bytes(value)
+ if raw is None:
+ return None
if len(raw) <= max_bytes:
return value
return raw[:max_bytes].decode("utf-8", errors="ignore")
@@ -1278,7 +1503,15 @@ def _bounded_opaque_string(value: object, *, max_bytes: int = 128) -> str | None
def _strict_receipt_id(value: object, *, max_bytes: int = 128) -> str | None:
if not isinstance(value, str):
return None
- return value if len(value.encode("utf-8")) <= max_bytes else None
+ raw = _utf8_bytes(value)
+ return value if raw is not None and len(raw) <= max_bytes else None
+
+
+def _utf8_bytes(value: str) -> bytes | None:
+ try:
+ return value.encode("utf-8")
+ except UnicodeError:
+ return None
def _optional_json_object(raw: bytes | None) -> dict[str, Any] | None:
@@ -1448,6 +1681,14 @@ class MemoryProviderPort(Protocol):
async def profile(self, principal_id: str, project_id: str) -> tuple[MemoryItem, ...]: ...
+ async def list_episodes(
+ self,
+ principal_id: str,
+ project_id: str,
+ page: int,
+ page_size: int,
+ ) -> MemoryListPage: ...
+
async def health(self) -> bool: ...
async def health_snapshot(self) -> ProviderHealthSnapshot: ...
@@ -1468,10 +1709,20 @@ class FakeMemoryProvider:
processing_healthy_flag: bool = True
search_items: tuple[MemoryItem, ...] = ()
profile_items: tuple[MemoryItem, ...] = ()
+ list_page: MemoryListPage = field(
+ default_factory=lambda: MemoryListPage(
+ items=(),
+ page=1,
+ page_size=_MAX_LIST_PAGE_SIZE,
+ count=0,
+ total_count=0,
+ )
+ )
captures: list[ProviderCapture] = field(default_factory=list)
flushes: list[ProviderSessionRef] = field(default_factory=list)
search_scopes: list[tuple[str, str]] = field(default_factory=list)
profile_scopes: list[tuple[str, str]] = field(default_factory=list)
+ list_requests: list[tuple[str, str, int, int]] = field(default_factory=list)
search_policies: list[
tuple[str, bool, ProviderSessionRef | None]
] = field(default_factory=list)
@@ -1481,6 +1732,7 @@ class FakeMemoryProvider:
flush_results: Deque[FlushResult] = field(default_factory=deque)
search_failure: BaseException | None = None
profile_failure: BaseException | None = None
+ list_failure: BaseException | None = None
health_failure: BaseException | None = None
agentic_budget_enforced_flag: bool = False
agentic_round: Literal["round1", "round2", "unknown"] = "unknown"
@@ -1555,6 +1807,18 @@ class FakeMemoryProvider:
raise self.profile_failure
return self.profile_items
+ async def list_episodes(
+ self,
+ principal_id: str,
+ project_id: str,
+ page: int,
+ page_size: int,
+ ) -> MemoryListPage:
+ self.list_requests.append((principal_id, project_id, page, page_size))
+ if self.list_failure is not None:
+ raise self.list_failure
+ return replace(self.list_page, page=page, page_size=page_size)
+
async def health(self) -> bool:
if self.health_failure is not None:
raise self.health_failure
diff --git a/core/memory/module.py b/core/memory/module.py
index f27ad1184..652e31f01 100644
--- a/core/memory/module.py
+++ b/core/memory/module.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import asyncio
import logging
import os
+import re
import shutil
import unicodedata
import weakref
@@ -50,6 +51,9 @@ from core.memory.types import (
MemoryFailureLogEntry,
MemoryItem,
MemoryItems,
+ MemoryListItem,
+ MemoryListPage,
+ MemoryListResult,
MemoryProfile,
MemoryProfileExplicitInfo,
MemoryProfileTrait,
@@ -71,6 +75,7 @@ MIN_FREE_DISK_BYTES = 512 * 1024 * 1024
MAX_PROVIDER_TIMESTAMP_MS = 4_102_444_800_000
MAX_QUERY_BYTES = 8 * 1024
MAX_SEARCH_LIMIT = 20
+MAX_LIST_PAGE_SIZE = 20
DEFAULT_SEARCH_LIMIT = 8
MAX_PROVIDER_ITEM_BYTES = 64 * 1024
MAX_PROVIDER_RESULT_BYTES = 256 * 1024
@@ -84,6 +89,9 @@ _SessionLifecycleResult = TypeVar("_SessionLifecycleResult")
_ROOT_LIFECYCLE_LOCKS: dict[str, asyncio.Lock] = {}
+_RFC3339_TIMESTAMP_RE = re.compile(
+ r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})\Z"
+)
class MemorySessionLifecycleBusyError(RuntimeError):
@@ -858,6 +866,60 @@ class MemoryModule:
limit=MAX_PROVIDER_RESULT_ITEMS,
)
+ async def list_episodes(
+ self,
+ *,
+ principal_id: str,
+ project_id: str,
+ page: int = 1,
+ page_size: int = MAX_LIST_PAGE_SIZE,
+ ) -> MemoryListResult:
+ """Return one bounded page of processed episodes or a closed error."""
+
+ if not self._is_enabled():
+ return OperationFailed(error="memory_disabled")
+ if not is_principal_id(principal_id):
+ return OperationFailed(error="memory_access_denied")
+ if not is_new_stored_memory_project_id(project_id):
+ return OperationFailed(error="memory_access_denied")
+ if (
+ isinstance(page, bool)
+ or not isinstance(page, int)
+ or page < 1
+ or isinstance(page_size, bool)
+ or not isinstance(page_size, int)
+ or not 1 <= page_size <= MAX_LIST_PAGE_SIZE
+ ):
+ return OperationFailed(error="memory_invalid_input")
+ if self._clear_active or self._is_maintenance_open():
+ return OperationFailed(error="memory_clear_failed")
+
+ async with self._lifecycle_lock:
+ if not self._is_enabled():
+ return OperationFailed(error="memory_disabled")
+ try:
+ meta = await self._store_call(self._store.ensure_meta)
+ except Exception:
+ return OperationFailed(error="memory_store_unavailable")
+ if meta.clear_in_progress:
+ return OperationFailed(error="memory_clear_failed")
+ result = await self._provider_list_read(
+ lambda: self._provider.list_episodes(
+ principal_id,
+ project_id,
+ page,
+ page_size,
+ )
+ )
+ if isinstance(result, OperationFailed):
+ return result
+ return self._bounded_list_page(
+ result,
+ project_id=project_id,
+ page=page,
+ page_size=page_size,
+ )
+
async def failure_log(self, *, limit: int = 50) -> tuple[MemoryFailureLogEntry, ...]:
"""Return terminal failure history while fencing its bounded compaction."""
@@ -894,6 +956,94 @@ class MemoryModule:
except Exception:
return OperationFailed(error="memory_processing_failed")
+ async def _provider_list_read(
+ self,
+ operation: Callable[[], Awaitable[MemoryListPage]],
+ ) -> MemoryListPage | OperationFailed:
+ try:
+ return await asyncio.wait_for(
+ operation(),
+ timeout=PROVIDER_READ_TIMEOUT_SECONDS,
+ )
+ except asyncio.TimeoutError:
+ return OperationFailed(error="memory_provider_timeout")
+ except MemoryProviderFailure as failure:
+ return OperationFailed(error=_provider_error_code(failure, "memory_processing_failed"))
+ except Exception:
+ return OperationFailed(error="memory_processing_failed")
+
+ def _bounded_list_page(
+ self,
+ result: MemoryListPage,
+ *,
+ project_id: str,
+ page: int,
+ page_size: int,
+ ) -> MemoryListResult:
+ if (
+ not isinstance(result, MemoryListPage)
+ or isinstance(result.page, bool)
+ or not isinstance(result.page, int)
+ or result.page != page
+ or isinstance(result.page_size, bool)
+ or not isinstance(result.page_size, int)
+ or result.page_size != page_size
+ or not isinstance(result.items, tuple)
+ or isinstance(result.count, bool)
+ or not isinstance(result.count, int)
+ or result.count != len(result.items)
+ or result.count > page_size
+ or isinstance(result.total_count, bool)
+ or not isinstance(result.total_count, int)
+ or result.total_count < result.count
+ or result.count != min(
+ page_size,
+ max(result.total_count - (page - 1) * page_size, 0),
+ )
+ or result.status != "ok"
+ or not isinstance(result.warnings, tuple)
+ or any(warning != "memory_list_truncated" for warning in result.warnings)
+ ):
+ return OperationFailed(error="memory_provider_response_invalid")
+ total_bytes = 0
+ seen_ids: set[str] = set()
+ previous_instant: datetime | None = None
+ for item in result.items:
+ instant = _list_timestamp_instant(item.timestamp) if isinstance(
+ item,
+ MemoryListItem,
+ ) else None
+ if (
+ not isinstance(item, MemoryListItem)
+ or item.kind != "episode"
+ or item.project != project_id
+ or not _valid_list_identifier(item.id)
+ or item.id in seen_ids
+ or instant is None
+ or (
+ previous_instant is not None
+ and instant > previous_instant
+ )
+ ):
+ return OperationFailed(error="memory_provider_response_invalid")
+ seen_ids.add(item.id)
+ previous_instant = instant
+ for value, allow_empty in (
+ (item.subject, True),
+ (item.summary, True),
+ (item.body, False),
+ ):
+ encoded = _list_text_bytes(value, allow_empty=allow_empty)
+ if encoded is None:
+ return OperationFailed(error="memory_provider_response_invalid")
+ total_bytes += len(encoded)
+ total_bytes += len(item.id.encode("utf-8"))
+ total_bytes += len(item.timestamp.encode("utf-8"))
+ total_bytes += len(item.project.encode("utf-8"))
+ if total_bytes > MAX_PROVIDER_RESULT_BYTES:
+ return OperationFailed(error="memory_provider_response_invalid")
+ return result
+
def _bounded_items(self, items: tuple[MemoryItem, ...], *, limit: int) -> MemoryResult:
if not isinstance(items, tuple) or len(items) > limit:
return OperationFailed(error="memory_provider_response_invalid")
@@ -1053,6 +1203,41 @@ def _profile_text_bytes(value: object) -> bytes | None:
return encoded
+def _list_text_bytes(value: object, *, allow_empty: bool) -> bytes | None:
+ if (
+ not isinstance(value, str)
+ or value != value.strip()
+ or (not allow_empty and not value)
+ or "\x00" in value
+ ):
+ return None
+ encoded = _utf8_bytes(value)
+ if encoded is None or len(encoded) > MAX_PROVIDER_ITEM_BYTES:
+ return None
+ if any(ord(character) < 32 and character not in {"\n", "\t", "\r"} for character in value):
+ return None
+ return encoded
+
+
+def _valid_list_identifier(value: object) -> bool:
+ encoded = _utf8_bytes(value) if isinstance(value, str) else None
+ return bool(value) and encoded is not None and len(encoded) <= 128 and "\x00" not in value
+
+
+def _list_timestamp_instant(value: object) -> datetime | None:
+ if (
+ not isinstance(value, str)
+ or len(value) > 64
+ or _RFC3339_TIMESTAMP_RE.fullmatch(value) is None
+ ):
+ return None
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ return parsed.astimezone(timezone.utc)
+ except (OverflowError, ValueError):
+ return None
+
+
def _profile_bytes(profile: object) -> int | None:
"""Revalidate every structured profile field before it leaves the module."""
diff --git a/core/memory/runtime.py b/core/memory/runtime.py
index 54431099c..1c64f70e8 100644
--- a/core/memory/runtime.py
+++ b/core/memory/runtime.py
@@ -92,6 +92,7 @@ from core.memory.types import (
MemoryFailureLogEntry,
MemoryItem,
MemoryItems,
+ MemoryListPage,
MemoryResult,
MemoryWarningCode,
OperationFailed,
@@ -99,6 +100,7 @@ from core.memory.types import (
RecallPolicy,
RecallResult,
memory_item_payload,
+ memory_list_page_payload,
)
from core.memory.worker import ProcessingEvent
@@ -1443,6 +1445,30 @@ class MemoryRuntime:
"profile_warning": "empty" if empty else None,
}
+ async def list_episodes_payload(
+ self,
+ principal_id: str,
+ project_id: str,
+ *,
+ page: int = 1,
+ page_size: int = 20,
+ ) -> dict[str, Any]:
+ """Return one single-project processed-episode page."""
+
+ if not self.available:
+ return {"status": "failed", "error": "memory_store_unavailable"}
+ result = await self.module.list_episodes(
+ principal_id=principal_id,
+ project_id=project_id,
+ page=page,
+ page_size=page_size,
+ )
+ if isinstance(result, OperationFailed):
+ return {"status": result.status, "error": result.error}
+ if isinstance(result, MemoryListPage):
+ return memory_list_page_payload(result)
+ return {"status": "failed", "error": "memory_processing_failed"}
+
def list_memory_projects(self, principal_id: str) -> tuple[str, ...]:
if not self.available:
return (DEFAULT_MEMORY_PROJECT_ID,)
diff --git a/core/memory/sidecar.py b/core/memory/sidecar.py
index ee74502b5..f3c7fff23 100644
--- a/core/memory/sidecar.py
+++ b/core/memory/sidecar.py
@@ -546,16 +546,36 @@ def _validate_search(payload: dict[str, Any]) -> str | None:
def _validate_get(payload: dict[str, Any]) -> str | None:
- keys = {"user_id", "app_id", "project_id", "memory_type", "page", "page_size"}
- if not _exact_keys(payload, keys):
+ profile_keys = {"user_id", "app_id", "project_id", "memory_type", "page", "page_size"}
+ if _exact_keys(payload, profile_keys):
+ if (
+ not _valid_principal(payload.get("user_id"))
+ or payload.get("app_id") != _APP_ID
+ or payload.get("project_id") != "default"
+ or payload.get("memory_type") != "profile"
+ or payload.get("page") != 1
+ or payload.get("page_size") != 1
+ ):
+ return "get"
+ return None
+
+ episode_keys = profile_keys | {"sort_by", "sort_order"}
+ if not _exact_keys(payload, episode_keys):
return "get"
+ page = payload.get("page")
+ page_size = payload.get("page_size")
if (
not _valid_principal(payload.get("user_id"))
- or payload.get("app_id") != _APP_ID
- or payload.get("project_id") != "default"
- or payload.get("memory_type") != "profile"
- or payload.get("page") != 1
- or payload.get("page_size") != 1
+ or not _valid_search_scope(payload)
+ or payload.get("memory_type") != "episode"
+ or isinstance(page, bool)
+ or not isinstance(page, int)
+ or page < 1
+ or isinstance(page_size, bool)
+ or not isinstance(page_size, int)
+ or not 1 <= page_size <= 20
+ or payload.get("sort_by") != "timestamp"
+ or payload.get("sort_order") != "desc"
):
return "get"
return None
diff --git a/core/memory/types.py b/core/memory/types.py
index 3ab11aa26..8d9c16bd6 100644
--- a/core/memory/types.py
+++ b/core/memory/types.py
@@ -296,8 +296,14 @@ class MemoryProfile:
MemoryWarningCode = Literal["memory_search_partial", "memory_search_truncated"]
+MemoryListWarningCode = Literal["memory_list_partial", "memory_list_truncated"]
CLOSED_MEMORY_WARNING_CODES = frozenset(
- {"memory_search_partial", "memory_search_truncated"}
+ {
+ "memory_search_partial",
+ "memory_search_truncated",
+ "memory_list_partial",
+ "memory_list_truncated",
+ }
)
@@ -365,6 +371,60 @@ class MemoryItems:
MemoryResult: TypeAlias = MemoryItems | OperationFailed
+@dataclass(frozen=True)
+class MemoryListItem:
+ """One provider-neutral processed episode returned by a list read."""
+
+ id: str
+ subject: str
+ summary: str
+ body: str
+ timestamp: str
+ project: str
+ kind: Literal["episode"] = "episode"
+
+
+@dataclass(frozen=True)
+class MemoryListPage:
+ """One exact 1-based provider page of processed episodes."""
+
+ items: tuple[MemoryListItem, ...]
+ page: int
+ page_size: int
+ count: int
+ total_count: int
+ warnings: tuple[MemoryListWarningCode, ...] = ()
+ status: Literal["ok"] = "ok"
+
+
+MemoryListResult: TypeAlias = MemoryListPage | OperationFailed
+
+
+def memory_list_page_payload(result: MemoryListPage) -> dict[str, Any]:
+ """Serialize a validated list page into the closed transport envelope."""
+
+ return {
+ "status": result.status,
+ "items": [
+ {
+ "id": item.id,
+ "kind": item.kind,
+ "subject": item.subject,
+ "summary": item.summary,
+ "body": item.body,
+ "timestamp": item.timestamp,
+ "project": item.project,
+ }
+ for item in result.items
+ ],
+ "page": result.page,
+ "page_size": result.page_size,
+ "count": result.count,
+ "total_count": result.total_count,
+ "warnings": list(result.warnings),
+ }
+
+
@dataclass(frozen=True)
class RecallPolicy:
"""One bounded, single-run provider-neutral recall decision request."""
diff --git a/docs/plans/memory-list-1427.md b/docs/plans/memory-list-1427.md
new file mode 100644
index 000000000..3764ad7e1
--- /dev/null
+++ b/docs/plans/memory-list-1427.md
@@ -0,0 +1,79 @@
+# Memory episode listing via EverOS `/memory/get`
+
+Issue: [#1427](https://github.com/avibe-bot/avibe/issues/1427)
+
+## Goal
+
+Add a closed, principal-scoped listing path for processed EverOS episodes, then
+expose it through `vibe memory list`. The provider boundary must not leak raw
+EverOS dictionaries or broaden the existing profile lookup.
+
+## Locked decisions
+
+- v1 lists only active processed `episode` memories. Profiles remain on the
+ existing profile surface; atomic facts, unprocessed messages, agent cases,
+ and agent skills are excluded.
+- Single-project listing uses EverOS's 1-based `page` and `page_size` contract.
+ CLI rejects `--project all`; only the verified UI/controller path may request
+ an Avibe-aggregated `all` listing.
+- The `all` result uses a versioned, bounded Avibe cursor that records per-project
+ consumed offsets and a project-catalog fingerprint. It is not an EverOS cursor.
+- `vibe memory list` is not added to the injected Personal Memory prompt. Parser
+ contracts must prove the injected CLI surface remains unchanged.
+- JSON output includes the provider-neutral opaque episode `id` for future item
+ management. The id has no management semantics in this change.
+- No config key, persisted schema, or EverOS source changes are required.
+
+## Contract
+
+The provider port accepts only an Avibe-derived principal, one stored project id,
+`page >= 1`, and `1 <= page_size <= 20`. It sends the exact EverOS episode shape
+to `POST /api/v2/memory/get` and returns a provider-neutral page:
+
+- item: `id`, `kind=episode`, `subject`, `summary`, `body`, RFC3339 `timestamp`,
+ and `project`
+- page: `items`, `page`, `page_size`, current-page `count`, pre-page
+ `total_count`, and closed warnings
+
+The adapter validates the complete EverOS envelope, all four kind arrays, owner,
+app/project scope, counts, and bounded item fields. Any malformed or cross-scope
+response fails closed as `memory_provider_response_invalid`. A provider
+`total_count` above EverOS's 20,000-row exact-ordering window adds the
+transport-only `memory_list_truncated` warning.
+
+The sidecar keeps the existing profile request as an independent exact shape.
+Episode requests additionally allow only the exact eight fields used by Avibe:
+`user_id`, `app_id`, `project_id`, `memory_type`, `page`, `page_size`, and the
+fixed `sort_order=desc`/`sort_by=timestamp` pair. Unknown keys, filters,
+`agent_id`, legacy/reserved projects, and values outside the bounds are rejected.
+
+## CLI and aggregation
+
+`vibe memory list [--project <slug>] [--page N] [--limit 1..20] [--json]`
+defaults to `default`, page 1, and limit 20. The internal route derives the
+principal from the caller-session binding exactly like search; no owner id is
+accepted on the wire.
+
+Single-project ordering is fixed to `timestamp desc`. This is the smallest
+closed v1 contract because the EverOS episode response exposes `timestamp` but
+not `updated_at`, so Avibe cannot correctly merge an `updated_at`-sorted `all`
+result. Sorting controls can be added later only when the provider response has
+the corresponding merge key.
+
+For UI-only `all`, the runtime enumerates the same principal's current Memory
+project catalog as search, fetches bounded provider pages under one 20-second
+deadline, and performs a deterministic merge by timestamp then project/id.
+Failures produce `memory_list_partial`; deadline/provider-window limits produce
+`memory_list_truncated`. `total_count` is null if any project failed.
+
+## Delivery and evidence
+
+1. PR1: value types, EverOS port/fake, exact sidecar expansion, module/runtime
+ single-project listing, and focused unit/contract tests.
+2. PR2 (after PR1 review pass): scoped internal route/client, CLI/i18n/docs,
+ UI-only aggregate cursor, parser contracts, and closed-loop scenarios.
+3. Browse UI remains out of scope until its design mockup is approved.
+
+Scenario IDs are catalogued under `tests/scenarios/memory_list/`; the closed-loop
+evidence captures processed episodes in one scoped project, lists them through
+the product boundary, and verifies an exact pagination boundary.
diff --git a/tests/test_fake_memory_provider.py b/tests/test_fake_memory_provider.py
index 993142903..64fe36b73 100644
--- a/tests/test_fake_memory_provider.py
+++ b/tests/test_fake_memory_provider.py
@@ -12,7 +12,7 @@ from core.memory.everos import (
MemoryProviderPort,
ProviderCapture,
)
-from core.memory.types import ProviderSessionRef
+from core.memory.types import MemoryListItem, MemoryListPage, ProviderSessionRef
SESSION_REF = ProviderSessionRef(
@@ -190,3 +190,39 @@ def test_timing_hooks_are_fake_only() -> None:
assert not hasattr(MemoryProviderPort, "add_hook")
assert not hasattr(MemoryProviderPort, "flush_hook")
assert not hasattr(MemoryProviderPort, "processing_healthy_hook")
+
+
+async def test_list_fake_records_exact_page_request_and_returns_configured_items() -> None:
+ item = MemoryListItem(
+ id="opaque-id",
+ subject="Subject",
+ summary="Summary",
+ body="Body",
+ timestamp="2026-08-14T00:00:00Z",
+ project="notes",
+ )
+ provider = FakeMemoryProvider(
+ list_page=MemoryListPage(
+ items=(item,),
+ page=1,
+ page_size=20,
+ count=1,
+ total_count=1,
+ )
+ )
+
+ result = await provider.list_episodes(
+ SESSION_REF.principal_id,
+ "notes",
+ 3,
+ 5,
+ )
+
+ assert result == MemoryListPage(
+ items=(item,),
+ page=3,
+ page_size=5,
+ count=1,
+ total_count=1,
+ )
+ assert provider.list_requests == [(SESSION_REF.principal_id, "notes", 3, 5)]
diff --git a/tests/test_memory_everos.py b/tests/test_memory_everos.py
index e89daf8ec..f1a8d0105 100644
--- a/tests/test_memory_everos.py
+++ b/tests/test_memory_everos.py
@@ -26,6 +26,8 @@ from core.memory.everos import (
)
from core.memory.store import _provider_session_ref
from core.memory.types import (
+ MemoryListItem,
+ MemoryListPage,
MemoryProfile,
MemoryProfileExplicitInfo,
MemoryProfileTrait,
@@ -846,6 +848,235 @@ def test_profile_uses_get_and_reports_empty_profile_as_non_failure() -> None:
assert items == ()
+def test_list_episodes_uses_exact_get_shape_and_projects_a_bounded_page() -> None:
+ requests: list[dict] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ requests.append(json.loads(request.content))
+ return httpx.Response(
+ 200,
+ json={
+ "request_id": "get-page-2",
+ "data": {
+ "episodes": [
+ {
+ "id": "episode-opaque-2",
+ "user_id": PRINCIPAL,
+ "app_id": "avibe",
+ "project_id": "notes",
+ "session_id": "provider-session",
+ "timestamp": "2026-08-14T10:11:12+08:00",
+ "sender_ids": [PRINCIPAL],
+ "summary": " A bounded summary. ",
+ "subject": " ",
+ "episode": "Processed episode body.",
+ "type": "Conversation",
+ }
+ ],
+ "profiles": [],
+ "agent_cases": [],
+ "agent_skills": [],
+ "total_count": 20_001,
+ "count": 1,
+ },
+ },
+ )
+
+ with _sidecar_transport(handler):
+ result = asyncio.run(
+ EverOSPort(Path("/tmp/everos.sock")).list_episodes(
+ PRINCIPAL,
+ "notes",
+ 2,
+ 1,
+ )
+ )
+
+ assert requests == [
+ {
+ "user_id": PRINCIPAL,
+ "app_id": "avibe",
+ "project_id": "notes",
+ "memory_type": "episode",
+ "page": 2,
+ "page_size": 1,
+ "sort_by": "timestamp",
+ "sort_order": "desc",
+ }
+ ]
+ assert result == MemoryListPage(
+ items=(
+ MemoryListItem(
+ id="episode-opaque-2",
+ subject="",
+ summary="A bounded summary.",
+ body="Processed episode body.",
+ timestamp="2026-08-14T02:11:12Z",
+ project="notes",
+ ),
+ ),
+ page=2,
+ page_size=1,
+ count=1,
+ total_count=20_001,
+ warnings=("memory_list_truncated",),
+ )
+
+
+ "mutation",
+ [
+ lambda data: data["episodes"][0].update(user_id="u-" + "f" * 32),
+ lambda data: data.update(count=0),
+ lambda data: data.update(episodes=[], count=0, total_count=1),
+ lambda data: data["profiles"].append({"profile_data": {}}),
+ lambda data: data["episodes"][0].update(timestamp="not-a-timestamp"),
+ lambda data: data["episodes"][0].update(
+ timestamp="0001-01-01T00:00:00+23:59"
+ ),
+ lambda data: data["episodes"][0].update(summary="\ud800"),
+ lambda data: (
+ data["episodes"].append(dict(data["episodes"][0])),
+ data.update(total_count=2, count=2),
+ ),
+ ],
+)
+def test_list_episodes_rejects_cross_scope_or_malformed_envelopes(mutation) -> None:
+ data = {
+ "episodes": [
+ {
+ "id": "episode-1",
+ "user_id": PRINCIPAL,
+ "app_id": "avibe",
+ "project_id": PROJECT,
+ "session_id": "provider-session",
+ "timestamp": "2026-08-14T00:00:00Z",
+ "sender_ids": [],
+ "summary": "Summary",
+ "subject": "Subject",
+ "episode": "Body",
+ "type": "Conversation",
+ }
+ ],
+ "profiles": [],
+ "agent_cases": [],
+ "agent_skills": [],
+ "total_count": 1,
+ "count": 1,
+ }
+ mutation(data)
+
+ def handler(_request: httpx.Request) -> httpx.Response:
+ body = json.dumps(
+ {"request_id": "request", "data": data},
+ ensure_ascii=True,
+ ).encode("ascii")
+ return httpx.Response(
+ 200,
+ content=body,
+ headers={"content-type": "application/json"},
+ )
+
+ async def run() -> None:
+ with pytest.raises(MemoryProviderFailure) as raised:
+ await EverOSPort(Path("/tmp/everos.sock")).list_episodes(
+ PRINCIPAL,
+ PROJECT,
+ 1,
+ 20,
+ )
+ assert raised.value.error == "memory_provider_response_invalid"
+
+ with _sidecar_transport(handler):
+ asyncio.run(run())
+
+
+def test_list_episodes_rejects_nonempty_page_beyond_total_count() -> None:
+ data = {
+ "episodes": [
+ {
+ "id": "episode-impossible-page",
+ "user_id": PRINCIPAL,
+ "app_id": "avibe",
+ "project_id": PROJECT,
+ "session_id": "provider-session",
+ "timestamp": "2026-08-14T00:00:00Z",
+ "sender_ids": [],
+ "summary": "Summary",
+ "subject": "Subject",
+ "episode": "Body",
+ "type": "Conversation",
+ }
+ ],
+ "profiles": [],
+ "agent_cases": [],
+ "agent_skills": [],
+ "total_count": 1,
+ "count": 1,
+ }
+
+ def handler(_request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json={"request_id": "request", "data": data})
+
+ async def run() -> None:
+ with pytest.raises(MemoryProviderFailure) as raised:
+ await EverOSPort(Path("/tmp/everos.sock")).list_episodes(
+ PRINCIPAL,
+ PROJECT,
+ 3,
+ 5,
+ )
+ assert raised.value.error == "memory_provider_response_invalid"
+
+ with _sidecar_transport(handler):
+ asyncio.run(run())
+
+
+def test_list_episodes_rejects_ascending_provider_page() -> None:
+ def episode(episode_id: str, timestamp: str) -> dict[str, object]:
+ return {
+ "id": episode_id,
+ "user_id": PRINCIPAL,
+ "app_id": "avibe",
+ "project_id": PROJECT,
+ "session_id": "provider-session",
+ "timestamp": timestamp,
+ "sender_ids": [],
+ "summary": "Summary",
+ "subject": "Subject",
+ "episode": "Body",
+ "type": "Conversation",
+ }
+
+ data = {
+ "episodes": [
+ episode("episode-older", "2026-08-14T00:00:00Z"),
+ episode("episode-newer", "2026-08-14T00:00:01Z"),
+ ],
+ "profiles": [],
+ "agent_cases": [],
+ "agent_skills": [],
+ "total_count": 2,
+ "count": 2,
+ }
+
+ def handler(_request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json={"request_id": "request", "data": data})
+
+ async def run() -> None:
+ with pytest.raises(MemoryProviderFailure) as raised:
+ await EverOSPort(Path("/tmp/everos.sock")).list_episodes(
+ PRINCIPAL,
+ PROJECT,
+ 1,
+ 20,
+ )
+ assert raised.value.error == "memory_provider_response_invalid"
+
+ with _sidecar_transport(handler):
+ asyncio.run(run())
+
+
def test_profile_canonicalizes_structured_profile() -> None:
def handler(_request: httpx.Request) -> httpx.Response:
return httpx.Response(
diff --git a/tests/test_memory_module.py b/tests/test_memory_module.py
index 166c8b685..7c020b86f 100644
--- a/tests/test_memory_module.py
+++ b/tests/test_memory_module.py
@@ -31,6 +31,9 @@ from core.memory.types import (
CaptureSkipped,
MemoryItem,
MemoryItems,
+ MemoryListItem,
+ MemoryListPage,
+ MemoryListResult,
MemoryProfile,
MemoryProfileExplicitInfo,
MemoryProfileTrait,
@@ -585,6 +588,280 @@ async def test_profile_bounds_accept_structured_data_only_on_profile_items(tmp_p
)
+async def test_list_episodes_enforces_scope_pagination_and_page_bounds(tmp_path: Path) -> None:
+ item = MemoryListItem(
+ id="opaque-episode-id",
+ subject="Subject",
+ summary="Summary",
+ body="Processed body",
+ timestamp="2026-08-14T02:11:12Z",
+ project="notes",
+ )
+ provider = FakeMemoryProvider(
+ list_page=MemoryListPage(
+ items=(item,),
+ page=1,
+ page_size=20,
+ count=1,
+ total_count=6,
+ )
+ )
+ module, _store, _provider = _module(tmp_path, provider=provider)
+
+ assert await module.list_episodes(
+ principal_id=PRINCIPAL,
+ project_id="notes",
+ page=2,
+ page_size=5,
+ ) == MemoryListPage(
+ items=(item,),
+ page=2,
+ page_size=5,
+ count=1,
+ total_count=6,
+ )
+ assert provider.list_requests == [(PRINCIPAL, "notes", 2, 5)]
+
+ for page, page_size in ((0, 5), (1, 0), (1, 21), (True, 5)):
+ assert await module.list_episodes(
+ principal_id=PRINCIPAL,
+ project_id="notes",
+ page=page,
+ page_size=page_size,
+ ) == OperationFailed(error="memory_invalid_input")
+ assert provider.list_requests == [(PRINCIPAL, "notes", 2, 5)]
+
+ assert await module.list_episodes(
+ principal_id=PRINCIPAL,
+ project_id="all",
+ ) == OperationFailed(error="memory_access_denied")
+
+ provider.list_page = replace(provider.list_page, count=0)
+ assert await module.list_episodes(
+ principal_id=PRINCIPAL,
+ project_id="notes",
+ ) == OperationFailed(error="memory_provider_response_invalid")
+
+ provider.list_failure = RuntimeError("provider-list-body-canary")
+ result = await module.list_episodes(
+ principal_id=PRINCIPAL,
+ project_id="notes",
+ )
+ assert result == OperationFailed(error="memory_processing_failed")
+ assert "provider-list-body-canary" not in repr(result)
+
+
+async def test_list_episodes_rejects_nonempty_page_beyond_total_count(
+ tmp_path: Path,
+) -> None:
+ provider = FakeMemoryProvider(
+ list_page=MemoryListPage(
+ items=(
+ MemoryListItem(
+ id="opaque-episode-id",
+ subject="Subject",
+ summary="Summary",
+ body="Processed body",
+ timestamp="2026-08-14T02:11:12Z",
+ project="notes",
+ ),
+ ),
+ page=1,
+ page_size=20,
+ count=1,
+ total_count=1,
+ )
+ )
+ module, _store, _provider = _module(tmp_path, provider=provider)
+
+ assert await module.list_episodes(
+ principal_id=PRINCIPAL,
+ project_id="notes",
+ page=3,
+ page_size=5,
+ ) == OperationFailed(error="memory_provider_response_invalid")
+
+
+ "page",
+ [
+ MemoryListPage(
+ items=(),
+ page=1,
+ page_size=20,
+ count=0,
+ total_count=1,
+ ),
+ MemoryListPage(
+ items=(
+ MemoryListItem(
+ id="opaque-episode-id",
+ subject="Subject",
+ summary="Summary",
+ body="Processed body",
+ timestamp="2026-08-14T02:11:12Z",
+ project="notes",
+ ),
+ ),
+ page=1,
+ page_size=20,
+ count=1,
+ total_count=1,
+ status="failed", # type: ignore[arg-type]
+ ),
+ MemoryListPage(
+ items=(
+ MemoryListItem(
+ id="duplicate-id",
+ subject="Subject",
+ summary="Summary",
+ body="Processed body one",
+ timestamp="2026-08-14T02:11:12Z",
+ project="notes",
+ ),
+ MemoryListItem(
+ id="duplicate-id",
+ subject="Subject",
+ summary="Summary",
+ body="Processed body two",
+ timestamp="2026-08-14T02:11:11Z",
+ project="notes",
+ ),
+ ),
+ page=1,
+ page_size=20,
+ count=2,
+ total_count=2,
+ ),
+ ],
+)
+async def test_list_episodes_rejects_invalid_page_envelope(
+ tmp_path: Path,
+ page: MemoryListPage,
+) -> None:
+ module, _store, _provider = _module(
+ tmp_path,
+ provider=FakeMemoryProvider(list_page=page),
+ )
+
+ assert await module.list_episodes(
+ principal_id=PRINCIPAL,
+ project_id="notes",
+ ) == OperationFailed(error="memory_provider_response_invalid")
+
+
+ "items",
+ [
+ (
+ MemoryListItem(
+ id="older",
+ subject="Subject",
+ summary="Summary",
+ body="Processed body",
+ timestamp="2026-08-14T02:11:11Z",
+ project="notes",
+ ),
+ MemoryListItem(
+ id="newer",
+ subject="Subject",
+ summary="Summary",
+ body="Processed body",
+ timestamp="2026-08-14T02:11:12Z",
+ project="notes",
+ ),
+ ),
+ (
+ MemoryListItem(
+ id="week-date",
+ subject="Subject",
+ summary="Summary",
+ body="Processed body",
+ timestamp="2026-W33-5T02:11:12+00:00",
+ project="notes",
+ ),
+ ),
+ (
+ MemoryListItem(
+ id="overflowing-offset",
+ subject="Subject",
+ summary="Summary",
+ body="Processed body",
+ timestamp="0001-01-01T00:00:00+23:59",
+ project="notes",
+ ),
+ ),
+ ],
+)
+async def test_list_episodes_rejects_invalid_shared_timestamp_contract(
+ tmp_path: Path,
+ items: tuple[MemoryListItem, ...],
+) -> None:
+ provider = FakeMemoryProvider(
+ list_page=MemoryListPage(
+ items=items,
+ page=1,
+ page_size=20,
+ count=len(items),
+ total_count=len(items),
+ )
+ )
+ module, _store, _provider = _module(tmp_path, provider=provider)
+
+ assert await module.list_episodes(
+ principal_id=PRINCIPAL,
+ project_id="notes",
+ ) == OperationFailed(error="memory_provider_response_invalid")
+
+
+async def test_list_episodes_rejects_invalid_items_container(tmp_path: Path) -> None:
+ provider = FakeMemoryProvider(
+ list_page=MemoryListPage(
+ items=None, # type: ignore[arg-type]
+ page=1,
+ page_size=20,
+ count=0,
+ total_count=0,
+ )
+ )
+ module, _store, _provider = _module(tmp_path, provider=provider)
+
+ assert await module.list_episodes(
+ principal_id=PRINCIPAL,
+ project_id="notes",
+ ) == OperationFailed(error="memory_provider_response_invalid")
+
+
+async def test_list_episodes_requires_canonical_provider_text(tmp_path: Path) -> None:
+ item = MemoryListItem(
+ id="opaque-episode-id",
+ subject="Subject",
+ summary="Summary",
+ body="Processed body",
+ timestamp="2026-08-14T02:11:12Z",
+ project="notes",
+ )
+ provider = FakeMemoryProvider()
+ module, _store, _provider = _module(tmp_path, provider=provider)
+
+ for malformed in (
+ replace(item, subject=" Subject"),
+ replace(item, summary="Summary "),
+ replace(item, body=" \t "),
+ ):
+ provider.list_page = MemoryListPage(
+ items=(malformed,),
+ page=1,
+ page_size=20,
+ count=1,
+ total_count=1,
+ )
+ assert await module.list_episodes(
+ principal_id=PRINCIPAL,
+ project_id="notes",
+ ) == OperationFailed(error="memory_provider_response_invalid")
+
+
async def test_keyword_recall_skips_health_and_succeeds_without_embedding(tmp_path: Path) -> None:
class NoHealthProvider(FakeMemoryProvider):
async def health_snapshot(self):
@@ -1059,6 +1336,17 @@ def test_provider_port_is_not_part_of_the_public_memory_package() -> None:
assert "ProviderCapture" not in memory.__all__
+def test_memory_list_result_types_are_public() -> None:
+ import core.memory as memory
+
+ assert memory.MemoryListItem is MemoryListItem
+ assert memory.MemoryListPage is MemoryListPage
+ assert memory.MemoryListResult is MemoryListResult
+ assert {"MemoryListItem", "MemoryListPage", "MemoryListResult"} <= set(
+ memory.__all__
+ )
+
+
def test_slice2_runtime_types_remain_internal_to_the_memory_package() -> None:
import core.memory as memory
import core.memory.artifact as artifact
diff --git a/tests/test_memory_runtime.py b/tests/test_memory_runtime.py
index c913295e4..b38e9d35e 100644
--- a/tests/test_memory_runtime.py
+++ b/tests/test_memory_runtime.py
@@ -63,6 +63,8 @@ from core.memory.types import (
CaptureAccepted,
MemoryItem,
MemoryItems,
+ MemoryListItem,
+ MemoryListPage,
MemoryProfile,
MemoryProfileExplicitInfo,
OperationFailed,
@@ -3920,6 +3922,76 @@ async def test_profile_payload_reports_only_its_own_principal_emptiness(
assert empty["profile_warning"] == "empty"
+def test_list_episodes_payload_serializes_opaque_id_and_page_metadata(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ runtime = create_memory_runtime(
+ MemoryConfig(enabled=True),
+ artifact_manager=_installed_artifact(),
+ )
+ item = MemoryListItem(
+ id="copyable-opaque-id",
+ subject="Subject",
+ summary="Summary",
+ body="Processed episode body",
+ timestamp="2026-08-14T02:11:12Z",
+ project="notes",
+ )
+
+ class _ListModule:
+ async def list_episodes(
+ self,
+ *,
+ principal_id: str,
+ project_id: str,
+ page: int,
+ page_size: int,
+ ) -> MemoryListPage:
+ assert principal_id == PRINCIPAL
+ assert project_id == "notes"
+ assert (page, page_size) == (2, 5)
+ return MemoryListPage(
+ items=(item,),
+ page=page,
+ page_size=page_size,
+ count=1,
+ total_count=6,
+ warnings=("memory_list_truncated",),
+ )
+
+ runtime._module = _ListModule()
+ payload = asyncio.run(
+ runtime.list_episodes_payload(
+ PRINCIPAL,
+ "notes",
+ page=2,
+ page_size=5,
+ )
+ )
+
+ assert payload == {
+ "status": "ok",
+ "items": [
+ {
+ "id": "copyable-opaque-id",
+ "kind": "episode",
+ "subject": "Subject",
+ "summary": "Summary",
+ "body": "Processed episode body",
+ "timestamp": "2026-08-14T02:11:12Z",
+ "project": "notes",
+ }
+ ],
+ "page": 2,
+ "page_size": 5,
+ "count": 1,
+ "total_count": 6,
+ "warnings": ["memory_list_truncated"],
+ }
+
+
def test_profile_payload_serializes_structured_profile_without_widening_legacy_items(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
diff --git a/tests/test_memory_sidecar.py b/tests/test_memory_sidecar.py
index fb594c6a4..faa143353 100644
--- a/tests/test_memory_sidecar.py
+++ b/tests/test_memory_sidecar.py
@@ -549,6 +549,56 @@ def test_sidecar_guard_accepts_agentic_but_rejects_untrusted_search_scope() -> N
)
+def test_sidecar_guard_keeps_profile_exact_and_allows_only_bounded_episode_lists() -> None:
+ principal = "u-11111111111111111111111111111111"
+ profile = {
+ "user_id": principal,
+ "app_id": "avibe",
+ "project_id": "default",
+ "memory_type": "profile",
+ "page": 1,
+ "page_size": 1,
+ }
+ episode = {
+ "user_id": principal,
+ "app_id": "avibe",
+ "project_id": "notes",
+ "memory_type": "episode",
+ "page": 2,
+ "page_size": 20,
+ "sort_by": "timestamp",
+ "sort_order": "desc",
+ }
+
+ assert _request_rejection("POST", "/api/v2/memory/get", json.dumps(profile).encode()) is None
+ assert _request_rejection("POST", "/api/v2/memory/get", json.dumps(episode).encode()) is None
+
+ invalid_profiles = (
+ {**profile, "project_id": "notes"},
+ {**profile, "page_size": 2},
+ {**profile, "sort_by": "timestamp"},
+ )
+ invalid_episodes = (
+ {**episode, "agent_id": principal},
+ {**episode, "project_id": "all"},
+ {**episode, "project_id": "p-" + "a" * 32},
+ {**episode, "page": 0},
+ {**episode, "page_size": 21},
+ {**episode, "sort_by": "updated_at"},
+ {**episode, "sort_order": "asc"},
+ {**episode, "filters": {}},
+ )
+ for invalid in (*invalid_profiles, *invalid_episodes):
+ assert (
+ _request_rejection(
+ "POST",
+ "/api/v2/memory/get",
+ json.dumps(invalid).encode(),
+ )
+ == "get"
+ )
+
+
def test_sidecar_guard_allows_workbench_attachment_file_uri_only(tmp_path: Path) -> None:
attachments_root = tmp_path / "attachments" / "avibe"
asset = attachments_root / "session-1" / "diagram.png"