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 scoped episode list CLI (#1435)

rkrkrkkc7a409e9dc24
diff --git a/core/internal_server.py b/core/internal_server.py
index e9558a636..d981a5f40 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -1570,6 +1570,160 @@ def create_app(
logger.warning("internal memory search failed")
return JSONResponse(status_code=503, content={"status": "failed", "error": "memory_processing_failed"})
+ @app.post("/internal/memory/list")
+ async def _memory_list(request: Request) -> Any:
+ try:
+ scope = _memory_read_scope(request)
+ except MemoryStoreUnavailableError:
+ return JSONResponse(
+ status_code=503,
+ content={"status": "failed", "error": "memory_store_unavailable"},
+ )
+ if scope is None:
+ return JSONResponse(
+ status_code=403,
+ content={"status": "failed", "error": "memory_access_denied"},
+ )
+ principal_id, _default_project_id = scope
+ 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) - {
+ "project",
+ "page",
+ "limit",
+ "cursor",
+ }:
+ return JSONResponse(
+ status_code=400,
+ content={"status": "failed", "error": "memory_invalid_input"},
+ )
+ from core.memory.http_headers import MEMORY_USER_KEY_HEADER
+ from core.memory.project_ids import (
+ DEFAULT_MEMORY_PROJECT_ID,
+ MEMORY_SEARCH_ALL_PROJECTS,
+ omitted_project_to_default,
+ parse_agent_search_project,
+ parse_ui_search_project,
+ )
+ from core.memory.runtime import MEMORY_LIST_CURSOR_MAX_BYTES
+
+ is_ui = bool(str(request.headers.get(MEMORY_USER_KEY_HEADER) or "").strip())
+ limit = payload.get("limit", 20)
+ try:
+ raw_project = omitted_project_to_default(payload.get("project"))
+ project_id = (
+ parse_ui_search_project(raw_project)
+ if is_ui
+ else parse_agent_search_project(raw_project)
+ )
+ except ValueError:
+ return JSONResponse(
+ status_code=400,
+ content={"status": "failed", "error": "memory_invalid_input"},
+ )
+ if (
+ isinstance(limit, bool)
+ or not isinstance(limit, int)
+ or not 1 <= limit <= 20
+ ):
+ return JSONResponse(
+ status_code=400,
+ content={"status": "failed", "error": "memory_invalid_input"},
+ )
+ if project_id == MEMORY_SEARCH_ALL_PROJECTS:
+ cursor = payload.get("cursor")
+ try:
+ cursor_bytes = (
+ len(cursor.encode("utf-8"))
+ if isinstance(cursor, str)
+ else None
+ )
+ except UnicodeEncodeError:
+ cursor_bytes = MEMORY_LIST_CURSOR_MAX_BYTES + 1
+ if (
+ "page" in payload
+ or (
+ cursor is not None
+ and (
+ not isinstance(cursor, str)
+ or not cursor
+ or cursor_bytes is None
+ or cursor_bytes > MEMORY_LIST_CURSOR_MAX_BYTES
+ )
+ )
+ ):
+ return JSONResponse(
+ status_code=400,
+ content={"status": "failed", "error": "memory_invalid_input"},
+ )
+ try:
+ result = await runtime.list_all_episodes_payload(
+ principal_id,
+ cursor=cursor,
+ limit=limit,
+ )
+ if result == {
+ "status": "failed",
+ "error": "memory_invalid_input",
+ }:
+ return JSONResponse(status_code=400, content=result)
+ return result
+ except Exception:
+ logger.warning("internal aggregate memory list failed")
+ return JSONResponse(
+ status_code=503,
+ content={"status": "failed", "error": "memory_processing_failed"},
+ )
+
+ page = payload.get("page", 1)
+ if (
+ "cursor" in payload
+ or isinstance(page, bool)
+ or not isinstance(page, int)
+ or page < 1
+ ):
+ return JSONResponse(
+ status_code=400,
+ content={"status": "failed", "error": "memory_invalid_input"},
+ )
+ if project_id != DEFAULT_MEMORY_PROJECT_ID:
+ if getattr(runtime, "available", True) is False:
+ return JSONResponse(
+ status_code=503,
+ content={"status": "failed", "error": "memory_store_unavailable"},
+ )
+ try:
+ catalog = await run_blocking(runtime.list_memory_projects, principal_id)
+ except Exception:
+ logger.warning("internal memory project catalog failed")
+ return JSONResponse(
+ status_code=503,
+ content={"status": "failed", "error": "memory_store_unavailable"},
+ )
+ if project_id not in catalog:
+ return JSONResponse(
+ status_code=400,
+ content={"status": "failed", "error": "memory_invalid_input"},
+ )
+ try:
+ return await runtime.list_episodes_payload(
+ principal_id,
+ project_id,
+ page=page,
+ page_size=limit,
+ )
+ except Exception:
+ logger.warning("internal memory list failed")
+ return JSONResponse(
+ status_code=503,
+ content={"status": "failed", "error": "memory_processing_failed"},
+ )
+
@app.post("/internal/memory/remember")
async def _memory_remember(request: Request) -> Any:
scope = _memory_cli_scope(request)
diff --git a/core/memory/module.py b/core/memory/module.py
index 652e31f01..313d56d5f 100644
--- a/core/memory/module.py
+++ b/core/memory/module.py
@@ -876,6 +876,80 @@ class MemoryModule:
) -> MemoryListResult:
"""Return one bounded page of processed episodes or a closed error."""
+ invalid = self._list_request_error(
+ principal_id=principal_id,
+ project_id=project_id,
+ page=page,
+ page_size=page_size,
+ )
+ if invalid is not None:
+ return invalid
+ async with self._lifecycle_lock:
+ return await self._list_episodes_under_lifecycle(
+ principal_id=principal_id,
+ project_id=project_id,
+ page=page,
+ page_size=page_size,
+ )
+
+ @asynccontextmanager
+ async def concurrent_episode_lists(
+ self,
+ *,
+ deadline: float,
+ ) -> AsyncIterator[Callable[..., Awaitable[MemoryListResult]]]:
+ """Fence one aggregate read while allowing its provider calls to overlap."""
+
+ def unavailable(
+ error: MemoryErrorCode,
+ ) -> Callable[..., Awaitable[MemoryListResult]]:
+ async def result(**_kwargs: Any) -> MemoryListResult:
+ return OperationFailed(error=error)
+
+ return result
+
+ if self._clear_active or self._is_maintenance_open():
+ yield unavailable("memory_clear_failed")
+ return
+ remaining = deadline - monotonic()
+ if remaining <= 0:
+ yield unavailable("memory_provider_timeout")
+ return
+ try:
+ await asyncio.wait_for(
+ self._lifecycle_lock.acquire(),
+ timeout=remaining,
+ )
+ except asyncio.TimeoutError:
+ yield unavailable("memory_provider_timeout")
+ return
+ try:
+ if self._clear_active or self._is_maintenance_open():
+ yield unavailable("memory_clear_failed")
+ return
+ try:
+ meta = await self._store_call(self._store.ensure_meta)
+ except Exception:
+ yield unavailable("memory_store_unavailable")
+ return
+ if meta.clear_in_progress:
+ yield unavailable("memory_clear_failed")
+ return
+ if monotonic() >= deadline:
+ yield unavailable("memory_provider_timeout")
+ return
+ yield self._list_episodes_after_store_check
+ finally:
+ self._lifecycle_lock.release()
+
+ def _list_request_error(
+ self,
+ *,
+ principal_id: str,
+ project_id: str,
+ page: int,
+ page_size: int,
+ ) -> OperationFailed | None:
if not self._is_enabled():
return OperationFailed(error="memory_disabled")
if not is_principal_id(principal_id):
@@ -893,24 +967,61 @@ class MemoryModule:
return OperationFailed(error="memory_invalid_input")
if self._clear_active or self._is_maintenance_open():
return OperationFailed(error="memory_clear_failed")
+ return None
- 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,
- )
+ async def _list_episodes_under_lifecycle(
+ self,
+ *,
+ principal_id: str,
+ project_id: str,
+ page: int,
+ page_size: int,
+ ) -> MemoryListResult:
+ invalid = self._list_request_error(
+ principal_id=principal_id,
+ project_id=project_id,
+ page=page,
+ page_size=page_size,
+ )
+ if invalid is not None:
+ return invalid
+ 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")
+ return await self._list_episodes_after_store_check(
+ principal_id=principal_id,
+ project_id=project_id,
+ page=page,
+ page_size=page_size,
+ )
+
+ async def _list_episodes_after_store_check(
+ self,
+ *,
+ principal_id: str,
+ project_id: str,
+ page: int,
+ page_size: int,
+ ) -> MemoryListResult:
+ invalid = self._list_request_error(
+ principal_id=principal_id,
+ project_id=project_id,
+ page=page,
+ page_size=page_size,
+ )
+ if invalid is not None:
+ return invalid
+ 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(
diff --git a/core/memory/runtime.py b/core/memory/runtime.py
index 1c64f70e8..29d7ee925 100644
--- a/core/memory/runtime.py
+++ b/core/memory/runtime.py
@@ -3,7 +3,10 @@
from __future__ import annotations
import asyncio
+import base64
from copy import deepcopy
+import hashlib
+import json
import logging
import os
import stat
@@ -11,7 +14,7 @@ import time
from concurrent.futures import CancelledError as FutureCancelledError
from concurrent.futures import Future as ThreadFuture
from concurrent.futures import TimeoutError as FutureTimeoutError
-from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
+from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Mapping
from contextlib import asynccontextmanager
from dataclasses import asdict, dataclass, replace
from datetime import datetime, timezone
@@ -93,6 +96,9 @@ from core.memory.types import (
MemoryItem,
MemoryItems,
MemoryListPage,
+ MemoryListItem,
+ MemoryListResult,
+ MemoryListWarningCode,
MemoryResult,
MemoryWarningCode,
OperationFailed,
@@ -115,6 +121,25 @@ ARTIFACT_ACTIVATION_TIMEOUT_SECONDS = 90.0
_CALL_LOG_RETENTION_INTERVAL_SECONDS = 6 * 60 * 60
_RECORDER_DISABLED = {"state": "disabled", "reason": None}
_RECORDER_DEGRADED = {"state": "degraded", "reason": "writer_failures"}
+_MEMORY_LIST_CURSOR_VERSION = 3
+MEMORY_LIST_CURSOR_MAX_BYTES = 8192
+_MEMORY_LIST_PROVIDER_PAGE_SIZE = 20
+_MEMORY_LIST_PROVIDER_MAX_PAGE = 1_000_000
+_MEMORY_LIST_AGGREGATE_TIMEOUT_SECONDS = 20.0
+
+
+@asynccontextmanager
+async def _concurrent_episode_lists(
+ module: MemoryModule,
+ *,
+ deadline: float,
+) -> AsyncIterator[Callable[..., Awaitable[MemoryListResult]]]:
+ batch = getattr(module, "concurrent_episode_lists", None)
+ if batch is None:
+ yield module.list_episodes
+ return
+ async with batch(deadline=deadline) as list_episodes:
+ yield list_episodes
@dataclass(frozen=True, slots=True)
@@ -1469,6 +1494,451 @@ class MemoryRuntime:
return memory_list_page_payload(result)
return {"status": "failed", "error": "memory_processing_failed"}
+ async def list_all_episodes_payload(
+ self,
+ principal_id: str,
+ *,
+ cursor: str | None,
+ limit: int = 20,
+ ) -> dict[str, Any]:
+ """Merge this principal's project pages behind an Avibe cursor."""
+
+ if not self.available:
+ return {"status": "failed", "error": "memory_store_unavailable"}
+ if (
+ not is_principal_id(principal_id)
+ or isinstance(limit, bool)
+ or not isinstance(limit, int)
+ or not 1 <= limit <= _MEMORY_LIST_PROVIDER_PAGE_SIZE
+ ):
+ return {"status": "failed", "error": "memory_invalid_input"}
+ try:
+ projects = await run_blocking(self.list_memory_projects, principal_id)
+ except Exception:
+ return {"status": "failed", "error": "memory_store_unavailable"}
+ if not projects:
+ projects = (DEFAULT_MEMORY_PROJECT_ID,)
+ projects = tuple(sorted(projects))
+ fingerprint = _memory_list_catalog_fingerprint(principal_id, projects)
+ try:
+ boundaries, page_hints, total_hints = _decode_memory_list_cursor(
+ cursor,
+ projects=projects,
+ fingerprint=fingerprint,
+ )
+ except ValueError:
+ return {"status": "failed", "error": "memory_invalid_input"}
+
+ deadline = time.monotonic() + _MEMORY_LIST_AGGREGATE_TIMEOUT_SECONDS
+ candidates: list[MemoryListItem] = []
+ warnings: list[MemoryListWarningCode] = []
+ totals: dict[str, int] = {}
+ failures: list[OperationFailed] = []
+ available_counts: dict[str, int] = {}
+ project_has_more: dict[str, bool] = {}
+ candidate_page_hints: dict[tuple[str, str], int] = {}
+ complete = True
+ async with _concurrent_episode_lists(
+ self.module,
+ deadline=deadline,
+ ) as list_episodes:
+ project_windows = await asyncio.gather(
+ *(
+ self._list_project_window(
+ principal_id,
+ project_id,
+ list_episodes=list_episodes,
+ boundary=boundaries[project_id],
+ page_hint=page_hints[project_id],
+ total_hint=total_hints[project_id],
+ limit=limit,
+ deadline=deadline,
+ )
+ for project_id in projects
+ )
+ )
+ for project_id, window in zip(projects, project_windows):
+ if isinstance(window, OperationFailed):
+ complete = False
+ failures.append(window)
+ warning: MemoryListWarningCode = (
+ "memory_list_truncated"
+ if window.error == "memory_provider_timeout"
+ else "memory_list_partial"
+ )
+ warnings.append(warning)
+ continue
+ (
+ items,
+ total_count,
+ project_warnings,
+ has_more,
+ window_complete,
+ item_page_hints,
+ ) = window
+ candidates.extend(items)
+ candidate_page_hints.update(
+ ((project_id, item.id), item_page_hints[item.id])
+ for item in items
+ )
+ totals[project_id] = total_count
+ available_counts[project_id] = len(items)
+ project_has_more[project_id] = has_more
+ warnings.extend(project_warnings)
+ if not window_complete:
+ complete = False
+
+ if not totals and failures:
+ failure = next(
+ (
+ item
+ for item in failures
+ if item.error == "memory_provider_timeout"
+ ),
+ failures[0],
+ )
+ return {"status": failure.status, "error": failure.error}
+
+ ordered = sorted(candidates, key=lambda item: (item.project, item.id))
+ ordered.sort(
+ key=lambda item: _memory_list_instant(item.timestamp),
+ reverse=True,
+ )
+ selected = tuple(ordered[:limit])
+ next_boundaries = dict(boundaries)
+ next_page_hints = dict(page_hints)
+ next_total_hints = dict(total_hints)
+ selected_counts = {project_id: 0 for project_id in projects}
+ for item in selected:
+ selected_counts[item.project] += 1
+ next_boundaries[item.project] = (item.timestamp, item.id)
+ next_page_hints[item.project] = candidate_page_hints[(item.project, item.id)]
+ next_total_hints[item.project] = totals[item.project]
+
+ has_more = any(
+ project_has_more[project_id]
+ or selected_counts[project_id] < available_counts[project_id]
+ for project_id in totals
+ )
+ if not complete:
+ has_more = True
+ next_cursor = (
+ _encode_memory_list_cursor(
+ fingerprint,
+ next_boundaries,
+ next_page_hints,
+ next_total_hints,
+ )
+ if has_more
+ else None
+ )
+ return {
+ "status": "ok",
+ "items": memory_list_page_payload(
+ MemoryListPage(
+ items=selected,
+ page=1,
+ page_size=limit,
+ count=len(selected),
+ total_count=sum(totals.values()),
+ )
+ )["items"],
+ "count": len(selected),
+ "total_count": sum(totals.values()) if complete else None,
+ "warnings": list(dict.fromkeys(warnings)),
+ "next_cursor": next_cursor,
+ }
+
+ async def _list_project_window(
+ self,
+ principal_id: str,
+ project_id: str,
+ *,
+ list_episodes: Callable[..., Awaitable[MemoryListResult]],
+ boundary: tuple[str, str] | None,
+ page_hint: int,
+ total_hint: int | None,
+ limit: int,
+ deadline: float,
+ ) -> (
+ tuple[
+ tuple[MemoryListItem, ...],
+ int,
+ tuple[MemoryListWarningCode, ...],
+ bool,
+ bool,
+ dict[str, int],
+ ]
+ | OperationFailed
+ ):
+ page = 1
+ items_by_id: dict[str, MemoryListItem] = {}
+ item_page_hints: dict[str, int] = {}
+ timestamp_page_hints: dict[datetime, int] = {}
+ warnings: list[MemoryListWarningCode] = []
+ total_count: int | None = None
+ previous_page: tuple[int, MemoryListPage] | None = None
+ open_timestamp: datetime | None = None
+ boundary_instant = (
+ _memory_list_instant(boundary[0])
+ if boundary is not None
+ else None
+ )
+ boundary_group_page_hint = page_hint
+
+ def retry_result(error: str, observed_total: int):
+ warning: MemoryListWarningCode = (
+ "memory_list_truncated"
+ if error == "memory_provider_timeout"
+ else "memory_list_partial"
+ )
+ return (
+ (),
+ observed_total,
+ tuple(dict.fromkeys((*warnings, warning))),
+ True,
+ False,
+ {},
+ )
+
+ async def read_page(page_number: int) -> MemoryListResult:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ return OperationFailed(error="memory_provider_timeout")
+ try:
+ return await asyncio.wait_for(
+ list_episodes(
+ principal_id=principal_id,
+ project_id=project_id,
+ page=page_number,
+ page_size=_MEMORY_LIST_PROVIDER_PAGE_SIZE,
+ ),
+ timeout=remaining,
+ )
+ except asyncio.TimeoutError:
+ return OperationFailed(error="memory_provider_timeout")
+
+ def failure_result(error):
+ if not items_by_id:
+ return OperationFailed(error=error)
+ ordered = _order_project_memory_list_items(items_by_id.values())
+ safe = tuple(
+ item
+ for item in ordered
+ if open_timestamp is not None
+ and _memory_list_instant(item.timestamp) > open_timestamp
+ )
+ warning: MemoryListWarningCode = (
+ "memory_list_truncated"
+ if error == "memory_provider_timeout"
+ else "memory_list_partial"
+ )
+ return (
+ safe[:limit],
+ total_count or 0,
+ tuple(dict.fromkeys((*warnings, warning))),
+ True,
+ False,
+ {
+ item.id: item_page_hints[item.id]
+ for item in safe[:limit]
+ },
+ )
+
+ async def locate_boundary_page() -> tuple[int | None, int] | OperationFailed:
+ first = await read_page(page_hint)
+ if isinstance(first, OperationFailed):
+ return first
+ warnings.extend(first.warnings)
+ observed_total = first.total_count
+ if observed_total == 0:
+ return (1, 0)
+ last_page = (
+ observed_total + _MEMORY_LIST_PROVIDER_PAGE_SIZE - 1
+ ) // _MEMORY_LIST_PROVIDER_PAGE_SIZE
+ probes = {page_hint: first}
+
+ async def probe(page_number: int) -> MemoryListPage | OperationFailed | None:
+ cached = probes.get(page_number)
+ if cached is not None:
+ return cached
+ result = await read_page(page_number)
+ if isinstance(result, OperationFailed):
+ return result
+ warnings.extend(result.warnings)
+ if result.total_count != observed_total:
+ return None
+ probes[page_number] = result
+ return result
+
+ pivot = min(page_hint, last_page)
+ pivot_result = await probe(pivot)
+ if isinstance(pivot_result, OperationFailed):
+ return pivot_result
+ if pivot_result is None:
+ return (None, observed_total)
+
+ def crosses_boundary(result: MemoryListPage) -> bool:
+ return bool(result.items) and min(
+ _memory_list_instant(item.timestamp)
+ for item in result.items
+ ) <= boundary_instant
+
+ if crosses_boundary(pivot_result):
+ low, high = 1, pivot
+ else:
+ low, high = pivot + 1, last_page + 1
+ while low < high:
+ middle = (low + high) // 2
+ if middle == last_page + 1:
+ high = middle
+ continue
+ middle_result = await probe(middle)
+ if isinstance(middle_result, OperationFailed):
+ return middle_result
+ if middle_result is None:
+ return (None, observed_total)
+ if crosses_boundary(middle_result):
+ high = middle
+ else:
+ low = middle + 1
+ for page_number, snapshot in tuple(probes.items()):
+ refreshed = await read_page(page_number)
+ if isinstance(refreshed, OperationFailed):
+ return refreshed
+ warnings.extend(refreshed.warnings)
+ if refreshed != snapshot:
+ return (None, refreshed.total_count)
+ return (low, observed_total)
+
+ if boundary_instant is not None:
+ location = await locate_boundary_page()
+ if isinstance(location, OperationFailed):
+ return failure_result(location.error)
+ boundary_page, observed_total = location
+ if boundary_page is None:
+ return retry_result("memory_list_partial", observed_total)
+ boundary_group_page_hint = max(
+ 1,
+ min(
+ boundary_page,
+ (
+ observed_total + _MEMORY_LIST_PROVIDER_PAGE_SIZE - 1
+ )
+ // _MEMORY_LIST_PROVIDER_PAGE_SIZE,
+ ),
+ )
+ page = max(1, boundary_page - 1)
+
+ while True:
+ result = await read_page(page)
+ if isinstance(result, OperationFailed):
+ return failure_result(result.error)
+ if (
+ total_count is None
+ and page > 1
+ and (page - 1) * _MEMORY_LIST_PROVIDER_PAGE_SIZE
+ >= result.total_count
+ ):
+ last_page = max(
+ 1,
+ (
+ result.total_count
+ + _MEMORY_LIST_PROVIDER_PAGE_SIZE
+ - 1
+ )
+ // _MEMORY_LIST_PROVIDER_PAGE_SIZE,
+ )
+ page = max(1, last_page - 1)
+ boundary_group_page_hint = min(
+ boundary_group_page_hint,
+ last_page,
+ )
+ warnings.extend(result.warnings)
+ continue
+ if total_count is not None and result.total_count != total_count:
+ warnings.extend(result.warnings)
+ return retry_result("memory_list_partial", result.total_count)
+ if previous_page is not None:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ return retry_result(
+ "memory_provider_timeout",
+ result.total_count,
+ )
+ previous_page_number, previous_page_result = previous_page
+ try:
+ refreshed_previous = await asyncio.wait_for(
+ list_episodes(
+ principal_id=principal_id,
+ project_id=project_id,
+ page=previous_page_number,
+ page_size=_MEMORY_LIST_PROVIDER_PAGE_SIZE,
+ ),
+ timeout=remaining,
+ )
+ except asyncio.TimeoutError:
+ return retry_result(
+ "memory_provider_timeout",
+ result.total_count,
+ )
+ if isinstance(refreshed_previous, OperationFailed):
+ return retry_result(
+ refreshed_previous.error,
+ result.total_count,
+ )
+ if refreshed_previous != previous_page_result:
+ warnings.extend(refreshed_previous.warnings)
+ return retry_result("memory_list_partial", result.total_count)
+ total_count = result.total_count
+ warnings.extend(result.warnings)
+ if boundary_instant is not None:
+ timestamp_page_hints[boundary_instant] = boundary_group_page_hint
+ for item in result.items:
+ if item.id not in items_by_id and _memory_list_after_boundary(
+ item,
+ boundary,
+ ):
+ items_by_id[item.id] = item
+ instant = _memory_list_instant(item.timestamp)
+ group_page = timestamp_page_hints.setdefault(instant, page)
+ item_page_hints[item.id] = group_page
+
+ ordered = _order_project_memory_list_items(items_by_id.values())
+ exhausted = (
+ result.count < _MEMORY_LIST_PROVIDER_PAGE_SIZE
+ or page * _MEMORY_LIST_PROVIDER_PAGE_SIZE >= total_count
+ )
+ if exhausted:
+ break
+ if len(ordered) > limit and result.items:
+ cutoff = _memory_list_instant(ordered[limit - 1].timestamp)
+ oldest_in_page = min(
+ _memory_list_instant(item.timestamp)
+ for item in result.items
+ )
+ if oldest_in_page < cutoff:
+ break
+ if result.items:
+ open_timestamp = min(
+ _memory_list_instant(item.timestamp)
+ for item in result.items
+ )
+ previous_page = (page, result)
+ page += 1
+ ordered = _order_project_memory_list_items(items_by_id.values())
+ return (
+ tuple(ordered[:limit]),
+ total_count or 0,
+ tuple(dict.fromkeys(warnings)),
+ len(ordered) > limit,
+ True,
+ {
+ item.id: item_page_hints[item.id]
+ for item in ordered[:limit]
+ },
+ )
+
def list_memory_projects(self, principal_id: str) -> tuple[str, ...]:
if not self.available:
return (DEFAULT_MEMORY_PROJECT_ID,)
@@ -3348,3 +3818,213 @@ def _merge_search_items(items: list[MemoryItem], *, limit: int) -> tuple[MemoryI
if len(merged) >= limit:
break
return tuple(merged)
+
+
+def _memory_list_catalog_fingerprint(
+ principal_id: str,
+ projects: tuple[str, ...],
+) -> str:
+ material = json.dumps(
+ {
+ "principal": principal_id,
+ "projects": list(projects),
+ "sort": "timestamp:desc,project:id:asc",
+ },
+ ensure_ascii=True,
+ separators=(",", ":"),
+ sort_keys=True,
+ ).encode("ascii")
+ return hashlib.sha256(material).hexdigest()
+
+
+def _encode_memory_list_cursor(
+ fingerprint: str,
+ boundaries: dict[str, tuple[str, str] | None],
+ page_hints: dict[str, int],
+ total_hints: dict[str, int | None],
+) -> str:
+ if (
+ set(page_hints) != set(boundaries)
+ or set(total_hints) != set(boundaries)
+ or any(
+ isinstance(page_hint, bool)
+ or not isinstance(page_hint, int)
+ or not 1 <= page_hint <= _MEMORY_LIST_PROVIDER_MAX_PAGE
+ or (boundaries[project_id] is None and page_hint != 1)
+ for project_id, page_hint in page_hints.items()
+ )
+ or any(
+ (boundary is None and total_hints[project_id] is not None)
+ or (
+ boundary is not None
+ and (
+ isinstance(total_hints[project_id], bool)
+ or not isinstance(total_hints[project_id], int)
+ or total_hints[project_id] < 0
+ )
+ )
+ for project_id, boundary in boundaries.items()
+ )
+ ):
+ raise ValueError("invalid Memory list page hints")
+ encoded_boundaries = {
+ project_id: (
+ {
+ "t": boundary[0],
+ "i": _encode_memory_list_boundary_id(boundary[1]),
+ "p": page_hints[project_id],
+ "n": total_hints[project_id],
+ }
+ if boundary is not None
+ else None
+ )
+ for project_id, boundary in boundaries.items()
+ }
+ raw = json.dumps(
+ {
+ "v": _MEMORY_LIST_CURSOR_VERSION,
+ "f": fingerprint,
+ "b": encoded_boundaries,
+ },
+ ensure_ascii=True,
+ separators=(",", ":"),
+ sort_keys=True,
+ ).encode("ascii")
+ token = base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
+ if len(token.encode("ascii")) > MEMORY_LIST_CURSOR_MAX_BYTES:
+ raise ValueError("Memory list cursor is too large")
+ return token
+
+
+def _decode_memory_list_cursor(
+ cursor: str | None,
+ *,
+ projects: tuple[str, ...],
+ fingerprint: str,
+) -> tuple[
+ dict[str, tuple[str, str] | None],
+ dict[str, int],
+ dict[str, int | None],
+]:
+ if cursor is None:
+ return (
+ {project_id: None for project_id in projects},
+ {project_id: 1 for project_id in projects},
+ {project_id: None for project_id in projects},
+ )
+ if (
+ not isinstance(cursor, str)
+ or not cursor
+ or len(cursor.encode("utf-8")) > MEMORY_LIST_CURSOR_MAX_BYTES
+ ):
+ raise ValueError("invalid Memory list cursor")
+ try:
+ padding = "=" * (-len(cursor) % 4)
+ raw = base64.b64decode(
+ cursor + padding,
+ altchars=b"-_",
+ validate=True,
+ )
+ payload = json.loads(raw)
+ except (UnicodeEncodeError, ValueError, TypeError, json.JSONDecodeError):
+ raise ValueError("invalid Memory list cursor") from None
+ if (
+ not isinstance(payload, dict)
+ or set(payload) != {"v", "f", "b"}
+ or payload.get("v") != _MEMORY_LIST_CURSOR_VERSION
+ or payload.get("f") != fingerprint
+ or not isinstance(payload.get("b"), dict)
+ or set(payload["b"]) != set(projects)
+ ):
+ raise ValueError("invalid Memory list cursor")
+ boundaries: dict[str, tuple[str, str] | None] = {}
+ page_hints: dict[str, int] = {}
+ total_hints: dict[str, int | None] = {}
+ for project_id in projects:
+ value = payload["b"][project_id]
+ if value is None:
+ boundaries[project_id] = None
+ page_hints[project_id] = 1
+ total_hints[project_id] = None
+ continue
+ if (
+ not isinstance(value, dict)
+ or set(value) != {"t", "i", "p", "n"}
+ or not isinstance(value.get("t"), str)
+ or len(value["t"]) > 64
+ or isinstance(value.get("p"), bool)
+ or not isinstance(value.get("p"), int)
+ or not 1 <= value["p"] <= _MEMORY_LIST_PROVIDER_MAX_PAGE
+ or isinstance(value.get("n"), bool)
+ or not isinstance(value.get("n"), int)
+ or value["n"] < 0
+ ):
+ raise ValueError("invalid Memory list cursor")
+ try:
+ _memory_list_instant(value["t"])
+ boundary_id = _decode_memory_list_boundary_id(value.get("i"))
+ except ValueError:
+ raise ValueError("invalid Memory list cursor") from None
+ boundaries[project_id] = (value["t"], boundary_id)
+ page_hints[project_id] = value["p"]
+ total_hints[project_id] = value["n"]
+ return boundaries, page_hints, total_hints
+
+
+def _encode_memory_list_boundary_id(value: str) -> str:
+ try:
+ raw = value.encode("utf-8")
+ except UnicodeEncodeError:
+ raise ValueError("invalid Memory list boundary ID") from None
+ if not raw or len(raw) > 128 or "\x00" in value:
+ raise ValueError("invalid Memory list boundary ID")
+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
+
+
+def _decode_memory_list_boundary_id(value: object) -> str:
+ if not isinstance(value, str) or not value or len(value) > 171:
+ raise ValueError("invalid Memory list boundary ID")
+ try:
+ padding = "=" * (-len(value) % 4)
+ raw = base64.b64decode(
+ value + padding,
+ altchars=b"-_",
+ validate=True,
+ )
+ decoded = raw.decode("utf-8")
+ except (UnicodeDecodeError, UnicodeEncodeError, ValueError):
+ raise ValueError("invalid Memory list boundary ID") from None
+ if _encode_memory_list_boundary_id(decoded) != value:
+ raise ValueError("invalid Memory list boundary ID")
+ return decoded
+
+
+def _memory_list_instant(value: str) -> datetime:
+ instant = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ if instant.tzinfo is None:
+ raise ValueError("invalid Memory list timestamp")
+ return instant.astimezone(timezone.utc)
+
+
+def _order_project_memory_list_items(
+ items: Iterable[MemoryListItem],
+) -> list[MemoryListItem]:
+ ordered = sorted(items, key=lambda item: item.id)
+ ordered.sort(
+ key=lambda item: _memory_list_instant(item.timestamp),
+ reverse=True,
+ )
+ return ordered
+
+
+def _memory_list_after_boundary(
+ item: MemoryListItem,
+ boundary: tuple[str, str] | None,
+) -> bool:
+ if boundary is None:
+ return True
+ item_instant = _memory_list_instant(item.timestamp)
+ boundary_instant = _memory_list_instant(boundary[0])
+ return item_instant < boundary_instant or (
+ item_instant == boundary_instant and item.id > boundary[1]
+ )
diff --git a/docs/CLI.md b/docs/CLI.md
index 19720ac3a..1c264b959 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -123,15 +123,25 @@ vibe status
Read scoped local Memory or queue durable context to remember — facts the user explicitly asked to save, and conclusions the Agent distills on its own from the conversation and from work on this machine, including lasting environment or account facts it meets in files or tool output — through the existing mode-0600 controller socket. This command does not start a service and has no clear, configuration, export, or delete subcommands.
-`status` works from a normal terminal. `profile`, `search`, and `remember` require an eligible Agent shell where Avibe has injected the current Session context; running them from a normal terminal returns `memory_access_denied`.
+`status` works from a normal terminal. `profile`, `list`, `search`, and `remember`
+require an eligible Agent shell where Avibe has injected the current Session
+context; running them from a normal terminal returns `memory_access_denied`.
```bash
vibe memory status [--json]
vibe memory profile [--json]
+vibe memory list [--project <slug>] [--page N] [--limit 1..20] [--json]
vibe memory search <query> [--project <slug>] [--mode {hybrid|keyword|vector|agentic}] [--limit 1..20] [--json]
vibe memory remember <text> [--project <slug>] [--json]
```
+List returns valid processed episodes newest first. It uses EverOS's exact
+1-based page semantics, defaults to 20 episodes per page, and exposes each
+episode's opaque entry id in JSON. The Agent CLI accepts `default` or one
+catalogued named project; `--project all` is reserved for the Settings UI.
+Listing is an explicit inspection command and is not added to the injected
+Personal Memory prompt.
+
Search defaults to `--mode hybrid` with `--limit 8`. Use `keyword` for exact
terms, `vector` for semantic matches, and reserve `agentic` for complex,
multi-hop recall. Agentic searches are bounded to 30 seconds and require the
diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.md
index ebae05074..93d771157 100644
--- a/docs/CLI_ZH.md
+++ b/docs/CLI_ZH.md
@@ -104,15 +104,23 @@ vibe status
通过现有 mode-0600 控制器 socket 读取当前范围内的本地记忆,或提交需要记住的长期内容——既包括用户明确要求保存的内容,也包括 Agent 从对话以及在本机工作中主动提炼的结论(含在文件或工具输出中遇到的持久环境、账户事实)。该命令不会启动服务,也没有清空、配置、导出或删除子命令。
-`status` 可在普通终端中使用。`profile`、`search` 和 `remember` 必须在 Avibe 已注入当前 Session 上下文的合规 Agent shell 中运行;从普通终端运行会返回 `memory_access_denied`。
+`status` 可在普通终端中使用。`profile`、`list`、`search` 和 `remember` 必须在
+Avibe 已注入当前 Session 上下文的合规 Agent shell 中运行;从普通终端运行会返回
+`memory_access_denied`。
```bash
vibe memory status [--json]
vibe memory profile [--json]
+vibe memory list [--project <slug>] [--page N] [--limit 1..20] [--json]
vibe memory search <查询> [--project <slug>] [--limit 1..20] [--json]
vibe memory remember <文本> [--project <slug>] [--json]
```
+`list` 按时间倒序返回有效且已处理的事件。页码严格采用 EverOS 从 1 开始的语义,每页
+默认 20 条;JSON 会包含每条事件的不透明 entry id。Agent CLI 只接受 `default` 或目录中
+已有的具名项目,`--project all` 仅供设置页使用。该命令用于显式检查,不会加入注入的
+个人记忆 prompt。
+
### `vibe doctor`
运行配置诊断检查。
diff --git a/docs/MEMORY.md b/docs/MEMORY.md
index e707fd282..ed9c90dae 100644
--- a/docs/MEMORY.md
+++ b/docs/MEMORY.md
@@ -14,6 +14,18 @@ Avibe Memory distills eligible Workbench and private-IM messages into a
per-user profile, episodes, and facts. Open **Settings > Memory** to inspect its
Processing Record, current profile, search results, and settings.
+## Processed episode listing
+
+`vibe memory list` reads only valid, active processed episodes for the current
+scoped principal and project. It does not include profiles, agent memories,
+atomic facts, unprocessed messages, or superseded episodes. Single-project
+reads use EverOS's 1-based pages and fixed newest-first order. The verified
+Settings UI may aggregate the same principal's projects through a bounded,
+versioned Avibe cursor; the Agent CLI cannot request `all`. JSON preserves the
+provider's opaque entry id as a future inspection handle. Listing does not add
+Search/Get payloads to provider diagnostics and does not invoke LLM, embedding,
+or reranking providers.
+
## Optional reranking endpoint
The third processing endpoint in **Settings > Memory** is optional. Configure
diff --git a/docs/MEMORY_ZH.md b/docs/MEMORY_ZH.md
index bd910d3dc..77684152c 100644
--- a/docs/MEMORY_ZH.md
+++ b/docs/MEMORY_ZH.md
@@ -3,6 +3,15 @@
Avibe 记忆会把符合条件的 Workbench 和私聊消息提炼为按用户隔离的画像、事件与事实。
在**设置 > 记忆**中可以查看状态、当前画像、搜索结果、设置和处理日志。
+## 已处理事件列表
+
+`vibe memory list` 只读取当前范围内用户和项目的有效、活跃、已处理事件,不包含画像、
+Agent 记忆、原子事实、未处理消息或已被取代的事件。单项目读取严格使用 EverOS 从 1
+开始的页码,并固定按时间倒序排列。经过验证的设置页可通过 Avibe 生成的有界、带版本
+cursor 聚合同一用户的多个项目;Agent CLI 不能请求 `all`。JSON 会保留提供方的不透明
+entry id,作为未来检查入口。列表读取不会把 Search/Get 负载写入提供方诊断,也不会调用
+LLM、Embedding 或重排序服务。
+
## 处理预检与可选重排序端点
确认更改 Embedding 端点标识或重试待处理的重建前,Avibe 会分别执行一次有界的聊天
diff --git a/docs/plans/memory-list-1427.md b/docs/plans/memory-list-1427.md
index 3764ad7e1..70bf95c45 100644
--- a/docs/plans/memory-list-1427.md
+++ b/docs/plans/memory-list-1427.md
@@ -17,7 +17,10 @@ EverOS dictionaries or broaden the existing profile lookup.
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.
+ timestamp/opaque-id boundaries, provider-page hints, observed-total hints, and
+ a principal-bound project-catalog fingerprint. Continuations locate the current
+ boundary timestamp with revalidated provider-page probes, so inserts and deletes
+ do not turn page offsets into replay or skip positions. 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
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index 6533cb5db..5bf1773a4 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -53,6 +53,18 @@ capabilities:
- tests/test_memory_project_ids.py
- tests/test_memory_sidecar.py
- tests/test_ui_memory_routes.py
+ - id: memory_list
+ name: Scoped processed Memory episode listing
+ status: active
+ catalog: tests/scenarios/memory_list/catalog.yaml
+ observations: tests/scenarios/memory_list/observations.yaml
+ scenario_tests:
+ - tests/scenarios/memory_list/test_memory_list_scenarios.py
+ unit_or_contract_tests:
+ - tests/test_memory_runtime.py
+ - tests/test_internal_server.py
+ - tests/test_internal_client.py
+ - tests/test_memory_cli.py
- id: memory_repair
name: Live Memory index repair via admitted artifact sync
status: active
diff --git a/tests/scenarios/memory_list/catalog.yaml b/tests/scenarios/memory_list/catalog.yaml
new file mode 100644
index 000000000..3756aa947
--- /dev/null
+++ b/tests/scenarios/memory_list/catalog.yaml
@@ -0,0 +1,43 @@
+version: 1
+capability:
+ id: memory_list
+ name: Scoped processed Memory episode listing
+ canonical_tests:
+ - tests/scenarios/memory_list/test_memory_list_scenarios.py
+ - tests/test_memory_runtime.py
+ - tests/test_internal_server.py
+ - tests/test_memory_cli.py
+status_legend:
+ covered: executable evidence exists
+ partial: contract coverage exists
+scenarios:
+ - id: MEMORY-LIST-001
+ name: Captured processed episodes are returned through the scoped CLI list
+ status: covered
+ kind: happy_path
+ layer: scenario
+ test: tests/scenarios/memory_list/test_memory_list_scenarios.py::test_captured_processed_episodes_list_through_cli_with_exact_page_boundary
+ - id: MEMORY-LIST-002
+ name: A named project list excludes episodes captured in other projects
+ status: covered
+ kind: authorization
+ layer: scenario
+ test: tests/scenarios/memory_list/test_memory_list_scenarios.py::test_captured_processed_episodes_list_through_cli_with_exact_page_boundary
+ - id: MEMORY-LIST-003
+ name: Settings all is principal-scoped and Agent CLI all is rejected
+ status: covered
+ kind: authorization
+ layer: contract
+ test: tests/test_internal_server.py::test_memory_list_all_is_available_only_to_signed_ui_principal
+ - id: MEMORY-LIST-004
+ name: Exact 1-based page boundary preserves newest-first order
+ status: covered
+ kind: boundary
+ layer: scenario
+ test: tests/scenarios/memory_list/test_memory_list_scenarios.py::test_captured_processed_episodes_list_through_cli_with_exact_page_boundary
+ - id: MEMORY-LIST-005
+ name: Aggregate project failures return partial data without an invented total
+ status: covered
+ kind: degradation
+ layer: contract
+ test: tests/test_memory_runtime.py::test_list_all_episodes_marks_partial_results_and_omits_total
diff --git a/tests/scenarios/memory_list/observations.yaml b/tests/scenarios/memory_list/observations.yaml
new file mode 100644
index 000000000..cf2244af8
--- /dev/null
+++ b/tests/scenarios/memory_list/observations.yaml
@@ -0,0 +1,17 @@
+version: 1
+capability: memory_list
+observations:
+ - id: MEMORY-LIST-OBS-001
+ scenarios:
+ - MEMORY-LIST-001
+ - MEMORY-LIST-002
+ - MEMORY-LIST-004
+ observation: The hermetic provider derives only extracted episodes from real module captures, and the public CLI reads two exact pages from one named project.
+ - id: MEMORY-LIST-OBS-002
+ scenarios:
+ - MEMORY-LIST-003
+ observation: The controller selects the UI or Agent project parser only after validating the caller scope; only the signed UI parser admits all.
+ - id: MEMORY-LIST-OBS-003
+ scenarios:
+ - MEMORY-LIST-005
+ observation: Aggregate reads retain healthy project items while surfacing a closed warning and nullable total when another project fails.
diff --git a/tests/scenarios/memory_list/test_memory_list_scenarios.py b/tests/scenarios/memory_list/test_memory_list_scenarios.py
new file mode 100644
index 000000000..374228356
--- /dev/null
+++ b/tests/scenarios/memory_list/test_memory_list_scenarios.py
@@ -0,0 +1,143 @@
+"""Closed-loop scenario evidence for processed Memory episode listing."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from collections import deque
+from datetime import datetime, timezone
+
+from core.caller_context import AVIBE_SESSION_ID_ENV
+from core.memory.everos import AddAck, FakeMemoryProvider
+from core.memory.module import MIN_FREE_DISK_BYTES, MemoryModule
+from core.memory.runtime import MemoryRuntime
+from core.memory.store import MemoryStore
+from core.memory.types import CaptureAccepted, CaptureRequest, MemoryListItem, MemoryListPage
+from vibe import cli, internal_client
+
+
+PRINCIPAL = "u-11111111111111111111111111111111"
+
+
+class _CapturedEpisodeProvider(FakeMemoryProvider):
+ 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))
+ matching = sorted(
+ (
+ capture
+ for capture in self.captures
+ if capture.session_ref.principal_id == principal_id
+ and capture.session_ref.project_ref == project_id
+ ),
+ key=lambda capture: capture.provider_timestamp_ms,
+ reverse=True,
+ )
+ start = (page - 1) * page_size
+ selected = matching[start : start + page_size]
+ items = tuple(
+ MemoryListItem(
+ id=f"episode-{capture.provider_timestamp_ms}",
+ subject=capture.text,
+ summary="",
+ body=capture.text,
+ timestamp=datetime.fromtimestamp(
+ capture.provider_timestamp_ms / 1000,
+ tz=timezone.utc,
+ )
+ .isoformat()
+ .replace("+00:00", "Z"),
+ project=project_id,
+ )
+ for capture in selected
+ )
+ return MemoryListPage(
+ items=items,
+ page=page,
+ page_size=page_size,
+ count=len(items),
+ total_count=len(matching),
+ )
+
+
+def test_captured_processed_episodes_list_through_cli_with_exact_page_boundary(
+ tmp_path,
+ monkeypatch,
+ capsys,
+) -> None:
+ """Scenarios: MEMORY-LIST-001, MEMORY-LIST-002, MEMORY-LIST-004."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe-home"))
+ provider = _CapturedEpisodeProvider(
+ add_results=deque(
+ AddAck(request_id=f"add-{index}", status="extracted")
+ for index in range(4)
+ )
+ )
+ effective_home = tmp_path / "avibe-home"
+ effective_home.mkdir(mode=0o700)
+ module = MemoryModule(
+ MemoryStore(effective_home / "state" / "memory.sqlite"),
+ provider,
+ enabled=True,
+ disk_free_bytes=lambda: MIN_FREE_DISK_BYTES,
+ effective_home=effective_home,
+ )
+
+ async def _capture_and_process() -> None:
+ requests = (
+ CaptureRequest("notes-1", "session", PRINCIPAL, "notes", "user_input", "old", 1_000),
+ CaptureRequest("notes-2", "session", PRINCIPAL, "notes", "user_input", "middle", 2_000),
+ CaptureRequest("notes-3", "session", PRINCIPAL, "notes", "user_input", "new", 3_000),
+ CaptureRequest("default-1", "session", PRINCIPAL, "default", "user_input", "foreign", 4_000),
+ )
+ for request in requests:
+ assert await module.capture(request) == CaptureAccepted()
+ assert await module.drain() == 4
+
+ asyncio.run(_capture_and_process())
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = module
+ runtime._retired = False
+ monkeypatch.setenv(AVIBE_SESSION_ID_ENV, "ses-memory-list-scenario")
+
+ def list_sync(*, project, page, limit, caller_session_id):
+ assert caller_session_id == "ses-memory-list-scenario"
+ return {
+ "status_code": 200,
+ "body": asyncio.run(
+ runtime.list_episodes_payload(
+ PRINCIPAL,
+ project,
+ page=page,
+ page_size=limit,
+ )
+ ),
+ }
+
+ monkeypatch.setattr(internal_client, "memory_list_sync", list_sync)
+
+ first_args = cli.build_parser().parse_args(
+ ["memory", "list", "--project", "notes", "--limit", "2", "--page", "1", "--json"]
+ )
+ assert cli.cmd_memory(first_args) == 0
+ first = json.loads(capsys.readouterr().out)["result"]
+
+ second_args = cli.build_parser().parse_args(
+ ["memory", "list", "--project", "notes", "--limit", "2", "--page", "2", "--json"]
+ )
+ assert cli.cmd_memory(second_args) == 0
+ second = json.loads(capsys.readouterr().out)["result"]
+
+ assert [item["subject"] for item in first["items"]] == ["new", "middle"]
+ assert [item["subject"] for item in second["items"]] == ["old"]
+ assert first["total_count"] == second["total_count"] == 3
+ assert first["count"] == 2
+ assert second["count"] == 1
+ assert all(item["project"] == "notes" for item in first["items"] + second["items"])
+ assert all(item["subject"] != "foreign" for item in first["items"] + second["items"])
diff --git a/tests/test_cli_pagination.py b/tests/test_cli_pagination.py
index 9ad59d461..2bb288daa 100644
--- a/tests/test_cli_pagination.py
+++ b/tests/test_cli_pagination.py
@@ -62,6 +62,7 @@ def test_all_collection_commands_share_bounded_pagination_contract() -> None:
("agent", "list"),
("agent", "models"),
("runs", "list"),
+ ("memory", "list"),
("session", "list"),
("session", "queue", "list"),
("vault", "list"),
diff --git a/tests/test_internal_client.py b/tests/test_internal_client.py
index 1de8dce30..de539a883 100644
--- a/tests/test_internal_client.py
+++ b/tests/test_internal_client.py
@@ -566,6 +566,83 @@ def test_memory_sync_read_helpers_use_verified_uds(socket_path):
]
+def test_memory_list_sync_forwards_page_project_and_caller_session(socket_path):
+ captured: dict[str, object] = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured.update(
+ path=request.url.path,
+ payload=json.loads(request.content.decode("utf-8")),
+ caller_session=request.headers.get("x-avibe-caller-session"),
+ )
+ return httpx.Response(200, json={"status": "ok", "items": []})
+
+ with patch(
+ "vibe.internal_client.httpx.HTTPTransport",
+ return_value=httpx.MockTransport(handler),
+ ):
+ response = internal_client.memory_list_sync(
+ project="notes",
+ page=3,
+ limit=7,
+ caller_session_id="ses-memory-list",
+ socket_path=socket_path,
+ )
+
+ assert response["status_code"] == 200
+ assert captured == {
+ "path": "/internal/memory/list",
+ "payload": {"page": 3, "limit": 7, "project": "notes"},
+ "caller_session": "ses-memory-list",
+ }
+
+
+def test_memory_list_async_signs_ui_aggregate_cursor(monkeypatch, socket_path):
+ from core.memory import ui_access
+
+ monkeypatch.setattr(ui_access, "_process_secret", "test-ui-controller-secret")
+ captured: dict[str, object] = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured.update(
+ path=request.url.path,
+ payload=json.loads(request.content.decode("utf-8")),
+ user_key=request.headers.get("x-avibe-memory-user-key"),
+ proof=request.headers.get("x-avibe-memory-ui-proof"),
+ )
+ return httpx.Response(200, json={"status": "ok", "items": []})
+
+ async def _exercise():
+ with patch(
+ "vibe.internal_client.httpx.AsyncHTTPTransport",
+ return_value=httpx.MockTransport(handler),
+ ):
+ return await internal_client.memory_list(
+ user_key="avibe:remote:user-list",
+ project="all",
+ cursor="cursor-token",
+ limit=9,
+ socket_path=socket_path,
+ )
+
+ response = asyncio.run(_exercise())
+
+ assert response["status_code"] == 200
+ assert captured["path"] == "/internal/memory/list"
+ assert captured["payload"] == {
+ "limit": 9,
+ "project": "all",
+ "cursor": "cursor-token",
+ }
+ assert captured["user_key"] == "avibe:remote:user-list"
+ assert captured["proof"] == ui_access.build_ui_read_proof(
+ "test-ui-controller-secret",
+ method="POST",
+ path="/internal/memory/list",
+ user_key="avibe:remote:user-list",
+ )
+
+
def test_memory_ui_read_helper_signs_the_fixed_local_owner(monkeypatch, socket_path):
from core.memory import ui_access
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index b201df64e..81dc62b81 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -724,6 +724,316 @@ def test_memory_search_accepts_bounded_agentic_policy_from_cli_session() -> None
assert current_session_id == "ses-memory"
+def test_memory_list_binds_cli_session_and_uses_exact_provider_page() -> None:
+ from core.memory.http_headers import CALLER_SESSION_HEADER
+
+ runtime = SimpleNamespace(
+ list_memory_projects=Mock(return_value=("default", "notes")),
+ list_episodes_payload=AsyncMock(
+ return_value={"status": "ok", "items": [], "page": 2}
+ ),
+ )
+ controller = _build_controller_double()
+ controller.memory_scope_for_cli_session.return_value = (
+ "u-11111111111111111111111111111111",
+ "default",
+ )
+ controller.memory_runtime = runtime
+ app = internal_server.create_app(controller)
+
+ async def _exercise() -> httpx.Response:
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
+ return await client.post(
+ "/internal/memory/list",
+ headers={CALLER_SESSION_HEADER: "ses-memory-list"},
+ json={"project": "notes", "page": 2, "limit": 5},
+ )
+
+ response = asyncio.run(_exercise())
+
+ assert response.status_code == 200
+ assert response.json() == {"status": "ok", "items": [], "page": 2}
+ controller.memory_scope_for_cli_session.assert_called_once_with("ses-memory-list")
+ runtime.list_memory_projects.assert_called_once_with(
+ "u-11111111111111111111111111111111"
+ )
+ runtime.list_episodes_payload.assert_awaited_once_with(
+ "u-11111111111111111111111111111111",
+ "notes",
+ page=2,
+ page_size=5,
+ )
+
+
+def test_memory_list_reports_unavailable_store_before_named_project_validation() -> None:
+ from core.memory.http_headers import CALLER_SESSION_HEADER
+
+ runtime = SimpleNamespace(
+ available=False,
+ list_memory_projects=Mock(return_value=("default",)),
+ list_episodes_payload=AsyncMock(),
+ )
+ controller = _build_controller_double()
+ controller.memory_scope_for_cli_session.return_value = (
+ "u-11111111111111111111111111111111",
+ "default",
+ )
+ controller.memory_runtime = runtime
+ app = internal_server.create_app(controller)
+
+ async def _exercise() -> httpx.Response:
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
+ return await client.post(
+ "/internal/memory/list",
+ headers={CALLER_SESSION_HEADER: "ses-memory-list"},
+ json={"project": "notes", "page": 1, "limit": 20},
+ )
+
+ response = asyncio.run(_exercise())
+
+ assert response.status_code == 503
+ assert response.json() == {
+ "status": "failed",
+ "error": "memory_store_unavailable",
+ }
+ runtime.list_memory_projects.assert_not_called()
+ runtime.list_episodes_payload.assert_not_awaited()
+
+
+def test_memory_list_rejects_all_for_cli_at_controller_boundary() -> None:
+ from core.memory.http_headers import CALLER_SESSION_HEADER
+
+ runtime = SimpleNamespace(
+ list_all_episodes_payload=AsyncMock(),
+ list_episodes_payload=AsyncMock(),
+ )
+ controller = _build_controller_double()
+ controller.memory_scope_for_cli_session.return_value = (
+ "u-11111111111111111111111111111111",
+ "default",
+ )
+ controller.memory_runtime = runtime
+ app = internal_server.create_app(controller)
+
+ async def _exercise() -> httpx.Response:
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
+ return await client.post(
+ "/internal/memory/list",
+ headers={CALLER_SESSION_HEADER: "ses-memory-list"},
+ json={"project": "all", "page": 1, "limit": 20},
+ )
+
+ response = asyncio.run(_exercise())
+
+ assert response.status_code == 400
+ assert response.json() == {
+ "status": "failed",
+ "error": "memory_invalid_input",
+ }
+ runtime.list_all_episodes_payload.assert_not_awaited()
+ runtime.list_episodes_payload.assert_not_awaited()
+
+
+def test_memory_list_all_is_available_only_to_signed_ui_principal() -> None:
+ from core.memory.http_headers import MEMORY_USER_KEY_HEADER
+ from core.memory.ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proof
+
+ secret = "test-memory-ui-secret"
+ runtime = SimpleNamespace(
+ principal_for_user_key=Mock(
+ return_value="u-22222222222222222222222222222222"
+ ),
+ list_all_episodes_payload=AsyncMock(
+ return_value={
+ "status": "ok",
+ "items": [],
+ "next_cursor": "next-token",
+ }
+ ),
+ )
+ controller = _build_controller_double()
+ controller.default_memory_project_id.return_value = "default"
+ controller.memory_runtime = runtime
+ app = internal_server.create_app(controller, memory_ui_secret=secret)
+ user_key = "avibe:remote:subject-list"
+
+ async def _exercise() -> httpx.Response:
+ path = "/internal/memory/list"
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
+ return await client.post(
+ path,
+ headers={
+ MEMORY_USER_KEY_HEADER: user_key,
+ MEMORY_UI_PROOF_HEADER: build_ui_read_proof(
+ secret,
+ method="POST",
+ path=path,
+ user_key=user_key,
+ ),
+ },
+ json={"project": "all", "cursor": "cursor-token", "limit": 7},
+ )
+
+ response = asyncio.run(_exercise())
+
+ assert response.status_code == 200
+ assert response.json()["next_cursor"] == "next-token"
+ runtime.principal_for_user_key.assert_called_once_with(user_key)
+ runtime.list_all_episodes_payload.assert_awaited_once_with(
+ "u-22222222222222222222222222222222",
+ cursor="cursor-token",
+ limit=7,
+ )
+
+
+def test_memory_list_rejects_invalid_aggregate_cursor_at_controller_boundary() -> None:
+ from core.memory.http_headers import MEMORY_USER_KEY_HEADER
+ from core.memory.ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proof
+
+ secret = "test-memory-ui-secret"
+ runtime = SimpleNamespace(
+ principal_for_user_key=Mock(
+ return_value="u-22222222222222222222222222222222"
+ ),
+ list_all_episodes_payload=AsyncMock(
+ return_value={"status": "failed", "error": "memory_invalid_input"}
+ ),
+ )
+ controller = _build_controller_double()
+ controller.default_memory_project_id.return_value = "default"
+ controller.memory_runtime = runtime
+ app = internal_server.create_app(controller, memory_ui_secret=secret)
+ path = "/internal/memory/list"
+ user_key = "avibe:local"
+
+ async def _exercise() -> httpx.Response:
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
+ return await client.post(
+ path,
+ headers={
+ MEMORY_USER_KEY_HEADER: user_key,
+ MEMORY_UI_PROOF_HEADER: build_ui_read_proof(
+ secret,
+ method="POST",
+ path=path,
+ user_key=user_key,
+ ),
+ },
+ json={"project": "all", "cursor": "malformed", "limit": 20},
+ )
+
+ response = asyncio.run(_exercise())
+
+ assert response.status_code == 400
+ assert response.json() == {
+ "status": "failed",
+ "error": "memory_invalid_input",
+ }
+
+
+def test_memory_list_rejects_surrogate_aggregate_cursor_at_controller_boundary() -> None:
+ from core.memory.http_headers import MEMORY_USER_KEY_HEADER
+ from core.memory.ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proof
+
+ secret = "test-memory-ui-secret"
+ runtime = SimpleNamespace(
+ principal_for_user_key=Mock(
+ return_value="u-22222222222222222222222222222222"
+ ),
+ list_all_episodes_payload=AsyncMock(),
+ )
+ controller = _build_controller_double()
+ controller.default_memory_project_id.return_value = "default"
+ controller.memory_runtime = runtime
+ app = internal_server.create_app(controller, memory_ui_secret=secret)
+ path = "/internal/memory/list"
+ user_key = "avibe:local"
+
+ async def _exercise() -> httpx.Response:
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
+ return await client.post(
+ path,
+ headers={
+ "content-type": "application/json",
+ MEMORY_USER_KEY_HEADER: user_key,
+ MEMORY_UI_PROOF_HEADER: build_ui_read_proof(
+ secret,
+ method="POST",
+ path=path,
+ user_key=user_key,
+ ),
+ },
+ content='{"project":"all","cursor":"\\ud800","limit":20}',
+ )
+
+ response = asyncio.run(_exercise())
+
+ assert response.status_code == 400
+ assert response.json() == {
+ "status": "failed",
+ "error": "memory_invalid_input",
+ }
+ runtime.list_all_episodes_payload.assert_not_awaited()
+
+
+def test_memory_list_accepts_maximum_aggregate_cursor_transport_bound() -> None:
+ from core.memory.http_headers import MEMORY_USER_KEY_HEADER
+ from core.memory.runtime import MEMORY_LIST_CURSOR_MAX_BYTES
+ from core.memory.ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proof
+
+ secret = "test-memory-ui-secret"
+ cursor = "a" * MEMORY_LIST_CURSOR_MAX_BYTES
+ runtime = SimpleNamespace(
+ principal_for_user_key=Mock(
+ return_value="u-22222222222222222222222222222222"
+ ),
+ list_all_episodes_payload=AsyncMock(
+ return_value={"status": "ok", "items": [], "next_cursor": None}
+ ),
+ )
+ controller = _build_controller_double()
+ controller.default_memory_project_id.return_value = "default"
+ controller.memory_runtime = runtime
+ app = internal_server.create_app(controller, memory_ui_secret=secret)
+ path = "/internal/memory/list"
+ user_key = "avibe:local"
+
+ async def _exercise() -> httpx.Response:
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://test",
+ ) as client:
+ return await client.post(
+ path,
+ headers={
+ MEMORY_USER_KEY_HEADER: user_key,
+ MEMORY_UI_PROOF_HEADER: build_ui_read_proof(
+ secret,
+ method="POST",
+ path=path,
+ user_key=user_key,
+ ),
+ },
+ json={"project": "all", "cursor": cursor, "limit": 20},
+ )
+
+ response = asyncio.run(_exercise())
+
+ assert response.status_code == 200
+ runtime.list_all_episodes_payload.assert_awaited_once_with(
+ "u-22222222222222222222222222222222",
+ cursor=cursor,
+ limit=20,
+ )
+
+
def test_memory_rebuild_requires_signed_ui_operator() -> None:
from core.memory.http_headers import MEMORY_USER_KEY_HEADER
from core.memory.ui_access import MEMORY_UI_PROOF_HEADER
diff --git a/tests/test_memory_cli.py b/tests/test_memory_cli.py
index 56ed6ac76..506589a48 100644
--- a/tests/test_memory_cli.py
+++ b/tests/test_memory_cli.py
@@ -20,11 +20,17 @@ _MEMORY_HELP_BY_LANGUAGE = {
"memory": (
"Show Memory status",
"Show the Memory profile",
+ "List processed Memory episodes",
"Search local Memory",
"Queue durable personal context",
),
"status": ("Print machine-readable output",),
"profile": ("Print machine-readable output",),
+ "list": (
+ "Page number (1-based)",
+ "Episodes per page (1-20)",
+ "Print machine-readable output",
+ ),
"search": (
"Search query",
"Maximum results (1-20)",
@@ -35,9 +41,16 @@ _MEMORY_HELP_BY_LANGUAGE = {
},
"zh": {
"top": ("通过运行中的控制器使用本地记忆",),
- "memory": ("显示记忆状态", "显示记忆档案", "搜索本地记忆", "将长期个人信息加入队列"),
+ "memory": (
+ "显示记忆状态",
+ "显示记忆档案",
+ "列出已处理的记忆片段",
+ "搜索本地记忆",
+ "将长期个人信息加入队列",
+ ),
"status": ("输出机器可读格式",),
"profile": ("输出机器可读格式",),
+ "list": ("页码(从 1 开始)", "每页记忆片段数(1-20)", "输出机器可读格式"),
"search": ("搜索内容", "最大结果数(1-20)", "召回模式(默认:hybrid)", "输出机器可读格式"),
"remember": ("要记住的文本(最多 4,000 个字符)", "输出机器可读格式"),
},
@@ -60,7 +73,7 @@ def test_memory_help_uses_configured_i18n(language, arguments, section, monkeypa
@pytest.mark.parametrize("language", ["en", "zh"])
[email protected]("command", ["status", "profile", "search", "remember"])
[email protected]("command", ["status", "profile", "list", "search", "remember"])
def test_memory_subcommand_help_uses_configured_i18n(language, command, monkeypatch, capsys) -> None:
monkeypatch.setattr(cli, "_memory_cli_language", lambda: language)
parser = cli.build_parser()
@@ -102,6 +115,167 @@ def test_memory_search_json_is_a_presentation_of_the_uds_response(monkeypatch, c
}
+def test_memory_list_json_preserves_opaque_entry_id_and_page_contract(
+ monkeypatch,
+ capsys,
+) -> None:
+ """Scenario: MEMORY-LIST-001 and MEMORY-LIST-004."""
+
+ args = cli.build_parser().parse_args(
+ ["memory", "list", "--project", "notes", "--page", "2", "--limit", "5", "--json"]
+ )
+ calls: list[dict[str, object]] = []
+ monkeypatch.setenv(AVIBE_SESSION_ID_ENV, "ses-memory-list")
+
+ def list_sync(**kwargs):
+ calls.append(kwargs)
+ return {
+ "status_code": 200,
+ "body": {
+ "status": "ok",
+ "items": [
+ {
+ "id": "opaque-entry-id",
+ "kind": "episode",
+ "subject": "Subject",
+ "summary": "Summary",
+ "body": "Body",
+ "timestamp": "2026-08-14T12:00:00Z",
+ "project": "notes",
+ }
+ ],
+ "page": 2,
+ "page_size": 5,
+ "count": 1,
+ "total_count": 6,
+ "warnings": [],
+ },
+ }
+
+ monkeypatch.setattr(internal_client, "memory_list_sync", list_sync)
+
+ assert cli.cmd_memory(args) == 0
+ assert calls == [
+ {
+ "page": 2,
+ "limit": 5,
+ "project": "notes",
+ "caller_session_id": "ses-memory-list",
+ }
+ ]
+ output = json.loads(capsys.readouterr().out)
+ assert output["kind"] == "memory_list"
+ assert output["result"]["items"][0]["id"] == "opaque-entry-id"
+ assert output["result"]["page"] == 2
+
+
+ ("language", "warning"),
+ [
+ (
+ "en",
+ "Memory listing reached the provider ordering limit. Later pages may be incomplete.",
+ ),
+ ("zh", "记忆列表已达到服务排序上限,后续页面可能不完整。"),
+ ],
+)
+def test_memory_list_human_surfaces_truncation_warning(
+ language,
+ warning,
+ monkeypatch,
+ capsys,
+) -> None:
+ args = cli.build_parser().parse_args(["memory", "list"])
+ monkeypatch.setattr(cli, "_memory_cli_language", lambda: language)
+ monkeypatch.setattr(
+ internal_client,
+ "memory_list_sync",
+ lambda **_kwargs: {
+ "status_code": 200,
+ "body": {
+ "status": "ok",
+ "items": [
+ {
+ "id": "opaque-entry-id",
+ "kind": "episode",
+ "subject": "Subject",
+ "summary": "",
+ "body": "Body",
+ "timestamp": "2026-08-14T12:00:00Z",
+ "project": "default",
+ }
+ ],
+ "warnings": ["memory_list_truncated"],
+ },
+ },
+ )
+
+ assert cli.cmd_memory(args) == 0
+ captured = capsys.readouterr()
+ assert warning in captured.err
+ assert "2026-08-14T12:00:00Z Subject" in captured.out
+
+
+def test_memory_list_parser_defaults_match_everos_page_semantics() -> None:
+ args = cli.build_parser().parse_args(["memory", "list"])
+
+ assert args.memory_command == "list"
+ assert args.project is None
+ assert args.page == 1
+ assert args.limit == 20
+ assert args.json is False
+
+
+ "arguments",
+ [
+ ["memory", "list", "--page", "0", "--json"],
+ ["memory", "list", "--limit", "0", "--json"],
+ ["memory", "list", "--limit", "21", "--json"],
+ ],
+)
+def test_memory_list_rejects_invalid_bounds_before_transport(
+ arguments,
+ monkeypatch,
+ capsys,
+) -> None:
+ args = cli.build_parser().parse_args(arguments)
+
+ def transport_must_not_run(**_kwargs):
+ raise AssertionError("invalid list input reached the controller")
+
+ monkeypatch.setattr(internal_client, "memory_list_sync", transport_must_not_run)
+
+ assert cli.cmd_memory(args) == 1
+ assert json.loads(capsys.readouterr().out)["code"] == "memory_invalid_input"
+
+
+def test_memory_list_all_rejection_comes_from_controller(monkeypatch, capsys) -> None:
+ """Scenario: MEMORY-LIST-003."""
+
+ args = cli.build_parser().parse_args(
+ ["memory", "list", "--project", "all", "--json"]
+ )
+ calls: list[str | None] = []
+
+ def list_sync(**kwargs):
+ calls.append(kwargs["project"])
+ return {
+ "status_code": 400,
+ "body": {"status": "failed", "error": "memory_invalid_input"},
+ }
+
+ monkeypatch.setattr(internal_client, "memory_list_sync", list_sync)
+
+ assert cli.cmd_memory(args) == 1
+ assert calls == ["all"]
+ assert json.loads(capsys.readouterr().out)["code"] == "memory_invalid_input"
+
+
+def test_memory_list_is_not_added_to_the_injected_personal_memory_prompt() -> None:
+ assert "vibe memory list" not in _MEMORY_CLI_PROMPT
+
+
def test_injected_agentic_memory_example_is_accepted_by_the_live_parser() -> None:
example = 'vibe memory search "<query>" --mode agentic --json'
assert f"`{example}`" in _MEMORY_CLI_PROMPT
diff --git a/tests/test_memory_runtime.py b/tests/test_memory_runtime.py
index b38e9d35e..cead39be8 100644
--- a/tests/test_memory_runtime.py
+++ b/tests/test_memory_runtime.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
+import base64
import hashlib
import inspect
import json
@@ -3992,6 +3993,1333 @@ def test_list_episodes_payload_serializes_opaque_id_and_page_metadata(
}
+async def test_list_all_episodes_uses_stable_project_boundaries_across_pages() -> None:
+ def item(entry_id: str, project: str, timestamp: str) -> MemoryListItem:
+ return MemoryListItem(
+ id=entry_id,
+ subject=entry_id,
+ summary="",
+ body=f"body {entry_id}",
+ timestamp=timestamp,
+ project=project,
+ )
+
+ by_project = {
+ "default": (
+ item("d-1", "default", "2026-08-14T12:00:00Z"),
+ item("d-2", "default", "2026-08-14T10:00:00Z"),
+ item("d-3", "default", "2026-08-14T08:00:00Z"),
+ ),
+ "notes": (
+ item("n-1", "notes", "2026-08-14T11:00:00Z"),
+ item("n-2", "notes", "2026-08-14T09:00:00Z"),
+ ),
+ }
+
+ class _ListModule:
+ async def list_episodes(self, *, project_id: str, page: int, page_size: int, **_kwargs):
+ assert page_size == 20
+ start = (page - 1) * page_size
+ entries = by_project[project_id][start : start + page_size]
+ return MemoryListPage(
+ items=entries,
+ page=page,
+ page_size=page_size,
+ count=len(entries),
+ total_count=len(by_project[project_id]),
+ )
+
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = _ListModule()
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default", "notes")
+
+ first = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=None, limit=2)
+ second = await runtime.list_all_episodes_payload(
+ PRINCIPAL,
+ cursor=first["next_cursor"],
+ limit=2,
+ )
+ third = await runtime.list_all_episodes_payload(
+ PRINCIPAL,
+ cursor=second["next_cursor"],
+ limit=2,
+ )
+
+ assert [entry["id"] for entry in first["items"]] == ["d-1", "n-1"]
+ assert [entry["id"] for entry in second["items"]] == ["d-2", "n-2"]
+ assert [entry["id"] for entry in third["items"]] == ["d-3"]
+ assert first["total_count"] == second["total_count"] == third["total_count"] == 5
+ assert first["next_cursor"] and second["next_cursor"]
+ assert third["next_cursor"] is None
+
+
+async def test_list_all_episodes_orders_fractional_timestamps_by_instant() -> None:
+ whole = MemoryListItem(
+ id="whole-second",
+ subject="whole",
+ summary="",
+ body="whole",
+ timestamp="2026-08-14T12:00:00Z",
+ project="default",
+ )
+ fractional = MemoryListItem(
+ id="fractional-second",
+ subject="fractional",
+ summary="",
+ body="fractional",
+ timestamp="2026-08-14T12:00:00.500000Z",
+ project="notes",
+ )
+
+ class _ListModule:
+ async def list_episodes(self, *, project_id: str, page: int, page_size: int, **_kwargs):
+ entry = whole if project_id == "default" else fractional
+ return MemoryListPage(
+ items=(entry,),
+ page=page,
+ page_size=page_size,
+ count=1,
+ total_count=1,
+ )
+
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = _ListModule()
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default", "notes")
+
+ payload = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=None, limit=2)
+
+ assert [entry["id"] for entry in payload["items"]] == [
+ "fractional-second",
+ "whole-second",
+ ]
+
+
+async def test_list_all_episodes_cursor_survives_insert_and_delete_between_pages() -> None:
+ def item(entry_id: str, timestamp: str) -> MemoryListItem:
+ return MemoryListItem(
+ id=entry_id,
+ subject=entry_id,
+ summary="",
+ body=entry_id,
+ timestamp=timestamp,
+ project="default",
+ )
+
+ entries = [
+ item("e-12", "2026-08-14T12:00:00Z"),
+ item("e-11", "2026-08-14T11:00:00Z"),
+ item("e-10", "2026-08-14T10:00:00Z"),
+ ]
+
+ class _ListModule:
+ async def list_episodes(self, *, page: int, page_size: int, **_kwargs):
+ start = (page - 1) * page_size
+ selected = tuple(entries[start : start + page_size])
+ return MemoryListPage(
+ items=selected,
+ page=page,
+ page_size=page_size,
+ count=len(selected),
+ total_count=len(entries),
+ )
+
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = _ListModule()
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default",)
+
+ first = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=None, limit=1)
+ entries.insert(0, item("e-13", "2026-08-14T13:00:00Z"))
+ second = await runtime.list_all_episodes_payload(
+ PRINCIPAL,
+ cursor=first["next_cursor"],
+ limit=1,
+ )
+ entries[:] = [entry for entry in entries if entry.id != "e-12"]
+ third = await runtime.list_all_episodes_payload(
+ PRINCIPAL,
+ cursor=second["next_cursor"],
+ limit=1,
+ )
+
+ assert [entry["id"] for entry in first["items"]] == ["e-12"]
+ assert [entry["id"] for entry in second["items"]] == ["e-11"]
+ assert [entry["id"] for entry in third["items"]] == ["e-10"]
+
+
+async def test_list_all_episodes_cursor_uses_bounded_provider_page_hint() -> None:
+ base = datetime(2026, 8, 14, 12, tzinfo=timezone.utc)
+
+ def item(index: int) -> MemoryListItem:
+ return MemoryListItem(
+ id=f"entry-{index:05d}",
+ subject="subject",
+ summary="summary",
+ body="body",
+ timestamp=(base - timedelta(seconds=index)).isoformat().replace("+00:00", "Z"),
+ project="default",
+ )
+
+ requested_pages: list[int] = []
+
+ class _ListModule:
+ async def list_episodes(self, *, page: int, page_size: int, **_kwargs):
+ requested_pages.append(page)
+ start = (page - 1) * page_size + 1
+ entries = tuple(item(index) for index in range(start, start + page_size))
+ return MemoryListPage(
+ items=entries,
+ page=page,
+ page_size=page_size,
+ count=len(entries),
+ total_count=20_000,
+ )
+
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = _ListModule()
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default",)
+ projects = ("default",)
+ fingerprint = memory_runtime._memory_list_catalog_fingerprint(PRINCIPAL, projects)
+ boundary = item(9_980)
+ cursor = memory_runtime._encode_memory_list_cursor(
+ fingerprint,
+ {"default": (boundary.timestamp, boundary.id)},
+ {"default": 499},
+ {"default": 20_000},
+ )
+
+ payload = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=cursor, limit=1)
+
+ assert requested_pages[0] == 499
+ assert len(requested_pages) <= 30
+ assert [entry["id"] for entry in payload["items"]] == ["entry-09981"]
+ assert payload["next_cursor"]
+ _, page_hints, total_hints = memory_runtime._decode_memory_list_cursor(
+ payload["next_cursor"],
+ projects=projects,
+ fingerprint=fingerprint,
+ )
+ assert page_hints == {"default": 500}
+ assert total_hints == {"default": 20_000}
+
+
+async def test_list_all_episodes_repositions_page_hint_after_large_shrink() -> None:
+ base = datetime(2026, 8, 13, 12, tzinfo=timezone.utc)
+ surviving = tuple(
+ MemoryListItem(
+ id=f"survivor-{index}",
+ subject="subject",
+ summary="summary",
+ body="body",
+ timestamp=(base - timedelta(seconds=index)).isoformat().replace("+00:00", "Z"),
+ project="default",
+ )
+ for index in range(159)
+ )
+ requested_pages: list[int] = []
+
+ class _ListModule:
+ async def list_episodes(self, *, page: int, page_size: int, **_kwargs):
+ requested_pages.append(page)
+ start = (page - 1) * page_size
+ selected = surviving[start : start + page_size]
+ return MemoryListPage(
+ items=selected,
+ page=page,
+ page_size=page_size,
+ count=len(selected),
+ total_count=len(surviving),
+ )
+
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = _ListModule()
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default",)
+ projects = ("default",)
+ fingerprint = memory_runtime._memory_list_catalog_fingerprint(PRINCIPAL, projects)
+ cursor = memory_runtime._encode_memory_list_cursor(
+ fingerprint,
+ {"default": ("2026-08-14T12:00:00Z", "removed-boundary")},
+ {"default": 5},
+ {"default": 200},
+ )
+
+ payload = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=cursor, limit=5)
+
+ assert requested_pages[0] == 5
+ assert len(requested_pages) <= 14
+ assert [entry["id"] for entry in payload["items"]] == [
+ f"survivor-{index}" for index in range(5)
+ ]
+
+
+async def test_list_all_episodes_does_not_rewind_for_deletions_after_boundary() -> None:
+ base = datetime(2026, 8, 14, 12, tzinfo=timezone.utc)
+
+ def item(index: int) -> MemoryListItem:
+ return MemoryListItem(
+ id=f"entry-{index:05d}",
+ subject="subject",
+ summary="summary",
+ body="body",
+ timestamp=(base - timedelta(seconds=index)).isoformat().replace("+00:00", "Z"),
+ project="default",
+ )
+
+ requested_pages: list[int] = []
+
+ class _ListModule:
+ async def list_episodes(self, *, page: int, page_size: int, **_kwargs):
+ requested_pages.append(page)
+ start = (page - 1) * page_size + 1
+ entries = tuple(item(index) for index in range(start, start + page_size))
+ return MemoryListPage(
+ items=entries,
+ page=page,
+ page_size=page_size,
+ count=len(entries),
+ total_count=12_000,
+ )
+
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = _ListModule()
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default",)
+ projects = ("default",)
+ fingerprint = memory_runtime._memory_list_catalog_fingerprint(PRINCIPAL, projects)
+ boundary = item(9_980)
+ cursor = memory_runtime._encode_memory_list_cursor(
+ fingerprint,
+ {"default": (boundary.timestamp, boundary.id)},
+ {"default": 500},
+ {"default": 20_000},
+ )
+
+ payload = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=cursor, limit=1)
+
+ assert requested_pages[0] == 500
+ assert len(requested_pages) <= 30
+ assert [entry["id"] for entry in payload["items"]] == ["entry-09981"]
+
+
+async def test_list_all_episodes_repositions_after_large_front_insertion() -> None:
+ base = datetime(2026, 8, 14, 12, tzinfo=timezone.utc)
+
+ def item(index: int) -> MemoryListItem:
+ return MemoryListItem(
+ id=f"entry-{index:05d}",
+ subject="subject",
+ summary="summary",
+ body="body",
+ timestamp=(base - timedelta(seconds=index)).isoformat().replace("+00:00", "Z"),
+ project="default",
+ )
+
+ requested_pages: list[int] = []
+
+ class _ListModule:
+ async def list_episodes(self, *, page: int, page_size: int, **_kwargs):
+ requested_pages.append(page)
+ start = (page - 1) * page_size + 1
+ entries = tuple(item(index) for index in range(start, start + page_size))
+ return MemoryListPage(
+ items=entries,
+ page=page,
+ page_size=page_size,
+ count=len(entries),
+ total_count=10_000,
+ )
+
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = _ListModule()
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default",)
+ projects = ("default",)
+ fingerprint = memory_runtime._memory_list_catalog_fingerprint(PRINCIPAL, projects)
+ boundary = item(9_980)
+ cursor = memory_runtime._encode_memory_list_cursor(
+ fingerprint,
+ {"default": (boundary.timestamp, boundary.id)},
+ {"default": 100},
+ {"default": 2_000},
+ )
+
+ payload = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=cursor, limit=1)
+
+ assert requested_pages[0] == 100
+ assert len(requested_pages) <= 30
+ assert [entry["id"] for entry in payload["items"]] == ["entry-09981"]
+
+
+async def test_list_all_episodes_retries_changed_binary_locator_probe() -> None:
+ base = datetime(2026, 8, 14, 12, tzinfo=timezone.utc)
+
+ def item(index: int) -> MemoryListItem:
+ return MemoryListItem(
+ id=f"entry-{index:03d}",
+ subject="subject",
+ summary="summary",
+ body="body",
+ timestamp=(base - timedelta(seconds=index)).isoformat().replace("+00:00", "Z"),
+ project="default",
+ )
+
+ entries = [item(index) for index in range(1, 101)]
+ boundary = item(70)
+ mutated = False
+
+ class _ListModule:
+ async def list_episodes(self, *, page: int, page_size: int, **_kwargs):
+ nonlocal mutated
+ if page != 3 and not mutated:
+ del entries[:40]
+ entries.extend(item(index) for index in range(101, 141))
+ mutated = True
+ start = (page - 1) * page_size
+ selected = tuple(entries[start : start + page_size])
+ return MemoryListPage(
+ items=selected,
+ page=page,
+ page_size=page_size,
+ count=len(selected),
+ total_count=len(entries),
+ )
+
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = _ListModule()
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default",)
+ projects = ("default",)
+ fingerprint = memory_runtime._memory_list_catalog_fingerprint(PRINCIPAL, projects)
+ cursor = memory_runtime._encode_memory_list_cursor(
+ fingerprint,
+ {"default": (boundary.timestamp, boundary.id)},
+ {"default": 3},
+ {"default": 100},
+ )
+
+ inconsistent = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=cursor, limit=5)
+ retried = await runtime.list_all_episodes_payload(
+ PRINCIPAL,
+ cursor=inconsistent["next_cursor"],
+ limit=5,
+ )
+
+ assert inconsistent["items"] == []
+ assert inconsistent["warnings"] == ["memory_list_partial"]
+ assert inconsistent["next_cursor"]
+ assert [entry["id"] for entry in retried["items"]] == [
+ f"entry-{index:03d}" for index in range(71, 76)
+ ]
+
+
+async def test_list_all_episodes_resumes_before_equal_timestamp_peers() -> None:
+ entries = tuple(
+ MemoryListItem(
+ id=f"entry-{index:03d}",
+ subject="subject",
+ summary="summary",
+ body="body",
+ timestamp="2026-08-14T12:00:00Z",
+ project="default",
+ )
+ for index in range(60, 0, -1)
+ )
+
+ class _ListModule:
+ async def list_episodes(self, *, page: int, page_size: int, **_kwargs):
+ start = (page - 1) * page_size
+ selected = entries[start : start + page_size]
+ return MemoryListPage(
+ items=selected,
+ page=page,
+ page_size=page_size,
+ count=len(selected),
+ total_count=len(entries),
+ )
+
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = _ListModule()
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default",)
+
+ first = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=None, limit=20)
+ projects = ("default",)
+ fingerprint = memory_runtime._memory_list_catalog_fingerprint(PRINCIPAL, projects)
+ _, first_page_hints, _ = memory_runtime._decode_memory_list_cursor(
+ first["next_cursor"],
+ projects=projects,
+ fingerprint=fingerprint,
+ )
+ second = await runtime.list_all_episodes_payload(
+ PRINCIPAL,
+ cursor=first["next_cursor"],
+ limit=20,
+ )
+ third = await runtime.list_all_episodes_payload(
+ PRINCIPAL,
+ cursor=second["next_cursor"],
+ limit=20,
+ )
+
+ assert [entry["id"] for entry in first["items"]] == [
+ f"entry-{index:03d}" for index in range(1, 21)
+ ]
+ assert first_page_hints == {"default": 1}
+ assert [entry["id"] for entry in second["items"]] == [
+ f"entry-{index:03d}" for index in range(21, 41)
+ ]
+ assert [entry["id"] for entry in third["items"]] == [
+ f"entry-{index:03d}" for index in range(41, 61)
+ ]
+
+
+async def test_list_all_episodes_retries_when_total_changes_mid_window() -> None:
+ entries = [
+ MemoryListItem(
+ id=f"entry-{index:03d}",
+ subject="subject",
+ summary="summary",
+ body="body",
+ timestamp=f"2026-08-14T12:{59 - index:02d}:00Z",
+ project="default",
+ )
+ for index in range(21)
+ ]
+ mutated = False
+
+ class _ListModule:
+ async def list_episodes(self, *, page: int, page_size: int, **_kwargs):
+ nonlocal mutated
+ if page == 2 and not mutated:
+ entries.pop(0)
+ mutated = True
+ start = (page - 1) * page_size
+ selected = tuple(entries[start : start + page_size])
+ return MemoryListPage(
+ items=selected,
+ page=page,
+ page_size=page_size,
+ count=len(selected),
+ total_count=len(entries),
+ )
+
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = _ListModule()
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default",)
+
+ inconsistent = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=None, limit=20)
+ retried = await runtime.list_all_episodes_payload(
+ PRINCIPAL,
+ cursor=inconsistent["next_cursor"],
+ limit=20,
+ )
+
+ assert inconsistent["items"] == []
+ assert inconsistent["warnings"] == ["memory_list_partial"]
+ assert inconsistent["total_count"] is None
+ assert inconsistent["next_cursor"]
+ assert [entry["id"] for entry in retried["items"]] == [
+ entry.id for entry in entries
+ ]
+ assert retried["next_cursor"] is None
+
+
+async def test_list_all_episodes_preserves_total_hint_for_retry_window() -> None:
+ base = datetime(2026, 8, 14, 12, tzinfo=timezone.utc)
+ entries = [
+ MemoryListItem(
+ id=f"entry-{index:03d}",
+ subject="subject",
+ summary="summary",
+ body="body",
+ timestamp=(base - timedelta(seconds=index)).isoformat().replace("+00:00", "Z"),
+ project="default",
+ )
+ for index in range(200)
+ ]
+ boundary = entries[80]
+ page_five_reads = 0
+
+ class _ListModule:
+ async def list_episodes(self, *, page: int, page_size: int, **_kwargs):
+ nonlocal page_five_reads
+ if page == 5:
+ page_five_reads += 1
+ if page == 5 and page_five_reads == 2:
+ del entries[:41]
+ start = (page - 1) * page_size
+ selected = tuple(entries[start : start + page_size])
+ return MemoryListPage(
+ items=selected,
+ page=page,
+ page_size=page_size,
+ count=len(selected),
+ total_count=len(entries),
+ )
+
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = _ListModule()
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default",)
+ projects = ("default",)
+ fingerprint = memory_runtime._memory_list_catalog_fingerprint(PRINCIPAL, projects)
+ cursor = memory_runtime._encode_memory_list_cursor(
+ fingerprint,
+ {"default": (boundary.timestamp, boundary.id)},
+ {"default": 5},
+ {"default": 200},
+ )
+
+ inconsistent = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=cursor, limit=5)
+ _, retry_page_hints, retry_total_hints = memory_runtime._decode_memory_list_cursor(
+ inconsistent["next_cursor"],
+ projects=projects,
+ fingerprint=fingerprint,
+ )
+ retried = await runtime.list_all_episodes_payload(
+ PRINCIPAL,
+ cursor=inconsistent["next_cursor"],
+ limit=5,
+ )
+
+ assert inconsistent["items"] == []
+ assert inconsistent["warnings"] == ["memory_list_partial"]
+ assert retry_page_hints == {"default": 5}
+ assert retry_total_hints == {"default": 200}
+ assert [entry["id"] for entry in retried["items"]] == [
+ f"entry-{index:03d}" for index in range(81, 86)
+ ]
+
+
+async def test_list_all_episodes_retries_same_count_page_membership_change() -> None:
+ entries = [
+ MemoryListItem(
+ id=f"entry-{index:03d}",
+ subject="subject",
+ summary="summary",
+ body="body",
+ timestamp=f"2026-08-14T12:{59 - index:02d}:00Z",
+ project="default",
+ )
+ for index in range(21)
+ ]
+ inserted = MemoryListItem(
+ id="inserted",
+ subject="subject",
+ summary="summary",
+ body="body",
+ timestamp="2026-08-13T12:00:00Z",
+ project="default",
+ )
+ mutated = False
+
+ class _ListModule:
+ async def list_episodes(self, *, page: int, page_size: int, **_kwargs):
+ nonlocal mutated
+ if page == 2 and not mutated:
+ entries.pop(0)
+ entries.append(inserted)
+ mutated = True
+ start = (page - 1) * page_size
+ selected = tuple(entries[start : start + page_size])
+ return MemoryListPage(
+ items=selected,
+ page=page,
+ page_size=page_size,
+ count=len(selected),
+ total_count=len(entries),
+ )
+
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = _ListModule()
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default",)
+
+ inconsistent = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=None, limit=20)
+ retried = await runtime.list_all_episodes_payload(
+ PRINCIPAL,
+ cursor=inconsistent["next_cursor"],
+ limit=20,
+ )
+ final = await runtime.list_all_episodes_payload(
+ PRINCIPAL,
+ cursor=retried["next_cursor"],
+ limit=20,
+ )
+
+ assert inconsistent["items"] == []
+ assert inconsistent["warnings"] == ["memory_list_partial"]
+ assert [entry["id"] for entry in retried["items"]] == [
+ entry.id for entry in entries[:20]
+ ]
+ assert [entry["id"] for entry in final["items"]] == [inserted.id]
+
+
+async def test_list_all_episodes_rejects_cursor_after_catalog_change() -> None:
+ class _ListModule:
+ async def list_episodes(self, *, project_id: str, page: int, page_size: int, **_kwargs):
+ entries = tuple(
+ MemoryListItem(
+ id=f"{project_id}-{index}",
+ subject="subject",
+ summary="summary",
+ body="body",
+ timestamp=f"2026-08-14T{13 - index:02d}:00:00Z",
+ project=project_id,
+ )
+ for index in (1, 2)
+ )
+ return MemoryListPage(
+ items=entries,
+ page=page,
+ page_size=page_size,
+ count=2,
+ total_count=2,
+ )
+
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = _ListModule()
+ runtime._retired = False
+ projects = ["default"]
+ runtime.list_memory_projects = lambda _principal_id: tuple(projects)
+
+ first = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=None, limit=1)
+ projects.append("notes")
+ changed = await runtime.list_all_episodes_payload(
+ PRINCIPAL,
+ cursor=first["next_cursor"],
+ limit=1,
+ )
+
+ assert changed == {"status": "failed", "error": "memory_invalid_input"}
+
+
+async def test_list_all_episodes_cursor_survives_project_catalog_reordering() -> None:
+ class _ListModule:
+ async def list_episodes(
+ self,
+ *,
+ project_id: str,
+ page: int,
+ page_size: int,
+ **_kwargs,
+ ) -> MemoryListPage:
+ entry = MemoryListItem(
+ id=f"{project_id}-entry",
+ subject="subject",
+ summary="summary",
+ body="body",
+ timestamp=(
+ "2026-08-14T12:00:00Z"
+ if project_id == "alpha"
+ else "2026-08-14T11:00:00Z"
+ ),
+ project=project_id,
+ )
+ return MemoryListPage(
+ items=(entry,),
+ page=page,
+ page_size=page_size,
+ count=1,
+ total_count=1,
+ )
+
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = _ListModule()
+ runtime._retired = False
+ projects = ["alpha", "beta"]
+ runtime.list_memory_projects = lambda _principal_id: tuple(projects)
+
+ first = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=None, limit=1)
+ projects.reverse()
+ second = await runtime.list_all_episodes_payload(
+ PRINCIPAL,
+ cursor=first["next_cursor"],
+ limit=1,
+ )
+
+ assert [entry["id"] for entry in first["items"]] == ["alpha-entry"]
+ assert [entry["id"] for entry in second["items"]] == ["beta-entry"]
+
+
+async def test_list_all_episodes_returns_retry_cursor_for_empty_partial_page() -> None:
+ notes_available = False
+
+ class _ListModule:
+ async def list_episodes(
+ self,
+ *,
+ project_id: str,
+ page: int,
+ page_size: int,
+ **_kwargs,
+ ) -> MemoryListPage | OperationFailed:
+ if project_id == "notes" and not notes_available:
+ return OperationFailed(error="memory_provider_unavailable")
+ items = (
+ (
+ MemoryListItem(
+ id="notes-entry",
+ subject="subject",
+ summary="summary",
+ body="body",
+ timestamp="2026-08-14T12:00:00Z",
+ project="notes",
+ ),
+ )
+ if project_id == "notes"
+ else ()
+ )
+ return MemoryListPage(
+ items=items,
+ page=page,
+ page_size=page_size,
+ count=len(items),
+ total_count=len(items),
+ )
+
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = _ListModule()
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default", "notes")
+
+ first = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=None, limit=20)
+ notes_available = True
+ retried = await runtime.list_all_episodes_payload(
+ PRINCIPAL,
+ cursor=first["next_cursor"],
+ limit=20,
+ )
+
+ assert first["items"] == []
+ assert first["warnings"] == ["memory_list_partial"]
+ assert first["total_count"] is None
+ assert first["next_cursor"]
+ assert [entry["id"] for entry in retried["items"]] == ["notes-entry"]
+
+
+ ("late_error", "expected_warning"),
+ [
+ ("memory_provider_timeout", "memory_list_truncated"),
+ ("memory_sidecar_unavailable", "memory_list_partial"),
+ ],
+)
+async def test_list_all_episodes_preserves_rows_before_late_page_failure(
+ late_error: str,
+ expected_warning: str,
+) -> None:
+ entries = tuple(
+ MemoryListItem(
+ id=f"entry-{index:03d}",
+ subject="subject",
+ summary="summary",
+ body="body",
+ timestamp=f"2026-08-14T12:{59 - index:02d}:00Z",
+ project="default",
+ )
+ for index in range(20)
+ )
+
+ class _ListModule:
+ async def list_episodes(
+ self,
+ *,
+ page: int,
+ page_size: int,
+ **_kwargs,
+ ) -> MemoryListPage | OperationFailed:
+ if page == 2:
+ return OperationFailed(error=late_error)
+ return MemoryListPage(
+ items=entries,
+ page=page,
+ page_size=page_size,
+ count=len(entries),
+ total_count=21,
+ )
+
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = _ListModule()
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default",)
+
+ payload = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=None, limit=20)
+
+ assert [entry["id"] for entry in payload["items"]] == [
+ entry.id for entry in entries[:-1]
+ ]
+ assert payload["warnings"] == [expected_warning]
+ assert payload["total_count"] is None
+ assert payload["next_cursor"]
+
+
+async def test_list_all_episodes_does_not_advance_incomplete_timestamp_group() -> None:
+ timestamp = "2026-08-14T12:00:00Z"
+ entries = tuple(
+ MemoryListItem(
+ id=f"z-{index:02d}",
+ subject="subject",
+ summary="summary",
+ body="body",
+ timestamp=timestamp,
+ project="default",
+ )
+ for index in range(20)
+ ) + tuple(
+ MemoryListItem(
+ id=f"a-{index:02d}",
+ subject="subject",
+ summary="summary",
+ body="body",
+ timestamp=timestamp,
+ project="default",
+ )
+ for index in range(20)
+ )
+ page_two_available = False
+
+ class _ListModule:
+ async def list_episodes(self, *, page: int, page_size: int, **_kwargs):
+ if page == 2 and not page_two_available:
+ return OperationFailed(error="memory_provider_timeout")
+ start = (page - 1) * page_size
+ selected = entries[start : start + page_size]
+ return MemoryListPage(
+ items=selected,
+ page=page,
+ page_size=page_size,
+ count=len(selected),
+ total_count=len(entries),
+ )
+
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = _ListModule()
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default",)
+
+ partial = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=None, limit=20)
+ page_two_available = True
+ retried = await runtime.list_all_episodes_payload(
+ PRINCIPAL,
+ cursor=partial["next_cursor"],
+ limit=20,
+ )
+
+ assert partial["items"] == []
+ assert partial["warnings"] == ["memory_list_truncated"]
+ assert partial["next_cursor"]
+ assert [entry["id"] for entry in retried["items"]] == [
+ f"a-{index:02d}" for index in range(20)
+ ]
+
+
+async def test_list_all_episodes_does_not_let_one_project_starve_others(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ memory_runtime,
+ "_MEMORY_LIST_AGGREGATE_TIMEOUT_SECONDS",
+ 0.05,
+ )
+ healthy = MemoryListItem(
+ id="notes-entry",
+ subject="subject",
+ summary="summary",
+ body="body",
+ timestamp="2026-08-14T12:00:00Z",
+ project="notes",
+ )
+
+ class _ListProvider(FakeMemoryProvider):
+ 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 project_id == "default":
+ await asyncio.Event().wait()
+ return MemoryListPage(
+ items=(healthy,),
+ page=page,
+ page_size=page_size,
+ count=1,
+ total_count=1,
+ )
+
+ module = memory_module.MemoryModule(
+ store=MemoryStore(),
+ provider=_ListProvider(),
+ enabled=True,
+ )
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = module
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default", "notes")
+
+ payload = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=None, limit=20)
+
+ assert [entry["id"] for entry in payload["items"]] == ["notes-entry"]
+ assert payload["warnings"] == ["memory_list_truncated"]
+ assert payload["total_count"] is None
+ assert payload["next_cursor"]
+
+
+async def test_list_all_episodes_bounds_lifecycle_lock_acquisition(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ memory_runtime,
+ "_MEMORY_LIST_AGGREGATE_TIMEOUT_SECONDS",
+ 0.01,
+ )
+ provider = FakeMemoryProvider()
+ module = memory_module.MemoryModule(
+ store=MemoryStore(),
+ provider=provider,
+ enabled=True,
+ )
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = module
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default",)
+ await module._lifecycle_lock.acquire()
+ try:
+ payload = await asyncio.wait_for(
+ runtime.list_all_episodes_payload(PRINCIPAL, cursor=None, limit=20),
+ timeout=0.2,
+ )
+ finally:
+ module._lifecycle_lock.release()
+
+ assert payload == {"status": "failed", "error": "memory_provider_timeout"}
+ assert provider.list_requests == []
+
+
+async def test_list_all_episodes_rejects_active_maintenance_before_lock_wait() -> None:
+ provider = FakeMemoryProvider()
+ module = memory_module.MemoryModule(
+ store=MemoryStore(),
+ provider=provider,
+ enabled=True,
+ )
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = module
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default",)
+ module.enter_maintenance()
+ await module._lifecycle_lock.acquire()
+ try:
+ payload = await asyncio.wait_for(
+ runtime.list_all_episodes_payload(PRINCIPAL, cursor=None, limit=20),
+ timeout=0.2,
+ )
+ finally:
+ module._lifecycle_lock.release()
+
+ assert payload == {"status": "failed", "error": "memory_clear_failed"}
+ assert provider.list_requests == []
+
+
+async def test_list_all_episodes_checks_store_once_before_provider_pages(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ entries = tuple(
+ MemoryListItem(
+ id=f"entry-{index:02d}",
+ subject="subject",
+ summary="summary",
+ body="body",
+ timestamp=f"2026-08-14T{23 - index:02d}:00:00Z",
+ project="default",
+ )
+ for index in range(21)
+ )
+
+ class _ListProvider(FakeMemoryProvider):
+ 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))
+ start = (page - 1) * page_size
+ selected = entries[start : start + page_size]
+ return MemoryListPage(
+ items=selected,
+ page=page,
+ page_size=page_size,
+ count=len(selected),
+ total_count=len(entries),
+ )
+
+ provider = _ListProvider()
+ module = memory_module.MemoryModule(
+ store=MemoryStore(),
+ provider=provider,
+ enabled=True,
+ )
+ ensure_meta = module._store.ensure_meta
+ store_checks = 0
+
+ def counted_ensure_meta():
+ nonlocal store_checks
+ store_checks += 1
+ return ensure_meta()
+
+ monkeypatch.setattr(module._store, "ensure_meta", counted_ensure_meta)
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = module
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default",)
+
+ payload = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=None, limit=20)
+
+ assert len(payload["items"]) == 20
+ assert store_checks == 1
+ assert len(provider.list_requests) == 3
+
+
+async def test_list_all_episodes_stops_when_store_check_consumes_deadline(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ memory_runtime,
+ "_MEMORY_LIST_AGGREGATE_TIMEOUT_SECONDS",
+ 0.01,
+ )
+ provider = FakeMemoryProvider()
+ module = memory_module.MemoryModule(
+ store=MemoryStore(),
+ provider=provider,
+ enabled=True,
+ )
+ ensure_meta = module._store.ensure_meta
+
+ def slow_ensure_meta():
+ threading.Event().wait(timeout=0.03)
+ return ensure_meta()
+
+ monkeypatch.setattr(module._store, "ensure_meta", slow_ensure_meta)
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = module
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default",)
+
+ payload = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=None, limit=20)
+
+ assert payload == {"status": "failed", "error": "memory_provider_timeout"}
+ assert provider.list_requests == []
+
+
+def test_memory_list_cursor_bound_covers_maximum_valid_catalog() -> None:
+ projects = (
+ "default",
+ *(f"p{index:02d}-" + "x" * 59 for index in range(16)),
+ )
+ timestamp = "2026-08-14T12:00:00." + "1" * 38 + "+00:00"
+ boundaries = {
+ project_id: (timestamp, "\\" * 128)
+ for project_id in projects
+ }
+ fingerprint = memory_runtime._memory_list_catalog_fingerprint(PRINCIPAL, projects)
+
+ page_hints = {
+ project_id: memory_runtime._MEMORY_LIST_PROVIDER_MAX_PAGE
+ for project_id in projects
+ }
+ cursor = memory_runtime._encode_memory_list_cursor(
+ fingerprint,
+ boundaries,
+ page_hints,
+ {project_id: 20_000_000 for project_id in projects},
+ )
+
+ assert len(cursor.encode("ascii")) <= memory_runtime.MEMORY_LIST_CURSOR_MAX_BYTES
+ assert memory_runtime._decode_memory_list_cursor(
+ cursor,
+ projects=projects,
+ fingerprint=fingerprint,
+ ) == (
+ boundaries,
+ page_hints,
+ {project_id: 20_000_000 for project_id in projects},
+ )
+
+
+async def test_list_all_episodes_rejects_surrogate_boundary_id() -> None:
+ projects = ("default",)
+ fingerprint = memory_runtime._memory_list_catalog_fingerprint(PRINCIPAL, projects)
+ raw = json.dumps(
+ {
+ "v": memory_runtime._MEMORY_LIST_CURSOR_VERSION,
+ "f": fingerprint,
+ "b": {
+ "default": {
+ "t": "2026-08-14T12:00:00Z",
+ "i": "\ud800",
+ "p": 1,
+ "n": 1,
+ }
+ },
+ },
+ ensure_ascii=True,
+ separators=(",", ":"),
+ sort_keys=True,
+ ).encode("ascii")
+ cursor = base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
+
+ class _ListModule:
+ async def list_episodes(self, **_kwargs):
+ raise AssertionError("invalid cursor reached the provider")
+
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = _ListModule()
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: projects
+
+ result = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=cursor, limit=1)
+
+ assert result == {"status": "failed", "error": "memory_invalid_input"}
+
+
+async def test_list_all_episodes_rejects_cursor_from_another_principal() -> None:
+ items = (
+ MemoryListItem(
+ id="entry-1",
+ subject="Subject 1",
+ summary="",
+ body="Body 1",
+ timestamp="2026-08-14T12:00:00Z",
+ project="default",
+ ),
+ MemoryListItem(
+ id="entry-2",
+ subject="Subject 2",
+ summary="",
+ body="Body 2",
+ timestamp="2026-08-14T11:00:00Z",
+ project="default",
+ ),
+ )
+
+ class _ListModule:
+ async def list_episodes(self, *, page: int, page_size: int, **_kwargs):
+ start = (page - 1) * page_size
+ entries = items[start : start + page_size]
+ return MemoryListPage(
+ items=entries,
+ page=page,
+ page_size=page_size,
+ count=len(entries),
+ total_count=len(items),
+ )
+
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = _ListModule()
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default",)
+
+ first = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=None, limit=1)
+ other = await runtime.list_all_episodes_payload(
+ "u-22222222222222222222222222222222",
+ cursor=first["next_cursor"],
+ limit=1,
+ )
+
+ assert other == {"status": "failed", "error": "memory_invalid_input"}
+
+
+async def test_list_all_episodes_marks_partial_results_and_omits_total() -> None:
+ """Scenario: MEMORY-LIST-005."""
+
+ good = MemoryListItem(
+ id="default-1",
+ subject="subject",
+ summary="summary",
+ body="body",
+ timestamp="2026-08-14T12:00:00Z",
+ project="default",
+ )
+
+ class _ListModule:
+ async def list_episodes(self, *, project_id: str, page: int, page_size: int, **_kwargs):
+ if project_id == "notes":
+ return OperationFailed(error="memory_provider_unavailable")
+ return MemoryListPage(
+ items=(good,),
+ page=page,
+ page_size=page_size,
+ count=1,
+ total_count=1,
+ )
+
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = _ListModule()
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default", "notes")
+
+ payload = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=None, limit=20)
+
+ assert [entry["id"] for entry in payload["items"]] == ["default-1"]
+ assert payload["total_count"] is None
+ assert payload["warnings"] == ["memory_list_partial"]
+
+
+async def test_list_all_episodes_returns_closed_failure_when_every_project_fails() -> None:
+ class _ListModule:
+ async def list_episodes(self, **_kwargs):
+ return OperationFailed(error="memory_sidecar_unavailable")
+
+ runtime = object.__new__(MemoryRuntime)
+ runtime._module = _ListModule()
+ runtime._retired = False
+ runtime.list_memory_projects = lambda _principal_id: ("default", "notes")
+
+ payload = await runtime.list_all_episodes_payload(PRINCIPAL, cursor=None, limit=20)
+
+ assert payload == {
+ "status": "failed",
+ "error": "memory_sidecar_unavailable",
+ }
+
+
def test_profile_payload_serializes_structured_profile_without_widening_legacy_items(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
diff --git a/tests/test_ui_memory_routes.py b/tests/test_ui_memory_routes.py
index bfff124d6..52e041035 100644
--- a/tests/test_ui_memory_routes.py
+++ b/tests/test_ui_memory_routes.py
@@ -18,6 +18,7 @@ from config.v2_config import (
V2Config,
)
from core.memory.operation_lock import MemoryOperationLease
+from core.memory.runtime import MEMORY_LIST_CURSOR_MAX_BYTES
from tests.ui_server_test_helpers import csrf_headers, remote_session_cookie
from vibe import api, internal_client, remote_access, ui_memory_routes, ui_server
from vibe.ui_server import app
@@ -1134,6 +1135,128 @@ def test_memory_search_rejects_agentic_policy_before_internal_transport(
assert response.headers["cache-control"] == "no-store"
+def test_memory_list_requires_csrf_and_forwards_ui_aggregate_cursor(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ calls: list[dict[str, object]] = []
+
+ async def memory_list(**kwargs):
+ calls.append(kwargs)
+ return {
+ "status_code": 200,
+ "body": {
+ "status": "ok",
+ "items": [],
+ "next_cursor": "next-token",
+ },
+ }
+
+ monkeypatch.setattr(internal_client, "memory_list", memory_list)
+ client = app.test_client()
+ cursor = "a" * MEMORY_LIST_CURSOR_MAX_BYTES
+ payload = {"project": "all", "cursor": cursor, "limit": 7}
+ rejected = client.post(
+ "/api/memory/list",
+ json=payload,
+ base_url="http://127.0.0.1:15131",
+ environ_base={"REMOTE_ADDR": "127.0.0.1"},
+ )
+ response = client.post(
+ "/api/memory/list",
+ json=payload,
+ 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 rejected.status_code == 403
+ assert response.status_code == 200
+ assert response.get_json()["next_cursor"] == "next-token"
+ assert response.headers["cache-control"] == "no-store"
+ assert calls == [
+ {
+ "user_key": "avibe:local",
+ "project": "all",
+ "page": None,
+ "cursor": cursor,
+ "limit": 7,
+ }
+ ]
+
+
+ "payload",
+ [
+ {"project": "all", "page": 1},
+ {"project": "notes", "cursor": "cursor-token"},
+ {"project": "all", "cursor": ""},
+ {
+ "project": "all",
+ "cursor": "a" * (MEMORY_LIST_CURSOR_MAX_BYTES + 1),
+ },
+ {"project": "default", "page": 0},
+ {"project": "default", "limit": 21},
+ {"project": "default", "unknown": True},
+ ],
+)
+def test_memory_list_rejects_invalid_pagination_before_internal_transport(
+ monkeypatch,
+ tmp_path,
+ payload,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+
+ async def transport_must_not_run(**_kwargs):
+ raise AssertionError("invalid list payload reached internal transport")
+
+ monkeypatch.setattr(internal_client, "memory_list", transport_must_not_run)
+ client = app.test_client()
+ response = client.post(
+ "/api/memory/list",
+ json=payload,
+ 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 == 400
+ assert response.get_json() == {
+ "status": "failed",
+ "error": "memory_invalid_input",
+ }
+
+
+def test_memory_list_rejects_unpaired_surrogate_cursor(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+
+ async def transport_must_not_run(**_kwargs):
+ raise AssertionError("invalid list cursor reached internal transport")
+
+ monkeypatch.setattr(internal_client, "memory_list", transport_must_not_run)
+ client = app.test_client()
+ headers = csrf_headers(client, "http://127.0.0.1:15131")
+ headers["content-type"] = "application/json"
+
+ response = client.post(
+ "/api/memory/list",
+ content=b'{"project":"all","cursor":"\\ud800"}',
+ headers=headers,
+ base_url="http://127.0.0.1:15131",
+ environ_base={"REMOTE_ADDR": "127.0.0.1"},
+ )
+
+ assert response.status_code == 400
+ assert response.get_json() == {
+ "status": "failed",
+ "error": "memory_invalid_input",
+ }
+
+
def test_memory_log_routes_forward_only_valid_query_and_are_no_store(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
diff --git a/vibe/cli.py b/vibe/cli.py
index af8828599..15f4cccc6 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -501,10 +501,35 @@ def _print_memory_cli_human(operation: str, result: dict, *, language: str) -> N
print(i18n_t("memory.cli.sourceReason", language, reason=reason_label))
return
+ if operation == "list":
+ warnings = result.get("warnings")
+ if isinstance(warnings, list) and "memory_list_truncated" in warnings:
+ print(i18n_t("memory.cli.listWarning.truncated", language), file=sys.stderr)
+
items = result.get("items")
if not isinstance(items, list) or not items:
print(i18n_t("memory.cli.empty", language))
return
+ if operation == "list":
+ for item in items:
+ if not isinstance(item, dict):
+ continue
+ timestamp = item.get("timestamp")
+ subject = item.get("subject")
+ summary = item.get("summary")
+ body = item.get("body")
+ lines = [
+ value
+ for value in (subject, summary, body)
+ if isinstance(value, str) and value
+ ]
+ if not lines:
+ continue
+ prefix = f"{timestamp} " if isinstance(timestamp, str) and timestamp else ""
+ print(f"{prefix}{lines[0]}")
+ for line in lines[1:]:
+ print(line)
+ return
for item in items:
if not isinstance(item, dict):
continue
@@ -526,7 +551,7 @@ def cmd_memory(args) -> int:
as_json = bool(getattr(args, "json", False))
language = _memory_cli_language()
query = ""
- if operation not in {"status", "profile", "search", "remember"}:
+ if operation not in {"status", "profile", "list", "search", "remember"}:
return _print_memory_cli_error("invalid", "memory_invalid_input", as_json=as_json, language=language)
if operation == "search":
query = args.query.strip() if isinstance(args.query, str) else ""
@@ -538,6 +563,15 @@ def cmd_memory(args) -> int:
or not 1 <= args.limit <= 20
):
return _print_memory_cli_error(operation, "memory_invalid_input", as_json=as_json, language=language)
+ if operation == "list" and (
+ not isinstance(args.page, int)
+ or isinstance(args.page, bool)
+ or args.page < 1
+ or not isinstance(args.limit, int)
+ or isinstance(args.limit, bool)
+ or not 1 <= args.limit <= 20
+ ):
+ return _print_memory_cli_error(operation, "memory_invalid_input", as_json=as_json, language=language)
if operation == "remember":
query = args.text if isinstance(args.text, str) else ""
if not query.strip() or len(query) > 4_000:
@@ -553,6 +587,13 @@ def cmd_memory(args) -> int:
response = internal_client.memory_status_sync(**access)
elif operation == "profile":
response = internal_client.memory_profile_sync(**access)
+ elif operation == "list":
+ response = internal_client.memory_list_sync(
+ page=args.page,
+ limit=args.limit,
+ project=getattr(args, "project", None),
+ **access,
+ )
elif operation == "search":
response = internal_client.memory_search_sync(
query,
@@ -14217,7 +14258,7 @@ def build_parser():
)
memory_subparsers = memory_parser.add_subparsers(
dest="memory_command",
- metavar="{status,profile,search,remember}",
+ metavar="{status,profile,list,search,remember}",
)
memory_subparsers.required = True
memory_status_parser = memory_subparsers.add_parser(
@@ -14238,6 +14279,32 @@ def build_parser():
action="store_true",
help=i18n_t("memory.cli.help.json", memory_help_language),
)
+ memory_list_parser = memory_subparsers.add_parser(
+ "list",
+ help=i18n_t("memory.cli.help.list", memory_help_language),
+ )
+ memory_list_parser.add_argument(
+ "--project",
+ default=None,
+ help=i18n_t("memory.cli.help.project", memory_help_language),
+ )
+ memory_list_parser.add_argument(
+ "--page",
+ type=int,
+ default=1,
+ help=i18n_t("memory.cli.help.page", memory_help_language),
+ )
+ memory_list_parser.add_argument(
+ "--limit",
+ type=int,
+ default=20,
+ help=i18n_t("memory.cli.help.pageLimit", memory_help_language),
+ )
+ memory_list_parser.add_argument(
+ "--json",
+ action="store_true",
+ help=i18n_t("memory.cli.help.json", memory_help_language),
+ )
memory_search_parser = memory_subparsers.add_parser(
"search",
help=i18n_t("memory.cli.help.search", memory_help_language),
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 2c874f80b..7cf99d422 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -697,10 +697,13 @@
"command": "Use local Memory through the running controller",
"status": "Show Memory status",
"profile": "Show the Memory profile",
+ "list": "List processed Memory episodes",
"search": "Search local Memory",
"remember": "Queue durable personal context",
"query": "Search query",
"project": "Memory project: default or a named slug such as billing",
+ "page": "Page number (1-based)",
+ "pageLimit": "Episodes per page (1-20)",
"limit": "Maximum results (1-20)",
"mode": "Recall mode (default: hybrid)",
"text": "Text to remember (maximum 4,000 characters)",
@@ -749,6 +752,9 @@
},
"empty": "No memory items found.",
"remembered": "Memory queued.",
+ "listWarning": {
+ "truncated": "Memory listing reached the provider ordering limit. Later pages may be incomplete."
+ },
"partialRestartWarning": "Memory Settings content is unavailable: the Web UI restarted while the service kept running,\n and their shared Memory proof exists only inside the running processes.\n Run 'vibe stop' and then 'vibe' to restart both together."
},
"alert": {
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 80b36fb5a..a5ace01d2 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -697,10 +697,13 @@
"command": "通过运行中的控制器使用本地记忆",
"status": "显示记忆状态",
"profile": "显示记忆档案",
+ "list": "列出已处理的记忆片段",
"search": "搜索本地记忆",
"remember": "将长期个人信息加入队列",
"query": "搜索内容",
"project": "记忆项目:default,或 billing 这类小写 slug",
+ "page": "页码(从 1 开始)",
+ "pageLimit": "每页记忆片段数(1-20)",
"limit": "最大结果数(1-20)",
"mode": "召回模式(默认:hybrid)",
"text": "要记住的文本(最多 4,000 个字符)",
@@ -749,6 +752,9 @@
},
"empty": "未找到记忆条目。",
"remembered": "记忆已加入队列。",
+ "listWarning": {
+ "truncated": "记忆列表已达到服务排序上限,后续页面可能不完整。"
+ },
"partialRestartWarning": "记忆设置内容暂不可用:Web UI 已重启,但服务仍在运行,\n 两者共享的记忆访问凭证仅存在于运行中的进程内。\n 请先运行 'vibe stop',再运行 'vibe',以同时重启两者。"
},
"alert": {
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index 0ca16fe1a..70b3fab99 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -890,6 +890,37 @@ async def memory_projects(
)
+async def memory_list(
+ *,
+ user_key: str,
+ project: str | None = None,
+ page: int | None = None,
+ cursor: str | None = None,
+ limit: int = 20,
+ socket_path: Optional[Path] = None,
+ timeout: float = MEMORY_READ_TIMEOUT_SECONDS,
+) -> dict[str, Any]:
+ payload: dict[str, object] = {"limit": limit}
+ if project is not None:
+ payload["project"] = project
+ if page is not None:
+ payload["page"] = page
+ if cursor is not None:
+ payload["cursor"] = cursor
+ return await _memory_request(
+ "POST",
+ "/internal/memory/list",
+ payload=payload,
+ headers=_memory_user_key_headers(
+ "POST",
+ "/internal/memory/list",
+ user_key,
+ ),
+ socket_path=socket_path,
+ timeout=timeout,
+ )
+
+
async def memory_search(
query: str,
policy: dict[str, object],
@@ -1007,6 +1038,28 @@ def memory_profile_sync(
)
+def memory_list_sync(
+ *,
+ page: int = 1,
+ limit: int = 20,
+ caller_session_id: str | None = None,
+ project: str | None = None,
+ socket_path: Optional[Path] = None,
+ timeout: float = MEMORY_READ_TIMEOUT_SECONDS,
+) -> dict[str, Any]:
+ payload: dict[str, object] = {"page": page, "limit": limit}
+ if project is not None:
+ payload["project"] = project
+ return _memory_request_sync(
+ "POST",
+ "/internal/memory/list",
+ payload=payload,
+ headers=_memory_cli_session_headers(caller_session_id),
+ socket_path=socket_path,
+ timeout=timeout,
+ )
+
+
def memory_search_sync(
query: str,
limit: int,
diff --git a/vibe/ui_memory_routes.py b/vibe/ui_memory_routes.py
index 21bce219f..0c915755f 100644
--- a/vibe/ui_memory_routes.py
+++ b/vibe/ui_memory_routes.py
@@ -1149,6 +1149,82 @@ def register_memory_routes(app) -> None:
return await app.dispatch_native_request(starlette_request, handler)
+ @app.post("/api/memory/list", include_in_schema=False)
+ async def memory_list_post(starlette_request: FastAPIRequest):
+ async def handler():
+ 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) - {
+ "project",
+ "page",
+ "cursor",
+ "limit",
+ }:
+ return _memory_response(
+ {"status": "failed", "error": "memory_invalid_input"},
+ status_code=400,
+ )
+ project = payload.get("project")
+ page = payload.get("page")
+ cursor = payload.get("cursor")
+ limit = payload.get("limit", 20)
+ from core.memory.runtime import MEMORY_LIST_CURSOR_MAX_BYTES
+
+ cursor_bytes: int | None = None
+ if isinstance(cursor, str):
+ try:
+ cursor_bytes = len(cursor.encode("utf-8"))
+ except UnicodeEncodeError:
+ pass
+
+ if (
+ (project is not None and not isinstance(project, str))
+ or isinstance(limit, bool)
+ or not isinstance(limit, int)
+ or not 1 <= limit <= 20
+ or (
+ page is not None
+ and (
+ isinstance(page, bool)
+ or not isinstance(page, int)
+ or page < 1
+ )
+ )
+ or (
+ cursor is not None
+ and (
+ not isinstance(cursor, str)
+ or not cursor
+ or cursor_bytes is None
+ or cursor_bytes > MEMORY_LIST_CURSOR_MAX_BYTES
+ )
+ )
+ or (project == "all" and page is not None)
+ or (project != "all" and cursor is not None)
+ ):
+ return _memory_response(
+ {"status": "failed", "error": "memory_invalid_input"},
+ status_code=400,
+ )
+ from vibe import internal_client
+
+ return await _memory_internal_response(
+ lambda: internal_client.memory_list(
+ user_key=user_key,
+ project=project,
+ page=page,
+ cursor=cursor,
+ limit=limit,
+ )
+ )
+
+ return await app.dispatch_native_request(starlette_request, handler)
+
@app.post("/api/memory/runtime/restart", include_in_schema=False)
async def memory_runtime_restart_post(starlette_request: FastAPIRequest):
"""Restart the live sidecar without changing persisted settings."""