80 lines
3.2 KiB
Python
80 lines
3.2 KiB
Python
import json
|
|
import typing
|
|
|
|
from claude_code.entries import assistant_parts, human_text, loop_text, parse_entry, part_text, tool_call
|
|
from failure import Failure
|
|
|
|
JUDGED_TOOL_INPUT = 400
|
|
|
|
|
|
class Typed(typing.NamedTuple):
|
|
"""A -p prompt of loop-claude's that carries an answer the human typed: loop-claude's words, and that answer."""
|
|
loop_words: str
|
|
answer: str
|
|
|
|
|
|
def read_transcript(path: str) -> list[dict] | Failure:
|
|
try:
|
|
with open(path, "rb") as handle:
|
|
return [entry for raw in handle if (entry := parse_entry(raw))]
|
|
except OSError as failure:
|
|
return Failure(f"could not read the transcript {path}: {failure.strerror}")
|
|
|
|
|
|
def current_thread(entries: list[dict]) -> list[dict]:
|
|
"""The entries of the transcript's current thread since its last compaction, oldest first: the newest entry with a uuid and its ancestors by parentUuid.
|
|
|
|
That leaves out a branch the session rewound, and the results of parallel tool calls that Claude Code chains on a side branch."""
|
|
chained = [entry for entry in entries if isinstance(entry.get("uuid"), str)]
|
|
by_uuid = {entry["uuid"]: entry for entry in chained}
|
|
found: list[dict] = []
|
|
entry = chained[-1] if chained else None
|
|
# A compaction writes {"type": "system", "subtype": "compact_boundary", "parentUuid": null, ...}, so the thread starts there; the length check stops a parent cycle.
|
|
while entry is not None and len(found) < len(chained):
|
|
found.append(entry)
|
|
entry = by_uuid.get(entry.get("parentUuid"))
|
|
return found[::-1]
|
|
|
|
|
|
# The lines before it, such as the session's title, are the same for every chunk of a project.
|
|
def first_timestamped_line(raw: bytes) -> bytes:
|
|
lines = raw.splitlines()
|
|
return next((line for line in lines if "timestamp" in (parse_entry(line) or {})), lines[0] if lines else b"")
|
|
|
|
|
|
def human_turns(entries: list[dict]) -> int:
|
|
return sum(1 for entry in entries if human_text(entry) is not None)
|
|
|
|
|
|
def render(entries: list[dict], typed_answer: typing.Callable[[str], Typed | None]) -> str:
|
|
"""The transcript as the judge reads it. typed_answer splits the answer the human typed out of a -p prompt of loop-claude's, so that answer reads as the human's, like one typed in claude."""
|
|
lines = []
|
|
for entry in entries:
|
|
lines += [line for part in assistant_parts(entry) if (line := part_line(part, JUDGED_TOOL_INPUT))]
|
|
if (text := human_text(entry)) is not None:
|
|
lines.append("[human] " + text)
|
|
elif (text := loop_text(entry)) is not None:
|
|
typed = typed_answer(text)
|
|
lines += ["[loop] " + text] if typed is None else ["[loop] " + typed.loop_words, "[human] " + typed.answer]
|
|
return "\n\n".join(lines)
|
|
|
|
|
|
def part_line(part: object, tool_input_chars: int) -> str:
|
|
if (text := part_text(part)) and text.strip():
|
|
return text
|
|
if call := tool_call(part):
|
|
name, arguments = call
|
|
return f"[tool {name}] {json.dumps(arguments, ensure_ascii=False)[:tool_input_chars]}"
|
|
return ""
|
|
|
|
|
|
def verbatim(quote: str, text: str) -> bool:
|
|
"""Whether text holds the judge's quote word for word, once plain strips emphasis and reflows whitespace in both."""
|
|
quoted = plain(quote)
|
|
return quoted != "" and quoted in plain(text)
|
|
|
|
|
|
def plain(text: str) -> str:
|
|
# The judge drops markdown emphasis and reflows whitespace when it quotes.
|
|
return " ".join(text.replace("*", "").replace("_", "").split())
|