Files
ai-agent/backend/test_carryover_tools.py
gabrielvidalandClaude Opus 5.5 4d0dcfa3ff refactor(toolproxy): the tools are plugins — retire the core brokers, the guests' tool groups and the hub editions
Since 2026-11-25 nanobanana, video-extract, 3d-gen, 3d-render, matomo,
movies and meta are live plugins with their own proxies and managed grants,
but the core still served the old path next to them — and its hub editions
won over the plugin skills on workers. This finishes the move (form
ai-agent-moves-to-ai-agent-plugins_o2qxmd, move A). Rebased on 41665fa2,
which had already removed the core's Meta Business.

- gone: toolproxy/{matomo,media,webroutes,owned,catalog}.py, the nanobanana /
  3d-gen / 3d-render / video-extract / matomo / movies routes and the movies
  webhook, cli/skills/{nanobanana,3d-gen,3d-render,video-extract,matomo,
  movies}, the guests' `tools` groups (users store, Caller.tool_groups,
  Me/GuestUser.tools, tools.matomoSites), the User page's Paid tools and
  Tools budget panels
- kept: the /proxy/tools door (tokens, whoami — now the caller's plugins and
  spend — and the shared client), the tool ledger, the tools chip, a guest
  job's tool token (c6e15991: tool_scope still gives one with plugin skills)
- labsync: a plugin skill wins over a lab skill of the same name; plugin
  skills with a proxy keep their hub.json
- guest runs get their plugins' skills on spawn, resume, reply, fork and No
  project runs alike (deps passed to scope_for / scratch_scope everywhere)
- Movies brings Jellyfin when the movies grant comes on (new guest, or the
  owner's switch)
- plugins/carryover_tools.py: tool groups → grants / installs (never over an
  explicit grant), Meta keys + saved days (only where the plugin has none),
  Matomo viewers, Seerr users and pending requests, 3d-gen ownership → the
  plugins' data, once
- matomo_sites: users.json tools.matomoSites → the matomo grant's
  `extraSites` (list grantField, sibling ai-agent-plugins PR), and the grant
  on for an `analytics` guest — once per guest, so Cel (analytics + site 11
  after the groups moved) gets it; an explicit grant only gets extraSites
  when it has none; waits for a matomo manifest with the field
- Me → Budget's Tools card reads the guest's managed plugins

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

275 lines
14 KiB
Python

"""The retired core tool proxy → the tool plugins, once (2026-11-26,
``plugins/carryover_tools.py``): the guests' tool groups become grants (managed
plugins) or installs (plain ones), never over an explicit grant; the Meta keys
and saved days, the Matomo viewers, the Seerr users and pending requests and the
3d-gen ownership become the plugins' own data."""
from __future__ import annotations
import json
import pathlib
import tempfile
import unittest
from plugins import carryover, carryover_tools as ct
from plugins.store import OWNER_UID, PluginStore
def _manifest(pid: str, managed: dict | None = None, **extra) -> dict:
m = {"schema": 1, "id": pid, "name": pid, "version": "1.0.0", **extra}
if managed is not None:
m["managed"] = managed
return m
MANIFESTS = {
"nanobanana": _manifest("nanobanana", {
"defaultForGuests": False, "metered": True,
"grantFields": [{"key": "allowPro", "label": "Pro", "type": "checkbox", "default": False}],
"limits": {"defaultMonthlyBudgetUsd": 5.0}}),
"movies": _manifest("movies", {"defaultForGuests": True}),
"matomo": _manifest("matomo", {"defaultForGuests": False}),
"3d-gen": _manifest("3d-gen", {"defaultForGuests": False}),
"3d-render": _manifest("3d-render", {"defaultForGuests": False}),
"video-extract": _manifest("video-extract", {"defaultForGuests": False}),
"video-dl": _manifest("video-dl"),
"meta": _manifest("meta", secrets=[{"key": "token", "label": "Key", "scope": "user"}]),
}
class FakeUsers:
def __init__(self, users):
self.users = users
def all(self):
return [dict(u) for u in self.users]
class Base(unittest.TestCase):
def setUp(self):
self._td = tempfile.TemporaryDirectory()
self.root = pathlib.Path(self._td.name)
self.store = PluginStore(self.root / "plugins")
def tearDown(self):
self._td.cleanup()
def install(self, *pids: str) -> None:
for pid in pids:
src = self.root / "src" / pid
src.mkdir(parents=True)
(src / "plugin.json").write_text(json.dumps(MANIFESTS[pid]))
self.store.install(OWNER_UID, str(src), is_owner=True, approve=True)
def grant(self, uid: str, pid: str) -> dict:
rec = self.store.get_raw(OWNER_UID, pid)
return self.store.effective_grant(uid, pid, rec["manifest"])
class Grants(Base):
USERS = [
{"id": "ana", "tools": {"groups": ["images", "3d", "media"], "pro": True,
"budgetUsd": 25}},
{"id": "bo", "tools": {"groups": ["analytics", "video"]}}, # Movies off
{"id": "cy"}, # never touched: Movies on
]
def test_groups_become_grants_and_installs(self):
self.install(*MANIFESTS)
done = ct.tool_grants(self.store, FakeUsers(self.USERS))
self.assertEqual(sorted(done), sorted(MANIFESTS))
nb = self.grant("ana", "nanobanana")
self.assertEqual((nb["enabled"], nb["config"]["allowPro"], nb["monthlyBudgetUsd"]),
(True, True, 25.0))
self.assertTrue(self.grant("ana", "3d-gen")["enabled"])
self.assertTrue(self.grant("ana", "3d-render")["enabled"])
self.assertFalse(self.grant("ana", "matomo")["enabled"])
# Movies is on for guests by default: Bo, who had it off, stays off;
# Ana and Cy keep the default (no grant written for them).
self.assertFalse(self.grant("bo", "movies")["enabled"])
self.assertTrue(self.grant("ana", "movies")["isDefault"])
self.assertTrue(self.grant("cy", "movies")["enabled"])
self.assertTrue(self.grant("bo", "matomo")["enabled"])
self.assertTrue(self.grant("bo", "video-extract")["enabled"])
# video-dl is a plain plugin: installed for Bo, not for the others.
self.assertIsNotNone(self.store.get_raw("bo", "video-dl"))
self.assertIsNone(self.store.get_raw("ana", "video-dl"))
def test_an_explicit_grant_wins_and_it_runs_once(self):
self.install("nanobanana", "movies")
self.store.set_grant("ana", "nanobanana", enabled=False)
ct.tool_grants(self.store, FakeUsers(self.USERS))
self.assertFalse(self.grant("ana", "nanobanana")["enabled"])
# Once done, a later change of the old field moves nothing.
users = FakeUsers([{"id": "bo", "tools": {"groups": ["media"]}}])
self.assertEqual(ct.tool_grants(self.store, users), [])
self.assertFalse(self.grant("bo", "movies")["enabled"])
def test_a_plugin_not_installed_yet_waits(self):
self.install("movies")
self.assertEqual(ct.tool_grants(self.store, FakeUsers(self.USERS)), ["movies"])
self.assertFalse(ct._done(self.store, "nanobanana"))
self.install("nanobanana")
self.assertEqual(ct.tool_grants(self.store, FakeUsers(self.USERS)), ["nanobanana"])
self.assertTrue(self.grant("ana", "nanobanana")["enabled"])
def test_the_old_default_was_movies_on(self):
self.assertEqual(ct.legacy_tools({})["groups"], ["media"])
self.assertEqual(ct.legacy_tools({"tools": {"groups": []}})["groups"], [])
self.assertEqual(ct.legacy_tools({"tools": {"budgetUsd": "x"}})["budgetUsd"], 10.0)
self.assertIn("meta", ct.TOOL_PLUGINS)
self.assertIs(carryover.tools, ct.tools)
class MatomoSites(Base):
EXTRA = {"key": "extraSites", "label": "Extra sites", "type": "list"}
def install_matomo(self, *, field: bool = True) -> None:
mg = {"defaultForGuests": False, "grantFields": [self.EXTRA] if field else []}
MANIFESTS["matomo"] = _manifest("matomo", mg)
self.addCleanup(MANIFESTS.__setitem__, "matomo",
_manifest("matomo", {"defaultForGuests": False}))
self.install("matomo")
def test_cel_added_to_analytics_after_the_groups_moved(self):
self.install_matomo()
# The groups were carried over before Cel had analytics…
ct.tool_grants(self.store, FakeUsers([{"id": "cel", "tools": {"groups": ["media"]}}]))
self.assertTrue(ct._done(self.store, "matomo"))
self.assertFalse(self.grant("cel", "matomo")["enabled"])
# …then the owner switched it on with site 11 (calamite.net).
cel = {"id": "cel", "tools": {"groups": ["media", "analytics"], "matomoSites": [11]}}
self.assertEqual(ct.matomo_sites(self.store, FakeUsers([cel])), ["cel"])
g = self.grant("cel", "matomo")
self.assertEqual((g["enabled"], g["config"]["extraSites"]), (True, [11]))
# Once per guest.
self.store.set_grant("cel", "matomo", enabled=False)
self.assertEqual(ct.matomo_sites(self.store, FakeUsers([cel])), [])
self.assertFalse(self.grant("cel", "matomo")["enabled"])
def test_an_explicit_grant_only_gets_its_missing_extra_sites(self):
self.install_matomo()
self.store.set_grant("cel", "matomo", enabled=False)
self.store.set_grant("dom", "matomo", enabled=True, config={"extraSites": [4]})
users = FakeUsers([
{"id": "cel", "tools": {"groups": ["analytics"], "matomoSites": ["11", 11, "x"]}},
{"id": "dom", "tools": {"groups": ["analytics"], "matomoSites": [11]}}])
self.assertEqual(sorted(ct.matomo_sites(self.store, users)), ["cel", "dom"])
cel, dom = self.grant("cel", "matomo"), self.grant("dom", "matomo")
self.assertEqual((cel["enabled"], cel["config"]["extraSites"]), (False, [11]))
self.assertEqual((dom["enabled"], dom["config"]["extraSites"]), (True, [4]))
def test_sites_wait_for_the_plugins_extra_sites_field(self):
self.install_matomo(field=False)
cel = {"id": "cel", "tools": {"groups": ["analytics"], "matomoSites": [11]}}
self.assertEqual(ct.matomo_sites(self.store, FakeUsers([cel])), [])
self.assertTrue(self.grant("cel", "matomo")["enabled"]) # the switch already
# The plugin's update brings the field: the sites follow.
rec = self.store.get_raw(OWNER_UID, "matomo")
rec["manifest"]["managed"]["grantFields"] = [self.EXTRA]
self.store._state["users"][OWNER_UID]["matomo"] = rec
self.assertEqual(ct.matomo_sites(self.store, FakeUsers([cel])), ["cel"])
self.assertEqual(self.grant("cel", "matomo")["config"]["extraSites"], [11])
def test_no_analytics_no_grant(self):
self.install_matomo()
users = FakeUsers([{"id": "bo", "tools": {"groups": ["media"], "matomoSites": [3]}},
{"id": "cy"}])
self.assertEqual(ct.matomo_sites(self.store, users), [])
self.assertTrue(self.grant("bo", "matomo")["isDefault"])
self.assertEqual(ct.legacy_tools({"tools": {"matomoSites": "11, 12 11"}})["matomoSites"],
[11, 12])
ct.tools(self.store, users) # wired in, never raises
class Data(Base):
def test_meta_keys_and_days_move_to_the_guests_plugin(self):
self.install("meta")
legacy = self.root / "tools-meta.json"
legacy.write_text(json.dumps({
"cel": {"token": "EAA-secret", "pageTokens": {"1": "p"}, "user": {"id": "9"},
"scopes": ["ads_read"], "connectedAt": "2026-11-25T08:00:00Z",
"snapshot": {"day": "2026-11-25", "ok": True}},
"dom": {"user": {"id": "1"}}})) # no key: nothing to move
days = self.root / "snaps" / "cel"
days.mkdir(parents=True)
(days / "2026-11-24.json").write_text('{"date":"2026-11-24","ads":[]}')
(days / "notes.txt").write_text("x")
self.assertEqual(ct.meta_connections(self.store, str(legacy), str(self.root / "snaps")), 1)
self.assertEqual(self.store.get_secret("cel", "meta", "token", scope="user"), "EAA-secret")
d = self.store.user_data_dir("cel", "meta")
conn = json.loads((d / "connection.json").read_text())
self.assertEqual(conn["user"], {"id": "9"})
self.assertNotIn("token", conn)
self.assertNotIn("pageTokens", conn)
self.assertEqual(json.loads((d / "snapshot.json").read_text())["day"], "2026-11-25")
self.assertTrue((d / "2026-11-24.json").is_file())
self.assertFalse((d / "notes.txt").exists())
self.assertFalse(legacy.exists())
self.assertTrue(legacy.with_name("tools-meta.json.migrated").is_file())
def test_a_meta_key_waits_for_a_plugin_to_install(self):
legacy = self.root / "tools-meta.json"
legacy.write_text(json.dumps({"cel": {"token": "EAA-secret"}}))
self.assertEqual(ct.meta_connections(self.store, str(legacy), str(self.root / "s")), 0)
self.assertTrue(legacy.is_file()) # kept for the next start
self.install("meta")
self.assertEqual(ct.meta_connections(self.store, str(legacy), str(self.root / "s")), 1)
def test_matomo_viewers(self):
self.install("matomo")
legacy = self.root / "tools-matomo.json"
legacy.write_text(json.dumps({"dom": {"login": "guest-dom-viewer", "password": "pw",
"token": "t1"}}))
self.assertEqual(ct.matomo_viewers(self.store, str(legacy)), 1)
p = self.store.user_data_dir("dom", "matomo") / "_private" / "viewer.json"
self.assertEqual(json.loads(p.read_text())["token"], "t1")
self.assertEqual(p.stat().st_mode & 0o777, 0o600)
def test_seerr_users_and_pending_requests(self):
self.install("movies")
legacy = self.root / "tools-media.json"
legacy.write_text(json.dumps({
"users": {"dom": 12},
"requests": {
"101": {"uid": "dom", "session": "s1", "type": "movie", "tmdb": 550,
"label": "Fight Club (1999)", "at": "2026-11-20T10:00:00+00:00"},
"102": {"uid": "dom", "type": "movie", "tmdb": 13, "told": "available"},
"103": {"uid": None, "type": "tv", "tmdb": 1399, "label": "GoT",
"seasons": [1]}}}))
self.assertEqual(ct.movies_users(self.store, str(legacy)), 2)
st = json.loads((self.store.user_data_dir("dom", "movies") / "state.json").read_text())
self.assertEqual(st["seerrUser"], 12)
self.assertEqual(sorted(st["requests"]), ["101", "102"])
self.assertTrue(st["indexed"])
idx = json.loads((self.store.shared_data_dir("movies") / "requests.json").read_text())
titles = idx["titles"]
self.assertEqual(sorted(titles), ["movie:550", "tv:1399"]) # 102 was told already
e = titles["movie:550"]["dom"]
self.assertEqual((e["requests"], e["session"], e["label"]), ([101], "s1", "Fight Club (1999)"))
self.assertEqual(titles["tv:1399"]["owner"]["seasons"], [1])
def test_3d_ownership(self):
self.install("3d-gen")
legacy = self.root / "tools-owned.json"
legacy.write_text(json.dumps({
"jobs": {"0123456789ab": {"uid": "dom", "t": 5}, "bad": {"uid": "dom"}},
"folders": {"chair-1": {"uid": "dom", "t": 6}, "x": {"uid": "Bad Uid"}}}))
self.assertEqual(ct.threed_owned(self.store, str(legacy)), 1)
owned = json.loads((self.store.user_data_dir("dom", "3d-gen") / "_private"
/ "owned.json").read_text())
self.assertEqual(owned, {"jobs": {"0123456789ab": {"t": 5}},
"folders": {"chair-1": {"t": 6}}})
def test_nothing_to_do_without_the_plugins(self):
legacy = self.root / "tools-owned.json"
legacy.write_text("{}")
self.assertEqual(ct.threed_owned(self.store, str(legacy)), 0)
self.assertTrue(legacy.is_file())
ct.tools(self.store, FakeUsers([])) # never raises
ct.tools(None)
if __name__ == "__main__":
unittest.main()