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

322 lines
17 KiB
Python

"""The transcript resource miner (conversations/resources.py) on records shaped
like the real work transcripts: spawned prompts with a guidelines tail, slash
commands, shared-checkout branch drift, reused worktrees, gh/Linear/Slack
lookups — the vendor parts through the ``github`` / ``linear`` / ``slack``
plugins' declarative ``resources[]`` (fixtures/resource_plugins/), and what
the card view (resource_view.py) makes of it. ``python -m pytest
test_resources.py`` from ``backend/``."""
import json
import pathlib
import tempfile
import unittest
from conversations import resource_view as rv
from conversations.parse import parse_conversation
from conversations.resources import ResourceMiner
from fixtures.resource_plugins.kit import FakePluginStore, bound, registry
from plugins import resources as plugin_resources
ORUS = "/Users/gabrielvidal/WORK/ORUS/orus"
WT = ORUS + "/.claude/worktrees/ins-2007-session-context"
PR = "https://github.com/orus-tech/orus-monorepo/pull/"
class T:
"""A tiny transcript builder."""
def __init__(self):
self.recs, self.n = [], 0
def _ts(self):
self.n += 1
return f"2026-10-13T10:{self.n // 60:02d}:{self.n % 60:02d}.000Z"
def user(self, text, cwd=ORUS, branch="main", **extra):
self.recs.append({"type": "user", "timestamp": self._ts(), "cwd": cwd,
"gitBranch": branch, "sessionId": "s",
"message": {"role": "user", "content": text}, **extra})
return self
def tool(self, name, inp, result, cwd=ORUS, branch="main", tid=None):
tid = tid or f"toolu_{self.n}"
self.recs.append({"type": "assistant", "timestamp": self._ts(), "cwd": cwd,
"gitBranch": branch, "sessionId": "s",
"message": {"id": f"m{self.n}", "role": "assistant",
"model": "claude-opus-5-5", "content": [
{"type": "tool_use", "id": tid, "name": name,
"input": inp}]}})
self.recs.append({"type": "user", "timestamp": self._ts(), "cwd": cwd,
"gitBranch": branch, "sessionId": "s",
"message": {"role": "user", "content": [
{"type": "tool_result", "tool_use_id": tid,
"content": result}]}})
return self
def raw(self, rec):
self.recs.append(rec)
return self
def parse(self, store=None):
"""Parsed while the fixture plugins are active (``store``: others)."""
with tempfile.TemporaryDirectory() as d, bound(store):
p = pathlib.Path(d) / "11111111-2222-3333-4444-555555555555.jsonl"
p.write_text("\n".join(json.dumps(r) for r in self.recs) + "\n")
return parse_conversation(p)
def keys(s, first_only=False):
"""What the miner stored."""
return [f"{r['kind']}:{r['id']}" for r in s["resourcesAuto"]
if r.get("firstTurn") or not first_only]
def view(s, reg=None, archive_teams=("INS",)):
"""What a card shows of one summary, the fixture plugins active and in
scope: what this transcript taught (teams / names / xrefs) plus the Linear
teams the rest of the archive has seen in real links."""
reg = reg or registry()
teams, *rest = rv._derive(reg, s)
teams = {k: set(v) for k, v in teams.items()}
teams.setdefault("linear", set()).update(archive_teams)
ctx = rv.Context(reg, teams, *rest)
return rv.merge(s["resourcesAuto"], [], [], ctx, reg.kinds, True)
def vkeys(s, first_only=False, reg=None):
return [f"{r['kind']}:{r['id']}" for r in view(s, reg)
if r.get("firstTurn") or not first_only]
class TestPrompts(unittest.TestCase):
def test_spawned_prompt_drops_the_guidelines_tail(self):
s = T().user(f"check this PR {PR}13694,\nin link with this thread maybe ?\n"
"https://orus-insurance.slack.com/archives/C03AQQ21WFL/p1792030252499889"
"\n\nGuidelines:\n- Send a push notification (notify-done) when you finish."
"\n- see https://ai-agent.lab.gabvdl.xyz/x/y").parse()
# Stored raw: two links of the first turn, the guideline's dropped…
self.assertEqual([r["kind"] for r in s["resourcesAuto"]], ["url", "url"])
self.assertTrue(all(r["firstTurn"] for r in s["resourcesAuto"]))
# …matched by the plugins at view time.
self.assertEqual(sorted(vkeys(s, first_only=True)),
["pr:orus-tech/orus-monorepo#13694",
"slack:C03AQQ21WFL/1792030252.499889"])
def test_slash_command_args(self):
s = T().user("<command-message>babysit-pr</command-message>\n<command-name>/babysit-pr"
f"</command-name>\n<command-args>{PR}13172</command-args>").parse()
self.assertEqual(vkeys(s, True), ["pr:orus-tech/orus-monorepo#13172"])
def test_later_turn_is_not_first_turn(self):
s = T().user("hello").user(f"now look at {PR}13258").parse()
self.assertEqual(vkeys(s), ["pr:orus-tech/orus-monorepo#13258"])
self.assertEqual(vkeys(s, True), [])
def test_compact_summary_is_not_mined(self):
s = T().user("hi").user(f"This session is being continued… {PR}1", isCompactSummary=True).parse()
self.assertEqual(keys(s), [])
def test_bare_keys_need_the_plugin_and_a_team_seen_in_a_real_link(self):
text = "fix INS-2175, dates are ISO-8601 https://linear.app/orus/issue/INS-1/x"
s = T().user(text).parse()
self.assertIn("linear:INS-2175", keys(s))
self.assertIn("linear:ISO-8601", keys(s)) # stored bare…
self.assertEqual(sorted(k for k in keys(s) if k.startswith("linear:")),
["linear:INS-2175", "linear:ISO-8601"])
got = [f"{r['kind']}:{r['id']}" for r in view(s, archive_teams=())]
self.assertEqual(sorted(got), ["linear:INS-1", "linear:INS-2175"]) # …gated
# Without the linear plugin the miner reads no keys at all.
s2 = T().user(text).parse(store=FakePluginStore(plugins=("github",)))
self.assertEqual([r["kind"] for r in s2["resourcesAuto"]], ["url"])
class TestZeroReindex(unittest.TestCase):
def test_links_parsed_before_any_plugin_light_up_when_one_is_installed(self):
# Parsed with no resource plugin at all: raw links only.
s = T().user(f"review {PR}13722 and https://linear.app/orus/issue/INS-2229/sep-tenant"
).parse(store=FakePluginStore(plugins=()))
self.assertEqual([r["kind"] for r in s["resourcesAuto"]], ["url", "url"])
# The same stored summary, viewed once github + linear are installed.
self.assertEqual(sorted(vkeys(s)), ["linear:INS-2229", "pr:orus-tech/orus-monorepo#13722"])
# Only github: the Linear link stays a plain link.
self.assertEqual(sorted(r["kind"] for r in view(s, registry(plugins=("github",)))),
["pr", "url"])
def test_legacy_summaries_still_show(self):
# A summary the old hardcoded miner wrote (resourcesAuto of kinds
# pr / linear / notion, `resourceTeams`, `slackChannels`).
s = {"resourcesAuto": [
{"kind": "linear", "id": "INS-2229", "label": "INS-2229", "team": "INS",
"url": "https://linear.app/orus/issue/INS-2229", "firstTurn": True, "source": "auto"},
{"kind": "pr", "id": "#13722", "label": "#13722", "number": 13722, "repo": None,
"url": None, "source": "auto"},
{"kind": "notion", "id": "3cf0ab24de31814bb058d2aa9d124dac", "label": "Ouverture DROM",
"url": "https://app.notion.com/p/orus-team/Ouverture-DROM-3cf0ab24de31814bb058d2aa9d124dac",
"slugTitle": "Ouverture DROM", "source": "auto"},
{"kind": "slack", "id": "C02GDHPF1RR/1791878511.818179", "label": "#C02GDHPF1RR",
"channel": "C02GDHPF1RR", "ts": "1791878511.818179", "url": None, "source": "auto"}],
"resourceTeams": ["INS"], "slackChannels": {"C02GDHPF1RR": "product-requests"}}
by = {f"{r['kind']}:{r['id']}": r for r in view(s)}
self.assertEqual(by["pr:orus-tech/orus-monorepo#13722"]["url"], # repo from settings
"https://github.com/orus-tech/orus-monorepo/pull/13722")
self.assertEqual(by["slack:C02GDHPF1RR/1791878511.818179"]["label"], "#product-requests")
notion = [r for r in by.values() if r["kind"] == "url"]
self.assertEqual([(r["label"], r.get("title")) for r in notion], # a plain link
[("Ouverture DROM", "Ouverture DROM")])
class TestBranches(unittest.TestCase):
def test_shared_checkout_drift_is_never_tagged(self):
s = T().user("fix the session context error", branch="ins-2010-legal-access").parse()
self.assertNotIn("branch:ins-2010-legal-access", keys(s))
def test_enter_worktree_then_rename(self):
s = (T().user("fix INS-2007", branch="ins-2010-legal-access")
.tool("EnterWorktree", {"name": "ins-2007-session-context"}, "ok")
.tool("Bash", {"command": "git status"}, "", cwd=WT,
branch="worktree-ins-2007-session-context")
.tool("Bash", {"command": "git branch -m ins-2007-technicalerror-the-session"},
"", cwd=WT, branch="worktree-ins-2007-session-context")
.tool("Bash", {"command": "ls"}, "", cwd=WT, branch="ins-2007-technicalerror-the-session")
.parse())
ks = vkeys(s)
self.assertIn("branch:ins-2007-technicalerror-the-session", ks)
self.assertNotIn("branch:worktree-ins-2007-session-context", ks)
self.assertNotIn("branch:ins-2010-legal-access", ks)
self.assertIn("linear:INS-2007", ks)
def test_reused_worktree_drops_the_issue_only_its_old_branch_named(self):
s = (T().user("certificates bug https://linear.app/orus/issue/INS-1")
.tool("Bash", {"command": "ls"}, "", cwd=WT, branch="ins-2229-separate-tenant")
.tool("Bash", {"command": "ls"}, "", cwd=WT, branch="ins-2224-mrp-aig-certificates")
.parse())
ks = vkeys(s)
self.assertEqual(sorted(k for k in ks if k != "linear:INS-1"),
["branch:ins-2224-mrp-aig-certificates", "linear:INS-2224"])
def test_git_commands(self):
s = (T().user("go")
.tool("Bash", {"command": "git checkout -- packages/a.ts && git checkout .claude/settings.json"}, "")
.tool("Bash", {"command": "git checkout -q -b ins-2165-fr-prel-reset origin/main"}, "")
.tool("Bash", {"command": "cd $S && git init -q -b main repo && git worktree add -q ../wt feat"}, "")
.tool("Bash", {"command": "git worktree add --detach $T ins-2171-x"}, "")
.tool("Bash", {"command": "git switch dev-checks-panel 2>/dev/null"}, "")
.parse())
ks = keys(s)
self.assertIn("branch:ins-2165-fr-prel-reset", ks)
self.assertIn("branch:dev-checks-panel", ks)
self.assertNotIn("branch:feat", ks)
self.assertFalse(any("packages" in k or "settings" in k or "ins-2171" in k for k in ks), ks)
class TestLookups(unittest.TestCase):
def test_gh_pr_view_links_the_issue_first_turn(self):
gh = json.dumps({"body": "closes INS-2229\r\n\r\n## Release message", "headRefName":
"ins-2229-separate-tenant-from-subtenant", "state": "OPEN",
"title": "feat(mrp): separate tenant from subtenant",
"url": PR + "13722"})
s = (T().user(f"review {PR}13722 https://linear.app/orus/issue/INS-1")
.tool("Bash", {"command": "gh pr view 13722 --json title,body,headRefName,state,url"},
gh + "\n[{\"path\":\"x\"}]")
.parse())
info = s["resourceInfo"]["pr:orus-tech/orus-monorepo#13722"]
self.assertEqual((info["title"], info["state"]),
("feat(mrp): separate tenant from subtenant", "open"))
self.assertEqual(info["xref"], ["ins-2229-separate-tenant-from-subtenant", "INS-2229"])
by = {f"{r['kind']}:{r['id']}": r for r in view(s)}
# The issue the PR is for — the github and linear plugins never import
# each other: linear's branchKeyPattern reads github's head branch.
lin = by["linear:INS-2229"]
self.assertTrue(lin["firstTurn"])
self.assertEqual(lin["via"], "xref")
self.assertEqual(by["pr:orus-tech/orus-monorepo#13722"]["title"],
"feat(mrp): separate tenant from subtenant")
def test_bare_gh_number_takes_the_sessions_repo(self):
s = (T().user("go")
.tool("Bash", {"command": "gh pr checks 13449"}, "ok")
.raw({"type": "pr-link", "sessionId": "s", "prNumber": 13450,
"prUrl": PR + "13450", "prRepository": "acme/widgets",
"timestamp": "2026-10-13T11:00:00.000Z"})
.parse())
# The pr-link's repo is the transcript's (sticky), over the settings'.
self.assertEqual(sorted(vkeys(s)), ["pr:acme/widgets#13449", "pr:acme/widgets#13450"])
def test_linear_get_issue_and_moved_issue(self):
res = json.dumps({"id": "INS-2007", "title": "TechnicalError: The session context",
"url": "https://linear.app/orus/issue/INS-2007/technicalerror",
"status": "Todo", "labels": ["Bug"], "project": {"name": "Session"},
"team": "Insurance"})
s = T().user("TECH-5027 please").tool("mcp__linear__get_issue", {"id": "TECH-5027"},
res).parse()
by = {f"{r['kind']}:{r['id']}": r for r in view(s)}
self.assertEqual(by["linear:INS-2007"]["title"], "TechnicalError: The session context")
self.assertEqual(by["linear:INS-2007"]["state"], "Todo")
self.assertEqual(s["resourceInfo"]["linear:TECH-5027"]["title"],
"TechnicalError: The session context")
self.assertEqual({k: s["resourceInfo"]["linear:INS-2007"][k]
for k in ("labels", "project", "team")},
{"labels": ["Bug"], "project": "Session", "team": "Insurance"})
self.assertNotIn("linear:TECH-5027", by) # TECH: no real link named that team
def test_slack_reads_and_channel_names(self):
search = ("## Messages (20 results)\n### Result 1 of 20\nChannel: #product-requests "
"(ID: C02GDHPF1RR)\nFrom: x\n… moved to <#C03AQQ21WFL|tech-alerts>")
s = (T().user("look")
.tool("mcp__claude_ai_Slack__slack_search_public_and_private", {"query": "x"},
[{"type": "text", "text": search}])
.tool("mcp__claude_ai_Slack__slack_read_thread",
{"channel_id": "C02GDHPF1RR", "message_ts": "1791878511.818179"}, "{}")
.parse())
self.assertEqual(s["resourceNames"], {"C02GDHPF1RR": "product-requests",
"C03AQQ21WFL": "tech-alerts"})
self.assertEqual(keys(s), ["slack:C02GDHPF1RR/1791878511.818179"])
self.assertEqual([r["label"] for r in view(s)], ["#product-requests"])
def test_notify_text_names_the_issue(self):
s = (T().user("go https://linear.app/orus/issue/INS-1")
.tool("Bash", {"command": 'notify-done "✅ INS-2224 fixed" "certs ok" --url https://x.io/a/b'},
"sent").parse())
self.assertEqual(sorted(k for k in keys(s) if not k.startswith("url:")),
["linear:INS-2224"])
self.assertEqual(len([k for k in keys(s) if k.startswith("url:")]), 1) # the prompt's
def test_no_subprocess_no_plugin_code(self):
# The miner never shells out: extractors are data run in-process.
import subprocess
orig = subprocess.run
subprocess.run = lambda *a, **k: (_ for _ in ()).throw(AssertionError("shelled out"))
try:
m = ResourceMiner(registry())
m.feed_events([{"t": "tool_call", "tool": "shell", "id": "t1",
"input": {"command": "gh pr view 7 --repo o/r"}}])
m.feed_events([{"t": "tool_result", "toolCall": "t1", "text": "title:\tX\nstate:\tMERGED"}])
finally:
subprocess.run = orig
self.assertEqual(m.summary()["resourceInfo"]["pr:o/r#7"], {"title": "X", "state": "merged"})
class TestRegistry(unittest.TestCase):
def test_cached_on_the_store_version_and_kept_while_unchanged(self):
store = FakePluginStore()
deps = __import__("types").SimpleNamespace(plugin_store=store)
a = plugin_resources.registry(deps)
store.version += 1 # a write that changed nothing it reads
self.assertIs(plugin_resources.registry(deps), a)
store.configure("github", githubRepo="acme/widgets")
b = plugin_resources.registry(deps)
self.assertIsNot(b, a)
self.assertEqual(b.version, a.version + 1)
self.assertEqual(b.parse_ref("#1")["id"], "acme/widgets#1")
def test_templates(self):
r = plugin_resources.render
self.assertEqual(r("{a|b}-{c:upper}", {"b": "x", "c": "y"}), "x-Y")
self.assertEqual(r("{{config.ws}}/{n}", {"n": "1"}, {"ws": "orus"}), "orus/1")
self.assertIsNone(r("{repo|config.repo}#{n}", {"n": "1"}, {}))
self.assertEqual(r("{repo}#{n}", {"n": "1"}, {}, sticky={"repo": "o/r"}), "o/r#1")
if __name__ == "__main__":
unittest.main()