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>
302 lines
13 KiB
Python
302 lines
13 KiB
Python
"""Past conversations on a subject — what ``ai-agent past INS-2229`` answers.
|
|
|
|
At work a conversation usually follows another on the same issue (Nov 2026:
|
|
177 of 326 work conversations started on a Linear issue an earlier, ended one
|
|
already listed; 63 % of their PR / issue / thread fetches before the first
|
|
edit repeated one of its fetches) and almost none says so (5 of 192 prompts).
|
|
The hub's work-context agent used to ask this once per brief (its PAST
|
|
section); since 2026-11-05 that agent is an opt-in file on the Orus Mac, and
|
|
this answers the CLI.
|
|
|
|
* **The subject is the hue resource** (``hueRole: hue`` — with the
|
|
``linear`` plugin, the issue). A shade resource (a PR) maps to its hue: the
|
|
one its head branch / body names (``branchKeyPattern``), else the hue most
|
|
of its own conversations have as their primary; a branch only names one;
|
|
a shade or a branch with no hue is its own subject. Resources without a
|
|
``hueRole`` (threads, links) aren't looked up: a channel thread is shared
|
|
by unrelated work.
|
|
* **Which conversations**: the related index (``related.py``) under that key,
|
|
the asking session left out. The ones running right now come apart (a
|
|
warning: two conversations on one issue step on each other's branch); then
|
|
the ended ones of the last ``MAX_AGE_DAYS``, those whose *primary* resource
|
|
it is first (a conversation lists many issues in passing), newest first,
|
|
``MAX_PAST`` of them.
|
|
* **What of each**: the last assistant message that *names* the subject (the
|
|
issue key, one of its PRs or branches — ≤ 1 000 chars, its ``searchMsgs``,
|
|
read with ``Store.search_msgs``). A conversation's last message is about another issue a
|
|
third of the time, so the plain last one misleads; when no message names
|
|
it there is no excerpt, only the title and the link.
|
|
|
|
The owner's view: a guest's computer asking through its outbox is refused
|
|
(:func:`outbox_lookup`), a guest's lab run only sees what ``visible`` lets it.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import collections
|
|
import datetime as dt
|
|
import os
|
|
import re
|
|
from typing import Callable
|
|
|
|
from conversations import related, resource_view
|
|
from plugins import resources as plugin_resources
|
|
from conversations.tree import _conv_id
|
|
|
|
VIEW_URL = os.environ.get("AI_AGENT_VIEW_URL", "https://ai-agent.lab.gabvdl.xyz").rstrip("/")
|
|
MAX_AGE_DAYS = 30
|
|
MAX_PAST = 3
|
|
MAX_RUNNING = 3
|
|
MAX_KEYS = 10
|
|
|
|
|
|
def _ts(s: str | None) -> dt.datetime | None:
|
|
try:
|
|
return dt.datetime.fromisoformat((s or "").replace("Z", "+00:00"))
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
def _rkey(r: dict) -> str:
|
|
return f"{r.get('kind')}:{r.get('id')}"
|
|
|
|
|
|
def _hue_of(reg, text: str | None, idx: dict | None) -> dict | None:
|
|
"""The hue resource a branch / a head names — one the hub knows, unless
|
|
``idx`` is None (a PR's own head is trusted)."""
|
|
for r in reg.cross_links(text):
|
|
if reg.roles.get(r["kind"]) == "hue" and (idx is None or _rkey(r) in idx):
|
|
return r
|
|
return None
|
|
|
|
|
|
def _hue_of_shade(deps, reg, key: str, idx: dict, by_id: dict) -> dict | None:
|
|
"""The hue a shade resource (a PR) is for: what its head / body names,
|
|
else the hue most of the conversations about it have as their primary."""
|
|
for text in resource_view.context(deps).xrefs.get(key, ()):
|
|
hit = _hue_of(reg, text, None)
|
|
if hit:
|
|
return hit
|
|
votes: collections.Counter = collections.Counter()
|
|
seen: dict[str, dict] = {}
|
|
for cid in idx.get(key, ()):
|
|
for r in ((by_id.get(cid) or {}).get("meta") or {}).get("resources") or ():
|
|
if reg.roles.get(r.get("kind")) == "hue" and r.get("primary"):
|
|
votes[_rkey(r)] += 1
|
|
seen[_rkey(r)] = r
|
|
return seen[votes.most_common(1)[0][0]] if votes else None
|
|
|
|
|
|
_CONV_REF = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
|
|
|
|
|
|
def _conversation_of(raw: str, by_id: dict) -> dict | None:
|
|
"""The card ``raw`` names when it is a conversation (its UUIDv7, its
|
|
session id, a viewer link), else None — `ai-agent past <conv>`."""
|
|
ref = raw.strip()
|
|
if "/conversation/" in ref:
|
|
ref = ref.split("/conversation/", 1)[1].split("?")[0].split("#")[0].strip("/")
|
|
ref = ref.lower()
|
|
if not _CONV_REF.match(ref):
|
|
return None
|
|
if ref in by_id:
|
|
return by_id[ref]
|
|
return next((c for c in by_id.values() if c.get("sessionId") == ref), None)
|
|
|
|
|
|
def subjects(deps, raw_keys: list[str], idx: dict,
|
|
by_id: dict) -> tuple[list[dict], list[str]]:
|
|
"""``raw_keys`` (INS-2229, a PR link or ``#13722``, a branch…) → the
|
|
subjects to look up, each ``{key, kind, id, label, needles, sources}``, and
|
|
what was left out."""
|
|
reg = plugin_resources.registry(deps)
|
|
out: dict[str, dict] = {}
|
|
skipped: list[str] = []
|
|
|
|
def add(r: dict, raw: str, needles: list[str]) -> None:
|
|
k = _rkey(r)
|
|
s = out.setdefault(k, {"key": k, "kind": r["kind"], "id": r["id"],
|
|
"label": r.get("label") or r["id"], "needles": [], "sources": []})
|
|
s["needles"] = list(dict.fromkeys(s["needles"] + [n for n in needles if n]))
|
|
if raw not in s["sources"]:
|
|
s["sources"].append(raw)
|
|
|
|
def needles(r: dict) -> list[str]:
|
|
d = reg.by_kind.get(r["kind"])
|
|
return d.needle_list(r) if d else [r["id"]]
|
|
|
|
keys: list[str] = []
|
|
for raw in [k.strip() for k in raw_keys if k and k.strip()][:MAX_KEYS]:
|
|
conv = _conversation_of(raw, by_id)
|
|
if conv is None:
|
|
keys.append(raw)
|
|
continue
|
|
# A conversation (its id, a session id, a viewer link): the hue and
|
|
# shade resources it is about stand for it — its primary ones, else all.
|
|
rs = [r for r in (conv.get("meta") or {}).get("resources") or ()
|
|
if reg.roles.get(r.get("kind")) and r.get("url")]
|
|
rs = [r for r in rs if r.get("primary")] or rs
|
|
if not rs:
|
|
skipped.append(raw)
|
|
keys.extend(r["url"] for r in rs[:3])
|
|
for raw in keys[:MAX_KEYS]:
|
|
try:
|
|
r = reg.parse_ref(raw)
|
|
except ValueError:
|
|
r = None
|
|
if r is not None and r["kind"] in reg.kinds:
|
|
r = reg.normalize(r) or r
|
|
role = reg.roles.get((r or {}).get("kind"))
|
|
if r is None:
|
|
skipped.append(raw)
|
|
elif role == "hue":
|
|
add(r, raw, needles(r))
|
|
elif role == "shade":
|
|
hue = _hue_of_shade(deps, reg, _rkey(r), idx, by_id)
|
|
head = list(resource_view.context(deps).xrefs.get(_rkey(r), ()))[:2]
|
|
if hue:
|
|
add(hue, raw, needles(hue) + needles(r) + head)
|
|
else:
|
|
add(r, raw, needles(r) + head)
|
|
elif r["kind"] == "branch":
|
|
# `fix-2-typos` reads as FIX-2: only a hue the hub knows counts.
|
|
hue = _hue_of(reg, r["id"], idx)
|
|
if hue:
|
|
add(hue, raw, needles(hue) + [r["id"]])
|
|
else:
|
|
add(r, raw, [r["id"]])
|
|
else:
|
|
skipped.append(raw)
|
|
return list(out.values()), skipped
|
|
|
|
|
|
def _naming(needles: list[str]) -> re.Pattern:
|
|
"""Whole words only: INS-1 is not INS-123, #7 is not #70."""
|
|
return re.compile(r"(?<!\w)(?:" + "|".join(map(re.escape, needles)) + r")(?!\w)", re.I)
|
|
|
|
|
|
def _excerpt(msgs: list[dict] | None, naming: re.Pattern) -> tuple[str | None, int | None]:
|
|
"""The last assistant message naming the subject, and its index — the
|
|
last of a turn first (a turn's answer, not its "I'll start by…"), off the
|
|
conversation's searchMsgs (``Store.search_msgs``)."""
|
|
msgs = msgs or []
|
|
hits = [(k + 1 == len(msgs) or msgs[k + 1].get("role") == "user", m)
|
|
for k, m in enumerate(msgs)
|
|
if m.get("role") == "assistant" and naming.search(m.get("text") or "")]
|
|
for ends_turn in (True, False):
|
|
m = next((m for e, m in reversed(hits) if e or not ends_turn), None)
|
|
if m:
|
|
return m.get("text"), m.get("i")
|
|
return None, None
|
|
|
|
|
|
def _is_primary(deps, card: dict, subject: dict) -> bool:
|
|
reg = plugin_resources.registry(deps)
|
|
for r in (card.get("meta") or {}).get("resources") or ():
|
|
if not r.get("primary"):
|
|
continue
|
|
if _rkey(r) == subject["key"]:
|
|
return True
|
|
if reg.roles.get(subject["kind"]) == "hue" and reg.roles.get(r.get("kind")) == "shade":
|
|
for text in resource_view.context(deps).xrefs.get(_rkey(r), ()):
|
|
hit = _hue_of(reg, text, None)
|
|
if hit and _rkey(hit) == subject["key"]:
|
|
return True
|
|
return False
|
|
|
|
|
|
def lookup(deps, raw_keys: list[str], *, session: str | None = None,
|
|
visible: Callable[[str], bool] | None = None,
|
|
now: dt.datetime | None = None) -> dict:
|
|
"""``{subjects: [{…, running, past, more}], skipped, maxAgeDays}``."""
|
|
from conversations.catalog import _conversation_cards # cycle-free
|
|
now = now or dt.datetime.now(dt.timezone.utc)
|
|
cutoff = now - dt.timedelta(days=MAX_AGE_DAYS)
|
|
cards = _conversation_cards(deps, False)
|
|
by_id = {c.get("id"): c for c in cards}
|
|
idx = related.index(deps)
|
|
subs, skipped = subjects(deps, raw_keys, idx, by_id)
|
|
|
|
picked: list[tuple[dict, list[dict], list[dict], int]] = []
|
|
wanted: set[str] = set()
|
|
for s in subs:
|
|
running, ended = [], []
|
|
for cid in dict.fromkeys(idx.get(s["key"], ())):
|
|
c = by_id.get(cid)
|
|
if c is None or (session and c.get("sessionId") == session):
|
|
continue
|
|
if visible and not visible(cid):
|
|
continue
|
|
if (c.get("meta") or {}).get("state") == "running":
|
|
running.append(c)
|
|
continue
|
|
ended_at = _ts(c.get("endedAt"))
|
|
if ended_at is None or ended_at < cutoff:
|
|
continue
|
|
ended.append((_is_primary(deps, c, s), c.get("endedAt") or "", c))
|
|
running.sort(key=lambda c: c.get("startedAt") or "", reverse=True)
|
|
ended.sort(key=lambda e: (e[0], e[1]), reverse=True)
|
|
top = [(p, c) for p, _, c in ended[:MAX_PAST]]
|
|
wanted.update(c["id"] for _, c in top)
|
|
picked.append((s, running[:MAX_RUNNING], top, len(ended) - len(top)))
|
|
|
|
paths = {cid: p for cid, p in ((_conv_id(p), p) for p, _ in deps.store.all_summaries())
|
|
if cid in wanted} if wanted else {}
|
|
corpus = deps.store.search_msgs(paths.values()) if paths else {}
|
|
out = []
|
|
for s, running, top, more in picked:
|
|
past = []
|
|
naming = _naming(s["needles"])
|
|
for primary, c in top:
|
|
text, mi = _excerpt(corpus.get(paths.get(c["id"])), naming)
|
|
url = f"{VIEW_URL}/conversation/{c['id']}"
|
|
past.append({"id": c["id"], "sessionId": c.get("sessionId"), "title": c.get("title"),
|
|
"startedAt": c.get("startedAt"), "endedAt": c.get("endedAt"),
|
|
"state": (c.get("meta") or {}).get("state"), "primary": primary,
|
|
"url": url, "excerpt": text,
|
|
"excerptUrl": f"{url}?m={mi}" if text is not None and mi is not None else None})
|
|
out.append({"key": s["key"], "kind": s["kind"], "id": s["id"], "label": s["label"],
|
|
"sources": s["sources"], "more": more,
|
|
"running": [{"id": c["id"], "sessionId": c.get("sessionId"),
|
|
"title": c.get("title"), "startedAt": c.get("startedAt"),
|
|
"url": f"{VIEW_URL}/conversation/{c['id']}"} for c in running],
|
|
"past": past})
|
|
return {"subjects": out, "skipped": skipped, "maxAgeDays": MAX_AGE_DAYS}
|
|
|
|
|
|
def split_keys(raw) -> list[str]:
|
|
"""``INS-2229,#13722`` / a list of them → the keys (commas or spaces)."""
|
|
items = raw if isinstance(raw, list) else [raw or ""]
|
|
return [k for item in items for k in re.split(r"[,\s]+", str(item)) if k]
|
|
|
|
|
|
def outbox_lookup(deps, payload: dict) -> dict:
|
|
"""A worker's ``ai-agent past`` (a ``lookup`` outbox item with ``keys``),
|
|
or its conv-ref hook's (one with ``ids``): answered in the ack, which ends it. A guest's computer gets nothing — the answer is
|
|
the owner's conversations; one of the owner's workers, its own profile's
|
|
(workers/bound.py — the rest of the CLI is the MCP's there)."""
|
|
from users import access
|
|
from workers import bound as worker_bound
|
|
from workers import guests
|
|
wid = payload.get("worker")
|
|
w = deps.worker_store.get(wid) if wid else None
|
|
if guests.is_guest(w):
|
|
return {"failed": True, "error": "ai-agent past is not open to a guest's computer"}
|
|
try:
|
|
caller = worker_bound.worker_caller(deps, wid)
|
|
except worker_bound.Refused as e:
|
|
d = e.detail
|
|
return {"failed": True, "error": str(d.get("message") if isinstance(d, dict) else d)}
|
|
visible = lambda cid: access.visible(deps, caller, cid) # noqa: E731
|
|
if payload.get("ids"):
|
|
# The conv-ref prompt hook (cli/conv_ref.py): a card per conversation
|
|
# the prompt names (refs.py), this worker's profile's only.
|
|
from conversations import refs
|
|
return {"ok": True, "result": refs.cards(deps, payload.get("ids"), visible=visible,
|
|
session=payload.get("sessionId") or None)}
|
|
keys = split_keys(payload.get("keys"))
|
|
if not keys:
|
|
return {"failed": True, "error": "no keys"}
|
|
return {"ok": True, "result": lookup(deps, keys, session=payload.get("sessionId") or None,
|
|
visible=visible)}
|