Files
ai-agent/backend/test_conv_refs.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

131 lines
6.8 KiB
Python

"""Conversation references (conversations/refs.py): the cards the conv-ref
prompt hook shows — by id, session id, viewer link or prefix, the asker and
the invisible left out — a worker's ``lookup`` with ``ids``, and ``ai-agent
past <conversation>`` (past.py) looking up the issues that conversation is
about. ``python -m unittest test_conv_refs`` from ``backend/``."""
import pathlib
import tempfile
import types
import unittest
from unittest import mock
from conversations import catalog, past, refs
from conversations import related as related_mod
from db import Store
from fixtures.resource_plugins.kit import FakePluginStore
A = "01a1e40a-9907-7a32-81d4-6bfc5a8f6240"
B = "01a1e38b-1540-7b16-840e-01bf10351672"
C = "01a1e38d-9878-7000-8000-000000000000"
SA = "a2533c3a-d718-4823-80d0-70bf2939ba81"
def real_store(summaries: dict) -> Store:
"""The summaries in a real ``db.Store``, which keeps ``searchMsgs`` apart
from the summary (``search_json``) as production does — a fake that
hands them back inside the summary let a reader of the wrong one pass."""
st = Store(str(pathlib.Path(tempfile.mkdtemp()) / "t.db"))
for path, s in summaries.items():
st.upsert_transcript(path, 0.0, 0, {}, {"messages": 1, **s})
return st
def card(cid, sid, title, worker=None, resources=(), state="finished", profile=None):
return {"id": cid, "sessionId": sid, "title": title, "startedAt": "2026-11-16T11:07:42Z",
"endedAt": "2026-11-16T13:54:30Z", "firstPrompt": f"prompt of {title}",
"meta": {"state": state, "worker": worker, "account": "work", "projects": ["orus"],
"resources": list(resources), **({"profile": profile} if profile else {})}}
class Refs(unittest.TestCase):
def setUp(self):
self.cards = [
card(A, SA, "Linear metadata widget", worker="mac",
resources=[{"kind": "slack", "id": "C1/2", "url": "https://x.slack.com/archives/C1/p2",
"primary": True},
{"kind": "linear", "id": "INS-2613", "url": "https://linear.app/orus/issue/INS-2613"}]),
card(B, "b5555555-0000-4000-8000-000000000000", "Restore script dry run"),
card(C, "c6666666-0000-4000-8000-000000000000", "Personal thing", profile="personal"),
]
self.summaries = {
A: {"searchMsgs": [{"i": 0, "role": "user", "text": "build the widget\n\nGuidelines:\n- Send a push"},
{"i": 1, "role": "assistant", "text": "I'll start"},
{"i": 2, "role": "assistant", "text": "x" * 2000}]},
}
self.deps = types.SimpleNamespace(
store=real_store(self.summaries),
worker_store=types.SimpleNamespace(get=lambda wid: {
"mac": {"id": "mac", "name": "Orus Macbook"},
"guestpc": {"id": "guestpc", "owner": "dom"}}.get(wid)),
profile_store=types.SimpleNamespace(
resolve_ref=lambda w, a=None, e=None: {"resources": {}},
for_runner=lambda r: {"id": "work"},
of_meta=lambda m, a=None: m.get("profile") or "work"),
# access.visible reads the meta of the id's session (an unknown
# UUIDv7 reads as itself here)
meta_store=types.SimpleNamespace(
peek=lambda sid: {"profile": "personal"} if sid in (C, "c6666666-0000-4000-8000-000000000000") else {}),
plugin_store=FakePluginStore())
by_id = {c["id"]: c for c in self.cards}
self.patches = [mock.patch.object(catalog, "_conversation_cards", lambda d, full: self.cards),
mock.patch.object(refs, "_roots", lambda d: [(c["id"], c["sessionId"]) for c in self.cards]),
mock.patch.object(refs, "_load", lambda d, cid: by_id.get(cid)),
mock.patch.object(refs, "_conv_id", lambda p: p),
mock.patch.object(related_mod, "index", lambda d: {}),
mock.patch.object(past, "_conv_id", lambda p: p)]
for p in self.patches:
p.start()
def tearDown(self):
for p in self.patches:
p.stop()
def test_parse_refs(self):
self.assertEqual(refs.parse_refs(f"https://ai-agent.lab.gabvdl.xyz/conversation/{A}?m=3, {A.upper()} 01a1e3"),
[A, "01a1e3"])
self.assertEqual(refs.parse_refs(["not-an-id!", ""]), [])
def test_a_card_by_id_session_link_or_prefix(self):
for ref in (A, SA, f"https://ai-agent.gabvdl.xyz/conversation/{A}", "a2533c3a"):
out = refs.cards(self.deps, ref)
self.assertEqual([c["id"] for c in out["cards"]], [A], ref)
(c,) = refs.cards(self.deps, A)["cards"]
self.assertEqual((c["title"], c["machine"], c["account"], c["state"]),
("Linear metadata widget", "Orus Macbook", "work", "finished"))
self.assertEqual(c["firstPrompt"], "build the widget")
self.assertTrue(c["lastAnswer"].endswith("…") and len(c["lastAnswer"]) == refs.ANSWER_MAX)
self.assertTrue(c["url"].endswith(f"/conversation/{A}"))
self.assertNotIn("path", c) # paths never leave the backend
(b,) = refs.cards(self.deps, B)["cards"]
self.assertEqual((b["machine"], b["firstPrompt"], b["lastAnswer"]),
("lab", "prompt of Restore script dry run", None))
def test_ambiguous_unknown_short_and_the_asker(self):
out = refs.cards(self.deps, "01a1e3,ffffffff-0000-4000-8000-000000000000,01a1")
self.assertEqual(out["ambiguous"], [{"ref": "01a1e3", "count": 2}])
self.assertEqual(out["unknown"], ["ffffffff-0000-4000-8000-000000000000", "01a1"]) # too short
self.assertEqual(refs.cards(self.deps, A, session=SA)["unknown"], [A]) # never itself
def test_visibility(self):
out = refs.cards(self.deps, f"{A},{B}", visible=lambda cid: cid != B)
self.assertEqual(([c["id"] for c in out["cards"]], out["unknown"]), ([A], [B]))
def test_worker_lookup_with_ids_is_its_profiles(self):
ok = past.outbox_lookup(self.deps, {"worker": "mac", "sessionId": "me", "ids": [A, C]})
self.assertTrue(ok["ok"])
self.assertEqual([c["id"] for c in ok["result"]["cards"]], [A])
self.assertEqual(ok["result"]["unknown"], [C]) # Personal: not the Mac's
no = past.outbox_lookup(self.deps, {"worker": "guestpc", "sessionId": "s", "ids": [A]})
self.assertTrue(no["failed"])
def test_past_takes_a_conversation(self):
out = past.lookup(self.deps, [A])
self.assertEqual([s["key"] for s in out["subjects"]], ["linear:INS-2613"]) # not its Slack
out = past.lookup(self.deps, [B])
self.assertEqual((out["subjects"], out["skipped"]), ([], [B])) # about nothing
if __name__ == "__main__":
unittest.main()