Files
ai-agent/scripts/ab/renames.py
gabrielvidalandClaude Opus 5.5 9c32e1676d feat(parse): a taskRef carries its card's native name
A shell_kill / shell_output / SendMessage card names the card that started
its task (`taskRef`); it now carries that card's `native` too, so the
card reads "output of Bash" as before rather than "output of shell".
Schema, openapi.json and the generated types re-dumped; the tools-v45
transform adds the same field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:03:27 +01:00

161 lines
6.9 KiB
Python

"""Renames a step was *meant* to make, applied to the BASE side's output so
``parse-ab.py --rename NAME`` can demand a zero diff against the new one.
A rename is restated here on purpose, not imported from the product: if the
product's table had a slip (``Grep`` → ``glob``), a transform built from that
same table would hide it. Nothing in this file imports product code.
``TRANSFORMS[name](summary) -> (summary', approx)``: the base summary as the
renamed parser must produce it, and the JSON paths of the costs that are sums
the new parser adds up in another order (two old cells merged into one, a
cell moved out of a bucket's total) — equal only to float rounding there.
``tools-v45`` — parser v45, the neutral tool names (ai-agent
``docs/transcript-format.md`` "Tool names"; §9 of the unified-format plan):
a tool card's ``name`` (and ``taskRef.name``) becomes the neutral name, with
``native`` = the old one (on both); the cost buckets ``bash`` → ``shell`` and ``task``
→ ``todo``; byToolSub's tool sub-keys neutral; TaskOutput / TaskStop move
from the ``tool`` bucket to ``shell`` (sub-key ``?``: they run no command),
TaskGet / TaskList to ``todo``."""
from __future__ import annotations
import copy
# ── tools-v45 ────────────────────────────────────────────────────────────────
_V45_CLAUDE = {
"Bash": "shell", "BashOutput": "shell_output", "TaskOutput": "shell_output",
"KillShell": "shell_kill", "TaskStop": "shell_kill",
"Read": "read", "NotebookRead": "read", "Write": "write",
"Edit": "edit", "MultiEdit": "edit", "NotebookEdit": "edit",
"Grep": "grep", "Glob": "glob", "LS": "list_dir",
"WebFetch": "web_fetch", "WebSearch": "web_search",
"Agent": "agent", "Task": "agent", "Skill": "skill",
"TodoWrite": "todo", "TaskCreate": "todo", "TaskUpdate": "todo",
"TaskGet": "todo", "TaskList": "todo",
"AskUserQuestion": "ask_user",
# the opencode mirror's own
"ApplyPatch": "apply_patch", "DeleteFile": "delete_file",
}
_V45_OWN = {"opencode": {"Execute": "execute"}}
_V45_BUCKET = {
"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",
}
_V45_BUCKET_KEYS = {"bash": "shell", "task": "todo"}
# Buckets whose sub-key is a file extension / program / constant, not a tool.
_V45_KEPT_SUBS = {"msg", "context", "bash", "read", "edit", "skill"}
def _v45_name(name, harness):
if not isinstance(name, str) or not name:
return name
if name in _V45_CLAUDE:
return _V45_CLAUDE[name]
if name.startswith("mcp_"):
return name
h = harness or ("pi" if name[:1].islower() else "claude")
return f"{h}:{_V45_OWN.get(h, {}).get(name, name)}"
def _v45_bucket(name) -> str:
return _V45_BUCKET.get(name or "", "tool")
def _add(acc: dict, v: dict) -> dict:
return {k: (acc.get(k) or 0) + (v.get(k) or 0) for k in ("tokens", "cost", "output")}
def _sub(acc: dict, v: dict) -> dict:
return {k: (acc.get(k) or 0) - (v.get(k) or 0) for k in ("tokens", "cost", "output")}
def tools_v45(s: dict) -> tuple[dict, set[str]]:
s = copy.deepcopy(s)
harness = s.get("harness")
approx: set[str] = set()
by_tool = s.get("byTool")
by_sub = s.get("byToolSub")
if isinstance(by_tool, dict) and isinstance(by_sub, dict):
new_tool = {_V45_BUCKET_KEYS.get(b, b): v for b, v in by_tool.items()}
new_sub: dict[str, dict] = {}
for b, subs in by_sub.items():
for sk, v in subs.items():
if b in _V45_KEPT_SUBS:
nb, nsk = _V45_BUCKET_KEYS.get(b, b), sk
elif b == "tool" and sk == "tool": # a call with no name
nb, nsk = "tool", sk
else:
nsk = _v45_name(sk, harness)
nb = _v45_bucket(nsk)
if nb == "shell":
nsk = "?" # no `command`: program "?"
if b == "tool" and nb != "tool":
# moved out of the catch-all into a real bucket
new_tool["tool"] = _sub(new_tool["tool"], v)
new_tool[nb] = _add(new_tool.get(nb) or {}, v)
approx |= {"$.byTool.tool.cost", f"$.byTool.{nb}.cost"}
cell = new_sub.setdefault(nb, {})
if nsk in cell:
cell[nsk] = _add(cell[nsk], v)
approx.add(f"$.byToolSub.{nb}.{nsk}.cost")
else:
cell[nsk] = dict(v)
if "tool" in by_sub and not new_sub.get("tool"):
# every catch-all call moved out: the new parser never opens it
new_tool.pop("tool", None)
new_sub.pop("tool", None)
s["byTool"], s["byToolSub"] = new_tool, new_sub
for it in s.get("thread") or []:
kind, name = it.get("kind"), it.get("name")
if kind == "tool_use" and name:
new = _v45_name(name, harness)
it["name"] = new
# the fold's own card for a typed `/name` has no native name
if new != name and not (it.get("role") == "user" and name == "Skill"):
it["native"] = name
elif kind == "tool_result" and name and name != "tool":
it["name"] = _v45_name(name, harness)
tb = it.get("turnBucket")
if tb in _V45_BUCKET_KEYS:
it["turnBucket"] = _V45_BUCKET_KEYS[tb]
elif tb == "tool" and kind == "tool_use":
it["turnBucket"] = _v45_bucket(it.get("name"))
ref = it.get("taskRef")
if isinstance(ref, dict) and ref.get("name"):
old = ref["name"]
ref["name"] = _v45_name(old, harness)
if ref["name"] != old:
ref["native"] = old
return s, approx
TRANSFORMS = {"tools-v45": tools_v45}
def split_costs(s: dict) -> tuple[dict, dict[str, float]]:
"""``s`` without its byTool / byToolSub costs, and those costs by JSON
path — compared apart, with a float tolerance where a rename re-sums."""
s = dict(s)
costs: dict[str, float] = {}
if isinstance(s.get("byTool"), dict):
bt = {}
for b, v in s["byTool"].items():
v = dict(v)
costs[f"$.byTool.{b}.cost"] = v.pop("cost", None)
bt[b] = v
s["byTool"] = bt
if isinstance(s.get("byToolSub"), dict):
bs = {}
for b, subs in s["byToolSub"].items():
bs[b] = {}
for sk, v in subs.items():
v = dict(v)
costs[f"$.byToolSub.{b}.{sk}.cost"] = v.pop("cost", None)
bs[b][sk] = v
s["byToolSub"] = bs
return s, costs