Files
gabrielvidalandClaude Opus 5.5 0e68e98795 feat(scheduled): Send later leaves the core for the scheduled-conversations plugin
Generic hooks the plugin builds on: the conversations.drawer, composer.send and
app.modal slot places (openModal / modal.setResult / modal.close, ?modal=
links), runs.start taking the composer's whole payload (auto routing,
account, projects, cwd, meta.scheduled) and hub/runs/resolve, a turn's knobs
on conversations.send, push buttons answered as the notify.action event,
hub/changed (SSE plugin-data), hub/title (conversations.title), the
runs.schedule provider behind /api/scheduled, the week's budget and the
stopped-run card, providers in /api/plugins/ui, carryover.scheduled.

backend/scheduled/ and frontend/src/business/scheduled/ are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 23:22:49 +01:00

575 lines
25 KiB
Python

"""Conversation resources mined from a transcript — free, deterministic, and
the backfill for every conversation recorded before the ``conv`` CLI existed.
A work conversation is almost always *about* one issue, one pull request,
one branch or one thread. :class:`ResourceMiner` rides along the transcript
parser (``ParserState`` feeds it every record's events) and collects:
* **prompts** — the URLs in the user's own turns (raw ``url`` records: the
view matches them against the plugins' kinds, so a plugin installed later
still lights them up), typed ``<key>-<n>-<slug>`` branches and plugin bare
keys (``INS-2229``), minus the composer's appended blocks (``Guidelines:``
& co.), ``<pasted_content>`` and system reminders; a slash command counts
by its ``<command-args>``. Everything in the **first** turn is
``firstTurn`` — what a resource title is built from;
* **the session's own branch** — never the first ``gitBranch``: on a shared
checkout that is whatever another session left checked out. What counts is
a branch the session created or moved to (``checkout -b`` / ``switch
[-c]`` / ``worktree add`` / ``branch -m``) and the ``gitBranch`` of records
whose cwd is a worktree;
* ``pr-link`` records — Claude Code's own "this session's PR", as its link;
* what the active plugins' declarative ``toolExtractors[]`` say
(``plugins/resources.py``): a ``gh pr view`` (title, state, head branch),
a tracker's ``get_issue`` (its title, labels, project, team), a Slack
thread read, channel names in any result — no subprocess, no plugin code.
The output is scope-agnostic (``resourcesAuto`` + ``resourceInfo`` +
``resourceNames``); which conversations show resources, the bare keys kept
(teams seen in real links), cross-links (a branch naming an issue), the
primary and the title are decided at view time (``resource_view.py``).
"""
from __future__ import annotations
import importlib.util
import json
import pathlib
import re
import shlex
import sys
def _load_resource_urls():
"""``cli/resource_urls.py`` — the one URL model the CLI and the backend
share. The image ships it as ``/app/cli`` (beside the backend's modules);
in the repo it is ``../cli``. Loaded by path so ``cli/`` never lands on
``sys.path`` (it also holds ``notify.py``)."""
if "resource_urls" in sys.modules:
return sys.modules["resource_urls"]
root = pathlib.Path(__file__).resolve().parent.parent
for d in (root / "cli", root.parent / "cli"):
f = d / "resource_urls.py"
if f.is_file():
spec = importlib.util.spec_from_file_location("resource_urls", f)
mod = importlib.util.module_from_spec(spec)
sys.modules["resource_urls"] = mod
spec.loader.exec_module(mod)
return mod
return None # no cli/ beside the backend: mining is off, parsing isn't
ru = _load_resource_urls()
# The blocks the composer appends (frontend lib/shortcuts.tsx — the same
# shapes conversations/short_title.clean strips): they are about *how* to work, not what.
_TAIL_RE = re.compile(
r"\n\s*(Attached files \(|Work in the following|Use the following in this "
r"task:|Guidelines:).*", re.S)
_PASTED_RE = re.compile(r"<pasted_content\b[^>]*>.*?</pasted_content>", re.S)
_REMINDER_RE = re.compile(r"<system-reminder>.*?</system-reminder>", re.S)
_CMD_ARGS_RE = re.compile(r"<command-args>(.*?)</command-args>", re.S)
_GIT_RE = re.compile(r"\bgit\s+(?:-C\s+\S+\s+)?(checkout|switch|worktree\s+add|branch)"
r"\b([^\n;&|]*)")
_NOTIFY_RE = re.compile(r"\b(?:notify-done|notify-ask|notify\s+(?:send|ask))\b")
# `gh pr view`'s plain-text answer (`title:\t…` lines), and any tool's alike.
_KV_RE = re.compile(r"^([A-Za-z][\w-]{0,40}):\t(.*)$", re.M)
# A last path segment with a dot is a file (`git checkout .claude/settings.json`).
_FILEISH_RE = re.compile(r"(^|/)[^/]*\.[A-Za-z0-9]{1,8}$")
_SHA_RE = re.compile(r"^[0-9a-f]{7,40}$")
_WORKTREE_CWD = ("/.claude/worktrees/", "/worktrees/")
def _clean_prompt(text: str) -> str:
if "<command-name>" in text or "<command-args>" in text:
m = _CMD_ARGS_RE.search(text)
return m.group(1) if m else ""
text = _PASTED_RE.sub(" ", text)
text = _REMINDER_RE.sub(" ", text)
return _TAIL_RE.sub("", text)
def _branchish(name: str) -> bool:
return bool(name) and "$" not in name and not name.startswith((".", "-", "origin/")) \
and not _SHA_RE.match(name) and not _FILEISH_RE.search(name) \
and "~" not in name and "^" not in name and ru.branch(name) is not None
def _split(args: str) -> list[str]:
try:
return shlex.split(args, comments=True)
except ValueError:
return args.split()
def git_branch_acts(command: str) -> list[tuple[str, str | None, str]]:
"""What a Bash command does to the session's branch, as
``("set", None, name)`` (created / switched to) or ``("rename", old|None,
new)``. File checkouts (``checkout -- f``, ``checkout ours f``), detached
worktrees, shas and variables never count."""
out: list[tuple[str, str | None, str]] = []
for m in _GIT_RE.finditer(command or ""):
verb = m.group(1).split()[0]
toks = _split(m.group(2))
cut = next((i for i, t in enumerate(toks) if "<" in t or ">" in t), None)
toks = toks[:cut] # `2>/dev/null`, `> out.txt`
if "--" in toks:
continue
flag_val, pos, i = {}, [], 0
while i < len(toks):
t = toks[i]
if t in ("-b", "-B", "-c", "-C", "--create", "-m", "-M", "--move"):
flag_val[t] = toks[i + 1] if i + 1 < len(toks) else ""
i += 2
continue
if t.startswith("-"):
flag_val.setdefault(t, "")
i += 1
continue
pos.append(t)
i += 1
new = None
if verb == "checkout":
new = flag_val.get("-b") or flag_val.get("-B") or (
pos[0] if len(pos) == 1 else None)
elif verb == "switch":
if "--detach" in flag_val or "-d" in flag_val:
continue
new = flag_val.get("-c") or flag_val.get("-C") or flag_val.get("--create") \
or (pos[0] if len(pos) == 1 else None)
elif verb == "worktree":
if "--detach" in flag_val:
continue
new = flag_val.get("-b") or flag_val.get("-B") or (
pos[1] if len(pos) >= 2 else (pos[0].rstrip("/").rsplit("/", 1)[-1]
if len(pos) == 1 else None))
elif verb == "branch":
moved = [flag_val.get(f) for f in ("-m", "-M", "--move") if f in flag_val]
if moved:
names = [x for x in moved if x] + pos
if len(names) == 1 and _branchish(names[0]):
out.append(("rename", None, names[0]))
elif len(names) >= 2 and _branchish(names[1]):
out.append(("rename", names[0], names[1]))
continue
if new and _branchish(new):
out.append(("set", None, new))
return out
def _result_text(content) -> str:
if isinstance(content, str):
return content
if isinstance(content, list):
return "\n".join(b.get("text") or "" for b in content
if isinstance(b, dict) and b.get("type") == "text")
return ""
def _first_json(text: str) -> dict | None:
i = text.find("{")
if i < 0:
return None
try:
obj, _ = json.JSONDecoder().raw_decode(text[i:])
except ValueError:
return None
return obj if isinstance(obj, dict) else None
def _kv(text: str) -> dict:
"""``key:\\tvalue`` lines (``gh pr view``'s plain-text answer)."""
return {k: v.strip() for k, v in _KV_RE.findall(text or "")}
def _get(obj, path: str) -> list:
"""The values at a field path: ``a.b``, ``labels[].name`` (``[]`` maps
over a list). Lenient like the APIs it reads: a key applied to a plain
string keeps the string (``labels: ["Bug"]`` and ``project: "X"``)."""
cur = [obj]
for part in path.split("."):
many = part.endswith("[]")
name = part[:-2] if many else part
nxt = []
for c in cur:
if isinstance(c, dict):
v = c.get(name)
elif isinstance(c, str):
v = c
else:
continue
if many:
if isinstance(v, list):
nxt.extend(v)
elif v is not None:
nxt.append(v)
cur = nxt
return cur
def _get1(obj, path: str):
vals = _get(obj, path)
return vals[0] if vals else None
def _text(v, n: int = 300) -> str | None:
if isinstance(v, bool) or v is None:
return None
if isinstance(v, (int, float)):
v = str(v)
if isinstance(v, str) and v.strip() and v.strip() != "None":
return v.strip()[:n]
return None
def _state(v) -> str | None:
s = _text(v, 40)
# `OPEN` / `MERGED` (gh) read as the other states do.
return s.lower() if s and s.isupper() and " " not in s else s
def _registry():
try:
from plugins import resources as plugin_resources
except Exception: # noqa: BLE001 — a bare parse (tests, scripts)
return None
return plugin_resources.current()
class ResourceMiner:
"""One transcript's resources. ``ParserState`` calls :meth:`feed_events`
with every record's events and :meth:`prompt` with each real user turn's
text; :meth:`summary` is a pure snapshot (callable between feeds).
``registry`` — the active plugins' kinds (``plugins/resources.py``) —
defaults to the app's at construction."""
def __init__(self, registry=None) -> None:
if registry is None:
registry = _registry()
if registry is None:
from plugins.resources import EMPTY
registry = EMPTY
self.reg = registry
self.found: dict[str, dict] = {} # key → tagged resource
self.info: dict[str, dict] = {} # key → what lookups said about it
self.names: dict[str, str] = {} # an id a plugin names (a channel) → its name
self.prompts = 0
# Per kind, the groups its full records named (a PR link's repo): a
# later bare `gh pr view 13722` is in that repo.
self.sticky: dict[str, dict] = {}
self._pending: dict[str, list] = {} # tool_use id → (extractor, asked record)
self._name_pending: dict[str, list] = {}
self._any_names = [ex for ex in registry.name_extractors if ex.tool == "*"]
self._wt_branch: dict[str, str] = {} # worktree cwd → its branch
self._own: str | None = None # the session's current own branch
self._cwd = self._gb = None # the session's current cwd / branch
# ── recording ──────────────────────────────────────────────────────────
def _tag(self, r: dict | None, ts: str | None, via: str,
first: bool = False) -> None:
if not r:
return
r = {**r, "source": "auto", "via": via, "firstSeen": ts}
if first:
r["firstTurn"] = True
k = ru.key(r)
cur = self.found.get(k)
if cur is None:
self.found[k] = r
else:
keep_via = cur.get("via")
self.found[k] = ru.merge(cur, r)
self.found[k]["via"] = keep_via # how it was *first* found
self._learn(r)
def _learn(self, r: dict | None) -> None:
d = self.reg.by_kind.get((r or {}).get("kind"))
if d is None or r.get("bare"):
return
g = d.id_groups(r.get("id")) or {}
g = {k: v for k, v in g.items() if not k.isdigit()}
if g:
self.sticky.setdefault(d.kind, {}).update(g)
def _url(self, r: dict | None, ts: str | None, via: str, first: bool = False) -> None:
"""A raw link — stored as ``url``: the view matches it against the
plugins of the day (a plugin installed later still lights it up)."""
if not r:
return
self._tag(r, ts, via, first)
self._learn(self.reg.resolve_url(r.get("url"), sticky=self.sticky, settings=False))
def _note(self, k: str, ts: str | None, **fields) -> None:
cur = self.info.setdefault(k, {})
for f, v in fields.items():
if v not in (None, "", []):
cur[f] = v
if ts:
cur["at"] = ts
def _set_branch(self, name: str, ts: str | None, old: str | None = None) -> None:
"""The session moved to ``name``; ``old`` is the branch it replaces
(a ``branch -m``, or a worktree that changed branch — a reused one
first reports whatever it had checked out). The old branch goes —
and with it whatever only its name pointed at (the view derives that)."""
r = ru.branch(name)
if old and old != name:
prev = self.found.pop(f"branch:{old}", None)
if prev and prev.get("firstSeen") and (not ts or prev["firstSeen"] < ts):
ts = prev["firstSeen"] if r else ts
if not r:
return
self._own = name
self._tag(r, ts, "branch")
# ── inputs ─────────────────────────────────────────────────────────────
def prompt(self, text: str, ts: str | None) -> None:
"""A real user turn (or a slash command's arguments)."""
if ru is None:
return
first = self.prompts == 0
self.prompts += 1
text = _clean_prompt(text or "")
for r in ru.find_all(text):
if r["kind"] == "url":
self._url(r, ts, "prompt", first)
else:
self._tag(r, ts, "prompt", first=first)
if self.reg.bare_defs:
for _pos, r in self.reg.bare_keys(text, ru.url_spans(text), settings=False):
self._tag(r, ts, "prompt", first=first)
def feed_events(self, evs: list[dict]) -> None:
"""One record's events (``parse/events.py``), before the parser folds
them: a PR the harness linked, the branch of a worktree the session
runs in, tool calls and their results."""
if ru is None:
return
for ev in evs:
t = ev["t"]
if t == "tool_call":
self._tool_use(ev, ev.get("at"))
elif t == "tool_result":
self._tool_result(ev, ev.get("at"))
elif t == "session":
if "cwd" in ev or "branch" in ev:
self._session(ev)
elif t == "meta" and ev.get("kind") == "pr":
# Claude Code's pr-link: its link (a GitHub PR, by definition).
d = ev.get("data") or {}
n, repo, url = d.get("number"), d.get("repo"), d.get("url")
if not (isinstance(url, str) and url.startswith("https://")):
url = (f"https://github.com/{repo}/pull/{n}"
if isinstance(n, int) and isinstance(repo, str) and "/" in repo
else None)
if url:
self._url(ru.parse_url(url), ev.get("at"), "pr-link")
def _session(self, ev: dict) -> None:
"""The session's cwd / branch changed: a worktree that changed branch
retags it."""
if "cwd" in ev:
self._cwd = ev["cwd"]
if "branch" in ev:
self._gb = ev["branch"]
cwd, gb = self._cwd, self._gb
if gb and cwd and any(s in cwd for s in _WORKTREE_CWD):
prev = self._wt_branch.get(cwd)
if prev != gb:
self._wt_branch[cwd] = gb
self._set_branch(gb, ev.get("at"), old=prev)
# Shaped without the plugin's settings (`settings=False`): what the
# transcript itself says wins; the view fills the rest from the settings.
def _from_groups(self, ex, g: dict) -> dict | None:
if g.get("url"):
return self.reg.resolve_url(g["url"], sticky=self.sticky, settings=False)
return ex.d.make(g, sticky=self.sticky.get(ex.d.kind), settings=False)
def _tool_use(self, ev: dict, ts: str | None) -> None:
name = ev.get("tool") or ""
inp = ev.get("input") if isinstance(ev.get("input"), dict) else {}
tid = ev.get("id") or ""
if name == "shell":
cmd = inp.get("command") or ""
# A command that `git init`s is playing in a scratch repo.
if "git " in cmd and "git init" not in cmd:
for act, old, new in git_branch_acts(cmd):
if act == "set":
self._set_branch(new, ts)
else:
self._set_branch(new, ts, old=old or self._own)
if _NOTIFY_RE.search(cmd) and self.reg:
# Claude's own pushes name the issue when nothing else does.
for r in ru.find_all(cmd):
if r["kind"] == "url" and self.reg.resolve_url(r["url"]):
self._url(r, ts, "notify")
for _pos, r in self.reg.bare_keys(cmd, ru.url_spans(cmd), settings=False):
self._tag(r, ts, "notify")
if not self.reg:
return
from plugins.resources import match_groups, render
for ex in self.reg.extractors:
if not ex.matches(name):
continue
if name == "shell":
if ex.cmd_rx is None:
continue
hits = list(ex.cmd_rx.finditer(inp.get("command") or ""))
recs = [self._from_groups(ex, match_groups(m)) for m in hits]
if ex.tag_on_call:
for r in recs:
self._tag(r, ts, "tool")
if ex.wants_result and tid and len(hits) == 1:
self._pending.setdefault(tid, []).append((ex, recs[0]))
else:
flat = {k: v for k, v in inp.items() if isinstance(v, (str, int))
and not isinstance(v, bool)}
asked = render(ex.input_tpl, flat, ex.d.config) if ex.input_tpl else None
rec = ex.d.from_id(asked, sticky=self.sticky.get(ex.d.kind),
settings=False) if asked else None
if ex.tag_on_call and rec:
self._tag(rec, ts, "tool")
if ex.wants_result and tid:
self._pending.setdefault(tid, []).append((ex, rec))
if tid:
for ex in self.reg.name_extractors:
if ex.tool != "*" and ex.matches(name):
self._name_pending.setdefault(tid, []).append(ex)
def _tool_result(self, ev: dict, ts: str | None) -> None:
# Text blocks only (`plainText` when the result also had images or
# tool references; a non-text result is "").
text = ev.get("plainText")
if text is None:
text = ev.get("text") or ""
tid = ev.get("toolCall") or ""
for ex, asked in self._pending.pop(tid, ()):
if ev.get("ok", True):
self._result(ex, asked, text, ts)
for ex in self._name_pending.pop(tid, []) + self._any_names:
self.names.update(ex.names(text))
def _result(self, ex, asked: dict | None, text: str, ts: str | None) -> None:
from plugins.resources import closes
obj = _first_json(text) or _kv(text)
if not obj:
return
rec = None
for path in ex.url_fields:
v = _text(_get1(obj, path), 2000)
if v and v.startswith(("http://", "https://")):
rec = self.reg.resolve_url(v, sticky=self.sticky, settings=False)
if rec:
break
if rec is None:
for path in ex.id_fields:
v = _text(_get1(obj, path), 200)
rec = ex.d.from_id(v, sticky=self.sticky.get(ex.d.kind),
settings=False) if v else None
if rec:
break
rec = rec or asked
if not rec:
return
title = next((t for p in ex.title_fields if (t := _text(_get1(obj, p)))), None)
state = next((s for p in ex.state_fields if (s := _state(_get1(obj, p)))), None)
for path, st in ex.state_flags.items():
if _get1(obj, path) is True:
state = st
meta = {}
for mname, path in ex.meta_fields.items():
if "[]" in path:
vals = [x for x in (_text(v, 80) for v in _get(obj, path)) if x][:12]
if vals:
meta[mname] = vals
else:
v = _text(_get1(obj, path), 200)
if v:
meta[mname] = v
xref: list[str] = []
for path in ex.xref_fields:
for v in _get(obj, path):
if isinstance(v, str) and v.strip():
xref.extend([v.strip()] if len(v) <= 200 and "\n" not in v
else closes(v[:8000]))
self._note(ru.key(rec), ts, title=title, state=state,
xref=list(dict.fromkeys(xref))[:8] or None, **meta)
if asked and ru.key(asked) != ru.key(rec):
# A moved issue answers under its new key (TECH-5027 → INS-2007).
self._note(ru.key(asked), ts, title=title, state=state, movedTo=rec["id"])
self._tag(rec, ts, "tool")
# ── snapshot ───────────────────────────────────────────────────────────
def summary(self) -> dict:
from plugins.resources import render_first
found = {k: dict(r) for k, r in self.found.items()}
info = {k: dict(v) for k, v in self.info.items()}
# A record seen before its full id was known (`gh pr view 13722`
# before the PR's repo showed up) joins the full one.
for k, r in list(found.items()):
d = self.reg.by_kind.get(r.get("kind"))
g = d.id_groups(r.get("id")) if d and d.id_tpls else None
if not g:
continue
new = render_first(d.id_tpls, g, {}, self.sticky.get(d.kind))
if not new or new == r["id"]:
continue
full = d.finalize({**r, "id": new}, sticky=self.sticky.get(d.kind), settings=False)
fk = ru.key(full)
found.pop(k)
found[fk] = ru.merge(found[fk], full) if fk in found else full
if k in info:
info[fk] = {**info.pop(k), **info.get(fk, {})}
out = []
for k, r in found.items():
v = info.get(k) or {}
for f in ("title", "state"):
if v.get(f) and not r.get(f):
r[f] = v[f]
out.append(r)
out.sort(key=lambda r: (not r.get("firstTurn"), r.get("firstSeen") or ""))
return {
"resourcesAuto": out,
# What lookups said (titles, states, labels, a PR's head branch…),
# for a parent to borrow from its subagents (tree._rollup_children)
# and for the view's archive-wide titles / cross-links.
"resourceInfo": {k: {f: x for f, x in v.items() if f != "at" and x}
for k, v in info.items()},
"resourceNames": dict(self.names),
}
def names_of(summary: dict) -> dict[str, str]:
"""The display names a transcript learned (``resourceNames``; legacy
summaries: ``slackChannels``)."""
out = dict(summary.get("slackChannels") or {})
out.update(summary.get("resourceNames") or {})
return out
def merge_children(summary: dict, children: list[dict]) -> dict:
"""A parent's resources with its subagents' lookups folded in (titles,
states, names). Children add no tags of their own: an investigation's
ten ``gh pr view`` calls are not what the card is about."""
infos = [c.get("resourceInfo") or {} for c in children]
names = names_of(summary)
mine = dict(names)
for c in children:
for cid, name in names_of(c).items():
names.setdefault(cid, name)
if not any(infos) and names == mine:
return summary
out = []
for r in summary.get("resourcesAuto") or []:
k = ru.key(r)
extra = {}
for inf in infos:
v = inf.get(k)
if v:
for f in ("title", "state", "headRefName"):
if v.get(f) and not r.get(f) and f not in extra:
extra[f] = v[f]
out.append({**r, **extra} if extra else r)
return {**summary, "resourcesAuto": out, "resourceNames": names}