Files
ai-agent/backend/plugins/trackers.py

648 lines
27 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Trackers — the things a conversation opened and closed (``trackers[]``).
A plugin declares, as pure data, how to read "it opened one" / "it closed
one" off a conversation's **shell commands** (docs/plugins.md → "Trackers").
No plugin code ever runs for it: the host's parser applies the rules
(``Fold``, fed by ``ParserState``) and keeps, per conversation and tracker,
``[{key, name, group, openedAt, closedAt}]``. The ``worktrees`` plugin's git
worktrees are the first one — the core knows none.
A rule is a **command** and its **argument grammar**::
{"id": "worktrees", "label": "Worktrees",
"hint": "new-worktree", # a literal every match holds
"command": "new-worktree(?:\\\\.sh)?", # the program's name (regex)
"flags": {"noop": ["-l", "--list"], # these make the call a no-op
"value": {"-r": "path", "-p": "project"}}, # flag → variable
"args": ["name"], # bare positionals, in order
"defaults": {"project": "homelab"},
"events": [{"do": "close", "needs": ["path"], "key": "{path:basename}"},
{"do": "open", "needs": ["name"], "key": "{project}-{name}",
"name": "{name}", "group": "{project}"}],
"group": "project"} # groups are project slugs
The host anchors ``command`` at **command position** (line start, after a
shell separator or a ``bash`` / ``sudo`` / … prefix, an optional path in
front), splits the argument tail on whitespace, and fires the first event
whose ``needs`` are all set. A rendered key / name / group that doesn't match
``valid`` (a git-ref-ish word by default) is parse noise and dropped.
**What a parse depends on.** A summary's ``trackersAuto`` is
``{"<plugin>:<tracker>": {"sig", "items"}}`` — ``sig`` is the signature of the
rules that read it, and :func:`view` only takes an entry whose ``sig`` is the
active tracker's. So a plugin install or an upgrade that changes a rule
invalidates exactly its own entries, and the indexer's re-derive pass
(``Indexer.rederive_trackers``) re-parses only the transcripts whose bytes
hold a changed tracker's ``hint`` — once per rule change (the store's
``trackers_sigs`` meta row), never on a plain boot.
Events can also be **stamped from outside** (``stamp`` — the
``trackers.stamp`` bridge below, and the ``worktree`` key of ``POST
/api/conversation-meta`` for the tracker that provides ``git.worktrees``):
they live in ``meta.trackers[<key>]`` and merge with the parse's.
**Provider roles.** ``provides: {"git.worktrees": "<tracker id>"}`` names the
tracker whose items are a conversation's git worktrees; :func:`provided`
hands them to the diff engines, the storage owners, the scaffold and the CLI
as ``{name, dir, project, createdAt, removedAt}`` — ``[]`` with no provider.
"""
from __future__ import annotations
import hashlib
import json
import posixpath
import re
import threading
from typing import Any
# ``provides`` keys that name one of the plugin's trackers (not an action).
ROLES = frozenset({"git.worktrees"})
CAP = "trackers.stamp"
MAX_TRACKERS = 4 # per plugin
MAX_EVENTS = 8 # per tracker
MAX_FLAGS = 24
MAX_ARGS = 6
MAX_ITEMS = 60 # per conversation and tracker
MAX_FIELD = 120 # a key / name / group
DEFAULT_VALID = r"^[A-Za-z0-9][\w./-]*$"
GROUP_KINDS = ("project",)
_VAR_RE = re.compile(r"^[a-z][a-zA-Z0-9]{0,23}$")
# Plain ASCII a JSON string never escapes: the indexer looks for it in a
# transcript's raw bytes.
_HINT_RE = re.compile(r"^[A-Za-z0-9._/:=@-][A-Za-z0-9 ._/:=@-]{2,38}[A-Za-z0-9._/:=@-]$")
_FLAG_RE = re.compile(r"^-{1,2}[A-Za-z0-9][\w-]{0,31}$")
_TPL_VAR_RE = re.compile(r"\{([^{}]+)\}")
_FILTERS = ("upper", "lower", "nodot", "title", "basename")
# Command position: the start of a line, after a shell separator, or after a
# `bash` / `sudo` / … prefix — then an optional path in front of the program.
_ANCHOR = (r"(?:^|[\n;&|(]|\b(?:bash|sh|sudo|exec|command)[ \t])[ \t]*"
r"(?:[\w./~$-]*/)?")
_TAIL = r"(?![\w.-])([^\n|&;<>]*)"
# ── manifest ────────────────────────────────────────────────────────────────
def _template(tpl: Any, where: str, names: set[str], errors: list[str],
required: bool = False) -> str | None:
if tpl is None:
if required:
errors.append(f"{where} is required")
return None
if not isinstance(tpl, str) or not tpl.strip() or len(tpl) > 200:
errors.append(f"{where} must be a template of 1–200 characters")
return None
for m in _TPL_VAR_RE.finditer(tpl):
expr, _, filt = m.group(1).partition(":")
if filt.strip() and filt.strip() not in _FILTERS:
errors.append(f"{where}: unknown filter '{filt.strip()}'")
return None
for alt in expr.split("|"):
if alt.strip() not in names:
errors.append(f"{where}: unknown variable '{alt.strip()}'")
return None
return tpl
def parse(raw: Any, errors: list[str]) -> list[dict[str, Any]]:
"""Validate ``trackers[]``; the normalized list (only set keys)."""
if raw is None:
return []
if not isinstance(raw, list):
errors.append("trackers must be a list")
return []
from plugins.manifest import _KEY_RE, _check_safe_regex
out: list[dict[str, Any]] = []
ids: set[str] = set()
for i, t in enumerate(raw[:MAX_TRACKERS]):
lb = f"trackers[{i}]"
if not isinstance(t, dict):
errors.append(f"{lb} must be an object")
continue
tid = str(t.get("id") or "").strip()
if not _KEY_RE.match(tid) or tid in ids:
errors.append(f"{lb}.id invalid or repeated")
continue
ids.add(tid)
label = str(t.get("label") or "").strip()
if not 1 <= len(label) <= 40:
errors.append(f"{lb}.label must be 1–40 characters")
continue
hint = t.get("hint")
if not isinstance(hint, str) or not _HINT_RE.match(hint):
errors.append(f"{lb}.hint must be a literal of 4–40 characters (letters, digits, "
"space and ._/:=@-) every matching command holds")
continue
cmd = _check_safe_regex(t.get("command"), f"{lb}.command", errors)
if not cmd:
if t.get("command") is None:
errors.append(f"{lb}.command is required")
continue
if len(cmd) > 200 or "\n" in cmd:
errors.append(f"{lb}.command must be at most 200 characters on one line")
continue
try:
re.compile(_ANCHOR + f"(?:{cmd})" + _TAIL)
except re.error as e:
errors.append(f"{lb}.command: invalid regex ({e})")
continue
o: dict[str, Any] = {"id": tid, "label": label, "hint": hint, "command": cmd}
names: set[str] = set()
# flags
fl = t.get("flags") or {}
noop: list[str] = []
value: dict[str, str] = {}
if not isinstance(fl, dict) or set(fl) - {"noop", "value"}:
errors.append(f"{lb}.flags must be an object {{noop?, value?}}")
fl = {}
for f in fl.get("noop") or []:
if not isinstance(f, str) or not _FLAG_RE.match(f):
errors.append(f"{lb}.flags.noop: invalid flag {f!r}")
else:
noop.append(f)
vraw = fl.get("value") or {}
if not isinstance(vraw, dict):
errors.append(f"{lb}.flags.value must be an object flag → variable")
vraw = {}
for f, var in vraw.items():
if not _FLAG_RE.match(str(f)) or not isinstance(var, str) or not _VAR_RE.match(var):
errors.append(f"{lb}.flags.value: invalid entry {f!r}")
else:
value[f] = var
names.add(var)
if len(noop) + len(value) > MAX_FLAGS:
errors.append(f"{lb}.flags: at most {MAX_FLAGS}")
if noop or value:
o["flags"] = {**({"noop": noop} if noop else {}), **({"value": value} if value else {})}
# positionals
args = t.get("args") or []
if not isinstance(args, list) or len(args) > MAX_ARGS \
or any(not isinstance(a, str) or not _VAR_RE.match(a) for a in args) \
or len(set(args)) != len(args):
errors.append(f"{lb}.args must be at most {MAX_ARGS} distinct variable names")
args = []
if args:
o["args"] = list(args)
names.update(args)
defaults = t.get("defaults") or {}
if not isinstance(defaults, dict) or any(
k not in names or not isinstance(v, str) or not 1 <= len(v) <= MAX_FIELD
for k, v in defaults.items()):
errors.append(f"{lb}.defaults must map declared variables to strings")
defaults = {}
if defaults:
o["defaults"] = dict(defaults)
if t.get("valid") is not None:
v = _check_safe_regex(t.get("valid"), f"{lb}.valid", errors)
if v:
o["valid"] = v
# events
evs = t.get("events")
ev_out: list[dict[str, Any]] = []
if not isinstance(evs, list) or not evs:
errors.append(f"{lb}.events must be a non-empty list")
evs = []
if len(evs) > MAX_EVENTS:
errors.append(f"{lb}.events: at most {MAX_EVENTS}")
for j, e in enumerate(evs[:MAX_EVENTS]):
el = f"{lb}.events[{j}]"
if not isinstance(e, dict) or e.get("do") not in ("open", "close"):
errors.append(f"{el}.do must be open or close")
continue
needs = e.get("needs") or []
if not isinstance(needs, list) or any(n not in names for n in needs):
errors.append(f"{el}.needs must list declared variables")
continue
eo: dict[str, Any] = {"do": e["do"]}
if needs:
eo["needs"] = list(needs)
key = _template(e.get("key"), f"{el}.key", names, errors, required=True)
if not key:
continue
eo["key"] = key
for k in ("name", "group"):
v = _template(e.get(k), f"{el}.{k}", names, errors)
if v:
eo[k] = v
ev_out.append(eo)
if not ev_out:
continue
o["events"] = ev_out
if t.get("group") is not None:
if t["group"] not in GROUP_KINDS:
errors.append(f"{lb}.group must be one of {', '.join(GROUP_KINDS)}")
else:
o["group"] = t["group"]
out.append(o)
if len(raw) > MAX_TRACKERS:
errors.append(f"trackers: at most {MAX_TRACKERS}")
return out
def fingerprint_sig(manifest: dict) -> list | None:
"""What of ``trackers[]`` enters the approval fingerprint: which commands
it reads (None when the plugin declares none)."""
ts = manifest.get("trackers") or []
return [(t["id"], t["command"]) for t in ts] or None
def consent_items(manifest: dict) -> list[dict]:
return [{"kind": "tracker",
"label": f"Tracks `{t['label']}` your conversations open and close, read off their shell commands"}
for t in manifest.get("trackers") or []]
# ── the compiled rules ──────────────────────────────────────────────────────
def _render(tpl: str | None, vars_: dict) -> str | None:
from plugins.resources import render
return render(tpl, vars_) if tpl else None
class Tracker:
"""One plugin's tracker, compiled."""
def __init__(self, pid: str, item: dict):
self.pid = pid
self.id = item["id"]
self.key = f"{pid}:{item['id']}"
self.label = item.get("label") or item["id"]
self.hint = item["hint"]
self.rx = re.compile(_ANCHOR + f"(?:{item['command']})" + _TAIL)
fl = item.get("flags") or {}
self.noop = frozenset(fl.get("noop") or ())
self.value = dict(fl.get("value") or {})
self.args = list(item.get("args") or ())
self.defaults = dict(item.get("defaults") or {})
self.valid = re.compile(item.get("valid") or DEFAULT_VALID)
self.rules = list(item.get("events") or ())
self.group = item.get("group")
self.sig = hashlib.sha256(
json.dumps(item, sort_keys=True).encode()).hexdigest()[:12]
def _ok(self, v: str | None) -> bool:
return bool(v) and len(v) <= MAX_FIELD and bool(self.valid.match(v))
def events(self, text) -> list[dict]:
"""The open / close events in a shell command:
``[{"do", "key", "name"?, "group"?}]``."""
out: list[dict] = []
if not isinstance(text, str) or self.hint not in text:
return out
for m in self.rx.finditer(text):
toks = m.group(1).split()
vars_: dict[str, str] = {}
pos = 0
noop = False
i = 0
while i < len(toks):
a = toks[i]
if a in self.noop:
noop = True
break
if a in self.value: # takes a value — skip both
if i + 1 < len(toks):
vars_[self.value[a]] = toks[i + 1]
i += 2
continue
if a.startswith("-"): # any other flag
i += 1
continue
if pos < len(self.args): # a bare positional
vars_[self.args[pos]] = a
pos += 1
i += 1
if noop:
continue
for rule in self.rules:
if any(n not in vars_ for n in rule.get("needs") or ()):
continue
full = {**self.defaults, **vars_}
key = _render(rule["key"], full)
name = _render(rule.get("name"), full)
group = _render(rule.get("group"), full)
# Every part it reads must be a plausible word: anything with
# shell quoting or punctuation is parse noise.
if self._ok(key) and (name is None or self._ok(name)) \
and (group is None or self._ok(group)) \
and all(self._ok(posixpath.basename(vars_[n].rstrip("/")))
for n in rule.get("needs") or ()):
ev = {"do": rule["do"], "key": key}
if name:
ev["name"] = name
if group:
ev["group"] = group
out.append(ev)
break # the first rule whose needs are set
return out
class Registry:
"""The owner's active trackers. Immutable; ``version`` moves when what it
is built from does (the cards' memo keys on it)."""
def __init__(self, trackers: list[Tracker] | None = None,
roles: dict[str, str] | None = None, version: int = 0, sig: str = ""):
self.trackers = list(trackers or ())
self.by_key = {t.key: t for t in self.trackers}
self.roles = dict(roles or {}) # role → tracker key
self.version = version
self.sig = sig
def __bool__(self) -> bool:
return bool(self.trackers)
@property
def sigs(self) -> dict[str, str]:
return {t.key: t.sig for t in self.trackers}
def provider(self, role: str) -> Tracker | None:
return self.by_key.get(self.roles.get(role) or "")
EMPTY = Registry()
def build(entries: list[tuple[str, list[dict], dict]], *, version: int = 1) -> Registry:
"""``entries``: ``(plugin id, its trackers[], its provides)`` in plugin
order. A role goes to the first plugin that provides it."""
trackers: list[Tracker] = []
roles: dict[str, str] = {}
for pid, items, provides in entries:
mine = {}
for it in items or ():
try:
t = Tracker(pid, it)
except (re.error, KeyError, TypeError):
continue # validated at install; a hand-edited record never breaks a parse
trackers.append(t)
mine[t.id] = t
for role, tid in (provides or {}).items():
if role in ROLES and tid in mine and role not in roles:
roles[role] = mine[tid].key
sig = hashlib.sha256(json.dumps(
[sorted((t.key, t.sig) for t in trackers), sorted(roles.items())]).encode()).hexdigest()[:12] \
if trackers else ""
return Registry(trackers, roles, version, sig)
_lock = threading.Lock()
_cache: dict[int, tuple[Any, int, Registry]] = {}
_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 []
return [(pid, mf["trackers"], mf.get("provides") or {})
for pid, mf, _cfg in rows if mf.get("trackers")]
def registry(deps) -> Registry:
"""The owner's active trackers — rebuilt when the plugin store changes,
the same object (and ``version``) while its rules hold."""
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]
new = build(_entries(store), version=(hit[2].version + 1) if hit else 1)
reg = hit[2] if hit and hit[2].sig == new.sig else new
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 parser has none)."""
global _bound
_bound = deps
def current() -> Registry:
return registry(_bound) if _bound is not None else EMPTY
# ── folding events into items ───────────────────────────────────────────────
def apply(items: dict[str, dict], ev: dict, ts: str | None) -> None:
"""Fold one event at ``ts`` into ``items`` (key → item), in place: an
open fills name / group and the earliest ``openedAt``, a close the latest
``closedAt``."""
key = ev.get("key")
if not key:
return
it = items.get(key)
if it is None:
if len(items) >= MAX_ITEMS:
return
it = {"key": key, "name": ev.get("name") or key, "group": None,
"openedAt": None, "closedAt": None}
items[key] = it
if ev.get("do") == "open":
if ev.get("name"):
it["name"] = ev["name"]
if ev.get("group"):
it["group"] = ev["group"]
if ts and (it["openedAt"] is None or ts < it["openedAt"]):
it["openedAt"] = ts
elif ts and (it["closedAt"] is None or ts > it["closedAt"]):
it["closedAt"] = ts
class Fold:
"""A transcript's tracker items as its shell commands go by — one per
``ParserState``, on the rules of the moment it was made."""
def __init__(self, reg: Registry | None = None):
self.reg = reg if reg is not None else current()
self.sig = self.reg.sig
self._items: dict[str, dict[str, dict]] = {t.key: {} for t in self.reg.trackers}
def feed(self, command, ts: str | None) -> None:
if not self.reg.trackers or not isinstance(command, str):
return
for t in self.reg.trackers:
for ev in t.events(command):
apply(self._items[t.key], ev, ts)
def summary(self) -> dict[str, dict]:
"""``{key: {"sig", "items"}}`` — an entry for every active tracker, an
empty one included: it says "read with these rules, found nothing"."""
return {t.key: {"sig": t.sig, "items": list(self._items[t.key].values())}
for t in self.reg.trackers}
# ── the merged view (cards, accessors) ──────────────────────────────────────
def merge(*sources) -> list[dict]:
"""Union item lists by ``key``: the earliest ``openedAt`` and the latest
``closedAt`` win, a real ``name`` beats one that is only the key. Ordered
by opening (unknown last)."""
by: dict[str, dict] = {}
for src in sources:
for e in src or ():
if not isinstance(e, dict):
continue
k = str(e.get("key") or "").strip()
if not k:
continue
cur = by.get(k)
if cur is None:
by[k] = {"key": k, "name": e.get("name") or k, "group": e.get("group") or None,
"openedAt": e.get("openedAt") or None, "closedAt": e.get("closedAt") or None}
continue
nm = e.get("name")
if nm and nm != k and (not cur["name"] or cur["name"] == k):
cur["name"] = nm
if e.get("group") and not cur.get("group"):
cur["group"] = e["group"]
for f, pick in (("openedAt", min), ("closedAt", max)):
vals = [v for v in (cur.get(f), e.get(f)) if v]
cur[f] = pick(vals) if vals else None
return sorted(by.values(), key=lambda w: (w.get("openedAt") is None, w.get("openedAt") or ""))
def _infer_group(t: Tracker, items: list[dict]) -> None:
if t.group != "project":
return
missing = [it for it in items if not it.get("group")]
if not missing:
return
try:
from projects.catalog import prefix_project
except Exception: # noqa: BLE001
return
for it in missing:
it["group"] = prefix_project(it["key"])
def items_for(t: Tracker, summary: dict | None, meta: dict | None,
reg: Registry | None = None) -> list[dict]:
"""One tracker's items on a conversation: its parse (only an entry read
with the tracker's current rules), what was stamped from outside, and —
for a provider role — what the core recorded before trackers existed."""
summary, meta = summary or {}, meta or {}
ent = (summary.get("trackersAuto") or {}).get(t.key) or {}
auto = ent.get("items") if ent.get("sig") == t.sig else None
stamped = (meta.get("trackers") or {}).get(t.key)
legacy: list = []
reg = reg if reg is not None else current()
for role, key in reg.roles.items():
if key == t.key:
from plugins import carryover_trackers
legacy += carryover_trackers.items(role, summary, meta)
out = merge(auto, stamped, legacy)
_infer_group(t, out)
return out
def view(deps, summary: dict | None, meta: dict | None) -> dict[str, list[dict]] | None:
"""Every active tracker's items on a conversation, ``{key: [items]}`` —
None when it has none (the card field)."""
reg = registry(deps) if deps is not None else current()
if not reg:
return None
out = {}
for t in reg.trackers:
items = items_for(t, summary, meta, reg)
if items:
out[t.key] = items
return out or None
def provided(role: str, summary: dict | None, meta: dict | None,
deps=None) -> list[dict]:
"""A provider role's records on a conversation, in the shape its readers
always had — ``git.worktrees``: ``{name, dir, project, createdAt,
removedAt}``. ``[]`` with no active provider."""
reg = registry(deps) if deps is not None else current()
t = reg.provider(role)
if t is None:
return []
return _records(items_for(t, summary, meta, reg))
# ── stamping from outside ───────────────────────────────────────────────────
def clean_event(ev: Any) -> dict | None:
"""A stamped event ``{do: open|close, key, name?, group?, at?}``, checked."""
if not isinstance(ev, dict) or ev.get("do") not in ("open", "close"):
return None
out: dict[str, Any] = {"do": ev["do"]}
for k in ("key", "name", "group", "at"):
v = ev.get(k)
if v is None or v == "":
continue
if not isinstance(v, str) or len(v) > MAX_FIELD or "\n" in v:
return None
out[k] = v.strip()
return out if out.get("key") else None
def stamp(deps, sid: str, key: str, ev: dict) -> dict | None:
"""Fold a cleaned event into ``meta.trackers[key]`` of ``sid`` and tell
the app; the conversation's metadata, or None for an unknown tracker."""
if key not in registry(deps).by_key:
return None
if ev.get("do") == "close" and not ev.get("at"):
import time
ev = {**ev, "at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
merged = deps.meta_store.update(sid, {"tracker": {"key": key, "event": ev}})
deps.hub.publish({"type": "meta", "id": sid})
return merged
def fold_stamped(items: list[dict], ev: dict) -> list[dict]:
"""``MetaStore.update``'s fold of a ``tracker`` patch: ``items`` with the
event applied at its ``at`` (a new list)."""
by = {it["key"]: dict(it) for it in items or () if isinstance(it, dict) and it.get("key")}
apply(by, ev, ev.get("at"))
return list(by.values())
def _records(items: list[dict]) -> list[dict]:
return [{"name": it["name"], "dir": it["key"], "project": it.get("group"),
"createdAt": it.get("openedAt"), "removedAt": it.get("closedAt")}
for it in items]
def sessions(deps, role: str) -> dict[str, list[dict]]:
"""``session id → its records`` for a provider role — who recorded what:
every conversation card's (memoized with the list), then the stamps of a
session the hub has no transcript of yet (it stamped before its first
record was indexed)."""
reg = registry(deps)
t = reg.provider(role)
if t is None:
return {}
from conversations.catalog import _conversation_cards
out: dict[str, list[dict]] = {}
seen: set[str] = set()
for c in _conversation_cards(deps, False):
sid = c.get("sessionId")
if not sid:
continue
seen.add(sid)
items = ((c.get("meta") or {}).get("trackers") or {}).get(t.key)
if items:
out[sid] = _records(items)
from plugins import carryover_trackers
for sid, m in deps.meta_store.items():
if sid in seen or not ((m.get("trackers") or {}).get(t.key)
or carryover_trackers.items(role, {}, m)):
continue
items = items_for(t, None, m, reg)
if items:
out[sid] = _records(items)
return out