Files
ai-agent/backend/test_plugin_catalog.py
gabrielvidalandClaude Opus 5.5 5670313285 feat(cron): cron jobs leave the core for the cron-jobs plugin
Owner jobs and guests' own scheduled jobs are the cron-jobs live plugin's
(forms move-ai-agent-cron-jobs-into-a-plugin_u0wa6b,
cron-scheduled-in-the-cli-and-mcp_x4nk83). Gone: backend/cron/,
schemas/cron.py, /api/cron*, /api/me/cron*, the cron scheduler thread,
Settings → Cron and the guests' Tâches planifiées pages, `ai-agent cron`
(now a pointer), MCP run_cron_job / set_cron_job / browse cron, the
scheduled-jobs core skill, guestDefaults.cronLimits.

The core keeps thin contracts:
- runs.guest bridge (runs/guestjob.py): a guest's job run as that guest,
  confined by the core from their record; the plugin only names it.
- runs.start's cron stamp → meta.cron.
- delivery of a guest job's result (push, mail, mailHtml) off the stamp.
- « Discuter »: POST /api/cron-runs/discuss.
- runs.cron provider readers (plugins/cron_bridge.py): budget,
  auto-archive, agents catalog, the agents page's Schedule.
- core/cronexpr.py, agents/runconfig.py; context.write create for a new
  agent definition; ui.pages[].unless; setRoute keeps a Settings page
  under /settings/p/.
- carryover.cron_jobs: /data/cron-jobs.json → the plugin's jobs.json,
  cronLimits → limits.json, guests' qwen jobs → sonnet (PR #23's
  decision, superseded).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 17:57:41 +01:00

272 lines
12 KiB
Python

"""The ``catalog.read`` / ``skills.share`` / ``agents.run`` bridges
(plugins/hubcatalog.py) — what the ``skills-agents`` plugin needs since Files →
Skills and Files → Agents left the core (2026-11-26)."""
from __future__ import annotations
import json
import pathlib
import tempfile
import unittest
from unittest.mock import patch
from fastapi import HTTPException
from fastapi.testclient import TestClient
import main
from plugins import hubcatalog
from plugins.manifest import ManifestError, capability_summary, requires_operator, validate_manifest
from plugins.store import OWNER_UID, PluginStore
from toolproxy import access
PID = "sa"
MANIFEST = {
"schema": 1, "id": PID, "name": "Skills & agents",
"ui": {"pages": [{"id": "skills", "label": "Skills", "nav": "files", "html": "ui/p.html",
"subpath": True}]},
"actions": {"skills": {"script": "handlers/h.py", "readOnly": True}},
"capabilities": ["catalog.read", "skills.share", "agents.run"],
}
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" / "p.html").write_text("<p>p</p>", encoding="utf-8")
(root / "handlers").mkdir(exist_ok=True)
(root / "handlers" / "h.py").write_text("print('{}')\n", encoding="utf-8")
return root
class TestManifest(unittest.TestCase):
def test_the_three_caps_are_privileged_operator_ones(self):
with tempfile.TemporaryDirectory() as td:
mf = validate_manifest(_write(pathlib.Path(td) / PID, MANIFEST))
self.assertEqual(sorted(mf["capabilities"]), ["agents.run", "catalog.read", "skills.share"])
self.assertTrue(requires_operator(mf))
caps = [c for c in capability_summary(mf) if c["kind"] == "capability"]
self.assertEqual(len(caps), 3)
self.assertTrue(all(c["privileged"] for c in caps))
def test_a_write_cap_that_does_not_exist_is_refused(self):
with tempfile.TemporaryDirectory() as td:
with self.assertRaises(ManifestError):
validate_manifest(_write(pathlib.Path(td) / PID, dict(MANIFEST, capabilities=["catalog.write"])))
class _Base(unittest.TestCase):
def setUp(self):
self.tc = TestClient(main.app)
self.deps = main.app.state.ai
self._td = tempfile.TemporaryDirectory()
self.addCleanup(self._td.cleanup)
def store(self, manifest=MANIFEST):
store = PluginStore(pathlib.Path(self._td.name) / "data")
store.install(OWNER_UID, str(_write(pathlib.Path(self._td.name) / "src", manifest)),
is_owner=True, approve=True)
return store
def owner(self):
return {"Authorization": f"Bearer {access.mint_handler(OWNER_UID, PID, ttl=600)}"}
class TestReads(_Base):
def test_skills_pass_the_scope_and_add_the_profiles(self):
seen = {}
def fake(deps, account=None):
seen["account"] = account
return {"skills": [{"name": "plan"}], "totals": {"skills": 1}}
with patch.object(self.deps, "plugin_store", self.store()), \
patch("dashboards.routes.skills_list", fake), \
patch("plugins.footprintdata.profiles", return_value=[{"id": "personal", "label": "Personal"}]):
r = self.tc.get(f"/proxy/tools/plugins/{PID}/hub/skills?account=profile:personal",
headers=self.owner())
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(seen["account"], "profile:personal")
body = r.json()
self.assertEqual(body["skills"], [{"name": "plan"}])
self.assertEqual(body["scope"], "profile:personal")
self.assertEqual(body["profiles"][0]["id"], "personal")
def test_a_bad_scope_is_refused_before_any_read(self):
with patch.object(self.deps, "plugin_store", self.store()), \
patch("dashboards.routes.skills_list") as fake:
r = self.tc.get(f"/proxy/tools/plugins/{PID}/hub/skills?account=../../etc",
headers=self.owner())
self.assertEqual(r.status_code, 400)
fake.assert_not_called()
def test_agent_detail_and_its_404(self):
def fake(deps, name, account=None):
if name == "nope":
raise HTTPException(404, "agent not found")
return {"agent": {"name": name}, "runs": [], "daily": [], "canSchedule": True}
with patch.object(self.deps, "plugin_store", self.store()), \
patch("agents.routes.agent_detail", fake), \
patch("plugins.footprintdata.profiles", return_value=[]):
ok = self.tc.get(f"/proxy/tools/plugins/{PID}/hub/agents/radar", headers=self.owner())
missing = self.tc.get(f"/proxy/tools/plugins/{PID}/hub/agents/nope", headers=self.owner())
self.assertEqual(ok.status_code, 200, ok.text)
self.assertEqual(ok.json()["agent"], {"name": "radar"})
self.assertEqual(missing.status_code, 404)
self.assertEqual(missing.json()["error"]["kind"], "not_found")
def test_skill_prompt(self):
with patch.object(self.deps, "plugin_store", self.store()), \
patch("dashboards.routes.skill_prompt", return_value={"name": "x", "prompt": "# hi"}):
r = self.tc.get(f"/proxy/tools/plugins/{PID}/hub/skills/x/prompt", headers=self.owner())
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(r.json()["prompt"], "# hi")
def test_a_guest_never_reads(self):
with patch.object(self.deps, "plugin_store", self.store()), \
patch("dashboards.routes.skills_list") as fake:
r = self.tc.get(f"/proxy/tools/plugins/{PID}/hub/skills",
headers={"Authorization": f"Bearer {access.mint('cel', ttl=600)}"})
self.assertIn(r.status_code, (403, 404))
fake.assert_not_called()
def test_needs_the_capability(self):
with patch.object(self.deps, "plugin_store", self.store(dict(MANIFEST, capabilities=[]))), \
patch("agents.routes.agents_list") as fake:
r = self.tc.get(f"/proxy/tools/plugins/{PID}/hub/agents", headers=self.owner())
self.assertEqual(r.status_code, 403)
self.assertIn("catalog.read", r.json()["error"]["message"])
fake.assert_not_called()
class _Users:
def __init__(self, shared):
self.shared = list(shared)
def defaults(self):
return {"sharedSkills": list(self.shared)}
def set_defaults(self, fields):
self.shared = list(fields["sharedSkills"])
return {"sharedSkills": list(self.shared)}
class _Hub:
def __init__(self):
self.events = []
def publish(self, ev):
self.events.append(ev)
class TestShare(unittest.TestCase):
CATALOG = [{"name": "plan", "sourceKind": "repo", "source": "repo"},
{"name": "deploy", "sourceKind": "project", "source": "zipgo"}]
def deps(self, shared=()):
d = type("D", (), {})()
d.users, d.hub = _Users(shared), _Hub()
return d
def test_on_adds_a_catalog_ref_once_and_publishes(self):
d = self.deps(["plan"])
with patch("dashboards.skills.catalog", return_value=self.CATALOG):
out = hubcatalog.share_skill(d, "zipgo/deploy", True)
again = hubcatalog.share_skill(d, "zipgo/deploy", True)
self.assertEqual(out["sharedSkills"], ["plan", "zipgo/deploy"])
self.assertEqual(again["sharedSkills"], ["plan", "zipgo/deploy"])
self.assertEqual(d.hub.events, [{"type": "users"}, {"type": "users"}])
def test_off_drops_it(self):
d = self.deps(["plan", "zipgo/deploy"])
self.assertEqual(hubcatalog.share_skill(d, "plan", False)["sharedSkills"], ["zipgo/deploy"])
def test_a_ref_the_catalog_does_not_offer_is_refused(self):
d = self.deps()
with patch("dashboards.skills.catalog", return_value=self.CATALOG), \
self.assertRaises(ValueError):
hubcatalog.share_skill(d, "../secrets", True)
self.assertEqual(d.users.shared, [])
class TestRun(_Base):
def test_run_goes_through_the_agent_run_route(self):
seen = {}
def fake(deps, name, body):
seen.update(name=name, prompt=body.prompt)
return {"sessionId": "s-123"}
with patch.object(self.deps, "plugin_store", self.store()), \
patch("agents.routes.agent_run", fake):
r = self.tc.post(f"/proxy/tools/plugins/{PID}/hub/agents/radar/run",
json={"prompt": "check the queue"}, headers=self.owner())
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(r.json(), {"sessionId": "s-123"})
self.assertEqual(seen, {"name": "radar", "prompt": "check the queue"})
def test_run_is_for_the_plugins_own_handlers_only(self):
"""A run's tool token (an agent's skill calling the bridge) may not
start runs: only the plugin's own handler token."""
owner_run = access.mint(OWNER_UID, ttl=600)
with patch.object(self.deps, "plugin_store", self.store()), \
patch("agents.routes.agent_run") as fake:
r = self.tc.post(f"/proxy/tools/plugins/{PID}/hub/agents/radar/run", json={},
headers={"Authorization": f"Bearer {owner_run}"})
self.assertEqual(r.status_code, 403)
self.assertEqual(r.json()["error"]["kind"], "handler_only")
fake.assert_not_called()
def test_schedule_makes_a_cron_job_on_the_definition(self):
seen = {}
def fake(deps, **kw):
seen.update(kw)
return {"id": "j1", "schedule": kw["schedule"]}
with patch.object(self.deps, "plugin_store", self.store()), \
patch("agents.routes._agent_entry", return_value={"name": "radar", "path": ".claude/agents/radar.md"}), \
patch("plugins.cron_bridge.create", fake):
r = self.tc.post(f"/proxy/tools/plugins/{PID}/hub/agents/radar/schedule",
json={"schedule": "0 9 * * *"}, headers=self.owner())
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(seen["prompt_file"], ".claude/agents/radar.md")
self.assertEqual(seen["name"], "radar")
self.assertEqual(seen["schedule"], "0 9 * * *")
def test_a_nested_definition_cannot_be_scheduled(self):
with patch.object(self.deps, "plugin_store", self.store()), \
patch("agents.routes._agent_entry", return_value={"name": "x", "path": ".claude/agents/hooks/x.md"}), \
patch("plugins.cron_bridge.create") as fake:
r = self.tc.post(f"/proxy/tools/plugins/{PID}/hub/agents/x/schedule",
json={"schedule": "0 9 * * *"}, headers=self.owner())
self.assertEqual(r.status_code, 400)
fake.assert_not_called()
class TestRealRoutes(unittest.TestCase):
def test_the_routes_take_what_the_bridges_pass(self):
"""Checked on the real functions, not stubs: a route that grows a
required parameter must not 500 the bridge (graph.read's lesson)."""
import inspect
from agents.routes import agent_detail, agent_run, agents_list
from dashboards.routes import skill_prompt, skills_list
from plugins.graphdata import _unwrap
passed = {
skills_list: {"deps", "caller", "account"},
skill_prompt: {"deps", "caller", "name"},
agents_list: {"deps", "caller", "account"},
agent_detail: {"deps", "caller", "name", "account"},
agent_run: {"deps", "name", "body"},
}
for fn, given in passed.items():
sig = inspect.signature(_unwrap(fn))
required = {n for n, prm in sig.parameters.items() if prm.default is inspect.Parameter.empty}
self.assertLessEqual(required, given, fn.__name__)
if __name__ == "__main__":
unittest.main()