Generic points the plugin stands on (docs/plugins.md → "Trackers" → Tool trackers, "Checklists"): - trackers[]: tool-call rules — `tool` (a neutral tool name) + `ops` (create / update by id / whole-list snapshot, told apart by the input's field paths) + `statuses`; items gain `status` and `startedAt`, keep the list's order; the re-derive pass finds the transcripts by the tool's quoted names (toolnames.byte_hints), no PARSER_VERSION bump (48: the unshipped v49 goes) - provides tasks.list: the completion scaffold reads the task list through trackers.provided; an older row's `tasks` is carried over until re-read - ui.card[].list.style "checklist" (the ✓ done/total pill and its card), ui.panels[] (the floating checklist over the thread) and ui.toolCards[] naming a tracker (the calls' rows) — declared by the plugin, drawn by the app: Checklist.tsx (the old TaskPanel, moved), PluginPanels, trackerCards; the tool-card registry has an epoch so mounted rows follow a declared card Removed from core: todo_op / _task_times and the summary's `tasks`, the card field, the Task schema, the registered `todo` card (its bucket stays), the taskPanel switch (a hidden one carries over to plugin:tasks:panel), their i18n keys. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
966 lines
42 KiB
Python
966 lines
42 KiB
Python
"""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.
|
||
|
||
**Tool trackers.** A tracker may read a **tool's calls** instead of shell
|
||
commands — ``tool`` (a neutral tool name, ``conversations/parse/readers/
|
||
toolnames.py``) and ``ops``, told apart by the call's input like the parser's
|
||
old ``todo_op``::
|
||
|
||
{"id": "tasks", "label": "Tasks", "tool": "todo",
|
||
"ops": [{"do": "snapshot", "items": "todos", # the whole list again
|
||
"name": ["content", "activeForm"], "status": "status"},
|
||
{"do": "update", "id": ["taskId", "task_id"], # one item, by its id
|
||
"name": "subject", "status": "status"},
|
||
{"do": "create", "name": ["subject", "content"]}], # a new item
|
||
"statuses": {"deleted": "cancelled"}} # the tool's words → ours
|
||
|
||
The first op whose input is there fires (``snapshot``: ``items`` is a list;
|
||
``update``: ``id`` is set; ``create``: ``name`` is set). A created item's key
|
||
is its 1-based ordinal — the id a sequential task tool's update cites; a
|
||
snapshot replaces the list, and an item whose name is unchanged keeps its
|
||
times. Such items carry a ``status`` (``pending`` / ``in_progress`` /
|
||
``completed`` / ``cancelled``) and three times: ``openedAt`` (added),
|
||
``startedAt`` (first in progress), ``closedAt`` (completed or cancelled; gone
|
||
again if it reopens). They keep the list's own order, and nothing stamps
|
||
them from outside. The ``tasks`` plugin's task list is the first one.
|
||
|
||
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.
|
||
``provides: {"tasks.list": "<tracker id>"}`` names the (tool) tracker whose
|
||
items are a conversation's task list: ``{id, subject, status, createdAt,
|
||
startedAt, endedAt}`` for the completion scaffold.
|
||
"""
|
||
|
||
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", "tasks.list"})
|
||
# A role only a tool tracker can play (its items carry a status).
|
||
TOOL_ROLES = frozenset({"tasks.list"})
|
||
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",)
|
||
# Tool trackers (``tool`` + ``ops``).
|
||
STATUSES = ("pending", "in_progress", "completed", "cancelled")
|
||
OP_KINDS = ("snapshot", "update", "create")
|
||
MAX_OPS = 6
|
||
MAX_PATHS = 4 # alternatives of one input field
|
||
MAX_STATUSES = 24
|
||
MAX_TOOL_ITEMS = 200 # per conversation and tool tracker
|
||
MAX_NAME = 200 # a tool tracker's item name (one line)
|
||
|
||
_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}$")
|
||
# A neutral tool name (`todo`), a harness's own (`claude:CronCreate`) or an MCP one.
|
||
_TOOL_RE = re.compile(r"^[A-Za-z][\w.-]{0,79}(?::[\w.-]{1,80})?$")
|
||
# An input field, dotted for a nested one (`task.id`).
|
||
_PATH_RE = re.compile(r"^[A-Za-z_][\w-]{0,39}(?:\.[A-Za-z_][\w-]{0,39}){0,3}$")
|
||
_TOOL_KEYS = frozenset({"id", "label", "tool", "ops", "statuses"})
|
||
_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 _paths(raw: Any, where: str, errors: list[str], required: bool = False) -> list[str] | None:
|
||
"""An input field of a tool tracker's op: one path or up to
|
||
``MAX_PATHS`` alternatives (the first that is set wins) — as a list."""
|
||
if raw is None:
|
||
if required:
|
||
errors.append(f"{where} is required")
|
||
return None
|
||
paths = [raw] if isinstance(raw, str) else raw
|
||
if not isinstance(paths, list) or not 1 <= len(paths) <= MAX_PATHS \
|
||
or any(not isinstance(p, str) or not _PATH_RE.match(p) for p in paths):
|
||
errors.append(f"{where} must be an input field (or up to {MAX_PATHS} alternatives), "
|
||
"dotted for a nested one")
|
||
return None
|
||
return list(paths)
|
||
|
||
|
||
def _parse_tool(t: dict, lb: str, o: dict[str, Any], errors: list[str]) -> bool:
|
||
"""The ``tool`` / ``ops`` / ``statuses`` of a tool tracker into ``o``."""
|
||
extra = set(t) - _TOOL_KEYS
|
||
if extra:
|
||
errors.append(f"{lb}: a tool tracker takes id, label, tool, ops and statuses "
|
||
f"(not {', '.join(sorted(extra))})")
|
||
return False
|
||
tool = t.get("tool")
|
||
if not isinstance(tool, str) or not _TOOL_RE.match(tool):
|
||
errors.append(f"{lb}.tool must be a tool's neutral name (todo, claude:CronCreate, mcp__…)")
|
||
return False
|
||
ops = t.get("ops")
|
||
if not isinstance(ops, list) or not 1 <= len(ops) <= MAX_OPS:
|
||
errors.append(f"{lb}.ops must be a list of 1–{MAX_OPS} ops")
|
||
return False
|
||
out_ops: list[dict[str, Any]] = []
|
||
for j, op in enumerate(ops):
|
||
ol = f"{lb}.ops[{j}]"
|
||
if not isinstance(op, dict) or op.get("do") not in OP_KINDS:
|
||
errors.append(f"{ol}.do must be one of {', '.join(OP_KINDS)}")
|
||
return False
|
||
do = op["do"]
|
||
allowed = {"snapshot": {"do", "items", "name", "status"},
|
||
"update": {"do", "id", "name", "status"},
|
||
"create": {"do", "name", "status"}}[do]
|
||
if set(op) - allowed:
|
||
errors.append(f"{ol}: a {do} op takes {', '.join(sorted(allowed - {'do'}))}")
|
||
return False
|
||
oo: dict[str, Any] = {"do": do}
|
||
need = {"snapshot": ("items", "name"), "update": ("id",), "create": ("name",)}[do]
|
||
bad = False
|
||
for k in ("items", "id", "name", "status"):
|
||
if k not in allowed:
|
||
continue
|
||
v = _paths(op.get(k), f"{ol}.{k}", errors, required=k in need)
|
||
if v is None:
|
||
bad = bad or k in need or op.get(k) is not None
|
||
else:
|
||
oo[k] = v
|
||
if bad:
|
||
return False
|
||
out_ops.append(oo)
|
||
o["tool"] = tool
|
||
o["ops"] = out_ops
|
||
st = t.get("statuses")
|
||
if st is not None:
|
||
if not isinstance(st, dict) or len(st) > MAX_STATUSES or any(
|
||
not isinstance(k, str) or not 1 <= len(k.strip()) <= 40 or v not in STATUSES
|
||
for k, v in st.items()):
|
||
errors.append(f"{lb}.statuses must map the tool's own words (at most {MAX_STATUSES}) "
|
||
f"to {', '.join(STATUSES)}")
|
||
return False
|
||
if st:
|
||
o["statuses"] = {k.strip().lower(): v for k, v in st.items()}
|
||
return True
|
||
|
||
|
||
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
|
||
if t.get("tool") is not None:
|
||
# A tool tracker: a tool's calls, not shell commands.
|
||
if t.get("command") is not None:
|
||
errors.append(f"{lb}: one of command (shell commands) or tool (a tool's calls)")
|
||
continue
|
||
to: dict[str, Any] = {"id": tid, "label": label}
|
||
if _parse_tool(t, lb, to, errors):
|
||
out.append(to)
|
||
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"] if "command" in t else f"tool:{t['tool']}") for t in ts] or None
|
||
|
||
|
||
def consent_items(manifest: dict) -> list[dict]:
|
||
return [{"kind": "tracker",
|
||
"label": (f"Keeps the `{t['label']}` list of your conversations, read off their "
|
||
f"`{t['tool']}` tool calls") if t.get("tool") else
|
||
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.sig = hashlib.sha256(
|
||
json.dumps(item, sort_keys=True).encode()).hexdigest()[:12]
|
||
self.group = item.get("group")
|
||
# A tool tracker reads a tool's calls (``fold_call``), not commands.
|
||
self.tool: str | None = item.get("tool")
|
||
if self.tool:
|
||
from conversations.parse.readers.toolnames import byte_hints
|
||
self.hint = None
|
||
# What a transcript's bytes hold when it calls the tool.
|
||
self.hints: tuple[str, ...] = byte_hints(self.tool)
|
||
# A path is a list of alternatives (a bare string: one).
|
||
self.ops = [{k: ([v] if isinstance(v, str) and k != "do" else v)
|
||
for k, v in op.items()} for op in item["ops"]]
|
||
self.statuses = {s: s for s in STATUSES} | dict(item.get("statuses") or {})
|
||
self.rules = []
|
||
return
|
||
self.hint = item["hint"]
|
||
self.hints = (self.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 ())
|
||
|
||
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 self.tool or 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
|
||
|
||
|
||
# ── a tool tracker's fold ───────────────────────────────────────────────
|
||
def op_of(self, inp: dict) -> dict | None:
|
||
"""The op a call's input makes — the first whose input is there:
|
||
a snapshot's ``items`` is a list, an update's ``id`` is set, a
|
||
create's ``name`` is set. None: the call changes nothing (a read)."""
|
||
for op in self.ops:
|
||
do = op["do"]
|
||
if do == "snapshot":
|
||
if isinstance(_field(inp, op["items"], any_type=True), list):
|
||
return op
|
||
elif _field(inp, op["id" if do == "update" else "name"]) is not None:
|
||
return op
|
||
return None
|
||
|
||
def _status(self, src: dict, op: dict) -> str | None:
|
||
raw = _field(src, op.get("status") or ())
|
||
return self.statuses.get(str(raw).strip().lower()) if raw is not None else None
|
||
|
||
def fold_call(self, items: dict[str, dict], inp, ts: str | None) -> None:
|
||
"""Fold one call of the tool at ``ts`` into ``items`` (key → item, in
|
||
list order), in place."""
|
||
if not isinstance(inp, dict):
|
||
return
|
||
op = self.op_of(inp)
|
||
if op is None:
|
||
return
|
||
do = op["do"]
|
||
if do == "create":
|
||
if len(items) >= MAX_TOOL_ITEMS:
|
||
return
|
||
# Its key is its 1-based ordinal: the id an update cites.
|
||
key = str(len(items) + 1)
|
||
items[key] = _stamp_times(
|
||
_tool_item(key, _field(inp, op["name"]), self._status(inp, op) or "pending"),
|
||
None, ts)
|
||
elif do == "update":
|
||
ref = _field(inp, op["id"])
|
||
if isinstance(ref, float) and ref.is_integer():
|
||
ref = int(ref)
|
||
cur = items.get(str(ref).strip())
|
||
if cur is None:
|
||
return
|
||
st = self._status(inp, op)
|
||
if st:
|
||
was = dict(cur)
|
||
cur["status"] = st
|
||
_stamp_times(cur, was, ts)
|
||
name = _field(inp, op.get("name") or ())
|
||
if name is not None:
|
||
cur["name"] = _one_line(name) or cur["name"]
|
||
else:
|
||
# The whole list again: an item is the one it was when its name
|
||
# is (its times carry over).
|
||
prev: dict[str, dict] = {}
|
||
for old in items.values():
|
||
prev.setdefault(old["name"], old)
|
||
items.clear()
|
||
for row in _field(inp, op["items"], any_type=True):
|
||
if not isinstance(row, dict) or len(items) >= MAX_TOOL_ITEMS:
|
||
continue
|
||
key = str(len(items) + 1)
|
||
it = _tool_item(key, _field(row, op["name"]), self._status(row, op) or "pending")
|
||
items[key] = _stamp_times(it, prev.pop(it["name"], None), ts)
|
||
|
||
|
||
def _field(src, paths, any_type: bool = False):
|
||
"""The first of ``paths`` (dotted input fields) that is set in ``src`` —
|
||
None when none is (an empty string counts as unset)."""
|
||
for path in paths:
|
||
cur = src
|
||
for part in path.split("."):
|
||
cur = cur.get(part) if isinstance(cur, dict) else None
|
||
if cur is None:
|
||
break
|
||
if cur is None or cur == "":
|
||
continue
|
||
if any_type or isinstance(cur, (str, int, float)) and not isinstance(cur, bool):
|
||
return cur
|
||
return None
|
||
|
||
|
||
def _one_line(v) -> str:
|
||
return " ".join(str(v if v is not None else "").split())[:MAX_NAME]
|
||
|
||
|
||
def _tool_item(key: str, name, status: str) -> dict:
|
||
return {"key": key, "name": _one_line(name) or key, "group": None, "status": status,
|
||
"openedAt": None, "startedAt": None, "closedAt": None}
|
||
|
||
|
||
def _stamp_times(it: dict, before: dict | None, ts: str | None) -> dict:
|
||
"""Stamp ``it`` (its status just set) with its times: ``openedAt`` (when
|
||
it was first listed), ``startedAt`` (the first time it was in progress)
|
||
and ``closedAt`` (completed or cancelled; gone again if it reopens).
|
||
``before`` is the same item as it was until this call (a copy taken
|
||
before an update, the earlier snapshot's row): its times carry over. A
|
||
call with no timestamp stamps nothing. Returns ``it``."""
|
||
before = before or {}
|
||
for k in ("openedAt", "startedAt", "closedAt"):
|
||
if before.get(k) and not it.get(k):
|
||
it[k] = before[k]
|
||
if ts:
|
||
st = it.get("status")
|
||
if not it.get("openedAt"):
|
||
it["openedAt"] = ts
|
||
if st == "in_progress" and not it.get("startedAt"):
|
||
it["startedAt"] = ts
|
||
if st in ("completed", "cancelled"):
|
||
if before.get("status") != st or not it.get("closedAt"):
|
||
it["closedAt"] = ts
|
||
else:
|
||
it["closedAt"] = None
|
||
return it
|
||
|
||
|
||
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 \
|
||
and (role in TOOL_ROLES) == bool(mine[tid].tool):
|
||
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 and tool calls 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}
|
||
self._commands = [t for t in self.reg.trackers if not t.tool]
|
||
self._tools: dict[str, list[Tracker]] = {}
|
||
for t in self.reg.trackers:
|
||
if t.tool:
|
||
self._tools.setdefault(t.tool, []).append(t)
|
||
|
||
def feed(self, command, ts: str | None) -> None:
|
||
if not self._commands or not isinstance(command, str):
|
||
return
|
||
for t in self._commands:
|
||
for ev in t.events(command):
|
||
apply(self._items[t.key], ev, ts)
|
||
|
||
def feed_tool(self, tool, inp, ts: str | None) -> None:
|
||
"""One tool call (its neutral name and input) — the tool trackers'."""
|
||
for t in self._tools.get(tool) or ():
|
||
t.fold_call(self._items[t.key], inp, 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
|
||
reg = reg if reg is not None else current()
|
||
if t.tool:
|
||
# A tool tracker's list is its transcript's, in the list's own order:
|
||
# nothing merges into it. Until a summary is re-read with its rules,
|
||
# what the core kept before it (a provider role's carry-over).
|
||
if auto is None:
|
||
from plugins import carryover_trackers
|
||
auto = [i for role, key in reg.roles.items() if key == t.key
|
||
for i in carryover_trackers.items(role, summary, meta)]
|
||
return [dict(i) for i in auto if isinstance(i, dict) and i.get("key")]
|
||
stamped = (meta.get("trackers") or {}).get(t.key)
|
||
legacy: list = []
|
||
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}``; ``tasks.list``: ``{id, subject, status, createdAt,
|
||
startedAt, endedAt}``. ``[]`` 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), role)
|
||
|
||
|
||
# ── 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 (a
|
||
tool tracker too: its list is its transcript's)."""
|
||
t = registry(deps).by_key.get(key)
|
||
if t is None or t.tool:
|
||
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], role: str = "git.worktrees") -> list[dict]:
|
||
if role == "tasks.list":
|
||
return [{"id": it["key"], "subject": it["name"], "status": it.get("status") or "pending",
|
||
"createdAt": it.get("openedAt"), "startedAt": it.get("startedAt"),
|
||
"endedAt": it.get("closedAt")}
|
||
for it in items]
|
||
return [{"name": it["name"], "dir": it["key"], "project": it.get("group"),
|
||
"createdAt": it.get("openedAt"), "removedAt": it.get("closedAt")}
|
||
for it in items]
|
||
|
||
|
||
def tracker_sessions(deps, key: str) -> dict[str, dict]:
|
||
"""``session id → {conversationId, title, state, worker, items}`` for one
|
||
tracker (``<plugin>:<id>``): every conversation holding items of it, with
|
||
the card's live state and the machine it ran on (``worker``: a worker's
|
||
id, None = the lab) — what the ``trackers.stamp`` bridge's read hands the
|
||
plugin that owns the tracker (who opened what, and is it still running)."""
|
||
reg = registry(deps)
|
||
t = reg.by_key.get(key)
|
||
if t is None:
|
||
return {}
|
||
from conversations.catalog import _conversation_cards
|
||
out: dict[str, dict] = {}
|
||
seen: set[str] = set()
|
||
for c in _conversation_cards(deps, False):
|
||
sid = c.get("sessionId")
|
||
if not sid:
|
||
continue
|
||
seen.add(sid)
|
||
meta = c.get("meta") or {}
|
||
items = (meta.get("trackers") or {}).get(t.key)
|
||
if items:
|
||
out[sid] = {"conversationId": c.get("id"), "title": c.get("title"),
|
||
"state": meta.get("state"),
|
||
"worker": meta.get("worker") or meta.get("workerSource") or None,
|
||
"items": [dict(i) for i in items]}
|
||
for sid, m in deps.meta_store.items():
|
||
if sid in seen or not (m.get("trackers") or {}).get(t.key):
|
||
continue
|
||
items = items_for(t, None, m, reg)
|
||
if items:
|
||
out[sid] = {"conversationId": None, "title": None, "state": None,
|
||
"worker": m.get("worker") or m.get("workerSource") or None,
|
||
"items": [dict(i) for i in items]}
|
||
return out
|
||
|
||
|
||
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, role)
|
||
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, role)
|
||
return out
|