Files
ai-agent/backend/test_plugin_resources.py
gabrielvidalandClaude Opus 5.5 c8fa334528 refactor(resources): plugin-driven resource kinds — retire live PR polling and Profile.resources
Work Resources becomes generic core composition over declarative plugin
`resources[]`, ahead of the `github` / `linear` / `slack` plugins (Wave 2B-2).

- Core knows only `branch` and `url` (cli/resource_urls.py). Every link is
  mined raw, so the plugins' kinds apply at view time: installing a plugin
  lights up the whole archive with zero re-parse. Notion links are plain
  `url` pills.
- New backend/plugins/resources.py: PluginResourceRegistry compiled from the
  owner's active plugins' `resources[]` + each plugin's settings (workers,
  cwdGlobs, notifPills, channelMap, {config.*} templates); cached on the new
  PluginStore.version and kept by identity while unchanged.
- manifest.py: expanded, ReDoS-checked `resources[]` (urlRegex, idRegex,
  id/url/label templates, titleToken, bareKeyRegex + team gate,
  branchKeyPattern cross-links, ignoreUrlRegex, toolExtractors[], icon,
  color, stateTones, clickAction, priority, hueRole); the v3 shape and the
  approval fingerprint stay as they were.
- ResourceMiner runs declarative toolExtractors / bare keys in-process (no
  subprocess); legacy resourcesAuto / resourceTeams / slackChannels still read.
- resource_view: per-plugin scope, branchKeyPattern cross-linking, priority
  primary, generic `<lead> · <title> · <shade>` title; Context cached on
  (summaries, meta, registry) with per-transcript memo.
- look.subject → generic (hueKey, shadeKey) from hueRole; past.py generic.
- conv add/rm send raw links / keys; the hub's registry reads them.
- Removed: conversations/pr_state.py, sidecar/routes_gh.py (/gh/pr-states),
  deps.pr_states, Profile.resources + Orus defaults (dropped on load),
  GET /api/profiles/resource-directory, ProfileResourcesEditor + the
  Profile page's Tracking tab.
- Frontend pills read `ui.resources` descriptors (icon, tone, stateTones,
  clickAction); historical kinds keep a fallback. ResourceKind widens to str.
- Fixture manifests + test kit for the three plugins in
  backend/fixtures/resource_plugins/.

OpenAPI not re-dumped (coordinator does it after Batch 2).

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

141 lines
6.7 KiB
Python

"""Declarative ``resources[]`` in ``plugin.json`` (plugins/manifest.py) and the
registry built from them (plugins/resources.py): validation (the v3 shape
still valid, ReDoS-shaped regexes refused, bare keys gated on a team group),
the three fixture plugins, the UI descriptors, and the view's ``Context``
kept by identity while nothing it reads changed.
``python -m pytest test_plugin_resources.py`` from ``backend/``."""
import json
import pathlib
import tempfile
import types
import unittest
from conversations import resource_view as rv
from fixtures.resource_plugins.kit import FakePluginStore, manifest, registry
from plugins import resources as plugin_resources
from plugins.manifest import ManifestError, capability_fingerprint, validate_manifest
def validate(resources, **extra):
with tempfile.TemporaryDirectory() as d:
(pathlib.Path(d) / "plugin.json").write_text(json.dumps({
"schema": 1, "id": "t", "name": "T", "version": "1.0.0", "description": "t",
"resources": resources, **extra}))
return validate_manifest(pathlib.Path(d))
class TestManifest(unittest.TestCase):
def test_v3_shape_still_valid_and_fingerprint_unchanged(self):
mf = validate([{"id": "jira", "label": "Jira", "color": "#0052CC",
"urlRegex": "https://[a-z0-9-]+\\.atlassian\\.net/browse/([A-Z]+-\\d+)"}])
(r,) = mf["resources"]
self.assertEqual((r["id"], r["label"], r["color"], r["priority"], r["clickAction"]),
("jira", "Jira", "#0052CC", 100, "open"))
# The approval fingerprint reads (id, urlRegex) only, as before.
fp = capability_fingerprint(mf)
mf["resources"][0]["toolExtractors"] = [{"tool": "x", "idFields": ["id"]}]
self.assertEqual(capability_fingerprint(mf), fp)
def test_the_three_fixture_plugins_validate(self):
kinds = {p: [r["id"] for r in manifest(p)["resources"]]
for p in ("github", "linear", "slack")}
self.assertEqual(kinds, {"github": ["pr"], "linear": ["linear"], "slack": ["slack"]})
lin = manifest("linear")["resources"][0]
self.assertEqual((lin["hueRole"], lin["priority"], lin["bareKeyTeamGroup"]),
("hue", 10, "team"))
def test_rejects(self):
bad = [
[{"id": "branch", "urlRegex": "x"}], # a core kind
[{"id": "x"}], # matches nothing
[{"id": "x", "urlRegex": "(a+)+$"}], # ReDoS shape
[{"id": "x", "urlRegex": "(\\w*)*"}],
[{"id": "x", "urlRegex": "x", "bareKeyRegex": "[A-Z]+-\\d+"}], # ungated bare keys
[{"id": "x", "urlRegex": "x", "clickAction": "run"}],
[{"id": "x", "urlRegex": "x", "priority": "high"}],
[{"id": "x", "urlRegex": "x", "hueRole": "tint"}],
[{"id": "x", "urlRegex": "x", "toolExtractors": [{"tool": "shell"}]}],
[{"id": "x", "urlRegex": "x", "toolExtractors": [
{"tool": "*", "channelMapRegex": "Channel: (\\w+)"}]}], # no id/name groups
[{"id": "x", "urlRegex": "x", "toolExtractors": [
{"tool": "*", "kind": "other", "idFields": ["id"]}]}], # not this plugin's kind
[{"id": "x", "urlRegex": "x", "labelTemplate": [{"match": "(", "template": "y"}]}],
[{"id": "x", "urlRegex": "x"}, {"id": "x", "urlRegex": "y"}], # duplicate
]
for b in bad:
with self.assertRaises(ManifestError, msg=b):
validate(b)
def test_safe_shapes_pass(self):
validate([{"id": "x", "urlRegex": "^https://a\\.io/(?:[\\w.-]+/)?(?P<n>\\d+)(?:-(?P<s>.+))?$",
"idTemplate": ["{n}", "#{n}"], "labelTemplate": [{"match": "^D", "template": ""},
{"template": "#{n}"}]}])
class TestRegistry(unittest.TestCase):
def test_descriptors_for_the_ui(self):
d = {r["id"]: r for r in registry().descriptors()}
self.assertEqual(d["pr"], {"id": "pr", "label": "Pull request", "icon": "git-pull-request",
"color": "sky", "stateTones": {
"open": "emerald", "draft": "zinc", "merged": "violet",
"closed": "rose"},
"clickAction": "open", "priority": 20, "hueRole": "shade",
"pluginId": "github"})
self.assertNotIn("urlRegex", d["linear"]) # display data only
def test_settings_defaults_apply(self):
store = FakePluginStore(plugins=("github",), settings={})
store.rows["github"][0]["settings"]["fields"][0]["default"] = "acme/w"
reg = plugin_resources.registry(types.SimpleNamespace(plugin_store=store))
self.assertEqual(reg.parse_ref("#3")["id"], "acme/w#3")
def test_a_broken_record_never_breaks_cards(self):
reg = plugin_resources.build([("p", [{"id": "x", "urlRegex": "("}], {})])
self.assertFalse(reg)
def test_no_plugins_no_kinds(self):
reg = registry(plugins=())
self.assertEqual((reg.kinds, reg.scoped_kinds(None, "/"), reg.descriptors()),
(frozenset(), frozenset(), []))
class TestContextIdentity(unittest.TestCase):
def deps(self, summaries):
state = {"v": 1}
return types.SimpleNamespace(
plugin_store=FakePluginStore(), store=_Store(summaries, state),
meta_store=types.SimpleNamespace(version=1, items=lambda: [])), state
def test_same_object_while_nothing_it_reads_changed(self):
summaries = {"a": {"resourcesAuto": [{"kind": "url", "id": "u", "label": "u",
"url": "https://linear.app/orus/issue/INS-1"}]}}
deps, state = self.deps(summaries)
a = rv.context(deps)
self.assertEqual(a.teams, {"linear": frozenset({"INS"})}) # learned from a raw link
state["v"] += 1
summaries["b"] = {"resourcesAuto": [{"kind": "branch", "id": "x", "label": "x"}]}
self.assertIs(rv.context(deps), a) # taught nothing
state["v"] += 1
summaries["c"] = {"resourcesAuto": [{"kind": "url", "id": "v", "label": "v",
"url": "https://linear.app/orus/issue/TECH-2"}]}
b = rv.context(deps)
self.assertIsNot(b, a)
self.assertEqual(b.teams["linear"], {"INS", "TECH"})
class _Store:
def __init__(self, summaries, state):
self._s, self._state = summaries, state
@property
def summaries_version(self):
return self._state["v"]
def all_summaries(self):
return list(self._s.items())
if __name__ == "__main__":
unittest.main()