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): capture user turns into the EverOS default project (#1397)

rkrkrkk29eba94e9e98
diff --git a/core/controller.py b/core/controller.py
index 95deb3d8e..e01432b1a 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -1882,6 +1882,7 @@ class Controller:
def memory_scope_for_cli_session(self, session_id: str) -> Optional[tuple[str, str]]:
"""Return the principal and project owned by an admitted Agent session."""
+ from core.memory.project_ids import DEFAULT_MEMORY_PROJECT_ID
from core.memory.store import is_principal_id, is_project_id
session_key = str(session_id or "").strip()
@@ -1926,17 +1927,11 @@ class Controller:
return scope[1] if scope is not None else None
def default_memory_project_id(self) -> str:
- """Return the Memory project used by a default-cwd Agent Session."""
+ """Return the Memory project used by Settings and default Agent search."""
- from core.services.agent_run_target import resolve_default_agent_workdir
+ from core.memory.project_ids import DEFAULT_MEMORY_PROJECT_ID
- workdir = resolve_default_agent_workdir(
- self,
- platform="avibe",
- settings_key="memory-ui",
- session_key="memory-ui",
- )
- return self.memory_runtime.project_for_workdir(workdir)
+ return DEFAULT_MEMORY_PROJECT_ID
async def final_flush_memory_session(
self,
@@ -2039,24 +2034,60 @@ class Controller:
if not isinstance(raw_session_id, str) or not raw_session_id:
return False
- scope = self.memory_scope_for_cli_session(raw_session_id)
- if scope is None:
- runtime = getattr(self, "memory_runtime", None)
- resolve = getattr(runtime, "resolve_current_session_scope", None)
- if callable(resolve):
- try:
- scope = await resolve(raw_session_id)
- except Exception:
- logger.debug("Memory session scope recovery failed", exc_info=True)
- return False
- if scope is None:
+ from core.memory.project_ids import (
+ DEFAULT_MEMORY_PROJECT_ID,
+ is_persisted_memory_project_id,
+ )
+ from core.memory.store import is_principal_id
+
+ live_scope = self.memory_scope_for_cli_session(raw_session_id)
+ runtime = getattr(self, "memory_runtime", None)
+ resolve_scopes = getattr(runtime, "resolve_current_session_scopes", None)
+ durable_scopes: tuple[tuple[str, str], ...] | None = ()
+ if callable(resolve_scopes):
+ try:
+ durable_scopes = await resolve_scopes(raw_session_id)
+ except Exception:
+ logger.debug("Memory session scope recovery failed", exc_info=True)
+ durable_scopes = None
+ if durable_scopes is None:
return False
- return await self._final_flush_memory_scope(
- raw_session_id,
- scope[0],
- scope[1],
- deadline_seconds=deadline_seconds,
+ scopes = set(durable_scopes)
+ if live_scope is not None:
+ scopes.add(live_scope)
+ if not scopes:
+ return False
+ ordered = tuple(
+ sorted(
+ scopes,
+ key=lambda scope: (scope[1] != DEFAULT_MEMORY_PROJECT_ID, scope),
+ )
)
+ if any(
+ not is_principal_id(principal_id)
+ or not is_persisted_memory_project_id(project_id)
+ for principal_id, project_id in ordered
+ ):
+ return False
+ run_lifecycle = getattr(runtime, "run_session_scopes_lifecycle", None)
+ if not callable(run_lifecycle):
+ return False
+
+ async def _flushed() -> bool:
+ return True
+
+ try:
+ return bool(
+ await run_lifecycle(
+ scopes=ordered,
+ raw_session_id=raw_session_id,
+ operation=_flushed,
+ deadline_seconds=deadline_seconds,
+ )
+ )
+ except Exception:
+ logger.debug("Memory multi-scope final flush failed", exc_info=True)
+ return False
async def archive_memory_cli_session(
self,
@@ -2072,6 +2103,7 @@ class Controller:
runtime lifecycle operation as final flush.
"""
+ from core.memory.project_ids import DEFAULT_MEMORY_PROJECT_ID
from core.memory.store import is_principal_id, is_project_id
from core.services import sessions as workbench_sessions_service
from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
@@ -2140,7 +2172,12 @@ class Controller:
or not is_project_id(scope[1])
):
raise RuntimeError("invalid canonical Memory session scope")
- canonical_scopes = tuple(sorted(scopes))
+ canonical_scopes = tuple(
+ sorted(
+ scopes,
+ key=lambda scope: (scope[1] != DEFAULT_MEMORY_PROJECT_ID, scope),
+ )
+ )
run_lifecycle = getattr(runtime, "run_session_scopes_lifecycle", None)
if not callable(run_lifecycle):
diff --git a/core/internal_server.py b/core/internal_server.py
index 02743c572..79a5c2d81 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -1463,6 +1463,45 @@ def create_app(
)
return payload
+ @app.get("/internal/memory/projects")
+ async def _memory_projects(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, _project_id = scope
+ runtime = _memory_runtime()
+ if runtime is None:
+ return JSONResponse(
+ status_code=503,
+ content={"status": "failed", "error": "memory_runtime_missing"},
+ )
+ from core.memory.project_ids import DEFAULT_MEMORY_PROJECT_ID, MEMORY_SEARCH_ALL_PROJECTS
+
+ try:
+ catalogued = await run_blocking(runtime.list_memory_projects, principal_id)
+ except Exception:
+ logger.warning("internal memory project list failed")
+ return JSONResponse(
+ status_code=503,
+ content={"status": "failed", "error": "memory_store_unavailable"},
+ )
+ named = [item for item in catalogued if item != DEFAULT_MEMORY_PROJECT_ID]
+ projects = [
+ {"id": DEFAULT_MEMORY_PROJECT_ID, "kind": "default"},
+ *[{"id": item, "kind": "named"} for item in named],
+ {"id": MEMORY_SEARCH_ALL_PROJECTS, "kind": "all"},
+ ]
+ return {"status": "ok", "projects": projects}
+
@app.post("/internal/memory/search")
async def _memory_search(request: Request) -> Any:
try:
@@ -1481,18 +1520,44 @@ def create_app(
payload = await _safe_json(request)
if (
not isinstance(payload, dict)
- or set(payload) != {"query", "policy"}
+ or not {"query", "policy"}.issubset(payload)
+ or set(payload) - {"query", "policy", "project"}
or not isinstance(payload.get("query"), str)
):
return JSONResponse(status_code=400, content={"status": "failed", "error": "memory_invalid_input"})
- from core.memory.http_headers import CALLER_SESSION_HEADER
+ from core.memory.http_headers import CALLER_SESSION_HEADER, MEMORY_USER_KEY_HEADER
+ from core.memory.project_ids import (
+ DEFAULT_MEMORY_PROJECT_ID,
+ omitted_project_to_default,
+ parse_agent_search_project,
+ parse_ui_search_project,
+ )
from core.memory.types import RecallPolicy
try:
policy = RecallPolicy.from_payload(payload.get("policy"))
+ raw_project = omitted_project_to_default(payload.get("project"))
+ if str(request.headers.get(MEMORY_USER_KEY_HEADER) or "").strip():
+ project_id = parse_ui_search_project(raw_project)
+ else:
+ project_id = parse_agent_search_project(raw_project)
except (TypeError, ValueError):
return JSONResponse(status_code=400, content={"status": "failed", "error": "memory_invalid_input"})
current_session_id = str(request.headers.get(CALLER_SESSION_HEADER) or "").strip() or None
+ if project_id not in {DEFAULT_MEMORY_PROJECT_ID, "all"}:
+ 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.search_payload(
payload["query"],
@@ -1517,12 +1582,21 @@ def create_app(
payload = await _safe_json(request)
if (
not isinstance(payload, dict)
- or set(payload) != {"text"}
+ or not {"text"}.issubset(payload)
+ or set(payload) - {"text", "project"}
or not isinstance(payload.get("text"), str)
or not payload["text"].strip()
or len(payload["text"]) > 4_000
):
return JSONResponse(status_code=400, content={"status": "failed", "error": "memory_invalid_input"})
+ from core.memory.project_ids import omitted_project_to_default, parse_writable_memory_project
+
+ try:
+ project_id = parse_writable_memory_project(
+ omitted_project_to_default(payload.get("project"))
+ )
+ except ValueError:
+ return JSONResponse(status_code=400, content={"status": "failed", "error": "memory_invalid_input"})
from core.memory import CaptureRequest
from core.memory.http_headers import CALLER_SESSION_HEADER
diff --git a/core/memory/admission.py b/core/memory/admission.py
index 8da8fc29e..1d614bc83 100644
--- a/core/memory/admission.py
+++ b/core/memory/admission.py
@@ -101,15 +101,12 @@ class CaptureAdmission:
return None
def project_for(self, facts: InboundTurnFacts) -> str | None:
- """Derive this turn's opaque project, or None when cwd is unresolved."""
+ """Return the default Memory project. User turns do not use workdir."""
- workdir = facts.workdir
- if not isinstance(workdir, str) or not workdir or workdir != workdir.strip():
- return None
- try:
- return self._principals.project_for_workdir(workdir)
- except Exception:
- return None
+ del facts
+ from core.memory.project_ids import DEFAULT_MEMORY_PROJECT_ID
+
+ return DEFAULT_MEMORY_PROJECT_ID
def admits(self, facts: InboundTurnFacts) -> bool:
"""Admit an attributed human Workbench turn or a bound private IM turn."""
diff --git a/core/memory/everos_insight/reader.py b/core/memory/everos_insight/reader.py
index 6d2081dec..e587b3289 100644
--- a/core/memory/everos_insight/reader.py
+++ b/core/memory/everos_insight/reader.py
@@ -12,6 +12,10 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Any, TypeAlias
+from core.memory.project_ids import (
+ is_new_stored_memory_project_id,
+ is_persisted_memory_project_id,
+)
from core.memory.processing_record import (
ProcessingSourceObservations,
SourceObservation,
@@ -1358,7 +1362,7 @@ def _validated_scope(scope: MemoryReadScope) -> MemoryReadScope:
principal_id, project_id = scope
if not isinstance(principal_id, str) or not _PRINCIPAL_RE.fullmatch(principal_id):
raise ValueError("invalid memory principal")
- if not isinstance(project_id, str) or not _PROJECT_RE.fullmatch(project_id):
+ if not isinstance(project_id, str) or not is_new_stored_memory_project_id(project_id):
raise ValueError("invalid memory project")
return principal_id, project_id
@@ -1374,7 +1378,12 @@ def _memcell_scope_sql(
)
if isinstance(query_filter, _AdminMemcellFilter):
return (
- "project_id GLOB ?",
+ "(project_id = 'default' OR project_id GLOB ? OR ("
+ "length(project_id) BETWEEN 1 AND 63 "
+ "AND substr(project_id, 1, 1) GLOB '[a-z]' "
+ "AND project_id NOT GLOB '*[^a-z0-9_-]*' "
+ "AND project_id NOT IN ('all', 'personal') "
+ "AND substr(project_id, 1, 2) NOT IN ('p-', 'u-')))",
"json_extract(sender_ids_json, '$[0]') GLOB ?",
(_PROJECT_GLOB, _PRINCIPAL_GLOB),
)
@@ -1398,7 +1407,7 @@ def _memcell_scope(row: sqlite3.Row) -> MemoryReadScope | None:
if row["app_id"] != _APP_ID or not isinstance(row["project_id"], str):
return None
project_id = row["project_id"]
- if _PROJECT_RE.fullmatch(project_id) is None:
+ if not is_persisted_memory_project_id(project_id):
return None
senders = _decode_json(row["sender_ids_json"])
if (
diff --git a/core/memory/module.py b/core/memory/module.py
index 8802e5bf2..b55ed842d 100644
--- a/core/memory/module.py
+++ b/core/memory/module.py
@@ -24,11 +24,15 @@ from core.memory.attachments import (
)
from core.memory.provider_root import ProviderRoot
from core.memory.everos import MemoryProviderFailure, MemoryProviderPort
+from core.memory.project_ids import (
+ is_new_stored_memory_project_id,
+ is_persisted_memory_project_id,
+ is_writable_memory_project_id,
+)
from core.memory.store import (
MAX_NONTERMINAL_QUEUE_ROWS,
MemoryStore,
is_principal_id,
- is_project_id,
)
from core.memory.types import (
CaptureAccepted,
@@ -336,13 +340,13 @@ class MemoryModule:
) -> _SessionLifecycleResult:
"""Flush all session scopes and run one transition under every fence."""
- canonical_scopes = tuple(sorted(set(scopes)))
+ canonical_scopes = tuple(dict.fromkeys(scopes))
if (
not canonical_scopes
or not isinstance(raw_session_id, str)
or not raw_session_id
or any(
- not is_principal_id(principal_id) or not is_project_id(project_id)
+ not is_principal_id(principal_id) or not is_persisted_memory_project_id(project_id)
for principal_id, project_id in canonical_scopes
)
):
@@ -383,14 +387,21 @@ class MemoryModule:
raise
try:
+ flush_succeeded = True
for principal_id, project_id in canonical_scopes:
- await self._final_flush_under_admission(
+ flush_succeeded = (
+ await self._final_flush_under_admission(
principal_id=principal_id,
project_id=project_id,
raw_session_id=raw_session_id,
deadline=deadline,
+ )
+ and flush_succeeded
)
- return await operation()
+ result = await operation()
+ if isinstance(result, bool):
+ return result and flush_succeeded
+ return result
finally:
for admission_lock in reversed(acquired):
admission_lock.release()
@@ -546,6 +557,8 @@ class MemoryModule:
return CaptureSkipped(reason="memory_queue_full")
if result.outcome == "timestamp_invalid":
return CaptureSkipped(reason="memory_invalid_input")
+ if result.outcome == "project_limit":
+ return CaptureSkipped(reason="memory_invalid_input")
return CaptureSkipped(reason="memory_clear_failed")
async def _capture_pin_failure(self, error: MemoryErrorCode) -> CaptureReceipt:
@@ -598,6 +611,7 @@ class MemoryModule:
principal_id: str,
project_id: str,
current_session_id: str | None = None,
+ effective_mode: Literal["keyword", "vector", "hybrid", "agentic"] | None = None,
) -> RecallResult:
"""Execute one capability-gated recall decision and at most one search."""
@@ -611,7 +625,7 @@ class MemoryModule:
return OperationFailed(error="memory_invalid_input")
if not is_principal_id(principal_id):
return OperationFailed(error="memory_access_denied")
- if not is_project_id(project_id):
+ if not is_new_stored_memory_project_id(project_id):
return OperationFailed(error="memory_access_denied")
if len(query_bytes) > MAX_QUERY_BYTES:
return OperationFailed(error="memory_input_too_large")
@@ -645,29 +659,15 @@ class MemoryModule:
return OperationFailed(error="memory_store_unavailable")
requested_mode = policy.mode
- if requested_mode == "agentic":
+ if effective_mode is None:
+ effective_mode = await self.resolve_recall_mode(policy)
+ if isinstance(effective_mode, OperationFailed):
+ return effective_mode
+ if effective_mode == "agentic":
# EverOS 1.2.3 has no public model-call/token budget contract.
# A local timeout alone cannot make this policy enforceable.
if not bool(getattr(self._provider, "agentic_budget_enforced", False)):
return OperationFailed(error="memory_capability_unavailable")
- effective_mode: Literal["keyword", "vector", "hybrid", "agentic"] = "agentic"
- elif requested_mode == "keyword":
- effective_mode = "keyword"
- else:
- try:
- health = await asyncio.wait_for(
- self._provider.health_snapshot(),
- timeout=PROVIDER_READ_TIMEOUT_SECONDS,
- )
- embed_available = health.capabilities.get("embed") is True
- except Exception:
- embed_available = False
- if requested_mode == "auto":
- effective_mode = "hybrid" if embed_available else "keyword"
- elif not embed_available:
- return OperationFailed(error="memory_capability_unavailable")
- else:
- effective_mode = requested_mode
result = await self._provider_read(
lambda: self._provider.search(
principal_id,
@@ -691,6 +691,30 @@ class MemoryModule:
current_session_overlay=session_ref is not None,
)
+ async def resolve_recall_mode(
+ self,
+ policy: RecallPolicy,
+ ) -> Literal["keyword", "vector", "hybrid", "agentic"] | OperationFailed:
+ if policy.mode == "agentic":
+ if not bool(getattr(self._provider, "agentic_budget_enforced", False)):
+ return OperationFailed(error="memory_capability_unavailable")
+ return "agentic"
+ if policy.mode == "keyword":
+ return "keyword"
+ try:
+ health = await asyncio.wait_for(
+ self._provider.health_snapshot(),
+ timeout=PROVIDER_READ_TIMEOUT_SECONDS,
+ )
+ embed_available = health.capabilities.get("embed") is True
+ except Exception:
+ embed_available = False
+ if policy.mode == "auto":
+ return "hybrid" if embed_available else "keyword"
+ if not embed_available:
+ return OperationFailed(error="memory_capability_unavailable")
+ return policy.mode
+
async def profile(self, *, principal_id: str, project_id: str) -> MemoryResult:
"""Return a bounded provider profile result or one closed error category."""
@@ -698,7 +722,7 @@ class MemoryModule:
return OperationFailed(error="memory_disabled")
if not is_principal_id(principal_id):
return OperationFailed(error="memory_access_denied")
- if not is_project_id(project_id):
+ if not is_new_stored_memory_project_id(project_id):
return OperationFailed(error="memory_access_denied")
if self._clear_active or self._is_maintenance_open():
return OperationFailed(error="memory_clear_failed")
@@ -793,7 +817,7 @@ class MemoryModule:
return "memory_invalid_input"
if (
not is_principal_id(request.principal_id)
- or not is_project_id(request.project_id)
+ or not is_writable_memory_project_id(request.project_id)
or request.provenance not in {"user_input", "agent"}
):
return "memory_invalid_input"
diff --git a/core/memory/project_ids.py b/core/memory/project_ids.py
new file mode 100644
index 000000000..b18a39e05
--- /dev/null
+++ b/core/memory/project_ids.py
@@ -0,0 +1,90 @@
+"""Closed Memory project-id vocabulary.
+
+Wire values must already be lowercase. Mixed case is invalid.
+"""
+
+from __future__ import annotations
+
+import re
+
+DEFAULT_MEMORY_PROJECT_ID = "default"
+MEMORY_SEARCH_ALL_PROJECTS = "all"
+RESERVED_MEMORY_PROJECT_IDS = frozenset(
+ {DEFAULT_MEMORY_PROJECT_ID, MEMORY_SEARCH_ALL_PROJECTS, "personal"}
+)
+MAX_NAMED_MEMORY_PROJECTS = 16
+
+_NAMED_SLUG = re.compile(r"^[a-z][a-z0-9_-]{0,62}\Z")
+_LEGACY_HASH = re.compile(r"^p-[0-9a-f]{32}\Z")
+
+
+def is_legacy_memory_project_id(value: object) -> bool:
+ """Return whether *value* is an exact leftover workdir hash."""
+
+ return isinstance(value, str) and _LEGACY_HASH.fullmatch(value) is not None
+
+
+def is_named_memory_project_id(value: object) -> bool:
+ """Return whether *value* is an opt-in named slug."""
+
+ return (
+ isinstance(value, str)
+ and value not in RESERVED_MEMORY_PROJECT_IDS
+ and not value.startswith("p-")
+ and not value.startswith("u-")
+ and _NAMED_SLUG.fullmatch(value) is not None
+ )
+
+
+def is_new_stored_memory_project_id(value: object) -> bool:
+ """Return whether *value* may appear in the product catalog."""
+
+ return value == DEFAULT_MEMORY_PROJECT_ID or is_named_memory_project_id(value)
+
+
+def is_writable_memory_project_id(value: object) -> bool:
+ """Return whether a new capture or remember may target *value*."""
+
+ return is_new_stored_memory_project_id(value)
+
+
+def is_persisted_memory_project_id(value: object) -> bool:
+ """Return whether *value* may exist on disk for recovery or drain."""
+
+ return is_legacy_memory_project_id(value) or is_new_stored_memory_project_id(value)
+
+
+def parse_writable_memory_project(value: object) -> str:
+ """Parse a remember/capture project. Missing/null is not handled here."""
+
+ if not isinstance(value, str) or value != value.strip() or not value:
+ raise ValueError("invalid Memory project")
+ if not is_writable_memory_project_id(value):
+ raise ValueError("invalid Memory project")
+ return value
+
+
+def parse_agent_search_project(value: object) -> str:
+ """Parse an Agent/CLI search project. ``all`` is rejected."""
+
+ if not isinstance(value, str) or value != value.strip() or not value:
+ raise ValueError("invalid Memory project")
+ if not is_new_stored_memory_project_id(value):
+ raise ValueError("invalid Memory project")
+ return value
+
+
+def parse_ui_search_project(value: object) -> str:
+ """Parse a Settings search project. ``all`` is allowed."""
+
+ if not isinstance(value, str) or value != value.strip() or not value:
+ raise ValueError("invalid Memory project")
+ if value == MEMORY_SEARCH_ALL_PROJECTS or is_new_stored_memory_project_id(value):
+ return value
+ raise ValueError("invalid Memory project")
+
+
+def omitted_project_to_default(value: object) -> object:
+ """Map omitted/null project fields to default; leave present values alone."""
+
+ return DEFAULT_MEMORY_PROJECT_ID if value is None else value
diff --git a/core/memory/runtime.py b/core/memory/runtime.py
index 3c8f47414..2061abf1a 100644
--- a/core/memory/runtime.py
+++ b/core/memory/runtime.py
@@ -7,6 +7,7 @@ from copy import deepcopy
import logging
import os
import stat
+import time
from concurrent.futures import CancelledError as FutureCancelledError
from concurrent.futures import Future as ThreadFuture
from concurrent.futures import TimeoutError as FutureTimeoutError
@@ -82,12 +83,18 @@ from core.memory.provider_root import (
ProviderRootMetadata,
ProviderRootRollback,
)
+from core.memory.project_ids import (
+ DEFAULT_MEMORY_PROJECT_ID,
+ MEMORY_SEARCH_ALL_PROJECTS,
+)
from core.memory.store import MemoryStore, is_principal_id, is_project_id
from core.memory.snapshot import MemorySnapshot
from core.memory.types import (
MemoryFailureLogEntry,
+ MemoryItem,
MemoryItems,
MemoryResult,
+ MemoryWarningCode,
OperationFailed,
RecallItems,
RecallPolicy,
@@ -1392,7 +1399,7 @@ class MemoryRuntime:
) -> _SessionLifecycleResult:
"""Flush all session scopes and run one transition under every fence."""
- canonical_scopes = tuple(sorted(set(scopes)))
+ canonical_scopes = tuple(dict.fromkeys(scopes))
if (
not canonical_scopes
or not isinstance(raw_session_id, str)
@@ -1425,6 +1432,11 @@ class MemoryRuntime:
"profile_warning": "empty" if empty else None,
}
+ def list_memory_projects(self, principal_id: str) -> tuple[str, ...]:
+ if not self.available:
+ return (DEFAULT_MEMORY_PROJECT_ID,)
+ return self._store.list_memory_projects(principal_id)
+
async def search_payload(
self,
query: str,
@@ -1436,14 +1448,117 @@ class MemoryRuntime:
) -> dict[str, Any]:
if not self.available:
return {"status": "failed", "error": "memory_store_unavailable"}
- return _result_payload(
- await self.module.recall(
- query,
- policy=policy,
- principal_id=principal_id,
- project_id=project_id,
- current_session_id=current_session_id,
+ if project_id == MEMORY_SEARCH_ALL_PROJECTS:
+ return _result_payload(
+ await self._recall_all_projects(
+ query,
+ policy=policy,
+ principal_id=principal_id,
+ )
+ )
+ result = await self.module.recall(
+ query,
+ policy=policy,
+ principal_id=principal_id,
+ project_id=project_id,
+ current_session_id=current_session_id,
+ )
+ if isinstance(result, RecallItems):
+ result = replace(
+ result,
+ items=tuple(
+ replace(item, project=project_id) for item in result.items
+ ),
+ )
+ return _result_payload(result)
+
+ async def _recall_all_projects(
+ self,
+ query: str,
+ *,
+ policy: RecallPolicy,
+ principal_id: str,
+ ) -> RecallResult:
+ if policy.mode == "agentic" or policy.include_current_session:
+ return OperationFailed(error="memory_invalid_input")
+ deadline = time.monotonic() + 20.0
+ projects = await run_blocking(self.list_memory_projects, principal_id)
+ if not projects:
+ projects = (DEFAULT_MEMORY_PROJECT_ID,)
+ collected: list[MemoryItem] = []
+ warnings: list[MemoryWarningCode] = []
+ first_failure: OperationFailed | None = None
+ succeeded = False
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ return RecallItems(
+ items=(),
+ requested_mode=policy.mode,
+ effective_mode="keyword",
+ warnings=("memory_search_truncated",),
)
+ try:
+ effective_mode = await asyncio.wait_for(
+ self.module.resolve_recall_mode(policy),
+ timeout=remaining,
+ )
+ except asyncio.TimeoutError:
+ return RecallItems(
+ items=(),
+ requested_mode=policy.mode,
+ effective_mode="keyword",
+ warnings=("memory_search_truncated",),
+ )
+ if isinstance(effective_mode, OperationFailed):
+ return effective_mode
+ for index, project_id in enumerate(projects):
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ warnings.append("memory_search_truncated")
+ break
+ scope_policy = replace(
+ policy,
+ include_current_session=False,
+ include_profile=bool(policy.include_profile and index == 0),
+ )
+ try:
+ result = await asyncio.wait_for(
+ self.module.recall(
+ query,
+ policy=scope_policy,
+ principal_id=principal_id,
+ project_id=project_id,
+ effective_mode=effective_mode,
+ ),
+ timeout=remaining,
+ )
+ except asyncio.TimeoutError:
+ warnings.append("memory_search_truncated")
+ break
+ if isinstance(result, OperationFailed):
+ if first_failure is None:
+ first_failure = result
+ warnings.append("memory_search_partial")
+ continue
+ succeeded = True
+ effective_mode = result.effective_mode
+ collected.extend(
+ replace(item, project=project_id) for item in result.items
+ )
+ if not succeeded:
+ return first_failure or RecallItems(
+ items=(),
+ requested_mode=policy.mode,
+ effective_mode=effective_mode,
+ warnings=tuple(dict.fromkeys(warnings)),
+ )
+ merged = _merge_search_items(collected, limit=policy.max_results)
+ unique_warnings = tuple(dict.fromkeys(warnings))
+ return RecallItems(
+ items=merged,
+ requested_mode=policy.mode,
+ effective_mode=effective_mode,
+ warnings=unique_warnings,
)
async def log_entries_payload(
@@ -3218,3 +3333,32 @@ def _result_payload(result: MemoryResult | RecallResult) -> dict[str, Any]:
"freshness": result.freshness,
}
return {"status": "failed", "error": "memory_processing_failed"}
+
+
+def _merge_search_items(items: list[MemoryItem], *, limit: int) -> tuple[MemoryItem, ...]:
+ ordered = sorted(
+ items,
+ key=lambda item: (
+ item.date is None,
+ item.date or "",
+ item.kind,
+ item.text,
+ item.project or "",
+ ),
+ reverse=False,
+ )
+ # date desc: invert the date key by sorting then reversing date-bearing first
+ dated = [item for item in ordered if item.date is not None]
+ undated = [item for item in ordered if item.date is None]
+ dated.sort(key=lambda item: item.date or "", reverse=True)
+ merged: list[MemoryItem] = []
+ seen: set[tuple[str, str, str | None, str | None]] = set()
+ for item in (*dated, *undated):
+ key = (item.kind, item.text, item.date, item.project)
+ if key in seen:
+ continue
+ seen.add(key)
+ merged.append(item)
+ if len(merged) >= limit:
+ break
+ return tuple(merged)
diff --git a/core/memory/schema.sql b/core/memory/schema.sql
index cbc0089ce..abe1a93f1 100644
--- a/core/memory/schema.sql
+++ b/core/memory/schema.sql
@@ -98,9 +98,19 @@ CREATE TABLE IF NOT EXISTS memory_capture_queue (
AND substr(principal_id, 3) NOT GLOB '*[^0-9a-f]*'
),
project_ref TEXT NOT NULL CHECK (
- length(project_ref) = 34
- AND substr(project_ref, 1, 2) = 'p-'
- AND substr(project_ref, 3) NOT GLOB '*[^0-9a-f]*'
+ project_ref = 'default'
+ OR (
+ length(project_ref) = 34
+ AND substr(project_ref, 1, 2) = 'p-'
+ AND substr(project_ref, 3) NOT GLOB '*[^0-9a-f]*'
+ )
+ OR (
+ length(project_ref) BETWEEN 1 AND 63
+ AND substr(project_ref, 1, 1) GLOB '[a-z]'
+ AND project_ref NOT GLOB '*[^a-z0-9_-]*'
+ AND project_ref NOT IN ('all', 'personal', 'default')
+ AND substr(project_ref, 1, 2) NOT IN ('p-', 'u-')
+ )
),
provenance TEXT NOT NULL CHECK (provenance IN ('user_input', 'agent')),
payload_text TEXT,
@@ -136,6 +146,27 @@ CREATE TABLE IF NOT EXISTS memory_capture_queue (
)
);
+CREATE TABLE IF NOT EXISTS memory_projects (
+ principal_id TEXT NOT NULL CHECK (
+ length(principal_id) = 34
+ AND substr(principal_id, 1, 2) = 'u-'
+ AND substr(principal_id, 3) NOT GLOB '*[^0-9a-f]*'
+ ),
+ project_id TEXT NOT NULL CHECK (
+ project_id = 'default'
+ OR (
+ length(project_id) BETWEEN 1 AND 63
+ AND substr(project_id, 1, 1) GLOB '[a-z]'
+ AND project_id NOT GLOB '*[^a-z0-9_-]*'
+ AND project_id NOT IN ('all', 'personal', 'default')
+ AND substr(project_id, 1, 2) NOT IN ('p-', 'u-')
+ )
+ ),
+ created_at TEXT NOT NULL,
+ last_written_at TEXT NOT NULL,
+ PRIMARY KEY (principal_id, project_id)
+);
+
CREATE INDEX IF NOT EXISTS ix_memory_capture_due
ON memory_capture_queue (epoch, state, next_retry_at);
diff --git a/core/memory/schema_v2.sql b/core/memory/schema_v2.sql
new file mode 100644
index 000000000..cbc0089ce
--- /dev/null
+++ b/core/memory/schema_v2.sql
@@ -0,0 +1,191 @@
+-- Initial Memory schema for new databases.
+CREATE TABLE IF NOT EXISTS memory_meta (
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
+ epoch INTEGER NOT NULL,
+ clear_in_progress INTEGER NOT NULL DEFAULT 0 CHECK (clear_in_progress IN (0, 1)),
+ scope_key BLOB NOT NULL,
+ provider_root_id TEXT NOT NULL,
+ last_provider_timestamp_ms INTEGER NOT NULL DEFAULT 0,
+ missed_count INTEGER NOT NULL DEFAULT 0 CHECK (missed_count >= 0),
+ last_success_at TEXT,
+ last_error TEXT CHECK (
+ last_error IS NULL OR last_error IN (
+ 'memory_disabled', 'memory_invalid_input', 'memory_input_too_large',
+ 'memory_queue_full', 'memory_low_disk_space', 'memory_store_unavailable',
+ 'memory_runtime_missing', 'memory_runtime_unsupported',
+ 'memory_runtime_install_failed', 'memory_sidecar_unavailable',
+ 'memory_provider_timeout', 'memory_provider_response_invalid',
+ 'memory_processing_failed', 'memory_clear_failed',
+ 'memory_capability_unavailable'
+ )
+ ),
+ last_error_at TEXT,
+ processing_fault_generation INTEGER NOT NULL DEFAULT 0 CHECK (
+ processing_fault_generation >= 0
+ ),
+ processing_fault_kind TEXT CHECK (
+ processing_fault_kind IS NULL OR processing_fault_kind IN ('credential', 'engine')
+ ),
+ processing_fault_since TEXT,
+ processing_alert_active INTEGER NOT NULL DEFAULT 0 CHECK (
+ processing_alert_active IN (0, 1)
+ ),
+ processing_recovery_pending_at TEXT,
+ processing_recovery_generation INTEGER CHECK (
+ processing_recovery_generation IS NULL OR processing_recovery_generation >= 0
+ ),
+ updated_at TEXT NOT NULL,
+ CHECK (
+ (processing_recovery_pending_at IS NULL
+ AND processing_recovery_generation IS NULL)
+ OR
+ (processing_recovery_pending_at IS NOT NULL
+ AND processing_recovery_generation IS NOT NULL)
+ )
+);
+
+CREATE TABLE IF NOT EXISTS memory_attachment_bundle (
+ bundle_id TEXT PRIMARY KEY CHECK (
+ length(bundle_id) = 32
+ AND bundle_id NOT GLOB '*[^0-9a-f]*'
+ ),
+ relative_path TEXT NOT NULL UNIQUE,
+ state TEXT NOT NULL CHECK (state IN ('pinned', 'releasing')),
+ file_count INTEGER NOT NULL CHECK (file_count BETWEEN 1 AND 8),
+ total_bytes INTEGER NOT NULL CHECK (total_bytes >= 0),
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+);
+
+CREATE TABLE IF NOT EXISTS memory_session_flush_state (
+ provider_session_ref TEXT PRIMARY KEY,
+ epoch INTEGER NOT NULL CHECK (epoch >= 0),
+ open_generation INTEGER NOT NULL DEFAULT 1 CHECK (open_generation >= 1),
+ target_generation INTEGER CHECK (target_generation IS NULL OR target_generation >= 1),
+ state TEXT NOT NULL DEFAULT 'idle' CHECK (
+ state IN ('idle', 'due', 'in_flight', 'manual_required')
+ ),
+ first_unflushed_at TEXT,
+ last_add_ack_at TEXT,
+ confirmed_add_watermark_ms INTEGER,
+ unflushed_count INTEGER NOT NULL DEFAULT 0 CHECK (unflushed_count >= 0),
+ due_at TEXT,
+ next_attempt_at TEXT,
+ retry_count INTEGER NOT NULL DEFAULT 0 CHECK (retry_count >= 0),
+ operation_epoch INTEGER NOT NULL DEFAULT 0 CHECK (operation_epoch >= 0),
+ fence_token TEXT,
+ submission_started_at TEXT,
+ updated_at TEXT NOT NULL,
+ CHECK (
+ (state = 'idle' AND target_generation IS NULL AND fence_token IS NULL
+ AND submission_started_at IS NULL)
+ OR
+ (state IN ('due', 'in_flight', 'manual_required')
+ AND target_generation IS NOT NULL AND fence_token IS NOT NULL)
+ ),
+ CHECK (state IN ('in_flight', 'manual_required') OR submission_started_at IS NULL)
+);
+
+CREATE TABLE IF NOT EXISTS memory_capture_queue (
+ source_message_digest TEXT PRIMARY KEY,
+ epoch INTEGER NOT NULL,
+ session_id TEXT NOT NULL,
+ provider_session_ref TEXT NOT NULL,
+ generation INTEGER NOT NULL CHECK (generation >= 1),
+ principal_id TEXT NOT NULL CHECK (
+ length(principal_id) = 34
+ AND substr(principal_id, 1, 2) = 'u-'
+ AND substr(principal_id, 3) NOT GLOB '*[^0-9a-f]*'
+ ),
+ project_ref TEXT NOT NULL CHECK (
+ length(project_ref) = 34
+ AND substr(project_ref, 1, 2) = 'p-'
+ AND substr(project_ref, 3) NOT GLOB '*[^0-9a-f]*'
+ ),
+ provenance TEXT NOT NULL CHECK (provenance IN ('user_input', 'agent')),
+ payload_text TEXT,
+ payload_attachments TEXT,
+ attachment_bundle_id TEXT REFERENCES memory_attachment_bundle(bundle_id) ON DELETE RESTRICT,
+ occurred_at_ms INTEGER NOT NULL,
+ provider_timestamp_ms INTEGER NOT NULL,
+ state TEXT NOT NULL CHECK (
+ state IN ('pending', 'processing', 'delivered', 'dead', 'manual_required')
+ ),
+ attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0),
+ next_retry_at TEXT,
+ lease_owner TEXT,
+ lease_at TEXT,
+ lease_token INTEGER NOT NULL DEFAULT 0 CHECK (lease_token >= 0),
+ last_error TEXT CHECK (
+ last_error IS NULL OR last_error IN (
+ 'memory_disabled', 'memory_invalid_input', 'memory_input_too_large',
+ 'memory_queue_full', 'memory_low_disk_space', 'memory_store_unavailable',
+ 'memory_runtime_missing', 'memory_runtime_unsupported',
+ 'memory_runtime_install_failed', 'memory_sidecar_unavailable',
+ 'memory_provider_timeout', 'memory_provider_response_invalid',
+ 'memory_processing_failed', 'memory_clear_failed'
+ )
+ ),
+ add_request_id TEXT,
+ add_status TEXT CHECK (add_status IS NULL OR add_status IN ('accumulated', 'extracted')),
+ created_at TEXT NOT NULL,
+ completed_at TEXT,
+ CHECK (
+ (state IN ('pending', 'processing', 'manual_required') AND payload_text IS NOT NULL)
+ OR (state IN ('delivered', 'dead') AND payload_text IS NULL)
+ )
+);
+
+CREATE INDEX IF NOT EXISTS ix_memory_capture_due
+ ON memory_capture_queue (epoch, state, next_retry_at);
+
+CREATE INDEX IF NOT EXISTS ix_memory_capture_session_generation
+ ON memory_capture_queue (provider_session_ref, epoch, generation, state);
+
+CREATE INDEX IF NOT EXISTS ix_memory_session_flush_due
+ ON memory_session_flush_state (epoch, state, due_at, next_attempt_at);
+
+CREATE TABLE IF NOT EXISTS memory_flush_settlements (
+ settlement_id INTEGER PRIMARY KEY AUTOINCREMENT,
+ provider_session_ref TEXT NOT NULL,
+ epoch INTEGER NOT NULL CHECK (epoch >= 0),
+ generation INTEGER NOT NULL CHECK (generation >= 1),
+ operation_kind TEXT NOT NULL CHECK (operation_kind IN ('add', 'flush')),
+ operation_token TEXT NOT NULL,
+ observation TEXT NOT NULL CHECK (
+ observation IN ('settled', 'rejected', 'manual_required')
+ ),
+ request_id TEXT,
+ confirmed_watermark_ms INTEGER,
+ observed_at TEXT NOT NULL,
+ error_code TEXT,
+ recovery_origin TEXT CHECK (recovery_origin IS NULL OR recovery_origin = 'boot'),
+ attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0),
+ CHECK (
+ (operation_kind = 'add' AND observation = 'rejected' AND attempts >= 1)
+ OR
+ (NOT (operation_kind = 'add' AND observation = 'rejected') AND attempts = 0)
+ ),
+ UNIQUE (
+ provider_session_ref, epoch, generation, operation_kind, operation_token
+ )
+);
+
+CREATE INDEX IF NOT EXISTS ix_memory_flush_settlements_recent
+ ON memory_flush_settlements (epoch, observed_at DESC, settlement_id DESC);
+
+CREATE TRIGGER IF NOT EXISTS trg_memory_flush_settlements_immutable
+BEFORE UPDATE ON memory_flush_settlements
+BEGIN
+ SELECT RAISE(ABORT, 'memory flush settlements are immutable');
+END;
+
+CREATE TRIGGER IF NOT EXISTS trg_memory_flush_settlements_no_delete
+BEFORE DELETE ON memory_flush_settlements
+WHEN COALESCE(
+ (SELECT clear_in_progress FROM memory_meta WHERE singleton = 1),
+ 0
+) != 1
+BEGIN
+ SELECT RAISE(ABORT, 'memory flush settlements are immutable');
+END;
diff --git a/core/memory/sidecar.py b/core/memory/sidecar.py
index 7736eef68..14072b6e3 100644
--- a/core/memory/sidecar.py
+++ b/core/memory/sidecar.py
@@ -17,6 +17,10 @@ from typing import Any
from urllib.parse import unquote, urlparse
from core.memory.artifact import EVEROS_VERSION
+from core.memory.project_ids import (
+ is_new_stored_memory_project_id,
+ is_persisted_memory_project_id,
+)
from core.memory.everos_insight import install_error_scrubbers, prepare_call_recorder
from core.memory.everos_insight.patches import boundary_request
from core.memory.modality import SUPPORTED_ATTACHMENT_EXTENSIONS
@@ -25,7 +29,6 @@ from core.memory.modality import SUPPORTED_ATTACHMENT_EXTENSIONS
_MAX_BODY_BYTES = 64 * 1024
_APP_ID = "avibe"
_PRINCIPAL_PATTERN = re.compile(r"u-[0-9a-f]{32}\Z")
-_PROJECT_PATTERN = re.compile(r"p-[0-9a-f]{32}\Z")
_SESSION_PATTERN = re.compile(r"src--[0-9a-f]{64}--e(?:0|[1-9][0-9]*)\Z")
logger = logging.getLogger(__name__)
@@ -201,13 +204,14 @@ def _request_rejection(
return _validate_get(payload)
-def _valid_scope(payload: dict[str, Any]) -> bool:
+def _valid_write_scope(payload: dict[str, Any]) -> bool:
project_id = payload.get("project_id")
- return (
- payload.get("app_id") == _APP_ID
- and isinstance(project_id, str)
- and _PROJECT_PATTERN.fullmatch(project_id) is not None
- )
+ return payload.get("app_id") == _APP_ID and is_persisted_memory_project_id(project_id)
+
+
+def _valid_search_scope(payload: dict[str, Any]) -> bool:
+ project_id = payload.get("project_id")
+ return payload.get("app_id") == _APP_ID and is_new_stored_memory_project_id(project_id)
def _exact_keys(payload: dict[str, Any], keys: set[str]) -> bool:
@@ -219,7 +223,7 @@ def _validate_add(
*,
attachments_root: Path | None,
) -> str | None:
- if not _exact_keys(payload, {"session_id", "app_id", "project_id", "messages"}) or not _valid_scope(payload):
+ if not _exact_keys(payload, {"session_id", "app_id", "project_id", "messages"}) or not _valid_write_scope(payload):
return "add"
messages = payload.get("messages")
if not _valid_session(payload.get("session_id")) or not isinstance(messages, list) or len(messages) != 1:
@@ -289,7 +293,7 @@ def _valid_workbench_attachment(item: dict[str, Any], attachments_root: Path | N
def _validate_flush(payload: dict[str, Any]) -> str | None:
- if not _exact_keys(payload, {"session_id", "app_id", "project_id"}) or not _valid_scope(payload):
+ if not _exact_keys(payload, {"session_id", "app_id", "project_id"}) or not _valid_write_scope(payload):
return "flush"
return None if _valid_session(payload.get("session_id")) else "flush"
@@ -307,7 +311,7 @@ def _validate_search(payload: dict[str, Any]) -> str | None:
}
if frozenset(payload) not in {frozenset(required), frozenset((*required, "filters"))}:
return "search"
- if not _valid_scope(payload):
+ if not _valid_search_scope(payload):
return "search"
if (
not _valid_principal(payload.get("user_id"))
diff --git a/core/memory/store.py b/core/memory/store.py
index e5e003012..2444bb048 100644
--- a/core/memory/store.py
+++ b/core/memory/store.py
@@ -25,6 +25,15 @@ from core.memory.observations import (
FlushSucceeded,
FlushUnknown,
)
+from core.memory.project_ids import (
+ DEFAULT_MEMORY_PROJECT_ID,
+ MAX_NAMED_MEMORY_PROJECTS,
+ is_legacy_memory_project_id,
+ is_named_memory_project_id,
+ is_new_stored_memory_project_id,
+ is_persisted_memory_project_id,
+ is_writable_memory_project_id,
+)
from core.memory.types import (
MemoryErrorCode,
MemoryFailureLogEntry,
@@ -35,7 +44,7 @@ from core.memory.types import (
MEMORY_STORE_FILENAME = "memory.sqlite"
MEMORY_STORE_DIRNAME = "memory"
-MEMORY_STORE_SCHEMA_VERSION = 2
+MEMORY_STORE_SCHEMA_VERSION = 3
MAX_NONTERMINAL_QUEUE_ROWS = 500
MAX_MESSAGE_ATTEMPTS = 3
TERMINAL_TOMBSTONE_LIMIT = 100_000
@@ -48,6 +57,7 @@ _MEMORY_STORE_TABLES = frozenset(
"memory_session_flush_state",
"memory_capture_queue",
"memory_flush_settlements",
+ "memory_projects",
}
)
_MEMORY_STORE_REQUIRED_COLUMNS = {
@@ -89,6 +99,14 @@ _MEMORY_STORE_REQUIRED_COLUMNS = {
"attempts",
}
),
+ "memory_projects": frozenset(
+ {
+ "principal_id",
+ "project_id",
+ "created_at",
+ "last_written_at",
+ }
+ ),
}
_MEMORY_STORE_INDEXES = frozenset(
{
@@ -523,7 +541,7 @@ def _migrate_v0_to_v2(
)
conn.execute("DROP TABLE memory_capture_queue_v0")
conn.execute("DROP TABLE memory_meta_v0")
- conn.execute(f"PRAGMA user_version = {MEMORY_STORE_SCHEMA_VERSION}")
+ conn.execute("PRAGMA user_version = 2")
except BaseException:
conn.execute("ROLLBACK")
raise
@@ -572,7 +590,143 @@ def _migrate_v1_to_v2(conn: sqlite3.Connection) -> None:
WHERE singleton = 1
"""
)
- conn.execute(f"PRAGMA user_version = {MEMORY_STORE_SCHEMA_VERSION}")
+ conn.execute("PRAGMA user_version = 2")
+ except BaseException:
+ conn.execute("ROLLBACK")
+ raise
+ else:
+ conn.execute("COMMIT")
+
+
+def _migrate_v2_to_v3(conn: sqlite3.Connection) -> None:
+ """Widen project_ref and add the durable project catalog."""
+
+ conn.execute("BEGIN IMMEDIATE")
+ try:
+ conn.execute("DROP INDEX IF EXISTS ix_memory_capture_due")
+ conn.execute("DROP INDEX IF EXISTS ix_memory_capture_session_generation")
+ conn.execute("ALTER TABLE memory_capture_queue RENAME TO memory_capture_queue_v2")
+ conn.execute(
+ """
+ CREATE TABLE memory_capture_queue (
+ source_message_digest TEXT PRIMARY KEY,
+ epoch INTEGER NOT NULL,
+ session_id TEXT NOT NULL,
+ provider_session_ref TEXT NOT NULL,
+ generation INTEGER NOT NULL CHECK (generation >= 1),
+ principal_id TEXT NOT NULL CHECK (
+ length(principal_id) = 34
+ AND substr(principal_id, 1, 2) = 'u-'
+ AND substr(principal_id, 3) NOT GLOB '*[^0-9a-f]*'
+ ),
+ project_ref TEXT NOT NULL CHECK (
+ project_ref = 'default'
+ OR (
+ length(project_ref) = 34
+ AND substr(project_ref, 1, 2) = 'p-'
+ AND substr(project_ref, 3) NOT GLOB '*[^0-9a-f]*'
+ )
+ OR (
+ length(project_ref) BETWEEN 1 AND 63
+ AND substr(project_ref, 1, 1) GLOB '[a-z]'
+ AND project_ref NOT GLOB '*[^a-z0-9_-]*'
+ AND project_ref NOT IN ('all', 'personal', 'default')
+ AND substr(project_ref, 1, 2) NOT IN ('p-', 'u-')
+ )
+ ),
+ provenance TEXT NOT NULL CHECK (provenance IN ('user_input', 'agent')),
+ payload_text TEXT,
+ payload_attachments TEXT,
+ attachment_bundle_id TEXT REFERENCES memory_attachment_bundle(bundle_id) ON DELETE RESTRICT,
+ occurred_at_ms INTEGER NOT NULL,
+ provider_timestamp_ms INTEGER NOT NULL,
+ state TEXT NOT NULL CHECK (
+ state IN ('pending', 'processing', 'delivered', 'dead', 'manual_required')
+ ),
+ attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0),
+ next_retry_at TEXT,
+ lease_owner TEXT,
+ lease_at TEXT,
+ lease_token INTEGER NOT NULL DEFAULT 0 CHECK (lease_token >= 0),
+ last_error TEXT CHECK (
+ last_error IS NULL OR last_error IN (
+ 'memory_disabled', 'memory_invalid_input', 'memory_input_too_large',
+ 'memory_queue_full', 'memory_low_disk_space', 'memory_store_unavailable',
+ 'memory_runtime_missing', 'memory_runtime_unsupported',
+ 'memory_runtime_install_failed', 'memory_sidecar_unavailable',
+ 'memory_provider_timeout', 'memory_provider_response_invalid',
+ 'memory_processing_failed', 'memory_clear_failed'
+ )
+ ),
+ add_request_id TEXT,
+ add_status TEXT CHECK (add_status IS NULL OR add_status IN ('accumulated', 'extracted')),
+ created_at TEXT NOT NULL,
+ completed_at TEXT,
+ CHECK (
+ (state IN ('pending', 'processing', 'manual_required') AND payload_text IS NOT NULL)
+ OR (state IN ('delivered', 'dead') AND payload_text IS NULL)
+ )
+ )
+ """
+ )
+ conn.execute(
+ "INSERT INTO memory_capture_queue SELECT * FROM memory_capture_queue_v2"
+ )
+ conn.execute("DROP TABLE memory_capture_queue_v2")
+ conn.execute(
+ """
+ CREATE INDEX ix_memory_capture_due
+ ON memory_capture_queue (epoch, state, next_retry_at)
+ """
+ )
+ conn.execute(
+ """
+ CREATE INDEX ix_memory_capture_session_generation
+ ON memory_capture_queue (provider_session_ref, epoch, generation, state)
+ """
+ )
+ conn.execute(
+ """
+ CREATE TABLE IF NOT EXISTS memory_projects (
+ principal_id TEXT NOT NULL CHECK (
+ length(principal_id) = 34
+ AND substr(principal_id, 1, 2) = 'u-'
+ AND substr(principal_id, 3) NOT GLOB '*[^0-9a-f]*'
+ ),
+ project_id TEXT NOT NULL CHECK (
+ project_id = 'default'
+ OR (
+ length(project_id) BETWEEN 1 AND 63
+ AND substr(project_id, 1, 1) GLOB '[a-z]'
+ AND project_id NOT GLOB '*[^a-z0-9_-]*'
+ AND project_id NOT IN ('all', 'personal', 'default')
+ AND substr(project_id, 1, 2) NOT IN ('p-', 'u-')
+ )
+ ),
+ created_at TEXT NOT NULL,
+ last_written_at TEXT NOT NULL,
+ PRIMARY KEY (principal_id, project_id)
+ )
+ """
+ )
+ for row in conn.execute(
+ "SELECT DISTINCT principal_id, project_ref FROM memory_capture_queue"
+ ):
+ project_ref = str(row["project_ref"])
+ if not is_new_stored_memory_project_id(project_ref):
+ continue
+ conn.execute(
+ """
+ INSERT OR IGNORE INTO memory_projects (
+ principal_id, project_id, created_at, last_written_at
+ ) VALUES (?, ?, ?, ?)
+ """,
+ (str(row["principal_id"]), project_ref, utc_now_iso(), utc_now_iso()),
+ )
+ leftover = conn.execute("PRAGMA foreign_key_check").fetchall()
+ if leftover:
+ raise RuntimeError("Memory store foreign keys failed after v3 migration")
+ conn.execute("PRAGMA user_version = 3")
_verify_current_schema(conn)
except BaseException:
conn.execute("ROLLBACK")
@@ -706,7 +860,14 @@ class QueueStats:
@dataclass(frozen=True)
class EnqueueResult:
- outcome: Literal["accepted", "duplicate", "queue_full", "clearing", "timestamp_invalid"]
+ outcome: Literal[
+ "accepted",
+ "duplicate",
+ "queue_full",
+ "clearing",
+ "timestamp_invalid",
+ "project_limit",
+ ]
row: QueueRow | None = None
@@ -992,6 +1153,27 @@ class MemoryStore:
meta = self.get_meta()
return bool(meta and meta.clear_in_progress)
+ def list_memory_projects(self, principal_id: str) -> tuple[str, ...]:
+ """Return implicit default plus catalogued named slugs for one principal."""
+
+ if not is_principal_id(principal_id):
+ raise ValueError("invalid Memory principal")
+ with self._connection() as conn:
+ rows = conn.execute(
+ """
+ SELECT project_id, last_written_at FROM memory_projects
+ WHERE principal_id = ? AND project_id != ?
+ ORDER BY last_written_at DESC, project_id ASC
+ """,
+ (principal_id, DEFAULT_MEMORY_PROJECT_ID),
+ ).fetchall()
+ named = tuple(
+ str(row["project_id"])
+ for row in rows
+ if is_named_memory_project_id(str(row["project_id"]))
+ )
+ return (DEFAULT_MEMORY_PROJECT_ID, *named)
+
def record_capture_skip(self, error: MemoryErrorCode | None) -> None:
"""Record a closed admission skip without retaining rejected input."""
@@ -1026,7 +1208,7 @@ class MemoryStore:
if (
not is_principal_id(principal_id)
- or not is_project_id(project_ref)
+ or not is_writable_memory_project_id(project_ref)
or provenance not in {"user_input", "agent"}
):
raise ValueError("invalid Memory capture identity")
@@ -1043,6 +1225,12 @@ class MemoryStore:
(source_message_digest,),
).fetchone()
if existing is not None:
+ _upsert_memory_project(
+ conn,
+ principal_id=principal_id,
+ project_id=project_ref,
+ now=now,
+ )
return EnqueueResult(outcome="duplicate", row=_queue_from_row(existing))
pending_count = int(
@@ -1063,6 +1251,26 @@ class MemoryStore:
if provider_timestamp_ms > max_provider_timestamp_ms:
self._record_capture_skip_in_connection(conn, None, now)
return EnqueueResult(outcome="timestamp_invalid")
+ if is_named_memory_project_id(project_ref):
+ existing_named = conn.execute(
+ """
+ SELECT 1 FROM memory_projects
+ WHERE principal_id = ? AND project_id = ?
+ """,
+ (principal_id, project_ref),
+ ).fetchone()
+ if existing_named is None:
+ named_count = int(
+ conn.execute(
+ """
+ SELECT COUNT(*) FROM memory_projects
+ WHERE principal_id = ? AND project_id != ?
+ """,
+ (principal_id, DEFAULT_MEMORY_PROJECT_ID),
+ ).fetchone()[0]
+ )
+ if named_count >= MAX_NAMED_MEMORY_PROJECTS:
+ return EnqueueResult(outcome="project_limit")
session_id_ref = _provider_session_ref(
meta.scope_key,
@@ -1176,6 +1384,12 @@ class MemoryStore:
now,
),
)
+ _upsert_memory_project(
+ conn,
+ principal_id=principal_id,
+ project_id=project_ref,
+ now=now,
+ )
return EnqueueResult(
outcome="accepted",
row=QueueRow(
@@ -2920,6 +3134,7 @@ class MemoryStore:
conn.execute("DELETE FROM memory_flush_settlements")
conn.execute("DELETE FROM memory_session_flush_state")
conn.execute("DELETE FROM memory_attachment_bundle")
+ conn.execute("DELETE FROM memory_projects")
conn.execute(
"""
UPDATE memory_meta
@@ -3135,15 +3350,14 @@ class MemoryStore:
def _initialize(self) -> None:
schema_sql = Path(__file__).with_name("schema.sql").read_text(encoding="utf-8")
+ v2_schema_sql = Path(__file__).with_name("schema_v2.sql").read_text(encoding="utf-8")
# Store migrations deliberately compose on this already-open connection.
with self._connection() as conn:
version = int(conn.execute("PRAGMA user_version").fetchone()[0])
application_tables = _application_tables(conn)
- if version == 1:
- _migrate_v1_to_v2(conn)
- elif version not in {0, MEMORY_STORE_SCHEMA_VERSION}:
+ if version not in {0, 1, 2, MEMORY_STORE_SCHEMA_VERSION}:
raise RuntimeError(f"Unsupported Memory store schema version: {version}")
- elif version == 0:
+ if version == 0:
if not application_tables:
_install_clean_schema(conn, schema_sql, application_tables)
else:
@@ -3155,9 +3369,15 @@ class MemoryStore:
)
_migrate_v0_to_v2(
conn,
- schema_sql,
+ v2_schema_sql,
has_provider_ref=has_provider_ref,
)
+ version = 2
+ if version == 1:
+ _migrate_v1_to_v2(conn)
+ version = 2
+ if version == 2:
+ _migrate_v2_to_v3(conn)
_verify_current_schema(conn)
@contextmanager
@@ -3635,13 +3855,27 @@ def is_principal_id(value: object) -> bool:
def is_project_id(value: object) -> bool:
- """Return whether a value has the exact opaque Memory project shape."""
+ """Compatibility alias for persisted project ids. Do not use on new writes."""
- return (
- isinstance(value, str)
- and len(value) == 34
- and value.startswith("p-")
- and all(character in "0123456789abcdef" for character in value[2:])
+ return is_persisted_memory_project_id(value)
+
+
+def _upsert_memory_project(
+ conn: sqlite3.Connection,
+ *,
+ principal_id: str,
+ project_id: str,
+ now: str,
+) -> None:
+ if not is_new_stored_memory_project_id(project_id):
+ return
+ conn.execute(
+ """
+ INSERT INTO memory_projects (principal_id, project_id, created_at, last_written_at)
+ VALUES (?, ?, ?, ?)
+ ON CONFLICT(principal_id, project_id) DO UPDATE SET last_written_at = excluded.last_written_at
+ """,
+ (principal_id, project_id, now, now),
)
diff --git a/core/memory/types.py b/core/memory/types.py
index 97e5cfb65..ded179b64 100644
--- a/core/memory/types.py
+++ b/core/memory/types.py
@@ -292,12 +292,23 @@ class MemoryProfile:
updated_at: str | None = None
+MemoryWarningCode = Literal["memory_search_partial", "memory_search_truncated"]
+CLOSED_MEMORY_WARNING_CODES = frozenset(
+ {"memory_search_partial", "memory_search_truncated"}
+)
+
+
+def is_memory_warning_code(value: object) -> bool:
+ return isinstance(value, str) and value in CLOSED_MEMORY_WARNING_CODES
+
+
@dataclass(frozen=True)
class MemoryItem:
kind: MemoryKind
text: str
date: str | None = None
profile: MemoryProfile | None = None
+ project: str | None = None
def memory_profile_payload(profile: MemoryProfile) -> dict[str, Any]:
@@ -336,13 +347,15 @@ def memory_item_payload(item: MemoryItem) -> dict[str, Any]:
}
if item.profile is not None:
payload["profile"] = memory_profile_payload(item.profile)
+ if item.project is not None:
+ payload["project"] = item.project
return payload
@dataclass(frozen=True)
class MemoryItems:
items: tuple[MemoryItem, ...] = ()
- warnings: tuple[MemoryErrorCode, ...] = ()
+ warnings: tuple[MemoryErrorCode | MemoryWarningCode, ...] = ()
status: Literal["ok"] = "ok"
@@ -458,7 +471,7 @@ class RecallItems:
current_session_overlay: bool = False
watermark_ms: int | None = None
freshness: Literal["unknown"] = "unknown"
- warnings: tuple[MemoryErrorCode, ...] = ()
+ warnings: tuple[MemoryErrorCode | MemoryWarningCode, ...] = ()
status: Literal["ok"] = "ok"
diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.py
index 5fb972aa0..e29bc3ff6 100644
--- a/core/system_prompt_injection.py
+++ b/core/system_prompt_injection.py
@@ -433,10 +433,12 @@ _MEMORY_CLI_PROMPT = """\
## Personal Memory
Avibe Memory is enabled for this conversation. Read Memory through the scoped CLI when durable personal context would materially improve the answer, and write to it whenever the conversation produces something worth carrying forward.
-- `vibe memory search "<query>" --json` searches recalled episodes and facts.
+- `vibe memory search "<query>" --json` searches this user's default Memory project.
+- `vibe memory search "<query>" --project <slug> --json` searches one named project. Slugs are lowercase `^[a-z][a-z0-9_-]{0,62}$` and cannot be `all`, `personal`, mixed case, empty, or start with `p-` / `u-`. Never use `--project all`.
- `vibe memory profile --json` reads the current distilled profile.
- `vibe memory status --json` is for diagnosing Memory availability and processing state.
-- `vibe memory remember "<text>" --json` queues one durable fact.
+- `vibe memory remember "<text>" --json` queues one durable fact in `default`.
+- `vibe memory remember "<text>" --project <slug> --json` stores the fact in that named project only when the user explicitly wants it there. The same slug rules apply.
### When to remember
When the user explicitly asks you to remember, note, or keep track of something, first apply the same eligibility, safety, and surface rules below. If the request is a durable, non-secret personal fact or stable user habit and the user did not name another destination, record it with `remember`. An explicit request overrides only the plain-text no-paraphrase rule below: it never makes project knowledge, one-off task detail, transient state, or secrets eligible for Memory. Route project knowledge to `AGENTS.md`, honor a specifically named surface, and otherwise explain briefly when the request cannot be saved.
diff --git a/docs/CLI.md b/docs/CLI.md
index c5548b89f..5bde2f70e 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -128,8 +128,8 @@ Read scoped local Memory or queue durable context to remember — facts the user
```bash
vibe memory status [--json]
vibe memory profile [--json]
-vibe memory search <query> [--limit 1..20] [--json]
-vibe memory remember <text> [--json]
+vibe memory search <query> [--project <slug>] [--limit 1..20] [--json]
+vibe memory remember <text> [--project <slug>] [--json]
```
### `vibe doctor`
diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.md
index a460fdcbf..ebae05074 100644
--- a/docs/CLI_ZH.md
+++ b/docs/CLI_ZH.md
@@ -109,8 +109,8 @@ vibe status
```bash
vibe memory status [--json]
vibe memory profile [--json]
-vibe memory search <查询> [--limit 1..20] [--json]
-vibe memory remember <文本> [--json]
+vibe memory search <查询> [--project <slug>] [--limit 1..20] [--json]
+vibe memory remember <文本> [--project <slug>] [--json]
```
### `vibe doctor`
diff --git a/docs/plans/memory-default-project-1393.md b/docs/plans/memory-default-project-1393.md
new file mode 100644
index 000000000..74e710c1c
--- /dev/null
+++ b/docs/plans/memory-default-project-1393.md
@@ -0,0 +1,492 @@
+# Memory default project and explicit project IDs
+
+> Status: accepted
+> Issue: #1393
+> Branch / worktree: `plan/memory-default-project` at
+> `/Users/rk/work/chainbot/avibe-bot/worktrees/memory-default-project`
+> Base: `origin/master` @ `b6c4393f`
+
+This revision absorbs the plan review: schema v3, split project-id
+predicates, a durable project catalog, a bounded UI-only `all`
+contract, multi-project final flush, and a closed ID input matrix.
+
+## Background
+
+#1393 is not a lost-index bug. User conversations are captured under an
+EverOS `project_id` derived from the Agent Session workdir
+(`p-<32 hex>`). Settings Search then hashes the **default Agent cwd**
+and queries that space. A Workbench project whose folder is not the
+default cwd returns HTTP 200 with `items: []`.
+
+EverOS treats `project_id` as a hard partition. Search always pins
+`project_id = ?`. The literal `"default"` is EverOS's reserved default
+space (on disk: `default_project`), not a cross-project view. Avibe's
+sidecar currently rejects `"default"` on add/search and only allows
+`p-[0-9a-f]{32}`. Profile `/get` already uses `"default"`.
+
+The current store CHECK (`core/memory/schema.sql` `project_ref`, schema
+version 2) also only accepts `p-<32 hex>`. Python-only relaxation of
+`is_project_id` cannot persist `"default"` or named slugs.
+
+Upstream EverOS 1.2.3 has no global search. Episode LanceDB ids omit
+`project_id` (EverOS #320). Multiple EverOS projects for one owner
+remain a residual index-collision risk; this iteration reduces how
+often that happens, it does not change EverOS key shape.
+
+## Goal
+
+Close #1393 by putting all user conversation capture on EverOS
+`"default"`, and by making extra projects **opt-in named slugs**.
+
+- User conversations always write `project_id = "default"`.
+- Agent `remember` may pass a named slug. Omitted → `"default"`.
+- Settings and Agent search this principal only. No `u-…` fan-out.
+- Agent search: `"default"` or a named slug. No `all`.
+- Settings Search: picker default `"default"`; may choose a named slug
+ or **all of this user's catalogued projects**.
+- Legacy `p-<32 hex>` is not a product id. It is only a persisted
+ recovery/drain shape.
+
+## Non-goals
+
+- Cross-user admin search.
+- Mapping Workbench `proj_…` or workdir onto EverOS `project_id`.
+- EverOS upstream global search.
+- Migrating historical `p-…` markdown into `"default"`.
+- Changing profile ownership. Profile stays per principal.
+- Patching EverOS row ids this iteration.
+
+## Project ID contract
+
+Single module: `core/memory/project_ids.py`. No second charset.
+
+Wire values must already be lowercase. **Do not `casefold()`.** Mixed
+case is invalid.
+
+| Token | Shape | New write | Agent search | UI search | Persist / drain |
+|---|---|---|---|---|---|
+| `default` | exact | yes | yes (CLI default) | yes (picker default) | yes |
+| named slug | `^[a-z][a-z0-9_-]{0,62}$`, not reserved, not `p-` prefix | yes | yes | yes | yes |
+| `all` | exact | no | no | yes | no |
+| `p-[0-9a-f]{32}` | exact legacy | no | no | no | yes |
+| `personal` | reserved | no | no | no | no |
+
+Reserved: `default`, `all`, `personal`. Named slugs must not start with
+`p-`.
+
+### Input matrix
+
+| Input | remember / user capture | Agent search | UI search |
+|---|---|---|---|
+| key omitted / JSON `null` | `default` | `default` | `default` |
+| `""` / whitespace | invalid | invalid | invalid |
+| `default` | `default` | `default` | `default` |
+| `Default` / `BILLING` | invalid | invalid | invalid |
+| `billing` | create/use `billing` | `billing` if catalogued, else invalid | same |
+| `all` | invalid | invalid | UI `all` fan-out |
+| `personal` | invalid | invalid | invalid |
+| `p-` + 32 hex | invalid | invalid | invalid |
+| `p-deadbeef` (short) | invalid | invalid | invalid |
+| `u-…` | invalid | invalid | invalid |
+
+Helpers:
+
+- `is_legacy_memory_project_id` — exact `p-[0-9a-f]{32}`
+- `is_new_stored_memory_project_id` — `default` or named slug
+- `is_persisted_memory_project_id` — legacy **or** new stored
+- `is_writable_memory_project_id` — new stored only
+- `parse_writable_memory_project`
+- `parse_agent_search_project` — new stored only
+- `parse_ui_search_project` — new stored or `all`
+
+Callsites must pick a predicate. **Do not** make `store.is_project_id`
+a drop-in alias for persisted and keep using it on new write/read
+paths.
+
+| Callsite | Predicate |
+|---|---|
+| New capture (`CaptureRequest` / `module.capture`) | `is_writable_memory_project_id` |
+| `enqueue_request` | `is_writable_memory_project_id` |
+| `module.recall` / `module.profile` | `is_new_stored_memory_project_id` |
+| `provider_session_ref`, `resolve_current_session_scopes`, worker drain, session lifecycle | `is_persisted_memory_project_id` |
+| Sidecar add/flush | persisted |
+| Sidecar search | new-stored |
+
+If `store.is_project_id` remains as a compatibility name, it may only
+wrap persisted and **must not** be called from capture, enqueue,
+recall, or profile. Grep those four sites in the implementation PR.
+
+`derive_project_id(scope_key, workdir)` stays for old tests. New
+capture and remember must not call it.
+
+## Schema v3 (P0)
+
+Current `MEMORY_STORE_SCHEMA_VERSION = 2`. Fresh `schema.sql` and
+existing v2 files must both accept the new project shapes.
+
+### Fresh schema
+
+- Bump `PRAGMA user_version` to 3.
+- Widen `memory_capture_queue.project_ref` CHECK to
+ `is_persisted_memory_project_id` (SQL equivalent of `default` OR
+ exact `p-<32 hex>` OR named slug).
+- Add catalog:
+
+```text
+memory_projects (
+ principal_id TEXT NOT NULL, -- same u- CHECK as the queue
+ project_id TEXT NOT NULL, -- new-stored CHECK only (no legacy)
+ created_at TEXT NOT NULL,
+ last_written_at TEXT NOT NULL,
+ PRIMARY KEY (principal_id, project_id)
+)
+```
+
+- Include `memory_projects` in `_MEMORY_STORE_TABLES` /
+ `_verify_current_schema`.
+
+### v2 → v3 migration
+
+Invariant: **no data loss and the final schema object set matches
+v3**. Temporary drop/recreate of queue indexes during the rebuild is
+required (SQLite keeps the old index names on the renamed table).
+Do not drop settlements, attachments, or their triggers.
+
+One transaction:
+
+1. Drop `ix_memory_capture_due` and
+ `ix_memory_capture_session_generation`.
+2. `ALTER TABLE memory_capture_queue RENAME TO memory_capture_queue_v2`.
+3. `CREATE TABLE memory_capture_queue` with the v3 `project_ref` CHECK
+ and the same columns otherwise.
+4. `INSERT INTO memory_capture_queue SELECT * FROM memory_capture_queue_v2`
+ (every row, including `p-…`).
+5. `DROP TABLE memory_capture_queue_v2`.
+6. Recreate `ix_memory_capture_due` and
+ `ix_memory_capture_session_generation`.
+7. `CREATE TABLE memory_projects` if missing.
+8. Backfill catalog from distinct `(principal_id, project_ref)` **only
+ where `project_ref` is new-stored**. Never insert `p-…`.
+9. Execute `PRAGMA foreign_key_check` and require zero returned rows;
+ then `_verify_current_schema`; then `PRAGMA user_version = 3`.
+
+Settlement triggers (`trg_memory_flush_settlements_*`) must still
+exist after the transaction.
+
+Open path (each step is a real snapshot, not a rename of
+`schema.sql`):
+
+| On-disk `user_version` | Action |
+|---|---|
+| 0, empty | Install current `schema.sql` (v3) |
+| 0, recognized non-empty v0 | Keep a frozen v2 `schema.sql` snapshot in-repo. `_migrate_v0_to_v2` applies **that snapshot only**, then `_migrate_v2_to_v3`. Do not point v0→v2 at live `schema.sql` after it becomes v3. |
+| 1 | existing `_migrate_v1_to_v2`, then `_migrate_v2_to_v3` |
+| 2 | `_migrate_v2_to_v3` |
+| 3 | verify only |
+| other | fail closed |
+
+Check in `tests/fixtures/memory_foundation_v2.sql` (released v2
+shape). Do not generate it from post-change `schema.sql`.
+
+### Legacy non-terminal rows
+
+`pending` / `processing` / `manual_required` rows with `p-…` stay
+drivable:
+
+- Worker add/flush still sends that legacy `project_id` to EverOS.
+- Sidecar add/flush therefore **accepts persisted ids** (legacy +
+ new stored) so drain can finish.
+- Sidecar search accepts **new stored only**.
+- New public remember/search/UI never accept `p-…`.
+- After drain, terminal `p-…` tombstones may remain until ordinary
+ compaction. They are invisible to picker and `all`.
+
+### Tests
+
+- Released v2 fixture (check in a v2-shaped file, or generate from
+ the current v2 `schema.sql` snapshot) loads, migrates, keeps a
+ `p-…` queue row, and then accepts a `"default"` enqueue.
+- Fresh install is user_version 3 and can enqueue `"default"` and
+ `billing`.
+- A v2 file with a non-terminal `p-…` row still recovers scopes and
+ can be claimed.
+
+## Durable project catalog
+
+Source of truth for picker, `all`, and “unknown slug”.
+
+- Created/updated in the **same enqueue transaction** as an accepted
+ capture or remember of a new-stored project. Duplicate remember
+ upserts `last_written_at`.
+- `"default"` is always implicitly searchable. Upsert it on first
+ user capture or default remember; picker always shows it even if
+ the row is missing.
+- Named slug remember of a not-yet-catalogued id **creates** the
+ row (that is how a project is created).
+- Named slug **search** of a not-yet-catalogued id is
+ `memory_invalid_input` (unknown).
+- Cap: 16 named projects per principal, plus `"default"`. A 17th
+ distinct named remember is `memory_invalid_input`.
+- Clear / factory reset deletes `memory_projects` with the other
+ Memory tables.
+- Picker order: `default`, named by `last_written_at` desc, then
+ UI-only `all`.
+- `all` = implicit `default` + catalogued named slugs (see Read path).
+
+## Write path
+
+### User conversations
+
+`CaptureAdmission.project_for` returns `"default"` and does not
+require a workdir. Human Workbench and bound IM turns enqueue
+`"default"` and upsert the catalog.
+
+### Agent remember
+
+`POST /internal/memory/remember`: `{text}` or `{text, project}`.
+
+- Missing / JSON `null` → `"default"`.
+- Present → `parse_writable_memory_project` (rejects `all`,
+ `personal`, `p-…`, mixed case, empty).
+- Principal and session come from the admitted CLI session, not
+ from the workdir hash.
+
+```bash
+vibe memory remember "<text>" [--project <slug>] [--json]
+```
+
+Idempotency:
+`agent:{principal}:{project}:{session}:{digest}`.
+
+### Final flush (P1)
+
+`final_flush_memory_cli_session` must flush **every** current-epoch
+scope of that raw session, not only live `(principal, "default")`.
+
+- Union live CLI scope with `resolve_current_session_scopes()`.
+- Order: `"default"` first, then remaining project ids sorted.
+- **One shared deadline** (controller default 5s, same as today's
+ single-scope budget). Compute an absolute deadline at entry.
+ Each scope gets only remaining time. After the deadline, do not
+ start another provider call; mark leftover scopes unfinished.
+- Prefer a `final_flush_scopes(...)` helper that reuses the
+ multi-scope admission-lock pattern from archive.
+- If any visited scope with unflushed work fails, or any scope was
+ skipped because the budget expired, the overall result is failure.
+- `archive_memory_cli_session` uses the same union + shared deadline.
+- Tests: (1) remember `--project billing` then final-flush visits
+ `billing` and `default` if in the union; (2) several slow scopes
+ still finish (or abort) within ~5s wall time, not 5s × N.
+
+### System prompt
+
+- `remember` / `search` without `--project` use `"default"`.
+- `remember --project <slug>` only when the fact is explicitly for
+ that named space.
+- `search --project <slug>` only that space.
+- Never `--project all` (Settings only).
+- Never hashes, never Workbench `proj_`, never `personal`.
+
+## Read path
+
+Principal is always server-side:
+
+- Settings: verified UI user key → one principal.
+- Agent CLI: admitted session → that principal.
+
+Callers never submit `u-…`.
+
+### Search request
+
+```text
+{ query, policy } # → default
+{ query, policy, project }
+```
+
+- UI user key: `parse_ui_search_project`.
+- CLI session: `parse_agent_search_project` (`all` → 400).
+
+```bash
+vibe memory search "<query>" [--project <slug>] [--limit 1..20] [--json]
+```
+
+### Universes
+
+| Selector | Who | EverOS queries |
+|---|---|---|
+| omitted / `default` | UI and Agent | one `(principal, default)` |
+| named slug | UI and Agent | one `(principal, slug)` if catalogued |
+| `all` | Settings UI only | implicit `default` + catalogued named slugs |
+
+### `all` membership
+
+```text
+all = implicit default + catalogued named projects
+```
+
+Always search `"default"` first, even if that principal has no
+`memory_projects` row for `default` (user created only named slugs).
+Then named slugs by `last_written_at` desc. Never include `p-…`.
+
+### `all` recall contract
+
+Applies only to Settings `project=all`.
+
+1. **Modes.** `keyword`, `vector`, `hybrid`, `auto`. Reject `agentic`
+ and reject `include_current_session=true`.
+2. Force `include_current_session=false`.
+3. Probe provider health / embed capability **once**.
+4. `include_profile` is sent on **at most one** project query (the
+ `default` query). Every other fan-out call sets
+ `include_profile=false`.
+5. Fan-out sequentially under the existing lifecycle lock. Overall
+ deadline 20s (must finish inside the 45s search transport).
+6. Per-project provider failure: skip, continue. If every project
+ fails, return the first error. If any succeed, return merged
+ items plus `warnings` including `memory_search_partial`.
+7. Deadline hit: return merged items so far plus
+ `memory_search_truncated`.
+8. Merge: collect items, attach `project`, sort by `date` desc
+ (missing last), then `kind`, then `text`; dedupe
+ `(kind, text, date, project)`; bound to `max_results`.
+9. UI shows the project badge on each hit when the selector is not
+ the single default space. Partial/truncated banners must render.
+
+### Search warning codes
+
+`memory_search_partial` and `memory_search_truncated` are
+**transport-only** warnings, not persisted queue errors.
+
+- Add a closed `MemoryWarningCode` (preferred) or a transport-only
+ extension of the public warning union. Do **not** add them to
+ SQLite `last_error` CHECKs.
+- `RecallItems.warnings` / public search JSON use that warning
+ union, not `MemoryErrorCode`.
+- TypeScript `MemoryRecallResult` narrows the same two strings.
+- `MemorySearchPanel` renders a banner for each present warning
+ (EN/ZH i18n + `memoryCopyContract`).
+- Tests: API returns the codes on injected per-project failure and
+ on an injected deadline; UI contract asserts the banner.
+
+`MemoryItem` / search JSON gain an optional `project` field. Single-
+project searches set it to that project.
+
+Do not fan-out other principals.
+
+### Settings UI
+
+`MemorySearchPanel` `<Select>`: Default, named slugs, All my
+projects. Default selected.
+
+`GET /api/memory/projects` returns this principal's catalog rows
+plus the implicit `default` and the UI-only `all` option. No host
+paths. No other principals.
+
+i18n: `ui/src/i18n/en.json` + `zh.json`,
+`memoryCopyContract.test.ts`, `vibe/i18n/en.json` + `zh.json`.
+
+## Sidecar and insight
+
+- Add/flush: `is_persisted_memory_project_id` (drain legacy + new
+ stored). Reject `all`, `personal`, malformed.
+- Search: `is_new_stored_memory_project_id` only.
+- Profile `/get` stays `project_id="default"`.
+
+Insight split (admin list currently filters with `_memcell_scope`):
+
+- `_memcell_scope` accepts **persisted** ids (legacy + new stored)
+ so admin log can still show historical `p-…` memcells.
+- User-scoped `_validated_scope` / scoped list+detail accept only
+ **new-stored** (`default` or named). A scoped read of a `p-…`
+ project is invalid input, not an empty page.
+- Admin SQL/GLOB and the post-filter use persisted.
+- Picker / `all` still read **only** `memory_projects` (new-stored),
+ never insight legacy ids.
+
+## Residual risk: EverOS project collision
+
+Named slugs still share EverOS owner-keyed Lance ids (EverOS #320).
+Opt-in + 16-named cap reduces how often two spaces share
+`{owner}_{ep_<date>_00000001}`. Markdown paths stay isolated.
+**Index isolation is not guaranteed** this iteration.
+
+Accepted residual: two named projects for one principal on the same
+UTC day may clobber one Lance episode/profile row. Follow-up is an
+EverOS-side key change or a later Avibe rebuild.
+
+Required regression: same principal, two named remembers with the
+same text/timestamp class produce distinct Avibe
+`(principal, project)` queue identities and distinct EverOS add
+`project_id`s. Do not claim Lance-level isolation in that test.
+
+## Residual data
+
+`p-<hash(workdir)>` markdown and tombstones stay on disk. They are
+not listed, not in `all`, not searchable, not writable. Drain-only
+until compaction. No rebuild in this iteration.
+
+#1393 closes for **new** captures: user turns → `"default"`;
+Settings default search → `"default"`.
+
+## Tests and catalog
+
+New capability `memory_search`. IDs in the executable test and PR.
+
+- `MEMORY-SEARCH-001` — Workbench turn whose workdir ≠ default cwd
+ captures as `"default"` and Settings default search returns it.
+- `MEMORY-SEARCH-002` — `remember --project billing` is absent from
+ default search and present in `--project billing`.
+- `MEMORY-SEARCH-003` — Settings `project=all` returns this
+ principal's `default` + named hits, never another principal,
+ never a `p-` space.
+- `MEMORY-SEARCH-004` — Agent `search --project all`,
+ `remember --project all` / `personal` / `p-…` / mixed case /
+ unknown slug search are rejected.
+- `MEMORY-SEARCH-005` — v2 store fixture migrates to v3; a
+ non-terminal `p-…` row still drains; a new `"default"` enqueue
+ succeeds.
+- `MEMORY-SEARCH-006` — `remember --project billing` then
+ final-flush visits `billing` (and `default` if in the union).
+
+Also:
+
+- Admission: human capture `"default"`; missing workdir still
+ admits.
+- Sidecar: add `"default"` allowed; add `all` / `personal`
+ rejected; add legacy `p-…` allowed (drain); search legacy
+ rejected.
+- UI route: search forwards only `{query, policy}` or
+ `{query, policy, project}`.
+- Catalog upsert on accepted remember; 17th named project
+ rejected.
+- Insight: `"default"` memcells appear in scoped/admin lists.
+- Prompt / CLI-example tests if they pin the old search sentence.
+
+`ruff check` on changed Python. `npm run build` if `ui/` changes.
+
+## Close-out
+
+- Implement on a non-draft PR from this worktree (new implementation
+ commits, not plan-only).
+- PR names the capability, lists `MEMORY-SEARCH-00x`, and states
+ unit / contract / scenario / residual manual layers.
+- After merge (or when the owner says): close #1393.
+
+In this worktree use
+`GH_CONFIG_DIR=$HOME/.config/gh-avibe-bot` (`rkrkrkk`).
+
+## Implementation order
+
+1. `project_ids.py` + input-matrix unit tests.
+2. Schema v3 + v2 fixture migration + catalog table.
+3. Split project-id validation by callsite: writable for
+ capture/enqueue, new-stored for recall/profile, persisted for
+ recovery/drain/lifecycle. Admission +
+ `default_memory_project_id()` → `"default"`.
+4. Sidecar persisted-vs-search split; insight new-stored ids.
+5. Remember/search payloads, catalog upsert, CLI `--project`.
+6. Final-flush union of all session scopes.
+7. UI-only `all` with the recall contract above.
+8. Settings picker + i18n.
+9. Scenario catalog and remaining tests.
+10. Prompt + `docs/CLI.md` / `docs/CLI_ZH.md`.
diff --git a/tests/fixtures/memory_foundation_v2.sql b/tests/fixtures/memory_foundation_v2.sql
new file mode 100644
index 000000000..8ea0f1347
--- /dev/null
+++ b/tests/fixtures/memory_foundation_v2.sql
@@ -0,0 +1,193 @@
+
+-- Frozen v2 Memory schema from origin/master b6c4393f.
+-- Initial Memory schema for new databases.
+CREATE TABLE IF NOT EXISTS memory_meta (
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
+ epoch INTEGER NOT NULL,
+ clear_in_progress INTEGER NOT NULL DEFAULT 0 CHECK (clear_in_progress IN (0, 1)),
+ scope_key BLOB NOT NULL,
+ provider_root_id TEXT NOT NULL,
+ last_provider_timestamp_ms INTEGER NOT NULL DEFAULT 0,
+ missed_count INTEGER NOT NULL DEFAULT 0 CHECK (missed_count >= 0),
+ last_success_at TEXT,
+ last_error TEXT CHECK (
+ last_error IS NULL OR last_error IN (
+ 'memory_disabled', 'memory_invalid_input', 'memory_input_too_large',
+ 'memory_queue_full', 'memory_low_disk_space', 'memory_store_unavailable',
+ 'memory_runtime_missing', 'memory_runtime_unsupported',
+ 'memory_runtime_install_failed', 'memory_sidecar_unavailable',
+ 'memory_provider_timeout', 'memory_provider_response_invalid',
+ 'memory_processing_failed', 'memory_clear_failed',
+ 'memory_capability_unavailable'
+ )
+ ),
+ last_error_at TEXT,
+ processing_fault_generation INTEGER NOT NULL DEFAULT 0 CHECK (
+ processing_fault_generation >= 0
+ ),
+ processing_fault_kind TEXT CHECK (
+ processing_fault_kind IS NULL OR processing_fault_kind IN ('credential', 'engine')
+ ),
+ processing_fault_since TEXT,
+ processing_alert_active INTEGER NOT NULL DEFAULT 0 CHECK (
+ processing_alert_active IN (0, 1)
+ ),
+ processing_recovery_pending_at TEXT,
+ processing_recovery_generation INTEGER CHECK (
+ processing_recovery_generation IS NULL OR processing_recovery_generation >= 0
+ ),
+ updated_at TEXT NOT NULL,
+ CHECK (
+ (processing_recovery_pending_at IS NULL
+ AND processing_recovery_generation IS NULL)
+ OR
+ (processing_recovery_pending_at IS NOT NULL
+ AND processing_recovery_generation IS NOT NULL)
+ )
+);
+
+CREATE TABLE IF NOT EXISTS memory_attachment_bundle (
+ bundle_id TEXT PRIMARY KEY CHECK (
+ length(bundle_id) = 32
+ AND bundle_id NOT GLOB '*[^0-9a-f]*'
+ ),
+ relative_path TEXT NOT NULL UNIQUE,
+ state TEXT NOT NULL CHECK (state IN ('pinned', 'releasing')),
+ file_count INTEGER NOT NULL CHECK (file_count BETWEEN 1 AND 8),
+ total_bytes INTEGER NOT NULL CHECK (total_bytes >= 0),
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+);
+
+CREATE TABLE IF NOT EXISTS memory_session_flush_state (
+ provider_session_ref TEXT PRIMARY KEY,
+ epoch INTEGER NOT NULL CHECK (epoch >= 0),
+ open_generation INTEGER NOT NULL DEFAULT 1 CHECK (open_generation >= 1),
+ target_generation INTEGER CHECK (target_generation IS NULL OR target_generation >= 1),
+ state TEXT NOT NULL DEFAULT 'idle' CHECK (
+ state IN ('idle', 'due', 'in_flight', 'manual_required')
+ ),
+ first_unflushed_at TEXT,
+ last_add_ack_at TEXT,
+ confirmed_add_watermark_ms INTEGER,
+ unflushed_count INTEGER NOT NULL DEFAULT 0 CHECK (unflushed_count >= 0),
+ due_at TEXT,
+ next_attempt_at TEXT,
+ retry_count INTEGER NOT NULL DEFAULT 0 CHECK (retry_count >= 0),
+ operation_epoch INTEGER NOT NULL DEFAULT 0 CHECK (operation_epoch >= 0),
+ fence_token TEXT,
+ submission_started_at TEXT,
+ updated_at TEXT NOT NULL,
+ CHECK (
+ (state = 'idle' AND target_generation IS NULL AND fence_token IS NULL
+ AND submission_started_at IS NULL)
+ OR
+ (state IN ('due', 'in_flight', 'manual_required')
+ AND target_generation IS NOT NULL AND fence_token IS NOT NULL)
+ ),
+ CHECK (state IN ('in_flight', 'manual_required') OR submission_started_at IS NULL)
+);
+
+CREATE TABLE IF NOT EXISTS memory_capture_queue (
+ source_message_digest TEXT PRIMARY KEY,
+ epoch INTEGER NOT NULL,
+ session_id TEXT NOT NULL,
+ provider_session_ref TEXT NOT NULL,
+ generation INTEGER NOT NULL CHECK (generation >= 1),
+ principal_id TEXT NOT NULL CHECK (
+ length(principal_id) = 34
+ AND substr(principal_id, 1, 2) = 'u-'
+ AND substr(principal_id, 3) NOT GLOB '*[^0-9a-f]*'
+ ),
+ project_ref TEXT NOT NULL CHECK (
+ length(project_ref) = 34
+ AND substr(project_ref, 1, 2) = 'p-'
+ AND substr(project_ref, 3) NOT GLOB '*[^0-9a-f]*'
+ ),
+ provenance TEXT NOT NULL CHECK (provenance IN ('user_input', 'agent')),
+ payload_text TEXT,
+ payload_attachments TEXT,
+ attachment_bundle_id TEXT REFERENCES memory_attachment_bundle(bundle_id) ON DELETE RESTRICT,
+ occurred_at_ms INTEGER NOT NULL,
+ provider_timestamp_ms INTEGER NOT NULL,
+ state TEXT NOT NULL CHECK (
+ state IN ('pending', 'processing', 'delivered', 'dead', 'manual_required')
+ ),
+ attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0),
+ next_retry_at TEXT,
+ lease_owner TEXT,
+ lease_at TEXT,
+ lease_token INTEGER NOT NULL DEFAULT 0 CHECK (lease_token >= 0),
+ last_error TEXT CHECK (
+ last_error IS NULL OR last_error IN (
+ 'memory_disabled', 'memory_invalid_input', 'memory_input_too_large',
+ 'memory_queue_full', 'memory_low_disk_space', 'memory_store_unavailable',
+ 'memory_runtime_missing', 'memory_runtime_unsupported',
+ 'memory_runtime_install_failed', 'memory_sidecar_unavailable',
+ 'memory_provider_timeout', 'memory_provider_response_invalid',
+ 'memory_processing_failed', 'memory_clear_failed'
+ )
+ ),
+ add_request_id TEXT,
+ add_status TEXT CHECK (add_status IS NULL OR add_status IN ('accumulated', 'extracted')),
+ created_at TEXT NOT NULL,
+ completed_at TEXT,
+ CHECK (
+ (state IN ('pending', 'processing', 'manual_required') AND payload_text IS NOT NULL)
+ OR (state IN ('delivered', 'dead') AND payload_text IS NULL)
+ )
+);
+
+CREATE INDEX IF NOT EXISTS ix_memory_capture_due
+ ON memory_capture_queue (epoch, state, next_retry_at);
+
+CREATE INDEX IF NOT EXISTS ix_memory_capture_session_generation
+ ON memory_capture_queue (provider_session_ref, epoch, generation, state);
+
+CREATE INDEX IF NOT EXISTS ix_memory_session_flush_due
+ ON memory_session_flush_state (epoch, state, due_at, next_attempt_at);
+
+CREATE TABLE IF NOT EXISTS memory_flush_settlements (
+ settlement_id INTEGER PRIMARY KEY AUTOINCREMENT,
+ provider_session_ref TEXT NOT NULL,
+ epoch INTEGER NOT NULL CHECK (epoch >= 0),
+ generation INTEGER NOT NULL CHECK (generation >= 1),
+ operation_kind TEXT NOT NULL CHECK (operation_kind IN ('add', 'flush')),
+ operation_token TEXT NOT NULL,
+ observation TEXT NOT NULL CHECK (
+ observation IN ('settled', 'rejected', 'manual_required')
+ ),
+ request_id TEXT,
+ confirmed_watermark_ms INTEGER,
+ observed_at TEXT NOT NULL,
+ error_code TEXT,
+ recovery_origin TEXT CHECK (recovery_origin IS NULL OR recovery_origin = 'boot'),
+ attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0),
+ CHECK (
+ (operation_kind = 'add' AND observation = 'rejected' AND attempts >= 1)
+ OR
+ (NOT (operation_kind = 'add' AND observation = 'rejected') AND attempts = 0)
+ ),
+ UNIQUE (
+ provider_session_ref, epoch, generation, operation_kind, operation_token
+ )
+);
+
+CREATE INDEX IF NOT EXISTS ix_memory_flush_settlements_recent
+ ON memory_flush_settlements (epoch, observed_at DESC, settlement_id DESC);
+
+CREATE TRIGGER IF NOT EXISTS trg_memory_flush_settlements_immutable
+BEFORE UPDATE ON memory_flush_settlements
+BEGIN
+ SELECT RAISE(ABORT, 'memory flush settlements are immutable');
+END;
+
+CREATE TRIGGER IF NOT EXISTS trg_memory_flush_settlements_no_delete
+BEFORE DELETE ON memory_flush_settlements
+WHEN COALESCE(
+ (SELECT clear_in_progress FROM memory_meta WHERE singleton = 1),
+ 0
+) != 1
+BEGIN
+ SELECT RAISE(ABORT, 'memory flush settlements are immutable');
+END;
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index 79ce124ac..96a0c7329 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -42,6 +42,17 @@ capabilities:
- ui/src/components/settings/SettingsDependenciesPage.test.tsx
- ui/src/components/settings/SettingsMemoryPage.test.tsx
- ui/src/components/settings/memory/MemorySettingsPanel.test.tsx
+ - id: memory_search
+ name: Default Memory project and explicit named projects
+ status: active
+ catalog: tests/scenarios/memory_search/catalog.yaml
+ scenario_tests:
+ - tests/test_memory_admission.py
+ - tests/test_memory_store.py
+ unit_or_contract_tests:
+ - tests/test_memory_project_ids.py
+ - tests/test_memory_sidecar.py
+ - tests/test_ui_memory_routes.py
- id: memory_repair
name: Live Memory index repair via admitted artifact sync
status: active
diff --git a/tests/scenarios/memory_search/catalog.yaml b/tests/scenarios/memory_search/catalog.yaml
new file mode 100644
index 000000000..eb50cca26
--- /dev/null
+++ b/tests/scenarios/memory_search/catalog.yaml
@@ -0,0 +1,48 @@
+version: 1
+capability:
+ id: memory_search
+ name: Default Memory project and explicit named projects
+ canonical_tests:
+ - tests/test_memory_admission.py
+ - tests/test_memory_store.py
+ - tests/test_internal_server.py
+status_legend:
+ covered: executable evidence exists
+ partial: contract coverage exists
+scenarios:
+ - id: MEMORY-SEARCH-001
+ name: User turns land in default and Settings default search can retrieve them
+ status: covered
+ kind: happy_path
+ layer: scenario
+ test: tests/test_memory_admission.py::test_user_turns_capture_into_default_without_a_workdir
+ - id: MEMORY-SEARCH-002
+ name: Named remember is isolated from default search
+ status: partial
+ kind: happy_path
+ layer: contract
+ test: tests/test_memory_project_ids.py::test_parsers_reject_empty_and_mixed_case
+ - id: MEMORY-SEARCH-003
+ name: Settings all searches this principal only
+ status: partial
+ kind: authorization
+ layer: contract
+ test: tests/test_memory_project_ids.py::test_ui_parser_accepts_all_agent_does_not
+ - id: MEMORY-SEARCH-004
+ name: Agent cannot search all; reserved ids are rejected
+ status: covered
+ kind: validation
+ layer: contract
+ test: tests/test_memory_project_ids.py::test_ui_parser_accepts_all_agent_does_not
+ - id: MEMORY-SEARCH-005
+ name: v2 stores migrate and accept default enqueue
+ status: covered
+ kind: migration
+ layer: contract
+ test: tests/test_memory_store.py::test_store_migrates_v2_queue_and_accepts_default_project
+ - id: MEMORY-SEARCH-006
+ name: Final flush visits every current session scope
+ status: partial
+ kind: lifecycle
+ layer: contract
+ test: tests/test_memory_store.py::test_session_scope_recovery_survives_store_reopen_and_separates_sessions
diff --git a/tests/test_memory_admission.py b/tests/test_memory_admission.py
index 20982e724..5696dab6f 100644
--- a/tests/test_memory_admission.py
+++ b/tests/test_memory_admission.py
@@ -136,7 +136,7 @@ def test_admitted_im_turn_becomes_a_namespaced_capture_request() -> None:
assert request.source_message_id == f"im:telegram:{PRINCIPAL}:native-1"
assert request.session_id == "stable-session"
assert request.principal_id == PRINCIPAL
- assert request.project_id == PROJECT
+ assert request.project_id == "default"
assert request.provenance == "user_input"
assert request.text == "ordinary text"
assert request.attachments == ()
@@ -150,6 +150,14 @@ def test_workbench_turn_uses_its_own_source_namespace() -> None:
assert request.source_message_id == f"workbench:{PRINCIPAL}:native-1"
+def test_user_turns_capture_into_default_without_a_workdir() -> None:
+ """Scenario: MEMORY-SEARCH-001"""
+ request = _admission().decide(_facts(workdir=None))
+
+ assert isinstance(request, CaptureRequest)
+ assert request.project_id == "default"
+
+
@pytest.mark.parametrize(
"facts,reason",
[
diff --git a/tests/test_memory_everos.py b/tests/test_memory_everos.py
index adcaae401..b4000f184 100644
--- a/tests/test_memory_everos.py
+++ b/tests/test_memory_everos.py
@@ -30,7 +30,7 @@ from core.memory.types import (
)
-PROJECT = "p-22222222222222222222222222222222"
+PROJECT = "default"
PRINCIPAL = "owner-1"
SESSION_REF = ProviderSessionRef(
principal_id=PRINCIPAL,
diff --git a/tests/test_memory_flush_coordinator.py b/tests/test_memory_flush_coordinator.py
index 79c568cd9..a4c8ef5b1 100644
--- a/tests/test_memory_flush_coordinator.py
+++ b/tests/test_memory_flush_coordinator.py
@@ -44,7 +44,7 @@ from core.memory.worker import MemoryWorker
PRINCIPAL = "u-11111111111111111111111111111111"
-PROJECT = "p-22222222222222222222222222222222"
+PROJECT = "default"
TEST_BUNDLE_ID = "a" * 32
diff --git a/tests/test_memory_insight.py b/tests/test_memory_insight.py
index f1f277765..0d0ea0d3a 100644
--- a/tests/test_memory_insight.py
+++ b/tests/test_memory_insight.py
@@ -17,8 +17,8 @@ from core.memory.types import ProviderSessionRef
ALICE = "u-" + "a" * 32
BOB = "u-" + "b" * 32
-PROJECT = "p-" + "1" * 32
-OTHER_PROJECT = "p-" + "2" * 32
+PROJECT = "default"
+OTHER_PROJECT = "billing"
def _json(value: object) -> str:
@@ -491,7 +491,7 @@ def test_scoped_and_admin_memcell_queries_keep_distinct_fail_closed_authorizatio
"mc_bad_project",
ALICE,
timestamp_ms=2_000,
- project="missing-provenance",
+ project="all",
)
_insert_memcell(insight_paths, "mc_bad_owner", ALICE, timestamp_ms=1_000)
with sqlite3.connect(insight_paths.system_db_path) as conn:
diff --git a/tests/test_memory_maintenance.py b/tests/test_memory_maintenance.py
index 447e22d42..b400b974d 100644
--- a/tests/test_memory_maintenance.py
+++ b/tests/test_memory_maintenance.py
@@ -39,7 +39,7 @@ from core.memory.types import (
PRINCIPAL = "u-11111111111111111111111111111111"
-PROJECT = "p-22222222222222222222222222222222"
+PROJECT = "default"
def _maintenance(runtime: MemoryRuntime) -> MemoryMaintenance:
diff --git a/tests/test_memory_module.py b/tests/test_memory_module.py
index 99ea86e42..a89f0dc76 100644
--- a/tests/test_memory_module.py
+++ b/tests/test_memory_module.py
@@ -40,7 +40,7 @@ from core.memory.types import (
)
-PROJECT = "p-22222222222222222222222222222222"
+PROJECT = "default"
PRINCIPAL = "u-11111111111111111111111111111111"
diff --git a/tests/test_memory_process.py b/tests/test_memory_process.py
index 2dca58061..81f34284b 100644
--- a/tests/test_memory_process.py
+++ b/tests/test_memory_process.py
@@ -62,7 +62,7 @@ from core.memory.types import (
)
-PROJECT = "p-22222222222222222222222222222222"
+PROJECT = "default"
_ORPHAN_PID = 424_242
_ORPHAN_DESCENDANT_PID = 424_243
_ORPHAN_GROUP_MEMBER_PID = 424_244
diff --git a/tests/test_memory_processing_record.py b/tests/test_memory_processing_record.py
index 5cfcdb9ad..29352dd3f 100644
--- a/tests/test_memory_processing_record.py
+++ b/tests/test_memory_processing_record.py
@@ -1208,7 +1208,7 @@ def _enqueue(runtime: MemoryRuntime, source: str) -> None:
source_message_id=source,
session_id="session",
principal_id="u-11111111111111111111111111111111",
- project_ref="p-22222222222222222222222222222222",
+ project_ref="default",
provenance="user_input",
payload_text="private payload",
occurred_at_ms=1,
diff --git a/tests/test_memory_project_ids.py b/tests/test_memory_project_ids.py
new file mode 100644
index 000000000..513612d4a
--- /dev/null
+++ b/tests/test_memory_project_ids.py
@@ -0,0 +1,98 @@
+from __future__ import annotations
+
+import pytest
+
+from core.memory.project_ids import (
+ DEFAULT_MEMORY_PROJECT_ID,
+ MEMORY_SEARCH_ALL_PROJECTS,
+ is_legacy_memory_project_id,
+ is_named_memory_project_id,
+ is_new_stored_memory_project_id,
+ is_persisted_memory_project_id,
+ is_writable_memory_project_id,
+ omitted_project_to_default,
+ parse_agent_search_project,
+ parse_ui_search_project,
+ parse_writable_memory_project,
+)
+
+LEGACY = "p-" + "a" * 32
+
+
+ ("value", "writable", "agent_search", "ui_search", "persisted"),
+ [
+ (None, False, False, False, False),
+ ("", False, False, False, False),
+ (" ", False, False, False, False),
+ ("default", True, True, True, True),
+ ("Default", False, False, False, False),
+ ("billing", True, True, True, True),
+ ("all", False, False, True, False),
+ ("personal", False, False, False, False),
+ (LEGACY, False, False, False, True),
+ ("p-deadbeef", False, False, False, False),
+ ("u-" + "1" * 32, False, False, False, False),
+ ("BILLING", False, False, False, False),
+ ],
+)
+def test_project_id_matrix(
+ value: object,
+ writable: bool,
+ agent_search: bool,
+ ui_search: bool,
+ persisted: bool,
+) -> None:
+ assert is_writable_memory_project_id(value) is writable
+ assert is_new_stored_memory_project_id(value) is agent_search
+ assert (value == MEMORY_SEARCH_ALL_PROJECTS or is_new_stored_memory_project_id(value)) is ui_search
+ assert is_persisted_memory_project_id(value) is persisted
+ assert is_legacy_memory_project_id(value) is (value == LEGACY)
+
+
+def test_omitted_project_becomes_default() -> None:
+ assert omitted_project_to_default(None) == DEFAULT_MEMORY_PROJECT_ID
+ assert omitted_project_to_default("billing") == "billing"
+
+
+def test_parsers_reject_empty_and_mixed_case() -> None:
+ """Scenario: MEMORY-SEARCH-002"""
+ for parser in (
+ parse_writable_memory_project,
+ parse_agent_search_project,
+ parse_ui_search_project,
+ ):
+ with pytest.raises(ValueError):
+ parser("")
+ with pytest.raises(ValueError):
+ parser("Default")
+ with pytest.raises(ValueError):
+ parser(LEGACY)
+
+
+def test_named_slug_rejects_p_prefix() -> None:
+ assert is_named_memory_project_id("pricing") is True
+ assert is_named_memory_project_id("p-foo") is False
+
+
+def test_prompt_exclusions_are_rejected_by_parsers() -> None:
+ """Scenario: MEMORY-SEARCH-004. Prompt examples must fail the shared parser."""
+
+ from core.system_prompt_injection import _MEMORY_CLI_PROMPT
+
+ assert "cannot be `all`, `personal`" in _MEMORY_CLI_PROMPT
+ assert "start with `p-` / `u-`" in _MEMORY_CLI_PROMPT
+ for value in ("all", "personal", "p-deadbeef", "u-" + "1" * 32, "Billing", ""):
+ with pytest.raises(ValueError):
+ parse_writable_memory_project(value)
+ with pytest.raises(ValueError):
+ parse_agent_search_project(value)
+
+
+def test_ui_parser_accepts_all_agent_does_not() -> None:
+ """Scenario: MEMORY-SEARCH-003 MEMORY-SEARCH-004"""
+ assert parse_ui_search_project("all") == "all"
+ with pytest.raises(ValueError):
+ parse_agent_search_project("all")
+ with pytest.raises(ValueError):
+ parse_writable_memory_project("all")
diff --git a/tests/test_memory_runtime.py b/tests/test_memory_runtime.py
index da2a8b2ad..ded32b2cc 100644
--- a/tests/test_memory_runtime.py
+++ b/tests/test_memory_runtime.py
@@ -83,7 +83,7 @@ from config.v2_config import (
)
-PROJECT = "p-22222222222222222222222222222222"
+PROJECT = "default"
def _maintenance(runtime: MemoryRuntime) -> MemoryMaintenance:
@@ -1970,11 +1970,11 @@ async def test_multi_scope_session_lifecycle_holds_every_fence_through_operation
)
first_scope = (
"u-11111111111111111111111111111111",
- "p-11111111111111111111111111111111",
+ "default",
)
second_scope = (
"u-22222222222222222222222222222222",
- "p-22222222222222222222222222222222",
+ "billing",
)
session_id = "multi-scope-lifecycle-session"
operation_entered = asyncio.Event()
diff --git a/tests/test_memory_sidecar.py b/tests/test_memory_sidecar.py
index 214619b8d..cd6a1b06d 100644
--- a/tests/test_memory_sidecar.py
+++ b/tests/test_memory_sidecar.py
@@ -17,7 +17,8 @@ from core.memory.sidecar import (
)
-PROJECT = "p-22222222222222222222222222222222"
+PROJECT = "default"
+LEGACY_PROJECT = "p-22222222222222222222222222222222"
SESSION_ID = f"src--{'1' * 64}--e1"
diff --git a/tests/test_memory_slice3.py b/tests/test_memory_slice3.py
index b7f3f7586..e23aad09d 100644
--- a/tests/test_memory_slice3.py
+++ b/tests/test_memory_slice3.py
@@ -31,7 +31,7 @@ from modules.im.message_facts import (
)
-PROJECT = "p-22222222222222222222222222222222"
+PROJECT = "default"
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -442,10 +442,9 @@ def test_final_flush_memory_cli_session_uses_trusted_stored_scope() -> None:
)
assert result is True
- assert controller.memory_runtime.final_flush_calls == [
+ assert controller.memory_runtime.session_lifecycle_calls == [
{
- "principal_id": principal_id,
- "project_id": PROJECT,
+ "scopes": ((principal_id, PROJECT),),
"raw_session_id": "ses-workbench",
"deadline_seconds": 4.0,
}
@@ -454,7 +453,7 @@ def test_final_flush_memory_cli_session_uses_trusted_stored_scope() -> None:
def test_final_flush_memory_cli_session_swallows_runtime_failure() -> None:
controller = _controller()
- controller.memory_runtime.final_flush_error = RuntimeError("provider unavailable")
+ controller.memory_runtime.session_lifecycle_error = RuntimeError("provider unavailable")
controller._memory_scopes_by_session = {
"ses-workbench": ("u-" + ("2" * 32), PROJECT),
}
@@ -467,23 +466,22 @@ def test_final_flush_memory_cli_session_swallows_runtime_failure() -> None:
)
assert result is False
- assert len(controller.memory_runtime.final_flush_calls) == 1
+ assert len(controller.memory_runtime.session_lifecycle_calls) == 1
def test_final_flush_memory_cli_session_recovers_scope_after_controller_restart() -> None:
controller = _controller()
principal_id = "u-" + ("2" * 32)
controller._memory_scopes_by_session = {}
- controller.memory_runtime.recovered_scope = (principal_id, PROJECT)
+ controller.memory_runtime.recovered_scopes = ((principal_id, PROJECT),)
result = asyncio.run(controller.final_flush_memory_cli_session("ses-workbench"))
assert result is True
- assert controller.memory_runtime.scope_recovery_calls == ["ses-workbench"]
- assert controller.memory_runtime.final_flush_calls == [
+ assert controller.memory_runtime.scopes_recovery_calls == ["ses-workbench"]
+ assert controller.memory_runtime.session_lifecycle_calls == [
{
- "principal_id": principal_id,
- "project_id": PROJECT,
+ "scopes": ((principal_id, PROJECT),),
"raw_session_id": "ses-workbench",
"deadline_seconds": 5.0,
}
@@ -497,7 +495,7 @@ def test_final_flush_memory_cli_session_skips_without_stored_scope() -> None:
result = asyncio.run(controller.final_flush_memory_cli_session("ses-absent"))
assert result is False
- assert controller.memory_runtime.scope_recovery_calls == ["ses-absent"]
+ assert controller.memory_runtime.scopes_recovery_calls == ["ses-absent"]
assert controller.memory_runtime.final_flush_calls == []
diff --git a/tests/test_memory_store.py b/tests/test_memory_store.py
index 6c289022e..a7de380b9 100644
--- a/tests/test_memory_store.py
+++ b/tests/test_memory_store.py
@@ -32,12 +32,14 @@ from core.memory.store import (
from core.memory.types import ProviderSessionRef
-PROJECT = "p-22222222222222222222222222222222"
+PROJECT = "default"
+LEGACY_PROJECT = "p-22222222222222222222222222222222"
FOUNDATION_SCHEMAS = (
Path(__file__).with_name("fixtures") / "memory_initial_foundation_v0.sql",
Path(__file__).with_name("fixtures") / "memory_foundation_v0.sql",
)
V1_SCHEMA = Path(__file__).with_name("fixtures") / "memory_foundation_v1.sql"
+V2_SCHEMA = Path(__file__).with_name("fixtures") / "memory_foundation_v2.sql"
def _dt(value: str) -> datetime:
@@ -185,6 +187,7 @@ def test_store_creates_exact_memory_tables_and_due_index(tmp_path: Path) -> None
"memory_capture_queue",
"memory_session_flush_state",
"memory_flush_settlements",
+ "memory_projects",
}.issubset(tables)
assert "ix_memory_capture_due" in indexes
queue_columns = {row[1] for row in conn.execute("PRAGMA table_info('memory_capture_queue')")}
@@ -282,7 +285,7 @@ def test_store_migrates_nonempty_foundation_v0_without_dropping_state(
provider_ref = ProviderSessionRef(
principal_id=principal_id,
epoch=0,
- project_ref=PROJECT,
+ project_ref=LEGACY_PROJECT,
session_id="src--4f619a27f96acb8854d2c1f4d2b301263832544740e2c0b176d1a1a05f5b997d--e0",
).serialize()
provider_column = (
@@ -298,9 +301,9 @@ def test_store_migrates_nonempty_foundation_v0_without_dropping_state(
) VALUES (?, 0, 'legacy-session'{provider_value}, ?, ?,
'user_input', 'legacy payload', 1, 1, 'pending', 'now')
""",
- ("legacy-digest", provider_ref, principal_id, PROJECT)
+ ("legacy-digest", provider_ref, principal_id, LEGACY_PROJECT)
if provider_column
- else ("legacy-digest", principal_id, PROJECT),
+ else ("legacy-digest", principal_id, LEGACY_PROJECT),
)
receipt_columns = (
", flush_observation, flush_status, flush_request_id, flush_observed_at, completed_at"
@@ -318,9 +321,9 @@ def test_store_migrates_nonempty_foundation_v0_without_dropping_state(
'agent', 2, 2, 'delivered', 1, 'add-legacy', 'now',
'succeeded', 'extracted', 'flush-legacy', 'now', 'now')
""",
- ("legacy-delivered", provider_ref, principal_id, PROJECT)
+ ("legacy-delivered", provider_ref, principal_id, LEGACY_PROJECT)
if provider_column
- else ("legacy-delivered", principal_id, PROJECT),
+ else ("legacy-delivered", principal_id, LEGACY_PROJECT),
)
store = MemoryStore(database)
@@ -449,10 +452,10 @@ def _install_representative_v1_database(database: Path) -> None:
ProviderSessionRef(
principal_id="u-11111111111111111111111111111111",
epoch=4,
- project_ref=PROJECT,
+ project_ref=LEGACY_PROJECT,
session_id="preserved-provider-session",
).serialize(),
- PROJECT,
+ LEGACY_PROJECT,
),
)
@@ -464,7 +467,7 @@ def test_store_migrates_v1_metadata_and_preserves_existing_data(tmp_path: Path)
store = MemoryStore(database)
with sqlite3.connect(database) as conn:
- assert conn.execute("PRAGMA user_version").fetchone()[0] == 2
+ assert conn.execute("PRAGMA user_version").fetchone()[0] == MEMORY_STORE_SCHEMA_VERSION
columns = {row[1] for row in conn.execute("PRAGMA table_info('memory_meta')")}
assert {
"processing_fault_generation",
@@ -513,10 +516,102 @@ def test_store_rolls_back_failed_v1_migration_without_changing_data(
).fetchone()[0] == "preserved payload"
+def test_named_project_cap_is_invalid_input_not_store_failure(tmp_path: Path) -> None:
+ store = MemoryStore(_store_path(tmp_path / "named-cap"))
+ principal = "u-11111111111111111111111111111111"
+ for index in range(16):
+ accepted = store.enqueue_request(
+ source_message_id=f"named-{index}",
+ session_id=f"ses-{index}",
+ principal_id=principal,
+ project_ref=f"proj{index:02d}",
+ provenance="agent",
+ payload_text="named",
+ occurred_at_ms=index + 1,
+ max_provider_timestamp_ms=4_102_444_800_000,
+ )
+ assert accepted.outcome == "accepted"
+ limited = store.enqueue_request(
+ source_message_id="named-overflow",
+ session_id="ses-overflow",
+ principal_id=principal,
+ project_ref="proj16",
+ provenance="agent",
+ payload_text="overflow",
+ occurred_at_ms=100,
+ max_provider_timestamp_ms=4_102_444_800_000,
+ )
+ assert limited.outcome == "project_limit"
+ reuse = store.enqueue_request(
+ source_message_id="named-reuse",
+ session_id="ses-reuse",
+ principal_id=principal,
+ project_ref="proj00",
+ provenance="agent",
+ payload_text="reuse",
+ occurred_at_ms=101,
+ max_provider_timestamp_ms=4_102_444_800_000,
+ )
+ assert reuse.outcome == "accepted"
+
+
+def test_store_migrates_v2_queue_and_accepts_default_project(tmp_path: Path) -> None:
+ """Scenario: MEMORY-SEARCH-005"""
+ database = _store_path(tmp_path / "schema-v2")
+ database.parent.mkdir(parents=True)
+ with sqlite3.connect(database) as conn:
+ conn.executescript(V2_SCHEMA.read_text(encoding="utf-8"))
+ conn.execute("PRAGMA user_version = 2")
+ conn.execute(
+ """
+ INSERT INTO memory_meta (
+ singleton, epoch, clear_in_progress, scope_key, provider_root_id,
+ last_provider_timestamp_ms, missed_count, processing_fault_generation,
+ processing_alert_active, updated_at
+ ) VALUES (1, 1, 0, ?, 'v2-root', 0, 0, 0, 0, 'now')
+ """,
+ (bytes.fromhex("11" * 32),),
+ )
+ conn.execute(
+ """
+ INSERT INTO memory_capture_queue (
+ source_message_digest, epoch, session_id, provider_session_ref,
+ generation, principal_id, project_ref, provenance, payload_text,
+ occurred_at_ms, provider_timestamp_ms, state, attempts,
+ lease_token, created_at
+ ) VALUES (
+ 'legacy-pending', 1, 'ses', 'ref', 1,
+ 'u-11111111111111111111111111111111', ?,
+ 'user_input', 'old payload', 1, 1, 'pending', 0, 0, 'now'
+ )
+ """,
+ (LEGACY_PROJECT,),
+ )
+
+ store = MemoryStore(database)
+ with sqlite3.connect(database) as conn:
+ assert conn.execute("PRAGMA user_version").fetchone()[0] == 3
+ assert conn.execute(
+ "SELECT project_ref FROM memory_capture_queue WHERE source_message_digest = 'legacy-pending'"
+ ).fetchone()[0] == LEGACY_PROJECT
+ accepted = store.enqueue_request(
+ source_message_id="new-default",
+ session_id="ses-new",
+ principal_id="u-11111111111111111111111111111111",
+ project_ref="default",
+ provenance="user_input",
+ payload_text="new payload",
+ occurred_at_ms=2,
+ max_provider_timestamp_ms=4_102_444_800_000,
+ )
+ assert accepted.outcome == "accepted"
+ assert store.list_memory_projects("u-11111111111111111111111111111111") == ("default",)
+
+
def test_store_rejects_unknown_nonzero_schema_without_rebuilding(
tmp_path: Path,
) -> None:
- version = 3
+ version = 4
database = _store_path(tmp_path / f"schema-v{version}")
database.parent.mkdir(parents=True)
with sqlite3.connect(database) as conn:
@@ -536,11 +631,12 @@ def test_store_rejects_unknown_nonzero_schema_without_rebuilding(
def test_session_scope_recovery_survives_store_reopen_and_separates_sessions(tmp_path: Path) -> None:
+ """Scenario: MEMORY-SEARCH-006"""
store_path = _store_path(tmp_path)
first_scope = ("u-11111111111111111111111111111111", PROJECT)
second_scope = (
"u-22222222222222222222222222222222",
- "p-33333333333333333333333333333333",
+ "billing",
)
store = MemoryStore(store_path)
_enqueue_for_scope(store, "source-a", "session-a", *first_scope)
@@ -572,7 +668,7 @@ def test_session_scope_recovery_fails_closed_when_raw_session_is_ambiguous(tmp_p
"source-b",
"shared-session",
"u-22222222222222222222222222222222",
- "p-33333333333333333333333333333333",
+ "billing",
)
assert store.resolve_current_session_scope("shared-session") is None
@@ -583,7 +679,7 @@ def test_session_scope_recovery_fails_closed_when_raw_session_is_ambiguous(tmp_p
),
(
"u-22222222222222222222222222222222",
- "p-33333333333333333333333333333333",
+ "billing",
),
)
@@ -595,7 +691,7 @@ def test_session_scope_recovery_fails_closed_when_raw_session_is_ambiguous(tmp_p
),
(
"u-22222222222222222222222222222222",
- "p-33333333333333333333333333333333",
+ "billing",
),
)
@@ -1426,7 +1522,7 @@ def test_reused_memory_session_anchor_is_namespaced_by_project(tmp_path: Path) -
source_message_id="second",
session_id="session",
principal_id="u-11111111111111111111111111111111",
- project_ref="p-33333333333333333333333333333333",
+ project_ref="billing",
provenance="user_input",
payload_text="queued payload",
occurred_at_ms=1_001,
diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.py
index 403da5f6b..412894682 100644
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@ -267,6 +267,8 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("## Personal Memory", enabled_prompt)
self.assertIn('`vibe memory search "<query>" --json`', enabled_prompt)
+ self.assertIn("cannot be `all`, `personal`", enabled_prompt)
+ self.assertIn("start with `p-` / `u-`", enabled_prompt)
self.assertIn("`vibe memory profile --json`", enabled_prompt)
self.assertIn("`vibe memory status --json`", enabled_prompt)
self.assertIn('`vibe memory remember "<text>" --json`', enabled_prompt)
diff --git a/tests/test_ui_memory_routes.py b/tests/test_ui_memory_routes.py
index 3bf3f241a..9b61ee18d 100644
--- a/tests/test_ui_memory_routes.py
+++ b/tests/test_ui_memory_routes.py
@@ -911,13 +911,13 @@ def test_memory_failures_proxy_is_direct_loopback_only_and_no_store(monkeypatch,
assert user_keys == ["avibe:local"]
-def test_memory_search_requires_csrf_and_only_forwards_query_and_policy(monkeypatch, tmp_path) -> None:
+def test_memory_search_requires_csrf_and_only_forwards_query_policy_and_optional_project(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
calls: list[tuple[str, dict[str, object], str]] = []
- async def search(query: str, policy: dict[str, object], *, user_key: str):
- calls.append((query, policy, user_key))
+ async def search(query: str, policy: dict[str, object], *, user_key: str, project: str | None = None):
+ calls.append((query, policy, user_key, project))
return {"status_code": 200, "body": {"status": "ok", "items": [], "warnings": []}}
monkeypatch.setattr(internal_client, "memory_search", search)
@@ -950,6 +950,7 @@ def test_memory_search_requires_csrf_and_only_forwards_query_and_policy(monkeypa
"include_current_session": False,
},
"avibe:local",
+ None,
)
]
assert response.headers["cache-control"] == "no-store"
diff --git a/ui/src/components/settings/memory/MemorySearchPanel.tsx b/ui/src/components/settings/memory/MemorySearchPanel.tsx
index ff8ec309b..45009df71 100644
--- a/ui/src/components/settings/memory/MemorySearchPanel.tsx
+++ b/ui/src/components/settings/memory/MemorySearchPanel.tsx
@@ -1,10 +1,11 @@
-import { useCallback, useState } from 'react';
+import { useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Loader2, Search as SearchIcon } from 'lucide-react';
import { Badge } from '../../ui/badge';
import { Button } from '../../ui/button';
import { Input } from '../../ui/input';
+import { Select } from '../../ui/select';
import { useApi } from '../../../context/ApiContext';
import type { MemoryRecallResult } from '../../../context/ApiContext';
import { useMemoryResource } from './useMemoryResource';
@@ -15,25 +16,49 @@ export const MemorySearchPanel: React.FC<{ enabled: boolean }> = ({ enabled }) =
const { t } = useTranslation();
const api = useApi();
const [query, setQuery] = useState('');
- const read = useCallback((text: string) => api.searchMemory(text, 20), [api]);
+ const [project, setProject] = useState('default');
+ const [projects, setProjects] = useState<Array<{ id: string; kind: string }>>([
+ { id: 'default', kind: 'default' },
+ { id: 'all', kind: 'all' },
+ ]);
+ const read = useCallback(
+ (text: string, selected: string) => api.searchMemory(text, 20, selected),
+ [api],
+ );
const {
data,
error,
loading: searching,
loaded: searched,
reload: search,
- } = useMemoryResource<MemoryItemsOk, [string]>({
+ } = useMemoryResource<MemoryItemsOk, [string, string]>({
read,
failureMessageKey: 'memory.search.searchFailed',
- // Each search reports its own outcome; a previous failure must not caption it.
clearErrorOnReload: true,
resetDataOnError: true,
});
+ useEffect(() => {
+ if (!enabled) return;
+ void api
+ .listMemoryProjects()
+ .then((result) => {
+ if (result && 'status' in result && result.status === 'ok' && Array.isArray(result.projects)) {
+ setProjects(result.projects);
+ }
+ })
+ .catch(() => {
+ setProjects([
+ { id: 'default', kind: 'default' },
+ { id: 'all', kind: 'all' },
+ ]);
+ });
+ }, [api, enabled]);
+
const runSearch = () => {
const trimmed = query.trim();
if (!trimmed) return;
- void search(trimmed);
+ void search(trimmed, project);
};
if (!enabled) {
@@ -41,11 +66,28 @@ export const MemorySearchPanel: React.FC<{ enabled: boolean }> = ({ enabled }) =
}
const items = data?.items ?? null;
+ const warnings = data?.warnings ?? [];
return (
<div className="flex flex-col gap-3">
<p className="text-[12.5px] text-muted">{t('memory.search.description')}</p>
- <div className="flex gap-2">
+ <div className="flex flex-col gap-2 sm:flex-row">
+ <Select
+ value={project}
+ onChange={(event) => setProject(event.target.value)}
+ aria-label={t('memory.search.projectLabel')}
+ wrapperClassName="sm:w-52"
+ >
+ {projects.map((row) => (
+ <option key={row.id} value={row.id}>
+ {row.kind === 'default'
+ ? t('memory.search.projectDefault')
+ : row.kind === 'all'
+ ? t('memory.search.projectAll')
+ : row.id}
+ </option>
+ ))}
+ </Select>
<div className="relative flex-1">
<SearchIcon size={14} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-muted" />
<Input
@@ -63,6 +105,12 @@ export const MemorySearchPanel: React.FC<{ enabled: boolean }> = ({ enabled }) =
{searching ? t('memory.search.searching') : t('memory.search.button')}
</Button>
</div>
+ {warnings.includes('memory_search_partial') ? (
+ <div className="rounded-xl border border-border bg-surface px-4 py-3 text-sm text-muted">{t('memory.search.partial')}</div>
+ ) : null}
+ {warnings.includes('memory_search_truncated') ? (
+ <div className="rounded-xl border border-border bg-surface px-4 py-3 text-sm text-muted">{t('memory.search.truncated')}</div>
+ ) : null}
{error ? (
<div className="rounded-xl border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive">{error}</div>
) : !searched ? null : !items || items.length === 0 ? (
@@ -75,6 +123,11 @@ export const MemorySearchPanel: React.FC<{ enabled: boolean }> = ({ enabled }) =
<div key={idx} className="rounded-xl border border-border bg-surface px-4 py-3">
<div className="mb-1 flex items-center gap-2">
<Badge variant="secondary">{t(`memory.kind.${item.kind}`)}</Badge>
+ {item.project && (project === 'all' || item.project !== 'default') ? (
+ <Badge variant="outline">
+ {item.project === 'default' ? t('memory.search.projectDefault') : item.project}
+ </Badge>
+ ) : null}
{item.date ? <span className="font-mono text-[10.5px] text-muted">{item.date}</span> : null}
</div>
<p className="whitespace-pre-wrap text-[13px] leading-relaxed text-foreground">{item.text}</p>
diff --git a/ui/src/components/settings/memory/memoryCopyContract.test.ts b/ui/src/components/settings/memory/memoryCopyContract.test.ts
index 1634941de..81571cd89 100644
--- a/ui/src/components/settings/memory/memoryCopyContract.test.ts
+++ b/ui/src/components/settings/memory/memoryCopyContract.test.ts
@@ -119,7 +119,9 @@ describe('Memory UI copy contracts', () => {
it.each(['en', 'zh'] as const)('keeps Search, source timestamps, and processing-log scope accurate in %s', (language) => {
if (language === 'en') {
- expect(en.memory.search.description).toBe('Search your profile, episodes, and facts.');
+ expect(en.memory.search.description).toContain('Default');
+ expect(en.memory.search.projectAll).toBe('All my projects');
+ expect(en.memory.search.partial).toContain('incomplete');
expect(en.memory.processingRecord.sources.help).toContain('last checked');
expect(en.memory.processingRecord.sources.help).not.toContain('last updated');
expect(en.memory.log.description).toBe(
@@ -127,7 +129,9 @@ describe('Memory UI copy contracts', () => {
);
expect(en.memory.clear.confirmDescription).toContain('Avibe-managed Memory data');
} else {
- expect(zh.memory.search.description).toBe('搜索你的画像、事件和事实。');
+ expect(zh.memory.search.description).toContain('Default');
+ expect(zh.memory.search.projectAll).toBe('我的全部项目');
+ expect(zh.memory.search.partial).toContain('不完整');
expect(zh.memory.processingRecord.sources.help).toContain('最近一次检查');
expect(zh.memory.processingRecord.sources.help).not.toContain('上次更新');
expect(zh.memory.log.description).toBe('查看本安装中所有用户和项目的已创建记忆条目的处理记录。');
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 873bb34c2..396f0a7ef 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -565,7 +565,8 @@ export type ApiContextType = {
getMemoryFailures: () => Promise<MemoryFailureLogResult>;
getMemoryMaintenance: () => Promise<MemoryMaintenanceResult>;
getMemoryProfile: () => Promise<MemoryItemsResult>;
- searchMemory: (query: string, limit?: number) => Promise<MemoryRecallResult>;
+ searchMemory: (query: string, limit?: number, project?: string) => Promise<MemoryRecallResult>;
+ listMemoryProjects: () => Promise<{ status: 'ok'; projects: Array<{ id: string; kind: 'default' | 'named' | 'all' }> } | { status: 'failed'; error?: string }>;
getMemoryLog: (cursor?: string | null, limit?: number) => Promise<MemoryLogListResult>;
getMemoryLogEntry: (memcellId: string) => Promise<MemoryLogDetailResult>;
clearMemory: () => Promise<MemoryClearResult>;
@@ -2003,11 +2004,14 @@ export type MemoryProfile = {
updated_at: string | null;
};
+export type MemorySearchWarning = 'memory_search_partial' | 'memory_search_truncated';
+
export type MemoryItem = {
kind: MemoryItemKind;
text: string;
date: string | null;
profile?: MemoryProfile;
+ project?: string;
};
export type MemoryItemsResult =
@@ -2018,7 +2022,7 @@ export type MemoryRecallResult =
| {
status: 'ok';
items: MemoryItem[];
- warnings: string[];
+ warnings: MemorySearchWarning[];
requested_mode: 'auto' | 'keyword' | 'vector' | 'hybrid' | 'agentic';
effective_mode: 'keyword' | 'vector' | 'hybrid' | 'agentic';
source: 'everos';
@@ -3321,7 +3325,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
getMemoryFailures: () => getJson('/api/memory/failures', { handleError: false }),
getMemoryMaintenance: () => getJson('/api/memory/maintenance', { handleError: false }),
getMemoryProfile: () => getJson('/api/memory/profile', { handleError: false }),
- searchMemory: (query, limit = 20) => postJson('/api/memory/search', {
+ searchMemory: (query, limit = 20, project) => postJson('/api/memory/search', {
query,
policy: {
mode: 'hybrid',
@@ -3329,7 +3333,9 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
include_profile: true,
include_current_session: false,
},
+ ...(project ? { project } : {}),
}, { handleError: false }),
+ listMemoryProjects: () => getJson('/api/memory/projects', { handleError: false }),
getMemoryLog: (cursor = null, limit = 20) => {
const query = new URLSearchParams({ limit: String(limit) });
if (cursor) query.set('cursor', cursor);
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 2d4440470..5504d7f8d 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -4221,14 +4221,19 @@
"sourceNote": "Distilled from your conversation history, plus any notes your Agent recorded."
},
"search": {
- "description": "Search your profile, episodes, and facts.",
+ "description": "Search your Memory. Conversations are stored in Default unless an Agent saved a fact to a named project.",
"placeholder": "Search your memory…",
"button": "Search",
"searching": "Searching…",
"empty": "No results.",
"searchFailed": "Search failed.",
"disabledHint": "Enable Memory to search.",
- "sourceNote": "Distilled from your conversation history, plus any notes your Agent recorded."
+ "sourceNote": "Distilled from your conversation history, plus any notes your Agent recorded.",
+ "projectLabel": "Memory project",
+ "projectDefault": "Default",
+ "projectAll": "All my projects",
+ "partial": "Some projects could not be searched. These results may be incomplete.",
+ "truncated": "Search stopped before every project was checked. These results may be incomplete."
},
"log": {
"description": "See the processing history for created Memory entries across every user and project on this installation.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 79d0b1b2d..46dca5a53 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -4221,14 +4221,19 @@
"sourceNote": "由你的对话历史,以及 Agent 记录的内容(如有)提炼而来。"
},
"search": {
- "description": "搜索你的画像、事件和事实。",
+ "description": "搜索你的记忆。对话默认写入 Default;只有 Agent 显式指定时才会进命名项目。",
"placeholder": "搜索你的记忆…",
"button": "搜索",
"searching": "搜索中…",
"empty": "没有结果。",
"searchFailed": "搜索失败。",
"disabledHint": "启用记忆后即可搜索。",
- "sourceNote": "由你的对话历史,以及 Agent 记录的内容(如有)提炼而来。"
+ "sourceNote": "由你的对话历史,以及 Agent 记录的内容(如有)提炼而来。",
+ "projectLabel": "记忆项目",
+ "projectDefault": "默认",
+ "projectAll": "我的全部项目",
+ "partial": "部分项目未能搜索,结果可能不完整。",
+ "truncated": "搜索在查完所有项目前停止,结果可能不完整。"
},
"log": {
"description": "查看本安装中所有用户和项目的已创建记忆条目的处理记录。",
diff --git a/vibe/cli.py b/vibe/cli.py
index 18d4edfec..7e0248fae 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -554,9 +554,18 @@ def cmd_memory(args) -> int:
elif operation == "profile":
response = internal_client.memory_profile_sync(**access)
elif operation == "search":
- response = internal_client.memory_search_sync(query, args.limit, **access)
+ response = internal_client.memory_search_sync(
+ query,
+ args.limit,
+ project=getattr(args, "project", None),
+ **access,
+ )
else:
- response = internal_client.memory_remember_sync(query, **access)
+ response = internal_client.memory_remember_sync(
+ query,
+ project=getattr(args, "project", None),
+ **access,
+ )
except internal_client.InternalServerUnavailable:
return _print_memory_cli_error(operation, "memory_sidecar_unavailable", as_json=as_json, language=language)
@@ -14242,6 +14251,11 @@ def build_parser():
default=8,
help=i18n_t("memory.cli.help.limit", memory_help_language),
)
+ memory_search_parser.add_argument(
+ "--project",
+ default=None,
+ help=i18n_t("memory.cli.help.project", memory_help_language),
+ )
memory_search_parser.add_argument(
"--json",
action="store_true",
@@ -14255,6 +14269,11 @@ def build_parser():
"text",
help=i18n_t("memory.cli.help.text", memory_help_language),
)
+ memory_remember_parser.add_argument(
+ "--project",
+ default=None,
+ help=i18n_t("memory.cli.help.project", memory_help_language),
+ )
memory_remember_parser.add_argument(
"--json",
action="store_true",
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 34cfed9fe..c7884601a 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -699,6 +699,7 @@
"search": "Search local Memory",
"remember": "Queue durable personal context",
"query": "Search query",
+ "project": "Memory project: default or a named slug such as billing",
"limit": "Maximum results (1-20)",
"text": "Text to remember (maximum 4,000 characters)",
"json": "Print machine-readable output"
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 9d4e81671..03a03194b 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -699,6 +699,7 @@
"search": "搜索本地记忆",
"remember": "将长期个人信息加入队列",
"query": "搜索内容",
+ "project": "记忆项目:default,或 billing 这类小写 slug",
"limit": "最大结果数(1-20)",
"text": "要记住的文本(最多 4,000 个字符)",
"json": "输出机器可读格式"
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index 5500e4370..ee20e3448 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -534,13 +534,17 @@ def memory_remember_sync(
text: str,
*,
caller_session_id: str | None = None,
+ project: str | None = None,
socket_path: Optional[Path] = None,
timeout: float = 10.0,
) -> dict[str, Any]:
+ payload: dict[str, object] = {"text": text}
+ if project is not None:
+ payload["project"] = project
return _memory_request_sync(
"POST",
"/internal/memory/remember",
- payload={"text": text},
+ payload=payload,
headers=_memory_cli_session_headers(caller_session_id),
socket_path=socket_path,
timeout=timeout,
@@ -866,18 +870,41 @@ async def memory_profile(
)
+async def memory_projects(
+ *,
+ user_key: str,
+ socket_path: Optional[Path] = None,
+ timeout: float = MEMORY_READ_TIMEOUT_SECONDS,
+) -> dict[str, Any]:
+ return await _memory_request(
+ "GET",
+ "/internal/memory/projects",
+ headers=_memory_user_key_headers(
+ "GET",
+ "/internal/memory/projects",
+ user_key,
+ ),
+ socket_path=socket_path,
+ timeout=timeout,
+ )
+
+
async def memory_search(
query: str,
policy: dict[str, object],
*,
user_key: str,
+ project: str | None = None,
socket_path: Optional[Path] = None,
timeout: float = MEMORY_SEARCH_TIMEOUT_SECONDS,
) -> dict[str, Any]:
+ payload: dict[str, object] = {"query": query, "policy": policy}
+ if project is not None:
+ payload["project"] = project
return await _memory_request(
"POST",
"/internal/memory/search",
- payload={"query": query, "policy": policy},
+ payload=payload,
headers=_memory_user_key_headers(
"POST",
"/internal/memory/search",
@@ -1004,21 +1031,25 @@ def memory_search_sync(
limit: int,
*,
caller_session_id: str | None = None,
+ project: str | None = None,
socket_path: Optional[Path] = None,
timeout: float = MEMORY_SEARCH_TIMEOUT_SECONDS,
) -> dict[str, Any]:
+ payload: dict[str, object] = {
+ "query": query,
+ "policy": {
+ "mode": "hybrid",
+ "max_results": limit,
+ "include_profile": True,
+ "include_current_session": False,
+ },
+ }
+ if project is not None:
+ payload["project"] = project
return _memory_request_sync(
"POST",
"/internal/memory/search",
- payload={
- "query": query,
- "policy": {
- "mode": "hybrid",
- "max_results": limit,
- "include_profile": True,
- "include_current_session": False,
- },
- },
+ payload=payload,
headers=_memory_cli_session_headers(caller_session_id),
socket_path=socket_path,
timeout=timeout,
@@ -1029,13 +1060,17 @@ def memory_remember_sync(
text: str,
*,
caller_session_id: str | None = None,
+ project: str | None = None,
socket_path: Optional[Path] = None,
timeout: float = 10.0,
) -> dict[str, Any]:
+ payload: dict[str, object] = {"text": text}
+ if project is not None:
+ payload["project"] = project
return _memory_request_sync(
"POST",
"/internal/memory/remember",
- payload={"text": text},
+ payload=payload,
headers=_memory_cli_session_headers(caller_session_id),
socket_path=socket_path,
timeout=timeout,
diff --git a/vibe/ui_memory_routes.py b/vibe/ui_memory_routes.py
index a0c11be1b..bb51fbea4 100644
--- a/vibe/ui_memory_routes.py
+++ b/vibe/ui_memory_routes.py
@@ -1051,6 +1051,20 @@ def register_memory_routes(app) -> None:
return await app.dispatch_native_request(starlette_request, handler)
+ @app.get("/api/memory/projects", include_in_schema=False)
+ async def memory_projects_get(starlette_request: FastAPIRequest):
+ async def handler():
+ user_key = _memory_ui_user_key()
+ if user_key is None:
+ return _memory_forbidden_response()
+ from vibe import internal_client
+
+ return await _memory_internal_response(
+ lambda: internal_client.memory_projects(user_key=user_key)
+ )
+
+ return await app.dispatch_native_request(starlette_request, handler)
+
@app.post("/api/memory/search", include_in_schema=False)
async def memory_search_post(starlette_request: FastAPIRequest):
async def handler():
@@ -1061,7 +1075,11 @@ def register_memory_routes(app) -> None:
payload = await starlette_request.json()
except Exception:
payload = None
- if not isinstance(payload, dict) or set(payload) != {"query", "policy"}:
+ if (
+ not isinstance(payload, dict)
+ or not {"query", "policy"}.issubset(payload)
+ or set(payload) - {"query", "policy", "project"}
+ ):
return _memory_response({"status": "failed", "error": "memory_invalid_input"}, status_code=400)
query = payload.get("query")
if not isinstance(query, str):
@@ -1072,6 +1090,9 @@ def register_memory_routes(app) -> None:
policy = RecallPolicy.from_payload(payload.get("policy"))
except (TypeError, ValueError):
return _memory_response({"status": "failed", "error": "memory_invalid_input"}, status_code=400)
+ project = payload.get("project")
+ if project is not None and not isinstance(project, str):
+ return _memory_response({"status": "failed", "error": "memory_invalid_input"}, status_code=400)
from vibe import internal_client
return await _memory_internal_response(
@@ -1079,6 +1100,7 @@ def register_memory_routes(app) -> None:
query,
policy.payload(),
user_key=user_key,
+ project=project,
)
)