Files
gabrielvidalandClaude Opus 5.5 618b17f6c2 feat(look): Linear projects — the card's colour and icon, a project pill
A resource plugin can declare a `hueRole: group` kind — what an issue
belongs to (a Linear project); its issue kind names it with `groupBy`.
The linear plugin's `linear-project` uses it (plugin 1.1.0, ai-agent-plugins
branch linear-projects). Decided in form linear-projects-icons-colour_yfnahd.

- Lookups only: get_project and list_projects (a new extractor field,
  `itemsPath: projects[]`, reads each item of a listing without tagging
  the conversation) teach Linear's icon and colour; `vendor_icons` turns
  `Brush` / `:heavy_plus_sign:` into glyph keys (`brush`, `emoji:➕`,
  gemoji table vendored). PARSER_VERSION 47 re-mines past lookups.
- Colour (`cardColour: group`, the default): a card wears its issue's
  project colour, each issue of the project a shade (`LookColors.group_color`,
  `shade_hex` ≡ the PWA's `shadeHex`); a palette hue when Linear's is
  unknown; an issue with no known project keeps issue + PR colours.
  A Settings → Tags colour on `linear:project/<name>` wins (the PWA
  re-shades it with `colorGroup` / `colorShade`); *Colour…* on such a card
  writes that tag.
- Icon (`iconOrder: group`): project › label › team; the project's tag
  icon, else Linear's own.
- Pill (`groupPills`): the issue's project beside it, in its own icon and
  colour (`Resource.icon` / `color`; the glyph is tinted, not the pill).
- `groupLooks` off: only what Settings → Tags sets.
- Emoji tag icons (`emoji:<char>`), Linear's look as a project tag's
  derived default in Settings → Tags, the mock seeds two projects.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:50:11 +01:00

658 lines
28 KiB
Python

"""The conversation resource registry: every resource kind the owner's active
plugins declare (``plugin.json`` ``resources[]``), compiled once and matched
in-process — no plugin code ever runs for it.
The core knows two kinds, ``branch`` and ``url`` (``cli/resource_urls.py``).
A plugin adds its own — ``github`` a ``pr``, ``linear`` a ``linear`` issue,
``slack`` a ``slack`` thread — as pure data (docs/plugins.md → "Resources"):
* **matching** — ``urlRegex`` (a link → the kind), ``idRegex`` (an id → its
groups), ``bareKeyRegex`` (``INS-2229`` in a prompt, gated on the teams
seen in real links so ``UTF-8`` never counts), ``branchKeyPattern`` (a git
branch / a PR's head names one: ``ins-2229-slug`` → ``INS-2229``) and
``toolExtractors[]`` (what a tool call and its result say: ``gh pr view``,
``get_issue``, Slack channel names);
* **shape** — ``idTemplate`` / ``urlTemplate`` / ``labelTemplate`` /
``titleToken`` over the match's groups and the plugin's own settings
(``{num}``, ``{repo|config.githubRepo}``, ``{{config.linearWorkspace}}``,
``{team:upper}``), ``slugTitleGroup``, ``namesGroup`` (a group whose
display name is learned — Slack channel ids), ``dateGroup``;
* **look** — ``icon``, ``color``, ``stateTones``, ``clickAction``,
``priority`` (lower = the primary first), ``hueRole`` (``hue`` / ``shade``:
the card colour's issue + PR; ``group``: what an issue belongs to — a
Linear project — named by the hue kind's ``groupBy`` lookup field; its
own icon / colour come from its lookups — conversations/look.py).
A plugin with a ``group`` kind also sets how cards look (:class:`LookPrefs`):
``cardColour``, ``iconOrder``, ``groupPills``, ``groupLooks``.
Each plugin's **settings** scope it: ``workers`` (runner ids; ``local`` = the
lab) and ``cwdGlobs`` — empty = every conversation — ``notifPills`` (pills on
its conversations' pushes) and ``channelMap`` (``C0123=name`` lines); any
other text setting is ``{config.<key>}`` in its templates.
Most matching happens **at view time** (``conversations/resource_view.py``)
over the raw ``url`` / ``branch`` records the transcript miner stored, so a
newly installed plugin lights up every past conversation without a re-parse;
bare keys and tool extractors run in the miner (``conversations/resources.py``)
for what it parses from then on. :func:`registry` is cached on
``PluginStore.version`` and keeps its object (and ``version``) while the
resource declarations and settings are unchanged — the cards' memo keys on it.
"""
from __future__ import annotations
import datetime
import fnmatch
import json
import os
import re
import threading
from typing import Any
from conversations.resources import ru
CORE_KINDS = ("branch", "url")
DEFAULT_PRIORITY = 100
# What a record keeps through a re-shape (where and when it was found, what
# a lookup or a session said about it).
_KEEP = ("source", "via", "firstSeen", "firstTurn", "primary", "title", "state",
"checks", "reviewDecision", "bare", "headRefName", "slugTitle", "at")
_PH_RE = re.compile(r"\{\{\s*([^{}]+?)\s*\}\}|\{([^{}]+)\}")
_CLOSES_RE = re.compile(r"\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+(\S{2,80})", re.I)
_LIST_SPLIT_RE = re.compile(r"[,\n]+")
# ── templates ────────────────────────────────────────────────────────────────
def _filter(v: str, f: str) -> str:
if f == "upper":
return v.upper()
if f == "lower":
return v.lower()
if f == "nodot":
return v.replace(".", "")
if f == "title":
return ru.titleize(v) or v
return v
def _value(expr: str, groups: dict, config: dict, sticky: dict | None) -> str | None:
expr, _, filt = expr.strip().partition(":")
for alt in expr.split("|"):
alt = alt.strip()
if alt.startswith("config."):
v = config.get(alt[7:])
else:
v = groups.get(alt)
if (v is None or v == "") and sticky:
v = sticky.get(alt)
if isinstance(v, bool):
continue
if isinstance(v, (int, float)):
v = str(v)
if isinstance(v, str) and v.strip():
return _filter(v.strip(), filt.strip())
return None
def render(tpl: str | None, groups: dict, config: dict | None = None,
sticky: dict | None = None) -> str | None:
"""``{a|b|config.c:upper}`` placeholders (``{{config.c}}`` too) filled
from the groups, the transcript's sticky groups, the plugin's settings —
None when any placeholder resolves to nothing."""
if tpl is None:
return None
config = config or {}
missing = False
def sub(m: re.Match) -> str:
nonlocal missing
v = _value(m.group(1) or m.group(2), groups, config, sticky)
if v is None:
missing = True
return ""
return v
out = _PH_RE.sub(sub, tpl)
return None if missing else out
def render_first(tpls, groups: dict, config: dict | None = None,
sticky: dict | None = None) -> str | None:
for t in tpls or ():
v = render(t, groups, config, sticky)
if v:
return v
return None
def _rules(rules, rid: str, groups: dict, config: dict) -> str | None:
"""The first rule whose ``match`` hits the id; ``""`` = deliberately none."""
for rule in rules or ():
rx = rule.get("_rx")
if rx is not None and not rx.search(rid or ""):
continue
return render(rule["template"], groups, config) if rule["template"] else ""
return None
def _groups(m: re.Match | None) -> dict:
if m is None:
return {}
g = {k: v for k, v in m.groupdict().items() if v not in (None, "")}
for i, v in enumerate(m.groups(), 1):
if v not in (None, ""):
g.setdefault(str(i), v)
g.setdefault("0", m.group(0))
return g
# ── settings (each plugin's scope) ───────────────────────────────────────────
def _as_list(v) -> list[str]:
if isinstance(v, str):
v = _LIST_SPLIT_RE.split(v)
if not isinstance(v, list):
return []
return [x.strip() for x in v if isinstance(x, str) and x.strip()]
def channel_map(v) -> dict[str, str]:
"""``channelMap``: ``{id: name}``, or ``id=name`` / ``id: name`` lines."""
out: dict[str, str] = {}
if isinstance(v, dict):
items = list(v.items())
else:
items = []
for line in _as_list(v):
k, sep, name = line.replace(":", "=", 1).partition("=")
if sep:
items.append((k, name))
for k, name in items:
if isinstance(k, str) and isinstance(name, str) and k.strip() and name.strip():
out[k.strip()] = name.strip().lstrip("#@")[:80]
return out
class LookPrefs:
"""How the plugin that declares a ``hueRole: group`` kind (the linear
plugin's projects) wants cards to look — its settings:
* ``cardColour`` — ``group`` (default): a card wears its issue's group
colour, each issue a shade of it; ``hue``: one colour per issue, its
PRs shades (the look before groups);
* ``iconOrder`` — ``group`` (default): the group's icon beats the
issue's labels and team; ``label``: labels first;
* ``groupPills`` — the group as a pill next to its issue (default on);
* ``groupLooks`` — the vendor's own icon and colour of a group (Linear's
project icon / colour, from lookups; default on). Off: only what the
owner sets in Settings → Tags."""
__slots__ = ("colour_by", "icon_order", "group_pills", "group_looks")
def __init__(self, config: dict | None = None):
c = config or {}
self.colour_by = "hue" if c.get("cardColour") == "hue" else "group"
self.icon_order = "label" if c.get("iconOrder") == "label" else "group"
self.group_pills = c.get("groupPills") is not False
self.group_looks = c.get("groupLooks") is not False
class Scope:
"""Which conversations a plugin's resources show on: its runner in
``workers`` and its cwd under ``cwdGlobs`` — an empty list = any."""
__slots__ = ("workers", "globs", "notif_pills")
def __init__(self, config: dict):
self.workers = frozenset(_as_list(config.get("workers")))
self.globs = tuple(os.path.expanduser(g) for g in _as_list(config.get("cwdGlobs")))
self.notif_pills = bool(config.get("notifPills"))
def matches(self, worker: str | None, cwd: str | None) -> bool:
if self.workers and (worker or "local") not in self.workers:
return False
if self.globs and not any(fnmatch.fnmatchcase(cwd or "", g) for g in self.globs):
return False
return True
# ── one resource kind ────────────────────────────────────────────────────────
def _rx(p: str | None):
return re.compile(p) if p else None
class Extractor:
"""One ``toolExtractors[]`` rule: what a tool call (and its result) says
about a resource of ``kind`` — pure data, run by the miner."""
def __init__(self, d: "ResourceDef", item: dict):
self.d = d # re-pointed to its kind's def by the registry
self.kind = item.get("kind") or d.kind
self.tool = item["tool"]
self.cmd_rx = _rx(item.get("commandRegex"))
self.input_tpl = item.get("inputTemplate")
self.id_fields = tuple(item.get("idFields") or ())
self.url_fields = tuple(item.get("urlFields") or ())
self.title_fields = tuple(item.get("titleFields") or ())
self.state_fields = tuple(item.get("stateFields") or ())
self.xref_fields = tuple(item.get("xrefFields") or ())
self.meta_fields = dict(item.get("metaFields") or {})
self.state_flags = dict(item.get("stateFlags") or {})
self.items_path = item.get("itemsPath")
self.names_rx = tuple(re.compile(p) for p in item.get("channelMapRegex") or ())
self.hint = tuple(item.get("textHint") or ())
self.tag_on_call = bool(item.get("tagOnCall"))
self.wants_result = bool(self.id_fields or self.url_fields or self.title_fields
or self.state_fields or self.xref_fields or self.meta_fields)
def matches(self, tool: str) -> bool:
if self.tool == "*":
return True
if self.tool == "shell":
return tool == "shell"
return fnmatch.fnmatchcase(tool or "", self.tool)
def names(self, text: str) -> dict[str, str]:
if not self.names_rx or (self.hint and not any(h in text for h in self.hint)):
return {}
out = {}
for rx in self.names_rx:
for m in rx.finditer(text):
out[m.group("id")] = m.group("name")
return out
class ResourceDef:
"""A compiled ``resources[]`` entry of one plugin, with its settings."""
def __init__(self, pid: str, item: dict, config: dict):
self.plugin = pid
self.kind = item["id"]
self.label = item.get("label") or self.kind
self.url_rx = _rx(item.get("urlRegex"))
self.id_rx = _rx(item.get("idRegex"))
self.bare_rx = _rx(item.get("bareKeyRegex"))
self.branch_rx = _rx(item.get("branchKeyPattern"))
self.ignore_rx = _rx(item.get("ignoreUrlRegex"))
idt = item.get("idTemplate")
self.id_tpls = tuple([idt] if isinstance(idt, str) else (idt or ()))
self.url_tpl = item.get("urlTemplate")
self.label_rules = self._compile_rules(item.get("labelTemplate"))
self.token_rules = self._compile_rules(item.get("titleToken"))
self.slug_group = item.get("slugTitleGroup")
self.team_group = item.get("bareKeyTeamGroup")
self.names_group = item.get("namesGroup")
self.date_group = item.get("dateGroup")
self.needles = tuple(item.get("needles") or ())
self.icon = item.get("icon")
self.color = item.get("color") or ""
self.state_tones = dict(item.get("stateTones") or {})
self.click_action = item.get("clickAction") or "open"
self.priority = item.get("priority", DEFAULT_PRIORITY)
self.hue_role = item.get("hueRole")
self.group_by = item.get("groupBy")
self.config = {k: v for k, v in (config or {}).items() if isinstance(v, str)}
self.extractors = [Extractor(self, ex) for ex in item.get("toolExtractors") or ()]
@staticmethod
def _compile_rules(rules):
if isinstance(rules, str):
rules = [{"template": rules}]
out = []
for r in rules or ():
r = dict(r)
r["_rx"] = re.compile(r["match"]) if r.get("match") else None
out.append(r)
return tuple(out)
def descriptor(self) -> dict:
"""What the app draws a pill of this kind with (``GET /api/plugins``)."""
return {"id": self.kind, "label": self.label, "icon": self.icon, "color": self.color,
"stateTones": self.state_tones, "clickAction": self.click_action,
"priority": self.priority, "hueRole": self.hue_role, "pluginId": self.plugin}
# ── shaping ──────────────────────────────────────────────────────────────
def id_groups(self, rid: str | None) -> dict | None:
if not rid:
return None
if self.id_rx is None:
return {"id": rid}
return _groups(self.id_rx.match(rid)) or None
def make(self, groups: dict, *, url: str | None = None, sticky: dict | None = None,
names: dict | None = None, settings: bool = True) -> dict | None:
"""A record of this kind from a match's groups. ``settings=False``
(the miner): no fallback to the plugin's settings — a ``#13722`` stays
partial until the transcript names its repo (the view completes it)."""
config = self.config if settings else {}
rid = render_first(self.id_tpls, groups, config, sticky) if self.id_tpls \
else (groups.get("id") or groups.get("0"))
if not rid:
return None
return self.finalize({"kind": self.kind, "id": rid, "url": url}, groups=groups,
sticky=sticky, names=names, settings=settings)
def from_id(self, rid: str | None, *, sticky: dict | None = None,
names: dict | None = None, settings: bool = True) -> dict | None:
g = self.id_groups((rid or "").strip())
return self.make(g, sticky=sticky, names=names, settings=settings) if g else None
def finalize(self, r: dict, *, groups: dict | None = None, sticky: dict | None = None,
names: dict | None = None, settings: bool = True) -> dict:
"""The canonical record: its id re-shaped (a ``#13722`` gets its repo
from the transcript, else the settings), its link, label, slug title
and team."""
config = self.config if settings else {}
rid = str(r.get("id") or "")
g = self.id_groups(rid)
if g is not None and self.id_tpls:
new = render_first(self.id_tpls, {**(groups or {}), **g}, config, sticky)
if new and new != rid:
rid = new
g = self.id_groups(rid) or g
allg = {**(groups or {}), **(g or {})}
if self.names_group and allg.get(self.names_group):
v = allg[self.names_group]
allg["name"] = (names or {}).get(v) or v
out = dict(r)
out["kind"], out["id"] = self.kind, rid
u = render(self.url_tpl, allg, config, sticky) if self.url_tpl else None
if u:
out["url"] = u
elif not out.get("url"):
out["url"] = None
lab = _rules(self.label_rules, rid, allg, config)
out["label"] = lab or out.get("label") or rid
if self.slug_group and allg.get(self.slug_group) and not out.get("slugTitle"):
out["slugTitle"] = ru.titleize(allg[self.slug_group])
if self.team_group and allg.get(self.team_group):
out["team"] = str(allg[self.team_group]).upper()
return out
def token(self, r: dict) -> str | None:
"""How the record reads in a composite title (``titleToken``; its
label by default) — None when its rule says nothing."""
if not self.token_rules:
return r.get("label") or None
g = {**(self.id_groups(r.get("id")) or {}), "label": r.get("label") or "",
"id": r.get("id") or ""}
return _rules(self.token_rules, r.get("id") or "", g, self.config) or None
def needle_list(self, r: dict) -> list[str]:
g = {**(self.id_groups(r.get("id")) or {}), "label": r.get("label") or "",
"id": r.get("id") or ""}
out = [r.get("id"), r.get("label")] + [render(t, g, self.config) for t in self.needles]
return list(dict.fromkeys(x for x in out if x))
def date_of(self, r: dict) -> datetime.datetime | None:
if not self.date_group:
return None
v = (self.id_groups(r.get("id")) or {}).get(self.date_group)
try:
return datetime.datetime.fromtimestamp(float(v), datetime.timezone.utc)
except (TypeError, ValueError, OverflowError, OSError):
return None
# ── the registry ─────────────────────────────────────────────────────────────
class PluginResourceRegistry:
"""Every active plugin's resource kinds, by priority. Immutable."""
def __init__(self, defs: list[ResourceDef], scopes: dict[str, Scope],
version: int = 0, sig: str = "", names: dict[str, str] | None = None,
prefs: dict[str, dict] | None = None):
self.defs = tuple(sorted(defs, key=lambda d: (d.priority, d.kind)))
self.by_kind: dict[str, ResourceDef] = {}
for d in self.defs:
self.by_kind.setdefault(d.kind, d) # one plugin per kind
self.defs = tuple(d for d in self.defs if self.by_kind[d.kind] is d)
self.scopes = scopes
self.version = version
self.sig = sig
self.names = dict(names or {}) # every plugin's channelMap
self.roles = {d.kind: d.hue_role for d in self.defs if d.hue_role}
# The group kind (a Linear project): what a hue resource's `groupBy`
# lookup field names, its look and pill. One — the first by priority.
self.group_def = next((d for d in self.defs if d.hue_role == "group"), None)
self.look = LookPrefs((prefs or {}).get(self.group_def.plugin)
if self.group_def else None)
self.kinds = frozenset(self.by_kind)
self.extractors: list[Extractor] = []
self.name_extractors: list[Extractor] = []
for d in self.defs:
for ex in d.extractors:
ex.d = self.by_kind.get(ex.kind) or d
if ex.names_rx:
self.name_extractors.append(ex)
if ex.cmd_rx or ex.input_tpl or ex.wants_result:
self.extractors.append(ex)
self.url_defs = tuple(d for d in self.defs if d.url_rx)
self.bare_defs = tuple(d for d in self.defs if d.bare_rx)
self.branch_defs = tuple(d for d in self.defs if d.branch_rx)
def __bool__(self) -> bool:
return bool(self.defs)
# ── scope ────────────────────────────────────────────────────────────────
def scoped_kinds(self, worker: str | None, cwd: str | None) -> frozenset[str]:
"""The plugin kinds whose plugin's scope matches a conversation."""
hit: dict[str, bool] = {}
out = set()
for d in self.defs:
ok = hit.get(d.plugin)
if ok is None:
sc = self.scopes.get(d.plugin)
ok = hit[d.plugin] = sc.matches(worker, cwd) if sc else True
if ok:
out.add(d.kind)
return frozenset(out)
def notif_pills(self, worker: str | None, cwd: str | None) -> bool:
return any(sc.notif_pills and sc.matches(worker, cwd) for pid, sc in self.scopes.items()
if any(d.plugin == pid for d in self.defs))
# ── matching ─────────────────────────────────────────────────────────────
def ignored(self, url: str | None) -> bool:
return bool(url) and any(d.ignore_rx and d.ignore_rx.search(url) for d in self.defs)
def resolve_url(self, url: str | None, *, sticky: dict | None = None,
names: dict | None = None, settings: bool = True) -> dict | None:
"""A link → the first (by priority) plugin kind whose ``urlRegex``
matches it, else None."""
if not url:
return None
url = ru.trim(url)
for d in self.url_defs:
m = d.url_rx.search(url)
if m:
r = d.make(_groups(m), url=url, sticky=(sticky or {}).get(d.kind),
names=names, settings=settings)
if r:
return r
return None
def bare_keys(self, text: str, spans=(), *, settings: bool = True) -> list[tuple[int, dict]]:
"""Plugin keys typed in free text (``INS-2229``), outside its URLs —
flagged ``bare`` (the view keeps them for teams seen in real links)."""
out = []
for d in self.bare_defs:
for m in d.bare_rx.finditer(text or ""):
if any(a <= m.start() < b for a, b in spans):
continue
r = d.make(_groups(m), settings=settings)
if r:
r["bare"] = True
out.append((m.start(), r))
return out
def cross_links(self, text: str | None, *, skip: str | None = None) -> list[dict]:
"""What a branch name / a PR's head names (``branchKeyPattern``)."""
s = (text or "").strip()
if not s:
return []
out = []
for d in self.branch_defs:
if d.kind == skip:
continue
m = d.branch_rx.match(s)
if m:
r = d.make(_groups(m))
if r:
r["bare"] = True
out.append(r)
return out
def parse_ref(self, raw: str, kind: str | None = None) -> dict | None:
"""What ``conv add`` / ``ai-agent past`` was handed — a link, a key
(``INS-2229``), an id (``#13722``, ``C0…/1791….818179``), a branch —
as a record of an active kind or a core one."""
s = ru.trim(raw or "")
if not s:
return None
if kind == "branch":
return ru.branch(s)
if s.startswith(("http://", "https://")):
hit = self.resolve_url(s) if kind != "url" else None
if hit and kind in (None, hit["kind"]):
return hit
return ru.parse_url(s) if kind in (None, "url") else None
defs = [self.by_kind[kind]] if kind in self.by_kind else (
[] if kind else list(self.defs))
for d in defs:
r = d.from_id(s)
if r is None and d.bare_rx:
m = d.bare_rx.fullmatch(s) or d.bare_rx.fullmatch(s.upper())
r = d.make(_groups(m)) if m else None
if r:
return r
if kind is None and " " not in s:
return ru.branch(s)
return None
def normalize(self, r: dict, names: dict | None = None) -> dict | None:
"""Any stored record (the miner's, a legacy summary's, a recorded one)
→ its canonical shape under the active kinds: a ``url`` a plugin
matches becomes that kind; a kind no active plugin declares (a legacy
``notion`` page, an uninstalled plugin's) falls back to a plain link."""
kind = r.get("kind")
if not kind or not r.get("id"):
return None
if kind == "branch":
return dict(r)
url = r.get("url")
if kind == "url" or kind not in self.by_kind:
if url and self.ignored(url):
return None
hit = self.resolve_url(url, names=names) if url else None
if hit:
hit.update({f: r[f] for f in _KEEP if r.get(f) not in (None, "")})
return hit
if kind == "url":
return dict(r)
u = ru.parse_url(url) if url else None
if not u:
return None
out = {**{f: r[f] for f in _KEEP if r.get(f) not in (None, "")}, **u}
out["label"] = r.get("label") or u["label"]
if not out.get("title") and r.get("slugTitle"):
out["title"] = r["slugTitle"]
out.pop("bare", None)
return out
return self.by_kind[kind].finalize(dict(r), names=names)
def descriptors(self) -> list[dict]:
return [d.descriptor() for d in self.defs]
EMPTY = PluginResourceRegistry([], {})
def closes(text: str) -> list[str]:
"""What a PR body says it closes / fixes / resolves (``closes INS-2229``)."""
return [m.group(1).rstrip(".,;:)") for m in _CLOSES_RE.finditer(text or "")][:6]
# ── building it from the plugin store ────────────────────────────────────────
def build(entries: list[tuple[str, list[dict], dict]], *, version: int = 1,
sig: str = "") -> PluginResourceRegistry:
"""``[(plugin id, manifest resources[], settings)]`` → a registry."""
defs, scopes, names, prefs = [], {}, {}, {}
for pid, items, config in entries:
if not items:
continue
scopes[pid] = Scope(config or {})
prefs[pid] = dict(config or {})
names.update(channel_map((config or {}).get("channelMap")))
for item in items:
try:
defs.append(ResourceDef(pid, item, config or {}))
except (re.error, KeyError, TypeError):
continue # validated at install; a hand-edited record never breaks cards
return PluginResourceRegistry(defs, scopes, version, sig, names, prefs)
_lock = threading.Lock()
# id(store) → (store, its version, registry): holding the store keeps its id
# from being reused by another (a test's) while the entry lives.
_cache: dict[int, tuple[Any, int, PluginResourceRegistry]] = {}
_bound = None
def _entries(store) -> list[tuple[str, list[dict], dict]]:
from plugins.store import OWNER_UID
try:
rows = store.active_manifests(OWNER_UID)
except Exception: # noqa: BLE001 — no store (tests, early boot)
return []
out = []
for pid, mf, cfg in rows:
if not mf.get("resources"):
continue
# A setting never saved reads as its declared default.
defaults = {f["key"]: f.get("default") for f in (mf.get("settings") or {}).get("fields") or ()
if f.get("default") not in (None, "")}
out.append((pid, mf["resources"], {**defaults, **(cfg or {})}))
return out
def registry(deps) -> PluginResourceRegistry:
"""The owner's active resource kinds — rebuilt when the plugin store
changes, the same object while what it is built from holds."""
store = getattr(deps, "plugin_store", None) if deps is not None else None
if store is None:
return EMPTY
v = getattr(store, "version", 0)
hit = _cache.get(id(store))
if hit and hit[0] is store and hit[1] == v:
return hit[2]
with _lock:
hit = _cache.get(id(store))
if hit and hit[0] is not store:
hit = None
if hit and hit[1] == v:
return hit[2]
entries = _entries(store)
sig = json.dumps(entries, sort_keys=True, default=str)
if hit and hit[2].sig == sig:
reg = hit[2]
else:
reg = build(entries, version=(hit[2].version + 1) if hit else 1, sig=sig)
if len(_cache) > 32:
_cache.clear()
_cache[id(store)] = (store, v, reg)
return reg
def bind(deps) -> None:
"""The app's deps — what :func:`current` reads (the transcript miner has
no deps of its own)."""
global _bound
_bound = deps
def current() -> PluginResourceRegistry:
return registry(_bound) if _bound is not None else EMPTY
match_groups = _groups