"""What task-bench distils from its runs' streams for the model that gathers plan items: a trace of each run worth reading, and per bug the decoys, the files that misled the runs that failed. A feature has traces and no decoys. No model reads a whole stream unless the digest leaves a question open.""" import collections import re import typing from claude_code.entries import AssistantTurn, Entry, Text, tool_calls, ToolCall, ToolResult, ToolResults from task_bench.runs import HOME, WORK from reading_cost.measure import reads_of from task_bench.figures import Side # A trace keeps the first TEXT_LINES lines of the model's text between two calls, and the first TEXT_WIDTH characters of each. TEXT_LINES = 3 TEXT_WIDTH = 200 # The characters a trace keeps of a search's pattern and of a shell command's first line. COMMAND_WIDTH = 120 CUT = " …" # The lines Claude Code's Grep and Glob print around the hits: "Found 3 files", "No matches found", "No files found", # "No entries at this offset. …", "[Showing results with pagination = limit: 3]" and "(Showing 100 of 240 matching files; …)". AROUND_HITS = re.compile(r"Found \d+ .*|No \w+ found.*|No entries at this offset.*|\[Showing .*|\(Showing .*") class Run(typing.NamedTuple): """One run of a task: the name of its stream's file without the suffix, whether its fix passed, the tokens it spent, None where it didn't finish, and its stream's entries.""" id: str passed: bool tokens: int | None entries: typing.Sequence[Entry] class TaskRuns(typing.NamedTuple): """A task as the digest tells it: its number and name, what Haiku was told, and its runs at both sides in the order they ran. For a bug, told is what the failing test printed at the base, and file is the file the bug is in. For a feature, told is its spec, and file is None.""" named: str file: str | None told: str runs: list[Run] def digest(sides: dict[Side, str], table: list[str], tasks: list[TaskRuns], is_file: typing.Callable[[str], bool], noun: str) -> str: """The digest of a bench of the commits sides names: where each side's code is, the table of its figures, then each task, which the digest calls by noun. is_file says whether a path in the project names a file.""" line = " A bug's name gives its line at the base." if noun == "bug" else "" # `trees` holds every shipped feature built; each one's task starts in trees of its own, which lack it. where = "shipped feature is in `shipped-features//base` and `shipped-features//head`" if noun == "shipped feature" else f"the {noun}s is in `trees/base` and `trees/head`" code = f"Base {sides['base']}, head {sides['head']}.{line} Each side's code without {where} in the bench's folder." return "\n".join(["# task-bench digest", "", code, "", *table, *(line for task in tasks for line in ["", *told(task, is_file, noun)])]) + "\n" def told(task: TaskRuns, is_file: typing.Callable[[str], bool], noun: str) -> list[str]: """The digest's section on task, under a heading that calls the task by noun. A task with a file is a bug; any other is a feature or a data source.""" passing, failing = [run for run in task.runs if run.passed], [run for run in task.runs if not run.passed] passed = f"{len(passing)} of the {len(task.runs)} runs passed." if failing else f"The {counted(len(task.runs), 'run')} passed." # Only a bug has a file of its own. A feature has none, so no file a run read counts as a decoy. misled = decoys([run.entries for run in failing], task.file, is_file) if task.file else [] if not task.file: found = "" elif not failing: found = " No run failed, so the bug has no decoys." elif not misled: found = f" No decoys: no file but the one the bug is in was read by more than half the {counted(len(failing), 'failing run')}." else: found = " Decoys, the files more than half the failing runs read that the bug isn't in:" shown: list[tuple[Run, str]] = [] # A run that didn't finish has no count of its tokens, and searched the longest. if unfinished := [run for run in failing if run.tokens is None]: shown.append((unfinished[0], "a failing run that didn't finish")) elif failing: most = max(failing, key=lambda run: run.tokens or 0) shown.append((most, f"the failing run that spent the most tokens, {most.tokens} tokens")) if finished := sorted((run for run in passing if run.tokens is not None), key=lambda run: run.tokens or 0): # Of an even count, the lower of the two in the middle, so the trace is a run's own. median = finished[(len(finished) - 1) // 2] shown.append((median, f"the passing run with the median tokens, {median.tokens} tokens")) return [ f"## {noun.capitalize()} {task.named}", "", "The failing test printed, at the base:" if task.file else "The spec Haiku was told:", "", *(f" {line}" for line in task.told.splitlines()), "", f"{passed}{found}", *(["", *(f"- {decoy}" for decoy in misled)] if misled else []), *(line for run, why in shown for line in ["", f"### {run.id}, {why}", "", *trace(run.entries)]), ] def decoys(failing: list[typing.Sequence[Entry]], fixed: str, is_file: typing.Callable[[str], bool]) -> list[str]: """The files of the project that more than half of the failing runs read, but for fixed, the file the bug is in: each with how many runs read it, sorted by name.""" read_by = collections.Counter(path for entries in failing for path in files_read(entries)) by = lambda count: "the one failing run" if len(failing) == 1 else f"{count} of the {len(failing)} failing runs" return [f"`{path}`, read by {by(count)}" for path, count in sorted(read_by.items()) if count * 2 > len(failing) and path != fixed and is_file(path)] def files_read(entries: typing.Sequence[Entry]) -> set[str]: """The paths in the project that the run opened or searched, a folder it searched among them.""" return {path.removeprefix(WORK + "/") for _, call in tool_calls(entries) for path in reads_of(call, WORK, HOME).read if path.startswith(WORK + "/")} def trace(entries: typing.Sequence[Entry]) -> list[str]: """The run in short: a line per tool call, and between calls the first TEXT_LINES lines of what the model wrote, each after `> `.""" results = {result.tool_use_id: result for entry in entries if isinstance(entry, ToolResults) for result in entry.results} return [line for entry in entries if isinstance(entry, AssistantTurn) for part in entry.parts for line in (written(part.text) if isinstance(part, Text) else [called(part, results.get(part.id))])] def written(text: str) -> list[str]: lines = [line.strip() for line in text.splitlines() if line.strip()] kept = [cut(line, TEXT_WIDTH) for line in lines[:TEXT_LINES]] if len(lines) > TEXT_LINES and not kept[-1].endswith(CUT): kept[-1] += CUT return [f"> {line}" for line in kept] def called(call: ToolCall, result: ToolResult | None) -> str: given = call.input searched = call.name in ("Glob", "Grep") if call.name == "Read": line = f"Read {in_project(given.get('file_path'))}{lines_asked(given)}" elif searched: line = f'{call.name} "{cut(str(given.get("pattern", "")), COMMAND_WIDTH)}"' + (f" in {in_project(given['path'])}" if given.get("path") else "") elif call.name == "Bash": first, _, rest = str(given.get("command", "")).strip().partition("\n") line = f"Bash {cut(first, COMMAND_WIDTH)}" + (CUT if rest and len(first) <= COMMAND_WIDTH else "") else: line = f"{call.name} {in_project(given['file_path'])}" if given.get("file_path") else call.name if result is None: return line if result.failed: return f"{line} → failed" return f"{line} → {counted(hits(result.text), 'hit')}" if searched else line def lines_asked(given: dict) -> str: """The lines a Read asks for, as `:120-180`; nothing where it asks for the whole file.""" offset, limit = given.get("offset"), given.get("limit") if not isinstance(offset, int) and not isinstance(limit, int): return "" first = offset if isinstance(offset, int) else 1 return f":{first}-{first + limit - 1 if isinstance(limit, int) else ''}" def hits(found: str) -> int: """The lines a search printed that name a file or a match each, without those Claude Code adds around them.""" return sum(1 for line in found.splitlines() if line.strip() and not AROUND_HITS.fullmatch(line.strip())) def in_project(path: object) -> str: return str(path).removeprefix(WORK + "/") def cut(text: str, width: int) -> str: return text if len(text) <= width else text[:width] + CUT def counted(count: int, noun: str) -> str: return f"{count} {noun}{'' if count == 1 else 's'}"