Files
ai-agent/cli/resource_urls.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

188 lines
7.2 KiB
Python

#!/usr/bin/env python3
"""Resource URLs — the core of what a conversation is *about*, parsed out of text.
A **resource** is a typed link. The core knows two kinds only:
* ``branch`` — a git branch the conversation works on;
* ``url`` — any other link a prompt, a tool call or the harness named.
Everything vendor-specific — a GitHub pull request, a Linear issue, a Slack
thread — is a **plugin** kind, declared in its ``plugin.json`` ``resources[]``
and matched by the backend's registry (``backend/plugins/resources.py``) —
mostly *at view time*, over the raw ``url`` records this module produces, so
installing a plugin lights up every past conversation without a re-parse.
Records look like::
{"kind": "url", "id": "3f1c…", "url": "https://example.org/a/b",
"label": "example.org/a/b"}
whose ``kind:id`` (:func:`key`) is the identity two mentions merge on. Shared
by the ``conv`` CLI (``notify.py``, on the lab and on a worker) and the
backend's transcript miner (``backend/conversations/resources.py`` — the image
ships this directory as ``/app/cli``), so **stdlib only**.
Pasted links carry junk the identity must not: a trailing ``,`` / ``.`` /
``)``, zsh's ``\\#``, a ``</command-args>`` tail, ``#fragment``s.
"""
from __future__ import annotations
import hashlib
import re
import urllib.parse
# The kinds the core itself produces; plugins add theirs.
KINDS = ("branch", "url")
# A URL in free text stops at whitespace, quotes, backticks, `<` (a closing
# tag) and `\` (zsh escapes the `#` of a pasted fragment as `\#`).
_URL_RE = re.compile(r"https?://[^\s<>\"'`\\]+")
_TRAILING = ",.;:!?)]}>'\"*_`"
# A `<key>-<n>-<slug>` branch typed in a prompt ("on this branch:
# ins-2171-pricing…") — the common issue-tracker branch convention.
_PROMPT_BRANCH_RE = re.compile(
r"(?<![\w/.-])((?:worktree-)?[a-z][a-z0-9]{1,6}-\d{1,6}-[a-z0-9][a-z0-9-]{2,})(?![\w/-])")
# Hosts whose links are never what a conversation is about.
_SKIP_HOSTS = ("localhost", "127.0.0.1", "0.0.0.0", "accounts.google.com",
"claude.com", "docs.anthropic.com",
# CDNs and font hosts: pasted allow-lists, never the subject
"cdnjs.cloudflare.com", "cdn.jsdelivr.net", "unpkg.com",
"cdn.tailwindcss.com", "code.jquery.com", "fonts.googleapis.com",
"fonts.gstatic.com")
BRANCH_IGNORE = ("main", "master", "HEAD", "develop", "dev", "trunk")
def key(r: dict) -> str:
"""A resource's identity: ``kind:id``."""
return f"{r.get('kind')}:{r.get('id')}"
def titleize(slug: str | None) -> str | None:
"""``separate-tenant-from-subtenant`` → ``Separate tenant from subtenant``
(URL slugs are often the title, lower-cased and cut)."""
words = [w for w in re.split(r"[-_\s]+", slug or "") if w]
if not words:
return None
s = " ".join(words)
return s[0].upper() + s[1:]
def trim(url: str) -> str:
url = (url or "").strip()
while url and url[-1] in _TRAILING:
url = url[:-1]
return url
def url_record(url: str, *, label: str | None = None) -> dict:
"""A plain link: its id is a hash of host + path + query (no fragment)."""
parts = urllib.parse.urlsplit(url)
canon = f"{parts.netloc.lower()}{parts.path.rstrip('/')}"
if parts.query:
canon += f"?{parts.query}"
rid = hashlib.sha1(canon.encode()).hexdigest()[:12]
clean = urllib.parse.urlunsplit((parts.scheme, parts.netloc, parts.path,
parts.query, ""))
if not label:
host = parts.netloc.lower().removeprefix("www.")
path = parts.path.rstrip("/")
label = host + (path if len(host + path) <= 40 else path[: max(0, 39 - len(host))] + "…")
return {"kind": "url", "id": rid, "url": clean, "label": label}
def parse_url(raw: str) -> dict | None:
"""One URL → a ``url`` record, or None for a link that is never a
resource (localhost, a sign-in page, a CDN, a bare domain…)."""
url = trim(raw)
try:
parts = urllib.parse.urlsplit(url)
except ValueError:
return None
host = (parts.hostname or "").lower()
if parts.scheme not in ("http", "https") or "." not in host or "<" in url:
return None
if host in _SKIP_HOSTS or host.endswith(".local"):
return None
if len(parts.path.strip("/")) < 2 and not parts.query:
return None # a bare domain is a site, not a thing to open
return url_record(url)
def branch(name: str) -> dict | None:
"""A git branch the conversation works on (never ``main`` & co)."""
name = (name or "").strip()
if not name or name in BRANCH_IGNORE or name.startswith("-") \
or not re.match(r"^[\w][\w./+-]*$", name) or ".." in name:
return None
return {"kind": "branch", "id": name, "url": None, "label": name}
def parse(raw: str, kind: str | None = None) -> dict | None:
"""What the ``conv`` CLI was handed, as a core resource: a URL (``url``)
or a branch name. ``kind`` forces the reading (``branch`` / ``url``);
any other kind is a plugin's, read by the hub (None here)."""
s = trim(raw)
if not s:
return None
if kind == "branch":
return branch(s)
if s.startswith(("http://", "https://")):
if kind not in (None, "url"):
return None
return parse_url(s)
if kind is None and " " not in s and "/" in s:
return branch(s) # `feature/foo` — a bare word may be a plugin key
return None
def url_spans(text: str) -> list[tuple[int, int]]:
"""Where the URLs sit in ``text`` (a bare key inside one is the URL's)."""
return [m.span() for m in _URL_RE.finditer(text or "")]
def find_all(text: str) -> list[dict]:
"""Every core resource mentioned in free text — its URLs and typed
``<key>-<n>-<slug>`` branches — in order of first appearance, one per
:func:`key`. Plugin bare keys (``INS-2229``) are the registry's."""
text = text or ""
found: list[tuple[int, dict]] = []
spans: list[tuple[int, int]] = []
for m in _URL_RE.finditer(text):
spans.append(m.span())
r = parse_url(m.group(0))
if r:
found.append((m.start(), r))
for m in _PROMPT_BRANCH_RE.finditer(text):
if any(a <= m.start() < b for a, b in spans):
continue
b = branch(m.group(1))
if b:
found.append((m.start(), b))
out: dict[str, dict] = {}
for _pos, r in sorted(found, key=lambda x: x[0]):
k = key(r)
out[k] = merge(out[k], r) if k in out else r
return list(out.values())
def merge(a: dict, b: dict) -> dict:
"""Two records of one resource: ``b``'s non-empty fields win, except that
the earliest ``firstSeen`` and any ``firstTurn`` stick, and a bare key
stops being bare once a real link names it."""
out = dict(a)
for k, v in b.items():
if v is None or v == "" or k in ("firstSeen", "firstTurn", "bare"):
continue
out[k] = v
fs = [x for x in (a.get("firstSeen"), b.get("firstSeen")) if x]
if fs:
out["firstSeen"] = min(fs)
if a.get("firstTurn") or b.get("firstTurn"):
out["firstTurn"] = True
if a.get("bare") and b.get("bare"):
out["bare"] = True
else:
out.pop("bare", None)
return out