Files
gabrielvidalandClaude Fable 5.2 b32458e821 feat(trackers): tasks leave the core for the tasks plugin — tool trackers, checklists
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>
2026-12-02 22:30:48 +01:00

283 lines
14 KiB
Python

"""Tool calls: the activity buckets and their sub-labels, the project /
service / commit evidence mined from them, the lifecycle stamps and
deploys and agent launches. (A task list is a plugin's tool tracker —
plugins/trackers.py.)"""
import re
from ..deploycmd import deploy_invocation
# Map a neutral tool name (readers/toolnames.py) → the activity bucket we
# attribute its turn's tokens/cost to (so a conversation's spend can be broken
# down by what it was spent doing: plain messages, sub-agents, the shell, file
# reads/edits, …). Anything else — a harness's own tool, an MCP tool,
# `ask_user` — is the catch-all "tool".
TOOL_BUCKETS = {
"shell": "shell", "shell_output": "shell", "shell_kill": "shell",
"read": "read",
"write": "edit", "edit": "edit", "apply_patch": "edit", "delete_file": "edit",
"grep": "search", "glob": "search", "list_dir": "search",
"web_fetch": "web", "web_search": "web",
"agent": "agent",
"skill": "skill",
"todo": "todo",
}
# All buckets the UI may show ("msg" = text-only turns, "context" = the first
# API call's injected context share, "tool" = catch-all).
TOOL_BUCKET_ORDER = ["msg", "context", "agent", "shell", "read", "edit", "search",
"skill", "web", "todo", "tool"]
# Where homelab projects and services live — only there do `projects/<slug>/`
# and `services/<slug>/` name one. Other repos have folders of those names of
# their own (the Orus monorepo's `docs/projects/nl-aovql/`,
# `…/modules/<m>/services/<file>.ts`), and those are not lab projects/services.
# A homelab checkout is `~/homelab`, `~/homelab-<wt>`, `~/worktrees/homelab-<wt>`
# or a `.claude/worktrees/<wt>` of one; a repo-relative path counts too.
_HOMELAB_ROOT = r"/homelab[^/]*/(?:\.claude/worktrees/[^/]+/)?"
# A homelab project is `~/projects/<slug>/…` (on the lab or a worker), or
# `projects/<slug>/…` under a homelab checkout (the old layout). Claude's own
# transcript store (`.claude/projects/<encoded-path>`) is excluded by the
# leading-dash filter below, since those encoded names always start with a dash.
_PROJECT_RE = re.compile(
rf"(?:^|^/(?:home|Users)/[^/]+/|{_HOMELAB_ROOT})projects/([A-Za-z0-9._][\w.-]*)/")
# A homelab service is `<homelab checkout>/services/<slug>/…` — the infra side
# of the repo. <slug> is a directory: a file right in `services/` is none.
_SERVICE_RE = re.compile(rf"(?:^|{_HOMELAB_ROOT})services/([A-Za-z0-9._][\w.-]*)/")
# A conversation is attributed to a project/service only when it actually
# **worked on** it — i.e. created or edited a file under `projects/<slug>` or
# `services/<slug>`. We therefore mine the auto-tags exclusively from the
# file-mutating tools' target paths (`write` / `edit` / `delete_file` →
# `file_path`, a notebook `edit` → `notebook_path`), *not* from the cwd, plain
# reads, searches, or shell commands that merely mention a path. This keeps the
# tag list to projects the conversation genuinely changed, instead of
# everything it happened to look at or `cd` into.
_EDIT_TOOLS = {"write", "edit", "delete_file"}
# Caps on the stored `writtenDirsAuto` / `gitRootsAuto` / `worktreeAddsAuto`.
_MAX_WRITTEN_DIRS = 300
_MAX_GIT_ROOTS = 40
_MAX_WORKTREE_ADDS = 40
# A shell command that can print git's `[branch sha] subject` commit line.
_COMMIT_CMD_RE = re.compile(r"\bgit\b[^\n]*\b(commit|merge|cherry-pick|revert|rebase|am|pull)\b"
r"|\bcommit-(homelab|project)\b")
# …that commits, then prints the result with a one-commit `git log`.
_LOG_ONE_RE = re.compile(r"\bgit\b[^\n;&|]*\bcommit\b[\s\S]*\bgit\b[^\n;&|]*\blog\b"
r"[^\n;&|]*(\s-1\b|\s-n\s*1\b|--max-count=1\b)")
# An `agent` call spawned with ``run_in_background`` gets its tool_result the
# instant the agent launches ("Async agent launched successfully… agentId: …"),
# so — unlike a blocking agent, whose result *is* its report — that result says
# nothing about whether the agent is still working. Its real end signal is the
# ``<task-notification>`` Claude Code injects when the agent stops, which names
# the agent call it belongs to. Only a result that *starts* with the agentId
# is a launch: a blocking agent's report ends on an "agentId: … (use
# SendMessage …)" line too.
_AGENT_ASYNC_RE = re.compile(r"Async agent launched|\A\s*agentId:")
# A SendMessage to an agent that had already stopped resumes it in the
# background ("Resuming agent …"): its call runs again until the next
# `<task-notification>` — which names the SendMessage, not the Agent call
# (``_agents_done``). One sent to a running agent is only queued.
_AGENT_RESUMED_RE = re.compile(r'"resumedAgentId"\s*:\s*"([\w-]+)"')
# A *recalled* memory is injected into the transcript (as a tool_result) with its
# full file content — frontmatter + body. We detect each one by its frontmatter
# (``name: <slug>`` shortly above ``node_type: memory``) and record the slug, so
# the viewer can show which memories a conversation read. The lazy span keeps the
# slug bound to the nearest ``node_type: memory`` below it; the session-start
# MEMORY.md index (plain ``- [..](..md)`` lines) carries no such frontmatter and
# so is correctly ignored.
_MEMORY_RE = re.compile(
r"name:\s*([A-Za-z0-9][\w.-]*)\s*\n[\s\S]{0,400}?node_type:\s*memory")
# ── lifecycle backfill ───────────────────────────────────────────────────────
# The CI/CD-style stamps (committed/pushed/merged/deployed/notified) are normally
# written live by the skill scripts (conv-meta.sh, called from the commit / deploy
# / notify skills) into the metadata sidecar. For conversations that ran before
# those hooks existed — or that committed/deployed via plain git/deploy commands —
# the sidecar is empty, so the status icons never light up. We *derive* the stamps
# from the transcript instead: scan each skill/shell tool call for evidence the
# action happened, and stamp it with that turn's timestamp. These derived values
# are merged non-destructively under `lifecycleAuto` (the live sidecar wins).
#
# The actual deploy commands (as opposed to the `conv-meta ... deployed` stamp
# below, which only *records* one after the fact) are recognised by what the
# command *runs* — `deploycmd.deploy_invocation` — not by a regex over its text,
# which also lit up on `cat deploy.sh`, `bash -n deploy.sh`, commit messages….
# Reused to detect a deploy in flight, see `_deploy_call`.
# Each pattern matches a command/skill-name string; a hit lights its stage(s).
_LIFECYCLE_PATTERNS: list[tuple[str, re.Pattern]] = [
# commit-homelab / commit-project both commit *and* push to Gitea.
("committed", re.compile(r"\b(?:commit-homelab|commit-project)\b")),
("pushed", re.compile(r"\b(?:commit-homelab|commit-project)\b")),
("committed", re.compile(r"\bgit\b[^\n|&;]*\bcommit\b")),
("pushed", re.compile(r"\bgit\b[^\n|&;]*\bpush\b")),
("merged", re.compile(r"\bgit\s+merge\b")),
# (deploy paths: skill/alias, npm/pnpm/yarn deploy, zipgo, make deploy,
# *.sh — matched by `deploy_invocation` in `_lifecycle_stages`.)
("notified", re.compile(r"\b(?:notify-done|notify-ask|notify\.sh|notify\s+(?:send|ask|form))\b")),
# explicit conv-meta stamps (e.g. `conv-meta.sh committed`).
("committed", re.compile(r"\bconv-meta(?:\.sh)?\b[^\n|&;]*\bcommitted\b")),
("pushed", re.compile(r"\bconv-meta(?:\.sh)?\b[^\n|&;]*\bpushed\b")),
("merged", re.compile(r"\bconv-meta(?:\.sh)?\b[^\n|&;]*\bmerged\b")),
("deployed", re.compile(r"\bconv-meta(?:\.sh)?\b[^\n|&;]*\bdeployed\b")),
("notified", re.compile(r"\bconv-meta(?:\.sh)?\b[^\n|&;]*\bnotified\b")),
]
# `skill` invocations (matched on the `skill` input) → stage(s).
_SKILL_STAGES: dict[str, tuple[str, ...]] = {
"commit-homelab": ("committed", "pushed"),
"commit-project": ("committed", "pushed"),
"deploy-html": ("deployed",),
"notify-done": ("notified",),
}
# ── deployed URL ─────────────────────────────────────────────────────────────
# Every deploy path prints where the thing landed, but always *last* and often
# after a very long build log — and the result we ship to the UI is clipped to
# MAX_BLOCK chars. So the URL is pulled out of the raw output here, before the
# clip, and hung on the tool card as `deployedUrl` (the UI turns it into a live
# preview widget + the conversation's "open the deploy" gizmo).
_DEPLOY_URL_PATTERNS: list[re.Pattern] = [
re.compile(r"Deployed URL\s*[:=]\s*(https?://[^\s'\"<>]+)"),
re.compile(r"Live:\s*HTTP\s*\d+\s*at\s+(https?://[^\s'\"<>]+)"),
re.compile(r"(?:deployed|live|serving|available)\s+(?:at|on)\s+(https?://[^\s'\"<>]+)",
re.IGNORECASE),
re.compile(r"https://[\w.-]+\.(?:gabvdl\.xyz|gabriel\.vidal--ayrinhac\.xyz)[^\s'\"<>]*"),
]
def _deployed_url(rtext: str) -> str | None:
"""The URL a deploy command reported, best-effort (raw, unclipped output)."""
for pat in _DEPLOY_URL_PATTERNS:
m = pat.search(rtext)
if m:
url = m.group(1) if m.groups() else m.group(0)
return url.rstrip(".,;:)\"'")
return None
def _lifecycle_stages(name: str | None, inp: dict) -> set[str]:
"""Stages a tool call provides evidence for (best-effort, may over-report)."""
stages: set[str] = set()
if name == "skill":
stages.update(_SKILL_STAGES.get((inp.get("skill") or ""), ()))
cmd = inp.get("command")
if isinstance(cmd, str) and cmd:
for stage, pat in _LIFECYCLE_PATTERNS:
if stage not in stages and pat.search(cmd):
stages.add(stage)
if "deployed" not in stages and deploy_invocation(cmd):
stages.add("deployed")
return stages
def _deploy_call(name: str | None, inp: dict) -> dict | None:
"""``{kind, target}`` if this tool call itself performs (or wraps) a deploy,
else ``None`` — hung on the tool card as ``deploy`` (the UI's deploy widget)
and used to detect one in flight, unlike `_lifecycle_stages`'s "deployed"
hit, which also fires on the post-hoc `conv-meta ... deployed` stamp."""
if name == "skill":
if inp.get("skill") == "deploy-html":
args = inp.get("args")
return {"kind": "deploy-html", "target": args if isinstance(args, str) else ""}
return None
if name != "shell":
return None
hit = deploy_invocation(inp.get("command"))
return {"kind": hit[0], "target": hit[1]} if hit else None
def _bucket(tool: str | None) -> str:
return TOOL_BUCKETS.get(tool or "", "tool")
# The leading program of a shell command — the sub-label a "shell" turn is broken
# down by (git / npm / docker / …). We skip common env/prefix wrappers so the
# real command shows through (e.g. `sudo docker …` → docker, `FOO=1 npm …` → npm).
_BASH_PREFIX = {"sudo", "env", "time", "nice", "nohup", "exec", "command",
"xargs", "then", "do", "if", "!"}
def _bash_program(command) -> str:
"""First real program name in a shell command (for the shell sub-breakdown)."""
if not isinstance(command, str):
return "?"
cmd = command.strip()
# `cd <dir> && <real cmd>` / `(cd <dir>; …)` is pervasive here — skip the cd
# prefix so the actual command shows through instead of "cd".
cmd = re.sub(r"^\(?\s*cd\s+[^\n&;|]+(?:&&|;|\|\|)\s*", "", cmd).lstrip("(").strip()
# Only look at the first pipeline/segment; strip a leading subshell/paren.
seg = re.split(r"[|;&\n]", cmd, 1)[0].strip().lstrip("(").strip()
for tok in seg.split():
# Skip VAR=value assignments and known wrapper prefixes.
if "=" in tok and not tok.startswith("-") and re.match(r"^\w+=", tok):
continue
if tok in _BASH_PREFIX:
continue
# Basename, drop any path so `/usr/bin/git` and `git` collapse together.
prog = tok.rsplit("/", 1)[-1]
return prog or "?"
return "?"
def _file_ext(inp: dict) -> str:
"""File extension sub-label for a read/edit turn (e.g. `.py`, `.tsx`)."""
p = inp.get("file_path") or inp.get("notebook_path") or ""
if not isinstance(p, str) or not p:
return "?"
base = p.rsplit("/", 1)[-1]
dot = base.rfind(".")
# Leading-dot names (`.env`) are extension-less; everything after the dot else.
if dot > 0:
return base[dot:].lower()
return "(no ext)"
def _subkey(bucket: str, tool: str | None, inp: dict) -> str | None:
"""The second-level breakdown label for a turn, given its activity bucket:
shell → program, read/edit → file extension, skill → constant "skills
read", any other tool bucket → the (neutral) tool name. ``None`` for
text-only (msg) turns, which are split by prompt/reply at accumulation time
instead."""
if bucket == "shell":
return _bash_program(inp.get("command"))
if bucket in ("read", "edit"):
return _file_ext(inp)
if bucket == "skill":
return "skills read"
if bucket == "msg":
return None
return tool or "tool"
_TASK_SUBJECT_MAX = 200
def _task_subject(s) -> str:
"""A short, single-line label (an agent call's description)."""
s = " ".join(str(s or "").split()).strip() or "task"
return s[:_TASK_SUBJECT_MAX]
def _projects_in(text) -> set[str]:
"""Pull homelab `projects/<name>` slugs out of an edited file's path."""
if not isinstance(text, str):
return set()
return {m.group(1) for m in _PROJECT_RE.finditer(text)
if not m.group(1).startswith("-")}
def _services_in(text) -> set[str]:
"""Pull homelab `services/<name>` slugs out of an edited file's path."""
if not isinstance(text, str):
return set()
return {m.group(1) for m in _SERVICE_RE.finditer(text)
if not m.group(1).startswith("-")}