Skip to content
Python

feat(memhub): multi-user Core — user_id on memory APIs, per-user Hermes grants

alvinfeia9709788d823
diff --git a/memhub/apps/core/src/one_memory/api.py b/memhub/apps/core/src/one_memory/api.py
index 342cd67..fc4c80d 100644
--- a/memhub/apps/core/src/one_memory/api.py
+++ b/memhub/apps/core/src/one_memory/api.py
@@ -14,6 +14,7 @@ from collections.abc import (
MutableMapping,
)
from contextlib import asynccontextmanager, nullcontext, suppress
+from dataclasses import replace
from datetime import UTC, datetime, timedelta
from functools import partial
from pathlib import Path
@@ -117,6 +118,7 @@ from one_memory.imports.access import (
AuthorizedSourceRoot,
SourceAccessError,
root_identity_matches,
+ source_root_identity,
)
from one_memory.imports.adapters import (
ScanFailure,
@@ -157,6 +159,7 @@ from one_memory.imports.sources.common import SourceInstallState
from one_memory.imports.sources.registry import (
RootCandidateKind,
SourceRegistration,
+ SourceRootCandidate,
build_source_catalog,
workbuddy_default_homes,
)
@@ -244,7 +247,17 @@ from one_memory.service_levels import (
from one_memory.source_import_receipts import SourceImportReceipt, build_source_import_receipt
from one_memory.source_read_access import SourceReadAccess
from one_memory.source_totals import SourceTotals
+from one_memory.strict_query import forbid_unknown_query_params
from one_memory.target_schema import bootstrap_fresh_management_schema
+from one_memory.user_scope import (
+ DEFAULT_USER_ID,
+ MULTI_USER_SOURCES,
+ USER_ID_PATTERN,
+ UserId,
+ lane_key,
+ owns,
+ split_lane,
+)
from one_memory.workspace_resolution import resolve_workspace_scopes
logger = logging.getLogger(__name__)
@@ -387,6 +400,12 @@ class CreateImportJobRequest(BaseModel):
class ConnectSourcesRequest(BaseModel):
source_ids: tuple[str, ...] = Field(min_length=1, max_length=32)
+ #: Whose grant this is. Only Hermes may connect a root for a user other
+ #: than `local`: a Hermes profile is another person's history.
+ user_id: UserId = DEFAULT_USER_ID
+ #: A root chosen by the caller instead of the source's candidate, such as
+ #: `~/.hermes/profiles/<name>`. Hermes only; Core computes its identity.
+ root: str | None = Field(default=None, min_length=1, max_length=4096)
confirm_environment_overrides: bool = False
full_rescan: bool = False
onboarding: bool = False
@@ -422,6 +441,8 @@ class SdkMemoryUpdateRequest(BaseModel):
variant: SdkMemoryVariant | None = None
# Experiences only: also replace the task.
task: str | None = Field(default=None, min_length=1, max_length=200_000)
+ #: Whose memory this is; another user's id answers 404.
+ user_id: UserId = DEFAULT_USER_ID
class SdkUserProfileResponse(BaseModel):
@@ -584,11 +605,15 @@ class ManualExtractReceipt(BaseModel):
class AskMemoryRequest(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
question: str = Field(min_length=1, max_length=2_000)
scope: str = Field(default="all-apps", min_length=1, max_length=512)
# Host-injected project directory, same boundary as recall. Optional so
# the web UI and older callers keep working unchanged.
workspace_path: str | None = Field(default=None, max_length=4_096)
+ #: Whose memories answer. Omitted, it is `local`, the App's library.
+ user_id: UserId = DEFAULT_USER_ID
class SdkHomeSummary(BaseModel):
@@ -626,6 +651,27 @@ class MemoryGraphResponse(BaseModel):
hy_graph_available: bool = True
+class SourceGrantView(BaseModel):
+ """One `(user_id, source_id)` grant, as `GET /api/v1/source-grants` lists it."""
+
+ model_config = ConfigDict(frozen=True, extra="forbid")
+
+ user_id: str
+ source_id: str
+ root_label: str
+ root_path: str
+ authorized: bool
+ revoked_at: datetime | None
+ sync_enabled: bool
+
+
+class SourceGrantList(BaseModel):
+ model_config = ConfigDict(frozen=True, extra="forbid")
+
+ schema_version: Literal[1] = 1
+ grants: tuple[SourceGrantView, ...]
+
+
class SdkMigrationRequired(RuntimeError):
"""A serving Core was started on a home that is not on SDK authority."""
@@ -928,6 +974,7 @@ def create_app(
write_queue=memory_write_queue,
extraction_settings=app.state.extraction_settings_store,
data_dir=runtime_settings.data_dir,
+ user_ids=lambda: _known_user_ids(app),
)
# C2 owns the single production budget (handle 5s + reserve 250ms,
# total 5.25s, lease 10s, renew 1s, claim 250ms). The composition
@@ -1100,6 +1147,13 @@ def create_app(
source_id
for source_id, registration in app.state.source_catalog.items()
if registration.capabilities.live_sync is CapabilityState.IMPLEMENTED
+ ) + tuple(
+ lane
+ for lane in _other_user_lanes(
+ app.state.source_catalog, app.state.source_grant_store
+ )
+ if app.state.source_catalog[split_lane(lane)[1]].capabilities.live_sync
+ is CapabilityState.IMPLEMENTED
)
# Resolved before the supervisor is built so it can state truthfully
# how it is being driven: watching only applies to roots that exist
@@ -1496,9 +1550,12 @@ def create_app(
Depends(local_api_guard(runtime_settings, valid_ui_session=ui_session_valid)),
Depends(require_external_endpoint),
]
- app.include_router(memory_add_router(protected))
+ # Memory reads and writes refuse a query parameter they do not declare: an
+ # ignored `user_id` would read as isolation that never happened.
+ strict = [*protected, Depends(forbid_unknown_query_params)]
+ app.include_router(memory_add_router(strict))
app.include_router(file_import_router(protected))
- app.include_router(sdk_context_router(protected))
+ app.include_router(sdk_context_router(strict))
# A4-01: scan-root configuration, so the CLI's `path` command has something
# to read instead of refusing.
@@ -1512,7 +1569,7 @@ def create_app(
if getattr(app.state, "memory_write_registry", None) is None:
app.state.memory_write_registry = WriteRegistry()
- app.include_router(sdk_memory_write_router(protected))
+ app.include_router(sdk_memory_write_router(strict))
from one_memory.call_event_routes import call_event_router
app.include_router(call_event_router(protected))
@@ -2287,7 +2344,11 @@ def create_app(
return SourceSyncState(source_id=source_id, sync_enabled=request.enabled)
async def _prepare_source_resume(source_id: str) -> None:
- """Prepare catch-up work before committing the new desired state."""
+ """Prepare catch-up work before committing the new desired state.
+
+ `source_id` is a lane key, so another user's lane prepares that
+ user's own cursors and history job.
+ """
await _live_sync(app).initialize_source(source_id, baseline_missing_files=True)
active = {
ImportStatus.PENDING,
@@ -2297,14 +2358,17 @@ def create_app(
ImportStatus.FAILED,
}
if any(
- job.source_id == source_id and job.operation == "history" and job.status in active
+ lane_key(job.user_id, job.source_id) == source_id
+ and job.operation == "history"
+ and job.status in active
for job in _job_store(app).list_jobs()
):
return
+ user_id, bare_source_id = split_lane(source_id)
await asyncio.to_thread(
_job_store(app).create,
- user_id="local",
- source_id=source_id,
+ user_id=user_id,
+ source_id=bare_source_id,
operation="history",
)
@@ -2312,7 +2376,7 @@ def create_app(
"""Run work prepared for a source after config.json has committed."""
try:
for job in _job_store(app).list_jobs():
- if job.source_id != source_id:
+ if lane_key(job.user_id, job.source_id) != source_id:
continue
if job.status is ImportStatus.PENDING:
_supervisor(app).enqueue(job.job_id)
@@ -2341,8 +2405,13 @@ def create_app(
response_model=SourceGrantReceipt,
dependencies=protected,
)
- async def revoke_source(source_id: str) -> SourceGrantReceipt:
+ async def revoke_source(
+ source_id: str,
+ user_id: str = Query(default=DEFAULT_USER_ID, pattern=USER_ID_PATTERN),
+ ) -> SourceGrantReceipt:
_require_registration(app, source_id)
+ if user_id != DEFAULT_USER_ID:
+ return await _revoke_other_user_grant(source_id, user_id)
receipt = _grant_store(app).receipt(
user_id="local",
source_id=source_id,
@@ -2378,6 +2447,65 @@ def create_app(
await _refresh_live_watch(app)
return receipt
+ async def _revoke_other_user_grant(source_id: str, user_id: str) -> SourceGrantReceipt:
+ """Stop reading another user's root. The App's switch is left alone."""
+ if source_id not in MULTI_USER_SOURCES:
+ raise HTTPException(status_code=422, detail="user_id_requires_multi_user_source")
+ lane = lane_key(user_id, source_id)
+ receipt = await asyncio.to_thread(
+ partial(_grant_store(app).receipt, user_id=user_id, source_id=source_id)
+ )
+ if receipt is None:
+ raise HTTPException(status_code=404, detail="grant_not_found")
+ active_statuses = {
+ ImportStatus.PENDING,
+ ImportStatus.RUNNING,
+ ImportStatus.PAUSED,
+ ImportStatus.INTERRUPTED,
+ ImportStatus.FAILED,
+ }
+ for job in _job_store(app).list_jobs():
+ if lane_key(job.user_id, job.source_id) == lane and job.status in active_statuses:
+ await _supervisor(app).cancel(job.job_id)
+ await _live_sync(app).stop_source(lane)
+ _supervisor(app).unregister_adapter(lane)
+ receipt = await asyncio.to_thread(
+ partial(_grant_store(app).revoke, user_id=user_id, source_id=source_id)
+ )
+ await _refresh_live_watch(app)
+ return receipt
+
+ @app.get(
+ "/api/v1/source-grants",
+ response_model=SourceGrantList,
+ dependencies=protected,
+ )
+ async def list_source_grants() -> SourceGrantList:
+ """Every grant of every user. `/api/v1/sources` stays `local`'s, as the App reads it."""
+
+ def describe() -> SourceGrantList:
+ config_store = _config_store(app)
+ views = []
+ for receipt, root_path in _grant_store(app).grants():
+ lane = lane_key(receipt.user_id, receipt.source_id)
+ authorized = receipt.revoked_at is None and receipt.revision > 0
+ views.append(
+ SourceGrantView(
+ user_id=receipt.user_id,
+ source_id=receipt.source_id,
+ root_label=receipt.root_label,
+ root_path=_display_candidate_path(
+ Path(root_path), runtime_settings.source_home
+ ),
+ authorized=authorized,
+ revoked_at=receipt.revoked_at,
+ sync_enabled=authorized and _lane_sync_enabled(config_store, lane),
+ )
+ )
+ return SourceGrantList(grants=tuple(views))
+
+ return await asyncio.to_thread(describe)
+
@app.post(
"/api/v1/import-jobs",
response_model=ImportJob,
@@ -2406,6 +2534,8 @@ def create_app(
async def connect_sources(
request: ConnectSourcesRequest,
) -> ConnectSourcesResponse:
+ if request.user_id != DEFAULT_USER_ID or request.root is not None:
+ return await _connect_other_root(request)
if request.onboarding:
app.state.history_import_gate_released = False
source_ids = tuple(dict.fromkeys(request.source_ids))
@@ -2511,6 +2641,103 @@ def create_app(
raise
return ConnectSourcesResponse(**result.model_dump())
+ async def _connect_other_root(request: ConnectSourcesRequest) -> ConnectSourcesResponse:
+ """Grant one Hermes root to a user: `~/.hermes/profiles/<name>` for its own user.
+
+ Only Hermes holds more than one person's history (one profile per
+ person), so a non-`local` user or a caller-chosen root is refused for
+ every other source. The grant is `(user_id, source_id)`; its cursors,
+ jobs and live sync follow that key.
+ """
+ source_ids = tuple(dict.fromkeys(request.source_ids))
+ if any(source_id not in MULTI_USER_SOURCES for source_id in source_ids):
+ raise HTTPException(status_code=422, detail="user_id_requires_multi_user_source")
+ if request.root is not None and len(source_ids) != 1:
+ raise HTTPException(status_code=422, detail="source_root_requires_one_source")
+ if request.user_id != DEFAULT_USER_ID and request.root is None:
+ # The user is the root that is read: another user must name theirs,
+ # or they would be handed `local`'s history.
+ raise HTTPException(status_code=422, detail="source_root_required_for_user")
+ if request.onboarding or request.import_upload_id is not None:
+ raise HTTPException(status_code=422, detail="user_id_unsupported_for_request")
+ if request.request_id is None:
+ raise HTTPException(status_code=409, detail="source_confirmation_required")
+ registrations = []
+ source_roots = dict(request.source_roots)
+ for source_id in source_ids:
+ registration = _require_registration(app, source_id)
+ if request.root is not None:
+ root = Path(request.root)
+ if not root.is_absolute():
+ raise HTTPException(status_code=422, detail="source_root_must_be_absolute")
+ # Named outright by the caller, like an environment override:
+ # no saved candidate may replace it, and naming it confirms it.
+ registration = replace(
+ registration,
+ candidate=SourceRootCandidate(
+ path=root, kind=RootCandidateKind.ENVIRONMENT_OVERRIDE
+ ),
+ )
+ try:
+ source_roots[source_id] = await asyncio.to_thread(source_root_identity, root)
+ except SourceAccessError as error:
+ raise HTTPException(status_code=409, detail=error.code) from None
+ registrations.append(registration)
+ existing_intent = await asyncio.to_thread(
+ partial(
+ app.state.source_connection_store.get,
+ request.request_id,
+ user_id=request.user_id,
+ )
+ )
+ try:
+ result = await asyncio.to_thread(
+ partial(
+ app.state.source_connection_store.connect,
+ request_id=request.request_id,
+ registrations=tuple(registrations),
+ source_roots=source_roots,
+ confirm_overrides=(
+ request.confirm_environment_overrides or request.root is not None
+ ),
+ full_rescan=request.full_rescan,
+ user_id=request.user_id,
+ )
+ )
+ except ConnectionIntentError as error:
+ raise HTTPException(status_code=409, detail=str(error)) from None
+ if existing_intent is not None:
+ return ConnectSourcesResponse(**result.model_dump())
+ for job in result.jobs:
+ registration = _require_registration(app, job.source_id)
+ grant = await asyncio.to_thread(
+ partial(
+ _grant_store(app).authorized_root,
+ user_id=job.user_id,
+ source_id=job.source_id,
+ )
+ )
+ if grant is None:
+ continue
+ lane = lane_key(job.user_id, job.source_id)
+ _supervisor(app).register_adapter(
+ registration.create_adapter(grant), user_id=job.user_id
+ )
+ _detection(app).pop(lane, None)
+ if job.user_id != DEFAULT_USER_ID:
+ if registration.capabilities.live_sync is CapabilityState.IMPLEMENTED:
+ _live_sync(app).ensure_source(lane)
+ # Another user's grant syncs while it stands (see
+ # `_lane_sync_enabled`); the App's switch is not touched.
+ await _prepare_source_resume(lane)
+ await _activate_source_resume(lane)
+ elif request.enable_sync:
+ await _prepare_source_resume(lane)
+ await asyncio.to_thread(_config_store(app).set_sync, job.source_id, True)
+ await _activate_source_resume(lane)
+ await _refresh_live_watch(app)
+ return ConnectSourcesResponse(**result.model_dump())
+
@app.get(
"/api/v1/source-connections/{request_id}",
response_model=ConnectionIntentReceipt,
@@ -2527,8 +2754,12 @@ def create_app(
response_model=list[ImportJob],
dependencies=protected,
)
- def list_import_jobs() -> list[ImportJob]:
- return _job_store(app).list_jobs()
+ def list_import_jobs(
+ user_id: str = Query(default=DEFAULT_USER_ID, pattern=USER_ID_PATTERN),
+ ) -> list[ImportJob]:
+ # One user's jobs: the App reads `local`'s and must not show another
+ # user's Hermes import as its own.
+ return [job for job in _job_store(app).list_jobs() if job.user_id == user_id]
@app.get(
"/api/v1/live-sync",
@@ -2857,9 +3088,11 @@ def create_app(
@app.get(
"/api/v2/home-summary",
response_model=SdkHomeSummary,
- dependencies=protected,
+ dependencies=strict,
)
- async def sdk_home_summary() -> SdkHomeSummary:
+ async def sdk_home_summary(
+ user_id: str = Query(default=DEFAULT_USER_ID, pattern=USER_ID_PATTERN),
+ ) -> SdkHomeSummary:
"""The home card: the memory page's count and its newest memory.
The count is `memory_stats` total (chat + working + coding
@@ -2871,12 +3104,12 @@ def create_app(
client = await _sdk_client_handle(app).client()
stats = await asyncio.to_thread(
client.memory_stats,
- user_id="local",
+ user_id=user_id,
statuses=["active"],
)
raw = await asyncio.to_thread(
client.list_memories,
- user_id="local",
+ user_id=user_id,
scene="all",
statuses=["active"],
limit=1,
@@ -2897,7 +3130,7 @@ def create_app(
@app.get(
"/api/v2/memory-library",
response_model=HySdkMemoryPage,
- dependencies=protected,
+ dependencies=strict,
)
async def sdk_memory_library(
statuses: list[str] = Query(default=["active"]), # noqa: B008
@@ -2907,6 +3140,7 @@ def create_app(
limit: int = Query(default=LIBRARY_PAGE_SIZE, ge=1, le=500),
window_id: str | None = Query(default=None, min_length=1, max_length=64),
scene: Literal["all", "chat", "working", "coding"] = Query(default="all"),
+ user_id: str = Query(default=DEFAULT_USER_ID, pattern=USER_ID_PATTERN),
) -> HySdkMemoryPage:
"""One page of memories across chat, working and coding.
@@ -2941,10 +3175,11 @@ def create_app(
limit=limit,
window_id=window_id,
scene=scene,
+ user_id=user_id,
)
raw = await asyncio.to_thread(
client.list_memories,
- user_id="local",
+ user_id=user_id,
scene=scene,
statuses=list(statuses),
include_sources=[source] if source else None,
@@ -2965,12 +3200,13 @@ def create_app(
@app.get(
"/api/v2/memories/graph",
response_model=MemoryGraphResponse,
- dependencies=protected,
+ dependencies=strict,
)
async def sdk_memory_graph(
limit: int = Query(default=160, ge=1, le=300),
offset: int = Query(default=0, ge=0),
source: str | None = Query(default=None, min_length=1),
+ user_id: str = Query(default=DEFAULT_USER_ID, pattern=USER_ID_PATTERN),
) -> MemoryGraphResponse:
"""The memory map on SDK authority: SDK memories plus the Kuzu overlay.
@@ -2984,7 +3220,7 @@ def create_app(
# left list's 20-row pagination window.
raw = await asyncio.to_thread(
client.list_memories,
- user_id="local",
+ user_id=user_id,
scene="all",
statuses=["active"],
include_sources=[source] if source else None,
@@ -3054,7 +3290,9 @@ def create_app(
# source withholds the overlay, as on the legacy map.
if not await asyncio.to_thread(_read_access(app).has_revoked_sources):
try:
- hy_graph = await _sdk_memory_runtime(app).graph_snapshot(limit=limit)
+ hy_graph = await _sdk_memory_runtime(app).graph_snapshot(
+ limit=limit, user_id=user_id
+ )
except HySdkError:
hy_graph = None
if hy_graph is not None:
@@ -3104,12 +3342,14 @@ def create_app(
@app.get(
"/api/v2/user-profile",
response_model=SdkUserProfileResponse,
- dependencies=protected,
+ dependencies=strict,
)
- async def sdk_user_profile() -> SdkUserProfileResponse:
+ async def sdk_user_profile(
+ user_id: str = Query(default=DEFAULT_USER_ID, pattern=USER_ID_PATTERN),
+ ) -> SdkUserProfileResponse:
try:
client = await _sdk_client_handle(app).client()
- value = await asyncio.to_thread(client.get_user_profile, user_id="local")
+ value = await asyncio.to_thread(client.get_user_profile, user_id=user_id)
profile = HySdkUserProfile.from_sdk(value)
except Exception as error:
raise _sdk_http_error(error, "hy_memory_profile_read_failed") from None
@@ -3118,18 +3358,23 @@ def create_app(
@app.get(
"/api/v2/memories/{memory_id}",
response_model=HySdkMemoryRecord,
- dependencies=protected,
+ dependencies=strict,
)
async def get_sdk_memory(
memory_id: str,
kind: SdkMemoryKind | None = None,
variant: SdkMemoryVariant | None = None,
+ user_id: str = Query(default=DEFAULT_USER_ID, pattern=USER_ID_PATTERN),
) -> HySdkMemoryRecord:
_check_memory_namespace(kind, variant)
try:
memory = await _get_sdk_memory(
_sdk_client_handle(app), memory_id, kind=kind, variant=variant
)
+ # The SDK's `get` takes no user: another user's memory reads as
+ # missing, never as existing.
+ if memory is not None and not owns(memory.user_id, user_id):
+ memory = None
except AmbiguousMemoryIdError:
raise HTTPException(status_code=409, detail="memory_id_ambiguous") from None
except Exception as error:
@@ -3141,7 +3386,7 @@ def create_app(
@app.put(
"/api/v2/memories/{memory_id}",
response_model=HySdkMemoryRecord,
- dependencies=protected,
+ dependencies=strict,
)
async def update_sdk_memory(
memory_id: str,
@@ -3153,6 +3398,13 @@ def create_app(
namespace = _namespace_kwargs(request.kind, request.variant)
try:
async with app.state.sdk_write_coordinator.use_client() as client:
+ # `update` takes no user: read the memory first and refuse
+ # another user's id exactly as a missing one.
+ current = await asyncio.to_thread(client.get, memory_id, **namespace)
+ if current is None or not owns(
+ HySdkMemoryRecord.from_sdk(current).user_id, request.user_id
+ ):
+ raise HTTPException(status_code=404, detail="memory_not_found")
update_kwargs: dict[str, object] = dict(namespace)
if request.task is not None:
update_kwargs["task"] = request.task
@@ -3190,16 +3442,27 @@ def create_app(
@app.delete(
"/api/v2/memories/{memory_id}",
status_code=204,
- dependencies=protected,
+ dependencies=strict,
)
async def delete_sdk_memory(
memory_id: str,
kind: SdkMemoryKind | None = None,
variant: SdkMemoryVariant | None = None,
+ user_id: str = Query(default=DEFAULT_USER_ID, pattern=USER_ID_PATTERN),
) -> Response:
_check_memory_namespace(kind, variant)
try:
async with app.state.sdk_write_coordinator.use_client() as client:
+ # `delete` takes no user. Another user's memory must not be
+ # deleted, nor its existence told: it answers 404. A memory
+ # that is already gone keeps answering 204, as before.
+ current = await asyncio.to_thread(
+ client.get, memory_id, **_namespace_kwargs(kind, variant)
+ )
+ if current is not None and not owns(
+ HySdkMemoryRecord.from_sdk(current).user_id, user_id
+ ):
+ raise HTTPException(status_code=404, detail="memory_not_found")
result = await asyncio.to_thread(
client.delete, memory_id, **_namespace_kwargs(kind, variant)
)
@@ -3210,6 +3473,8 @@ def create_app(
raise HySdkError(str(error_code or "hy_memory_delete_incomplete"))
if result.get("success") is not True and result.get("deleted_count") != 0:
raise HySdkError("hy_memory_delete_rejected")
+ except HTTPException:
+ raise
except AmbiguousMemoryIdError:
raise HTTPException(status_code=409, detail="memory_id_ambiguous") from None
except Exception as error:
@@ -3219,18 +3484,19 @@ def create_app(
@app.get(
"/api/v2/raw",
response_model=SdkRawPage,
- dependencies=protected,
+ dependencies=strict,
)
async def sdk_raw_library(
source: str | None = Query(default=None, min_length=1),
offset: int = Query(default=0, ge=0),
limit: int = Query(default=100, ge=1, le=500),
+ user_id: str = Query(default=DEFAULT_USER_ID, pattern=USER_ID_PATTERN),
) -> SdkRawPage:
try:
client = await _sdk_client_handle(app).client()
value = await asyncio.to_thread(
client.list_memories,
- user_id="local",
+ user_id=user_id,
layers=["l1_raw"],
include_sources=[source] if source else None,
offset=offset,
@@ -3244,7 +3510,7 @@ def create_app(
@app.post(
"/api/v2/memories/ask",
response_model=SdkMemoryAnswer,
- dependencies=protected,
+ dependencies=strict,
)
async def ask_sdk_memories(
request: AskMemoryRequest,
@@ -3261,7 +3527,9 @@ def create_app(
"om_ask",
)
try:
- answer = await _sdk_request_answerer(app).answer(request.question)
+ answer = await _sdk_request_answerer(app).answer(
+ request.question, user_id=request.user_id
+ )
except MemoryAnswerError as error:
raise HTTPException(status_code=503, detail=str(error)) from None
if request.question != "__om_probe__" and access is not None:
@@ -3278,7 +3546,7 @@ def create_app(
@app.post(
"/api/v2/memories/ask/stream",
- dependencies=protected,
+ dependencies=strict,
)
async def ask_sdk_memories_stream(
request: AskMemoryRequest,
@@ -3300,7 +3568,9 @@ def create_app(
final: dict[str, object] | None = None
try:
- async for event in answerer.answer_stream(request.question):
+ async for event in answerer.answer_stream(
+ request.question, user_id=request.user_id
+ ):
if event.get("type") == "final":
final = event
yield _sse(_serialize_ask_event(event))
@@ -3331,7 +3601,7 @@ def create_app(
@app.post(
"/api/v1/recall",
response_model=RecallReceipt,
- dependencies=protected,
+ dependencies=strict,
)
async def recall_memories(
request: RecallRequest,
@@ -3344,16 +3614,20 @@ def create_app(
await _require_external_recall_scope(
app, http_request, request.scope, request.workspace_path
)
- target = _recall_target(app)
+ target = (
+ _recall_target(app)
+ if request.user_id == DEFAULT_USER_ID
+ else _sdk_recall_target(app, request.user_id)
+ )
access = external_access(http_request.headers)
receipt = await recall_with_fallback(
request,
model_ready=lambda: _recall_model_ready(app),
recall_memories=target.recall_async,
- has_memories=lambda: _library_has_memories(app),
+ has_memories=lambda: _library_has_memories(app, request.user_id),
raw_sources=lambda: _recall_raw_sources(app, request, access, started),
search_raw=lambda query, limit, sources: _search_sdk_raw(
- app, query, limit=limit, sources=sources
+ app, query, limit=limit, sources=sources, user_id=request.user_id
),
)
event_store = getattr(app.state, "call_event_store", None)
@@ -3730,21 +4004,60 @@ def _sync_refused(code: str) -> HTTPException:
return HTTPException(status_code=409, detail=code)
+def _lane_sync_enabled(config_store: ConfigStore, lane: str) -> bool:
+ """Whether a lane may sync, before its grant is asked.
+
+ `local` keeps the App's per-source switch in the configuration document,
+ which stays global. Another user's Hermes grant syncs for as long as it
+ stands: connecting it is the consent, revoking it stops it, and it never
+ turns the App's switch on or off.
+ """
+ user_id, source_id = split_lane(lane)
+ if user_id == DEFAULT_USER_ID:
+ return config_store.sync_enabled(source_id)
+ return source_id in MULTI_USER_SOURCES
+
+
+def _other_user_lanes(
+ catalog: dict[str, SourceRegistration],
+ grant_store: SourceGrantStore,
+) -> tuple[str, ...]:
+ """Lanes of every unrevoked grant held by a user other than `local`."""
+ return tuple(
+ lane_key(receipt.user_id, receipt.source_id)
+ for receipt, _root in grant_store.grants()
+ if receipt.user_id != DEFAULT_USER_ID
+ and receipt.revoked_at is None
+ and receipt.source_id in MULTI_USER_SOURCES
+ and receipt.source_id in catalog
+ )
+
+
+def _known_user_ids(app: FastAPI) -> tuple[str, ...]:
+ """`local` and every user holding a grant: the users whose data Core keeps."""
+ users = [DEFAULT_USER_ID]
+ for receipt, _root in _grant_store(app).grants():
+ if receipt.user_id not in users:
+ users.append(receipt.user_id)
+ return tuple(users)
+
+
def _granted_roots(
source_ids: Iterable[str],
grant_store: SourceGrantStore,
config_store: ConfigStore,
) -> dict[str, Path]:
roots: dict[str, Path] = {}
- for source_id in source_ids:
- if not config_store.sync_enabled(source_id):
+ for lane in source_ids:
+ if not _lane_sync_enabled(config_store, lane):
continue
+ user_id, source_id = split_lane(lane)
try:
- grant = grant_store.authorized_root(user_id="local", source_id=source_id)
+ grant = grant_store.authorized_root(user_id=user_id, source_id=source_id)
except SourceAccessError:
continue
if grant is not None:
- roots[source_id] = grant.root
+ roots[lane] = grant.root
return roots
@@ -3753,6 +4066,14 @@ def _active_adapters(
grant_store: SourceGrantStore,
) -> dict[str, SourceAdapter]:
adapters: dict[str, SourceAdapter] = {}
+ for lane in _other_user_lanes(catalog, grant_store):
+ user_id, source_id = split_lane(lane)
+ try:
+ grant = grant_store.authorized_root(user_id=user_id, source_id=source_id)
+ if grant is not None:
+ adapters[lane] = catalog[source_id].create_adapter(grant)
+ except SourceAccessError:
+ continue
for source_id, registration in catalog.items():
try:
grant = grant_store.authorized_root(
@@ -3915,10 +4236,14 @@ def _config_store(app: FastAPI) -> ConfigStore:
def _source_processing_enabled(app: FastAPI, source_id: str) -> bool:
- if not _config_store(app).sync_enabled(source_id):
+ """`source_id` is a lane key: another user's lane asks that user's grant."""
+ if not _lane_sync_enabled(_config_store(app), source_id):
return False
+ user_id, bare_source_id = split_lane(source_id)
try:
- return _grant_store(app).authorized_root(user_id="local", source_id=source_id) is not None
+ return (
+ _grant_store(app).authorized_root(user_id=user_id, source_id=bare_source_id) is not None
+ )
except SourceAccessError:
return False
@@ -4437,13 +4762,32 @@ async def _recall_model_ready(app: FastAPI) -> bool:
return profile is not None and bool(profile.capabilities.model_available)
-async def _library_has_memories(app: FastAPI) -> bool:
+def _sdk_recall_target(app: FastAPI, user_id: str) -> SdkRecallTarget:
+ """Recall over one user's SDK memories; `get` results are kept only if theirs."""
+ handle = _sdk_client_handle(app)
+
+ async def owned(memory_id: str) -> HySdkMemoryRecord | None:
+ memory = await _get_sdk_memory(handle, memory_id)
+ return memory if memory is not None and owns(memory.user_id, user_id) else None
+
+ return SdkRecallTarget(
+ semantic_search=lambda query: _search_sdk_memories(
+ handle,
+ query,
+ user_id=user_id,
+ agent_id="*",
+ ),
+ get_memory=owned,
+ )
+
+
+async def _library_has_memories(app: FastAPI, user_id: str = DEFAULT_USER_ID) -> bool:
"""Any active memory at all. Asked only after an empty memory search."""
try:
client = await _sdk_client_handle(app).client()
raw = await asyncio.to_thread(
client.list_memories,
- user_id="local",
+ user_id=user_id,
statuses=["active"],
limit=1,
offset=0,
@@ -4501,13 +4845,14 @@ async def _search_sdk_raw(
*,
limit: int,
sources: frozenset[str] | None,
+ user_id: str = DEFAULT_USER_ID,
) -> tuple[HySdkRawHit, ...]:
"""The imported conversations nearest the query: the SDK raw layer."""
client = await _sdk_client_handle(app).client()
raw = await asyncio.to_thread(
client.search,
query,
- user_ids=["local"],
+ user_ids=[user_id],
agent_ids=[],
include_sources=sorted(sources) if sources else None,
limit=limit,
@@ -4610,6 +4955,7 @@ async def _library_search_page(
limit: int,
window_id: str | None,
scene: str = "all",
+ user_id: str = DEFAULT_USER_ID,
) -> HySdkMemoryPage:
"""One page of a keyword search, cut from a cached result window.
@@ -4621,7 +4967,9 @@ async def _library_search_page(
SDK so edits and deletes show. The whole library is never listed in Core.
"""
windows = _library_search_windows(app)
- key = window_key(query, source, statuses, scene)
+ # The user is part of the window's identity: one user's `window_id` must
+ # never cut a page from another user's matches.
+ key = window_key(query, source, statuses, scene, user_id)
window = windows.get(window_id, key) if window_id else None
window_reset = window_id is not None and window is None
if window is None:
@@ -4631,7 +4979,7 @@ async def _library_search_page(
query,
scene="all",
rerank=False,
- user_ids=["local"],
+ user_ids=[user_id],
agent_ids=[],
include_sources=[source] if source else None,
limit=fetch,
@@ -4667,7 +5015,7 @@ async def _library_search_page(
except HySdkReadError:
skipped += 1
continue
- if record.status == "active":
+ if record.status == "active" and owns(record.user_id, user_id):
memories.append(record)
_log_skipped_sdk_memories(skipped)
return HySdkMemoryPage(
@@ -4724,8 +5072,10 @@ def _source_writes_on(app: FastAPI, source_id: str) -> bool:
forever with attempts=0 while later jobs ran. Intake, claim and execute
all ask this one question.
"""
- if source_id == "one-memory-manual":
- receipt = _grant_store(app).receipt(user_id="local", source_id=source_id)
+ if split_lane(source_id)[1] == "one-memory-manual":
+ # One switch for hand-added memories, whoever adds them: it is a
+ # management setting, and management stays global.
+ receipt = _grant_store(app).receipt(user_id="local", source_id="one-memory-manual")
return receipt is None or receipt.revoked_at is None
return _source_processing_enabled(app, source_id)
@@ -4759,6 +5109,7 @@ def _history_import_gate_released(app: FastAPI) -> bool:
job
for job in jobs.list_jobs()
if job.operation == "history"
+ and job.user_id == DEFAULT_USER_ID
and job.source_id in selected
and (state.started_at is None or job.created_at >= state.started_at)
]
diff --git a/memhub/apps/core/src/one_memory/context_models.py b/memhub/apps/core/src/one_memory/context_models.py
index 6d02ee7..25fce74 100644
--- a/memhub/apps/core/src/one_memory/context_models.py
+++ b/memhub/apps/core/src/one_memory/context_models.py
@@ -5,6 +5,8 @@ from typing import Annotated, Literal
from pydantic import BaseModel, ConfigDict, Field, model_validator
+from one_memory.user_scope import DEFAULT_USER_ID, UserId
+
ContextKind = Literal["raw", "memory"]
ContextSearchChannel = Literal["lexical", "semantic"]
ContextSemanticStatus = Literal["not_searched", "completed", "failed", "timed_out"]
@@ -58,6 +60,8 @@ class SdkContextSearchRequest(ContextSearchRequest):
limit: int = Field(default=10, ge=1, le=20, strict=True)
schema_limit: int = Field(default=3, ge=0, le=20, strict=True)
intention_limit: int = Field(default=1, ge=0, le=20, strict=True)
+ #: Whose memories to search. The App never sends it and reads `local`.
+ user_id: UserId = DEFAULT_USER_ID
class ContextMessage(BaseModel):
diff --git a/memhub/apps/core/src/one_memory/context_routes.py b/memhub/apps/core/src/one_memory/context_routes.py
index 29ea443..500ad4d 100644
--- a/memhub/apps/core/src/one_memory/context_routes.py
+++ b/memhub/apps/core/src/one_memory/context_routes.py
@@ -28,6 +28,7 @@ from one_memory.hy_sdk_types import (
parse_sdk_search,
)
from one_memory.imports.storage import EvidenceStore
+from one_memory.user_scope import owns
CALL_EVENT_RESPONSE_BUDGET_MS = 250
@@ -73,7 +74,7 @@ def sdk_context_router(dependencies: Sequence[Depends]) -> APIRouter:
raw = await asyncio.to_thread(
client.search,
value.query,
- user_ids=["local"],
+ user_ids=[value.user_id],
agent_ids=[],
include_sources=list(authority.raw_sources or ()),
limit=value.limit,
@@ -108,7 +109,7 @@ def sdk_context_router(dependencies: Sequence[Depends]) -> APIRouter:
raw = await asyncio.to_thread(
client.search,
value.query,
- user_ids=["local"],
+ user_ids=[value.user_id],
agent_ids=[],
limit=value.limit,
min_score=sdk_relevance_floor(),
@@ -123,7 +124,12 @@ def sdk_context_router(dependencies: Sequence[Depends]) -> APIRouter:
for hit in hits:
record = await asyncio.to_thread(client.get, hit.memory_id)
memory = None if record is None else HySdkMemoryRecord.from_sdk(record)
- if memory is None or memory.status != "active":
+ # `get` takes no user: a hit is kept only if it is the caller's.
+ if (
+ memory is None
+ or memory.status != "active"
+ or not owns(memory.user_id, value.user_id)
+ ):
continue
items.append(
SdkMemoryContextItem(
diff --git a/memhub/apps/core/src/one_memory/imports/discovery.py b/memhub/apps/core/src/one_memory/imports/discovery.py
index 551a10f..b406bd2 100644
--- a/memhub/apps/core/src/one_memory/imports/discovery.py
+++ b/memhub/apps/core/src/one_memory/imports/discovery.py
@@ -27,6 +27,7 @@ def discovered_off_loop(
*,
suffixes: frozenset[str],
max_targets: int,
+ excluded_top_directories: frozenset[str] = frozenset(),
) -> AsyncIterator[SourceFileDiscoveryEvent]:
"""The same walk, for callers that have an event loop to keep free.
@@ -41,6 +42,7 @@ def discovered_off_loop(
grant,
suffixes=suffixes,
max_targets=max_targets,
+ excluded_top_directories=excluded_top_directories,
),
scope_key=grant.source_id,
)
@@ -51,12 +53,15 @@ def discover_source_files(
*,
suffixes: frozenset[str],
max_targets: int,
+ excluded_top_directories: frozenset[str] = frozenset(),
) -> Iterator[SourceFileDiscoveryEvent]:
"""Metadata only: one lstat per candidate, no open and no per-file grant lookup.
The grant and root identity are checked once before the walk. Each listed
file keeps the grant's check, which runs again when that file is opened;
the open itself refuses symlinks and any inode other than the one listed.
+ `excluded_top_directories` are directories directly under the root that
+ are never entered, such as another user's Hermes profiles.
"""
grant.check_root()
inspected = 0
@@ -64,8 +69,12 @@ def discover_source_files(
grant.root,
followlinks=False,
):
+ at_root = Path(directory) == grant.root
child_directories[:] = sorted(
- child for child in child_directories if not (Path(directory) / child).is_symlink()
+ child
+ for child in child_directories
+ if not (Path(directory) / child).is_symlink()
+ and not (at_root and child in excluded_top_directories)
)
for filename in sorted(filenames):
if Path(filename).suffix.lower() not in suffixes:
diff --git a/memhub/apps/core/src/one_memory/imports/grants.py b/memhub/apps/core/src/one_memory/imports/grants.py
index e0ddffd..f6c67e1 100644
--- a/memhub/apps/core/src/one_memory/imports/grants.py
+++ b/memhub/apps/core/src/one_memory/imports/grants.py
@@ -252,6 +252,18 @@ class SourceGrantStore:
).fetchone()
return self._to_receipt(row) if row else None
+ def grants(self) -> tuple[tuple[SourceGrantReceipt, str], ...]:
+ """Every grant of every user, with its granted root path.
+
+ One source may hold several grants, one per `(user_id, source_id)`:
+ a Hermes root for `local` and a Hermes profile for another user.
+ """
+ with self._connect() as connection:
+ rows = connection.execute(
+ "SELECT * FROM source_grants ORDER BY source_id, user_id"
+ ).fetchall()
+ return tuple((self._to_receipt(row), str(row["requested_path"])) for row in rows)
+
def require_receipt(self, *, user_id: str, source_id: str) -> SourceGrantReceipt:
receipt = self.receipt(user_id=user_id, source_id=source_id)
if receipt is None:
diff --git a/memhub/apps/core/src/one_memory/imports/live_sync.py b/memhub/apps/core/src/one_memory/imports/live_sync.py
index d432add..4eae0d2 100644
--- a/memhub/apps/core/src/one_memory/imports/live_sync.py
+++ b/memhub/apps/core/src/one_memory/imports/live_sync.py
@@ -28,6 +28,7 @@ from one_memory.imports.adapters import (
)
from one_memory.imports.jobs import ImportJob, ImportJobStore, ImportStatus
from one_memory.imports.supervisor import ImportSupervisor
+from one_memory.user_scope import DEFAULT_USER_ID, lane_key, split_lane
#: How long an automatic retry will wait for a wedged worker to notice cancel.
ABANDON_TIMEOUT_SECONDS = 5.0
@@ -64,7 +65,12 @@ class LiveSyncHealth(BaseModel):
class PollingLiveSyncSupervisor:
- """Near-live sync that reuses each adapter's persisted incremental cursor."""
+ """Near-live sync that reuses each adapter's persisted incremental cursor.
+
+ A "source" here is a lane key (`user_scope.lane_key`): the bare source id
+ for `local`, `source@user` for another user's grant. Cursors, jobs and
+ locks are therefore per `(user_id, source_id)`.
+ """
def __init__(
self,
@@ -92,8 +98,22 @@ class PollingLiveSyncSupervisor:
}
self._locks = {source_id: asyncio.Lock() for source_id in self.source_ids}
self._task: asyncio.Task[None] | None = None
+ self._group: asyncio.TaskGroup | None = None
self._observers: set[asyncio.Task[None]] = set()
+ def ensure_source(self, source_id: str) -> None:
+ """Follow a lane granted after start, such as a new Hermes profile."""
+ if source_id in self._locks:
+ return
+ self.source_ids = (*self.source_ids, source_id)
+ self._health.setdefault(
+ source_id,
+ LiveSyncHealth(source_id=source_id, mode=self.mode, state=LiveSyncState.IDLE),
+ )
+ self._locks[source_id] = asyncio.Lock()
+ if self._group is not None:
+ self._group.create_task(self._poll_source(source_id))
+
def _set_health(self, source_id: str, value: LiveSyncHealth) -> None:
previous = self._health.get(source_id)
self._health[source_id] = value
@@ -152,7 +172,12 @@ class PollingLiveSyncSupervisor:
self._watched_sources = frozenset(source_ids)
def all_health(self) -> tuple[LiveSyncHealth, ...]:
- return tuple(self.health(source_id) for source_id in self.source_ids)
+ """`local`'s lanes only: what the App has always been shown."""
+ return tuple(
+ self.health(source_id)
+ for source_id in self.source_ids
+ if split_lane(source_id)[0] == DEFAULT_USER_ID
+ )
async def initialize_source(
self, source_id: str, *, baseline_missing_files: bool = True
@@ -164,11 +189,12 @@ class PollingLiveSyncSupervisor:
baselines = (
await adapter.live_baseline() if isinstance(adapter, _LiveBaselineAdapter) else {}
)
+ user_id, bare_source_id = split_lane(source_id)
await in_the_background(
partial(
self.job_store.ensure_live_cursors,
- user_id="local",
- source_id=source_id,
+ user_id=user_id,
+ source_id=bare_source_id,
baselines=baselines,
baseline_missing_files=baseline_missing_files,
)
@@ -228,7 +254,7 @@ class PollingLiveSyncSupervisor:
(
job
for job in reversed(source_jobs)
- if job.source_id == source_id
+ if lane_key(job.user_id, job.source_id) == source_id
and job.operation == "sync"
and job.status
in {
@@ -277,13 +303,13 @@ class PollingLiveSyncSupervisor:
competing = [
job
for job in source_jobs
- if job.source_id == source_id
+ if lane_key(job.user_id, job.source_id) == source_id
and job.operation != "sync"
and job.status
in {ImportStatus.PENDING, ImportStatus.RUNNING, ImportStatus.INTERRUPTED}
]
bounded_history_incomplete = any(
- job.source_id == source_id
+ lane_key(job.user_id, job.source_id) == source_id
and job.operation == "history"
and job.history_after is not None
and job.status is not ImportStatus.COMPLETED
@@ -379,11 +405,12 @@ class PollingLiveSyncSupervisor:
await close()
async def _live_cursors(self, source_id: str, adapter: object) -> dict[str, SourceCursor]:
+ user_id, bare_source_id = split_lane(source_id)
cursors = await in_the_background(
partial(
self.job_store.get_source_cursors,
- user_id="local",
- source_id=source_id,
+ user_id=user_id,
+ source_id=bare_source_id,
operation="sync",
)
)
@@ -395,8 +422,8 @@ class PollingLiveSyncSupervisor:
return await in_the_background(
partial(
self.job_store.ensure_live_cursors,
- user_id="local",
- source_id=source_id,
+ user_id=user_id,
+ source_id=bare_source_id,
baselines=baselines,
)
)
@@ -520,9 +547,13 @@ class PollingLiveSyncSupervisor:
async def _run(self) -> None:
# A source owns its cadence; one large catch-up cannot delay every
# other source. The group keeps shutdown responsible for every poller.
- async with asyncio.TaskGroup() as group:
- for source_id in self.source_ids:
- group.create_task(self._poll_source(source_id))
+ try:
+ async with asyncio.TaskGroup() as group:
+ self._group = group
+ for source_id in self.source_ids:
+ group.create_task(self._poll_source(source_id))
+ finally:
+ self._group = None
async def _poll_source(self, source_id: str) -> None:
while True:
diff --git a/memhub/apps/core/src/one_memory/imports/runner.py b/memhub/apps/core/src/one_memory/imports/runner.py
index f45b1e6..72ed922 100644
--- a/memhub/apps/core/src/one_memory/imports/runner.py
+++ b/memhub/apps/core/src/one_memory/imports/runner.py
@@ -3,7 +3,7 @@ import logging
import math
import sqlite3
from collections import Counter
-from collections.abc import Callable
+from collections.abc import AsyncIterator, Callable
from contextlib import suppress
from contextvars import ContextVar
from dataclasses import dataclass, field
@@ -227,14 +227,17 @@ class ImportRunner:
heartbeat = asyncio.create_task(self._keep_alive(job_id=job_id, runner_token=runner_token))
pending = _PendingSkips()
writes = _PendingWrites()
- stream = adapter.scan(
- ScanOptions(
- cursors=cursors,
- reuse_listing=(
- job.operation == "history"
- or (job.operation == "sync" and job.source_id == "workbuddy")
- ),
- )
+ stream = _owned_by(
+ adapter.scan(
+ ScanOptions(
+ cursors=cursors,
+ reuse_listing=(
+ job.operation == "history"
+ or (job.operation == "sync" and job.source_id == "workbuddy")
+ ),
+ )
+ ),
+ job.user_id,
)
slice_cursors = dict(cursors)
next_event: asyncio.Future[ScanEvent] | None = None
@@ -924,3 +927,30 @@ async def _settled_work[T](
with suppress(asyncio.CancelledError, Exception):
task.result()
raise
+
+
+def _owned_by(stream: AsyncIterator[ScanEvent], user_id: str) -> AsyncIterator[ScanEvent]:
+ """Stamp every scanned record with the user whose root is being read.
+
+ Adapters know nothing of users and emit `local`. Which user a record
+ belongs to is decided by the grant the job reads (a Hermes profile's
+ `state.db` is that profile's user), so the job's user is the record's.
+ `local` passes the stream through untouched.
+ """
+ if user_id == "local":
+ return stream
+ return _restamped(stream, user_id)
+
+
+async def _restamped(stream: AsyncIterator[ScanEvent], user_id: str) -> AsyncIterator[ScanEvent]:
+ try:
+ async for event in stream:
+ if isinstance(event, ScannedEvidence) and event.evidence.user_id != user_id:
+ event = event.model_copy(
+ update={"evidence": event.evidence.model_copy(update={"user_id": user_id})}
+ )
+ yield event
+ finally:
+ close = getattr(stream, "aclose", None)
+ if close is not None:
+ await close()
diff --git a/memhub/apps/core/src/one_memory/imports/sources/hermes.py b/memhub/apps/core/src/one_memory/imports/sources/hermes.py
index f36c839..3f558a0 100644
--- a/memhub/apps/core/src/one_memory/imports/sources/hermes.py
+++ b/memhub/apps/core/src/one_memory/imports/sources/hermes.py
@@ -88,6 +88,7 @@ class HermesSourceAdapter:
self.grant,
suffixes=frozenset({".jsonl", ".db"}),
max_targets=10_000,
+ excluded_top_directories=frozenset({HERMES_PROFILES_DIRECTORY}),
):
if isinstance(item, AuthorizedSourceFile) and _is_hermes_target(
item.relative_path.as_posix()
@@ -101,6 +102,7 @@ class HermesSourceAdapter:
self.grant,
suffixes=frozenset({".jsonl", ".db"}),
max_targets=options.max_scan_targets or 100_000,
+ excluded_top_directories=frozenset({HERMES_PROFILES_DIRECTORY}),
):
yield ScanProgressEvent(
phase=ScanPhase.DISCOVER,
@@ -247,8 +249,17 @@ def parse_hermes_rollout_record(
)
+#: Hermes keeps each extra profile under `<root>/profiles/<name>/`, with its
+#: own `state.db` and sessions. A profile is another person's history: it is
+#: read only through its own grant (its own MemHub user), never as part of the
+#: root above it. Hermes' own export skips this directory for the same reason.
+HERMES_PROFILES_DIRECTORY = "profiles"
+
+
def _is_hermes_target(relative_path: str) -> bool:
path = PurePosixPath(relative_path)
+ if path.parts and path.parts[0] == HERMES_PROFILES_DIRECTORY:
+ return False
return path.name == "state.db" or (path.suffix == ".jsonl" and "sessions" in path.parts)
diff --git a/memhub/apps/core/src/one_memory/imports/supervisor.py b/memhub/apps/core/src/one_memory/imports/supervisor.py
index 9c03bc9..b46bef4 100644
--- a/memhub/apps/core/src/one_memory/imports/supervisor.py
+++ b/memhub/apps/core/src/one_memory/imports/supervisor.py
@@ -24,6 +24,7 @@ from one_memory.service_levels import (
ServiceLevelScheduler,
ServiceResource,
)
+from one_memory.user_scope import lane_key, split_lane
class UnknownSourceError(KeyError):
@@ -82,36 +83,45 @@ class ImportSupervisor:
self._tasks: dict[str, asyncio.Task[None]] = {}
self._drains: dict[str, asyncio.Task[None]] = {}
- def register_adapter(self, adapter: SourceAdapter) -> None:
- self.adapters[adapter.descriptor.source_id] = adapter
+ def register_adapter(self, adapter: SourceAdapter, *, user_id: str = "local") -> None:
+ """Adapters are keyed by lane: the source id for `local`, `source@user`
+ for another user's grant of the same source."""
+ self.adapters[lane_key(user_id, adapter.descriptor.source_id)] = adapter
def unregister_adapter(self, source_id: str) -> None:
self.adapters.pop(source_id, None)
+ @staticmethod
+ def lane_of(job: ImportJob) -> str:
+ return lane_key(job.user_id, job.source_id)
+
def active_job_ids(self) -> frozenset[str]:
return frozenset(job_id for job_id, task in self._tasks.items() if not task.done())
def create_job(
self, source_id: str, *, operation: Literal["history", "sync"] = "history"
) -> ImportJob:
+ """`source_id` is a lane key: another user's lane creates that user's job."""
if self.source_enabled is not None and not self.source_enabled(source_id):
raise SourceAccessError(SourceAccessErrorCode.GRANT_REQUIRED)
- return self.job_store.create(user_id="local", source_id=source_id, operation=operation)
+ user_id, bare_source_id = split_lane(source_id)
+ return self.job_store.create(user_id=user_id, source_id=bare_source_id, operation=operation)
def enqueue(self, job_id: str) -> ImportJob:
if job_id in self._drains:
raise InvalidJobTransitionError("import_cleanup_in_progress")
job = self.job_store.require(job_id)
- if job.source_id not in self.adapters:
- raise UnknownSourceError(job.source_id)
- if self.source_enabled is not None and not self.source_enabled(job.source_id):
+ lane = self.lane_of(job)
+ if lane not in self.adapters:
+ raise UnknownSourceError(lane)
+ if self.source_enabled is not None and not self.source_enabled(lane):
return job
existing = self._tasks.get(job_id)
if existing is None or existing.done():
self._tasks[job_id] = asyncio.create_task(
self._execute(
job_id,
- source_id=job.source_id,
+ source_id=lane,
operation=job.operation,
)
)
@@ -130,8 +140,10 @@ class ImportSupervisor:
# pending history. Each resumed runner will yield after one bounded slice.
for status in (ImportStatus.INTERRUPTED, ImportStatus.PENDING):
for job in self.job_store.list_jobs(status=status):
- if job.source_id in self.adapters:
- if self.source_enabled is not None and not self.source_enabled(job.source_id):
+ if self.lane_of(job) in self.adapters:
+ if self.source_enabled is not None and not self.source_enabled(
+ self.lane_of(job)
+ ):
continue
if job.status is not ImportStatus.PENDING:
self.job_store.queue_for_resume(job.job_id)
@@ -227,7 +239,7 @@ class ImportSupervisor:
}:
return
if self.source_enabled is not None and not await in_the_background(
- self.source_enabled, job.source_id
+ self.source_enabled, self.lane_of(job)
):
return
runner = ImportRunner(
@@ -238,7 +250,7 @@ class ImportSupervisor:
sdk_queue=self.sdk_queue,
sdk_authority=self.sdk_authority,
)
- adapter = self.adapters[job.source_id]
+ adapter = self.adapters[self.lane_of(job)]
if self.prepare_adapter is not None:
adapter = await self.prepare_adapter(job, adapter)
@@ -273,7 +285,7 @@ class ImportSupervisor:
and retry_attempt < self.max_history_retries
and (
self.source_enabled is None
- or await in_the_background(self.source_enabled, current.source_id)
+ or await in_the_background(self.source_enabled, self.lane_of(current))
)
):
delay = self.retry_base_seconds * (2**retry_attempt)
diff --git a/memhub/apps/core/src/one_memory/library_search_window.py b/memhub/apps/core/src/one_memory/library_search_window.py
index f5906dc..8c17477 100644
--- a/memhub/apps/core/src/one_memory/library_search_window.py
+++ b/memhub/apps/core/src/one_memory/library_search_window.py
@@ -7,9 +7,9 @@ between pages. The matches are kept here under an opaque ``window_id`` that
the client passes back with the next offset.
A window is bound to the filters it was searched with (query, source,
-statuses, scene). It expires after ``ttl_seconds`` without being read, and the
-store keeps at most ``max_windows`` windows, dropping the least recently read
-first.
+statuses, scene) and to the user whose library it searched. It expires after
+``ttl_seconds`` without being read, and the store keeps at most
+``max_windows`` windows, dropping the least recently read first.
Only memory identities are kept, never content: each page is read fresh from
the SDK, so an edit or a delete shows on the next page read.
"""
@@ -28,13 +28,17 @@ from one_memory.hy_sdk_types import LibraryHit
DEFAULT_WINDOW_TTL_SECONDS = 300.0
DEFAULT_MAX_WINDOWS = 32
-WindowKey = tuple[str, str | None, tuple[str, ...], str]
+WindowKey = tuple[str, str | None, tuple[str, ...], str, str]
def window_key(
- query: str, source: str | None, statuses: list[str], scene: str = "all"
+ query: str,
+ source: str | None,
+ statuses: list[str],
+ scene: str = "all",
+ user_id: str = "local",
) -> WindowKey:
- return (query, source, tuple(sorted(set(statuses))), scene)
+ return (query, source, tuple(sorted(set(statuses))), scene, user_id)
@dataclass(frozen=True)
diff --git a/memhub/apps/core/src/one_memory/memory_additions.py b/memhub/apps/core/src/one_memory/memory_additions.py
index 89fa297..e43d425 100644
--- a/memhub/apps/core/src/one_memory/memory_additions.py
+++ b/memhub/apps/core/src/one_memory/memory_additions.py
@@ -11,10 +11,11 @@ import asyncio
import sqlite3
from collections.abc import Sequence
from datetime import UTC, datetime
+from functools import partial
from typing import Any, Literal, cast
from uuid import UUID
-from fastapi import APIRouter, BackgroundTasks, HTTPException, Request
+from fastapi import APIRouter, BackgroundTasks, HTTPException, Query, Request
from fastapi.params import Depends
from pydantic import BaseModel, ConfigDict, Field, field_validator
@@ -34,6 +35,7 @@ from one_memory.memory_server.durable_queue import DurableWriteQueue
from one_memory.memory_server.unified_entry import UnifiedWriteIntake
from one_memory.memory_tasks import MemoryTaskStatus, MemoryTaskStore
from one_memory.secrets import SecretStoreUnavailableError
+from one_memory.user_scope import DEFAULT_USER_ID, USER_ID_PATTERN, UserId
SOURCE_ID = "one-memory-manual"
MemoryAddState = Literal[
@@ -53,6 +55,8 @@ class MemoryAddInput(BaseModel):
request_id: UUID
text: str = Field(min_length=1, max_length=12_000)
scope: Literal["all-apps"]
+ #: Whose memory this is. The App never sends it and writes `local`.
+ user_id: UserId = DEFAULT_USER_ID
@field_validator("text")
@classmethod
@@ -108,7 +112,11 @@ class MemoryAdditionStore:
def save(self, addition: MemoryAddInput) -> EvidenceRecord:
now = datetime.now(UTC)
+ if addition.user_id != DEFAULT_USER_ID and not self.sdk_authority:
+ # Legacy authority keeps one person's library only.
+ raise ValueError("memory_add_user_requires_sdk_authority")
value = EvidenceInput(
+ user_id=addition.user_id,
source_id=SOURCE_ID,
conversation_id=f"note:{addition.request_id}",
message_id=str(addition.request_id),
@@ -200,7 +208,7 @@ class MemoryAdditionStore:
)
return self.require(value.evidence_id)
- def require(self, evidence_id: str) -> EvidenceRecord:
+ def require(self, evidence_id: str, *, user_id: str = DEFAULT_USER_ID) -> EvidenceRecord:
if self.sdk_authority:
if self.write_queue is None:
raise KeyError(evidence_id)
@@ -219,11 +227,11 @@ class MemoryAdditionStore:
(item for item in payload.input_records if item.evidence_id == evidence_id),
None,
)
- if record is None:
+ if record is None or record.user_id != user_id:
raise KeyError(evidence_id)
return record
record = self.evidence.get(evidence_id)
- if record is None or record.user_id != "local" or record.source_id != SOURCE_ID:
+ if record is None or record.user_id != user_id or record.source_id != SOURCE_ID:
raise KeyError(evidence_id)
metadata = record.origin_meta.get(EvidenceOrigin.MANUAL_IMPORT)
if metadata is None or metadata.raw_meta.get("input_mode") != "direct_memory_note":
@@ -237,8 +245,8 @@ class MemoryAdditionStore:
raise ValueError("memory_add_source_revoked")
return record
- def receipt(self, evidence_id: str) -> MemoryAddReceipt:
- record = self.require(evidence_id)
+ def receipt(self, evidence_id: str, *, user_id: str = DEFAULT_USER_ID) -> MemoryAddReceipt:
+ record = self.require(evidence_id, user_id=user_id)
if self.sdk_authority:
assert self.write_queue is not None
with main_database(self.write_queue.database_path).read() as database:
@@ -300,10 +308,15 @@ class MemoryAdditionStore:
error=error,
)
- def receipt_for_request(self, request_id: UUID) -> MemoryAddReceipt:
+ def receipt_for_request(
+ self, request_id: UUID, *, user_id: str = DEFAULT_USER_ID
+ ) -> MemoryAddReceipt:
identity = str(request_id)
if self.sdk_authority:
+ # The Evidence id carries the user, so another user's request id
+ # names a different note and reads as not found.
probe = EvidenceInput(
+ user_id=user_id,
source_id=SOURCE_ID,
conversation_id=f"note:{identity}",
message_id=identity,
@@ -316,16 +329,16 @@ class MemoryAdditionStore:
)
},
)
- return self.receipt(probe.evidence_id)
+ return self.receipt(probe.evidence_id, user_id=user_id)
with main_database(self.evidence.database_path).read() as db:
row = db.execute(
- "SELECT evidence_id FROM evidence WHERE user_id='local' AND source_id=? "
+ "SELECT evidence_id FROM evidence WHERE user_id=? AND source_id=? "
"AND conversation_id=? AND message_id=?",
- (SOURCE_ID, f"note:{identity}", identity),
+ (user_id, SOURCE_ID, f"note:{identity}", identity),
).fetchone()
if row is None:
raise KeyError(identity)
- return self.receipt(str(row[0]))
+ return self.receipt(str(row[0]), user_id=user_id)
def memory_add_router(dependencies: Sequence[Depends]) -> APIRouter:
@@ -376,14 +389,20 @@ def memory_add_router(dependencies: Sequence[Depends]) -> APIRouter:
record = await asyncio.to_thread(additions.save, addition)
except ValueError as error:
raise HTTPException(409, str(error)) from error
- saved = await asyncio.to_thread(additions.receipt, record.evidence_id)
+ saved = await asyncio.to_thread(
+ partial(additions.receipt, record.evidence_id, user_id=addition.user_id)
+ )
background.add_task(schedule, additions, record)
return saved
@router.get("/additions/{request_id}", response_model=MemoryAddReceipt)
- def memory_add_status(request_id: UUID, request: Request) -> MemoryAddReceipt:
+ def memory_add_status(
+ request_id: UUID,
+ request: Request,
+ user_id: str = Query(default=DEFAULT_USER_ID, pattern=USER_ID_PATTERN),
+ ) -> MemoryAddReceipt:
try:
- return store(request).receipt_for_request(request_id)
+ return store(request).receipt_for_request(request_id, user_id=user_id)
except KeyError as error:
raise HTTPException(404, "memory_add_not_found") from error
except ValueError as error:
diff --git a/memhub/apps/core/src/one_memory/memory_server/contracts.py b/memhub/apps/core/src/one_memory/memory_server/contracts.py
index 235cec1..ba3e65b 100644
--- a/memhub/apps/core/src/one_memory/memory_server/contracts.py
+++ b/memhub/apps/core/src/one_memory/memory_server/contracts.py
@@ -75,7 +75,11 @@ def batch_id(*, internal_session_id: str, first_round: int, last_round: int) ->
INTERNAL_SESSION_ID_MAX = 128
-def internal_session_id_for(conversation_id: str, source_id: str) -> str:
+def internal_session_id_for(
+ conversation_id: str,
+ source_id: str,
+ user_id: str = "local",
+) -> str:
"""Normalise a conversation identity to the durable ``internal_session_id``.
This is the single derivation shared by every Evidence-first intake path.
@@ -86,7 +90,17 @@ def internal_session_id_for(conversation_id: str, source_id: str) -> str:
per-session serialisation split). Only a value that the contract would have
rejected before it ever reached the queue is replaced by the versioned
session id, which is deterministic for a given (source, conversation).
+
+ Another user's conversation is always derived with the user in it: two
+ Hermes profiles can hold the same session id, and sharing a session key
+ would serialise and batch one person's turns behind the other's. `local`
+ keeps the identity it always had.
"""
+ if user_id != "local":
+ return session_id(
+ harness_id=source_id,
+ external_session_id=f"user:{user_id}|{conversation_id}",
+ )
if len(conversation_id) <= INTERNAL_SESSION_ID_MAX:
return conversation_id
derived = session_id(harness_id=source_id, external_session_id=conversation_id)
diff --git a/memhub/apps/core/src/one_memory/memory_server/durable_queue.py b/memhub/apps/core/src/one_memory/memory_server/durable_queue.py
index 5d74014..a708060 100644
--- a/memhub/apps/core/src/one_memory/memory_server/durable_queue.py
+++ b/memhub/apps/core/src/one_memory/memory_server/durable_queue.py
@@ -54,6 +54,7 @@ from one_memory.memory_tasks import (
)
from one_memory.sdk_migration_log import error_chain_text
from one_memory.service_levels import ServiceLevel, service_level_context
+from one_memory.user_scope import DEFAULT_USER_ID, lane_key, other_user_lane_prefix
logger = logging.getLogger(__name__)
@@ -345,6 +346,27 @@ EVENT_TIME_WINDOW = timedelta(minutes=10)
DIRECT_WRITE_SOURCES = frozenset({"one-memory-manual"})
+def request_user_id(request: WriteRequest) -> str:
+ """Whose write this is: its frozen input's user, `local` for id-only rows."""
+ users = {record.user_id for record in request.input_records}
+ if len(users) > 1:
+ raise ValueError("durable_write_multiple_users")
+ return next(iter(users), DEFAULT_USER_ID)
+
+
+def request_source_key(request: WriteRequest) -> str:
+ """The FIFO/claim key of a write: its source, per user.
+
+ `local` keeps the bare source id it always had. Another user's Hermes
+ lane is `hermes@user`, so one person's running job never holds the other
+ person's queue and the claim gate answers for that user's grant.
+ """
+ return lane_key(
+ request_user_id(request),
+ request.source_id or request.internal_session_id,
+ )
+
+
@dataclass(frozen=True)
class DurableWriteRecord:
job_id: str
@@ -862,7 +884,7 @@ class DurableWriteQueue:
job_id,
queue_seq,
request.internal_session_id,
- request.source_id or request.internal_session_id,
+ request_source_key(request),
request.batch_identity.batch_id,
key,
payload,
@@ -929,7 +951,9 @@ class DurableWriteQueue:
f"{hashlib.sha256(file_key.encode()).hexdigest()}:"
f"{hashlib.sha256(record.conversation_id.encode()).hexdigest()}"
)
- session_key = internal_session_id_for(record.conversation_id, record.source_id)
+ session_key = internal_session_id_for(
+ record.conversation_id, record.source_id, record.user_id
+ )
written = connection.execute(
"SELECT 1 FROM memory_write_jobs AS job, json_each(job.evidence_ids_json) AS ref "
"WHERE job.session_key=? AND job.state!='assembling' AND ref.value=? LIMIT 1",
@@ -998,7 +1022,7 @@ class DurableWriteQueue:
str(uuid4()),
queue_seq,
session_key,
- record.source_id,
+ lane_key(record.user_id, record.source_id),
assembly_key,
assembly_key,
payload_json,
@@ -1034,10 +1058,13 @@ class DurableWriteQueue:
`flush` (history at end of file) completes the last turn and writes a
short batch; without it (live polling) those stay in the row.
"""
+ # Two users' roots can hold a file with the same relative key (each
+ # Hermes profile has its own `state.db`): only this user's rows.
+ assembly_prefix = f"assembly:{user_id}:{source_id}:"
rows = connection.execute(
"SELECT * FROM memory_write_jobs WHERE state='assembling' "
- "AND source_key=? ORDER BY queue_seq",
- (source_id,),
+ "AND source_key=? AND substr(idempotency_key,1,?)=? ORDER BY queue_seq",
+ (lane_key(user_id, source_id), len(assembly_prefix), assembly_prefix),
).fetchall()
finalized: list[str] = []
for row in rows:
@@ -1160,7 +1187,7 @@ class DurableWriteQueue:
Same records, same key: a re-read returns the job already written.
"""
first = records[0]
- session_id = internal_session_id_for(first.conversation_id, first.source_id)
+ session_id = internal_session_id_for(first.conversation_id, first.source_id, first.user_id)
material = ":".join(f"{item.evidence_id}:{item.content_hash}" for item in records)
request_id = f"turn:v2:{hashlib.sha256(material.encode()).hexdigest()}"
existing = connection.execute(
@@ -1205,7 +1232,7 @@ class DurableWriteQueue:
job_id,
queue_seq,
session_id,
- first.source_id,
+ lane_key(first.user_id, first.source_id),
request.batch_identity.batch_id,
request_id,
json.dumps(
@@ -2494,6 +2521,12 @@ async def execute_job(
source_id = request.internal_session_id
if source_ids and source_ids != {source_id}:
raise RuntimeError("durable_write_multiple_sources")
+ users = {getattr(record, "user_id", DEFAULT_USER_ID) for record in records}
+ if len(users) > 1:
+ raise RuntimeError("durable_write_multiple_users")
+ # The gates answer per user: another user's Hermes job asks about
+ # that user's grant, not `local`'s.
+ source_id = lane_key(next(iter(users), DEFAULT_USER_ID), source_id)
async def mark() -> bool:
return await in_the_background(queue.mark_invoked, job_id, owner=owner)
@@ -2799,6 +2832,19 @@ class DurableWriteDrain:
source_clause = f"AND candidate.source_key IN ({placeholders}) "
source_params = tuple(sorted(enabled_sources))
direct_sources = ",".join("?" for _ in DIRECT_WRITE_SOURCES)
+ # Another user's hand-added memories are `one-memory-manual@user`:
+ # the same lane ahead of history, still serial per user.
+ direct_lanes = " OR ".join(
+ "substr(candidate.source_key,1,?)=?" for _ in DIRECT_WRITE_SOURCES
+ )
+ direct_lane_params = tuple(
+ value
+ for source in sorted(DIRECT_WRITE_SOURCES)
+ for value in (
+ len(other_user_lane_prefix(source)),
+ other_user_lane_prefix(source),
+ )
+ )
# Same eligibility as the window claim below (free lease, no
# running job of its source, nothing earlier in its session), but
# not bound to the window: a note must not wait for history.
@@ -2808,7 +2854,7 @@ class DurableWriteDrain:
"WHERE candidate.state=? "
"AND (candidate.lease_expires_at IS NULL OR candidate.lease_expires_at < ?) "
+ source_clause
- + f"AND candidate.source_key IN ({direct_sources}) "
+ + f"AND (candidate.source_key IN ({direct_sources}) OR {direct_lanes}) "
"AND NOT EXISTS ("
"SELECT 1 FROM memory_write_jobs AS held "
"WHERE held.source_key=candidate.source_key AND held.state=? "
@@ -2826,6 +2872,7 @@ class DurableWriteDrain:
now.isoformat(),
*source_params,
*sorted(DIRECT_WRITE_SOURCES),
+ *direct_lane_params,
RUNNING,
now.isoformat(),
*_FIFO_BLOCKING_STATES,
diff --git a/memhub/apps/core/src/one_memory/memory_server/routes.py b/memhub/apps/core/src/one_memory/memory_server/routes.py
index b2b5cec..169feb3 100644
--- a/memhub/apps/core/src/one_memory/memory_server/routes.py
+++ b/memhub/apps/core/src/one_memory/memory_server/routes.py
@@ -19,10 +19,11 @@ does the writing. That separation is D52.
from __future__ import annotations
+import hashlib
from datetime import UTC, datetime
from typing import Any, Literal, cast
-from fastapi import APIRouter, HTTPException, Request
+from fastapi import APIRouter, HTTPException, Query, Request
from pydantic import BaseModel, ConfigDict, Field
from one_memory.imports.models import (
@@ -43,6 +44,24 @@ from one_memory.memory_server.durable_queue import (
)
from one_memory.memory_server.registry import WriteRegistry, WriteState
from one_memory.memory_server.submit import WriteConflictError
+from one_memory.user_scope import DEFAULT_USER_ID, USER_ID_PATTERN, UserId
+
+#: Durable keys of another user's writes start with this. A `local` request
+#: id never may, so `local` cannot name another user's receipt.
+_USER_KEY_PREFIX = "user:"
+
+
+def durable_request_key(request_id: str, user_id: str) -> str:
+ """The queue key of a caller's request id, namespaced per user.
+
+ Two users choosing the same request id must not collide: the key is the
+ queue's idempotency key and the SDK's `request_id`. `local` keeps its own
+ request id unchanged.
+ """
+ if user_id == DEFAULT_USER_ID:
+ return request_id
+ digest = hashlib.sha256(request_id.encode()).hexdigest()
+ return f"{_USER_KEY_PREFIX}{user_id}:{digest}"
class MemoryWriteReceipt(BaseModel):
@@ -71,6 +90,7 @@ class SdkMemoryWriteInput(BaseModel):
messages: list[OpenAIMessage] = Field(min_length=1, max_length=200)
memory_at: datetime | None = None
priority: Literal["live", "normal"] = "normal"
+ user_id: UserId = DEFAULT_USER_ID
def _registry(
@@ -124,6 +144,9 @@ def sdk_router(dependencies: list[Any] | None = None) -> APIRouter:
) -> MemoryWriteReceipt:
if not any(message.role == "user" for message in payload.messages):
raise HTTPException(422, "messages_require_user_turn")
+ if payload.user_id == DEFAULT_USER_ID and payload.request_id.startswith(_USER_KEY_PREFIX):
+ raise HTTPException(422, "request_id_reserved_prefix")
+ request_key = durable_request_key(payload.request_id, payload.user_id)
observed_at = payload.memory_at or datetime(1970, 1, 1, tzinfo=UTC)
written_by = {
"user": WrittenBy.PERSON,
@@ -133,6 +156,7 @@ def sdk_router(dependencies: list[Any] | None = None) -> APIRouter:
records = tuple(
materialize_write_input(
EvidenceInput(
+ user_id=payload.user_id,
source_id=payload.source_id,
conversation_id=payload.session_id,
message_id=f"{payload.request_id}:{index}",
@@ -157,6 +181,7 @@ def sdk_router(dependencies: list[Any] | None = None) -> APIRouter:
internal_session_id = internal_session_id_for(
payload.session_id,
payload.source_id,
+ payload.user_id,
)
contract = WriteRequest(
internal_session_id=internal_session_id,
@@ -168,7 +193,7 @@ def sdk_router(dependencies: list[Any] | None = None) -> APIRouter:
),
evidence_ids=[record.evidence_id for record in records],
input_records=records,
- idempotency_key=payload.request_id,
+ idempotency_key=request_key,
priority=payload.priority,
event_at=payload.memory_at,
time_quality="exact" if payload.memory_at is not None else "approximate",
@@ -178,7 +203,7 @@ def sdk_router(dependencies: list[Any] | None = None) -> APIRouter:
except (WriteConflictError, ValueError) as error:
raise HTTPException(409, str(error)) from error
return MemoryWriteReceipt(
- request_id=record.request_id,
+ request_id=payload.request_id,
state=record.state,
created_at=record.created_at,
updated_at=record.updated_at,
@@ -186,16 +211,24 @@ def sdk_router(dependencies: list[Any] | None = None) -> APIRouter:
)
@instance.get("/{request_id}", response_model=MemoryWriteReceipt)
- def status(request_id: str, request: Request) -> MemoryWriteReceipt:
+ def status(
+ request_id: str,
+ request: Request,
+ user_id: str = Query(default=DEFAULT_USER_ID, pattern=USER_ID_PATTERN),
+ ) -> MemoryWriteReceipt:
+ # A receipt belongs to the user that submitted it. Another user's key
+ # is namespaced, and `local` may not name a namespaced key directly.
+ if user_id == DEFAULT_USER_ID and request_id.startswith(_USER_KEY_PREFIX):
+ raise HTTPException(404, "unknown request id")
registry = _registry(request, write=False)
try:
- record = registry.get(request_id)
+ record = registry.get(durable_request_key(request_id, user_id))
except DurableQueueSchemaUnavailableError as error:
raise HTTPException(503, str(error)) from error
if record is None:
raise HTTPException(404, "unknown request id")
return MemoryWriteReceipt(
- request_id=record.request_id,
+ request_id=request_id,
state=record.state,
created_at=record.created_at,
updated_at=record.updated_at,
diff --git a/memhub/apps/core/src/one_memory/memory_server/submit.py b/memhub/apps/core/src/one_memory/memory_server/submit.py
index c9e2e6f..c12f425 100644
--- a/memhub/apps/core/src/one_memory/memory_server/submit.py
+++ b/memhub/apps/core/src/one_memory/memory_server/submit.py
@@ -271,7 +271,9 @@ def build_request_from_evidence(
# Keep the exact conversation id when it fits the 128-char contract;
# otherwise derive the versioned session id, so a long branch id does
# not reject the whole history import.
- internal_session_id=internal_session_id_for(seed.conversation_id, seed.source_id),
+ internal_session_id=internal_session_id_for(
+ seed.conversation_id, seed.source_id, seed.user_id
+ ),
first_round=first_round,
last_round=last_round,
evidence_ids=list(ordered),
diff --git a/memhub/apps/core/src/one_memory/memory_server/unified_entry.py b/memhub/apps/core/src/one_memory/memory_server/unified_entry.py
index f0b61c8..98c8ea1 100644
--- a/memhub/apps/core/src/one_memory/memory_server/unified_entry.py
+++ b/memhub/apps/core/src/one_memory/memory_server/unified_entry.py
@@ -28,6 +28,7 @@ from one_memory.memory_server.contracts import (
internal_session_id_for,
)
from one_memory.memory_server.durable_queue import DurableWriteQueue, DurableWriteRecord
+from one_memory.user_scope import lane_key
WritePriority = Literal["live", "normal"]
@@ -74,7 +75,7 @@ class UnifiedWriteIntake:
if priority not in {"live", "normal"}:
raise ValueError("priority must be 'live' or 'normal'")
if self.source_writes_permitted is not None and not self.source_writes_permitted(
- record.source_id
+ lane_key(record.user_id, record.source_id)
):
# Freeze is the product's one Harness processing decision. Refuse
# new intake so a frozen source creates no new durable write row;
@@ -106,7 +107,9 @@ class UnifiedWriteIntake:
last_round: int,
priority: WritePriority,
) -> WriteRequest:
- session_id = internal_session_id_for(record.conversation_id, record.source_id)
+ session_id = internal_session_id_for(
+ record.conversation_id, record.source_id, record.user_id
+ )
event_at, time_quality = _job_time((record,))
request_key = (
f"entry:{record.evidence_id}"
@@ -145,14 +148,14 @@ class UnifiedWriteIntake:
):
raise ValueError("records must belong to one conversation")
if self.source_writes_permitted is not None and not self.source_writes_permitted(
- first.source_id
+ lane_key(first.user_id, first.source_id)
):
raise SourceWriteDisabledError(first.evidence_id)
material = ":".join(
f"{record.evidence_id}:{record.revision}:{record.content_hash}" for record in records
)
request_id = f"turn:v1:{sha256(material.encode()).hexdigest()}"
- session_id = internal_session_id_for(first.conversation_id, first.source_id)
+ session_id = internal_session_id_for(first.conversation_id, first.source_id, first.user_id)
event_at, time_quality = _job_time(records)
durable = self.queue.submit(
WriteRequest(
diff --git a/memhub/apps/core/src/one_memory/recall.py b/memhub/apps/core/src/one_memory/recall.py
index 85bb82b..fa275a4 100644
--- a/memhub/apps/core/src/one_memory/recall.py
+++ b/memhub/apps/core/src/one_memory/recall.py
@@ -22,6 +22,7 @@ from one_memory.semantic_deadline import (
normalize_semantic_hits,
search_within,
)
+from one_memory.user_scope import DEFAULT_USER_ID, UserId
def recall_blend_mode() -> str:
@@ -67,6 +68,8 @@ class RecallRequest(BaseModel):
#: Wall-clock budget for candidate gather + score. Not a substitute for
#: raising the old newest-500 page; it is the third parallel budget.
timeout_ms: int = Field(default=2_000, ge=50, le=30_000)
+ #: Whose memories to recall. Omitted, it is `local`, the App's library.
+ user_id: UserId = DEFAULT_USER_ID
class RecallHit(BaseModel):
diff --git a/memhub/apps/core/src/one_memory/sdk_memory_qa.py b/memhub/apps/core/src/one_memory/sdk_memory_qa.py
index 3bd69dd..2f39645 100644
--- a/memhub/apps/core/src/one_memory/sdk_memory_qa.py
+++ b/memhub/apps/core/src/one_memory/sdk_memory_qa.py
@@ -32,6 +32,7 @@ from one_memory.model_profiles import (
attach_disable_thinking,
)
from one_memory.secrets import SecretStore, SecretStoreUnavailableError
+from one_memory.user_scope import owns
_NO_GROUNDING = "现有记忆不足以回答这个问题。"
_GROUNDING_LIMIT = 6
@@ -117,7 +118,12 @@ class SdkMemoryAnswerer:
if hit.memory_id in seen:
continue
record = await _get_memory(client, hit.memory_id)
- if record is None or record.status != "active" or not record.is_latest:
+ if (
+ record is None
+ or record.status != "active"
+ or not record.is_latest
+ or not owns(record.user_id, user_id)
+ ):
continue
seen.add(record.memory_id)
found.append(_wire_memory(record))
diff --git a/memhub/apps/core/src/one_memory/sdk_memory_runtime.py b/memhub/apps/core/src/one_memory/sdk_memory_runtime.py
index 4e13689..1fe42b9 100644
--- a/memhub/apps/core/src/one_memory/sdk_memory_runtime.py
+++ b/memhub/apps/core/src/one_memory/sdk_memory_runtime.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import asyncio
import logging
import re
-from collections.abc import AsyncIterator
+from collections.abc import AsyncIterator, Callable, Iterable
from contextlib import AsyncExitStack, asynccontextmanager, suppress
from datetime import UTC, datetime, timedelta
from pathlib import Path
@@ -56,8 +56,11 @@ class SdkMemoryRuntime:
write_queue: DurableWriteQueue,
extraction_settings: ExtractionSettingsStore,
data_dir: Path,
+ user_ids: Callable[[], Iterable[str]] = lambda: ("local",),
) -> None:
self.coordinator = coordinator
+ #: Every user whose raw layer is kept to the retention window.
+ self.user_ids = user_ids
self.read_handle = read_handle
self.write_queue = write_queue
self.extraction_settings = extraction_settings
@@ -72,6 +75,12 @@ class SdkMemoryRuntime:
)
async def prune_expired_raw(self, *, now: datetime | None = None) -> int:
+ deleted = 0
+ for user_id in dict.fromkeys(await asyncio.to_thread(lambda: tuple(self.user_ids()))):
+ deleted += await self._prune_expired_raw_for(user_id, now=now)
+ return deleted
+
+ async def _prune_expired_raw_for(self, user_id: str, *, now: datetime | None) -> int:
cutoff = (now or datetime.now(UTC)) - timedelta(days=RAW_RETENTION_DAYS)
cutoff_timestamp = int(cutoff.timestamp())
client = await self.read_handle.client()
@@ -79,7 +88,7 @@ class SdkMemoryRuntime:
while True:
page = await asyncio.to_thread(
client.list_memories,
- user_id="local",
+ user_id=user_id,
layers=["l1_raw"],
statuses=list(_RAW_STATUSES),
order="asc",
@@ -95,8 +104,7 @@ class SdkMemoryRuntime:
for row in rows
if isinstance(row, dict)
and isinstance(row.get("memory_id"), str)
- and int(row.get("memory_at") or row.get("gmt_created") or 0)
- < cutoff_timestamp
+ and int(row.get("memory_at") or row.get("gmt_created") or 0) < cutoff_timestamp
]
if not expired:
return deleted
@@ -154,11 +162,10 @@ class SdkMemoryRuntime:
limit: int = 12,
) -> tuple[tuple[str, float], ...]:
return tuple(
- (hit.memory_id, hit.score)
- for hit in await self.semantic_recall(query, limit=limit)
+ (hit.memory_id, hit.score) for hit in await self.semantic_recall(query, limit=limit)
)
- async def graph_snapshot(self, *, limit: int = 300) -> HyGraphSnapshot:
+ async def graph_snapshot(self, *, limit: int = 300, user_id: str = "local") -> HyGraphSnapshot:
try:
await self.coordinator.active_profile_credentials()
except RuntimeError as error:
@@ -173,7 +180,7 @@ class SdkMemoryRuntime:
return await asyncio.to_thread(
read_graph_snapshot,
client,
- "local",
+ user_id,
"*",
limit,
)
diff --git a/memhub/apps/core/src/one_memory/sdk_migration_runner.py b/memhub/apps/core/src/one_memory/sdk_migration_runner.py
index a98ef46..2dc0263 100644
--- a/memhub/apps/core/src/one_memory/sdk_migration_runner.py
+++ b/memhub/apps/core/src/one_memory/sdk_migration_runner.py
@@ -259,6 +259,7 @@ def prepare_legacy_write_queue_for_cutover(database_path: Path) -> tuple[int, in
internal_session_id = internal_session_id_for(
source.conversation_id,
source.source_id,
+ source.user_id,
)
queue.submit(
WriteRequest(
diff --git a/memhub/apps/core/src/one_memory/strict_query.py b/memhub/apps/core/src/one_memory/strict_query.py
new file mode 100644
index 0000000..7162550
--- /dev/null
+++ b/memhub/apps/core/src/one_memory/strict_query.py
@@ -0,0 +1,39 @@
+"""Refuse query parameters a route does not declare.
+
+FastAPI ignores an unknown query parameter. For a memory read that is a
+silent widening: `memory-library?user_id=__nobody__` against a Core that did
+not know `user_id` answered with the whole library, and the caller believed
+it was isolated. Routes that carry this dependency answer such a request with
+the same 422 a malformed body gets.
+"""
+
+from fastapi import Request
+from fastapi.dependencies.models import Dependant
+from fastapi.exceptions import RequestValidationError
+from fastapi.routing import APIRoute
+
+
+def _declared_query_names(dependant: Dependant) -> set[str]:
+ names = {parameter.alias for parameter in dependant.query_params}
+ for dependency in dependant.dependencies:
+ names |= _declared_query_names(dependency)
+ return names
+
+
+async def forbid_unknown_query_params(request: Request) -> None:
+ route = request.scope.get("route")
+ if not isinstance(route, APIRoute):
+ return
+ unknown = sorted(set(request.query_params) - _declared_query_names(route.dependant))
+ if unknown:
+ raise RequestValidationError(
+ [
+ {
+ "type": "extra_forbidden",
+ "loc": ("query", name),
+ "msg": "Extra inputs are not permitted",
+ "input": None,
+ }
+ for name in unknown
+ ]
+ )
diff --git a/memhub/apps/core/src/one_memory/user_scope.py b/memhub/apps/core/src/one_memory/user_scope.py
new file mode 100644
index 0000000..e33e90f
--- /dev/null
+++ b/memhub/apps/core/src/one_memory/user_scope.py
@@ -0,0 +1,65 @@
+"""Who a memory belongs to: one Runtime, many `user_id`s.
+
+A user is decided by which source root is read (a Hermes profile is its own
+`state.db`), never by session or platform fields. The App never names a user
+and keeps reading and writing `local`; every other harness stays on `local`
+too. Only Hermes may connect a second root for another user.
+
+In memory, a source's import lane is keyed by `lane_key(user_id, source_id)`.
+For `local` that is the bare source id, so every existing key, health record
+and log line stays byte-identical; another user's lane is `source@user`.
+`@` cannot occur in a user id or a source id, so the key splits back exactly.
+"""
+
+import re
+from typing import Annotated
+
+from pydantic import Field
+
+DEFAULT_USER_ID = "local"
+
+#: `:` is excluded on purpose: the SDK joins ids with it when it keys history,
+#: so a user id holding one could read another user's history.
+USER_ID_PATTERN = r"^[A-Za-z0-9._-]{1,64}$"
+_USER_ID = re.compile(USER_ID_PATTERN)
+
+#: The only source whose roots may belong to a user other than `local`.
+MULTI_USER_SOURCES = frozenset({"hermes"})
+
+UserId = Annotated[str, Field(min_length=1, max_length=64, pattern=USER_ID_PATTERN)]
+
+_LANE_SEPARATOR = "@"
+
+
+def valid_user_id(value: str) -> bool:
+ return bool(_USER_ID.fullmatch(value))
+
+
+def lane_key(user_id: str, source_id: str) -> str:
+ if user_id == DEFAULT_USER_ID:
+ return source_id
+ return f"{source_id}{_LANE_SEPARATOR}{user_id}"
+
+
+def other_user_lane_prefix(source_id: str) -> str:
+ """What every other user's lane of `source_id` starts with."""
+ return f"{source_id}{_LANE_SEPARATOR}"
+
+
+def split_lane(key: str) -> tuple[str, str]:
+ """`(user_id, source_id)` of a lane key; a bare source id is `local`'s."""
+ source_id, separator, user_id = key.partition(_LANE_SEPARATOR)
+ if not separator or not valid_user_id(user_id):
+ return DEFAULT_USER_ID, key
+ return user_id, source_id
+
+
+def owns(record_user_id: str | None, user_id: str) -> bool:
+ """Whether a stored memory belongs to `user_id`.
+
+ The SDK's `get`/`update`/`delete`/`history`/`get_write_outcome` take no
+ user, so MemHub checks this before acting on an id. A memory written
+ before MemHub named users carries `local` or nothing; both are `local`'s.
+ """
+ stored = record_user_id or DEFAULT_USER_ID
+ return stored == user_id
diff --git a/memhub/apps/core/tests/TEST_INDEX.md b/memhub/apps/core/tests/TEST_INDEX.md
index 689047b..b29b94a 100644
--- a/memhub/apps/core/tests/TEST_INDEX.md
+++ b/memhub/apps/core/tests/TEST_INDEX.md
@@ -197,6 +197,7 @@
| `test_model_profiles.py` | `contract` | 覆盖 profile uses one model and keeps key out of database、api key updates reuse one stable secret reference、startup cleanup removes only secrets not referenced by current profiles 等 15 个场景。 |
| `test_model_request_audit.py` | `contract` | 覆盖 failure is recorded without error message、missing usage stays unknown in detail and zero in summary、records one physical request with provider usage and no content 等 5 个场景。 |
| `test_model_request_budget.py` | `contract` | 覆盖 persists failed request reservations without content、parallel leases cannot exceed request limit、unknown or excessive output and body are denied 等 6 个场景。 |
+| `test_multi_user_runtime.py` | `contract` | One Runtime, many users: `user_id` on the memory API, per-user Hermes profiles. |
| `test_mysql_lifecycle.py` | `contract` | A1-07: the decisions Runtime makes around the bundled MySQL. |
| `test_mysql_platform.py` | `contract` | A1-07: the machine-facing half of managing the bundled MySQL. |
| `test_obs03_health_probe.py` | `contract` | OBS-03: '/health' answered with the web app instead of a health payload. |
@@ -310,4 +311,4 @@
| `test_workspace_recall.py` | `contract` | Workspace memories were unreachable from every host; these pin the way in. |
| `test_write_queue_lease_renewal.py` | `contract` | Rule 8: a lease must outlive the work it covers, and be renewed while it runs. |
-共 305 个测试文件。
+共 306 个测试文件。
diff --git a/memhub/apps/core/tests/core_test_classification.py b/memhub/apps/core/tests/core_test_classification.py
index d1aa4e1..a441cc5 100644
--- a/memhub/apps/core/tests/core_test_classification.py
+++ b/memhub/apps/core/tests/core_test_classification.py
@@ -14,8 +14,8 @@ from pathlib import Path
import pytest
PRIMARY_MARKERS = ("unit", "contract", "integration", "performance", "live")
-EXPECTED_TEST_FILE_COUNT = 305
-EXPECTED_TEST_FILES_SHA256 = "41962ea0ef2469fb14f65d79deb79566183d025d31c6287e9015384653e403d8"
+EXPECTED_TEST_FILE_COUNT = 306
+EXPECTED_TEST_FILES_SHA256 = "e616dcf9fea288bf15a4445045f7b4278517f3304091c04fffd55be80308d481"
# Pure transformations, validation models, parity checks and state machines.
# This list is intentionally small: uncertain files default to contract.
diff --git a/memhub/apps/core/tests/test_memory_additions.py b/memhub/apps/core/tests/test_memory_additions.py
index b579cc4..11778c4 100644
--- a/memhub/apps/core/tests/test_memory_additions.py
+++ b/memhub/apps/core/tests/test_memory_additions.py
@@ -102,7 +102,7 @@ def test_memory_add_requires_authentication_explicit_scope_and_nonempty_content(
{"text": " \n"},
{"text": "x" * 12_001},
{"scope": "*"},
- {"user_id": "other"},
+ {"user_id": "not:a-user"},
):
assert (
await client.post("/api/v2/memories", json={**base, **change})
diff --git a/memhub/apps/core/tests/test_memory_qa_api.py b/memhub/apps/core/tests/test_memory_qa_api.py
index eeb4565..a168188 100644
--- a/memhub/apps/core/tests/test_memory_qa_api.py
+++ b/memhub/apps/core/tests/test_memory_qa_api.py
@@ -56,7 +56,7 @@ def test_sdk_ask_v2_stream_is_native(tmp_path, monkeypatch) -> None:
)
class Answerer:
- async def answer_stream(self, _question):
+ async def answer_stream(self, _question, *, user_id="local"):
yield {"type": "recall", "memories": (memory,)}
yield {"type": "delta", "text": "你要求真实数据。"}
yield {
diff --git a/memhub/apps/core/tests/test_multi_user_runtime.py b/memhub/apps/core/tests/test_multi_user_runtime.py
new file mode 100644
index 0000000..8060746
--- /dev/null
+++ b/memhub/apps/core/tests/test_multi_user_runtime.py
@@ -0,0 +1,740 @@
+"""One Runtime, many users: `user_id` on the memory API, per-user Hermes profiles.
+
+A user is the root that is read (a Hermes profile's own `state.db`), never a
+session or platform field. The App never names a user and keeps `local`;
+every other harness stays on `local`. These tests drive the production app
+against a user-aware stand-in for the public SDK client, whose `get`,
+`update` and `delete` take no user exactly like hy-memory 2.0.9's.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import sqlite3
+from contextlib import asynccontextmanager
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+from uuid import uuid4
+
+import pytest
+from httpx import ASGITransport, AsyncClient
+from pydantic import SecretStr
+
+from one_memory.api import _sdk_recall_target, create_app
+from one_memory.config import Settings
+from one_memory.imports.access import AuthorizedSourceRoot
+from one_memory.imports.adapters import ScannedEvidence, ScanOptions
+from one_memory.imports.models import (
+ EvidenceInput,
+ EvidenceOrigin,
+ OriginMetadata,
+ WrittenBy,
+ materialize_write_input,
+)
+from one_memory.imports.sources.hermes import HERMES_DESCRIPTOR, create_hermes_adapter
+from one_memory.imports.sources.registry import build_source_catalog
+from one_memory.memory_server.contracts import internal_session_id_for
+from one_memory.memory_server.durable_queue import (
+ DurableWriteDrain,
+ DurableWriteQueue,
+ execute_job,
+)
+from one_memory.sdk_write_processor import SdkWriteProcessor
+from one_memory.secrets import InMemorySecretStore
+from one_memory.user_scope import lane_key, split_lane, valid_user_id
+
+TOKEN = "multi-user-test"
+
+
+class UserAwareSdk:
+ """The public client surface MemHub calls, holding memories per user."""
+
+ def __init__(self) -> None:
+ self.memories: dict[str, dict[str, object]] = {}
+ self.add_calls: list[dict[str, object]] = []
+
+ def _store(self, user_id: str, content: str, *, source: str, session_id: str) -> str:
+ memory_id = f"memory-{len(self.memories) + 1}"
+ self.memories[memory_id] = {
+ "memory_id": memory_id,
+ "content": content,
+ "layer": "l2_fact",
+ "status": "active",
+ "user_id": user_id,
+ "agent_id": "all-apps",
+ "session_id": session_id,
+ "source": source,
+ "tags": [],
+ "gmt_created": 1_790_000_000,
+ }
+ return memory_id
+
+ def add(self, messages, *, user_id, session_id, source, request_id, **_kwargs):
+ self.add_calls.append({"user_id": user_id, "request_id": request_id})
+ text = " ".join(item["content"] for item in messages if item["role"] == "user")
+ memory_id = self._store(user_id, text, source=source, session_id=session_id)
+ return {"success": True, "memory_ids": [memory_id]}
+
+ def add_extracted(self, contents, *, user_id, session_id, source, request_id, **_kwargs):
+ self.add_calls.append({"user_id": user_id, "request_id": request_id})
+ memory_id = self._store(user_id, " ".join(contents), source=source, session_id=session_id)
+ return {"success": True, "memory_ids": [memory_id]}
+
+ def _rows(self, user_ids) -> list[dict[str, object]]:
+ return [dict(row) for row in self.memories.values() if row["user_id"] in user_ids]
+
+ def list_memories(self, *, user_id, scene=None, offset=0, limit=100, **_kwargs):
+ rows = [] if _kwargs.get("layers") == ["l1_raw"] else self._rows({user_id})
+ page = rows[offset : offset + limit]
+ if scene == "all":
+ return {
+ "scene": "all",
+ "memories": [{**row, "scene": "chat", "kind": "chat"} for row in page],
+ "total": len(rows),
+ "totals": {"chat": len(rows), "working": 0, "coding": 0},
+ "errors": {},
+ "limit": limit,
+ "offset": offset,
+ "request_id": "list",
+ "elapsed_ms": 1.0,
+ }
+ return {"vdb": {"memories": page, "total": len(rows), "limit": limit, "offset": offset}}
+
+ def memory_stats(self, *, user_id, statuses=None):
+ return {"total": len(self._rows({user_id})), "request_id": "stats", "elapsed_ms": 1.0}
+
+ def search(self, query, *, user_ids, scene=None, **kwargs):
+ rows = [] if kwargs.get("layers") == ["l1_raw"] else self._rows(set(user_ids))
+ items = [{**row, "scene": "chat", "kind": "chat", "score": 0.9} for row in rows]
+ if scene == "all":
+ return {
+ "request_id": "search",
+ "scene": "all",
+ "memories": items,
+ "lanes": {"chat": len(items), "working": 0, "coding": 0},
+ "errors": {},
+ "elapsed_ms": 1.0,
+ }
+ return {"request_id": "search", "scene": scene or "normal", "memories": items}
+
+ def get(self, memory_id, kind=None, variant=None):
+ row = self.memories.get(memory_id)
+ return None if row is None else {**row, "kind": "chat", "variant": None}
+
+ def update(self, memory_id, content, kind=None, variant=None, task=None):
+ if memory_id not in self.memories:
+ return {"success": False, "error_message": f"memory_id '{memory_id}' not found"}
+ self.memories[memory_id]["content"] = content
+ return {"success": True, "memory_id": memory_id}
+
+ def delete(self, memory_id, kind=None, variant=None):
+ if self.memories.pop(memory_id, None) is None:
+ return {"success": False, "deleted_count": 0}
+ return {"success": True, "deleted_count": 1}
+
+ def get_user_profile(self, *, user_id):
+ return {
+ "request_id": f"profile-{user_id}",
+ "profile": {
+ "memory_id": f"l0-{user_id}",
+ "content": f"name is {user_id}",
+ "layer": "L0_BASIC_INFO",
+ "basic_info": {"name": user_id},
+ },
+ "elapsed_ms": 1.0,
+ }
+
+
+class Handle:
+ def __init__(self, sdk: UserAwareSdk) -> None:
+ self.sdk = sdk
+
+ async def client(self) -> UserAwareSdk:
+ return self.sdk
+
+ async def close(self) -> None:
+ return None
+
+
+class Coordinator:
+ """The production write processor over the stand-in client."""
+
+ def __init__(self, sdk: UserAwareSdk) -> None:
+ self.processor = SdkWriteProcessor(Handle(sdk)) # type: ignore[arg-type]
+
+ async def process_sdk_job(self, records, *, request_id, before_hy_invocation):
+ return await self.processor.process_sdk_job(
+ records, request_id=request_id, before_hy_invocation=before_hy_invocation
+ )
+
+
+async def _never(_job_id: str) -> None:
+ return None
+
+
+async def drain_all(queue: DurableWriteQueue, sdk: UserAwareSdk) -> None:
+ """Claim and run every pending job, ungated, the way the drain would."""
+ drain = DurableWriteDrain(queue, execute=_never, lease=timedelta(seconds=30))
+ while claimed := drain.claim(limit=8):
+ for job_id in claimed:
+ await execute_job(
+ job_id,
+ queue=queue,
+ supervisor=Coordinator(sdk),
+ evidence=None, # type: ignore[arg-type]
+ )
+
+
+def application(tmp_path: Path, *, home: Path | None = None):
+ """The production app; with `home`, imports run over that home's sources."""
+ settings = Settings(
+ data_dir=tmp_path / "data",
+ source_home=home or tmp_path,
+ api_token=SecretStr(TOKEN),
+ imports_enabled=home is not None,
+ automatic_memory_processing=False,
+ live_sync_enabled=False,
+ )
+ return create_app(
+ settings,
+ secret_store=InMemorySecretStore(),
+ source_catalog=(
+ build_source_catalog(home=home, environment={}, platform="darwin")
+ if home is not None
+ else None
+ ),
+ )
+
+
+def client_for(app) -> AsyncClient:
+ return AsyncClient(
+ transport=ASGITransport(app=app),
+ base_url="http://test",
+ headers={"Authorization": f"Bearer {TOKEN}"},
+ )
+
+
+def run_with_sdk(tmp_path, monkeypatch, scenario) -> None:
+ async def main() -> None:
+ app = application(tmp_path)
+ sdk = UserAwareSdk()
+
+ @asynccontextmanager
+ async def write_client():
+ yield sdk
+
+ async with app.router.lifespan_context(app):
+ app.state.sdk_client_handle = Handle(sdk)
+ monkeypatch.setattr(app.state.sdk_write_coordinator, "use_client", write_client)
+ async with client_for(app) as client:
+ await scenario(app, sdk, client)
+
+ asyncio.run(main())
+
+
+def _messages(text: str) -> list[dict[str, str]]:
+ return [{"role": "user", "content": text}, {"role": "assistant", "content": "noted"}]
+
+
+async def _write_both_users(app, sdk, client) -> dict[str, str]:
+ """`local` and `wife` each add one memory and submit one conversation."""
+ receipts = {}
+ for user, word in (("local", "tea"), ("wife", "coffee")):
+ request_id = str(uuid4())
+ body = {"request_id": request_id, "text": f"{user} drinks {word}", "scope": "all-apps"}
+ if user != "local":
+ body["user_id"] = user
+ added = await client.post("/api/v2/memories", json=body)
+ assert added.status_code == 201, added.text
+ receipts[f"add:{user}"] = request_id
+ write = {
+ "request_id": "same-request-id",
+ "session_id": "same-session",
+ "source_id": "one-memory-manual",
+ "messages": _messages(f"{user} walks the {word} route"),
+ }
+ if user != "local":
+ write["user_id"] = user
+ written = await client.post("/api/v2/memory-writes", json=write)
+ assert written.status_code == 202, written.text
+ assert written.json()["request_id"] == "same-request-id"
+ await drain_all(app.state.memory_write_queue, sdk)
+ return receipts
+
+
+def _contents(page: dict) -> set[str]:
+ return {memory["content"] for memory in page["memories"]}
+
+
+def test_each_user_reads_only_their_own_library_search_profile_and_graph(
+ tmp_path, monkeypatch
+) -> None:
+ async def scenario(app, sdk, client):
+ await _write_both_users(app, sdk, client)
+ assert {call["user_id"] for call in sdk.add_calls} == {"local", "wife"}
+ # The same caller request id from two users is two SDK requests.
+ assert len({call["request_id"] for call in sdk.add_calls}) == len(sdk.add_calls) == 4
+
+ local = (await client.get("/api/v2/memory-library")).json()
+ wife = (await client.get("/api/v2/memory-library", params={"user_id": "wife"})).json()
+ assert _contents(local) == {"local drinks tea", "local walks the tea route"}
+ assert _contents(wife) == {"wife drinks coffee", "wife walks the coffee route"}
+ nobody = await client.get("/api/v2/memory-library", params={"user_id": "__nobody__"})
+ assert nobody.status_code == 200 and nobody.json()["memories"] == []
+
+ searched = (
+ await client.get("/api/v2/memory-library", params={"query": "route", "user_id": "wife"})
+ ).json()
+ assert _contents(searched) == {"wife walks the coffee route"}
+
+ context = await client.post(
+ "/api/v2/context/search",
+ json={"query": "drinks", "kinds": ["memory"], "user_id": "wife"},
+ )
+ assert context.status_code == 200, context.text
+ assert {item["content"] for item in context.json()["items"]} == {
+ "wife drinks coffee",
+ "wife walks the coffee route",
+ }
+ local_context = await client.post(
+ "/api/v2/context/search", json={"query": "drinks", "kinds": ["memory"]}
+ )
+ assert all("wife" not in item["content"] for item in local_context.json()["items"])
+
+ profile = (await client.get("/api/v2/user-profile", params={"user_id": "wife"})).json()
+ assert profile["profile"]["basic_info"] == {"name": "wife"}
+ assert (await client.get("/api/v2/user-profile")).json()["profile"]["basic_info"] == {
+ "name": "local"
+ }
+
+ graph = (await client.get("/api/v2/memories/graph", params={"user_id": "wife"})).json()
+ labels = {node["label"] for node in graph["nodes"] if node["node_type"] == "memory"}
+ assert labels == {"wife drinks coffee", "wife walks the coffee route"}
+
+ summary = (await client.get("/api/v2/home-summary", params={"user_id": "wife"})).json()
+ assert summary["memory_count"] == 2
+
+ run_with_sdk(tmp_path, monkeypatch, scenario)
+
+
+def test_another_users_memory_id_answers_404_for_read_update_and_delete(
+ tmp_path, monkeypatch
+) -> None:
+ async def scenario(app, sdk, client):
+ await _write_both_users(app, sdk, client)
+ [wife_memory] = [
+ memory_id
+ for memory_id, row in sdk.memories.items()
+ if row["user_id"] == "wife" and row["content"] == "wife drinks coffee"
+ ]
+ path = f"/api/v2/memories/{wife_memory}"
+
+ assert (await client.get(path)).status_code == 404
+ assert (await client.put(path, json={"content": "stolen"})).status_code == 404
+ assert (await client.delete(path)).status_code == 404
+ assert sdk.memories[wife_memory]["content"] == "wife drinks coffee"
+
+ own = await client.get(path, params={"user_id": "wife"})
+ assert own.status_code == 200 and own.json()["user_id"] == "wife"
+ updated = await client.put(path, json={"content": "wife drinks tea", "user_id": "wife"})
+ assert updated.status_code == 200
+ assert (await client.delete(path, params={"user_id": "wife"})).status_code == 204
+ assert wife_memory not in sdk.memories
+
+ run_with_sdk(tmp_path, monkeypatch, scenario)
+
+
+def test_receipts_belong_to_the_user_that_submitted_them(tmp_path, monkeypatch) -> None:
+ async def scenario(app, sdk, client):
+ receipts = await _write_both_users(app, sdk, client)
+ wife_add = f"/api/v2/memories/additions/{receipts['add:wife']}"
+ assert (await client.get(wife_add)).status_code == 404
+ own = await client.get(wife_add, params={"user_id": "wife"})
+ assert own.status_code == 200 and own.json()["state"] == "ready"
+ local_add = f"/api/v2/memories/additions/{receipts['add:local']}"
+ assert (await client.get(local_add, params={"user_id": "wife"})).status_code == 404
+
+ # Both users used `same-request-id`; each reads only their own receipt.
+ local_write = await client.get("/api/v2/memory-writes/same-request-id")
+ wife_write = await client.get(
+ "/api/v2/memory-writes/same-request-id", params={"user_id": "wife"}
+ )
+ assert local_write.status_code == wife_write.status_code == 200
+ assert local_write.json()["memory_ids"] != wife_write.json()["memory_ids"]
+ assert (
+ await client.get("/api/v2/memory-writes/same-request-id", params={"user_id": "kid"})
+ ).status_code == 404
+ # `local` cannot name another user's namespaced queue key directly.
+ with sqlite3.connect(app.state.settings.data_dir / "one-memory.sqlite3") as db:
+ keys = [row[0] for row in db.execute("SELECT idempotency_key FROM memory_write_jobs")]
+ wife_key = next(key for key in keys if key.startswith("user:wife:"))
+ assert (await client.get(f"/api/v2/memory-writes/{wife_key}")).status_code == 404
+
+ run_with_sdk(tmp_path, monkeypatch, scenario)
+
+
+def test_omitting_user_id_keeps_local_and_recall_and_ask_pass_it_through(
+ tmp_path, monkeypatch
+) -> None:
+ async def scenario(app, sdk, client):
+ await _write_both_users(app, sdk, client)
+ seen: list[str] = []
+ original = sdk.list_memories
+
+ def recording(**kwargs):
+ seen.append(kwargs["user_id"])
+ return original(**kwargs)
+
+ sdk.list_memories = recording # type: ignore[method-assign]
+ # Built at startup over the real handle; rebuilt here over the stand-in.
+ app.state.recall_target = _sdk_recall_target(app, "local")
+ await client.get("/api/v2/memory-library")
+ await client.get("/api/v2/raw")
+ await client.get("/api/v2/home-summary")
+ assert set(seen) == {"local"}
+
+ monkeypatch.setattr(
+ "one_memory.api._recall_model_ready", lambda _app: _true(), raising=True
+ )
+ recalled = await client.post("/api/v1/recall", json={"query": "drinks", "user_id": "wife"})
+ assert recalled.status_code == 200, recalled.text
+ assert {hit["content"] for hit in recalled.json()["hits"]} == {
+ "wife drinks coffee",
+ "wife walks the coffee route",
+ }
+ local = await client.post("/api/v1/recall", json={"query": "drinks"})
+ assert all("wife" not in hit["content"] for hit in local.json()["hits"])
+
+ answered = await client.post(
+ "/api/v2/memories/ask", json={"question": "what does she drink", "user_id": "wife"}
+ )
+ assert answered.status_code == 200, answered.text
+ assert {memory["content"] for memory in answered.json()["memories"]} <= {
+ "wife drinks coffee",
+ "wife walks the coffee route",
+ }
+
+ run_with_sdk(tmp_path, monkeypatch, scenario)
+
+
+async def _true() -> bool:
+ return True
+
+
+ ("method", "path", "kwargs"),
+ [
+ ("get", "/api/v2/memory-library", {"params": {"nobody": "1"}}),
+ ("get", "/api/v2/home-summary", {"params": {"userid": "wife"}}),
+ ("get", "/api/v2/user-profile", {"params": {"user": "wife"}}),
+ ("get", "/api/v2/raw", {"params": {"scope": "x"}}),
+ ("get", "/api/v2/memories/graph", {"params": {"scene": "all"}}),
+ ("get", "/api/v2/memories/some-id", {"params": {"owner": "wife"}}),
+ ("delete", "/api/v2/memories/some-id", {"params": {"owner": "wife"}}),
+ ("get", "/api/v2/memory-writes/some-id", {"params": {"owner": "wife"}}),
+ ("get", f"/api/v2/memories/additions/{uuid4()}", {"params": {"owner": "wife"}}),
+ ("post", "/api/v2/memories/ask", {"json": {"question": "q", "user": "wife"}}),
+ ("post", "/api/v1/recall", {"json": {"query": "q", "user": "wife"}}),
+ ("post", "/api/v1/recall", {"json": {"query": "q"}, "params": {"user_id": "wife"}}),
+ ("post", "/api/v2/context/search", {"json": {"query": "q", "owner": "wife"}}),
+ (
+ "post",
+ "/api/v2/memories",
+ {"json": {"request_id": str(uuid4()), "text": "t", "scope": "all-apps", "u": 1}},
+ ),
+ ("put", "/api/v2/memories/some-id", {"json": {"content": "c", "owner": "wife"}}),
+ ],
+)
+def test_unknown_query_and_body_parameters_answer_422(tmp_path, method, path, kwargs) -> None:
+ async def scenario():
+ app = application(tmp_path)
+ async with app.router.lifespan_context(app), client_for(app) as client:
+ response = await client.request(method.upper(), path, **kwargs)
+ assert response.status_code == 422, response.text
+ assert response.json()["detail"] == "request_validation_failed"
+
+ asyncio.run(scenario())
+
+
[email protected]("bad", ["a:b", "", "x" * 65, "white space", "ü", "a/b"])
+def test_a_malformed_user_id_answers_422(tmp_path, bad) -> None:
+ async def scenario():
+ app = application(tmp_path)
+ async with app.router.lifespan_context(app), client_for(app) as client:
+ responses = [
+ await client.get("/api/v2/memory-library", params={"user_id": bad}),
+ await client.get("/api/v2/user-profile", params={"user_id": bad}),
+ await client.post(
+ "/api/v2/memories",
+ json={
+ "request_id": str(uuid4()),
+ "text": "t",
+ "scope": "all-apps",
+ "user_id": bad,
+ },
+ ),
+ await client.post(
+ "/api/v2/memory-writes",
+ json={
+ "request_id": "r",
+ "session_id": "s",
+ "messages": _messages("hello"),
+ "user_id": bad,
+ },
+ ),
+ await client.post("/api/v1/recall", json={"query": "q", "user_id": bad}),
+ ]
+ assert [response.status_code for response in responses] == [422] * len(responses)
+
+ asyncio.run(scenario())
+
+
+def test_user_ids_and_lanes() -> None:
+ assert valid_user_id("wife") and valid_user_id("A.b_c-9")
+ assert not valid_user_id("a:b") and not valid_user_id("wife\n")
+ assert lane_key("local", "hermes") == "hermes"
+ assert lane_key("wife", "hermes") == "hermes@wife"
+ assert split_lane("hermes@wife") == ("wife", "hermes")
+ assert split_lane("hermes") == ("local", "hermes")
+ # `local` keeps the session identity it always had; another user's never equals it.
+ assert internal_session_id_for("s-1", "hermes") == "s-1"
+ assert internal_session_id_for("s-1", "hermes", "wife") != "s-1"
+ assert internal_session_id_for("s-1", "hermes", "wife") != internal_session_id_for(
+ "s-1", "hermes", "kid"
+ )
+
+
+def _hermes_state_db(root: Path, rows: list[tuple[int, str, str, str]]) -> None:
+ root.mkdir(parents=True, exist_ok=True)
+ connection = sqlite3.connect(root / "state.db")
+ connection.execute(
+ "CREATE TABLE messages (id INTEGER PRIMARY KEY, session_id TEXT, role TEXT,"
+ " content TEXT, timestamp REAL, tool_name TEXT, active INTEGER)"
+ )
+ connection.executemany(
+ "INSERT INTO messages VALUES (?, ?, ?, ?, 1790000000, NULL, 1)",
+ rows,
+ )
+ connection.commit()
+ connection.close()
+
+
+def _hermes_homes(home: Path) -> tuple[Path, Path]:
+ hermes = home / ".hermes"
+ wife = hermes / "profiles" / "wife"
+ # The same Hermes session id in both profiles: identities must not merge.
+ _hermes_state_db(
+ hermes,
+ [(1, "session-1", "user", "I am the husband"), (2, "session-1", "assistant", "hi")],
+ )
+ _hermes_state_db(
+ wife,
+ [(1, "session-1", "user", "I am the wife"), (2, "session-1", "assistant", "hello")],
+ )
+ return hermes, wife
+
+
+def _scan_texts(root: Path, home: Path) -> list[str]:
+ adapter = create_hermes_adapter(
+ AuthorizedSourceRoot.grant(
+ source_id=HERMES_DESCRIPTOR.source_id, root=root, user_confirmed=True, home=home
+ )
+ )
+
+ async def collect() -> list[str]:
+ return [
+ event.evidence.verbatim
+ async for event in adapter.scan(ScanOptions(cursors={}))
+ if isinstance(event, ScannedEvidence)
+ ]
+
+ return asyncio.run(collect())
+
+
+def test_a_hermes_root_scan_never_reads_its_profiles(tmp_path) -> None:
+ hermes, wife = _hermes_homes(tmp_path)
+ (hermes / "profiles" / "wife" / "sessions").mkdir()
+ (hermes / "profiles" / "wife" / "sessions" / "s.jsonl").write_text(
+ json.dumps({"type": "message", "role": "user", "content": "wife's transcript"}) + "\n"
+ )
+
+ assert _scan_texts(hermes, tmp_path) == ["I am the husband", "hi"]
+ assert _scan_texts(wife, tmp_path) == ["I am the wife", "hello", "wife's transcript"]
+
+
+def _jobs(database: Path) -> list[sqlite3.Row]:
+ with sqlite3.connect(database) as db:
+ db.row_factory = sqlite3.Row
+ return db.execute(
+ "SELECT session_key,source_key,idempotency_key,state,payload_json "
+ "FROM memory_write_jobs ORDER BY queue_seq"
+ ).fetchall()
+
+
+def test_two_hermes_grants_each_read_their_own_root_into_separate_batches(tmp_path) -> None:
+ async def scenario():
+ home = tmp_path / "home"
+ _hermes, wife = _hermes_homes(home)
+ app = application(tmp_path, home=home)
+ async with app.router.lifespan_context(app), client_for(app) as client:
+ location = (await client.post("/api/v1/sources/hermes/location")).json()
+ local = await client.post(
+ "/api/v1/sources/connect",
+ json={
+ "source_ids": ["hermes"],
+ "request_id": str(uuid4()),
+ "source_roots": {"hermes": location["root_id"]},
+ "enable_sync": True,
+ },
+ )
+ assert local.status_code == 200, local.text
+ profile = await client.post(
+ "/api/v1/sources/connect",
+ json={
+ "source_ids": ["hermes"],
+ "request_id": str(uuid4()),
+ "user_id": "wife",
+ "root": str(wife),
+ },
+ )
+ assert profile.status_code == 200, profile.text
+ [wife_job] = profile.json()["jobs"]
+ assert wife_job["user_id"] == "wife"
+ jobs = [*local.json()["jobs"], wife_job]
+ for job in jobs:
+ finished = await app.state.import_supervisor.wait(job["job_id"])
+ assert finished.status == "completed", finished
+
+ rows = [row for row in _jobs(app.state.settings.data_dir / "one-memory.sqlite3")]
+ assert rows, "history import wrote no batches"
+ by_user: dict[str, list[str]] = {}
+ for row in rows:
+ records = json.loads(row["payload_json"])["input_records"]
+ users = {record["user_id"] for record in records}
+ assert len(users) == 1, "a batch mixed users"
+ [user] = users
+ by_user.setdefault(user, []).extend(record["verbatim"] for record in records)
+ assert row["source_key"] == lane_key(user, "hermes")
+ assert row["session_key"] == internal_session_id_for("session-1", "hermes", user)
+ assert sorted(by_user["local"]) == ["I am the husband", "hi"]
+ assert sorted(by_user["wife"]) == ["I am the wife", "hello"]
+
+ grants = (await client.get("/api/v1/source-grants")).json()["grants"]
+ assert {(grant["user_id"], grant["source_id"]) for grant in grants} >= {
+ ("local", "hermes"),
+ ("wife", "hermes"),
+ }
+ # The App's view stays `local`'s.
+ listed = (await client.get("/api/v1/import-jobs")).json()
+ assert {job["user_id"] for job in listed} == {"local"}
+ wife_jobs = (await client.get("/api/v1/import-jobs", params={"user_id": "wife"})).json()
+ assert {job["user_id"] for job in wife_jobs} == {"wife"}
+ assert all(
+ item["source_id"] != "hermes@wife"
+ for item in (await client.get("/api/v1/live-sync")).json()
+ )
+
+ revoked = await client.post("/api/v1/sources/hermes/revoke", params={"user_id": "wife"})
+ assert revoked.status_code == 200 and revoked.json()["revoked_at"] is not None
+ local_grant = app.state.source_grant_store.receipt(user_id="local", source_id="hermes")
+ assert local_grant.revoked_at is None
+
+ asyncio.run(scenario())
+
+
+def test_only_hermes_takes_another_user_or_a_custom_root(tmp_path) -> None:
+ async def scenario():
+ home = tmp_path / "home"
+ (home / ".claude" / "projects").mkdir(parents=True)
+ app = application(tmp_path, home=home)
+ async with app.router.lifespan_context(app), client_for(app) as client:
+ for extra in ({"user_id": "wife"}, {"root": str(home / ".claude" / "projects")}):
+ response = await client.post(
+ "/api/v1/sources/connect",
+ json={
+ "source_ids": ["claude-code"],
+ "request_id": str(uuid4()),
+ "source_roots": {},
+ **extra,
+ },
+ )
+ assert response.status_code == 422, response.text
+ assert response.json()["detail"] == "user_id_requires_multi_user_source"
+ revoke = await client.post(
+ "/api/v1/sources/claude-code/revoke", params={"user_id": "wife"}
+ )
+ assert revoke.status_code == 422
+ # Hermes too: another user must name their own root.
+ rootless = await client.post(
+ "/api/v1/sources/connect",
+ json={
+ "source_ids": ["hermes"],
+ "request_id": str(uuid4()),
+ "source_roots": {},
+ "user_id": "wife",
+ },
+ )
+ assert rootless.status_code == 422
+ assert rootless.json()["detail"] == "source_root_required_for_user"
+
+ asyncio.run(scenario())
+
+
+def _record(user_id: str, message_id: str, role: str, text: str):
+ return materialize_write_input(
+ EvidenceInput(
+ user_id=user_id,
+ source_id="hermes",
+ conversation_id="session-1",
+ message_id=message_id,
+ role=role,
+ written_by=WrittenBy.PERSON if role == "user" else WrittenBy.AGENT,
+ created_at=datetime(2026, 10, 1, tzinfo=UTC),
+ verbatim=text,
+ origin_meta={EvidenceOrigin.FILE: OriginMetadata()},
+ )
+ )
+
+
+def test_assembling_rows_and_batches_are_keyed_by_user(tmp_path) -> None:
+ """Two users' `state.db` share a relative file key and a session id.
+
+ Finishing one user's file must neither take nor drop the other user's
+ staged turns, and the batches it writes hold one user each.
+ """
+ path = tmp_path / "one-memory.sqlite3"
+ queue = DurableWriteQueue(path, sdk_authority=True)
+ file_key = "f" * 64
+ from one_memory.database_access import main_database
+
+ with main_database(path).write(row_factory=sqlite3.Row) as connection, connection:
+ for user in ("local", "wife"):
+ for index, role in enumerate(("user", "assistant")):
+ queue.stage_sdk_input(
+ _record(user, f"m{index}", role, f"{user} {role}"),
+ file_key=file_key,
+ priority="normal",
+ connection=connection,
+ )
+ queue.finalize_sdk_file(
+ user_id="local", source_id="hermes", file_key=file_key, connection=connection
+ )
+
+ rows = _jobs(path)
+ pending = [row for row in rows if row["state"] == "pending"]
+ assembling = [row for row in rows if row["state"] == "assembling"]
+ assert [
+ {record["user_id"] for record in json.loads(row["payload_json"])["input_records"]}
+ for row in pending
+ ] == [{"local"}]
+ assert [split_lane(row["source_key"]) for row in assembling] == [("wife", "hermes")]
+ assert pending[0]["session_key"] != assembling[0]["session_key"]
diff --git a/memhub/apps/core/tests/test_policy_api_wiring.py b/memhub/apps/core/tests/test_policy_api_wiring.py
index 23c1e62..5d2af3c 100644
--- a/memhub/apps/core/tests/test_policy_api_wiring.py
+++ b/memhub/apps/core/tests/test_policy_api_wiring.py
@@ -173,12 +173,14 @@ def test_first_import_gate_waits_for_every_selected_history_job() -> None:
jobs = [
SimpleNamespace(
operation="history",
+ user_id="local",
source_id="cursor",
created_at=datetime(2026, 10, 18, tzinfo=UTC),
status="completed",
),
SimpleNamespace(
operation="history",
+ user_id="local",
source_id="codex",
created_at=datetime(2026, 10, 18, tzinfo=UTC),
status="running",
diff --git a/memhub/apps/core/tests/test_recall_raw_fallback.py b/memhub/apps/core/tests/test_recall_raw_fallback.py
index a843bc2..691f63f 100644
--- a/memhub/apps/core/tests/test_recall_raw_fallback.py
+++ b/memhub/apps/core/tests/test_recall_raw_fallback.py
@@ -210,7 +210,7 @@ def test_recall_route_falls_back_and_keeps_the_raw_grant(tmp_path, monkeypatch):
async def no_model(_app):
return False
- async def raw(_app, query, *, limit, sources):
+ async def raw(_app, query, *, limit, sources, user_id="local"):
searched.append(sources)
return (_raw("r1", "上周决定用 Postgres", source="cursor"),)
diff --git a/memhub/apps/core/tests/test_sdk_data_plane_migration.py b/memhub/apps/core/tests/test_sdk_data_plane_migration.py
index 810faa3..d180e2a 100644
--- a/memhub/apps/core/tests/test_sdk_data_plane_migration.py
+++ b/memhub/apps/core/tests/test_sdk_data_plane_migration.py
@@ -1353,7 +1353,7 @@ def test_the_sdk_memory_map_draws_sdk_memories_without_legacy_tables(tmp_path) -
original = app.state.sdk_client_handle
app.state.sdk_client_handle = Handle()
- async def graph_snapshot(*, limit):
+ async def graph_snapshot(*, limit, user_id="local"):
del limit
return HyGraphSnapshot(
nodes=(HyGraphNode(node_id="t1", content="topic", layer="TOPIC"),),
diff --git a/memhub/apps/core/tests/test_v2_authority_and_call_events.py b/memhub/apps/core/tests/test_v2_authority_and_call_events.py
index 942bd85..7b3f1c7 100644
--- a/memhub/apps/core/tests/test_v2_authority_and_call_events.py
+++ b/memhub/apps/core/tests/test_v2_authority_and_call_events.py
@@ -57,10 +57,10 @@ def client_for(app, headers=None):
class Answerer:
- async def answer(self, question):
+ async def answer(self, question, *, user_id="local"):
return SdkMemoryAnswer(answer="真实数据。", memories=(MEMORY,), mode="extractive")
- async def answer_stream(self, question):
+ async def answer_stream(self, question, *, user_id="local"):
yield {"type": "recall", "memories": (MEMORY,)}
yield {
"type": "final",