Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(platform): add expert memory admin viewer (#14032)

Nicholas Tindled4efc6301013
diff --git a/autogpt_platform/backend/backend/api/features/admin/memory_admin_routes.py b/autogpt_platform/backend/backend/api/features/admin/memory_admin_routes.py
index 2591333fe4..d142f922cb 100644
--- a/autogpt_platform/backend/backend/api/features/admin/memory_admin_routes.py
+++ b/autogpt_platform/backend/backend/api/features/admin/memory_admin_routes.py
@@ -22,6 +22,7 @@ from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from redis.exceptions import ResponseError
+from backend.api.features.experts import experts_db
from backend.copilot.dream.job_status import (
JobKind,
JobState,
@@ -33,7 +34,7 @@ from backend.copilot.dream.job_status import (
from backend.copilot.dream.nightly_batch import NightlyBatchResult
from backend.copilot.dream.ratification import RatificationResult
from backend.copilot.dream.schemas import DreamPassResult
-from backend.copilot.graphiti.client import derive_group_id
+from backend.copilot.graphiti.client import derive_memory_group_id
from backend.copilot.graphiti.config import graphiti_config
from backend.copilot.graphiti.falkordb_driver import AutoGPTFalkorDriver
from backend.util.clients import get_scheduler_client
@@ -56,6 +57,7 @@ class MemoryOverview(BaseModel):
"""Counts surfaced in the visualizer's header strip."""
user_id: str
+ expert_id: str | None = None
group_id: str
entities: int
episodes: int
@@ -137,6 +139,7 @@ class GraphEdge(BaseModel):
class GraphResponse(BaseModel):
user_id: str
+ expert_id: str | None = None
group_id: str
nodes: list[GraphNode]
edges: list[GraphEdge]
@@ -184,12 +187,35 @@ def _resolve_user_id(user_id: str, caller_id: str) -> str:
return caller_id if user_id == "me" else user_id
+async def _resolve_memory_scope(
+ user_id: str, expert_id: str | None
+) -> tuple[str, str | None]:
+ """Derive an owned memory group without trusting client group identifiers."""
+
+ if expert_id is None:
+ try:
+ return derive_memory_group_id(user_id), None
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc))
+
+ expert = await experts_db.get_expert(user_id, expert_id, include_workflows=False)
+ if expert is None:
+ raise HTTPException(status_code=404, detail="Expert not found")
+
+ try:
+ return derive_memory_group_id(user_id, expert.id), expert.id
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc))
+
+
def _audit_cross_user_access(
*,
request: Request,
caller_id: str,
target_id: str,
jwt_payload: dict,
+ expert_id: str | None = None,
+ group_id: str | None = None,
) -> None:
"""Log admin reads/writes against another user's memory.
@@ -203,12 +229,51 @@ def _audit_cross_user_access(
caller_email = jwt_payload.get("email") or jwt_payload.get("user_metadata", {}).get(
"email", ""
)
+ memory_scope = f"expert {expert_id!r}" if expert_id is not None else "AutoPilot"
+ if group_id is not None:
+ memory_scope = f"{memory_scope} (group {group_id})"
logger.info(
f"Admin memory access: {caller_id} ({caller_email}) "
- f"acting on user {target_id} for {request.method} {request.url}"
+ f"acting on user {target_id!r}, scope {memory_scope}, "
+ # The URL is repr-escaped too: with path-scoped expert routes the
+ # expert_id is a path segment, so control characters would
+ # otherwise ride into the log line through the URL itself.
+ f"for {request.method} {str(request.url)!r}"
)
+async def _resolve_and_audit_memory_scope(
+ *,
+ request: Request,
+ caller_id: str,
+ target_id: str,
+ jwt_payload: dict,
+ expert_id: str | None = None,
+) -> tuple[str, str | None]:
+ """Resolve an authorized scope while auditing successful and failed attempts."""
+ try:
+ group_id, resolved_expert_id = await _resolve_memory_scope(target_id, expert_id)
+ except Exception:
+ _audit_cross_user_access(
+ request=request,
+ caller_id=caller_id,
+ target_id=target_id,
+ jwt_payload=jwt_payload,
+ expert_id=expert_id,
+ )
+ raise
+
+ _audit_cross_user_access(
+ request=request,
+ caller_id=caller_id,
+ target_id=target_id,
+ jwt_payload=jwt_payload,
+ expert_id=resolved_expert_id,
+ group_id=group_id,
+ )
+ return group_id, resolved_expert_id
+
+
async def _mark_schedule_failed(kind: JobKind, job_id: str, exc: Exception) -> None:
"""Best-effort: flip a just-queued JobStatus to errored when the
scheduler hand-off failed, so a poller doesn't wait on a job that
@@ -281,26 +346,37 @@ async def _count(driver, query: str) -> int:
# ---------------------------------------------------------------------------
# Routes
# ---------------------------------------------------------------------------
+#
+# Memory scope is structural: account (AutoPilot) reads live at
+# ``/{user_id}/...`` and expert reads at
+# ``/{user_id}/experts/{expert_id}/...``. Each pair shares one ``_impl``
+# so the route bodies aren't duplicated. Maintenance POSTs exist only
+# under the account paths — there is deliberately no expert-scoped
+# maintenance route, so a maintenance job can never be aimed at an
+# expert graph by construction.
+
+_USER_ID_PATH = Path(description="User id or 'me'")
+_EXPERT_ID_PATH = Path(
+ min_length=1, max_length=128, description="Expert id owned by the user"
+)
[email protected]("/{user_id}/overview", response_model=MemoryOverview)
-async def get_memory_overview(
+async def _get_memory_overview_impl(
+ *,
request: Request,
- user_id: Annotated[str, Path(description="User id or 'me'")],
- caller_id: Annotated[str, Depends(get_user_id)],
- jwt_payload: Annotated[dict, Security(get_jwt_payload)],
+ user_id: str,
+ caller_id: str,
+ jwt_payload: dict,
+ expert_id: str | None,
) -> MemoryOverview:
target = _resolve_user_id(user_id, caller_id)
- _audit_cross_user_access(
+ group_id, resolved_expert_id = await _resolve_and_audit_memory_scope(
request=request,
caller_id=caller_id,
target_id=target,
jwt_payload=jwt_payload,
+ expert_id=expert_id,
)
- try:
- group_id = derive_group_id(target)
- except ValueError as exc:
- raise HTTPException(status_code=400, detail=str(exc))
driver = _open_driver(group_id)
try:
@@ -318,6 +394,7 @@ async def get_memory_overview(
return MemoryOverview(
user_id=target,
+ expert_id=resolved_expert_id,
group_id=group_id,
entities=entities,
episodes=episodes,
@@ -327,25 +404,61 @@ async def get_memory_overview(
)
[email protected]("/{user_id}/entities", response_model=EntityListResponse)
-async def list_entities(
[email protected]("/{user_id}/overview", response_model=MemoryOverview)
+async def get_memory_overview(
request: Request,
- user_id: Annotated[str, Path(description="User id or 'me'")],
+ user_id: Annotated[str, _USER_ID_PATH],
caller_id: Annotated[str, Depends(get_user_id)],
jwt_payload: Annotated[dict, Security(get_jwt_payload)],
- limit: Annotated[int, Query(ge=1, le=10000)] = 1000,
+) -> MemoryOverview:
+ """Count summary of the user's account (AutoPilot) memory graph."""
+ return await _get_memory_overview_impl(
+ request=request,
+ user_id=user_id,
+ caller_id=caller_id,
+ jwt_payload=jwt_payload,
+ expert_id=None,
+ )
+
+
+ "/{user_id}/experts/{expert_id}/overview",
+ response_model=MemoryOverview,
+)
+async def get_expert_memory_overview(
+ request: Request,
+ user_id: Annotated[str, _USER_ID_PATH],
+ expert_id: Annotated[str, _EXPERT_ID_PATH],
+ caller_id: Annotated[str, Depends(get_user_id)],
+ jwt_payload: Annotated[dict, Security(get_jwt_payload)],
+) -> MemoryOverview:
+ """Count summary of one expert's isolated memory graph."""
+ return await _get_memory_overview_impl(
+ request=request,
+ user_id=user_id,
+ caller_id=caller_id,
+ jwt_payload=jwt_payload,
+ expert_id=expert_id,
+ )
+
+
+async def _list_entities_impl(
+ *,
+ request: Request,
+ user_id: str,
+ caller_id: str,
+ jwt_payload: dict,
+ expert_id: str | None,
+ limit: int,
) -> EntityListResponse:
target = _resolve_user_id(user_id, caller_id)
- _audit_cross_user_access(
+ group_id, _ = await _resolve_and_audit_memory_scope(
request=request,
caller_id=caller_id,
target_id=target,
jwt_payload=jwt_payload,
+ expert_id=expert_id,
)
- try:
- group_id = derive_group_id(target)
- except ValueError as exc:
- raise HTTPException(status_code=400, detail=str(exc))
driver = _open_driver(group_id)
try:
@@ -378,29 +491,67 @@ async def list_entities(
return EntityListResponse(user_id=target, items=items)
[email protected]("/{user_id}/facts", response_model=FactListResponse)
-async def list_facts(
[email protected]("/{user_id}/entities", response_model=EntityListResponse)
+async def list_entities(
request: Request,
- user_id: Annotated[str, Path(description="User id or 'me'")],
+ user_id: Annotated[str, _USER_ID_PATH],
caller_id: Annotated[str, Depends(get_user_id)],
jwt_payload: Annotated[dict, Security(get_jwt_payload)],
limit: Annotated[int, Query(ge=1, le=10000)] = 1000,
- status: Annotated[
- Literal["active", "superseded", "contradicted", "any"], Query()
- ] = "any",
- scope: Annotated[str | None, Query()] = None,
+) -> EntityListResponse:
+ """Entities in the user's account (AutoPilot) memory graph."""
+ return await _list_entities_impl(
+ request=request,
+ user_id=user_id,
+ caller_id=caller_id,
+ jwt_payload=jwt_payload,
+ expert_id=None,
+ limit=limit,
+ )
+
+
+ "/{user_id}/experts/{expert_id}/entities",
+ response_model=EntityListResponse,
+)
+async def list_expert_entities(
+ request: Request,
+ user_id: Annotated[str, _USER_ID_PATH],
+ expert_id: Annotated[str, _EXPERT_ID_PATH],
+ caller_id: Annotated[str, Depends(get_user_id)],
+ jwt_payload: Annotated[dict, Security(get_jwt_payload)],
+ limit: Annotated[int, Query(ge=1, le=10000)] = 1000,
+) -> EntityListResponse:
+ """Entities in one expert's isolated memory graph."""
+ return await _list_entities_impl(
+ request=request,
+ user_id=user_id,
+ caller_id=caller_id,
+ jwt_payload=jwt_payload,
+ expert_id=expert_id,
+ limit=limit,
+ )
+
+
+async def _list_facts_impl(
+ *,
+ request: Request,
+ user_id: str,
+ caller_id: str,
+ jwt_payload: dict,
+ expert_id: str | None,
+ limit: int,
+ status: str,
+ scope: str | None,
) -> FactListResponse:
target = _resolve_user_id(user_id, caller_id)
- _audit_cross_user_access(
+ group_id, _ = await _resolve_and_audit_memory_scope(
request=request,
caller_id=caller_id,
target_id=target,
jwt_payload=jwt_payload,
+ expert_id=expert_id,
)
- try:
- group_id = derive_group_id(target)
- except ValueError as exc:
- raise HTTPException(status_code=400, detail=str(exc))
# Build optional filters
where_clauses = ["e.group_id = $g"]
@@ -460,25 +611,78 @@ async def list_facts(
return FactListResponse(user_id=target, items=items)
[email protected]("/{user_id}/communities", response_model=CommunityListResponse)
-async def list_communities(
+_FACT_STATUS_QUERY = Annotated[
+ Literal["active", "superseded", "contradicted", "any"], Query()
+]
+
+
[email protected]("/{user_id}/facts", response_model=FactListResponse)
+async def list_facts(
request: Request,
- user_id: Annotated[str, Path(description="User id or 'me'")],
+ user_id: Annotated[str, _USER_ID_PATH],
caller_id: Annotated[str, Depends(get_user_id)],
jwt_payload: Annotated[dict, Security(get_jwt_payload)],
- limit: Annotated[int, Query(ge=1, le=2000)] = 500,
+ limit: Annotated[int, Query(ge=1, le=10000)] = 1000,
+ status: _FACT_STATUS_QUERY = "any",
+ scope: Annotated[str | None, Query()] = None,
+) -> FactListResponse:
+ """Facts (RELATES_TO edges) in the user's account (AutoPilot) memory graph."""
+ return await _list_facts_impl(
+ request=request,
+ user_id=user_id,
+ caller_id=caller_id,
+ jwt_payload=jwt_payload,
+ expert_id=None,
+ limit=limit,
+ status=status,
+ scope=scope,
+ )
+
+
+ "/{user_id}/experts/{expert_id}/facts",
+ response_model=FactListResponse,
+)
+async def list_expert_facts(
+ request: Request,
+ user_id: Annotated[str, _USER_ID_PATH],
+ expert_id: Annotated[str, _EXPERT_ID_PATH],
+ caller_id: Annotated[str, Depends(get_user_id)],
+ jwt_payload: Annotated[dict, Security(get_jwt_payload)],
+ limit: Annotated[int, Query(ge=1, le=10000)] = 1000,
+ status: _FACT_STATUS_QUERY = "any",
+ scope: Annotated[str | None, Query()] = None,
+) -> FactListResponse:
+ """Facts (RELATES_TO edges) in one expert's isolated memory graph."""
+ return await _list_facts_impl(
+ request=request,
+ user_id=user_id,
+ caller_id=caller_id,
+ jwt_payload=jwt_payload,
+ expert_id=expert_id,
+ limit=limit,
+ status=status,
+ scope=scope,
+ )
+
+
+async def _list_communities_impl(
+ *,
+ request: Request,
+ user_id: str,
+ caller_id: str,
+ jwt_payload: dict,
+ expert_id: str | None,
+ limit: int,
) -> CommunityListResponse:
target = _resolve_user_id(user_id, caller_id)
- _audit_cross_user_access(
+ group_id, _ = await _resolve_and_audit_memory_scope(
request=request,
caller_id=caller_id,
target_id=target,
jwt_payload=jwt_payload,
+ expert_id=expert_id,
)
- try:
- group_id = derive_group_id(target)
- except ValueError as exc:
- raise HTTPException(status_code=400, detail=str(exc))
driver = _open_driver(group_id)
try:
@@ -519,38 +723,68 @@ async def list_communities(
return CommunityListResponse(user_id=target, items=items)
[email protected]("/{user_id}/graph", response_model=GraphResponse)
-async def get_graph(
[email protected]("/{user_id}/communities", response_model=CommunityListResponse)
+async def list_communities(
request: Request,
- user_id: Annotated[str, Path(description="User id or 'me'")],
+ user_id: Annotated[str, _USER_ID_PATH],
caller_id: Annotated[str, Depends(get_user_id)],
jwt_payload: Annotated[dict, Security(get_jwt_payload)],
- node_limit: Annotated[int, Query(ge=1, le=20000)] = 5000,
- edge_limit: Annotated[int, Query(ge=1, le=50000)] = 10000,
- include_episodes: Annotated[bool, Query()] = False,
- include_communities: Annotated[bool, Query()] = True,
-) -> GraphResponse:
- """Single-shot graph payload for the visualizer canvas.
+ limit: Annotated[int, Query(ge=1, le=2000)] = 500,
+) -> CommunityListResponse:
+ """Communities in the user's account (AutoPilot) memory graph."""
+ return await _list_communities_impl(
+ request=request,
+ user_id=user_id,
+ caller_id=caller_id,
+ jwt_payload=jwt_payload,
+ expert_id=None,
+ limit=limit,
+ )
- Returns nodes + edges in one round-trip so the frontend can hand
- the whole thing to a force-directed layout without N+1 fetches.
- Defaults to entities + communities (the "what does my memory know
- about" view). ``include_episodes=True`` adds the temporal
- :Episodic nodes — useful for debugging extraction but noisy for the
- typical inspector view.
- """
+ "/{user_id}/experts/{expert_id}/communities",
+ response_model=CommunityListResponse,
+)
+async def list_expert_communities(
+ request: Request,
+ user_id: Annotated[str, _USER_ID_PATH],
+ expert_id: Annotated[str, _EXPERT_ID_PATH],
+ caller_id: Annotated[str, Depends(get_user_id)],
+ jwt_payload: Annotated[dict, Security(get_jwt_payload)],
+ limit: Annotated[int, Query(ge=1, le=2000)] = 500,
+) -> CommunityListResponse:
+ """Communities in one expert's isolated memory graph."""
+ return await _list_communities_impl(
+ request=request,
+ user_id=user_id,
+ caller_id=caller_id,
+ jwt_payload=jwt_payload,
+ expert_id=expert_id,
+ limit=limit,
+ )
+
+
+async def _get_graph_impl(
+ *,
+ request: Request,
+ user_id: str,
+ caller_id: str,
+ jwt_payload: dict,
+ expert_id: str | None,
+ node_limit: int,
+ edge_limit: int,
+ include_episodes: bool,
+ include_communities: bool,
+) -> GraphResponse:
target = _resolve_user_id(user_id, caller_id)
- _audit_cross_user_access(
+ group_id, resolved_expert_id = await _resolve_and_audit_memory_scope(
request=request,
caller_id=caller_id,
target_id=target,
jwt_payload=jwt_payload,
+ expert_id=expert_id,
)
- try:
- group_id = derive_group_id(target)
- except ValueError as exc:
- raise HTTPException(status_code=400, detail=str(exc))
# Build the labels-of-interest list for the node queries — one
# Cypher per label so the label can travel through the result row
@@ -674,6 +908,7 @@ async def get_graph(
return GraphResponse(
user_id=target,
+ expert_id=resolved_expert_id,
group_id=group_id,
nodes=nodes,
edges=edges,
@@ -681,6 +916,69 @@ async def get_graph(
)
[email protected]("/{user_id}/graph", response_model=GraphResponse)
+async def get_graph(
+ request: Request,
+ user_id: Annotated[str, _USER_ID_PATH],
+ caller_id: Annotated[str, Depends(get_user_id)],
+ jwt_payload: Annotated[dict, Security(get_jwt_payload)],
+ node_limit: Annotated[int, Query(ge=1, le=20000)] = 5000,
+ edge_limit: Annotated[int, Query(ge=1, le=50000)] = 10000,
+ include_episodes: Annotated[bool, Query()] = False,
+ include_communities: Annotated[bool, Query()] = True,
+) -> GraphResponse:
+ """Single-shot graph payload for the visualizer canvas (account scope).
+
+ Returns nodes + edges in one round-trip so the frontend can hand
+ the whole thing to a force-directed layout without N+1 fetches.
+
+ Defaults to entities + communities (the "what does my memory know
+ about" view). ``include_episodes=True`` adds the temporal
+ :Episodic nodes — useful for debugging extraction but noisy for the
+ typical inspector view.
+ """
+ return await _get_graph_impl(
+ request=request,
+ user_id=user_id,
+ caller_id=caller_id,
+ jwt_payload=jwt_payload,
+ expert_id=None,
+ node_limit=node_limit,
+ edge_limit=edge_limit,
+ include_episodes=include_episodes,
+ include_communities=include_communities,
+ )
+
+
+ "/{user_id}/experts/{expert_id}/graph",
+ response_model=GraphResponse,
+)
+async def get_expert_graph(
+ request: Request,
+ user_id: Annotated[str, _USER_ID_PATH],
+ expert_id: Annotated[str, _EXPERT_ID_PATH],
+ caller_id: Annotated[str, Depends(get_user_id)],
+ jwt_payload: Annotated[dict, Security(get_jwt_payload)],
+ node_limit: Annotated[int, Query(ge=1, le=20000)] = 5000,
+ edge_limit: Annotated[int, Query(ge=1, le=50000)] = 10000,
+ include_episodes: Annotated[bool, Query()] = False,
+ include_communities: Annotated[bool, Query()] = True,
+) -> GraphResponse:
+ """Visualizer graph payload for one expert's isolated memory graph."""
+ return await _get_graph_impl(
+ request=request,
+ user_id=user_id,
+ caller_id=caller_id,
+ jwt_payload=jwt_payload,
+ expert_id=expert_id,
+ node_limit=node_limit,
+ edge_limit=edge_limit,
+ include_episodes=include_episodes,
+ include_communities=include_communities,
+ )
+
+
class JobTriggerResponse(BaseModel):
"""202 response from a fire-and-forget admin trigger.
@@ -736,16 +1034,12 @@ async def trigger_dream_pass(
nightly fan-out use ``POST /{user_id}/nightly``.
"""
target = _resolve_user_id(user_id, caller_id)
- _audit_cross_user_access(
+ await _resolve_and_audit_memory_scope(
request=request,
caller_id=caller_id,
target_id=target,
jwt_payload=jwt_payload,
)
- try:
- derive_group_id(target) # validate before kicking off
- except ValueError as exc:
- raise HTTPException(status_code=400, detail=str(exc))
job_id = str(_uuid.uuid4())
status = await write_initial_status(
@@ -821,16 +1115,12 @@ async def trigger_ratification_pass(
without the full nightly fan-out.
"""
target = _resolve_user_id(user_id, caller_id)
- _audit_cross_user_access(
+ await _resolve_and_audit_memory_scope(
request=request,
caller_id=caller_id,
target_id=target,
jwt_payload=jwt_payload,
)
- try:
- derive_group_id(target)
- except ValueError as exc:
- raise HTTPException(status_code=400, detail=str(exc))
try:
result = await get_scheduler_client().execute_ratification_pass_now(
@@ -868,16 +1158,12 @@ async def trigger_nightly_batch(
for cost-log attribution.
"""
target = _resolve_user_id(user_id, caller_id)
- _audit_cross_user_access(
+ await _resolve_and_audit_memory_scope(
request=request,
caller_id=caller_id,
target_id=target,
jwt_payload=jwt_payload,
)
- try:
- derive_group_id(target)
- except ValueError as exc:
- raise HTTPException(status_code=400, detail=str(exc))
job_id = str(_uuid.uuid4())
status = await write_initial_status(kind="nightly", job_id=job_id, user_id=target)
@@ -966,16 +1252,12 @@ async def rebuild_communities(
"""
_ = force # not yet plumbed through the with_status wrapper
target = _resolve_user_id(user_id, caller_id)
- _audit_cross_user_access(
+ await _resolve_and_audit_memory_scope(
request=request,
caller_id=caller_id,
target_id=target,
jwt_payload=jwt_payload,
)
- try:
- derive_group_id(target)
- except ValueError as exc:
- raise HTTPException(status_code=400, detail=str(exc))
job_id = str(_uuid.uuid4())
status = await write_initial_status(kind="rebuild", job_id=job_id, user_id=target)
diff --git a/autogpt_platform/backend/backend/api/features/admin/memory_admin_routes_test.py b/autogpt_platform/backend/backend/api/features/admin/memory_admin_routes_test.py
index 2659d52b4a..4ca4f61260 100644
--- a/autogpt_platform/backend/backend/api/features/admin/memory_admin_routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/admin/memory_admin_routes_test.py
@@ -1,6 +1,7 @@
"""Tests for the admin memory inspector routes."""
from unittest.mock import AsyncMock, MagicMock, patch
+from urllib.parse import quote
import fastapi
import fastapi.testclient
@@ -8,6 +9,9 @@ import pytest
from autogpt_libs.auth.jwt_utils import get_jwt_payload
from redis.exceptions import ResponseError
+from backend.api.features.experts.models import PROTECTED_SOUL_RULES, Expert
+from backend.copilot.graphiti.client import derive_memory_group_id
+
from .memory_admin_routes import router as memory_admin_router
app = fastapi.FastAPI()
@@ -35,6 +39,28 @@ def _driver_returning(*query_results) -> AsyncMock:
return driver
+def _expert(
+ expert_id: str,
+) -> Expert:
+ return Expert(
+ id=expert_id,
+ name="Memory Expert",
+ avatar_url=None,
+ role="Researcher",
+ tagline=None,
+ bio=None,
+ skills=[],
+ identity="Keep this expert's memory isolated.",
+ voice_preferences="",
+ boundaries="",
+ protected_soul_rules=list(PROTECTED_SOUL_RULES),
+ is_template=False,
+ source_template_id=None,
+ is_archived=False,
+ workflows=[],
+ )
+
+
class TestOverview:
def test_returns_counts_for_all_node_types(self) -> None:
# Returns one row per count query in order: entities, episodes,
@@ -118,6 +144,358 @@ class TestOverview:
driver.close.assert_awaited_once()
+class TestExpertMemoryScope:
+ def test_invalid_autopilot_scope_is_400_before_driver(self) -> None:
+ with (
+ patch(
+ f"{_MOCK_MODULE}.derive_memory_group_id",
+ side_effect=ValueError("invalid memory owner"),
+ ),
+ patch(f"{_MOCK_MODULE}._open_driver") as open_driver,
+ ):
+ resp = client.get("/admin/memory/abc/overview")
+
+ assert resp.status_code == 400
+ assert resp.json() == {"detail": "invalid memory owner"}
+ open_driver.assert_not_called()
+
+ def test_invalid_expert_scope_is_400_before_driver(self) -> None:
+ expert_id = "expert-owned"
+ with (
+ patch(
+ f"{_MOCK_MODULE}.experts_db.get_expert",
+ new=AsyncMock(return_value=_expert(expert_id)),
+ ),
+ patch(
+ f"{_MOCK_MODULE}.derive_memory_group_id",
+ side_effect=ValueError("invalid expert memory scope"),
+ ),
+ patch(f"{_MOCK_MODULE}._open_driver") as open_driver,
+ ):
+ resp = client.get(f"/admin/memory/abc/experts/{expert_id}/graph")
+
+ assert resp.status_code == 400
+ assert resp.json() == {"detail": "invalid expert memory scope"}
+ open_driver.assert_not_called()
+
+ def test_owned_expert_opens_exact_server_derived_group(self) -> None:
+ expert_id = "expert-owned"
+ expected_group = derive_memory_group_id("abc", expert_id)
+ driver = _driver_returning(
+ [{"c": 1}], [{"c": 2}], [{"c": 3}], [{"c": 4}], [{"c": 5}]
+ )
+ with (
+ patch(
+ f"{_MOCK_MODULE}.experts_db.get_expert",
+ new=AsyncMock(return_value=_expert(expert_id)),
+ ) as get_expert,
+ patch(f"{_MOCK_MODULE}._open_driver", return_value=driver) as open_driver,
+ ):
+ resp = client.get(f"/admin/memory/abc/experts/{expert_id}/overview")
+
+ assert resp.status_code == 200
+ assert resp.json()["expert_id"] == expert_id
+ assert resp.json()["group_id"] == expected_group
+ get_expert.assert_awaited_once_with("abc", expert_id, include_workflows=False)
+ open_driver.assert_called_once_with(expected_group)
+
+ def test_owned_expert_graph_uses_expert_group(self) -> None:
+ expert_id = "expert-owned"
+ expected_group = derive_memory_group_id("abc", expert_id)
+ driver = _driver_returning([], [], [])
+ with (
+ patch(
+ f"{_MOCK_MODULE}.experts_db.get_expert",
+ new=AsyncMock(return_value=_expert(expert_id)),
+ ),
+ patch(f"{_MOCK_MODULE}._open_driver", return_value=driver) as open_driver,
+ ):
+ resp = client.get(f"/admin/memory/abc/experts/{expert_id}/graph")
+
+ assert resp.status_code == 200
+ assert resp.json()["expert_id"] == expert_id
+ assert resp.json()["group_id"] == expected_group
+ open_driver.assert_called_once_with(expected_group)
+
+ @pytest.mark.parametrize(
+ "endpoint", ["overview", "graph", "entities", "facts", "communities"]
+ )
+ def test_unowned_expert_is_404_before_driver(self, endpoint: str) -> None:
+ expert_id = "expert-owned-by-another-user"
+ with (
+ patch(
+ f"{_MOCK_MODULE}.experts_db.get_expert",
+ new=AsyncMock(return_value=None),
+ ) as get_expert,
+ patch(f"{_MOCK_MODULE}._open_driver") as open_driver,
+ ):
+ resp = client.get(f"/admin/memory/abc/experts/{expert_id}/{endpoint}")
+
+ assert resp.status_code == 404
+ assert resp.json() == {"detail": "Expert not found"}
+ get_expert.assert_awaited_once_with("abc", expert_id, include_workflows=False)
+ open_driver.assert_not_called()
+
+ @pytest.mark.parametrize("endpoint", ["entities", "facts", "communities"])
+ def test_owned_expert_list_uses_server_derived_group(self, endpoint: str) -> None:
+ expert_id = "expert-owned"
+ expected_group = derive_memory_group_id("abc", expert_id)
+ driver = _driver_returning([])
+ with (
+ patch(
+ f"{_MOCK_MODULE}.experts_db.get_expert",
+ new=AsyncMock(return_value=_expert(expert_id)),
+ ) as get_expert,
+ patch(f"{_MOCK_MODULE}._open_driver", return_value=driver) as open_driver,
+ ):
+ resp = client.get(f"/admin/memory/abc/experts/{expert_id}/{endpoint}")
+
+ assert resp.status_code == 200
+ get_expert.assert_awaited_once_with("abc", expert_id, include_workflows=False)
+ open_driver.assert_called_once_with(expected_group)
+
+ @pytest.mark.parametrize("endpoint", ["entities", "facts", "communities"])
+ def test_list_without_expert_id_remains_autopilot(self, endpoint: str) -> None:
+ driver = _driver_returning([])
+ with (
+ patch(
+ f"{_MOCK_MODULE}.experts_db.get_expert",
+ new=AsyncMock(),
+ ) as get_expert,
+ patch(f"{_MOCK_MODULE}._open_driver", return_value=driver) as open_driver,
+ ):
+ resp = client.get(f"/admin/memory/abc/{endpoint}")
+
+ assert resp.status_code == 200
+ get_expert.assert_not_awaited()
+ open_driver.assert_called_once_with("user_abc")
+
+ @pytest.mark.parametrize(
+ "endpoint", ["overview", "graph", "entities", "facts", "communities"]
+ )
+ def test_overlong_expert_id_is_422_before_lookup_or_driver(
+ self, endpoint: str
+ ) -> None:
+ expert_id = "x" * 129
+ with (
+ patch(
+ f"{_MOCK_MODULE}.experts_db.get_expert",
+ new=AsyncMock(),
+ ) as get_expert,
+ patch(f"{_MOCK_MODULE}._open_driver") as open_driver,
+ ):
+ resp = client.get(f"/admin/memory/abc/experts/{expert_id}/{endpoint}")
+
+ assert resp.status_code == 422
+ get_expert.assert_not_awaited()
+ open_driver.assert_not_called()
+
+ @pytest.mark.parametrize("endpoint", ["overview", "graph"])
+ def test_account_routes_ignore_expert_id_query_param(self, endpoint: str) -> None:
+ """Scope is path-structural now — a stray ``?expert_id=`` on an
+ account route is an unknown query param and must not switch the
+ response to an expert graph."""
+ driver = (
+ _driver_returning(
+ [{"c": 0}], [{"c": 0}], [{"c": 0}], [{"c": 0}], [{"c": 0}]
+ )
+ if endpoint == "overview"
+ else _driver_returning([], [], [])
+ )
+ with (
+ patch(
+ f"{_MOCK_MODULE}.experts_db.get_expert",
+ new=AsyncMock(),
+ ) as get_expert,
+ patch(f"{_MOCK_MODULE}._open_driver", return_value=driver) as open_driver,
+ ):
+ resp = client.get(
+ f"/admin/memory/abc/{endpoint}", params={"expert_id": "expert-owned"}
+ )
+
+ assert resp.status_code == 200
+ assert resp.json()["expert_id"] is None
+ assert resp.json()["group_id"] == "user_abc"
+ get_expert.assert_not_awaited()
+ open_driver.assert_called_once_with("user_abc")
+
+ @pytest.mark.parametrize("endpoint", ["overview", "graph"])
+ def test_raw_group_id_query_cannot_select_memory_scope(self, endpoint: str) -> None:
+ driver = (
+ _driver_returning(
+ [{"c": 0}], [{"c": 0}], [{"c": 0}], [{"c": 0}], [{"c": 0}]
+ )
+ if endpoint == "overview"
+ else _driver_returning([], [], [])
+ )
+ with (
+ patch(
+ f"{_MOCK_MODULE}.experts_db.get_expert",
+ new=AsyncMock(),
+ ) as get_expert,
+ patch(f"{_MOCK_MODULE}._open_driver", return_value=driver) as open_driver,
+ ):
+ resp = client.get(
+ f"/admin/memory/abc/{endpoint}",
+ params={"group_id": "expert_attacker_controlled"},
+ )
+
+ assert resp.status_code == 200
+ assert resp.json()["expert_id"] is None
+ assert resp.json()["group_id"] == "user_abc"
+ get_expert.assert_not_awaited()
+ open_driver.assert_called_once_with("user_abc")
+
+ @pytest.mark.parametrize("endpoint", ["overview", "graph"])
+ def test_max_length_expert_id_reaches_owned_scope_lookup(
+ self, endpoint: str
+ ) -> None:
+ expert_id = "x" * 128
+ driver = (
+ _driver_returning(
+ [{"c": 0}], [{"c": 0}], [{"c": 0}], [{"c": 0}], [{"c": 0}]
+ )
+ if endpoint == "overview"
+ else _driver_returning([], [], [])
+ )
+ with (
+ patch(
+ f"{_MOCK_MODULE}.experts_db.get_expert",
+ new=AsyncMock(return_value=_expert(expert_id)),
+ ) as get_expert,
+ patch(f"{_MOCK_MODULE}._open_driver", return_value=driver),
+ ):
+ resp = client.get(f"/admin/memory/abc/experts/{expert_id}/{endpoint}")
+
+ assert resp.status_code == 200
+ get_expert.assert_awaited_once_with("abc", expert_id, include_workflows=False)
+
+ @pytest.mark.parametrize("endpoint", ["overview", "graph"])
+ def test_failed_cross_user_expert_scope_is_audited(
+ self, mock_jwt_admin, endpoint: str
+ ) -> None:
+ expert_id = "missing-expert"
+ with (
+ patch(
+ f"{_MOCK_MODULE}.experts_db.get_expert",
+ new=AsyncMock(return_value=None),
+ ),
+ patch(f"{_MOCK_MODULE}._open_driver") as open_driver,
+ patch(f"{_MOCK_MODULE}.logger.info") as audit_log,
+ ):
+ resp = client.get(f"/admin/memory/abc/experts/{expert_id}/{endpoint}")
+
+ assert resp.status_code == 404
+ open_driver.assert_not_called()
+ audit_log.assert_called_once()
+ message = audit_log.call_args.args[0]
+ assert mock_jwt_admin["user_id"] in message
+ assert f"scope expert {expert_id!r}" in message
+ assert "group None" not in message
+
+ def test_failed_expert_scope_escapes_control_chars_in_audit(
+ self, mock_jwt_admin
+ ) -> None:
+ expert_id = "missing\nforged-record"
+ with (
+ patch(
+ f"{_MOCK_MODULE}.experts_db.get_expert",
+ new=AsyncMock(return_value=None),
+ ),
+ patch(f"{_MOCK_MODULE}._open_driver") as open_driver,
+ patch(f"{_MOCK_MODULE}.logger.info") as audit_log,
+ ):
+ resp = client.get(
+ f"/admin/memory/abc/experts/{quote(expert_id, safe='')}/overview"
+ )
+
+ assert resp.status_code == 404
+ open_driver.assert_not_called()
+ message = audit_log.call_args.args[0]
+ assert "missing\\nforged-record" in message
+ assert "\n" not in message
+
+ def test_failed_cross_user_autopilot_scope_is_audited(self, mock_jwt_admin) -> None:
+ with (
+ patch(
+ f"{_MOCK_MODULE}.derive_memory_group_id",
+ side_effect=ValueError("invalid memory owner"),
+ ),
+ patch(f"{_MOCK_MODULE}._open_driver") as open_driver,
+ patch(f"{_MOCK_MODULE}.logger.info") as audit_log,
+ ):
+ resp = client.get("/admin/memory/abc/overview")
+
+ assert resp.status_code == 400
+ open_driver.assert_not_called()
+ audit_log.assert_called_once()
+ message = audit_log.call_args.args[0]
+ assert mock_jwt_admin["user_id"] in message
+ assert "scope AutoPilot" in message
+ assert "group None" not in message
+
+ @pytest.mark.parametrize(
+ "endpoint", ["overview", "graph", "entities", "facts", "communities"]
+ )
+ def test_non_admin_expert_request_never_reaches_lookup_or_driver(
+ self, mock_jwt_user, endpoint: str
+ ) -> None:
+ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]
+ with (
+ patch(
+ f"{_MOCK_MODULE}.experts_db.get_expert",
+ new=AsyncMock(),
+ ) as get_expert,
+ patch(f"{_MOCK_MODULE}._open_driver") as open_driver,
+ ):
+ resp = client.get(f"/admin/memory/abc/experts/expert-owned/{endpoint}")
+
+ assert resp.status_code == 403
+ get_expert.assert_not_awaited()
+ open_driver.assert_not_called()
+
+ def test_cross_user_expert_audit_records_resolved_scope(
+ self, mock_jwt_admin
+ ) -> None:
+ expert_id = "expert-owned"
+ expected_group = derive_memory_group_id("abc", expert_id)
+ driver = _driver_returning([], [], [])
+ with (
+ patch(
+ f"{_MOCK_MODULE}.experts_db.get_expert",
+ new=AsyncMock(return_value=_expert(expert_id)),
+ ),
+ patch(f"{_MOCK_MODULE}._open_driver", return_value=driver),
+ patch(f"{_MOCK_MODULE}.logger.info") as audit_log,
+ ):
+ resp = client.get(f"/admin/memory/abc/experts/{expert_id}/graph")
+
+ assert resp.status_code == 200
+ audit_log.assert_called_once()
+ message = audit_log.call_args.args[0]
+ assert mock_jwt_admin["user_id"] in message
+ assert expert_id in message
+ assert expected_group in message
+
+ def test_cross_user_autopilot_audit_records_resolved_scope(
+ self, mock_jwt_admin
+ ) -> None:
+ driver = _driver_returning(
+ [{"c": 0}], [{"c": 0}], [{"c": 0}], [{"c": 0}], [{"c": 0}]
+ )
+ with (
+ patch(f"{_MOCK_MODULE}._open_driver", return_value=driver),
+ patch(f"{_MOCK_MODULE}.logger.info") as audit_log,
+ ):
+ resp = client.get("/admin/memory/abc/overview")
+
+ assert resp.status_code == 200
+ audit_log.assert_called_once()
+ message = audit_log.call_args.args[0]
+ assert mock_jwt_admin["user_id"] in message
+ assert "AutoPilot (group user_abc)" in message
+
+
class TestListEntities:
def test_returns_entity_summaries(self) -> None:
driver = _driver_returning(
@@ -134,6 +512,21 @@ class TestListEntities:
assert items[0]["name"] == "Alice"
assert items[1]["summary"] is None
+ def test_cross_user_audit_includes_autopilot_group(self, mock_jwt_admin) -> None:
+ driver = _driver_returning([])
+ with (
+ patch(f"{_MOCK_MODULE}._open_driver", return_value=driver),
+ patch(f"{_MOCK_MODULE}.logger.info") as audit_log,
+ ):
+ resp = client.get("/admin/memory/abc/entities")
+
+ assert resp.status_code == 200
+ audit_log.assert_called_once()
+ message = audit_log.call_args.args[0]
+ assert mock_jwt_admin["user_id"] in message
+ assert "AutoPilot (group user_abc)" in message
+ assert "group None" not in message
+
def test_limit_above_cap_rejected_with_422(self) -> None:
"""The entities route caps ``limit`` at 10000 via FastAPI Query
validation. Anything beyond gets a 422 — not a 500 from a runaway
@@ -251,11 +644,12 @@ class TestRebuildCommunitiesPolling:
scheduler.schedule_immediate_community_rebuild = AsyncMock(
return_value={"scheduled": True, "job_id": "x", "kind": "rebuild"}
)
- with patch(
- f"{_MOCK_MODULE}.get_scheduler_client", return_value=scheduler
- ), patch(
- f"{_MOCK_MODULE}.write_initial_status",
- new=_make_fake_initial_status("rebuild"),
+ with (
+ patch(f"{_MOCK_MODULE}.get_scheduler_client", return_value=scheduler),
+ patch(
+ f"{_MOCK_MODULE}.write_initial_status",
+ new=_make_fake_initial_status("rebuild"),
+ ),
):
resp = client.post("/admin/memory/abc/communities/rebuild")
assert resp.status_code == 202
@@ -276,13 +670,13 @@ class TestRebuildCommunitiesPolling:
side_effect=RuntimeError("scheduler unreachable")
)
mark_errored = AsyncMock()
- with patch(
- f"{_MOCK_MODULE}.get_scheduler_client", return_value=scheduler
- ), patch(
- f"{_MOCK_MODULE}.write_initial_status",
- new=_make_fake_initial_status("rebuild"),
- ), patch(
- f"{_MOCK_MODULE}.mark_errored", mark_errored
+ with (
+ patch(f"{_MOCK_MODULE}.get_scheduler_client", return_value=scheduler),
+ patch(
+ f"{_MOCK_MODULE}.write_initial_status",
+ new=_make_fake_initial_status("rebuild"),
+ ),
+ patch(f"{_MOCK_MODULE}.mark_errored", mark_errored),
):
resp = client.post("/admin/memory/abc/communities/rebuild")
assert resp.status_code == 500
@@ -293,6 +687,44 @@ class TestRebuildCommunitiesPolling:
assert mark_errored.call_args.kwargs["kind"] == "rebuild"
+class TestNoExpertScopedMaintenance:
+ """Maintenance is account-only by construction.
+
+ The expert scope is structural (``/experts/{expert_id}/...``) and
+ only the five read endpoints exist under it — there is no path at
+ which a maintenance job could be aimed at an expert graph.
+ """
+
+ @pytest.mark.parametrize(
+ "suffix",
+ ["dream", "ratification", "nightly", "communities/rebuild"],
+ )
+ def test_maintenance_posts_do_not_exist_under_expert_scope(
+ self, suffix: str
+ ) -> None:
+ with (
+ patch(f"{_MOCK_MODULE}.get_scheduler_client") as get_scheduler,
+ patch(
+ f"{_MOCK_MODULE}.write_initial_status", new=AsyncMock()
+ ) as write_status,
+ ):
+ resp = client.post(f"/admin/memory/abc/experts/expert-owned/{suffix}")
+
+ assert resp.status_code == 404
+ get_scheduler.assert_not_called()
+ write_status.assert_not_awaited()
+
+ @pytest.mark.parametrize(
+ "endpoint", ["overview", "graph", "entities", "facts", "communities"]
+ )
+ def test_expert_read_paths_reject_post(self, endpoint: str) -> None:
+ with patch(f"{_MOCK_MODULE}.get_scheduler_client") as get_scheduler:
+ resp = client.post(f"/admin/memory/abc/experts/expert-owned/{endpoint}")
+
+ assert resp.status_code == 405
+ get_scheduler.assert_not_called()
+
+
class TestTriggerStatusGetEndpoints:
"""Each trigger has a paired GET that reads the JobStatus row."""
@@ -375,6 +807,7 @@ class TestAdminGating:
"/admin/memory/abc/entities",
"/admin/memory/abc/facts",
"/admin/memory/abc/communities",
+ "/admin/memory/abc/graph",
]:
resp = client.get(path)
assert resp.status_code == 403, path
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
index e10e1ccfda..8905afaa57 100644
--- a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
@@ -472,6 +472,7 @@ async def test_get_expert_scopes_by_owner(
):
template = await _seed_template(name="Maria", preload_listings=[])
hired = await experts_db.hire_expert(test_user.id, template.id, None)
+ assert await experts_db.get_expert(test_user.id, template.id) is None
assert await experts_db.get_expert(other_user.id, hired.expert.id) is None
assert await experts_db.get_expert(test_user.id, hired.expert.id) is not None
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/memory/__tests__/memory-visualizer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/memory/__tests__/memory-visualizer.test.tsx
index 5d23d46097..8a2ee2a5bf 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/memory/__tests__/memory-visualizer.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/memory/__tests__/memory-visualizer.test.tsx
@@ -1,23 +1,42 @@
import { describe, expect, test, vi } from "vitest";
+import { useState } from "react";
import userEvent from "@testing-library/user-event";
-import { http, HttpResponse } from "msw";
+import { delay, http, HttpResponse } from "msw";
+import { useQueryClient } from "@tanstack/react-query";
-import { render, screen, waitFor } from "@/tests/integrations/test-utils";
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@/tests/integrations/test-utils";
import { server } from "@/mocks/mock-server";
+import {
+ getGetV2GetExpertGraphQueryKey,
+ getGetV2GetExpertMemoryOverviewQueryKey,
+ getGetV2GetGraphQueryKey,
+ getGetV2GetMemoryOverviewQueryKey,
+} from "@/app/api/__generated__/endpoints/admin/admin";
import {
getGetV2GetCommunityRebuildStatusMockHandler200,
getGetV2GetCommunityRebuildStatusResponseMock200,
getGetV2GetDreamPassStatusMockHandler200,
getGetV2GetDreamPassStatusResponseMock200,
- getGetV2GetGraphMockHandler200,
getGetV2GetGraphResponseMock200,
- getGetV2GetMemoryOverviewMockHandler200,
getGetV2GetMemoryOverviewResponseMock200,
getPostV2RebuildCommunitiesMockHandler202,
getPostV2RebuildCommunitiesResponseMock202,
getPostV2TriggerDreamPassMockHandler202,
getPostV2TriggerDreamPassResponseMock202,
} from "@/app/api/__generated__/endpoints/admin/admin.msw";
+import { getListExpertsMockHandler200 } from "@/app/api/__generated__/endpoints/experts/experts.msw";
+import type { Expert } from "@/app/api/__generated__/models/expert";
+
+const { toastMock } = vi.hoisted(() => ({ toastMock: vi.fn() }));
+
+vi.mock("@/components/molecules/Toast/use-toast", () => ({
+ useToast: () => ({ toast: toastMock }),
+}));
// react-force-graph-2d uses HTMLCanvas + window APIs and pulls in d3 at
// import time. In the jsdom test env neither exists, so swap it for a
@@ -27,30 +46,704 @@ vi.mock("react-force-graph-2d", () => ({
}));
import { MemoryVisualizer } from "../components/MemoryVisualizer";
+import { useMemoryVisualizer } from "../components/useMemoryVisualizer";
+
+function makeExpert(id: string, name: string, role = "Researcher"): Expert {
+ return {
+ id,
+ name,
+ avatar_url: null,
+ role,
+ tagline: null,
+ bio: null,
+ skills: [],
+ identity: "",
+ voice_preferences: "",
+ boundaries: "",
+ protected_soul_rules: [],
+ is_template: false,
+ source_template_id: null,
+ is_archived: false,
+ workflows: [],
+ };
+}
-function setupBaseHandlers() {
+// Account and expert scopes are separate (path-scoped) endpoints. The
+// generated response mocks randomize ``expert_id`` and the hook's scope
+// tripwire refuses payloads whose echoed expert_id disagrees with the
+// requested scope, so each handler pins the echo for its own scope.
+function setupBaseHandlers(experts: Expert[] = []) {
server.use(
- getGetV2GetMemoryOverviewMockHandler200({
- ...getGetV2GetMemoryOverviewResponseMock200(),
- user_id: "u-1",
- group_id: "g-1",
- entities: 12,
- episodes: 30,
- relates_to_edges: 25,
- mentions_edges: 30,
- communities: 0,
- }),
- getGetV2GetGraphMockHandler200({
- ...getGetV2GetGraphResponseMock200(),
- user_id: "u-1",
- group_id: "g-1",
- nodes: [],
- edges: [],
- truncated: false,
- }),
+ getListExpertsMockHandler200(experts),
+ http.get("*/api/admin/memory/:userId/overview", () =>
+ HttpResponse.json({
+ ...getGetV2GetMemoryOverviewResponseMock200(),
+ expert_id: null,
+ user_id: "u-1",
+ group_id: "g-1",
+ entities: 12,
+ episodes: 30,
+ relates_to_edges: 25,
+ mentions_edges: 30,
+ communities: 0,
+ }),
+ ),
+ http.get("*/api/admin/memory/:userId/graph", () =>
+ HttpResponse.json({
+ ...getGetV2GetGraphResponseMock200(),
+ expert_id: null,
+ user_id: "u-1",
+ group_id: "g-1",
+ nodes: [],
+ edges: [],
+ truncated: false,
+ }),
+ ),
+ http.get(
+ "*/api/admin/memory/:userId/experts/:expertId/overview",
+ ({ params }) =>
+ HttpResponse.json({
+ ...getGetV2GetMemoryOverviewResponseMock200(),
+ expert_id: String(params.expertId),
+ user_id: "u-1",
+ group_id: "g-expert",
+ entities: 3,
+ episodes: 4,
+ relates_to_edges: 2,
+ mentions_edges: 1,
+ communities: 0,
+ }),
+ ),
+ http.get(
+ "*/api/admin/memory/:userId/experts/:expertId/graph",
+ ({ params }) =>
+ HttpResponse.json({
+ ...getGetV2GetGraphResponseMock200(),
+ expert_id: String(params.expertId),
+ user_id: "u-1",
+ group_id: "g-expert",
+ nodes: [],
+ edges: [],
+ truncated: false,
+ }),
+ ),
+ );
+}
+
+function MemoryActionHarness() {
+ const memory = useMemoryVisualizer("expert-ada");
+ return (
+ <>
+ <button type="button" onClick={memory.triggerRebuild}>
+ Rebuild callback
+ </button>
+ <button type="button" onClick={memory.triggerDream}>
+ Dream callback
+ </button>
+ <button type="button" onClick={memory.triggerRatification}>
+ Ratification callback
+ </button>
+ <button type="button" onClick={memory.triggerNightly}>
+ Nightly callback
+ </button>
+ <span data-testid="mutation-states">
+ {[
+ memory.rebuild.isIdle,
+ memory.dream.isIdle,
+ memory.ratification.isIdle,
+ memory.nightly.isIdle,
+ ].join(",")}
+ </span>
+ </>
+ );
+}
+
+function MemoryVisualizerWithRefetch() {
+ const queryClient = useQueryClient();
+ return (
+ <>
+ <MemoryVisualizer />
+ <button type="button" onClick={() => queryClient.invalidateQueries()}>
+ Refetch experts
+ </button>
+ </>
+ );
+}
+
+const PERSISTENT_GRAPH_PARAMS = {
+ include_episodes: true,
+ include_communities: true,
+ node_limit: 10000,
+ edge_limit: 20000,
+};
+
+function MemoryVisualizerWithPersistentGraphCache() {
+ const queryClient = useQueryClient();
+ const [ready, setReady] = useState(false);
+ const [expertCacheInvalidated, setExpertCacheInvalidated] = useState<
+ string | undefined
+ >();
+
+ function loadVisualizer() {
+ queryClient.setQueryDefaults(getGetV2GetGraphQueryKey("me"), {
+ staleTime: Infinity,
+ });
+ queryClient.setQueryDefaults(getGetV2GetMemoryOverviewQueryKey("me"), {
+ staleTime: Infinity,
+ });
+ queryClient.setQueryDefaults(
+ getGetV2GetExpertGraphQueryKey("me", "expert-ada"),
+ { staleTime: Infinity },
+ );
+ queryClient.setQueryDefaults(
+ getGetV2GetExpertMemoryOverviewQueryKey("me", "expert-ada"),
+ { staleTime: Infinity },
+ );
+ setReady(true);
+ }
+
+ function inspectExpertCache() {
+ setExpertCacheInvalidated(
+ [
+ queryClient.getQueryState(
+ getGetV2GetExpertMemoryOverviewQueryKey("me", "expert-ada"),
+ )?.isInvalidated,
+ queryClient.getQueryState(
+ getGetV2GetExpertGraphQueryKey(
+ "me",
+ "expert-ada",
+ PERSISTENT_GRAPH_PARAMS,
+ ),
+ )?.isInvalidated,
+ ].join(","),
+ );
+ }
+
+ if (!ready) {
+ return (
+ <button type="button" onClick={loadVisualizer}>
+ Load persistent graph cache
+ </button>
+ );
+ }
+
+ return (
+ <>
+ <MemoryVisualizer />
+ <button type="button" onClick={inspectExpertCache}>
+ Inspect expert cache
+ </button>
+ <output data-testid="expert-cache-invalidated">
+ {String(expertCacheInvalidated)}
+ </output>
+ </>
);
}
+describe("MemoryVisualizer — memory scope", () => {
+ test("uses the account memory endpoints by default", async () => {
+ setupBaseHandlers();
+ const overviewScopes: Array<string | null> = [];
+ const graphScopes: Array<string | null> = [];
+ server.use(
+ http.get("*/api/admin/memory/:userId/overview", () => {
+ overviewScopes.push(null);
+ return HttpResponse.json({
+ ...getGetV2GetMemoryOverviewResponseMock200(),
+ expert_id: null,
+ entities: 12,
+ });
+ }),
+ http.get("*/api/admin/memory/:userId/graph", () => {
+ graphScopes.push(null);
+ return HttpResponse.json({
+ ...getGetV2GetGraphResponseMock200(),
+ expert_id: null,
+ nodes: [],
+ edges: [],
+ truncated: false,
+ });
+ }),
+ http.get(
+ "*/api/admin/memory/:userId/experts/:expertId/overview",
+ ({ params }) => {
+ overviewScopes.push(String(params.expertId));
+ return HttpResponse.json({
+ ...getGetV2GetMemoryOverviewResponseMock200(),
+ expert_id: String(params.expertId),
+ });
+ },
+ ),
+ http.get(
+ "*/api/admin/memory/:userId/experts/:expertId/graph",
+ ({ params }) => {
+ graphScopes.push(String(params.expertId));
+ return HttpResponse.json({
+ ...getGetV2GetGraphResponseMock200(),
+ expert_id: String(params.expertId),
+ nodes: [],
+ edges: [],
+ truncated: false,
+ });
+ },
+ ),
+ );
+
+ render(<MemoryVisualizer />);
+
+ expect(
+ (await screen.findByRole("combobox", { name: "Memory scope" }))
+ .textContent,
+ ).toContain("AutoPilot");
+ await screen.findByText("12");
+ await waitFor(() => {
+ expect(overviewScopes).toEqual([null]);
+ expect(graphScopes).toEqual([null]);
+ });
+ expect(screen.getByRole("button", { name: /dream pass/i })).toBeDefined();
+ });
+
+ test("selecting an expert scopes reads and hides memory maintenance", async () => {
+ setupBaseHandlers([makeExpert("expert-ada", "Ada")]);
+ const overviewScopes: Array<string | null> = [];
+ const graphScopes: Array<string | null> = [];
+ server.use(
+ http.get(
+ "*/api/admin/memory/:userId/experts/:expertId/overview",
+ ({ params }) => {
+ overviewScopes.push(String(params.expertId));
+ return HttpResponse.json({
+ ...getGetV2GetMemoryOverviewResponseMock200(),
+ expert_id: String(params.expertId),
+ });
+ },
+ ),
+ http.get(
+ "*/api/admin/memory/:userId/experts/:expertId/graph",
+ ({ params }) => {
+ graphScopes.push(String(params.expertId));
+ return HttpResponse.json({
+ ...getGetV2GetGraphResponseMock200(),
+ expert_id: String(params.expertId),
+ nodes: [],
+ edges: [],
+ truncated: false,
+ });
+ },
+ ),
+ );
+
+ render(<MemoryVisualizer />);
+
+ const selector = await screen.findByRole("combobox", {
+ name: "Memory scope",
+ });
+ await waitFor(() => {
+ expect((selector as HTMLButtonElement).disabled).toBe(false);
+ });
+ fireEvent.click(selector);
+ fireEvent.click(
+ await screen.findByRole("option", { name: /Ada — Researcher/ }),
+ );
+
+ expect(
+ await screen.findByText("Expert memory is read-only."),
+ ).toBeDefined();
+ await waitFor(() => {
+ expect(overviewScopes).toContain("expert-ada");
+ expect(graphScopes).toContain("expert-ada");
+ });
+ expect(
+ screen.queryByRole("button", { name: /rebuild communities/i }),
+ ).toBeNull();
+ expect(screen.queryByRole("button", { name: /dream pass/i })).toBeNull();
+ expect(screen.queryByRole("button", { name: /ratification/i })).toBeNull();
+ expect(screen.queryByRole("button", { name: /nightly batch/i })).toBeNull();
+ expect(screen.queryByTestId("dream-result-panel")).toBeNull();
+ expect(
+ screen.getByRole("checkbox", { name: /communities/i }),
+ ).toBeDefined();
+ });
+
+ test("scope switches preserve in-flight AutoPilot job tracking", async () => {
+ setupBaseHandlers([makeExpert("expert-ada", "Ada")]);
+ let dreamRequests = 0;
+ server.use(
+ http.post("*/api/admin/memory/:userId/dream", () => {
+ dreamRequests += 1;
+ return HttpResponse.json(
+ {
+ ...getPostV2TriggerDreamPassResponseMock202(),
+ job_id: "job-dream-switch",
+ state: "queued",
+ },
+ { status: 202 },
+ );
+ }),
+ getGetV2GetDreamPassStatusMockHandler200({
+ ...getGetV2GetDreamPassStatusResponseMock200(),
+ job_id: "job-dream-switch",
+ kind: "dream_pass",
+ state: "running",
+ current_phase: "consolidate",
+ }),
+ );
+ render(<MemoryVisualizer />);
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: /dream pass/i }),
+ );
+ await screen.findByRole("button", { name: /consolidate…/i });
+
+ const selector = screen.getByRole("combobox", { name: "Memory scope" });
+ fireEvent.click(selector);
+ fireEvent.click(
+ await screen.findByRole("option", { name: /Ada — Researcher/ }),
+ );
+ await screen.findByText("Expert memory is read-only.");
+
+ fireEvent.click(selector);
+ fireEvent.click(await screen.findByRole("option", { name: /AutoPilot/i }));
+
+ const activeButton = await screen.findByRole("button", {
+ name: /consolidate…/i,
+ });
+ expect((activeButton as HTMLButtonElement).disabled).toBe(true);
+ expect(dreamRequests).toBe(1);
+ });
+
+ test("expert callbacks stay read-only even when invoked directly", async () => {
+ setupBaseHandlers([makeExpert("expert-ada", "Ada")]);
+ render(<MemoryActionHarness />);
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Rebuild callback" }),
+ );
+ await userEvent.click(
+ screen.getByRole("button", { name: "Dream callback" }),
+ );
+ await userEvent.click(
+ screen.getByRole("button", { name: "Ratification callback" }),
+ );
+ await userEvent.click(
+ screen.getByRole("button", { name: "Nightly callback" }),
+ );
+
+ expect(screen.getByTestId("mutation-states").textContent).toBe(
+ "true,true,true,true",
+ );
+ });
+
+ test("expert-list errors keep AutoPilot memory available", async () => {
+ setupBaseHandlers();
+ server.use(
+ http.get("*/api/experts", () =>
+ HttpResponse.json({ detail: "boom" }, { status: 500 }),
+ ),
+ );
+
+ render(<MemoryVisualizer />);
+
+ await screen.findByText("Failed to load experts.");
+ const selector = screen.getByRole("combobox", { name: "Memory scope" });
+ expect((selector as HTMLButtonElement).disabled).toBe(false);
+ expect(selector.textContent).toContain("AutoPilot");
+ await screen.findByText("12");
+ });
+
+ test("removed experts reset the selected scope to AutoPilot", async () => {
+ let experts = [makeExpert("expert-ada", "Ada")];
+ setupBaseHandlers();
+ server.use(http.get("*/api/experts", () => HttpResponse.json(experts)));
+ render(<MemoryVisualizerWithRefetch />);
+
+ const selector = await screen.findByRole("combobox", {
+ name: "Memory scope",
+ });
+ await waitFor(() =>
+ expect((selector as HTMLButtonElement).disabled).toBe(false),
+ );
+ fireEvent.click(selector);
+ fireEvent.click(
+ await screen.findByRole("option", { name: /Ada — Researcher/ }),
+ );
+ await screen.findByText("Expert memory is read-only.");
+
+ experts = [];
+ await userEvent.click(
+ screen.getByRole("button", { name: "Refetch experts" }),
+ );
+
+ await waitFor(() => expect(selector.textContent).toContain("AutoPilot"));
+ expect(screen.queryByText("Expert memory is read-only.")).toBeNull();
+ expect(toastMock).toHaveBeenCalledWith({
+ title: "Expert no longer available",
+ description: "Showing AutoPilot account memory instead.",
+ });
+ });
+
+ test("expert-list refetch errors keep the selected cached expert", async () => {
+ let expertsRequestFails = false;
+ setupBaseHandlers();
+ server.use(
+ http.get("*/api/experts", () =>
+ expertsRequestFails
+ ? HttpResponse.json({ detail: "boom" }, { status: 500 })
+ : HttpResponse.json([makeExpert("expert-ada", "Ada")]),
+ ),
+ );
+ render(<MemoryVisualizerWithRefetch />);
+
+ const selector = await screen.findByRole("combobox", {
+ name: "Memory scope",
+ });
+ await waitFor(() =>
+ expect((selector as HTMLButtonElement).disabled).toBe(false),
+ );
+ fireEvent.click(selector);
+ fireEvent.click(
+ await screen.findByRole("option", { name: /Ada — Researcher/ }),
+ );
+ await screen.findByText("Expert memory is read-only.");
+ toastMock.mockClear();
+
+ expertsRequestFails = true;
+ await userEvent.click(
+ screen.getByRole("button", { name: "Refetch experts" }),
+ );
+
+ await screen.findByText("Failed to load experts.");
+ expect(selector.textContent).toContain("Ada");
+ expect(screen.getByText("Expert memory is read-only.")).toBeDefined();
+ expect(toastMock).not.toHaveBeenCalled();
+ });
+
+ test("empty and error scope states are announced without blocking AutoPilot", async () => {
+ setupBaseHandlers();
+ render(<MemoryVisualizer />);
+
+ const emptyState = await screen.findByText("No experts for this account.");
+ expect(emptyState.closest('[aria-live="polite"]')).not.toBeNull();
+ expect(
+ (
+ screen.getByRole("combobox", {
+ name: "Memory scope",
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(false);
+ });
+
+ test("announces expert loading separately from an empty roster", async () => {
+ setupBaseHandlers();
+ server.use(
+ http.get("*/api/experts", async () => {
+ await delay(100);
+ return HttpResponse.json([]);
+ }),
+ );
+
+ render(<MemoryVisualizer />);
+
+ expect(screen.getByText("Loading experts…")).toBeDefined();
+ await screen.findByText("No experts for this account.");
+ });
+
+ test("only appends IDs when expert name and role labels collide", async () => {
+ setupBaseHandlers([
+ makeExpert("ada-one-1234", "Ada", "Researcher"),
+ makeExpert("ada-two-5678", "Ada", "Writer"),
+ makeExpert("ada-three-9012", "Ada", "Researcher"),
+ ]);
+
+ render(<MemoryVisualizer />);
+
+ const selector = await screen.findByRole("combobox", {
+ name: "Memory scope",
+ });
+ await waitFor(() =>
+ expect((selector as HTMLButtonElement).disabled).toBe(false),
+ );
+ fireEvent.click(selector);
+
+ expect(
+ await screen.findByRole("option", {
+ name: "Ada — Researcher (ada-one-1234)",
+ }),
+ ).toBeDefined();
+ expect(
+ screen.getByRole("option", { name: "Ada — Researcher (ada-three-9012)" }),
+ ).toBeDefined();
+ expect(screen.getByRole("option", { name: "Ada — Writer" })).toBeDefined();
+ });
+
+ test("switching scope swaps the rendered graph content, not just the request", async () => {
+ setupBaseHandlers([makeExpert("expert-ada", "Ada")]);
+ server.use(
+ http.get("*/api/admin/memory/:userId/graph", () =>
+ HttpResponse.json({
+ ...getGetV2GetGraphResponseMock200(),
+ expert_id: null,
+ nodes: [
+ {
+ uuid: "n-auto-1",
+ label: "Entity",
+ type: "AutoPilotFact",
+ name: "Account node",
+ },
+ ],
+ edges: [],
+ truncated: false,
+ }),
+ ),
+ http.get(
+ "*/api/admin/memory/:userId/experts/:expertId/graph",
+ ({ params }) =>
+ HttpResponse.json({
+ ...getGetV2GetGraphResponseMock200(),
+ expert_id: String(params.expertId),
+ nodes: [
+ {
+ uuid: "n-expert-1",
+ label: "Entity",
+ type: "ExpertInsight",
+ name: "Expert node",
+ },
+ ],
+ edges: [],
+ truncated: false,
+ }),
+ ),
+ );
+
+ render(<MemoryVisualizer />);
+
+ // Account scope renders the account graph's node-type pill.
+ await screen.findByRole("button", { name: "AutoPilotFact (1)" });
+
+ const selector = screen.getByRole("combobox", { name: "Memory scope" });
+ await waitFor(() =>
+ expect((selector as HTMLButtonElement).disabled).toBe(false),
+ );
+ fireEvent.click(selector);
+ fireEvent.click(
+ await screen.findByRole("option", { name: /Ada — Researcher/ }),
+ );
+
+ // Expert scope renders the expert graph's pill and drops the
+ // account one — proves the displayed data actually swapped.
+ await screen.findByRole("button", { name: "ExpertInsight (1)" });
+ expect(
+ screen.queryByRole("button", { name: "AutoPilotFact (1)" }),
+ ).toBeNull();
+
+ fireEvent.click(selector);
+ fireEvent.click(await screen.findByRole("option", { name: /AutoPilot/i }));
+
+ await screen.findByRole("button", { name: "AutoPilotFact (1)" });
+ expect(
+ screen.queryByRole("button", { name: "ExpertInsight (1)" }),
+ ).toBeNull();
+ });
+
+ test("account job status text hides while an expert scope is selected", async () => {
+ setupBaseHandlers([makeExpert("expert-ada", "Ada")]);
+ server.use(
+ getPostV2TriggerDreamPassMockHandler202({
+ ...getPostV2TriggerDreamPassResponseMock202(),
+ job_id: "job-dream-hidden",
+ state: "queued",
+ }),
+ getGetV2GetDreamPassStatusMockHandler200({
+ ...getGetV2GetDreamPassStatusResponseMock200(),
+ job_id: "job-dream-hidden",
+ kind: "dream_pass",
+ state: "running",
+ current_phase: "consolidate",
+ }),
+ );
+ render(<MemoryVisualizer />);
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: /dream pass/i }),
+ );
+ await screen.findByText("dream: running (consolidate)");
+
+ const selector = screen.getByRole("combobox", { name: "Memory scope" });
+ fireEvent.click(selector);
+ fireEvent.click(
+ await screen.findByRole("option", { name: /Ada — Researcher/ }),
+ );
+ await screen.findByText("Expert memory is read-only.");
+
+ // The account job keeps polling, but its status must not bleed
+ // into the expert-scoped (read-only) control bar.
+ expect(screen.queryByText("dream: running (consolidate)")).toBeNull();
+
+ fireEvent.click(selector);
+ fireEvent.click(await screen.findByRole("option", { name: /AutoPilot/i }));
+
+ await screen.findByText("dream: running (consolidate)");
+ });
+
+ test("responses scoped to a different expert are rejected, not rendered", async () => {
+ setupBaseHandlers([makeExpert("expert-ada", "Ada")]);
+ toastMock.mockClear();
+ server.use(
+ // Malfunctioning server: the expert endpoints return account-
+ // scoped payloads (expert_id echo of null) instead of the
+ // requested expert's data.
+ http.get("*/api/admin/memory/:userId/experts/:expertId/overview", () =>
+ HttpResponse.json({
+ ...getGetV2GetMemoryOverviewResponseMock200(),
+ expert_id: null,
+ entities: 999,
+ episodes: 1,
+ relates_to_edges: 1,
+ mentions_edges: 1,
+ communities: 1,
+ }),
+ ),
+ http.get("*/api/admin/memory/:userId/experts/:expertId/graph", () =>
+ HttpResponse.json({
+ ...getGetV2GetGraphResponseMock200(),
+ expert_id: null,
+ nodes: [],
+ edges: [],
+ truncated: false,
+ }),
+ ),
+ );
+
+ render(<MemoryVisualizer />);
+
+ // Account scope renders normally from the base handlers.
+ await screen.findByText("12");
+
+ const selector = screen.getByRole("combobox", { name: "Memory scope" });
+ await waitFor(() =>
+ expect((selector as HTMLButtonElement).disabled).toBe(false),
+ );
+ fireEvent.click(selector);
+ fireEvent.click(
+ await screen.findByRole("option", { name: /Ada — Researcher/ }),
+ );
+
+ // Expert scope now receives account-scoped payloads → tripwire.
+ await waitFor(() => {
+ expect(toastMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "Memory scope mismatch",
+ variant: "destructive",
+ }),
+ );
+ });
+ expect(screen.queryByText("999")).toBeNull();
+ expect(screen.getAllByText(/Memory scope mismatch/).length).toBeGreaterThan(
+ 0,
+ );
+ });
+});
+
describe("MemoryVisualizer — 202 + polling contract", () => {
test("renders rebuild and dream buttons + the overview chip", async () => {
setupBaseHandlers();
@@ -118,6 +811,111 @@ describe("MemoryVisualizer — 202 + polling contract", () => {
});
});
+ test("job completion refreshes every AutoPilot cache without invalidating expert memory", async () => {
+ setupBaseHandlers([makeExpert("expert-ada", "Ada")]);
+ const graphRequests = new Map<string, number>();
+ server.use(
+ http.get("*/api/admin/memory/:userId/graph", ({ request }) => {
+ const url = new URL(request.url);
+ const requestKey = [
+ "autopilot",
+ url.searchParams.get("include_episodes"),
+ url.searchParams.get("include_communities"),
+ ].join(":");
+ graphRequests.set(requestKey, (graphRequests.get(requestKey) ?? 0) + 1);
+ return HttpResponse.json({
+ ...getGetV2GetGraphResponseMock200(),
+ expert_id: null,
+ nodes: [],
+ edges: [],
+ truncated: false,
+ });
+ }),
+ http.get(
+ "*/api/admin/memory/:userId/experts/:expertId/graph",
+ ({ request, params }) => {
+ const url = new URL(request.url);
+ const requestKey = [
+ String(params.expertId),
+ url.searchParams.get("include_episodes"),
+ url.searchParams.get("include_communities"),
+ ].join(":");
+ graphRequests.set(
+ requestKey,
+ (graphRequests.get(requestKey) ?? 0) + 1,
+ );
+ return HttpResponse.json({
+ ...getGetV2GetGraphResponseMock200(),
+ expert_id: String(params.expertId),
+ nodes: [],
+ edges: [],
+ truncated: false,
+ });
+ },
+ ),
+ getPostV2TriggerDreamPassMockHandler202({
+ ...getPostV2TriggerDreamPassResponseMock202(),
+ job_id: "job-dream-cache",
+ state: "queued",
+ }),
+ getGetV2GetDreamPassStatusMockHandler200({
+ ...getGetV2GetDreamPassStatusResponseMock200(),
+ job_id: "job-dream-cache",
+ kind: "dream_pass",
+ state: "complete",
+ }),
+ );
+ render(<MemoryVisualizerWithPersistentGraphCache />);
+ await userEvent.click(
+ screen.getByRole("button", { name: "Load persistent graph cache" }),
+ );
+
+ await waitFor(() =>
+ expect(graphRequests.get("autopilot:false:true")).toBe(1),
+ );
+ const episodes = await screen.findByRole("checkbox", {
+ name: /episodes/i,
+ });
+ await userEvent.click(episodes);
+ await waitFor(() =>
+ expect(graphRequests.get("autopilot:true:true")).toBe(1),
+ );
+
+ const selector = screen.getByRole("combobox", { name: "Memory scope" });
+ await waitFor(() =>
+ expect((selector as HTMLButtonElement).disabled).toBe(false),
+ );
+ fireEvent.click(selector);
+ fireEvent.click(
+ await screen.findByRole("option", { name: /Ada — Researcher/ }),
+ );
+ await waitFor(() =>
+ expect(graphRequests.get("expert-ada:true:true")).toBe(1),
+ );
+
+ fireEvent.click(selector);
+ fireEvent.click(await screen.findByRole("option", { name: /AutoPilot/i }));
+ await userEvent.click(episodes);
+ await userEvent.click(
+ await screen.findByRole("button", { name: /dream pass/i }),
+ );
+
+ await waitFor(() =>
+ expect(graphRequests.get("autopilot:false:true")).toBe(2),
+ );
+ await userEvent.click(
+ screen.getByRole("button", { name: "Inspect expert cache" }),
+ );
+ expect(screen.getByTestId("expert-cache-invalidated").textContent).toBe(
+ "false,false",
+ );
+
+ await userEvent.click(episodes);
+ await waitFor(() =>
+ expect(graphRequests.get("autopilot:true:true")).toBe(2),
+ );
+ });
+
test("status-endpoint 500 stops polling + reactivates the dream button", async () => {
setupBaseHandlers();
server.use(
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/memory/components/MaintenanceControls.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/memory/components/MaintenanceControls.tsx
new file mode 100644
index 0000000000..b1b28d3ece
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/memory/components/MaintenanceControls.tsx
@@ -0,0 +1,132 @@
+"use client";
+
+import type { AnyJobStatus } from "./memoryJobStatus";
+
+interface Props {
+ onRebuild: () => void;
+ rebuildActive: boolean;
+ rebuildStatus: AnyJobStatus | undefined;
+ force: boolean;
+ setForce: (value: boolean) => void;
+ onDream: () => void;
+ dreamActive: boolean;
+ dreamStatus: AnyJobStatus | undefined;
+ onRatification: () => void;
+ ratificationPending: boolean;
+ onNightly: () => void;
+ nightlyActive: boolean;
+ nightlyStatus: AnyJobStatus | undefined;
+}
+
+export function MaintenanceControls({
+ onRebuild,
+ rebuildActive,
+ rebuildStatus,
+ force,
+ setForce,
+ onDream,
+ dreamActive,
+ dreamStatus,
+ onRatification,
+ ratificationPending,
+ onNightly,
+ nightlyActive,
+ nightlyStatus,
+}: Props) {
+ return (
+ <>
+ <RebuildControl
+ onRebuild={onRebuild}
+ active={rebuildActive}
+ status={rebuildStatus}
+ force={force}
+ setForce={setForce}
+ />
+ <span className="mx-2 h-5 border-l border-gray-200" />
+ <button
+ type="button"
+ onClick={onDream}
+ disabled={dreamActive}
+ className="rounded-md bg-purple-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-purple-700 disabled:opacity-50"
+ title="Run ONLY the dream pass (consolidate → recombine → sanitize) — skips community rebuild and ratification."
+ >
+ {dreamActive ? jobButtonLabel(dreamStatus, "Dreaming…") : "Dream pass"}
+ </button>
+ <button
+ type="button"
+ onClick={onRatification}
+ disabled={ratificationPending}
+ className="rounded-md bg-teal-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-teal-700 disabled:opacity-50"
+ title="Run ONLY the ratification supersession sweep — promotes hit tentatives, supersedes unratified ones past their grace period."
+ >
+ {ratificationPending ? "Ratifying…" : "Ratification"}
+ </button>
+ <button
+ type="button"
+ onClick={onNightly}
+ disabled={nightlyActive}
+ className="rounded-md bg-indigo-700 px-3 py-1.5 text-sm font-medium text-white hover:bg-indigo-800 disabled:opacity-50"
+ title="Run the FULL nightly batch — what the 03:00 cron does. Fans out dream pass + ratification sweep (+ future P2/P3/P4/P11 stages) in one pass."
+ >
+ {nightlyActive
+ ? jobButtonLabel(nightlyStatus, "Running nightly…")
+ : "Nightly batch"}
+ </button>
+ <span className="mx-2 h-5 border-l border-gray-200" />
+ </>
+ );
+}
+
+type RebuildControlProps = Pick<Props, "onRebuild" | "force" | "setForce"> & {
+ active: boolean;
+ status: AnyJobStatus | undefined;
+};
+
+function RebuildControl({
+ onRebuild,
+ active,
+ status,
+ force,
+ setForce,
+}: RebuildControlProps) {
+ return (
+ <>
+ <button
+ type="button"
+ onClick={onRebuild}
+ disabled={active}
+ className="rounded-md bg-blue-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
+ >
+ {active ? jobButtonLabel(status, "Rebuilding…") : "Rebuild communities"}
+ </button>
+ <label className="flex items-center gap-2 text-gray-700">
+ <input
+ type="checkbox"
+ checked={force}
+ onChange={(event) => setForce(event.target.checked)}
+ />
+ Force
+ </label>
+ </>
+ );
+}
+
+function jobButtonLabel(
+ status: AnyJobStatus | undefined,
+ fallback: string,
+): string {
+ if (!status) return fallback;
+ if (status.state === "submitted") {
+ return status.current_phase
+ ? `Batch submitted (${status.current_phase})…`
+ : "Batch submitted…";
+ }
+ if (status.current_phase) {
+ return `${capitalize(status.current_phase)}…`;
+ }
+ return fallback;
+}
+
+function capitalize(value: string): string {
+ return value.charAt(0).toUpperCase() + value.slice(1);
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/memory/components/MemoryScopeSelector.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/memory/components/MemoryScopeSelector.tsx
new file mode 100644
index 0000000000..3d707ac80d
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/memory/components/MemoryScopeSelector.tsx
@@ -0,0 +1,67 @@
+"use client";
+
+import type { Expert } from "@/app/api/__generated__/models/expert";
+import { Select } from "@/components/atoms/Select/Select";
+import { AUTOPILOT_MEMORY_SCOPE } from "./useMemoryScope";
+
+interface Props {
+ value: string;
+ onValueChange: (value: string) => void;
+ experts: Expert[];
+ loading: boolean;
+ error: unknown;
+}
+
+export function MemoryScopeSelector({
+ value,
+ onValueChange,
+ experts,
+ loading,
+ error,
+}: Props) {
+ const labelCounts = experts.reduce<Record<string, number>>(
+ (counts, expert) => {
+ const label = `${expert.name} — ${expert.role.trim() || "Expert"}`;
+ counts[label] = (counts[label] ?? 0) + 1;
+ return counts;
+ },
+ {},
+ );
+ const options = [
+ { value: AUTOPILOT_MEMORY_SCOPE, label: "AutoPilot (account memory)" },
+ ...experts.map((expert) => {
+ const label = `${expert.name} — ${expert.role.trim() || "Expert"}`;
+ return {
+ value: expert.id,
+ label:
+ (labelCounts[label] ?? 0) > 1 ? `${label} (${expert.id})` : label,
+ };
+ }),
+ ];
+
+ return (
+ <div className="flex flex-col gap-2 rounded-md border bg-white p-3 sm:flex-row sm:items-end sm:justify-between">
+ <div className="w-full sm:max-w-sm">
+ <Select
+ id="memory-scope"
+ label="Memory scope"
+ value={value}
+ onValueChange={onValueChange}
+ options={options}
+ size="small"
+ disabled={loading}
+ />
+ </div>
+ <div aria-live="polite" className="flex flex-col gap-1 text-xs">
+ {loading ? <p className="text-gray-500">Loading experts…</p> : null}
+ {value !== AUTOPILOT_MEMORY_SCOPE ? (
+ <p className="text-gray-500">Expert memory is read-only.</p>
+ ) : null}
+ {error ? <p className="text-red-700">Failed to load experts.</p> : null}
+ {!loading && !error && experts.length === 0 ? (
+ <p className="text-gray-500">No experts for this account.</p>
+ ) : null}
+ </div>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/memory/components/MemoryVisualizer.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/memory/components/MemoryVisualizer.tsx
index b2db19c362..09f005b50f 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/memory/components/MemoryVisualizer.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/memory/components/MemoryVisualizer.tsx
@@ -1,28 +1,50 @@
"use client";
-import { useMemo, useState } from "react";
-import type { CommunityRebuildJobStatus } from "@/app/api/__generated__/models/communityRebuildJobStatus";
-import type { DreamJobStatus } from "@/app/api/__generated__/models/dreamJobStatus";
-import type { NightlyJobStatus } from "@/app/api/__generated__/models/nightlyJobStatus";
+import { useEffect, useMemo, useState } from "react";
import { GraphCanvas } from "./GraphCanvas";
import { useMemoryVisualizer } from "./useMemoryVisualizer";
import { DreamOperationsView } from "./DreamOperationsView/DreamOperationsView";
import { DreamUsageSummary } from "./DreamUsageSummary/DreamUsageSummary";
-
-// Polling envelope shared across all three job kinds — see the matching
-// alias in useMemoryVisualizer.ts. Narrowed to a specific kind at the
-// view layer that reads ``status.result``.
-type AnyJobStatus =
- | DreamJobStatus
- | NightlyJobStatus
- | CommunityRebuildJobStatus;
+import { MemoryScopeSelector } from "./MemoryScopeSelector";
+import { MaintenanceControls } from "./MaintenanceControls";
+import { useMemoryScope } from "./useMemoryScope";
+import type { AnyJobStatus } from "./memoryJobStatus";
export function MemoryVisualizer() {
+ const {
+ selectedScope,
+ setSelectedScope,
+ selectedExpertID,
+ experts,
+ expertsLoading,
+ expertsError,
+ } = useMemoryScope();
+
+ return (
+ <div className="space-y-4">
+ <MemoryScopeSelector
+ value={selectedScope}
+ onValueChange={setSelectedScope}
+ experts={experts}
+ loading={expertsLoading}
+ error={expertsError}
+ />
+ <MemoryScopeView expertID={selectedExpertID} />
+ </div>
+ );
+}
+
+interface MemoryScopeViewProps {
+ expertID?: string;
+}
+
+function MemoryScopeView({ expertID }: MemoryScopeViewProps) {
const {
overview,
overviewData,
graph,
graphData,
+ scopeMismatchError,
triggerRebuild,
triggerDream,
ratification,
@@ -40,7 +62,8 @@ export function MemoryVisualizer() {
activeDreamJobId,
activeNightlyJobId,
activeRebuildJobId,
- } = useMemoryVisualizer();
+ readOnly,
+ } = useMemoryVisualizer(expertID);
// Per-label / per-relationship visibility toggles. Selected via a Set
// of "hidden" entries — empty set = show everything.
@@ -52,6 +75,12 @@ export function MemoryVisualizer() {
);
const [selectedUuid, setSelectedUuid] = useState<string | null>(null);
+ useEffect(() => {
+ setHiddenNodeTypes(new Set());
+ setHiddenEdgeTypes(new Set());
+ setSelectedUuid(null);
+ }, [expertID]);
+
const nodes = graphData?.nodes ?? [];
const edges = graphData?.edges ?? [];
const truncated = graphData?.truncated ?? false;
@@ -91,11 +120,12 @@ export function MemoryVisualizer() {
<div className="space-y-4">
<OverviewStrip
loading={overview.isLoading}
- error={overview.error}
+ error={overview.error ?? scopeMismatchError}
data={overviewData}
/>
<ControlBar
+ readOnly={readOnly}
onRebuild={triggerRebuild}
rebuildActiveJobId={activeRebuildJobId}
rebuildStatus={rebuildStatusData}
@@ -118,7 +148,7 @@ export function MemoryVisualizer() {
edgeCount={edges.length}
/>
- <DreamResultPanel status={dreamStatusData} />
+ {readOnly ? null : <DreamResultPanel status={dreamStatusData} />}
<div className="grid grid-cols-12 gap-4">
<Sidebar
@@ -134,9 +164,9 @@ export function MemoryVisualizer() {
<div className="flex h-[70vh] items-center justify-center text-sm text-gray-500">
Loading graph…
</div>
- ) : graph.error ? (
+ ) : graph.error || scopeMismatchError ? (
<div className="p-6 text-sm text-red-700">
- Failed to load graph: {String(graph.error)}
+ Failed to load graph: {String(graph.error ?? scopeMismatchError)}
</div>
) : nodes.length === 0 ? (
<div className="flex h-[70vh] flex-col items-center justify-center text-sm text-gray-500">
@@ -221,6 +251,7 @@ function OverviewStrip({ loading, error, data }: OverviewStripProps) {
}
interface ControlBarProps {
+ readOnly: boolean;
onRebuild: () => void;
rebuildActiveJobId: string | undefined;
rebuildStatus: AnyJobStatus | undefined;
@@ -244,6 +275,7 @@ interface ControlBarProps {
}
function ControlBar({
+ readOnly,
onRebuild,
rebuildActiveJobId,
rebuildStatus,
@@ -270,55 +302,27 @@ function ControlBar({
const nightlyActive = !!nightlyActiveJobId;
return (
<div className="flex flex-wrap items-center gap-3 rounded-md border bg-white p-3 text-sm">
- <button
- type="button"
- onClick={onRebuild}
- disabled={rebuildActive}
- className="rounded-md bg-blue-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
- >
- {rebuildActive
- ? jobButtonLabel(rebuildStatus, "Rebuilding…")
- : "Rebuild communities"}
- </button>
- <label className="flex items-center gap-2 text-gray-700">
- <input
- type="checkbox"
- checked={force}
- onChange={(e) => setForce(e.target.checked)}
+ {readOnly ? (
+ <span className="rounded bg-gray-100 px-2 py-1 text-xs text-gray-600">
+ Read-only
+ </span>
+ ) : (
+ <MaintenanceControls
+ onRebuild={onRebuild}
+ rebuildActive={rebuildActive}
+ rebuildStatus={rebuildStatus}
+ force={force}
+ setForce={setForce}
+ onDream={onDream}
+ dreamActive={dreamActive}
+ dreamStatus={dreamStatus}
+ onRatification={onRatification}
+ ratificationPending={ratificationPending}
+ onNightly={onNightly}
+ nightlyActive={nightlyActive}
+ nightlyStatus={nightlyStatus}
/>
- Force
- </label>
- <span className="mx-2 h-5 border-l border-gray-200" />
- <button
- type="button"
- onClick={onDream}
- disabled={dreamActive}
- className="rounded-md bg-purple-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-purple-700 disabled:opacity-50"
- title="Run ONLY the dream pass (consolidate → recombine → sanitize) — skips community rebuild and ratification."
- >
- {dreamActive ? jobButtonLabel(dreamStatus, "Dreaming…") : "Dream pass"}
- </button>
- <button
- type="button"
- onClick={onRatification}
- disabled={ratificationPending}
- className="rounded-md bg-teal-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-teal-700 disabled:opacity-50"
- title="Run ONLY the ratification supersession sweep — promotes hit tentatives, supersedes unratified ones past their grace period."
- >
- {ratificationPending ? "Ratifying…" : "Ratification"}
- </button>
- <button
- type="button"
- onClick={onNightly}
- disabled={nightlyActive}
- className="rounded-md bg-indigo-700 px-3 py-1.5 text-sm font-medium text-white hover:bg-indigo-800 disabled:opacity-50"
- title="Run the FULL nightly batch — what the 03:00 cron does. Fans out dream pass + ratification sweep (+ future P2/P3/P4/P11 stages) in one pass."
- >
- {nightlyActive
- ? jobButtonLabel(nightlyStatus, "Running nightly…")
- : "Nightly batch"}
- </button>
- <span className="mx-2 h-5 border-l border-gray-200" />
+ )}
<label className="flex items-center gap-2 text-gray-700">
<input
type="checkbox"
@@ -342,15 +346,15 @@ function ControlBar({
truncated
</span>
)}
- {rebuildActive && rebuildStatus && (
+ {!readOnly && rebuildActive && rebuildStatus && (
<span className="ml-2">
rebuild: {jobStateSummary(rebuildStatus)}
</span>
)}
- {dreamActive && dreamStatus && (
+ {!readOnly && dreamActive && dreamStatus && (
<span className="ml-2">dream: {jobStateSummary(dreamStatus)}</span>
)}
- {nightlyActive && nightlyStatus && (
+ {!readOnly && nightlyActive && nightlyStatus && (
<span className="ml-2">
nightly: {jobStateSummary(nightlyStatus)}
</span>
@@ -360,22 +364,6 @@ function ControlBar({
);
}
-function jobButtonLabel(
- status: AnyJobStatus | undefined,
- fallback: string,
-): string {
- if (!status) return fallback;
- if (status.state === "submitted") {
- return status.current_phase
- ? `Batch submitted (${status.current_phase})…`
- : "Batch submitted…";
- }
- if (status.current_phase) {
- return `${capitalize(status.current_phase)}…`;
- }
- return fallback;
-}
-
function jobStateSummary(status: AnyJobStatus): string {
if (status.state === "running" && status.current_phase) {
return `${status.state} (${status.current_phase})`;
@@ -388,10 +376,6 @@ function jobStateSummary(status: AnyJobStatus): string {
return status.state;
}
-function capitalize(s: string): string {
- return s.charAt(0).toUpperCase() + s.slice(1);
-}
-
interface SidebarProps {
nodeTypeCounts: Map<string, number>;
edgeTypeCounts: Map<string, number>;
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/memory/components/memoryJobStatus.ts b/autogpt_platform/frontend/src/app/(platform)/admin/memory/components/memoryJobStatus.ts
new file mode 100644
index 0000000000..6af05b8b0e
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/memory/components/memoryJobStatus.ts
@@ -0,0 +1,8 @@
+import type { CommunityRebuildJobStatus } from "@/app/api/__generated__/models/communityRebuildJobStatus";
+import type { DreamJobStatus } from "@/app/api/__generated__/models/dreamJobStatus";
+import type { NightlyJobStatus } from "@/app/api/__generated__/models/nightlyJobStatus";
+
+export type AnyJobStatus =
+ | DreamJobStatus
+ | NightlyJobStatus
+ | CommunityRebuildJobStatus;
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/memory/components/useMemoryScope.ts b/autogpt_platform/frontend/src/app/(platform)/admin/memory/components/useMemoryScope.ts
new file mode 100644
index 0000000000..9da3f62249
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/memory/components/useMemoryScope.ts
@@ -0,0 +1,62 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import {
+ type listExpertsResponse,
+ useListExperts,
+} from "@/app/api/__generated__/endpoints/experts/experts";
+import type { Expert } from "@/app/api/__generated__/models/expert";
+import { useToast } from "@/components/molecules/Toast/use-toast";
+
+export const AUTOPILOT_MEMORY_SCOPE = "autopilot";
+const EMPTY_EXPERTS: Expert[] = [];
+
+function selectExperts(response: listExpertsResponse): Expert[] {
+ return response.status === 200 ? response.data : EMPTY_EXPERTS;
+}
+
+export function useMemoryScope() {
+ const { toast } = useToast();
+ const [selectedScope, setSelectedScope] = useState(AUTOPILOT_MEMORY_SCOPE);
+ const expertsQuery = useListExperts({
+ query: {
+ select: selectExperts,
+ },
+ });
+ const experts = expertsQuery.data ?? EMPTY_EXPERTS;
+
+ useEffect(() => {
+ if (
+ selectedScope === AUTOPILOT_MEMORY_SCOPE ||
+ expertsQuery.isLoading ||
+ expertsQuery.error
+ ) {
+ return;
+ }
+ if (!experts?.some(({ id }) => id === selectedScope)) {
+ setSelectedScope(AUTOPILOT_MEMORY_SCOPE);
+ toast({
+ title: "Expert no longer available",
+ description: "Showing AutoPilot account memory instead.",
+ });
+ }
+ }, [
+ experts,
+ expertsQuery.error,
+ expertsQuery.isLoading,
+ selectedScope,
+ toast,
+ ]);
+
+ const selectedExpertID =
+ selectedScope === AUTOPILOT_MEMORY_SCOPE ? undefined : selectedScope;
+
+ return {
+ selectedScope,
+ setSelectedScope,
+ selectedExpertID,
+ experts,
+ expertsLoading: expertsQuery.isLoading,
+ expertsError: expertsQuery.error,
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/memory/components/useMemoryVisualizer.ts b/autogpt_platform/frontend/src/app/(platform)/admin/memory/components/useMemoryVisualizer.ts
index d7100744a7..00fece3530 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/memory/components/useMemoryVisualizer.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/memory/components/useMemoryVisualizer.ts
@@ -1,7 +1,7 @@
"use client";
import { useEffect, useState } from "react";
-import { useQueryClient } from "@tanstack/react-query";
+import { type QueryClient, useQueryClient } from "@tanstack/react-query";
import {
getGetV2GetCommunityRebuildStatusQueryKey,
getGetV2GetDreamPassStatusQueryKey,
@@ -10,6 +10,8 @@ import {
getGetV2GetNightlyBatchStatusQueryKey,
useGetV2GetCommunityRebuildStatus,
useGetV2GetDreamPassStatus,
+ useGetV2GetExpertGraph,
+ useGetV2GetExpertMemoryOverview,
useGetV2GetGraph,
useGetV2GetMemoryOverview,
useGetV2GetNightlyBatchStatus,
@@ -18,24 +20,13 @@ import {
usePostV2TriggerNightlyBatch,
usePostV2TriggerRatificationPass,
} from "@/app/api/__generated__/endpoints/admin/admin";
-import type { CommunityRebuildJobStatus } from "@/app/api/__generated__/models/communityRebuildJobStatus";
-import type { DreamJobStatus } from "@/app/api/__generated__/models/dreamJobStatus";
import type { DreamJobStatusState } from "@/app/api/__generated__/models/dreamJobStatusState";
import type { GraphResponse } from "@/app/api/__generated__/models/graphResponse";
import type { JobTriggerResponse } from "@/app/api/__generated__/models/jobTriggerResponse";
import type { MemoryOverview } from "@/app/api/__generated__/models/memoryOverview";
-import type { NightlyJobStatus } from "@/app/api/__generated__/models/nightlyJobStatus";
import type { RatificationResult } from "@/app/api/__generated__/models/ratificationResult";
import { useToast } from "@/components/molecules/Toast/use-toast";
-
-// Polling envelope shared across all three job kinds — they're
-// structurally identical except for the typed ``result`` payload, so
-// the polling hook walks them as a union. Narrowing to a specific
-// kind happens at the view layer that reads ``status.result``.
-type AnyJobStatus =
- | DreamJobStatus
- | NightlyJobStatus
- | CommunityRebuildJobStatus;
+import type { AnyJobStatus } from "./memoryJobStatus";
// The state enum is identical across all three concrete envelopes
// (same underlying Pydantic Literal). Pick the dream variant as the
@@ -55,12 +46,28 @@ function isTerminal(state: JobStateValue | undefined): state is TerminalState {
return state === "complete" || state === "errored";
}
-export function useMemoryVisualizer() {
+function invalidateAutoPilotMemoryQueries(queryClient: QueryClient) {
+ // Account and expert scopes are separate endpoints (and therefore
+ // separate query-key URLs), so a prefix invalidation of the account
+ // keys can never touch an expert cache.
+ queryClient.invalidateQueries({
+ queryKey: getGetV2GetMemoryOverviewQueryKey(USER_ID),
+ });
+ queryClient.invalidateQueries({
+ queryKey: getGetV2GetGraphQueryKey(USER_ID),
+ });
+}
+
+export function useMemoryVisualizer(expertID?: string) {
const { toast } = useToast();
const queryClient = useQueryClient();
const [force, setForce] = useState(false);
const [includeEpisodes, setIncludeEpisodes] = useState(false);
const [includeCommunities, setIncludeCommunities] = useState(true);
+ // Normalize "" to undefined so read-only state and the fetch scope
+ // can never disagree about whether an expert is selected.
+ const scopedExpertID = expertID || undefined;
+ const readOnly = scopedExpertID !== undefined;
// Track the in-flight job per kind so the polling hooks know what
// to watch. ``undefined`` means no job in flight for that kind.
@@ -74,13 +81,35 @@ export function useMemoryVisualizer() {
string | undefined
>();
- const overview = useGetV2GetMemoryOverview(USER_ID);
- const graph = useGetV2GetGraph(USER_ID, {
+ const baseGraphParams = {
include_episodes: includeEpisodes,
include_communities: includeCommunities,
node_limit: 10000,
edge_limit: 20000,
+ };
+
+ // Account and expert scopes are separate (path-scoped) endpoints.
+ // Hooks can't be mounted conditionally, so both pairs are always
+ // called and exactly one pair is enabled for the current scope.
+ const accountOverview = useGetV2GetMemoryOverview(USER_ID, {
+ query: { enabled: !readOnly },
});
+ const accountGraph = useGetV2GetGraph(USER_ID, baseGraphParams, {
+ query: { enabled: !readOnly },
+ });
+ const expertOverview = useGetV2GetExpertMemoryOverview(
+ USER_ID,
+ scopedExpertID ?? "",
+ { query: { enabled: readOnly } },
+ );
+ const expertGraph = useGetV2GetExpertGraph(
+ USER_ID,
+ scopedExpertID ?? "",
+ baseGraphParams,
+ { query: { enabled: readOnly } },
+ );
+ const overview = readOnly ? expertOverview : accountOverview;
+ const graph = readOnly ? expertGraph : accountGraph;
// --- Triggers (POST → 202 + job_id) ---------------------------------------
@@ -153,12 +182,7 @@ export function useMemoryVisualizer() {
`superseded=${result.superseded_count}`,
});
}
- queryClient.invalidateQueries({
- queryKey: getGetV2GetMemoryOverviewQueryKey(USER_ID),
- });
- queryClient.invalidateQueries({
- queryKey: getGetV2GetGraphQueryKey(USER_ID),
- });
+ invalidateAutoPilotMemoryQueries(queryClient);
},
onError: (error: Error) => {
toast({
@@ -222,12 +246,7 @@ export function useMemoryVisualizer() {
queryClient.invalidateQueries({
queryKey: getGetV2GetDreamPassStatusQueryKey(USER_ID, activeDreamJobId),
});
- queryClient.invalidateQueries({
- queryKey: getGetV2GetMemoryOverviewQueryKey(USER_ID),
- });
- queryClient.invalidateQueries({
- queryKey: getGetV2GetGraphQueryKey(USER_ID),
- });
+ invalidateAutoPilotMemoryQueries(queryClient);
},
toast,
);
@@ -245,12 +264,7 @@ export function useMemoryVisualizer() {
activeNightlyJobId,
),
});
- queryClient.invalidateQueries({
- queryKey: getGetV2GetMemoryOverviewQueryKey(USER_ID),
- });
- queryClient.invalidateQueries({
- queryKey: getGetV2GetGraphQueryKey(USER_ID),
- });
+ invalidateAutoPilotMemoryQueries(queryClient);
},
toast,
);
@@ -268,12 +282,7 @@ export function useMemoryVisualizer() {
activeRebuildJobId,
),
});
- queryClient.invalidateQueries({
- queryKey: getGetV2GetMemoryOverviewQueryKey(USER_ID),
- });
- queryClient.invalidateQueries({
- queryKey: getGetV2GetGraphQueryKey(USER_ID),
- });
+ invalidateAutoPilotMemoryQueries(queryClient);
},
toast,
);
@@ -281,23 +290,72 @@ export function useMemoryVisualizer() {
// --- Action callbacks ---------------------------------------------------
function triggerRebuild() {
+ if (readOnly) return;
rebuild.mutate({ userId: USER_ID, params: { force } });
}
function triggerDream() {
+ if (readOnly) return;
dream.mutate({ userId: USER_ID });
}
function triggerRatification() {
+ if (readOnly) return;
ratification.mutate({ userId: USER_ID });
}
function triggerNightly() {
+ if (readOnly) return;
nightly.mutate({ userId: USER_ID });
}
- const overviewData = overview.data?.data as MemoryOverview | undefined;
- const graphData = graph.data?.data as GraphResponse | undefined;
+ // --- Scope tripwire -----------------------------------------------------
+ //
+ // Overview + graph responses echo the expert_id they were computed
+ // for (null/absent = account scope). If the echo ever disagrees with
+ // the scope we requested, never render that payload as the requested
+ // scope — surface it as an error instead.
+
+ function matchesRequestedScope(
+ payload: { expert_id?: string | null } | undefined,
+ ): boolean {
+ return (
+ payload === undefined ||
+ (payload.expert_id ?? undefined) === scopedExpertID
+ );
+ }
+
+ const rawOverviewData = overview.data?.data as MemoryOverview | undefined;
+ const rawGraphData = graph.data?.data as GraphResponse | undefined;
+ const overviewData = matchesRequestedScope(rawOverviewData)
+ ? rawOverviewData
+ : undefined;
+ const graphData = matchesRequestedScope(rawGraphData)
+ ? rawGraphData
+ : undefined;
+ const scopeMismatch =
+ overviewData !== rawOverviewData || graphData !== rawGraphData;
+ const scopeMismatchError = scopeMismatch
+ ? new Error(
+ "Memory scope mismatch: the server returned memory for a " +
+ "different scope than requested",
+ )
+ : undefined;
+
+ useEffect(() => {
+ if (!scopeMismatch) return;
+ toast({
+ title: "Memory scope mismatch",
+ description:
+ "The server returned memory for a different scope than " +
+ "requested. The mismatched data was not rendered.",
+ variant: "destructive",
+ });
+ // ``toast`` changes identity every render; the mismatch flag is the
+ // signal we react to.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [scopeMismatch]);
+
const dreamStatusData = dreamStatus.data?.data as AnyJobStatus | undefined;
const nightlyStatusData = nightlyStatus.data?.data as
| AnyJobStatus
@@ -313,6 +371,7 @@ export function useMemoryVisualizer() {
dream,
ratification,
nightly,
+ readOnly,
triggerRebuild,
triggerDream,
triggerRatification,
@@ -325,6 +384,7 @@ export function useMemoryVisualizer() {
setIncludeCommunities,
overviewData,
graphData,
+ scopeMismatchError,
// Polling status + active flags consumed by MemoryVisualizer to
// render phase-aware button text.
dreamStatusData,
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 82deacee05..5a8027d9f3 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -1224,6 +1224,7 @@
"get": {
"tags": ["v2", "admin", "admin", "memory"],
"summary": "List Communities",
+ "description": "Communities in the user's account (AutoPilot) memory graph.",
"operationId": "getV2ListCommunities",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
@@ -1488,6 +1489,7 @@
"get": {
"tags": ["v2", "admin", "admin", "memory"],
"summary": "List Entities",
+ "description": "Entities in the user's account (AutoPilot) memory graph.",
"operationId": "getV2ListEntities",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
@@ -1538,10 +1540,393 @@
}
}
},
+ "/api/admin/memory/{user_id}/experts/{expert_id}/communities": {
+ "get": {
+ "tags": ["v2", "admin", "admin", "memory"],
+ "summary": "List Expert Communities",
+ "description": "Communities in one expert's isolated memory graph.",
+ "operationId": "getV2ListExpertCommunities",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "user_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "description": "User id or 'me'",
+ "title": "User Id"
+ },
+ "description": "User id or 'me'"
+ },
+ {
+ "name": "expert_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128,
+ "description": "Expert id owned by the user",
+ "title": "Expert Id"
+ },
+ "description": "Expert id owned by the user"
+ },
+ {
+ "name": "limit",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "maximum": 2000,
+ "minimum": 1,
+ "default": 500,
+ "title": "Limit"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CommunityListResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/api/admin/memory/{user_id}/experts/{expert_id}/entities": {
+ "get": {
+ "tags": ["v2", "admin", "admin", "memory"],
+ "summary": "List Expert Entities",
+ "description": "Entities in one expert's isolated memory graph.",
+ "operationId": "getV2ListExpertEntities",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "user_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "description": "User id or 'me'",
+ "title": "User Id"
+ },
+ "description": "User id or 'me'"
+ },
+ {
+ "name": "expert_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128,
+ "description": "Expert id owned by the user",
+ "title": "Expert Id"
+ },
+ "description": "Expert id owned by the user"
+ },
+ {
+ "name": "limit",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "maximum": 10000,
+ "minimum": 1,
+ "default": 1000,
+ "title": "Limit"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/EntityListResponse" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/api/admin/memory/{user_id}/experts/{expert_id}/facts": {
+ "get": {
+ "tags": ["v2", "admin", "admin", "memory"],
+ "summary": "List Expert Facts",
+ "description": "Facts (RELATES_TO edges) in one expert's isolated memory graph.",
+ "operationId": "getV2ListExpertFacts",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "user_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "description": "User id or 'me'",
+ "title": "User Id"
+ },
+ "description": "User id or 'me'"
+ },
+ {
+ "name": "expert_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128,
+ "description": "Expert id owned by the user",
+ "title": "Expert Id"
+ },
+ "description": "Expert id owned by the user"
+ },
+ {
+ "name": "limit",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "maximum": 10000,
+ "minimum": 1,
+ "default": 1000,
+ "title": "Limit"
+ }
+ },
+ {
+ "name": "status",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "enum": ["active", "superseded", "contradicted", "any"],
+ "type": "string",
+ "default": "any",
+ "title": "Status"
+ }
+ },
+ {
+ "name": "scope",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Scope"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/FactListResponse" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/api/admin/memory/{user_id}/experts/{expert_id}/graph": {
+ "get": {
+ "tags": ["v2", "admin", "admin", "memory"],
+ "summary": "Get Expert Graph",
+ "description": "Visualizer graph payload for one expert's isolated memory graph.",
+ "operationId": "getV2GetExpertGraph",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "user_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "description": "User id or 'me'",
+ "title": "User Id"
+ },
+ "description": "User id or 'me'"
+ },
+ {
+ "name": "expert_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128,
+ "description": "Expert id owned by the user",
+ "title": "Expert Id"
+ },
+ "description": "Expert id owned by the user"
+ },
+ {
+ "name": "node_limit",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "maximum": 20000,
+ "minimum": 1,
+ "default": 5000,
+ "title": "Node Limit"
+ }
+ },
+ {
+ "name": "edge_limit",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "maximum": 50000,
+ "minimum": 1,
+ "default": 10000,
+ "title": "Edge Limit"
+ }
+ },
+ {
+ "name": "include_episodes",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "boolean",
+ "default": false,
+ "title": "Include Episodes"
+ }
+ },
+ {
+ "name": "include_communities",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "boolean",
+ "default": true,
+ "title": "Include Communities"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/GraphResponse" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/api/admin/memory/{user_id}/experts/{expert_id}/overview": {
+ "get": {
+ "tags": ["v2", "admin", "admin", "memory"],
+ "summary": "Get Expert Memory Overview",
+ "description": "Count summary of one expert's isolated memory graph.",
+ "operationId": "getV2GetExpertMemoryOverview",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "user_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "description": "User id or 'me'",
+ "title": "User Id"
+ },
+ "description": "User id or 'me'"
+ },
+ {
+ "name": "expert_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128,
+ "description": "Expert id owned by the user",
+ "title": "Expert Id"
+ },
+ "description": "Expert id owned by the user"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/MemoryOverview" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/admin/memory/{user_id}/facts": {
"get": {
"tags": ["v2", "admin", "admin", "memory"],
"summary": "List Facts",
+ "description": "Facts (RELATES_TO edges) in the user's account (AutoPilot) memory graph.",
"operationId": "getV2ListFacts",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
@@ -1616,7 +2001,7 @@
"get": {
"tags": ["v2", "admin", "admin", "memory"],
"summary": "Get Graph",
- "description": "Single-shot graph payload for the visualizer canvas.\n\nReturns nodes + edges in one round-trip so the frontend can hand\nthe whole thing to a force-directed layout without N+1 fetches.\n\nDefaults to entities + communities (the \"what does my memory know\nabout\" view). ``include_episodes=True`` adds the temporal\n:Episodic nodes — useful for debugging extraction but noisy for the\ntypical inspector view.",
+ "description": "Single-shot graph payload for the visualizer canvas (account scope).\n\nReturns nodes + edges in one round-trip so the frontend can hand\nthe whole thing to a force-directed layout without N+1 fetches.\n\nDefaults to entities + communities (the \"what does my memory know\nabout\" view). ``include_episodes=True`` adds the temporal\n:Episodic nodes — useful for debugging extraction but noisy for the\ntypical inspector view.",
"operationId": "getV2GetGraph",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
@@ -1800,6 +2185,7 @@
"get": {
"tags": ["v2", "admin", "admin", "memory"],
"summary": "Get Memory Overview",
+ "description": "Count summary of the user's account (AutoPilot) memory graph.",
"operationId": "getV2GetMemoryOverview",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
@@ -19013,6 +19399,10 @@
"GraphResponse": {
"properties": {
"user_id": { "type": "string", "title": "User Id" },
+ "expert_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Expert Id"
+ },
"group_id": { "type": "string", "title": "Group Id" },
"nodes": {
"items": { "$ref": "#/components/schemas/GraphNode" },
@@ -20636,6 +21026,10 @@
"MemoryOverview": {
"properties": {
"user_id": { "type": "string", "title": "User Id" },
+ "expert_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Expert Id"
+ },
"group_id": { "type": "string", "title": "Group Id" },
"entities": { "type": "integer", "title": "Entities" },
"episodes": { "type": "integer", "title": "Episodes" },