Files
ai-agent/backend/test_plugin_graph.py
gabrielvidalandClaude Opus 5.5 683897f32f feat(plugins): Memories leaves the core for the live memories plugin
backend/memories/ (store + /api/memories, /api/memory), core/filecache.py
(its last caller) and the MemorySummary / MemoryDetail / MemoriesResponse
schemas are gone; Claude's memory folder is the `memories` plugin's
(ai-agent-plugins, plugins/memories).

- graph.read takes its memory nodes from memories_bridge only (no core fallback)
- ConversationDetail no longer carries memoriesRead / memoriesCreated; the
  indexer still records the slugs a transcript read (parse/state.py) and the
  plugin reads them through hub/conversations?memories=1
- `ai-agent memories [--show SLUG]` and MCP browse("memories") /
  read_document("memory") call /api/plugins/memories/actions/{index,get}
  (memories_call, the plans_call twin) and say so when the plugin is off
- frontend: business/memories/ removed; /memories and /memories/:slug
  redirect to /plugins/memories/memories[/<slug>]; the Details drawer's
  Memories card is the plugin's conversation.details slot (saved layouts map
  `memories` → pluginSlots), a service page's memories its service.detail
  slot; the Files/nav entries, useMemories / fetchMemories, the tags' memory
  counts, mock handlers and stale French keys are gone
- authz: the two routes leave lab.read and matrix.golden.txt
- standalone-smoke.sh no longer probes /api/memories (nor /api/plans, gone
  since the Plans extraction)

openapi.json / src/generated are left for the coordinator's one re-dump
after Batch 1 merges.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 10:44:18 +01:00

205 lines
9.5 KiB
Python

"""The ``graph.read`` capability (plugins/graphdata.py) and the ``fill`` page
flag — what the Graph plugin needs since the dashboard left the core
(2026-11-25)."""
from __future__ import annotations
import json
import pathlib
import tempfile
import unittest
from unittest.mock import patch
from fastapi.testclient import TestClient
import main
from plugins import graphdata
from plugins.manifest import (ManifestError, capability_fingerprint, capability_summary,
requires_operator, validate_manifest)
from plugins.store import OWNER_UID, PluginStore
from toolproxy import access
def _write(root: pathlib.Path, manifest: dict) -> pathlib.Path:
root.mkdir(parents=True, exist_ok=True)
(root / "plugin.json").write_text(json.dumps(manifest), encoding="utf-8")
(root / "ui").mkdir(exist_ok=True)
(root / "ui" / "g.html").write_text("<p>g</p>", encoding="utf-8")
(root / "handlers").mkdir(exist_ok=True)
(root / "handlers" / "g.py").write_text("print('{}')\n", encoding="utf-8")
return root
MANIFEST = {
"schema": 1, "id": "gr", "name": "Graph",
"ui": {"pages": [{"id": "graph", "label": "Graph", "nav": "dashboards",
"html": "ui/g.html", "fill": True}]},
"actions": {"graph": {"script": "handlers/g.py"}},
"capabilities": ["graph.read"],
}
class TestManifest(unittest.TestCase):
def test_graph_read_is_a_privileged_operator_capability(self):
with tempfile.TemporaryDirectory() as td:
mf = validate_manifest(_write(pathlib.Path(td) / "gr", MANIFEST))
self.assertEqual(mf["capabilities"], ["graph.read"])
self.assertTrue(requires_operator(mf))
cap = [c for c in capability_summary(mf) if c["kind"] == "capability"]
self.assertTrue(cap[0]["privileged"])
def test_fill_is_kept_only_when_set(self):
with tempfile.TemporaryDirectory() as td:
mf = validate_manifest(_write(pathlib.Path(td) / "a", MANIFEST))
self.assertIs(mf["ui"]["pages"][0]["fill"], True)
plain = json.loads(json.dumps(MANIFEST))
del plain["ui"]["pages"][0]["fill"]
mf2 = validate_manifest(_write(pathlib.Path(td) / "b", plain))
# No key at all: an installed page's fingerprint must not move.
self.assertNotIn("fill", mf2["ui"]["pages"][0])
self.assertNotEqual(capability_fingerprint(mf), capability_fingerprint(mf2))
def test_unknown_capability_still_refused(self):
with tempfile.TemporaryDirectory() as td:
bad = dict(MANIFEST, capabilities=["graph.write"])
with self.assertRaises(ManifestError):
validate_manifest(_write(pathlib.Path(td) / "gr", bad))
class _UiState:
def __init__(self, values: dict[str, dict]):
self.values = values
def get(self, key):
v = self.values.get(key)
return json.dumps({"state": v, "version": 0}) if v is not None else None
class TestLegacyPrefs(unittest.TestCase):
def test_reads_the_old_filters_and_physics_switch(self):
deps = type("D", (), {})()
deps.ui_state = _UiState({
"ai-agent-graph-filters": {"hidden": ["conversation", "subagent", "plan", "bogus"]},
"ai-agent-visibility": {"hidden": ["cost", "graphPhysics"]},
})
self.assertEqual(graphdata.legacy_prefs(deps),
{"hidden": ["conversation", "subagent", "plan"], "physics": False})
def test_defaults_when_nothing_was_saved(self):
deps = type("D", (), {})()
deps.ui_state = _UiState({})
self.assertEqual(graphdata.legacy_prefs(deps), {"hidden": [], "physics": True})
def _lists():
"""The list endpoints, as their bodies (no @_json_in_worker), and the
plans and memories the `plans` and `memories` plugins hand their bridges."""
return {
"projects.routes.projects_list": lambda deps, caller: {"projects": [{"dir": "brain", "name": "Brain", "costs": {}}]},
"services.routes.services_list": lambda deps: {"services": [{"dir": "mail", "name": ""}]},
"conversations.routes.conversations_list": lambda deps, caller, limit, archived: {"conversations": [
{"id": "019a-c1", "sessionId": "s1", "title": "auto", "meta": {"title": "Fix search", "state": "running",
"projects": ["brain"], "services": [], "account": "personal"}, "cost": 3.2},
{"id": "019a-c2", "sessionId": "", "title": "Untagged", "meta": {}},
]},
"plugins.plans_bridge.list_plans": lambda deps: [{"slug": "p1", "title": "", "sessionId": "s1",
"conversationIds": ["s9", None], "projects": ["brain"]}],
"plugins.memories_bridge.list_memories": lambda deps: [{"slug": "m1", "name": "M", "links": ["m2"],
"originSessionId": "s1", "content": "secret text"}],
"conversations.routes.subagents_list": lambda deps, caller: {"subagents": [
{"id": "019a-a1", "parentId": "019a-c1", "rootId": "019a-c1", "description": "Explore code",
"state": "running", "cost": 1}]},
}
class TestBridge(unittest.TestCase):
def setUp(self):
self.tc = TestClient(main.app)
def _with_plugin(self, td, manifest=MANIFEST):
store = PluginStore(pathlib.Path(td) / "data")
store.install(OWNER_UID, str(_write(pathlib.Path(td) / "src", manifest)),
is_owner=True, approve=True)
return store
def test_build_keeps_only_what_the_graph_draws(self):
patches = [patch(k, v) for k, v in _lists().items()]
deps = main.app.state.ai
for p in patches:
p.start()
try:
with patch.object(deps, "ui_state", _UiState({})):
out = graphdata.build(deps)
finally:
for p in patches:
p.stop()
self.assertEqual(out["projects"], [{"dir": "brain", "name": "Brain"}])
self.assertEqual(out["services"], [{"dir": "mail", "name": "mail"}])
self.assertEqual(out["conversations"][0], {"id": "019a-c1", "sessionId": "s1", "title": "Fix search",
"running": True, "projects": ["brain"], "services": []})
self.assertEqual(out["conversations"][1]["title"], "Untagged")
self.assertEqual(out["plans"][0]["sessions"], ["s1", "s9"])
self.assertEqual(out["plans"][0]["title"], "p1")
self.assertEqual(out["memories"], [{"slug": "m1", "name": "M", "links": ["m2"], "projects": [],
"services": [], "originSessionId": "s1"}])
self.assertEqual(out["subagents"][0]["label"], "Explore code")
self.assertTrue(out["subagents"][0]["running"])
self.assertEqual(out["prefs"], {"hidden": [], "physics": True})
def test_every_list_route_can_be_called(self):
"""Each list route's required parameters are ones the bridge passes —
a route that grows one (services_list took ``deps``) must not 500
the bridge again. Checked on the real functions, not stubs."""
import inspect
from conversations.routes import conversations_list, subagents_list
from projects.routes import projects_list
from services.routes import services_list
passed = {"deps", "caller", "limit", "archived"}
for fn in (projects_list, services_list, conversations_list, subagents_list):
sig = inspect.signature(graphdata._unwrap(fn))
required = {n for n, prm in sig.parameters.items()
if prm.default is inspect.Parameter.empty}
self.assertLessEqual(required, passed, fn.__name__)
def test_owner_reads_it(self):
deps = main.app.state.ai
with tempfile.TemporaryDirectory() as td:
store = self._with_plugin(td)
tok = access.mint_handler(OWNER_UID, "gr", ttl=600)
with patch.object(deps, "plugin_store", store), \
patch("plugins.graphdata.build", return_value={"conversations": [], "prefs": {}}):
r = self.tc.get("/proxy/tools/plugins/gr/hub/graph",
headers={"Authorization": f"Bearer {tok}"})
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(r.json()["conversations"], [])
def test_a_guest_never_does(self):
deps = main.app.state.ai
with tempfile.TemporaryDirectory() as td:
store = self._with_plugin(td)
tok = access.mint("cel", ttl=600)
with patch.object(deps, "plugin_store", store), \
patch("plugins.graphdata.build") as build:
r = self.tc.get("/proxy/tools/plugins/gr/hub/graph",
headers={"Authorization": f"Bearer {tok}"})
self.assertEqual(r.status_code, 403)
build.assert_not_called()
def test_needs_the_capability(self):
deps = main.app.state.ai
with tempfile.TemporaryDirectory() as td:
store = self._with_plugin(td, dict(MANIFEST, capabilities=[]))
tok = access.mint_handler(OWNER_UID, "gr", ttl=600)
with patch.object(deps, "plugin_store", store), \
patch("plugins.graphdata.build") as build:
r = self.tc.get("/proxy/tools/plugins/gr/hub/graph",
headers={"Authorization": f"Bearer {tok}"})
self.assertEqual(r.status_code, 403)
self.assertIn("graph.read", r.json()["error"]["message"])
build.assert_not_called()
if __name__ == "__main__":
unittest.main()