Files
ai-agent/backend/test_trackers.py
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

709 lines
38 KiB
Python

"""Trackers (plugins/trackers.py): what a conversation opened and closed, read
off its shell commands by a plugin's declarative rules — on the reference
``worktrees`` manifest (fixtures/tracker_plugins), which reads exactly what
the core's worktree parse read before it left.
``python3 -m pytest test_trackers.py``"""
import copy
import json
import os
import pathlib
import sys
import tempfile
import unittest
from unittest import mock
HERE = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from fixtures.tracker_plugins import kit # noqa: E402
from plugins import carryover_trackers, trackers # noqa: E402
from plugins.manifest import ManifestError, validate_manifest # noqa: E402
from projects import catalog # noqa: E402
KEY = kit.KEY
def tracker():
return kit.registry().by_key[KEY]
def events(cmd):
return tracker().events(cmd)
class Events(unittest.TestCase):
def test_project_mode_records_the_project(self):
self.assertEqual(events("scripts/new-worktree.sh -p creature-forge ae-paint"),
[{"do": "open", "key": "creature-forge-ae-paint", "name": "ae-paint",
"group": "creature-forge"}])
def test_super_mode_takes_the_default_group(self):
self.assertEqual(events("cd ~/homelab && scripts/new-worktree.sh fix-x"),
[{"do": "open", "key": "homelab-fix-x", "name": "fix-x", "group": "homelab"}])
def test_remove_closes_by_basename(self):
self.assertEqual(events("scripts/new-worktree.sh -r ~/worktrees/bffr-groups/"),
[{"do": "close", "key": "bffr-groups"}])
def test_the_devbox_command_has_no_extension(self):
self.assertEqual(events("new-worktree -p ai-agent worktrees-plugin"),
[{"do": "open", "key": "ai-agent-worktrees-plugin",
"name": "worktrees-plugin", "group": "ai-agent"}])
self.assertEqual(events("~/.local/bin/new-worktree -r /home/u/worktrees/ai-agent-x"),
[{"do": "close", "key": "ai-agent-x"}])
def test_flags_in_any_order_and_an_optional_branch(self):
self.assertEqual(events("bash scripts/new-worktree.sh --no-link fix-y my/branch -p bffr"),
[{"do": "open", "key": "bffr-fix-y", "name": "fix-y", "group": "bffr"}])
def test_list_and_help_are_no_ops(self):
for cmd in ("scripts/new-worktree.sh -l", "new-worktree --help", "new-worktree -h x",
"scripts/new-worktree.sh"):
self.assertEqual(events(cmd), [], cmd)
def test_only_at_command_position(self):
for cmd in ("cat scripts/new-worktree.sh", "grep -n foo scripts/new-worktree.sh | head",
"echo 'run new-worktree.sh fix-x'", "git log -- scripts/new-worktree.sh",
"vim new-worktree.sh.bak", "my-new-worktree x"):
self.assertEqual(events(cmd), [], cmd)
def test_noise_names_are_dropped(self):
for cmd in ('scripts/new-worktree.sh "$NAME"', "new-worktree -p 'a b' x",
"new-worktree $(date +%s)", "new-worktree -r \"$WT\"", "new-worktree .hidden"):
self.assertEqual(events(cmd), [], cmd)
def test_several_in_one_command(self):
self.assertEqual(
[(e["do"], e["key"]) for e in events(
"new-worktree -p bffr a && new-worktree -p bffr b; new-worktree -r ~/worktrees/bffr-a")],
[("open", "bffr-a"), ("open", "bffr-b"), ("close", "bffr-a")])
def test_a_command_without_the_hint_is_not_even_matched(self):
t = tracker()
with mock.patch.object(t, "rx") as rx:
self.assertEqual(t.events("ls -la && git status"), [])
rx.finditer.assert_not_called()
class FoldAndView(unittest.TestCase):
def fold(self, *calls):
f = trackers.Fold(kit.registry())
for cmd, ts in calls:
f.feed(cmd, ts)
return f.summary()
def test_fold_keeps_the_earliest_open_and_the_latest_close(self):
s = self.fold(("new-worktree -p bffr a", "2026-11-02T10:00:00Z"),
("new-worktree -p bffr a", "2026-11-02T09:00:00Z"),
("new-worktree -r ~/worktrees/bffr-a", "2026-11-02T11:00:00Z"),
("new-worktree -r ~/worktrees/other-b", "2026-11-02T12:00:00Z"))
ent = s[KEY]
self.assertEqual(ent["sig"], tracker().sig)
self.assertEqual(ent["items"], [
{"key": "bffr-a", "name": "a", "group": "bffr",
"openedAt": "2026-11-02T09:00:00Z", "closedAt": "2026-11-02T11:00:00Z"},
{"key": "other-b", "name": "other-b", "group": None,
"openedAt": None, "closedAt": "2026-11-02T12:00:00Z"}])
def test_an_entry_for_every_tracker_even_empty(self):
self.assertEqual(self.fold(("ls", None)), {KEY: {"sig": tracker().sig, "items": []}})
def test_items_are_bounded(self):
s = self.fold(*[(f"new-worktree n{i}", "2026-11-02T10:00:00Z") for i in range(200)])
self.assertEqual(len(s[KEY]["items"]), trackers.MAX_ITEMS)
def test_the_view_reads_only_an_entry_of_the_current_rules(self):
reg = kit.registry()
good = {"trackersAuto": self.fold(("new-worktree x", "2026-11-02T10:00:00Z"))}
deps = kit.deps_with(kit.FakePluginStore())
self.assertEqual([i["key"] for i in trackers.view(deps, good, {})[KEY]], ["homelab-x"])
stale = copy.deepcopy(good)
stale["trackersAuto"][KEY]["sig"] = "0" * 12
self.assertIsNone(trackers.view(deps, stale, {}))
self.assertTrue(reg)
def test_no_plugin_no_trackers(self):
deps = kit.deps_with(kit.FakePluginStore([]))
summary = {"trackersAuto": self.fold(("new-worktree x", "2026-11-02T10:00:00Z")),
"worktreesAuto": [{"name": "a", "dir": "homelab-a"}]}
self.assertIsNone(trackers.view(deps, summary, {"worktrees": [{"dir": "homelab-b"}]}))
self.assertEqual(trackers.provided("git.worktrees", summary, {}, deps), [])
self.assertEqual(trackers.Fold(trackers.registry(deps)).summary(), {})
def test_stamps_merge_with_the_parse_and_groups_are_inferred(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
root = pathlib.Path(tmp.name)
for d in ("creature-forge", "creature", "spore-study"):
(root / d).mkdir()
with mock.patch.object(catalog, "PROJECTS_DIR", root), \
mock.patch.object(catalog, "_prefix_slugs_cache", None):
deps = kit.deps_with(kit.FakePluginStore())
summary = {"trackersAuto": self.fold(
("new-worktree -p spore-study ae-paint", "2026-10-20T19:07:08Z"),
("new-worktree -p creature-forge x", "2026-10-20T19:08:00Z"))}
# parsed: an explicit group, even one the key would not infer
summary["trackersAuto"][KEY]["items"][1]["key"] = "creature-x"
meta = {"trackers": {KEY: [
{"key": "homelab-groups", "name": "groups", "openedAt": "2026-10-20T20:00:00Z"},
{"key": "spore-study-ae-paint", "name": "spore-study-ae-paint",
"closedAt": "2026-10-20T22:24:11Z"},
{"key": "gone-project-y", "name": "y"}]}}
items = trackers.view(deps, summary, meta)[KEY]
self.assertEqual([(i["key"], i["name"], i["group"]) for i in items], [
("spore-study-ae-paint", "ae-paint", "spore-study"),
("creature-x", "x", "creature-forge"),
("homelab-groups", "groups", "homelab"),
("gone-project-y", "y", None)])
self.assertEqual(items[0]["closedAt"], "2026-10-20T22:24:11Z")
def test_prefix_project_takes_the_longest_slug(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
root = pathlib.Path(tmp.name)
for d in ("creature-forge", "creature", "ai-agent", "node_modules"):
(root / d).mkdir()
with mock.patch.object(catalog, "PROJECTS_DIR", root), \
mock.patch.object(catalog, "_prefix_slugs_cache", None):
self.assertEqual(catalog.prefix_project("creature-forge-ae-paint"), "creature-forge")
self.assertEqual(catalog.prefix_project("creature-x"), "creature")
self.assertEqual(catalog.prefix_project("ai-agent-hold-fix"), "ai-agent")
self.assertEqual(catalog.prefix_project("homelab-relay-mirror"), "homelab")
self.assertIsNone(catalog.prefix_project("gone-project-x"))
self.assertIsNone(catalog.prefix_project("node_modules-x"))
self.assertIsNone(catalog.prefix_project(""))
class ProviderAndCarryOver(unittest.TestCase):
"""``git.worktrees``: the records its readers take, and what the core
recorded before the plugin existed."""
def test_provided_maps_items_back(self):
deps = kit.deps_with(kit.FakePluginStore())
f = trackers.Fold(trackers.registry(deps))
f.feed("new-worktree -p bffr a", "2026-11-02T09:00:00Z")
f.feed("new-worktree -r ~/worktrees/bffr-a", "2026-11-02T11:00:00Z")
self.assertEqual(trackers.provided("git.worktrees", {"trackersAuto": f.summary()}, {}, deps), [
{"name": "a", "dir": "bffr-a", "project": "bffr",
"createdAt": "2026-11-02T09:00:00Z", "removedAt": "2026-11-02T11:00:00Z"}])
def test_the_cores_old_records_still_show(self):
deps = kit.deps_with(kit.FakePluginStore())
summary = {"worktreesAuto": [{"name": "old", "dir": "bffr-old", "project": "bffr",
"createdAt": "2026-10-01T10:00:00Z", "removedAt": None}]}
meta = {"worktrees": [{"name": "old", "dir": "bffr-old", "removedAt": "2026-10-02T10:00:00Z"},
{"name": "stamped", "dir": "bffr-stamped", "project": "bffr",
"createdAt": "2026-10-03T10:00:00Z"}]}
self.assertEqual(trackers.view(deps, summary, meta)[KEY], [
{"key": "bffr-old", "name": "old", "group": "bffr",
"openedAt": "2026-10-01T10:00:00Z", "closedAt": "2026-10-02T10:00:00Z"},
{"key": "bffr-stamped", "name": "stamped", "group": "bffr",
"openedAt": "2026-10-03T10:00:00Z", "closedAt": None}])
def test_a_tracker_without_the_role_reads_none_of_it(self):
mf = kit.manifest()
mf.pop("provides")
deps = kit.deps_with(kit.FakePluginStore([mf]))
self.assertIsNone(trackers.view(deps, {"worktreesAuto": [{"name": "a", "dir": "x-a"}]}, {}))
def test_the_old_stamp_becomes_an_event(self):
ev = carryover_trackers.event
self.assertEqual(ev("git.worktrees", {"name": "a", "dir": "bffr-a", "project": "bffr",
"createdAt": "T1"}),
{"do": "open", "key": "bffr-a", "name": "a", "group": "bffr", "at": "T1"})
self.assertEqual(ev("git.worktrees", {"dir": "bffr-a", "removedAt": "T2"}),
{"do": "close", "key": "bffr-a", "at": "T2"})
self.assertIsNone(ev("git.worktrees", {}))
self.assertIsNone(ev("other.role", {"dir": "x"}))
def test_fold_stamped(self):
items = trackers.fold_stamped([], {"do": "open", "key": "bffr-a", "name": "a", "at": "T1"})
items = trackers.fold_stamped(items, {"do": "close", "key": "bffr-a", "at": "T2"})
self.assertEqual(items, [{"key": "bffr-a", "name": "a", "group": None,
"openedAt": "T1", "closedAt": "T2"}])
self.assertIsNone(trackers.clean_event({"do": "open"}))
self.assertIsNone(trackers.clean_event({"do": "nope", "key": "x"}))
self.assertIsNone(trackers.clean_event({"do": "open", "key": "x" * 500}))
# ── tool trackers (the reference ``tasks`` manifest) ────────────────────────
TASKS = kit.TASKS
T = "2026-12-02T10:%02d:00Z"
def tasks_tracker():
return kit.registry([kit.manifest("tasks")]).by_key[TASKS]
class ToolRules(unittest.TestCase):
"""A tracker over a tool's calls: create / update by id / whole-list
snapshot, told apart by the input, with a status and three times."""
def fold(self, *calls, tool="todo"):
f = trackers.Fold(kit.registry([kit.manifest("tasks")]))
for i, inp in enumerate(calls):
f.feed_tool(tool, inp, T % i)
return f.summary()[TASKS]["items"]
def test_the_op_is_told_by_the_input(self):
t = tasks_tracker()
op = lambda inp: (t.op_of(inp) or {}).get("do") # noqa: E731
self.assertEqual(op({"todos": []}), "snapshot")
self.assertEqual(op({"taskId": "2", "status": "completed"}), "update")
self.assertEqual(op({"task_id": 2}), "update") # a lookup: changes nothing
self.assertEqual(op({"subject": "x", "description": "y"}), "create")
self.assertEqual(op({"content": "x"}), "create")
self.assertIsNone(op({})) # the list read back
self.assertIsNone(op({"todos": "nope"}))
def test_create_appends_and_update_cites_the_ordinal(self):
items = self.fold({"subject": "a", "description": "."}, {"subject": " b\n two "},
{}, {"taskId": "1"},
{"taskId": "1", "status": "completed"},
{"taskId": 2, "subject": "b2"}, {"taskId": "9", "status": "completed"})
self.assertEqual([(i["key"], i["name"], i["status"]) for i in items],
[("1", "a", "completed"), ("2", "b2", "pending")])
self.assertEqual(items[0], {"key": "1", "name": "a", "group": None, "status": "completed",
"openedAt": T % 0, "startedAt": None, "closedAt": T % 4})
def test_times_added_first_started_ended(self):
items = self.fold(
{"subject": "a"}, # 0
{"subject": "b"}, # 1
{"taskId": "1", "status": "in_progress"}, # 2
{"taskId": "1", "status": "in_progress"}, # 3: still the first start
{"taskId": "1", "status": "completed"}, # 4
{"taskId": "1", "status": "completed"}, # 5: still the first end
{"taskId": "2", "status": "completed"}, # 6
{"taskId": "2", "status": "pending"}) # 7: reopened
self.assertEqual([(i["openedAt"], i["startedAt"], i["closedAt"]) for i in items],
[(T % 0, T % 2, T % 4), (T % 1, None, None)])
def test_a_snapshot_replaces_the_list_and_a_same_named_item_keeps_its_times(self):
snap = lambda *rows: {"todos": [{"content": n, "status": st, "activeForm": n} # noqa: E731
for n, st in rows]}
items = self.fold(
snap(("a", "pending")), # 0
snap(("a", "in_progress"), ("b", "pending")), # 1
snap(("c", "pending"), ("a", "completed"), ("b", "cancelled")), # 2
snap(("c", "pending"), ("a", "completed"), ("b", "cancelled"))) # 3: no change
# the list's own order (the plan's), never by opening time
self.assertEqual([(i["key"], i["name"], i["status"], i["openedAt"], i["startedAt"], i["closedAt"])
for i in items], [
("1", "c", "pending", T % 2, None, None),
("2", "a", "completed", T % 0, T % 1, T % 2),
("3", "b", "cancelled", T % 1, None, T % 2)])
# a row that isn't an object is skipped; an odd status reads pending
odd = self.fold({"todos": ["x", {"content": "", "activeForm": "doing", "status": "weird"}]})
self.assertEqual([(i["name"], i["status"]) for i in odd], [("doing", "pending")])
def test_the_status_map_and_unknown_words(self):
items = self.fold({"subject": "a"}, {"subject": "b"},
{"taskId": "1", "status": "deleted"}, # the manifest's own word
{"taskId": "2", "status": "Blocked"}) # unknown: nothing moves
self.assertEqual([i["status"] for i in items], ["cancelled", "pending"])
self.assertEqual(items[0]["closedAt"], T % 2)
def test_only_its_tool_and_no_timestamp_stamps_nothing(self):
self.assertEqual(self.fold({"subject": "a"}, tool="shell"), [])
f = trackers.Fold(kit.registry([kit.manifest("tasks")]))
f.feed_tool("todo", {"subject": "a"}, None)
f.feed_tool("todo", "not an object", None)
f.feed("new-worktree x", T % 0) # no command tracker: nothing
self.assertEqual(f.summary()[TASKS]["items"], [
{"key": "1", "name": "a", "group": None, "status": "pending",
"openedAt": None, "startedAt": None, "closedAt": None}])
def test_bounded(self):
many = self.fold(*[{"subject": f"t{i}"} for i in range(trackers.MAX_TOOL_ITEMS + 20)])
self.assertEqual(len(many), trackers.MAX_TOOL_ITEMS)
long = self.fold({"subject": "x" * 1000})
self.assertEqual(len(long[0]["name"]), trackers.MAX_NAME)
snap = self.fold({"todos": [{"content": f"t{i}"} for i in range(trackers.MAX_TOOL_ITEMS + 20)]})
self.assertEqual(len(snap), trackers.MAX_TOOL_ITEMS)
def test_what_a_transcript_holds_when_it_calls_the_tool(self):
from conversations.parse.readers.toolnames import byte_hints
# the tool's names with their JSON quotes: a message that only talks
# about TaskCreate (escaped inside a string) isn't a call
self.assertEqual(set(tasks_tracker().hints),
{'"todo"', '"TodoWrite"', '"TaskCreate"', '"TaskUpdate"', '"TaskGet"',
'"TaskList"', ':update_steps"'})
self.assertEqual(byte_hints("claude:CronCreate"), ('"CronCreate"', ':CronCreate"'))
self.assertEqual(byte_hints("mcp__linear__get_issue"), ('"mcp__linear__get_issue"',))
self.assertEqual(byte_hints("shell"), ('"shell"', '"Bash"'))
self.assertEqual(tracker().hints, ("new-worktree",))
for rec in ({"type": "tool_use", "name": "TaskCreate", "input": {}},
{"t": "tool_call", "tool": "todo", "native": "update_steps"},
{"t": "tool_call", "tool": "agy:update_steps", "input": {"steps": []}}):
for dump in (json.dumps(rec), json.dumps(rec, separators=(",", ":"))):
self.assertTrue(any(h in dump for h in tasks_tracker().hints), dump)
prose = json.dumps({"type": "user", "message": {"content": 'use TaskCreate or "TodoWrite" / "todo"'}})
self.assertFalse(any(h in prose for h in tasks_tracker().hints))
class ToolView(unittest.TestCase):
def deps(self):
return kit.deps_with(kit.tasks_store())
def summary(self, *calls):
f = trackers.Fold(trackers.registry(self.deps()))
for i, inp in enumerate(calls):
f.feed_tool("todo", inp, T % i)
return {"trackersAuto": f.summary()}
def test_the_view_keeps_the_lists_order_and_takes_no_stamp(self):
s = self.summary({"todos": [{"content": "a", "status": "pending"}]},
{"todos": [{"content": "z", "status": "pending"},
{"content": "a", "status": "completed"}]})
meta = {"trackers": {TASKS: [{"key": "9", "name": "stamped", "openedAt": T % 0}]}}
got = trackers.view(self.deps(), s, meta)[TASKS]
self.assertEqual([(i["key"], i["name"]) for i in got], [("1", "z"), ("2", "a")])
got[0]["name"] = "mutated" # a copy: the summary is read-only
self.assertEqual(trackers.view(self.deps(), s, meta)[TASKS][0]["name"], "z")
def test_provided_is_the_task_list_the_scaffold_reads(self):
s = self.summary({"subject": "a"}, {"taskId": "1", "status": "in_progress"},
{"taskId": "1", "status": "completed"})
self.assertEqual(trackers.provided("tasks.list", s, {}, self.deps()), [
{"id": "1", "subject": "a", "status": "completed",
"createdAt": T % 0, "startedAt": T % 1, "endedAt": T % 2}])
# no provider: no list
none = kit.deps_with(kit.FakePluginStore([]))
self.assertEqual(trackers.provided("tasks.list", s, {}, none), [])
self.assertEqual(trackers.provided("tasks.list", s, {}, kit.deps_with(kit.FakePluginStore())), [])
def test_the_cores_old_task_list_shows_until_the_row_is_re_read(self):
old = {"tasks": [{"id": "1", "subject": "a", "status": "completed",
"createdAt": "C", "startedAt": "S", "endedAt": "E"},
{"id": "2", "subject": "b", "status": "odd"}]}
got = trackers.view(self.deps(), old, {})[TASKS]
self.assertEqual(got, [
{"key": "1", "name": "a", "group": None, "status": "completed",
"openedAt": "C", "startedAt": "S", "closedAt": "E"},
{"key": "2", "name": "b", "group": None, "status": "pending",
"openedAt": None, "startedAt": None, "closedAt": None}])
# a stale entry (other rules) falls back to it too; a current one wins
stale = {**old, "trackersAuto": {TASKS: {"sig": "0" * 12, "items": []}}}
self.assertEqual(len(trackers.view(self.deps(), stale, {})[TASKS]), 2)
fresh = {**old, **self.summary({"subject": "new"})}
self.assertEqual([i["name"] for i in trackers.view(self.deps(), fresh, {})[TASKS]], ["new"])
# …and without the role, none of it
mf = kit.manifest("tasks")
mf.pop("provides")
self.assertIsNone(trackers.view(kit.deps_with(kit.FakePluginStore([mf])), old, {}))
def test_nothing_stamps_a_tool_tracker(self):
import types
deps = self.deps()
deps.meta_store = types.SimpleNamespace(update=mock.Mock())
deps.hub = types.SimpleNamespace(publish=mock.Mock())
self.assertIsNone(trackers.stamp(deps, "sid", TASKS, {"do": "open", "key": "1"}))
deps.meta_store.update.assert_not_called()
def test_a_role_goes_to_a_tracker_of_its_kind(self):
wt, tk = kit.manifest(), kit.manifest("tasks")
reg = kit.registry([wt, tk])
self.assertEqual(reg.roles, {"git.worktrees": KEY, "tasks.list": TASKS})
wt["provides"] = {"tasks.list": "worktrees"} # a hand-edited record
tk["provides"] = {"git.worktrees": "tasks"}
self.assertEqual(kit.registry([wt, tk]).roles, {})
class ToolManifest(unittest.TestCase):
def check(self, mutate=None):
mf = kit.manifest("tasks")
if mutate:
mutate(mf)
with tempfile.TemporaryDirectory() as d:
(pathlib.Path(d) / "plugin.json").write_text(json.dumps(mf))
return validate_manifest(pathlib.Path(d))
def bad(self, mutate, needle):
with self.assertRaises(ManifestError) as cm:
self.check(mutate)
self.assertIn(needle, str(cm.exception))
def test_the_reference_manifest_validates(self):
mf = self.check()
(t,) = mf["trackers"]
self.assertEqual((t["tool"], t["statuses"]), ("todo", {"deleted": "cancelled"}))
# a path is a list of alternatives once normalized
self.assertEqual(t["ops"], [
{"do": "snapshot", "items": ["todos"], "name": ["content", "activeForm"], "status": ["status"]},
{"do": "update", "id": ["taskId", "task_id"], "name": ["subject"], "status": ["status"]},
{"do": "create", "name": ["subject", "content"]}])
self.assertEqual(mf["provides"], {"tasks.list": "tasks"})
ui = mf["ui"]
self.assertEqual(ui["card"][0]["list"], kit.manifest("tasks")["ui"]["card"][0]["list"])
self.assertEqual(ui["panels"], kit.manifest("tasks")["ui"]["panels"])
# a card drawn from a tracker is kept apart from the frames' cards
self.assertEqual(ui["toolCards"], [])
self.assertEqual(ui["trackerCards"], kit.manifest("tasks")["ui"]["toolCards"])
def test_texts_default(self):
def m(mf):
mf["ui"]["card"][0]["list"] = {"tracker": "tasks", "style": "checklist"}
mf["ui"]["panels"] = [{"id": "p", "tracker": "tasks"}]
mf["ui"]["toolCards"] = [{"id": "c", "tracker": "tasks"}]
ui = self.check(m)["ui"]
self.assertEqual(ui["card"][0]["list"], {
"tracker": "tasks", "style": "checklist", "title": "Checklist",
"progress": "{done} of {total} done", "added": "added {when}",
"started": "started {when}", "done": "done {when}",
"cancelled": "cancelled {when}", "took": "took {time}"})
self.assertEqual(ui["panels"], [{"id": "p", "tracker": "tasks", "title": "Checklist",
"show": "Show the checklist"}])
self.assertEqual(ui["trackerCards"], [{"id": "c", "tracker": "tasks", "create": "Added",
"update": "Updated", "snapshot": "Updated the list",
"many": "{count} list updates"}])
def test_a_plugin_without_them_keeps_its_shape(self):
# the worktrees manifest gains no key (its approval fingerprint holds)
with tempfile.TemporaryDirectory() as d:
(pathlib.Path(d) / "plugin.json").write_text(json.dumps(kit.manifest()))
ui = validate_manifest(pathlib.Path(d))["ui"]
self.assertNotIn("panels", ui)
self.assertNotIn("trackerCards", ui)
self.assertNotIn("style", ui["card"][0]["list"])
def test_refusals(self):
t = lambda f: (lambda mf: f(mf["trackers"][0])) # noqa: E731
self.bad(t(lambda x: x.update(command="todo")), "one of command")
self.bad(t(lambda x: x.update(hint="TaskCreate")), "a tool tracker takes")
self.bad(t(lambda x: x.update(tool="to do")), "neutral name")
self.bad(t(lambda x: x.update(ops=[])), "ops must be")
self.bad(t(lambda x: x["ops"][0].update(do="merge")), "snapshot, update, create")
self.bad(t(lambda x: x["ops"][0].pop("items")), "items is required")
self.bad(t(lambda x: x["ops"][1].pop("id")), "id is required")
self.bad(t(lambda x: x["ops"][2].update(name="a b")), "input field")
self.bad(t(lambda x: x["ops"][2].update(name=["a", "b", "c", "d", "e"])), "input field")
self.bad(t(lambda x: x["ops"][2].update(id="taskId")), "a create op takes")
self.bad(t(lambda x: x.update(statuses={"done": "finished"})), "statuses")
self.bad(lambda mf: mf.update(provides={"git.worktrees": "tasks"}), "command tracker")
self.bad(lambda mf: mf["ui"]["card"][0]["list"].update(style="grid"), "style")
self.bad(lambda mf: mf["ui"]["card"][0]["list"].update(many="{count}"), "unknown key")
self.bad(lambda mf: mf["ui"]["card"][0]["list"].update(progress="some done"), "{done}")
self.bad(lambda mf: mf["ui"]["panels"][0].update(tracker="nope"), "tool tracker")
self.bad(lambda mf: mf["ui"]["panels"][0].update(html="x.html"), "unknown key")
self.bad(lambda mf: mf["ui"]["toolCards"][0].update(tracker="nope"), "tool tracker")
self.bad(lambda mf: mf["ui"]["toolCards"][0].update(html="x.html"), "takes no html")
self.bad(lambda mf: mf["ui"]["toolCards"][0].update(many="lots"), "{count}")
self.bad(lambda mf: mf["ui"]["toolCards"].append(dict(mf["ui"]["toolCards"][0], id="again")),
"one card per tracker")
def test_a_checklist_and_a_panel_need_a_tool_tracker(self):
def m(mf):
wt = kit.manifest()
mf["trackers"].append(wt["trackers"][0])
mf["ui"]["card"][0]["list"]["tracker"] = "worktrees"
self.bad(m, "a checklist lists a tool tracker")
self.bad(lambda mf: (mf["trackers"].append(kit.manifest()["trackers"][0]),
mf["ui"]["panels"][0].update(tracker="worktrees")), "tool tracker")
# …and the worktrees role needs a command tracker, the task list a tool one
wt = kit.manifest()
wt["provides"] = {"tasks.list": "worktrees"}
with tempfile.TemporaryDirectory() as d:
(pathlib.Path(d) / "plugin.json").write_text(json.dumps(wt))
with self.assertRaises(ManifestError) as cm:
validate_manifest(pathlib.Path(d))
self.assertIn("tool tracker", str(cm.exception))
def test_the_tool_enters_the_fingerprint_and_the_consent(self):
from plugins.manifest import capability_fingerprint
a = capability_fingerprint(self.check())
b = capability_fingerprint(self.check(lambda mf: mf["trackers"][0].update(tool="claude:Other")))
self.assertNotEqual(a, b)
(item,) = trackers.consent_items(self.check())
self.assertIn("`todo` tool calls", item["label"])
class ToolParser(unittest.TestCase):
"""The transcript parse folds every tool call through the tool trackers."""
def parse(self, calls, store):
import conversations as c
with tempfile.TemporaryDirectory() as d:
p = pathlib.Path(d) / "s.jsonl"
recs = [{"type": "user", "sessionId": "s", "timestamp": T % 0, "cwd": "/home/u/x",
"message": {"role": "user", "content": "go"}}]
for i, (name, inp) in enumerate(calls):
recs.append({"type": "assistant", "sessionId": "s", "timestamp": T % (i + 1),
"message": {"role": "assistant", "model": "claude-opus-5-5", "id": f"m{i}",
"usage": {"input_tokens": 1, "output_tokens": 1},
"content": [{"type": "tool_use", "id": f"t{i}", "name": name,
"input": inp}]}})
p.write_text("".join(json.dumps(r) + "\n" for r in recs))
with kit.bound(store):
return c.parse_conversation(p), c.parse_conversation(p, full=True)
CALLS = [("TaskCreate", {"subject": "a", "description": "."}),
("TaskCreate", {"subject": "b", "description": "."}),
("TaskList", {}), ("TaskGet", {"taskId": "1"}),
("TaskUpdate", {"taskId": "1", "status": "in_progress"}),
("TaskUpdate", {"taskId": "1", "status": "completed"})]
def test_claude_codes_task_tools_fill_the_list(self):
for s in self.parse(self.CALLS, kit.tasks_store()):
self.assertNotIn("tasks", s) # the core keeps no list of its own
self.assertEqual(kit.task_list(s), [
{"key": "1", "name": "a", "group": None, "status": "completed",
"openedAt": T % 1, "startedAt": T % 5, "closedAt": T % 6},
{"key": "2", "name": "b", "group": None, "status": "pending",
"openedAt": T % 2, "startedAt": None, "closedAt": None}])
def test_the_older_todowrite_snapshots_too(self):
snap = lambda *rows: ("TodoWrite", {"todos": [ # noqa: E731
{"content": n, "status": st, "activeForm": n} for n, st in rows]})
s, _ = self.parse([snap(("a", "in_progress")), snap(("a", "completed"), ("b", "pending"))],
kit.tasks_store())
self.assertEqual([(i["name"], i["status"], i["startedAt"], i["closedAt"])
for i in kit.task_list(s)],
[("a", "completed", T % 1, T % 2), ("b", "pending", None, None)])
def test_without_the_plugin_no_list_anywhere(self):
for store in (kit.FakePluginStore([]), kit.FakePluginStore()):
s, full = self.parse(self.CALLS, store)
self.assertNotIn("tasks", s)
self.assertEqual(kit.task_list(s), [])
# …and the calls are still in the thread, as any tool's
self.assertEqual([it["native"] for it in full["thread"] if it["kind"] == "tool_use"],
[n for n, _ in self.CALLS])
class Registry(unittest.TestCase):
def test_version_holds_while_the_rules_do(self):
store = kit.FakePluginStore()
deps = kit.deps_with(store)
r1 = trackers.registry(deps)
store.version += 1 # a settings save: same rules
self.assertIs(trackers.registry(deps), r1)
mf = kit.manifest()
mf["trackers"][0]["defaults"] = {"project": "lab"}
store.put(mf)
r2 = trackers.registry(deps)
self.assertNotEqual((r2.version, r2.sig, r2.sigs), (r1.version, r1.sig, r1.sigs))
store.remove("worktrees")
self.assertFalse(trackers.registry(deps))
def test_the_first_plugin_keeps_a_role(self):
a, b = kit.manifest(), kit.manifest()
a["id"], b["id"] = "a-wt", "b-wt"
reg = kit.registry([b, a])
self.assertEqual(reg.roles, {"git.worktrees": "a-wt:worktrees"})
class Manifest(unittest.TestCase):
def check(self, mutate=None):
mf = kit.manifest()
if mutate:
mutate(mf)
with tempfile.TemporaryDirectory() as d:
(pathlib.Path(d) / "plugin.json").write_text(json.dumps(mf))
return validate_manifest(pathlib.Path(d))
def bad(self, mutate, needle):
with self.assertRaises(ManifestError) as cm:
self.check(mutate)
self.assertIn(needle, str(cm.exception))
def test_the_reference_manifest_validates(self):
mf = self.check()
self.assertEqual(mf["trackers"], kit.manifest()["trackers"])
self.assertEqual(mf["provides"], {"git.worktrees": "worktrees"})
self.assertEqual(mf["ui"]["card"][0]["list"], kit.manifest()["ui"]["card"][0]["list"])
def test_list_texts_default(self):
def m(mf):
mf["ui"]["card"][0]["list"] = {"tracker": "worktrees"}
lst = self.check(m)["ui"]["card"][0]["list"]
self.assertEqual(lst["many"], "{count}")
self.assertEqual(lst["opened"], "opened {when}")
def test_refusals(self):
t = lambda f: (lambda mf: f(mf["trackers"][0])) # noqa: E731
self.bad(t(lambda x: x.update(command="(a+)+")), "nested quantifiers")
self.bad(t(lambda x: x.update(command="(")), "invalid regex")
self.bad(t(lambda x: x.update(hint="a\"b c")), "hint")
self.bad(t(lambda x: x.update(hint="abc")), "hint")
self.bad(t(lambda x: x.update(valid="(x*)*")), "nested quantifiers")
self.bad(t(lambda x: x["events"][0].update(key="{nope}")), "unknown variable")
self.bad(t(lambda x: x["events"][0].update(key="{path:shout}")), "unknown filter")
self.bad(t(lambda x: x["events"][0].update(needs=["nope"])), "needs")
self.bad(t(lambda x: x["events"][0].update(do="toggle")), "open or close")
self.bad(t(lambda x: x.update(events=[])), "events")
self.bad(t(lambda x: x.update(group="team")), "group")
self.bad(t(lambda x: x["flags"].update(value={"r": "path"})), "flags.value")
self.bad(lambda mf: mf.update(provides={"git.worktrees": "nope"}), "declared tracker")
self.bad(lambda mf: mf["ui"]["card"][0]["list"].update(tracker="nope"), "declared tracker")
self.bad(lambda mf: mf["ui"]["card"][0]["list"].update(many="lots"), "{count}")
self.bad(lambda mf: mf["ui"]["card"][0].update(place="cost"), "list bit")
self.bad(lambda mf: mf["ui"]["card"][0]["list"].update(extra="x"), "unknown key")
self.bad(lambda mf: mf.update(trackers=mf["trackers"] * 5), "repeated")
def test_the_rules_enter_the_fingerprint(self):
from plugins.manifest import capability_fingerprint
a = capability_fingerprint(self.check())
b = capability_fingerprint(self.check(
lambda mf: mf["trackers"][0].update(command="other-tool")))
self.assertNotEqual(a, b)
class Parser(unittest.TestCase):
"""The transcript parse folds the shell commands through the active
trackers — and through none without a plugin."""
def transcript(self, d):
p = pathlib.Path(d) / "s.jsonl"
recs = [
{"type": "user", "sessionId": "s", "timestamp": "2026-11-02T10:00:00Z", "cwd": "/home/u/homelab",
"message": {"role": "user", "content": "go"}},
{"type": "assistant", "sessionId": "s", "timestamp": "2026-11-02T10:00:05Z",
"message": {"role": "assistant", "model": "claude-opus-5-5", "id": "m1",
"usage": {"input_tokens": 1, "output_tokens": 1},
"content": [{"type": "tool_use", "id": "t1", "name": "Bash",
"input": {"command": "scripts/new-worktree.sh -p bffr groups"}}]}},
{"type": "assistant", "sessionId": "s", "timestamp": "2026-11-02T11:00:05Z",
"message": {"role": "assistant", "model": "claude-opus-5-5", "id": "m2",
"usage": {"input_tokens": 1, "output_tokens": 1},
"content": [{"type": "tool_use", "id": "t2", "name": "Bash",
"input": {"command": "scripts/new-worktree.sh -r ~/worktrees/bffr-groups"}}]}},
]
p.write_text("".join(json.dumps(r) + "\n" for r in recs))
return p
def test_with_the_plugin(self):
import conversations
with tempfile.TemporaryDirectory() as d, kit.bound():
s = conversations.parse_conversation(self.transcript(d), full=False)
self.assertNotIn("worktreesAuto", s)
self.assertEqual(s["trackersAuto"][KEY]["items"], [
{"key": "bffr-groups", "name": "groups", "group": "bffr",
"openedAt": "2026-11-02T10:00:05Z", "closedAt": "2026-11-02T11:00:05Z"}])
def test_without_any(self):
import conversations
with tempfile.TemporaryDirectory() as d, kit.bound(kit.FakePluginStore([])):
s = conversations.parse_conversation(self.transcript(d), full=False)
self.assertNotIn("trackersAuto", s)
self.assertNotIn("worktreesAuto", s)
class MetaStamp(unittest.TestCase):
def test_the_meta_store_folds_a_tracker_patch(self):
import meta as meta_mod
with tempfile.TemporaryDirectory() as d:
ms = meta_mod.MetaStore(os.path.join(d, "meta.json"))
ms.update("s1", {"tracker": {"key": KEY, "event": {
"do": "open", "key": "bffr-a", "name": "a", "group": "bffr", "at": "T1"}}})
m = ms.update("s1", {"tracker": {"key": KEY, "event": {
"do": "close", "key": "bffr-a", "at": "T2"}}})
self.assertEqual(m["trackers"], {KEY: [
{"key": "bffr-a", "name": "a", "group": "bffr", "openedAt": "T1", "closedAt": "T2"}]})
self.assertNotIn("tracker", m)
if __name__ == "__main__":
unittest.main()