From b490545439c65b4d8bdabf05f6eedc7999bffb1c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 23 Nov 2026 01:01:42 +0100 Subject: [PATCH 01/11] Release review of 0.15.1 -- 2.52.0 From 21200cb6981c710d120f221a0945faa5daada1de Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 23 Nov 2026 01:01:56 +0100 Subject: [PATCH 02/11] Record the reading cost --- docs/reading-cost.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/reading-cost.md b/docs/reading-cost.md index dfc23683..2209859d 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -3442,3 +3442,17 @@ Read most (opens and searches): - `bin/task_bench/runs.py` 2 - `ci.sh` 2 - `bin/task_bench/bench_folder.py` 1 + +## Reading cost, chunk 55d6a4a1c134, finished 2026-11-23T00:01:27Z + +96728 new input tokens before the first commit. + +Read most (opens and searches): + +- `bin/task_bench/main.py` 7 +- `bin/task_bench/test_task_bench.py` 4 +- `README.md` 2 +- `bin/task_bench/plant.py` 2 +- `bin/task_bench/runs.py` 2 +- `docs/decisions.md` 2 +- `CHANGELOG.md` 1 -- 2.52.0 From 0bf87b736e9c10c6ab22eaf139164c4c485d406a Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 23 Nov 2026 01:20:55 +0100 Subject: [PATCH 03/11] =?UTF-8?q?Answer=20architecture=20round=201:=202=20?= =?UTF-8?q?=F0=9F=94=B4,=208=20=F0=9F=9F=A1=20(0=20misread);=20split=20tas?= =?UTF-8?q?k-bench's=20benched=20into=20phases=20and=20its=20table=20into?= =?UTF-8?q?=20one=20column=20list,=20parse=20each=20stream=20once,=20move?= =?UTF-8?q?=20do-epic's=20parking=20out=20with=20pure=20move=20and=20news?= =?UTF-8?q?=20decisions,=20share=20the=20round=20summaries,=20rename=20sco?= =?UTF-8?q?ring=5Fdue,=20and=20file=20the=20version=20question=20as=20item?= =?UTF-8?q?=20517?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 +- bin/agent_cycle/run.py | 2 +- bin/agent_cycle/verdicts.py | 2 +- bin/claude_code/entries.py | 5 + bin/claude_code/test_claude_code.py | 5 + bin/do_epic/epic_run.py | 83 +++++++ bin/do_epic/main.py | 251 +++++--------------- bin/do_epic/parking.py | 137 +++++++++++ bin/do_epic/test_main.py | 39 ++- bin/do_epic/test_parking.py | 44 ++++ bin/larv_review/history_commands.py | 2 +- bin/larv_review/main.py | 20 +- bin/larv_review/owed.py | 2 +- bin/larv_review/reviewer_header.py | 14 +- bin/larv_review/round_title.py | 14 +- bin/larv_review/{plan.py => scoring_due.py} | 2 + bin/larv_review/test_larv_review.py | 2 +- bin/reading_cost/measure.py | 6 +- bin/routing_figures/archive.py | 5 +- bin/task_bench/digest.py | 24 +- bin/task_bench/figures.py | 65 ++--- bin/task_bench/main.py | 202 ++++++++++------ bin/task_bench/plant.py | 17 ++ bin/task_bench/runs.py | 4 +- bin/task_bench/test_digest.py | 11 +- bin/task_bench/test_figures.py | 8 +- bin/task_bench/test_plant.py | 21 +- bin/task_bench/test_task_bench.py | 41 +++- todo.md | 14 +- 29 files changed, 678 insertions(+), 368 deletions(-) create mode 100644 bin/do_epic/epic_run.py create mode 100644 bin/do_epic/parking.py create mode 100644 bin/do_epic/test_parking.py rename bin/larv_review/{plan.py => scoring_due.py} (97%) diff --git a/README.md b/README.md index b0a5292e..70c5c165 100644 --- a/README.md +++ b/README.md @@ -243,10 +243,10 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`. - `deploy_release` imports `release_plan`'s `release_standing`. - `do_epic/` holds `do-epic`, the tool that drives one Jira epic: - - `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. + - `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `epic_run.py` holds what one run of do-epic keeps, and starts the chunks that may start now. - `planning.py` settles, before the chunks start, where each open issue is worked, its scores and the order the issues start in, through `split.py`, `repo_pick.py`, `issue_scores.py` and `ranking.py`. - `scheduler.py` says which issues run now: as many as the epic's cap and each repo's `parallel-chunks` allow, and none in a repo where loop-claude runs chunks. - - `gates.py` reads once whether a chunk's pull request waits on its checks, an approval or a new review, and `parked.py` keeps each chunk that does in a state file, so it takes no running slot while it waits and goes on waiting after a reboot. + - `gates.py` reads once whether a chunk's pull request waits on its checks, an approval or a new review, and `parked.py` keeps each chunk that does in a state file, so it takes no running slot while it waits and goes on waiting after a reboot. `parking.py` parks such a chunk after a cycle and polls the gate until its worker has something to do. - `chunk_prompt.py` words what a chunk's worker reads. Through `findings.py` that worker files a finding as an issue of the epic, with `--file`, and appends a decision to its description, with `--record-decision`. - `finish.py` ends an epic that holds no open issue: its finishing chunk files a release review of each repo the epic changed, has the human confirm each goal, and with `--close-epic` posts the summary on the epic and closes it. - `config.py` reads its machine-wide settings, importing `project_config`'s settings and `model_routing`'s ladder file, and `epic_record.py` reads and writes an epic's description by section, language line and cap line, through `record_store`'s `EpicDescription`. diff --git a/bin/agent_cycle/run.py b/bin/agent_cycle/run.py index 065cdef2..84205b86 100644 --- a/bin/agent_cycle/run.py +++ b/bin/agent_cycle/run.py @@ -100,7 +100,7 @@ def archived_stop(project_archive: pathlib.Path, session: Session, task: str, ro def archived(project_archive: pathlib.Path, transcript_path: str, task: str, outcome: str, effects: Effects, judge_run: JudgeRun | None = None) -> Failure | None: - """transcript_archive.write.archive, stamped now and saying its notes through effects. A cycle and close.py, which has no Cycle, both archive through it.""" + """transcript_archive.write.archive, stamped now and saying its notes through effects. A cycle and chunk_driver.chunk_run.closed_cycle, which has no Cycle, both archive through it.""" return archive(project_archive, transcript_path, task, outcome, effects.now(), lambda text: say(text, effects), judge_run, replace=effects.replace_file) diff --git a/bin/agent_cycle/verdicts.py b/bin/agent_cycle/verdicts.py index e5cf240d..0e33c905 100644 --- a/bin/agent_cycle/verdicts.py +++ b/bin/agent_cycle/verdicts.py @@ -38,7 +38,7 @@ class Interrupt: # How many transcript entries the judge read, which escalation_mark.stamped stamps. An escalation the verdict carries moves the route's mark there. None means it was never stamped, and then its escalation doesn't step the worker. entries_read: int | None = None judged: Judged = Judged() - # The [human] line from earlier in the chunk that answered the same question, and the words of it that leave the question open; empty for none. cycle.judge.re_ask_checked turns the Interrupt into an Unfinished where the question doesn't quote them. + # The [human] line from earlier in the chunk that answered the same question, and the words of it that leave the question open; empty for none. agent_cycle.judge.re_ask_checked turns the Interrupt into an Unfinished where the question doesn't quote them. answered_before: str = "" left_open: str = "" diff --git a/bin/claude_code/entries.py b/bin/claude_code/entries.py index e87a9450..337b2f88 100644 --- a/bin/claude_code/entries.py +++ b/bin/claude_code/entries.py @@ -84,6 +84,11 @@ def parse_entry(raw: str | bytes) -> Entry | None: return None if found is None else entry_from(found) +def entries_of(raw: bytes) -> list[Entry]: + """The entries of a transcript or a stream-json stream, one per line that is a JSON object.""" + return [entry for line in raw.splitlines() if (entry := parse_entry(line))] + + def entry_from(found: dict) -> Entry: """A transcript entry, or a stream-json event, as its kind.""" carried = Carried(uuid=field(found, "uuid"), parent_uuid=field(found, "parentUuid"), timestamp=field(found, "timestamp"), cwd=field(found, "cwd"), git_branch=field(found, "gitBranch")) diff --git a/bin/claude_code/test_claude_code.py b/bin/claude_code/test_claude_code.py index f012f115..186b6b47 100644 --- a/bin/claude_code/test_claude_code.py +++ b/bin/claude_code/test_claude_code.py @@ -99,6 +99,11 @@ class Parse(unittest.TestCase): self.assertEqual(entries.parse_entry('{"type": "user", "message": {"content": "do it"}}'), entries.HumanTurn(text="do it")) self.assertIsNone(entries.parse_entry("[1, 2]")) + def test_a_stream_parses_into_an_entry_per_line_that_is_a_json_object(self): + raw = b'{"type": "user", "message": {"content": "do it"}}\nnot json\n\n{"type": "summary"}\n' + self.assertEqual(entries.entries_of(raw), [entries.HumanTurn(text="do it"), entries.Entry()]) + self.assertEqual(entries.entries_of(b""), []) + class EntryKinds(unittest.TestCase): def test_names_who_wrote_each_user_entry_and_queued_prompt(self): diff --git a/bin/do_epic/epic_run.py b/bin/do_epic/epic_run.py new file mode 100644 index 00000000..191b7d56 --- /dev/null +++ b/bin/do_epic/epic_run.py @@ -0,0 +1,83 @@ +"""One run of do-epic on an epic (`EpicRun`), and how it starts the epic's chunks that may start now (`chunks_started`).""" +import dataclasses +import pathlib +import typing + +from do_epic.config import DoEpicConfig +from loop_effects.effects import Effects, say +from do_epic.backend.protocol import EpicIssue, EpicStore +from do_epic.epic_record import EpicRecord +from failure import Failure +from do_epic import finish, planning, scheduler +from do_epic.repos import locate +from loop_state.paths import Paths +from forge.commands import Run, runner +from agent_cycle import tmux + +# How often a parked chunk reads its pull request's gate, and a human task's window reads the epic: a person answers in hours, and each read is a few calls. +POLL_SECONDS = 60 + + +@dataclasses.dataclass(frozen=True) +class EpicRun: + """What stays the same through one run of do-epic on an epic.""" + key: str + config: DoEpicConfig + store: EpicStore + record: EpicRecord + paths: Paths + env: typing.Mapping[str, str] + launcher: pathlib.Path + effects: Effects + # The runner of git's and the forge's commands in a folder. + forge_at: typing.Callable[[str], Run] = runner + + @property + def session(self) -> str: + return tmux.session_name(tmux.EPIC, self.key) + + +def chunks_started(epic: EpicRun, issues: list[EpicIssue], own: str | None, told: str = "") -> scheduler.Started | Failure: + """scheduler.start_chunks on the epic's issues, as read, in order of score, and its cap, read afresh; own is the issue of the chunk that asks, and told is the reason the planning just gave for stopping, which isn't said twice. Where no issue is open, the chunk to start is the epic's finishing, unless the epic is closed.""" + due = finish.due(finish.landed(issues, epic.config.pull_merged_status)) + closed = due and epic.store.closed() + if isinstance(closed, Failure): + return closed + order = planning.start_order(planned_epic(epic), issues) + if isinstance(order, Failure): + say(f"the issues of {epic.key} start in Jira's backlog order, since they cannot be put in order of score" + ("" if order.reason == told else f": {order.reason}"), epic.effects, stdout=True) + elif len(order) > 1: + say(f"by score, the issues of {epic.key} start in the order {', '.join(order)}", epic.effects, stdout=True) + scheduled = scheduled_epic(epic, () if isinstance(order, Failure) else tuple(order)) + if isinstance(scheduled, Failure): + return scheduled + started = scheduler.start_chunks(scheduled, issues, due and not closed, own, epic.effects.tmux) + return started if isinstance(started, Failure) else dataclasses.replace(started, closed=closed) + + +def planned_epic(epic: EpicRun) -> planning.Planned: + """The epic as planning reads and writes it.""" + return planning.Planned(epic.key, epic.config, epic.store, epic.record, epic.paths.home, epic.effects) + + +def scheduled_epic(epic: EpicRun, order: tuple[str, ...]) -> scheduler.Epic | Failure: + """The epic as scheduler limits its chunks: with its cap, read afresh, each repo's checkout, and the order its scored issues start in.""" + cap = epic.record.parallel_chunks() + if isinstance(cap, Failure): + return cap + # The checkouts located so far, from whose remotes repos.locate tells where to clone a repo that is missing. + seen: list[pathlib.Path] = [] + + def located(name: str) -> tuple[pathlib.Path, int] | Failure: + found = locate(name, [checkout for checkout in seen], epic.config, epic.paths.home, epic.effects.git) + if isinstance(found, Failure): + return found + seen.append(found.checkout) + return real(found.checkout), found.config.parallel_chunks + + return scheduler.Epic(epic.key, cap, located, epic.paths.home, epic.launcher, epic.env, epic.config.label_repos, order, epic.config.unblocking) + + +def real(checkout: pathlib.Path) -> pathlib.Path: + """The checkout as loop-claude names it, which is as git does: through no symlink or `..`. Each keys the checkout's lock and its chunks by that path, so a project config that spells it another way hides neither from the other.""" + return checkout.resolve() diff --git a/bin/do_epic/main.py b/bin/do_epic/main.py index e46216ad..bb479885 100644 --- a/bin/do_epic/main.py +++ b/bin/do_epic/main.py @@ -11,8 +11,9 @@ import typing from chunk_driver.cycle_start import announced_route, cycle_of, project_routing, routing_on from chunk_driver.claims import CHUNK_FLAG -from do_epic import chunk_prompt, dry_run, findings, finish, gates, human_tasks, parent_moves, parked, planning, scheduler, split, status +from do_epic import chunk_prompt, dry_run, findings, finish, human_tasks, parent_moves, planning, scheduler, split, status from chunk_driver.chunk_run import ChunkRun, closed_cycle +from do_epic.epic_run import chunks_started, EpicRun, planned_epic, POLL_SECONDS, real from do_epic.repo_pick import ClaudeWork, HumanTask, recorded, Repo from project_config.main import located as config_located from chunk_driver.project.records import CONSEQUENCE, read_records @@ -33,6 +34,7 @@ from text_files.markdown_text import listed from do_epic.repos import locate from chunk_driver.this_loop import Loop from chunk_driver.project.model_choice import Models, overridden +from do_epic.parking import parked_through from loop_state.paths import Paths from chunk_driver.project.premises import read_premises from git_cli.git_repo import record_chunk_base @@ -78,8 +80,6 @@ ARCHIVE = ".claude/do-epic-transcripts" STATUS_FLAG = "--status" # The flag that prints what planning and the scheduler would do, without doing it. DRY_RUN_FLAG = "--dry-run" -# How often a parked chunk reads its pull request's gate, and a human task's window reads the epic: a person answers in hours, and each read is a few calls. -POLL_SECONDS = 60 # A call to origin that levels an epic's working branch is stopped after this long, chunk-preflight's limit for the same calls: one that hangs would hold the chunk's running slot before any cycle, with nothing said. LEVEL_SECONDS = 60 @@ -92,25 +92,6 @@ def jira_backend(config: DoEpicConfig, key: str) -> tuple[EpicStore, EpicRecord] return JiraEpic(epic, config.env_file, finish=config.finish, finding_type=config.finding_type, review_type=config.review_type, start=config.start), EpicRecord(EpicDescription(epic, config.env_file)) -@dataclasses.dataclass(frozen=True) -class EpicRun: - """What stays the same through one run of do-epic on an epic.""" - key: str - config: DoEpicConfig - store: EpicStore - record: EpicRecord - paths: Paths - env: typing.Mapping[str, str] - launcher: pathlib.Path - effects: Effects - # The runner of git's and the forge's commands in a folder. - forge_at: typing.Callable[[str], Run] = runner - - @property - def session(self) -> str: - return tmux.session_name(tmux.EPIC, self.key) - - def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, effects: Effects, backend: Backend = jira_backend, stdin: typing.TextIO = sys.stdin, forge_at: typing.Callable[[str], Run] = runner) -> int: try: stop = run(argv, env, paths, launcher, effects, backend, stdin, forge_at) @@ -233,47 +214,6 @@ def dry_run_printed(epic: EpicRun) -> Stop: return Stop(0, "") -def chunks_started(epic: EpicRun, issues: list[EpicIssue], own: str | None, told: str = "") -> scheduler.Started | Failure: - """scheduler.start_chunks on the epic's issues, as read, in order of score, and its cap, read afresh; own is the issue of the chunk that asks, and told is the reason the planning just gave for stopping, which isn't said twice. Where no issue is open, the chunk to start is the epic's finishing, unless the epic is closed.""" - due = finish.due(finish.landed(issues, epic.config.pull_merged_status)) - closed = due and epic.store.closed() - if isinstance(closed, Failure): - return closed - order = planning.start_order(planned_epic(epic), issues) - if isinstance(order, Failure): - say(f"the issues of {epic.key} start in Jira's backlog order, since they cannot be put in order of score" + ("" if order.reason == told else f": {order.reason}"), epic.effects, stdout=True) - elif len(order) > 1: - say(f"by score, the issues of {epic.key} start in the order {', '.join(order)}", epic.effects, stdout=True) - scheduled = scheduled_epic(epic, () if isinstance(order, Failure) else tuple(order)) - if isinstance(scheduled, Failure): - return scheduled - started = scheduler.start_chunks(scheduled, issues, due and not closed, own, epic.effects.tmux) - return started if isinstance(started, Failure) else dataclasses.replace(started, closed=closed) - - -def planned_epic(epic: EpicRun) -> planning.Planned: - """The epic as planning reads and writes it.""" - return planning.Planned(epic.key, epic.config, epic.store, epic.record, epic.paths.home, epic.effects) - - -def scheduled_epic(epic: EpicRun, order: tuple[str, ...]) -> scheduler.Epic | Failure: - """The epic as scheduler limits its chunks: with its cap, read afresh, each repo's checkout, and the order its scored issues start in.""" - cap = epic.record.parallel_chunks() - if isinstance(cap, Failure): - return cap - # The checkouts located so far, from whose remotes repos.locate tells where to clone a repo that is missing. - seen: list[pathlib.Path] = [] - - def located(name: str) -> tuple[pathlib.Path, int] | Failure: - found = locate(name, [checkout for checkout in seen], epic.config, epic.paths.home, epic.effects.git) - if isinstance(found, Failure): - return found - seen.append(found.checkout) - return real(found.checkout), found.config.parallel_chunks - - return scheduler.Epic(epic.key, cap, located, epic.paths.home, epic.launcher, epic.env, epic.config.label_repos, order, epic.config.unblocking) - - @dataclasses.dataclass(frozen=True) class RoutingIssue: """An issue as what routes its chunk (agent_cycle.routing.Scored).""" @@ -293,11 +233,6 @@ class RoutingIssue: return self.issue.scores.get("E", 0) + self.issue.scores.get("I", 0) -def real(checkout: pathlib.Path) -> pathlib.Path: - """The checkout as loop-claude names it, which is as git does: through no symlink or `..`. Each keys the checkout's lock and its chunks by that path, so a project config that spells it another way hides neither from the other.""" - return checkout.resolve() - - def chunk_run(key: str, epic: EpicRun) -> Stop: """Runs the cycles of the chunk of the issue called key until one stops the loop, or the judge rules the chunk finished. For a human's task it runs no cycle: it waits until the task no longer holds up an issue (`human_tasks.awaited`), then starts the next chunks. A chunk in a repo parks after each cycle that leaves its pull request waiting on a gate, and before its first where it was parked when its window last ended, as at a reboot.""" pane = epic.env.get("TMUX_PANE") @@ -376,124 +311,6 @@ def issue_started(key: str, epic: EpicRun) -> None: say(f"{key} stays assigned to {other}", epic.effects, stdout=True) -def parked_through(repo: str, loop: Loop, epic: EpicRun, told: str | None, finished: bool, based: str | None) -> str | Stop: - """Keeps the chunk in loop's window parked. Its work is in the repo called repo. It stays parked for as long as its pull request waits on a gate, and returns once its worker has something to do: what to tell that worker, or empty where the chunk was never parked. told is the news its last cycle's worker got, None where the window just started, and finished says the judge ruled the chunk finished. based is the epic's working branch that `epic_based` recorded as the chunk's base when the window started, None where it recorded none. A window that just started parks the chunk only if its file says so: the forge isn't read for a chunk that starts afresh. - - Where a person merges, a worker ends its run with the pull request open, so the judge may rule the chunk finished before it is. For such a finished chunk, a gate that cannot be read is read again until it can, and a pull request no longer open, in a worktree that still stands, is news the worker hasn't been told: the worker removes the worktree. A pull request that doesn't merge into its base is news after every cycle that leaves it so: the worker levels the branch. - - A chunk parks in three steps: its file is written, its window is shown as parked, and the epic's next chunks start in the slot it frees. It resumes in the reverse order: `scheduler.resume` gives it a running slot, then its file is removed. So a window that ends in between finds the chunk parked when it starts again. - """ - key, folder = loop.window.name, epic.paths.home / scheduler.STATE / epic.key - recorded_as = parked.parked_chunks(folder) - if isinstance(recorded_as, Failure): - return Stop(1, recorded_as.reason) - config = config_located(loop.root, epic.paths.home) - if isinstance(config, Failure): - return Stop(1, config.reason) - # A pull request into an epic's working branch merges without a person, whatever `merge` says. The base recorded says so, not the config: the gate fails where the forge merges the pull request elsewhere. - poll = Poll(key, repo, config.merge == "human" and based is None, folder, loop, epic) - if key in recorded_as: - return resumed_news(poll, recorded_as[key].on, shown=None) - entered = None if told is None else poll.first_gate(again=finished) - if not isinstance(entered, gates.Gate): - if isinstance(entered, Failure): - say(f"cannot tell whether the chunk's pull request waits on a gate, so the chunk isn't parked: {entered.reason}", epic.effects, stdout=True) - if not (finished and poll.by_human and isinstance(entered, (gates.Unopened, gates.Unmergeable))): - return "" - if isinstance(entered, gates.Unmergeable): - return f"{chunk_prompt.DRIVER} keeps the chunk open while its pull request doesn't merge into its base: {entered.news}." - uncleaned = f"{chunk_prompt.DRIVER} keeps the chunk open while its worktree stands: {entered.news}." - return "" if uncleaned in (told or "") else uncleaned - if failed := poll.record(entered): - return Stop(1, failed.reason) - if based is not None and (status := epic.config.pull_open_status): - # The team's automation moves an issue only from a pull request into the default branch. - if isinstance(moved := epic.store.move_issue(key, status), Failure): - say(f"{key} did not move to {status!r} though its pull request is open: {moved.reason}", epic.effects, stdout=True) - tmux.park(loop.window, entered.on, epic.effects.tmux) - # Once the window shows as parked, so the chunks that start count it as running nowhere. - issues = epic.store.read() - started = issues if isinstance(issues, Failure) else chunks_started(epic, issues, key) - say(f"could not start the next chunk: {started.reason}" if isinstance(started, Failure) else f"started {', '.join(started.started) or 'no other'}", epic.effects, stdout=True) - epic.effects.sleep(POLL_SECONDS) - return resumed_news(poll, entered.on, shown=entered.on) - - -@dataclasses.dataclass(frozen=True) -class Poll: - """What each read of a parked chunk's gate needs: the chunk's key, the repo its work is in, whether a person merges its pull request, the folder of the epic's parked chunks, and the chunk's loop and epic.""" - key: str - repo: str - by_human: bool - folder: pathlib.Path - loop: Loop - epic: EpicRun - - def gate(self) -> gates.Gate | gates.Open | Failure: - return gates.gate(self.key, self.loop.root, self.epic.forge_at, self.by_human) - - def first_gate(self, again: bool) -> gates.Gate | gates.Open | Failure: - """The gate as a cycle ends. Where again holds and a person merges, one that cannot be read is read again every POLL_SECONDS until it can.""" - now = self.gate() - if not again: - return now - if self.by_human and isinstance(now, Failure): - say(f"cannot read the gate of a pull request a person merges: {now.reason}; trying again every {POLL_SECONDS} seconds", self.epic.effects, stdout=True) - while self.by_human and isinstance(now, Failure): - self.epic.effects.sleep(POLL_SECONDS) - now = self.gate() - return now - - def record(self, gate: gates.Gate) -> Failure | None: - """Writes the chunk's file as parked on gate, and says so.""" - failed = parked.park(self.folder, parked.Parked(self.key, gate.worktree, gate.pull, str(self.loop.session.id), gate.on)) - if failed is None: - say(f"parked: pull request #{gate.pull} awaits {gate.on}", self.epic.effects, stdout=True) - return failed - - -def resumed_news(poll: Poll, on: str, shown: str | None) -> str | Stop: - """Reads the gate of the parked chunk every POLL_SECONDS until its worker has something to do and a running slot is free, then removes its file: what to tell that worker. on is the gate the chunk's file says it is parked on, and shown what its window's name says it awaits, None where nothing yet. A gate that cannot be read leaves the chunk parked as it was.""" - # The last reason said for staying parked. - said = None - while True: - now = poll.gate() - if isinstance(now, gates.Gate): - awaits, stays = now.on, None - if now.on != on: - if failed := poll.record(now): - return Stop(1, failed.reason) - on = now.on - elif isinstance(now, Failure): - awaits, stays = shown or on, f"cannot read the gate: {now.reason}" - else: - full = resumed(poll.repo, poll.loop, poll.epic) - if full is None: - failed = parked.unpark(poll.folder, poll.key) - return Stop(1, failed.reason) if failed is not None else f"{DRIVER_PARKED} its pull request awaited {"a person's merge" if on == gates.MERGE else on}. It resumes now: {now.news}." - awaits, stays = parked.SLOT, f"{now.news}, but the chunk stays parked: {full}" - if awaits != shown: - tmux.park(poll.loop.window, awaits, poll.epic.effects.tmux) - shown = awaits - if stays is not None and stays != said: - say(f"{stays}; trying again every {POLL_SECONDS} seconds", poll.epic.effects, stdout=True) - said = stays - poll.epic.effects.sleep(POLL_SECONDS) - - -# How the news for a chunk that was parked opens. -DRIVER_PARKED = f"{chunk_prompt.DRIVER} parked the chunk while" - - -def resumed(repo: str, loop: Loop, epic: EpicRun) -> str | None: - """scheduler.resume for the parked chunk in loop's window, whose work is in the repo called repo, on the epic's cap and repos read afresh: None once it holds a running slot, else why it stays parked.""" - # A chunk that resumes starts no other, so it needs no start order. - scheduled = scheduled_epic(epic, ()) - if isinstance(scheduled, Failure): - return scheduled.reason - return scheduler.resume(scheduled, repo, loop.window, epic.effects.tmux) - - def issue_read(key: str, epic: EpicRun) -> EpicIssue | Stop: """The epic's issue called key, read afresh.""" issues = epic.store.read() @@ -535,25 +352,69 @@ class Landed(enum.Enum): ON_EPIC_BRANCH = enum.auto() +class How(enum.Enum): + """How a finished chunk's issue moves.""" + # do-epic neither moves nor awaits it. + LEFT = enum.auto() + # do-epic moves it to the status the Move names. + TO_STATUS = enum.auto() + # Nobody would move it, so the loop stops. + STUCK = enum.auto() + # The team's automation moves it, and do-epic waits for that. + AWAITED = enum.auto() + TO_DONE = enum.auto() + + +@dataclasses.dataclass(frozen=True) +class Move: + """The move of a finished chunk's issue. For How.TO_STATUS, status is where it moves, and through a status a failed move is tried again by way of, None where there is none.""" + how: How + status: str | None = None + through: str | None = None + + +def issue_move(landed: Landed, automated: bool, merged: str | None, opened: str | None, finishing: bool) -> Move: + """The move of the issue of a finished chunk whose work landed as landed says. automated says the team's automation moves issues, merged and opened are the statuses `jira-pull-request-merged-status` and `jira-pull-request-open-status` name, each None where the config names none, and finishing says the chunk is the epic's finishing. The first row that fits: + + | The chunk | The automation moves issues | A merged status is named | Move | + |---|---|---|---| + | the epic's finishing, which has no issue | either | either | LEFT | + | a human's task | yes | either | LEFT: the human moves it | + | landed on the epic's working branch | either | yes | TO_STATUS merged, through opened | + | landed on the epic's working branch | yes | no | STUCK: the automation doesn't see that merge | + | landed on the default branch | yes | either | AWAITED | + | any other | either | either | TO_DONE | + + A chunk that never parked left its issue before the open status, from which a workflow may offer no way to the merged one: hence through.""" + if finishing or (landed is Landed.WITH_A_HUMAN and automated): + return Move(How.LEFT) + if landed is Landed.ON_EPIC_BRANCH and merged: + return Move(How.TO_STATUS, merged, opened or None) + if landed is Landed.ON_EPIC_BRANCH and automated: + return Move(How.STUCK) + if landed is Landed.ON_DEFAULT_BRANCH and automated: + return Move(How.AWAITED) + return Move(How.TO_DONE) + + def handed_on(key: str, epic: EpicRun, landed: Landed = Landed.NOWHERE) -> Stop: """The stop of a do-epic whose chunk finished. It first moves the chunk's issue to done (the epic's finishing has none), and its parent too where the parent's sub-tasks now let it move (`parents_settled`), so that no finished chunk starts again and what they block may start, then starts each chunk that may start now. Where the team's automation moves issues, others move two kinds of issue. The automation moves the issue of a chunk whose work landed on the default branch, from its pull request: the stop waits for that move (`moved_by_automation`). The human moves their own task: the stop doesn't move or await anything. A chunk without a repo has no pull request, so its issue moves to done as ever, and so does a split item, once Jira counts each of its sub-tasks done. The automation doesn't see a pull request that merged into an epic's working branch: the stop moves that chunk's issue to the status `jira-pull-request-merged-status` names. Where none is named, it moves the issue to done, or stops where the automation moves issues, since then nobody would move it. do-epic's window closes as it exits.""" - automated = epic.config.automation_moves - # The epic's finishing has no issue to move: the epic is closed by `--close-epic`. Nor has a human's task where the human moves it: its window waited until it holds up no issue. - if key == epic.key or (landed is Landed.WITH_A_HUMAN and automated): - issues: list[EpicIssue] | Failure = epic.store.read() - elif landed is Landed.ON_EPIC_BRANCH and (status := epic.config.pull_merged_status): + move = issue_move(landed, epic.config.automation_moves, epic.config.pull_merged_status, epic.config.pull_open_status, finishing=key == epic.key) + issues: list[EpicIssue] | Failure + if move.how is How.LEFT: + issues = epic.store.read() + elif move.how is How.TO_STATUS and (status := move.status): moved = epic.store.move_issue(key, status) - # A chunk that never parked left its issue before the open status, from which a workflow may offer no way to the merged one. - if isinstance(moved, Failure) and (opened := epic.config.pull_open_status) and not isinstance(epic.store.move_issue(key, opened), Failure): + if isinstance(moved, Failure) and move.through and not isinstance(epic.store.move_issue(key, move.through), Failure): moved = epic.store.move_issue(key, status) if isinstance(moved, Failure): return Stop(1, f"the chunk finished, but its issue could not move to {status!r}: {moved.reason}; once it has that status in Jira, run `do-epic {epic.key}` to start the chunks it blocks") issues = epic.store.read() # A search may not show the move yet, so the issue counts as moved here whatever the read says. issues = issues if isinstance(issues, Failure) else [dataclasses.replace(each, status=status) if each.key == key else each for each in issues] - elif landed is Landed.ON_EPIC_BRANCH and automated: + elif move.how is How.STUCK: return Stop(1, f"the chunk finished, but its issue stays as it is: its pull request merged into the epic's working branch, where the team's automation moves no issue, and do-epic's config names no `{PULL_MERGED_STATUS}` to move it to. Move {key} in Jira, then run `do-epic {epic.key}` to start the chunks it blocks") - elif landed is Landed.ON_DEFAULT_BRANCH and automated: + elif move.how is How.AWAITED: issues = moved_by_automation(key, epic) else: moved = epic.store.finish_issue(key) diff --git a/bin/do_epic/parking.py b/bin/do_epic/parking.py new file mode 100644 index 00000000..55df9e6f --- /dev/null +++ b/bin/do_epic/parking.py @@ -0,0 +1,137 @@ +"""A chunk parked while its pull request waits on a gate (docs/decisions.md → `do-epic: drives one Jira epic …`): `parked_through` keeps it parked from the end of a cycle until its worker has something to do, and `news_after` says what a chunk that isn't parked tells its worker.""" +import dataclasses +import pathlib + +from do_epic import chunk_prompt, gates, parked, scheduler +from do_epic.epic_run import chunks_started, EpicRun, POLL_SECONDS, scheduled_epic +from project_config.main import located as config_located +from failure import Failure +from chunk_driver.this_loop import Loop +from loop_effects.effects import say +from agent_cycle.stop import Stop +from agent_cycle import tmux + + +def parked_through(repo: str, loop: Loop, epic: EpicRun, told: str | None, finished: bool, based: str | None) -> str | Stop: + """Keeps the chunk in loop's window parked. Its work is in the repo called repo. It stays parked for as long as its pull request waits on a gate, and returns once its worker has something to do: what to tell that worker, or empty where the chunk was never parked. told is the news its last cycle's worker got, None where the window just started, and finished says the judge ruled the chunk finished. based is the epic's working branch that `epic_based` recorded as the chunk's base when the window started, None where it recorded none. A window that just started parks the chunk only if its file says so: the forge isn't read for a chunk that starts afresh. + + Where a person merges, a worker ends its run with the pull request open, so the judge may rule the chunk finished before it is. For such a finished chunk, a gate that cannot be read is read again until it can, and a pull request no longer open, in a worktree that still stands, is news the worker hasn't been told: the worker removes the worktree. A pull request that doesn't merge into its base is news after every cycle that leaves it so: the worker levels the branch. + + A chunk parks in three steps: its file is written, its window is shown as parked, and the epic's next chunks start in the slot it frees. It resumes in the reverse order: `scheduler.resume` gives it a running slot, then its file is removed. So a window that ends in between finds the chunk parked when it starts again. + """ + key, folder = loop.window.name, epic.paths.home / scheduler.STATE / epic.key + recorded_as = parked.parked_chunks(folder) + if isinstance(recorded_as, Failure): + return Stop(1, recorded_as.reason) + config = config_located(loop.root, epic.paths.home) + if isinstance(config, Failure): + return Stop(1, config.reason) + # A pull request into an epic's working branch merges without a person, whatever `merge` says. The base recorded says so, not the config: the gate fails where the forge merges the pull request elsewhere. + poll = Poll(key, repo, config.merge == "human" and based is None, folder, loop, epic) + if key in recorded_as: + return resumed_news(poll, recorded_as[key].on, shown=None) + entered = None if told is None else poll.first_gate(again=finished) + if not isinstance(entered, gates.Gate): + if isinstance(entered, Failure): + say(f"cannot tell whether the chunk's pull request waits on a gate, so the chunk isn't parked: {entered.reason}", epic.effects, stdout=True) + return news_after(entered, finished, poll.by_human, told) + if failed := poll.record(entered): + return Stop(1, failed.reason) + if based is not None and (status := epic.config.pull_open_status): + # The team's automation moves an issue only from a pull request into the default branch. + if isinstance(moved := epic.store.move_issue(key, status), Failure): + say(f"{key} did not move to {status!r} though its pull request is open: {moved.reason}", epic.effects, stdout=True) + tmux.park(loop.window, entered.on, epic.effects.tmux) + # Once the window shows as parked, so the chunks that start count it as running nowhere. + issues = epic.store.read() + started = issues if isinstance(issues, Failure) else chunks_started(epic, issues, key) + say(f"could not start the next chunk: {started.reason}" if isinstance(started, Failure) else f"started {', '.join(started.started) or 'no other'}", epic.effects, stdout=True) + epic.effects.sleep(POLL_SECONDS) + return resumed_news(poll, entered.on, shown=entered.on) + + +def news_after(entered: gates.Open | Failure | None, finished: bool, by_human: bool, told: str | None) -> str: + """What to tell the worker of a chunk that isn't parked as its cycle ends, empty where there isn't anything. entered is what was read instead of a gate, None where the window just started. Only a chunk the judge ruled finished, whose pull request a person merges, has news: that its pull request doesn't merge into its base, after every cycle that leaves it so, or that its worktree stands though no pull request is open, unless told, the news its last worker got, says so already.""" + if not (finished and by_human): + return "" + if isinstance(entered, gates.Unmergeable): + return f"{chunk_prompt.DRIVER} keeps the chunk open while its pull request doesn't merge into its base: {entered.news}." + if isinstance(entered, gates.Unopened): + uncleaned = f"{chunk_prompt.DRIVER} keeps the chunk open while its worktree stands: {entered.news}." + return "" if uncleaned in (told or "") else uncleaned + return "" + + +@dataclasses.dataclass(frozen=True) +class Poll: + """What each read of a parked chunk's gate needs: the chunk's key, the repo its work is in, whether a person merges its pull request, the folder of the epic's parked chunks, and the chunk's loop and epic.""" + key: str + repo: str + by_human: bool + folder: pathlib.Path + loop: Loop + epic: EpicRun + + def gate(self) -> gates.Gate | gates.Open | Failure: + return gates.gate(self.key, self.loop.root, self.epic.forge_at, self.by_human) + + def first_gate(self, again: bool) -> gates.Gate | gates.Open | Failure: + """The gate as a cycle ends. Where again holds and a person merges, one that cannot be read is read again every POLL_SECONDS until it can.""" + now = self.gate() + if not again: + return now + if self.by_human and isinstance(now, Failure): + say(f"cannot read the gate of a pull request a person merges: {now.reason}; trying again every {POLL_SECONDS} seconds", self.epic.effects, stdout=True) + while self.by_human and isinstance(now, Failure): + self.epic.effects.sleep(POLL_SECONDS) + now = self.gate() + return now + + def record(self, gate: gates.Gate) -> Failure | None: + """Writes the chunk's file as parked on gate, and says so.""" + failed = parked.park(self.folder, parked.Parked(self.key, gate.worktree, gate.pull, str(self.loop.session.id), gate.on)) + if failed is None: + say(f"parked: pull request #{gate.pull} awaits {gate.on}", self.epic.effects, stdout=True) + return failed + + +def resumed_news(poll: Poll, on: str, shown: str | None) -> str | Stop: + """Reads the gate of the parked chunk every POLL_SECONDS until its worker has something to do and a running slot is free, then removes its file: what to tell that worker. on is the gate the chunk's file says it is parked on, and shown what its window's name says it awaits, None where nothing yet. A gate that cannot be read leaves the chunk parked as it was.""" + # The last reason said for staying parked. + said = None + while True: + now = poll.gate() + if isinstance(now, gates.Gate): + awaits, stays = now.on, None + if now.on != on: + if failed := poll.record(now): + return Stop(1, failed.reason) + on = now.on + elif isinstance(now, Failure): + awaits, stays = shown or on, f"cannot read the gate: {now.reason}" + else: + full = resumed(poll.repo, poll.loop, poll.epic) + if full is None: + failed = parked.unpark(poll.folder, poll.key) + return Stop(1, failed.reason) if failed is not None else f"{DRIVER_PARKED} its pull request awaited {"a person's merge" if on == gates.MERGE else on}. It resumes now: {now.news}." + awaits, stays = parked.SLOT, f"{now.news}, but the chunk stays parked: {full}" + if awaits != shown: + tmux.park(poll.loop.window, awaits, poll.epic.effects.tmux) + shown = awaits + if stays is not None and stays != said: + say(f"{stays}; trying again every {POLL_SECONDS} seconds", poll.epic.effects, stdout=True) + said = stays + poll.epic.effects.sleep(POLL_SECONDS) + + +# How the news for a chunk that was parked opens. +DRIVER_PARKED = f"{chunk_prompt.DRIVER} parked the chunk while" + + +def resumed(repo: str, loop: Loop, epic: EpicRun) -> str | None: + """scheduler.resume for the parked chunk in loop's window, whose work is in the repo called repo, on the epic's cap and repos read afresh: None once it holds a running slot, else why it stays parked.""" + # A chunk that resumes starts no other, so it needs no start order. + scheduled = scheduled_epic(epic, ()) + if isinstance(scheduled, Failure): + return scheduled.reason + return scheduler.resume(scheduled, repo, loop.window, epic.effects.tmux) diff --git a/bin/do_epic/test_main.py b/bin/do_epic/test_main.py index cac4f295..df62b4b8 100644 --- a/bin/do_epic/test_main.py +++ b/bin/do_epic/test_main.py @@ -12,7 +12,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from do_epic import chunk_prompt, main, planning +from do_epic import chunk_prompt, epic_run, main, planning from chunk_driver.chunk_run import ChunkRun from project_config.doubles import configured from do_epic.config import DoEpicConfig @@ -86,11 +86,11 @@ class DoEpicTest(unittest.TestCase): self.issues = [issue("ABC-20", "repo:api")] return folder - def epic_run(self, fake: FakeEffects, env: dict[str, str] | None = None) -> main.EpicRun: + def epic_run(self, fake: FakeEffects, env: dict[str, str] | None = None) -> epic_run.EpicRun: config = main.load(self.home) assert not isinstance(config, Failure) store, record = self.backend(config, "ABC-12") - return main.EpicRun("ABC-12", config, store, record, paths_from(self.home), env or {}, pathlib.Path("/b/do-epic"), fake.effects()) + return epic_run.EpicRun("ABC-12", config, store, record, paths_from(self.home), env or {}, pathlib.Path("/b/do-epic"), fake.effects()) def run_main(self, argv: list[str], fake: FakeEffects, env: dict[str, str] | None = None) -> tuple[int, str, str]: out, err = io.StringIO(), io.StringIO() @@ -1237,6 +1237,37 @@ class AnEpicsWorkingBranch(DoEpicTest): self.assertTrue(stop.reason.endswith("once it has that status in Jira, run `do-epic ABC-12` to start the chunks it blocks"), stop.reason) +class TheMoveOfAFinishedChunksIssue(unittest.TestCase): + def move(self, landed: main.Landed, automated: bool, merged: str | None = None, opened: str | None = None, finishing: bool = False) -> main.Move: + return main.issue_move(landed, automated, merged, opened, finishing) + + def test_the_epics_finishing_has_no_issue_to_move(self) -> None: + for automated in (False, True): + self.assertEqual(self.move(main.Landed.NOWHERE, automated, "Release Ready", "In Review", finishing=True), main.Move(main.How.LEFT)) + + def test_a_humans_task_is_left_where_the_automation_moves_issues_and_done_otherwise(self) -> None: + self.assertEqual(self.move(main.Landed.WITH_A_HUMAN, True, "Release Ready"), main.Move(main.How.LEFT)) + self.assertEqual(self.move(main.Landed.WITH_A_HUMAN, False, "Release Ready"), main.Move(main.How.TO_DONE)) + + def test_a_chunk_without_a_repo_moves_to_done(self) -> None: + for automated in (False, True): + self.assertEqual(self.move(main.Landed.NOWHERE, automated, "Release Ready", "In Review"), main.Move(main.How.TO_DONE)) + + def test_work_on_the_default_branch_awaits_the_automation_or_moves_to_done(self) -> None: + self.assertEqual(self.move(main.Landed.ON_DEFAULT_BRANCH, True, "Release Ready", "In Review"), main.Move(main.How.AWAITED)) + self.assertEqual(self.move(main.Landed.ON_DEFAULT_BRANCH, False, "Release Ready", "In Review"), main.Move(main.How.TO_DONE)) + + def test_work_on_the_epics_branch_moves_to_the_merged_status_through_the_open_one_where_named(self) -> None: + for automated in (False, True): + self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, automated, "Release Ready", "In Review"), main.Move(main.How.TO_STATUS, "Release Ready", "In Review")) + self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, automated, "Release Ready"), main.Move(main.How.TO_STATUS, "Release Ready")) + + def test_work_on_the_epics_branch_with_no_merged_status_is_stuck_under_automation_and_done_otherwise(self) -> None: + self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, True, None, "In Review"), main.Move(main.How.STUCK)) + self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, True, "", "In Review"), main.Move(main.How.STUCK)) + self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, False, None, "In Review"), main.Move(main.How.TO_DONE)) + + class TheStatus(DoEpicTest): def test_prints_what_each_open_issue_does_and_starts_nothing(self) -> None: self.issues = [issue("ABC-21", "repo:api"), issue("ABC-24", "repo:api"), issue("ABC-27")] @@ -1369,7 +1400,7 @@ class TheDryRun(DoEpicTest): self.issues = [dataclasses.replace(issue(key, "do-epic-claude"), scores={"L": 1, "E": 1, "I": 1, "S": 1}) for key in ("ABC-20", "ABC-21")] out = io.StringIO() with contextlib.redirect_stdout(out): - main.chunks_started(self.epic_run(FakeEffects(on_terminal=False)), self.issues, None) + epic_run.chunks_started(self.epic_run(FakeEffects(on_terminal=False)), self.issues, None) self.assertIn("the issues of ABC-12 start in Jira's backlog order, since they cannot be put in order of score: the epic ABC-12's description states `Score = ...` 0 times under ## Scoring", out.getvalue()) self.description = DESCRIPTION.replace("Ship the import.", "1. **Achieve:** Ship the import.") + "\n## Scoring\n`Score = V`\n" self.issues = self.issues[:1] diff --git a/bin/do_epic/test_parking.py b/bin/do_epic/test_parking.py new file mode 100644 index 00000000..4a7d2154 --- /dev/null +++ b/bin/do_epic/test_parking.py @@ -0,0 +1,44 @@ +import pathlib +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from do_epic import chunk_prompt +from failure import Failure +from do_epic.parking import news_after +from do_epic.gates import Open, Unmergeable, Unopened + +UNOPENED = Unopened("no pull request is open") +UNCLEANED = f"{chunk_prompt.DRIVER} keeps the chunk open while its worktree stands: no pull request is open." +UNMERGEABLE = Unmergeable("pull request #7 conflicts with its base branch") +UNLEVELLED = f"{chunk_prompt.DRIVER} keeps the chunk open while its pull request doesn't merge into its base: pull request #7 conflicts with its base branch." + + +class TheNewsOfAChunkThatIsNotParked(unittest.TestCase): + def test_a_window_that_just_started_has_no_news(self) -> None: + self.assertEqual(news_after(None, finished=True, by_human=True, told=None), "") + + def test_a_gate_that_cannot_be_read_or_a_pull_request_with_news_of_its_own_adds_none(self) -> None: + for entered in (Failure("no network"), Open("a reviewer requested changes")): + with self.subTest(entered): + self.assertEqual(news_after(entered, finished=True, by_human=True, told=""), "") + + def test_an_unfinished_chunk_or_one_no_person_merges_has_no_news(self) -> None: + for entered in (UNOPENED, UNMERGEABLE): + for finished, by_human in ((False, True), (True, False), (False, False)): + with self.subTest(entered=entered, finished=finished, by_human=by_human): + self.assertEqual(news_after(entered, finished, by_human, told=""), "") + + def test_a_finished_chunk_a_person_merges_is_told_its_worktree_stands_once(self) -> None: + self.assertEqual(news_after(UNOPENED, finished=True, by_human=True, told=""), UNCLEANED) + self.assertEqual(news_after(UNOPENED, finished=True, by_human=True, told=UNLEVELLED), UNCLEANED) + self.assertEqual(news_after(UNOPENED, finished=True, by_human=True, told=f"Before. {UNCLEANED}"), "") + + def test_a_finished_chunk_a_person_merges_is_told_after_every_cycle_that_its_pull_request_doesnt_merge(self) -> None: + self.assertEqual(news_after(UNMERGEABLE, finished=True, by_human=True, told=""), UNLEVELLED) + self.assertEqual(news_after(UNMERGEABLE, finished=True, by_human=True, told=UNLEVELLED), UNLEVELLED) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/larv_review/history_commands.py b/bin/larv_review/history_commands.py index cbc39cf2..cebd2b80 100644 --- a/bin/larv_review/history_commands.py +++ b/bin/larv_review/history_commands.py @@ -3,7 +3,7 @@ import typing from larv_review.agreement import agreement_report from review_rules.comprehension_history import appended, DIMENSIONS, heading, Heading, latest_places, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text -from larv_review.plan import checkout_plan, plan_reasons +from larv_review.scoring_due import checkout_plan, plan_reasons from git_cli.git_repo import commit_exists from larv_review.ruling import counted, overall, ruling, split, surplus, votes from failure import Failure diff --git a/bin/larv_review/main.py b/bin/larv_review/main.py index d260a28f..b745e92a 100644 --- a/bin/larv_review/main.py +++ b/bin/larv_review/main.py @@ -34,7 +34,7 @@ needs-scoring-run takes the IDs of the todo.md items the chunk ships, none when prints why the chunk is due a scoring run, or `No scoring run due.` It is due when the chunk ships a floor item, one whose tagline opens with `Reach the comprehension floor:`. It is also due when the chunk leaves a release with no item in the project's todo.md, once the shipped items are set aside, and work has landed -towards that release; bin/larv_review/plan.py's `work_landed` and `landed_towards` say when. A release the checkout's +towards that release; bin/larv_review/scoring_due.py's `work_landed` and `landed_towards` say when. A release the checkout's todo.md marks renamed in its ## Renamed section, as `- 0.2.1 renamed to 0.3.0`, is due none. A chunk is also due one while no scoring run in the default branch's history is newer than the commit of its second-newest v* tag, so a release cut unmeasured is caught up by the next chunk. A project whose @@ -171,8 +171,9 @@ import sys import time import typing -from git_cli.git_repo import branch_titles, default_branch, git, top +from larv_review.reviewer_header import branch_summaries, reviewer_header from review_rules.round_titles import cap, CAP, RELEASE_REVIEW_CAP, round_counts +from git_cli.git_repo import default_branch, git, top from project_config.settings import DEFAULT_FLOOR from failure import Failure from larv_review.history_changes import history_changes @@ -182,12 +183,10 @@ from larv_review.ruling_base import measured_commit from larv_review.agreement import MIN_PAIRS from larv_review.owed import owed_scoring_run from review_rules.review_passes import PASSES, REVIEWERS -from larv_review.plan import plan_reasons +from larv_review.scoring_due import plan_reasons from larv_review.scoring_setup import prepare_scoring from larv_review.history_commands import read_agreement, read_places, record_ruling, record_scoring -from larv_review.reviewer_header import reviewer_header from larv_review.round_title import round_title -from project_config.main import title_templates class Command(typing.NamedTuple): @@ -321,13 +320,10 @@ def show_ruling_base(default: str, home: pathlib.Path) -> Failure | None: def round_count(default: str) -> Failure | None: - titles = branch_titles(default) - if isinstance(titles, Failure): - return titles - templates = title_templates(None, pathlib.Path.home()) - if isinstance(templates, Failure): - return templates - for name, count in round_counts([templates.summary(title) for title in titles]).items(): + summaries = branch_summaries(default, pathlib.Path.home()) + if isinstance(summaries, Failure): + return summaries + for name, count in round_counts(summaries).items(): print(f"{name}: {count}{cap_note(count, cap(name)) if name in PASSES else ', not a pass: check the commit title'}") return None diff --git a/bin/larv_review/owed.py b/bin/larv_review/owed.py index a1e30dfb..079ba26b 100644 --- a/bin/larv_review/owed.py +++ b/bin/larv_review/owed.py @@ -1,7 +1,7 @@ import pathlib import typing -from larv_review.plan import Emptied, plan_reasons +from larv_review.scoring_due import Emptied, plan_reasons from review_rules.comprehension_history import entries from failure import Failure from git_cli.git_repo import file_at, git diff --git a/bin/larv_review/reviewer_header.py b/bin/larv_review/reviewer_header.py index d565302b..872ca8cb 100644 --- a/bin/larv_review/reviewer_header.py +++ b/bin/larv_review/reviewer_header.py @@ -80,15 +80,19 @@ def unanswered_round(titles: list[str], pass_: str) -> int | Failure: return done + 1 -def reviewer_header(default: str, pass_: str, rerun: bool, home: pathlib.Path) -> str | Failure: - """Writes the branch diff, the places and the plan's listing into the review folder, and returns the header that launches pass_'s reviewer in the pass's unanswered round, or its relaunch one rung up where rerun.""" +def branch_summaries(default: str, home: pathlib.Path) -> list[str] | Failure: + """The branch's commit titles since default, each read as its summary in the project's title templates, so round titles count under any template. rule-hook's round-cap reads them its own way: guarded, and counting none where git fails.""" titles = branch_titles(default) if isinstance(titles, Failure): return titles templates = title_templates(None, home) - if isinstance(templates, Failure): - return templates - round_ = unanswered_round([templates.summary(title) for title in titles], pass_) + return templates if isinstance(templates, Failure) else [templates.summary(title) for title in titles] + + +def reviewer_header(default: str, pass_: str, rerun: bool, home: pathlib.Path) -> str | Failure: + """Writes the branch diff, the places and the plan's listing into the review folder, and returns the header that launches pass_'s reviewer in the pass's unanswered round, or its relaunch one rung up where rerun.""" + summaries = branch_summaries(default, home) + round_ = summaries if isinstance(summaries, Failure) else unanswered_round(summaries, pass_) if isinstance(round_, Failure): return round_ found = [top(), *(git(*args) for args in (["symbolic-ref", "--short", "HEAD"], ["rev-parse", "--short", "HEAD"], ["merge-base", "HEAD", default]))] diff --git a/bin/larv_review/round_title.py b/bin/larv_review/round_title.py index 27bb249b..0485cac5 100644 --- a/bin/larv_review/round_title.py +++ b/bin/larv_review/round_title.py @@ -1,23 +1,17 @@ """round-title: print the opening of a round commit's title, counted from the round's report.""" import pathlib -from git_cli.git_repo import branch_titles, top +from larv_review.reviewer_header import branch_summaries, unanswered_round from failure import Failure from review_rules.review_folder import findings_in, review_folder, standing_report from review_rules.round_titles import round_prefix -from project_config.main import title_templates -from larv_review.reviewer_header import unanswered_round +from git_cli.git_repo import top def round_title(default: str, pass_: str, home: pathlib.Path) -> str | Failure: """The title prefix of pass_'s unanswered round, counted from that round's report in the chunk's review folder.""" - titles = branch_titles(default) - if isinstance(titles, Failure): - return titles - templates = title_templates(None, home) - if isinstance(templates, Failure): - return templates - round_ = unanswered_round([templates.summary(title) for title in titles], pass_) + summaries = branch_summaries(default, home) + round_ = summaries if isinstance(summaries, Failure) else unanswered_round(summaries, pass_) if isinstance(round_, Failure): return round_ worktree = top() diff --git a/bin/larv_review/plan.py b/bin/larv_review/scoring_due.py similarity index 97% rename from bin/larv_review/plan.py rename to bin/larv_review/scoring_due.py index bbe378b8..2d7a17f7 100644 --- a/bin/larv_review/plan.py +++ b/bin/larv_review/scoring_due.py @@ -1,3 +1,5 @@ +"""When the plan calls a scoring run: a chunk that ships a floor item, one that empties a release work has landed towards, or one after a release cut unmeasured; and each reason it gives.""" + import pathlib from release_plan.release_standing import Cut, LastCut, next_release, project_plan, standing_of, Unknown diff --git a/bin/larv_review/test_larv_review.py b/bin/larv_review/test_larv_review.py index 8aba70b4..177e0189 100644 --- a/bin/larv_review/test_larv_review.py +++ b/bin/larv_review/test_larv_review.py @@ -15,7 +15,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from larv_review.agreement import agreement_report, ruling_agreement, run_agreement from review_rules.comprehension_history import appended, entries, HistoryChange, latest_places, Place, recorded, ruling_entry, scoring_entry, ScoringRun, Seat from larv_review.history_commands import appended_to -from larv_review.plan import checkout_plan, Emptied, EMPTIED_WORDS, landed_towards, plan_reasons, scoring_run_due +from larv_review.scoring_due import checkout_plan, Emptied, EMPTIED_WORDS, landed_towards, plan_reasons, scoring_run_due from review_rules import comprehension_history from project_config.doubles import configured from larv_review.ruling import counted, ruling, split, surplus, votes diff --git a/bin/reading_cost/measure.py b/bin/reading_cost/measure.py index 65690a45..f426c1e4 100644 --- a/bin/reading_cost/measure.py +++ b/bin/reading_cost/measure.py @@ -2,7 +2,7 @@ import collections import dataclasses import re -from claude_code.entries import AssistantTurn, Entry, messages, parse_entry, tool_calls, ToolCall, usage_count +from claude_code.entries import AssistantTurn, entries_of, Entry, messages, tool_calls, ToolCall, usage_count from git_cli.git_command import commits from reading_cost.shell_reads import Reads, shell_reads from command_lines.shell_command import resolved, simple_commands @@ -38,10 +38,6 @@ def measure(threads: list[bytes], checkout: Checkout, home: str) -> Reading | No return Reading(sum(map(tokens_in, before)), files) -def entries_of(raw: bytes) -> list[Entry]: - return [entry for line in raw.splitlines() if (entry := parse_entry(line))] - - def commit_time(worker: list[Entry], home: str) -> str | None: return next((turn.timestamp for turn, call in tool_calls(worker) if call.name == "Bash" and commits(simple_commands(str(call.input.get("command", "")), turn.cwd, home), home)), None) diff --git a/bin/routing_figures/archive.py b/bin/routing_figures/archive.py index 240fdea4..e79f962d 100644 --- a/bin/routing_figures/archive.py +++ b/bin/routing_figures/archive.py @@ -3,7 +3,6 @@ import contextlib import dataclasses import fcntl import functools -import io import json import pathlib import typing @@ -14,7 +13,7 @@ from branch_chunks.cut import BranchChunk from transcript_archive.project_key import checkout_of from routing_figures.chunk import Chunk, chunk_figures, ChunkFigures, Subagent from git_cli.git_repo import default_ref, Git -from claude_code.entries import Entry, parse_entry +from claude_code.entries import entries_of, Entry from failure import Failure from text_files.compressed import read_stored from text_files.file_writes import replace_file @@ -117,7 +116,7 @@ def branch_history(checkout: str, home: pathlib.Path, titles: Titles, git: Git) def entries(path: pathlib.Path) -> list[Entry]: - return [entry for line in io.BytesIO(read_stored(path)) if (entry := parse_entry(line))] + return entries_of(read_stored(path)) def subagent(transcript: pathlib.Path) -> Subagent: diff --git a/bin/task_bench/digest.py b/bin/task_bench/digest.py index b918f2df..24f7b26c 100644 --- a/bin/task_bench/digest.py +++ b/bin/task_bench/digest.py @@ -5,8 +5,8 @@ import collections import re import typing -from claude_code.entries import AssistantTurn, parse_entry, Text, tool_calls, ToolCall, ToolResult, ToolResults -from task_bench.figures import HOME, WORK +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 # A trace keeps the first TEXT_LINES lines of the model's text between two calls, and the first TEXT_WIDTH characters of each. @@ -22,12 +22,12 @@ AROUND_HITS = re.compile(r"Found \d+ .*|No \w+ found.*|No entries at this offset class Run(typing.NamedTuple): """One run of a bug: 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.""" + it didn't finish, and its stream's entries.""" id: str passed: bool tokens: int | None - stream: bytes + entries: typing.Sequence[Entry] class Bug(typing.NamedTuple): @@ -50,7 +50,7 @@ def digest(sides: dict[str, str], table: list[str], bugs: list[Bug], is_file: ty def told(bug: Bug, is_file: typing.Callable[[str], bool]) -> list[str]: passing, failing = [run for run in bug.runs if run.passed], [run for run in bug.runs if not run.passed] passed = f"{len(passing)} of the {len(bug.runs)} runs passed." if failing else f"The {counted(len(bug.runs), 'run')} passed." - misled = decoys([run.stream for run in failing], bug.file, is_file) + misled = decoys([run.entries for run in failing], bug.file, is_file) if not failing: found = "No run failed, so the bug has no decoys." elif not misled: @@ -77,27 +77,25 @@ def told(bug: Bug, is_file: typing.Callable[[str], bool]) -> list[str]: "", 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.stream)]), + *(line for run, why in shown for line in ["", f"### {run.id}, {why}", "", *trace(run.entries)]), ] -def decoys(failing: list[bytes], fixed: str, is_file: typing.Callable[[str], bool]) -> list[str]: - """The files of the project that more than half of the failing runs' streams read, but for fixed, the file the bug is in: +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 stream in failing for path in files_read(stream)) + 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(stream: bytes) -> set[str]: +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.""" - entries = [entry for line in stream.splitlines() if (entry := parse_entry(line))] 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(stream: bytes) -> list[str]: +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 `> `.""" - entries = [entry for line in stream.splitlines() if (entry := parse_entry(line))] 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))])] diff --git a/bin/task_bench/figures.py b/bin/task_bench/figures.py index d5bae7b9..1a65f1c5 100644 --- a/bin/task_bench/figures.py +++ b/bin/task_bench/figures.py @@ -3,18 +3,15 @@ import dataclasses import statistics import typing +from claude_code.entries import Entry, json_object, tool_calls, ToolCall from failure import Failure -from claude_code.entries import json_object, parse_entry, tool_calls, ToolCall +from task_bench.runs import HOME, WORK from reading_cost.measure import reads_of from claude_code.tokens import Tokens, tokens_of -# Where each run's container mounts its copy of the code, and its home folder: the paths in a run's stream start there. -WORK = "/work" -HOME = "/tmp" # The tools that read or search without a shell. A Bash call counts where `reads_of` finds a file it reads. READING_TOOLS = frozenset({"Glob", "Grep", "Read"}) SIDES = ("base", "head") -HEADER = ["| Bug | Side | Passed | Input | Cache write | Cache read | Output | Turns | Wall, s | Reads |", "|---|---|---|---|---|---|---|---|---|---|"] @dataclasses.dataclass(frozen=True) @@ -30,17 +27,42 @@ class Figures: class Result(typing.NamedTuple): - """One run of a task at a side. figures is None where its claude ended without a result, as when it ran out of time.""" + """One run of a task at a side. figures is None where its claude ended without a result, as when it ran out of time. entries + holds what its stream tells, for the digest.""" task: int side: str run: int passed: bool figures: Figures | None + entries: typing.Sequence[Entry] = () -def figures(stream: bytes, bug_file: str) -> Figures | None | Failure: - """The figures of the run whose claude printed stream, with bug_file the bug's file as the run's container names it. +class Column(typing.NamedTuple): + """A figure the table shows: its heading, its value in one run, None where the run has none, and whether the head's change + in it is a share of the base or a count.""" + + heading: str + value: typing.Callable[[Figures], float | None] + change: typing.Literal["share", "count"] + + +# Turns and reads are small counts, where a share misleads. +COLUMNS = ( + Column("Input", lambda found: found.tokens.input, "share"), + Column("Cache write", lambda found: found.tokens.write_5m + found.tokens.write_1h, "share"), + Column("Cache read", lambda found: found.tokens.read, "share"), + Column("Output", lambda found: found.tokens.output, "share"), + Column("Turns", lambda found: found.turns, "count"), + Column("Wall, s", lambda found: found.seconds, "share"), + Column("Reads", lambda found: found.reads, "count"), +) +HEADINGS = ["Bug", "Side", "Passed", *(column.heading for column in COLUMNS)] + + +def figures(stream: bytes, entries: typing.Sequence[Entry], bug_file: str) -> Figures | None | Failure: + """The figures of the run whose claude printed stream, which parses into entries, with bug_file the bug's file as the run's + container names it. None where the stream holds no result. A Failure where the API refused the run, as on a token it doesn't take: such a run doesn't measure anything, and every later run would end the same.""" @@ -48,11 +70,11 @@ def figures(stream: bytes, bug_file: str) -> Figures | None | Failure: result = next((event for event in reversed(events) if event.get("type") == "result"), None) if result is None: return None + # Claude Code retries a failed API call itself, on 429, 529 and 5xx, up to CLAUDE_CODE_MAX_RETRIES times, so its retries didn't clear this one. if result.get("api_error_status") or result.get("terminal_reason") == "api_error": return Failure(f"claude could not use the API: {result.get('result')}") # {"type": "system", "subtype": "init", "model": "claude-haiku-5-5", "claude_code_version": "2.1.330", ...} init = next((event for event in events if event.get("subtype") == "init"), {}) - entries = [entry for line in stream.splitlines() if (entry := parse_entry(line))] calls = [call for _, call in tool_calls(entries)] return Figures(str(init.get("claude_code_version", "")), str(init.get("model", "")), tokens_of(result.get("usage")), int(result.get("num_turns") or 0), (result.get("duration_ms") or 0) / 1000, reads_before(calls, bug_file)) @@ -73,27 +95,18 @@ def table(results: list[Result], tasks: dict[int, str]) -> list[str]: sides = {(task, side): [result for result in results if (result.task, result.side) == (task, side)] for task in tasks for side in SIDES} rows = [row(f"{task}: {tasks[task]}", side, sides[task, side]) for task in sorted(tasks) for side in SIDES] base, head = ([result for result in results if result.side == side] for side in SIDES) - return [*HEADER, *rows, row("All", "base", base), row("All", "head", head), change([(sides[task, "base"], sides[task, "head"]) for task in sorted(tasks)])] + return [cells(HEADINGS), cells(["---"] * len(HEADINGS)).replace(" ", ""), *rows, row("All", "base", base), row("All", "head", head), change([(sides[task, "base"], sides[task, "head"]) for task in sorted(tasks)])] -def medians(results: list[Result]) -> list[float | None]: - """Input, cache write, cache read, output, turns, wall time and reads.""" - measured = [result.figures for result in results if result.figures] - columns: list[list[float]] = [ - [found.tokens.input for found in measured], - [found.tokens.write_5m + found.tokens.write_1h for found in measured], - [found.tokens.read for found in measured], - [found.tokens.output for found in measured], - [found.turns for found in measured], - [found.seconds for found in measured], - [found.reads for found in measured if found.reads is not None], - ] - return [statistics.median(column) if column else None for column in columns] +def median(column: Column, results: list[Result]) -> float | None: + """The column's median over the runs that have a value in it.""" + values = [value for result in results if result.figures and (value := column.value(result.figures)) is not None] + return statistics.median(values) if values else None def row(task: str, side: str, results: list[Result]) -> str: passed = f"{sum(result.passed for result in results)}/{len(results)}" - return cells([task, side, passed, *("-" if median is None else number(median) for median in medians(results))]) + return cells([task, side, passed, *("-" if (found := median(column, results)) is None else number(found) for column in COLUMNS)]) def change(bugs: list[tuple[list[Result], list[Result]]]) -> str: @@ -102,9 +115,7 @@ def change(bugs: list[tuple[list[Result], list[Result]]]) -> str: as a share of the base median for tokens and wall time, and as a count for turns and reads. This isn't the change from the All base row to the All head row: those medians land in whichever bug's runs sit in the middle of the pooled costs.""" passed = sum(result.passed for _, head in bugs for result in head) - sum(result.passed for base, _ in bugs for result in base) - pairs = [list(zip(medians(base), medians(head))) for base, head in bugs] - # Turns and reads are small counts, where a share misleads. - means = [mean_change([pair[column] for pair in pairs], share=column not in (4, 6)) for column in range(7)] + means = [mean_change([(median(column, base), median(column, head)) for base, head in bugs], share=column.change == "share") for column in COLUMNS] return cells(["All", "change", number(passed, signed=True), *(found or "-" for found in means)]) diff --git a/bin/task_bench/main.py b/bin/task_bench/main.py index 21d4c454..52d353a7 100644 --- a/bin/task_bench/main.py +++ b/bin/task_bench/main.py @@ -37,15 +37,15 @@ It prints the base and the head, then a table: a row per bug and side with how m that finished, of the input, cache-write, cache-read and output tokens, the turns, the wall time, and the reads and searches before the run first opened the file the bug is in. The median of the reads leaves out a run that never opened that file. Then come a row per side over every bug, and the head's change against the base. That last row holds the pass count's difference and, for each other -column, the mean over the bugs of each bug's own change, so it isn't the difference of the two rows above it. The last line names the bench's folder: `task-bench` in the -chunk's review folder. +column, the mean over the bugs of each bug's own change, so it isn't the difference of the two rows above it. The last line names +the bench's folder: `task-bench` in the chunk's review folder. That folder holds each run's result and stream, and digest.md, which says why runs failed in a few kilobytes per bug: - the table; - per bug its decoys, the files more than half of its failing runs read that the bug isn't in; - per bug up to two traces: of a failing run, one that didn't finish or else the one that spent the most tokens, and of the - passing run with the median tokens. A trace has a line per tool call, such as `Read pick.go:120-180` or `Grep "readName" → 4 hits`, and the first 3 lines of what Haiku wrote - between calls. + passing run with the median tokens. A trace has a line per tool call, such as `Read pick.go:120-180` or `Grep "readName" → 4 + hits`, and the first 3 lines of what Haiku wrote between calls. Read a change against the noise. Measured on `fejkdata`, a Go project, with the defaults, a bench of a commit against itself shows, in 19 cases of 20, an All change under 12% in output tokens, 16% in cache-read tokens and 10% in wall time. On its bugs every run @@ -79,17 +79,18 @@ import tarfile import typing import uuid -from task_bench.digest import Bug, digest, Run -from task_bench.runs import checked_tree, closed, Containers, docker_cli, fix_attempted, MEMORY_MIB, opened, ran_tests, TimedOut, TOKEN +from task_bench.digest import Bug, counted, digest, Run +from task_bench.plant import bug_at_sides, drawn, killed_mutants, Mutant, place_files, task_text +from task_bench.runs import checked_tree, closed, Containers, docker_cli, fix_attempted, MEMORY_MIB, opened, ran_tests, TimedOut, TOKEN, WORK from claude_code.reply import Claude from task_bench.bench_folder import clear_left, held from machine_load.slots import CPUS_PER_SLOT from git_cli.git_repo import default_ref, Git, top from task_bench.gather import DIGEST, gather, run_claude -from task_bench.plant import drawn, killed_mutants, line_at_head, Mutant, mutated, place_files, task_text +from claude_code.entries import entries_of from mutate_changes.tool_process import failed, Ran, run_tool from failure import Failure -from task_bench.figures import figures, Result, SIDES, table, WORK +from task_bench.figures import figures, Result, SIDES, table from git_cli import git_repo from review_rules.review_folder import made_review_folder, REPORTS from larv_review.history_commands import read_places @@ -117,6 +118,32 @@ class Task: return f"{self.mutant.path}:{self.mutant.line}:{self.mutant.column} {self.mutant.mutator}" +class Asked(typing.NamedTuple): + """What the caller asked of a bench: the seed that orders the mutants, how many bugs to plant and how often to run each fix.""" + seed: int + bugs: int + runs: int + + +@dataclasses.dataclass(frozen=True) +class Bench: + """What a bench's phases share: the checkout, per side its commit and its tree without a bug, what the caller asked, the + containers, the bench's folder and git.""" + checkout: str + sides: dict[str, str] + trees: dict[str, str] + asked: Asked + containers: Containers + folder: pathlib.Path + git: Git + + +class Fixes(typing.NamedTuple): + """The runs that finished, in the order they ran, and the failure that stopped the bench before the rest, if one did.""" + results: list[Result] + stopped: Failure | None + + def main(argv: list[str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path], str | Failure] = read_places, claude: Claude = run_claude) -> int: """Runs task-bench with the arguments argv; git, docker and Gremlins run in the environment env, `read` reads what `larv-review places` prints for the checkout, and `claude` runs the claude that gathers.""" @@ -202,7 +229,7 @@ def bench_in(folder: pathlib.Path, given: dict[str, str], env: typing.Mapping[st if isinstance(mutants, Failure): return mutants try: - found = opened(containers, given["--image"]) or benched(given, checkout, sides, trees, mutants, containers, folder, git) + found = opened(containers, given["--image"]) or benched(Bench(checkout, sides, trees, Asked(int(given["--seed"]), int(given["--bugs"]), int(given["--runs"])), containers, folder, git), mutants) finally: closed(containers) except OSError as failure: @@ -239,45 +266,74 @@ def archived(commit: str, into: pathlib.Path, checkout: str, git: Git) -> str | return str(into) -def benched(given: dict[str, str], checkout: str, sides: dict[str, str], trees: dict[str, str], mutants: list[Mutant], containers: Containers, folder: pathlib.Path, git: Git) -> list[str] | Failure: - """Plants the bugs, runs each fix, writes the results into folder and returns the report.""" - for side, tree in trees.items(): - ran = tests_in_copy(containers, tree, folder) +def benched(bench: Bench, mutants: list[Mutant]) -> list[str] | Failure: + """Plants the bugs, runs each fix, writes the results into the bench's folder and returns the report.""" + if failure := baseline_failure(bench): + return failure + tasks = planted_tasks(bench, mutants) + if isinstance(tasks, Failure): + return tasks + total = bench.asked.runs * len(tasks) * len(SIDES) + fixes = ran_fixes(bench, tasks, total) + if fixes.stopped and not fixes.results: + return fixes.stopped + names = {task.number: task.named() for task in tasks} + kept(bench, tasks, fixes.results) + if fixes.stopped: + return stopped_report(fixes.stopped, fixes.results, total, names, bench.folder) + return report(bench.sides, names, bench.asked, fixes.results) + + +def baseline_failure(bench: Bench) -> Failure | None: + """Why a side's tests don't pass without a planted bug; None where both sides' pass.""" + for side, tree in bench.trees.items(): + ran = tests_in_copy(bench.containers, tree, bench.folder) if isinstance(ran, Failure) or ran.code: return ran if isinstance(ran, Failure) else failed(f"The tests fail at the {side} without a planted bug: the test command", ran) + return None + + +def planted_tasks(bench: Bench, mutants: list[Mutant]) -> list[Task] | Failure: + """The mutants that become bugs, in the order the seed draws them, until the bench has as many as asked for.""" tasks: list[Task] = [] - for mutant in drawn(mutants, int(given["--seed"])): - if len(tasks) == int(given["--bugs"]): + for mutant in drawn(mutants, bench.asked.seed): + if len(tasks) == bench.asked.bugs: break - task = planted(len(tasks) + 1, mutant, checkout, sides, trees, containers, folder, git) + task = planted(bench, len(tasks) + 1, mutant) if isinstance(task, Failure): return task tasks += [task] if task else [] if not tasks: return Failure(f"None of the {len(mutants)} mutants the tests kill becomes a bug: each is on a line the head changed, or the test it fails doesn't print a message.") + return tasks + + +def ran_fixes(bench: Bench, tasks: list[Task], total: int) -> Fixes: + """Each task's fix at each side, as many times as asked for, the sides in turn, until a run stops the bench.""" results: list[Result] = [] - stopped = None - total = int(given["--runs"]) * len(tasks) * len(SIDES) - for number, task, side in itertools.product(range(1, int(given["--runs"]) + 1), tasks, SIDES): - result = fixed(task, side, number, containers, folder) + for number, task, side in itertools.product(range(1, bench.asked.runs + 1), tasks, SIDES): + result = fixed(task, side, number, bench.containers, bench.folder) if isinstance(result, Failure): - stopped = result - break + return Fixes(results, result) results.append(result) print(f"task-bench: run {len(results)} of {total}, bug {task.number} at the {side}: {'passed' if result.passed else 'not passed'}.", file=sys.stderr) - if stopped and not results: - return stopped + return Fixes(results, None) + + +def kept(bench: Bench, tasks: list[Task], results: list[Result]) -> None: + """Writes results.json and the digest into the bench's folder.""" names = {task.number: task.named() for task in tasks} - (folder / "results.json").write_text(json.dumps({"sides": sides, "seed": int(given["--seed"]), "bugs": names, "runs": [recorded(result) for result in results]}, indent="\t") + "\n", encoding="utf-8") - in_a_tree = lambda path: any(pathlib.Path(tree, path).is_file() for tree in trees.values()) - (folder / DIGEST).write_text(digest(sides, table(results, names), [digested(task, results, folder) for task in tasks], in_a_tree), encoding="utf-8", errors="replace") - if stopped: - # The runs that finished took hours and tokens, so the bench shows them before it fails. - return Failure("\n".join([stopped.reason, f"task-bench stopped after {len(results)} of {total} runs, which results.json holds in {folder}:", "", *table(results, names)])) + (bench.folder / "results.json").write_text(json.dumps({"sides": bench.sides, "seed": bench.asked.seed, "bugs": names, "runs": [recorded(result) for result in results]}, indent="\t") + "\n", encoding="utf-8") + in_a_tree = lambda path: any(pathlib.Path(tree, path).is_file() for tree in bench.trees.values()) + (bench.folder / DIGEST).write_text(digest(bench.sides, table(results, names), [digested(task, results, bench.folder) for task in tasks], in_a_tree), encoding="utf-8", errors="replace") + + +def report(sides: dict[str, str], names: dict[int, str], asked: Asked, results: list[Result]) -> list[str]: + """What a finished bench prints: the commits, the bugs named in names, what ran them, and the table.""" ran_on = sorted({f"{found.model} in Claude Code {found.version}" for result in results if (found := result.figures)}) - short = [] if len(tasks) == int(given["--bugs"]) else [f"Planted {len(tasks)} of the {given['--bugs']} bugs asked for: no other mutant the tests kill becomes one."] + short = [] if len(names) == asked.bugs else [f"Planted {len(names)} of the {asked.bugs} bugs asked for: no other mutant the tests kill becomes one."] return [ - f"task-bench: base {sides['base'][:12]}, head {sides['head'][:12]}. {counted(len(tasks), 'bug')}, each run {counted(int(given['--runs']), 'time')} at each side by {' and '.join(ran_on) or 'no run that finished'}.", + f"task-bench: base {sides['base'][:12]}, head {sides['head'][:12]}. {counted(len(names), 'bug')}, each run {counted(asked.runs, 'time')} at each side by {' and '.join(ran_on) or 'no run that finished'}.", *short, "", *table(results, names), @@ -285,39 +341,51 @@ def benched(given: dict[str, str], checkout: str, sides: dict[str, str], trees: ] -def planted(number: int, mutant: Mutant, checkout: str, sides: dict[str, str], trees: dict[str, str], containers: Containers, folder: pathlib.Path, git: Git) -> Task | Failure | None: - """The task of fixing mutant, with its planted tree at each side; None where the mutant doesn't become a bug at one side or the other. +def stopped_report(stopped: Failure, results: list[Result], total: int, names: dict[int, str], folder: pathlib.Path) -> Failure: + """Why the bench stopped, then the table of the runs that finished: they took hours and tokens, so the bench shows them + before it fails.""" + return Failure("\n".join([stopped.reason, f"task-bench stopped after {len(results)} of {total} runs, which results.json holds in {folder}:", "", *table(results, names)])) - The bug is the same change to the same line at both sides, so only the code around it differs between them.""" - diff = git("diff", "-U0", "--no-color", "--no-ext-diff", "--no-textconv", sides["base"], sides["head"], "--", mutant.path, cwd=checkout, errors="replace") + +def planted(bench: Bench, number: int, mutant: Mutant) -> Task | Failure | None: + """The task of fixing mutant, with its planted tree at each side; None where the mutant doesn't become a bug at one side or the other.""" + diff = bench.git("diff", "-U0", "--no-color", "--no-ext-diff", "--no-textconv", bench.sides["base"], bench.sides["head"], "--", mutant.path, cwd=bench.checkout, errors="replace") if isinstance(diff, Failure): return diff - at_head = line_at_head(diff, mutant.line) - if at_head is None: + sources = {side: source.read_bytes() if (source := pathlib.Path(tree, mutant.path)).is_file() else None for side, tree in bench.trees.items()} + bugs = bug_at_sides(mutant, diff, sources) + if bugs is None: return None - planted_trees, messages = {}, {} - for side, placed in (("base", mutant), ("head", mutant._replace(line=at_head))): - source = pathlib.Path(trees[side], mutant.path) - changed = mutated(source.read_bytes(), placed) if source.is_file() else None - if changed is None: - return None - tree = folder / "bugs" / str(number) / side - shutil.rmtree(tree, ignore_errors=True) - shutil.copytree(trees[side], tree, symlinks=True) - (tree / mutant.path).write_bytes(changed) - ran = tests_in_copy(containers, str(tree), folder) - if isinstance(ran, Failure) and not isinstance(ran, TimedOut): - return ran - # Tests that never end under the bug have no message to tell Haiku. - message = None if isinstance(ran, TimedOut) else task_text(ran.output) - if message is None: - return None - for args in (["init", "--quiet"], ["add", "--all", "--force"], COMMIT): - done = git(*args, cwd=str(tree)) - if isinstance(done, Failure): - return done - planted_trees[side], messages[side] = str(tree), message - return Task(number, mutant, planted_trees, messages) + trees, messages = {}, {} + for side, changed in bugs.items(): + tree = bench.folder / "bugs" / str(number) / side + message = planted_tree(bench, side, tree, mutant.path, changed) + if message is None or isinstance(message, Failure): + return message + trees[side], messages[side] = str(tree), message + return Task(number, mutant, trees, messages) + + +def planted_tree(bench: Bench, side: str, tree: pathlib.Path, path: str, changed: bytes) -> str | Failure | None: + """Makes tree a copy of the side's with the file at path holding changed, committed once, and returns what the failing test + prints there; None where it prints no message to tell Haiku.""" + shutil.rmtree(tree, ignore_errors=True) + shutil.copytree(bench.trees[side], tree, symlinks=True) + (tree / path).write_bytes(changed) + ran = tests_in_copy(bench.containers, str(tree), bench.folder) + # Tests that never end under the bug have no message. + if isinstance(ran, TimedOut): + return None + if isinstance(ran, Failure): + return ran + message = task_text(ran.output) + if message is None: + return None + for args in (["init", "--quiet"], ["add", "--all", "--force"], COMMIT): + done = bench.git(*args, cwd=str(tree)) + if isinstance(done, Failure): + return done + return message def tests_in_copy(containers: Containers, tree: str, folder: pathlib.Path) -> Ran | Failure: @@ -341,14 +409,16 @@ def fixed(task: Task, side: str, number: int, containers: Containers, folder: pa attempted = fix_attempted(containers, str(copy), task.messages[side], stream) if isinstance(attempted, Failure): return attempted - found = figures(stream.read_bytes(), os.path.join(WORK, task.mutant.path)) + raw = stream.read_bytes() + entries = entries_of(raw) + found = figures(raw, entries, os.path.join(WORK, task.mutant.path)) if isinstance(found, Failure): return found checked_tree(task.trees[side], str(copy), str(check)) ran = ran_tests(containers, str(check)) if isinstance(ran, Failure) and not isinstance(ran, TimedOut): return ran - return Result(task.number, side, number, isinstance(ran, Ran) and ran.code == 0, found) + return Result(task.number, side, number, isinstance(ran, Ran) and ran.code == 0, found, tuple(entries)) finally: shutil.rmtree(copy, ignore_errors=True) shutil.rmtree(check, ignore_errors=True) @@ -361,7 +431,7 @@ def stream_of(result: Result, folder: pathlib.Path) -> pathlib.Path: def digested(task: Task, results: list[Result], folder: pathlib.Path) -> Bug: """The bug as the digest tells it, with each of its runs in results. A run that didn't finish has no tokens.""" - runs = [Run(stream_of(result, folder).stem, result.passed, found.tokens.context() + found.tokens.output if (found := result.figures) else None, stream_of(result, folder).read_bytes()) for result in results if result.task == task.number] + runs = [Run(stream_of(result, folder).stem, result.passed, found.tokens.context() + found.tokens.output if (found := result.figures) else None, result.entries) for result in results if result.task == task.number] return Bug(f"{task.number}: {task.named()}", task.mutant.path, task.messages["base"], runs) @@ -371,7 +441,3 @@ def recorded(result: Result) -> dict: if not (found := result.figures): return run return {**run, "claude_code": found.version, "model": found.model, "tokens": dataclasses.asdict(found.tokens), "turns": found.turns, "seconds": found.seconds, "reads": found.reads} - - -def counted(count: int, noun: str) -> str: - return f"{count} {noun}{'' if count == 1 else 's'}" diff --git a/bin/task_bench/plant.py b/bin/task_bench/plant.py index 962bb01a..65e46017 100644 --- a/bin/task_bench/plant.py +++ b/bin/task_bench/plant.py @@ -86,6 +86,23 @@ def mutated(source: bytes, mutant: Mutant) -> bytes | None: return b"\n".join(lines) +def bug_at_sides(mutant: Mutant, diff: str, sources: dict[str, bytes | None]) -> dict[str, bytes] | None: + """The file of mutant with the bug in it, at the base and at the head, from the file at each side, None where the side has + none, and the diff of it from base to head. None where the mutant doesn't become a bug at one side or the other. + + The bug is the same change to the same line at both sides, so only the code around it differs between them.""" + at_head = line_at_head(diff, mutant.line) + if at_head is None: + return None + bugs = {} + for side, placed in (("base", mutant), ("head", mutant._replace(line=at_head))): + changed = None if (source := sources[side]) is None else mutated(source, placed) + if changed is None: + return None + bugs[side] = changed + return bugs + + def line_at_head(diff: str, line: int) -> int | None: """The number at the head of a file's line `line` at the base, or None where the head changed or removed that line. diff --git a/bin/task_bench/runs.py b/bin/task_bench/runs.py index cb8e1298..2d8aab5b 100644 --- a/bin/task_bench/runs.py +++ b/bin/task_bench/runs.py @@ -10,11 +10,13 @@ import typing from mutate_changes.tool_process import failed, Ran from failure import Failure -from task_bench.figures import HOME, WORK from mutate_changes.changed_lines import is_test from task_bench.api_proxy import PORT MODEL = "claude-haiku-5-5" +# Where each run's container mounts its copy of the code, and its home folder: the paths in a run's stream start there. +WORK = "/work" +HOME = "/tmp" # No MCP server, skill, command or stored session, so a run starts from the code alone; -p needs --verbose with stream-json, and no # one answers a permission prompt. Not --bare, which can't sign in by a long-lived token: docs/decisions.md → `Claude Code in a home # of its own`. diff --git a/bin/task_bench/test_digest.py b/bin/task_bench/test_digest.py index 76d49ada..1765307f 100644 --- a/bin/task_bench/test_digest.py +++ b/bin/task_bench/test_digest.py @@ -7,6 +7,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from task_bench.digest import Bug, decoys, digest, Run, trace +from claude_code.entries import entries_of, Entry def said(text: str) -> dict: @@ -21,11 +22,11 @@ def result(at: str, text: str, failed: bool = False) -> dict: return {"type": "user", "message": {"role": "user", "content": [{"type": "tool_result", "tool_use_id": f"toolu_{at}", "content": text, "is_error": failed}]}} -def stream(*events: dict) -> bytes: - return "\n".join(map(json.dumps, events)).encode() +def stream(*events: dict) -> list[Entry]: + return entries_of("\n".join(map(json.dumps, events)).encode()) -def reading(*paths: str) -> bytes: +def reading(*paths: str) -> list[Entry]: return stream(*(call("Read", str(at), file_path=f"/work/{path}") for at, path in enumerate(paths))) @@ -145,11 +146,11 @@ class DigestTest(unittest.TestCase): self.assertIn("### bug-2-base-1, the passing run with the median tokens, 10 tokens", held.splitlines()) def test_the_median_is_by_tokens_whatever_the_order_the_runs_ran_in(self): - runs = [Run("bug-2-base-1", True, 20, b""), Run("bug-2-head-1", True, 10, b""), Run("bug-2-base-2", True, 30, b"")] + runs = [Run("bug-2-base-1", True, 20, []), Run("bug-2-head-1", True, 10, []), Run("bug-2-base-2", True, 30, [])] self.assertEqual(digest(SIDES, [], [Bug("2: a.go:1:1 X", "a.go", "boom", runs)], lambda path: True).splitlines()[-2:], ["### bug-2-base-1, the passing run with the median tokens, 20 tokens", ""]) def test_a_run_that_did_not_finish_is_the_failing_trace_and_is_left_out_of_the_median(self): - runs = [Run("bug-4-base-1", False, 900, b""), Run("bug-4-head-1", False, None, b""), Run("bug-4-base-2", True, None, b""), Run("bug-4-head-2", True, 60, b"")] + runs = [Run("bug-4-base-1", False, 900, []), Run("bug-4-head-1", False, None, []), Run("bug-4-base-2", True, None, []), Run("bug-4-head-2", True, 60, [])] held = digest(SIDES, [], [Bug("4: a.go:1:1 X", "a.go", "boom", runs)], lambda path: True).splitlines() self.assertEqual([line for line in held if line.startswith("###")], ["### bug-4-head-1, a failing run that didn't finish", "### bug-4-head-2, the passing run with the median tokens, 60 tokens"]) diff --git a/bin/task_bench/test_figures.py b/bin/task_bench/test_figures.py index 77d710e5..29f68dd8 100644 --- a/bin/task_bench/test_figures.py +++ b/bin/task_bench/test_figures.py @@ -6,8 +6,10 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from task_bench import figures as bench_figures +from claude_code.entries import entries_of from failure import Failure -from task_bench.figures import Figures, figures, Result, table +from task_bench.figures import Figures, Result, table from claude_code.tokens import Tokens INIT = {"type": "system", "subtype": "init", "cwd": "/work", "model": "claude-haiku-5-5", "claude_code_version": "2.1.330"} @@ -23,6 +25,10 @@ def stream(*events: dict) -> bytes: return "\n".join(map(json.dumps, events)).encode() + b"\n" +def figures(raw: bytes, bug_file: str) -> Figures | None | Failure: + return bench_figures.figures(raw, entries_of(raw), bug_file) + + class FiguresTest(unittest.TestCase): def test_reads_the_version_model_tokens_turns_and_wall_time_from_the_streams_first_and_last_events(self): found = figures(stream(INIT, RESULT), "/work/calc.go") diff --git a/bin/task_bench/test_plant.py b/bin/task_bench/test_plant.py index e8fe8ffd..e6316ca1 100644 --- a/bin/task_bench/test_plant.py +++ b/bin/task_bench/test_plant.py @@ -7,7 +7,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from task_bench.plant import drawn, go_files, killed_mutants, line_at_head, Mutant, mutated, place_files, task_text +from task_bench.plant import bug_at_sides, drawn, go_files, killed_mutants, line_at_head, Mutant, mutated, place_files, task_text from failure import Failure from mutate_changes.tool_process import Ran @@ -156,6 +156,25 @@ class LineAtHeadTest(unittest.TestCase): self.assertEqual(line_at_head("", 12), 12) +class BugAtSidesTest(unittest.TestCase): + MUTANT = Mutant("calc.go", 3, 11, "ARITHMETIC_BASE") + BASE = b"package calc\n\n\treturn a + b\n" + # The head adds a line above the bug's. + HEAD = b"package calc\n// Add adds.\n\n\treturn a + b\n" + DIFF = "@@ -1,0 +2 @@\n+// Add adds.\n" + + def test_the_bug_is_the_same_change_at_each_side_on_the_line_as_that_side_numbers_it(self): + found = bug_at_sides(self.MUTANT, self.DIFF, {"base": self.BASE, "head": self.HEAD}) + self.assertEqual(found, {"base": self.BASE.replace(b"+", b"-"), "head": self.HEAD.replace(b"+", b"-")}) + + def test_a_line_the_head_changed_holds_no_bug(self): + self.assertIsNone(bug_at_sides(self.MUTANT, "@@ -3 +3 @@\n-\treturn a + b\n+\treturn b + a\n", {"base": self.BASE, "head": self.BASE})) + + def test_a_side_without_the_file_or_without_the_token_holds_no_bug(self): + self.assertIsNone(bug_at_sides(self.MUTANT, "", {"base": self.BASE, "head": None})) + self.assertIsNone(bug_at_sides(self.MUTANT, "", {"base": self.BASE, "head": b"package calc\n\n\treturn sum(a, b)\n"})) + + class KilledMutantsTest(unittest.TestCase): def setUp(self): folder = tempfile.TemporaryDirectory() diff --git a/bin/task_bench/test_task_bench.py b/bin/task_bench/test_task_bench.py index dc0b2a5c..9df98188 100644 --- a/bin/task_bench/test_task_bench.py +++ b/bin/task_bench/test_task_bench.py @@ -17,10 +17,12 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from task_bench import api_proxy, bench_folder, main, runs from task_bench.runs import checked_tree, closed, Containers, docker_cli, fix_attempted, opened, ran_tests, TimedOut from task_bench.plant import drawn, Mutant +from claude_code.entries import Entry from failure import Failure +from task_bench.figures import Figures, Result, table from test_env import isolated_env from mutate_changes.tool_process import Ran -from task_bench.figures import Result +from claude_code.tokens import Tokens BASE_CODE = "package calc\n\nfunc Add(a, b int) int {\n\treturn a + b\n}\n\nfunc Twice(a int) int {\n\treturn a * 2\n}\n" # The head adds a line right above Add, which moves it down, and rewrites Twice's line. @@ -344,6 +346,24 @@ class BenchTest(unittest.TestCase): self.assertIn("docker build", found.reason) +class ReportTest(unittest.TestCase): + SIDES = {"base": "b" * 40, "head": "h" * 40} + NAMES = {1: "calc.go:4:11 ARITHMETIC_BASE"} + RESULTS = [Result(1, "base", 1, True, Figures("2.1.330", "claude-haiku-5-5", Tokens(40, 0, 9000, 52000, 800), 7, 61.5, 2)), Result(1, "head", 1, False, None)] + + def test_names_the_commits_the_bugs_the_runs_and_what_ran_them_above_the_table(self): + told = main.report(self.SIDES, self.NAMES, main.Asked(seed=1, bugs=1, runs=2), self.RESULTS) + self.assertEqual(told, ["task-bench: base bbbbbbbbbbbb, head hhhhhhhhhhhh. 1 bug, each run 2 times at each side by claude-haiku-5-5 in Claude Code 2.1.330.", "", *table(self.RESULTS, self.NAMES), ""]) + + def test_says_where_fewer_bugs_were_planted_than_asked_for_and_where_no_run_finished(self): + told = main.report(self.SIDES, self.NAMES, main.Asked(seed=1, bugs=3, runs=1), self.RESULTS[1:]) + self.assertEqual(told[:3], ["task-bench: base bbbbbbbbbbbb, head hhhhhhhhhhhh. 1 bug, each run 1 time at each side by no run that finished.", "Planted 1 of the 3 bugs asked for: no other mutant the tests kill becomes one.", ""]) + + def test_a_stopped_bench_tells_why_then_how_far_it_came_then_the_table(self): + told = main.stopped_report(Failure("claude could not use the API: Invalid bearer token"), self.RESULTS, 10, self.NAMES, pathlib.Path("/reviews/task-bench")) + self.assertEqual(told, Failure("\n".join(["claude could not use the API: Invalid bearer token", "task-bench stopped after 2 of 10 runs, which results.json holds in /reviews/task-bench:", "", *table(self.RESULTS, self.NAMES)]))) + + class MainTest(unittest.TestCase): def run_main(self, *argv: str, token: str = "t") -> tuple[int, str]: with contextlib.redirect_stderr(io.StringIO()) as errors, contextlib.redirect_stdout(io.StringIO()): @@ -377,12 +397,10 @@ class MainTest(unittest.TestCase): def test_a_run_that_did_not_finish_has_no_tokens_in_the_digest(self): - with tempfile.TemporaryDirectory() as folder: - pathlib.Path(folder, "runs").mkdir() - pathlib.Path(folder, "runs/bug-1-base-2.jsonl").write_bytes(b"{}") - task = main.Task(1, Mutant("calc.go", 4, 11, "ARITHMETIC_BASE"), {}, {"base": "boom", "head": "bang"}) - bug = main.digested(task, [Result(1, "base", 2, False, None), Result(2, "base", 1, True, None)], pathlib.Path(folder)) - self.assertEqual(bug, ("1: calc.go:4:11 ARITHMETIC_BASE", "calc.go", "boom", [("bug-1-base-2", False, None, b"{}")])) + task = main.Task(1, Mutant("calc.go", 4, 11, "ARITHMETIC_BASE"), {}, {"base": "boom", "head": "bang"}) + entries = (Entry(),) + bug = main.digested(task, [Result(1, "base", 2, False, None, entries), Result(2, "base", 1, True, None)], pathlib.Path("/bench")) + self.assertEqual(bug, ("1: calc.go:4:11 ARITHMETIC_BASE", "calc.go", "boom", [("bug-1-base-2", False, None, entries)])) def test_records_a_run_that_did_not_finish_without_figures(self): self.assertEqual(main.recorded(Result(1, "base", 2, False, None)), {"bug": 1, "side": "base", "run": 2, "passed": False, "finished": False}) @@ -431,6 +449,9 @@ class RunOutcomesTest(unittest.TestCase): def containers(self, *runs: Ran | Failure) -> Containers: return Containers(InTurn(*runs), "bench", "go test ./...", 512, "1000:1000") + def bench(self, *runs: Ran | Failure) -> main.Bench: + return main.Bench("", {"base": "b", "head": "h"}, self.trees, main.Asked(seed=1, bugs=1, runs=1), self.containers(*runs), self.folder, lambda *args, **given: "") + def test_a_fix_whose_tests_run_out_of_time_does_not_pass(self): late = TimedOut("docker run still ran after 30 min") self.assertEqual(main.fixed(self.task, "base", 1, self.containers(Ran(0, ""), late), self.folder), Result(1, "base", 1, False, None)) @@ -441,15 +462,15 @@ class RunOutcomesTest(unittest.TestCase): def test_tests_docker_could_not_run_without_a_bug_fail_the_bench(self): broke = Failure("docker could not start: No such file or directory") - self.assertEqual(main.benched({}, "", {}, self.trees, [], self.containers(broke), self.folder, None), broke) + self.assertEqual(main.benched(self.bench(broke), []), broke) def test_a_mutant_whose_tests_run_out_of_time_is_passed_over(self): late = TimedOut("docker run still ran after 30 min") - self.assertIsNone(main.planted(1, self.MUTANT, "", {"base": "b", "head": "h"}, self.trees, self.containers(late), self.folder, lambda *args, **given: "")) + self.assertIsNone(main.planted(self.bench(late), 1, self.MUTANT)) def test_a_mutant_whose_tests_docker_could_not_run_fails_the_bench(self): broke = Failure("docker could not start: No such file or directory") - self.assertEqual(main.planted(1, self.MUTANT, "", {"base": "b", "head": "h"}, self.trees, self.containers(broke), self.folder, lambda *args, **given: ""), broke) + self.assertEqual(main.planted(self.bench(broke), 1, self.MUTANT), broke) class ContainersTest(unittest.TestCase): diff --git a/todo.md b/todo.md index bd0d0898..9934733e 100644 --- a/todo.md +++ b/todo.md @@ -6,12 +6,13 @@ `Bar = 0.1` -`Next ID = 517` +`Next ID = 518` ## Items | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| +| 517 | 0.15.1 | | question | **Choose whether the release holding task-bench's new All change row is 0.16.0 or 0.15.1.** | 1 | 2 | 1 | 2 | 1 | 1.2 by 3 | 1.3 | | 509 | 0.16.0 | | owner | **Run `task-bench` beside the scoring run in larv-review comprehension check, and record its figures in the comprehension history beside the panel scores.** | 3 | 2 | 3 | 6 | 5 | code health by 5, 1.1 by 3 | 5.6 | | 504 | 0.16.0 | | owner | **Bench new features in `task-bench`, each a spec for Haiku with acceptance tests it never sees and a reference patch that proves it can be built, kept in a `bench-tasks` folder the project config names, starting with six for fejkdata.** | 3 | 2 | 1 | 4 | 6 | 1.1 by 4, code health by 3 | 2.6 | | 505 | 0.16.0 | 504 | owner | **Bench adding source data in `task-bench`: hand Haiku a fake register that a seeded script generates for a made-up country, and check the importer, the data and the licence entry it adds, starting with five tasks for fejkdata.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 3, code health by 2 | 2.6 | @@ -103,6 +104,17 @@ ## Details +### 517. Choose whether the release holding task-bench's new All change row is 0.16.0 or 0.15.1. + +This release changes what `task-bench`'s All change row means: it is now the mean of the bugs' own head/base changes, where 0.15.0 printed the change of the two All rows' medians. Semver read strictly lets only a minor change what exists before 1.0.0, so a patch can't ship it. The release review's architecture pass found this (`technical-principles.md`, "Semantic versioning, read strictly"). + +Two ways out: +- Ship this release as 0.16.0. Recommended: the old figure swung up to three times as far in tokens, so restoring it brings back a figure the release found misleading. +- Keep 0.15.1: restore the old row under its old label, add the new figure as a row of its own, and leave the new row's meaning for 0.16.0. + +Touches: +- `CHANGELOG.md`: `## Unreleased` (small) + ### 509. Run `task-bench` beside the scoring run in larv-review comprehension check, and record its figures in the comprehension history beside the panel scores. It stays a report beside the panel until about 10 chunks show whether the two agree; whether it can replace the scoring run or gate a merge is the human's call then. -- 2.52.0 From 9fe060575b89852325d2d5798cb655900bfb4cd7 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 23 Nov 2026 01:22:23 +0100 Subject: [PATCH 04/11] =?UTF-8?q?Answer=20architecture=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20every=20ans?= =?UTF-8?q?wer=20holds?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From cfe537b3fdbaf2041ff37e608c5465a70b5c841f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 23 Nov 2026 01:37:39 +0100 Subject: [PATCH 05/11] =?UTF-8?q?Answer=20principles=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=205=20=F0=9F=9F=A1=20(0=20misread);=20make=20a=20?= =?UTF-8?q?move=20a=20union=20with=20ToStatus,=20take=20only=20parsed=20ev?= =?UTF-8?q?ents=20in=20figures,=20catch=20OSError=20at=20each=20file=20ope?= =?UTF-8?q?ration,=20pass=20progress=20through=20the=20bench,=20type=20the?= =?UTF-8?q?=20sides,=20and=20split=20the=20README=20bullet?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 3 +- bin/claude_code/entries.py | 7 +- bin/do_epic/main.py | 73 ++++++++------- bin/do_epic/parking.py | 7 +- bin/do_epic/test_main.py | 25 ++--- bin/task_bench/digest.py | 3 +- bin/task_bench/figures.py | 15 +-- bin/task_bench/main.py | 150 ++++++++++++++++++------------ bin/task_bench/plant.py | 8 +- bin/task_bench/test_figures.py | 4 +- bin/task_bench/test_task_bench.py | 14 ++- 11 files changed, 186 insertions(+), 123 deletions(-) diff --git a/README.md b/README.md index 70c5c165..145b579f 100644 --- a/README.md +++ b/README.md @@ -261,7 +261,8 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `git_cli/` runs git for every tool (`git_repo.py`), reads the git calls in a shell command (`git_command.py`), and keeps an epic's working branch level with the default branch (`epic_branch.py`). - `judge_replay` imports `agent_cycle`'s judge and verdicts, and `chunk_driver`'s premises, records and `ANSWER_DESTINATIONS`. - `loop_claude` runs `chunk-preflight` as a process of its own. -- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, do-epic, both replay tools and `reviewer-merge-trials`' driver use it.- `loop_state/` holds where loop-claude and do-epic keep their files (`paths.py`), which `rung_replay` reads too. +- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, do-epic, both replay tools and `reviewer-merge-trials`' driver use it. +- `loop_state/` holds where loop-claude and do-epic keep their files (`paths.py`), which `rung_replay` reads too. - `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy` and `adf_codec`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count. - `model_routing/` holds the shipped routing ladder (`routing-ladder.json`) and its steps (`ladder.py`), and reads a ladder from that file or a project's own (`ladder_file.py`), for loop-claude, `rule_hook`, `do_epic`, both replay tools and `subagent-rung`. It finds a project's config folder through `project_config`. It also holds the list prices, which `routing_figures` and `transcript_archive` read. - `notifier/` sends the human a DM through the notifier a project's config names, for `notify` and for loop-claude through `loop_effects`. Its backends are `mattermost.py` and `slack.py`. diff --git a/bin/claude_code/entries.py b/bin/claude_code/entries.py index 337b2f88..43d21637 100644 --- a/bin/claude_code/entries.py +++ b/bin/claude_code/entries.py @@ -84,9 +84,14 @@ def parse_entry(raw: str | bytes) -> Entry | None: return None if found is None else entry_from(found) +def json_objects(raw: bytes) -> list[dict]: + """The lines of a transcript or a stream-json stream that are JSON objects, parsed.""" + return [found for line in raw.splitlines() if (found := json_object(line))] + + def entries_of(raw: bytes) -> list[Entry]: """The entries of a transcript or a stream-json stream, one per line that is a JSON object.""" - return [entry for line in raw.splitlines() if (entry := parse_entry(line))] + return [entry_from(found) for found in json_objects(raw)] def entry_from(found: dict) -> Entry: diff --git a/bin/do_epic/main.py b/bin/do_epic/main.py index bb479885..52fd6900 100644 --- a/bin/do_epic/main.py +++ b/bin/do_epic/main.py @@ -353,24 +353,26 @@ class Landed(enum.Enum): class How(enum.Enum): - """How a finished chunk's issue moves.""" + """How a finished chunk's issue moves, where it moves to no status the config names.""" # do-epic neither moves nor awaits it. LEFT = enum.auto() - # do-epic moves it to the status the Move names. - TO_STATUS = enum.auto() # Nobody would move it, so the loop stops. STUCK = enum.auto() # The team's automation moves it, and do-epic waits for that. AWAITED = enum.auto() + # do-epic moves it to done. TO_DONE = enum.auto() @dataclasses.dataclass(frozen=True) -class Move: - """The move of a finished chunk's issue. For How.TO_STATUS, status is where it moves, and through a status a failed move is tried again by way of, None where there is none.""" - how: How - status: str | None = None - through: str | None = None +class ToStatus: + """do-epic moves a finished chunk's issue to status, trying a failed move again by way of through, None where there is none.""" + status: str + through: str | None + + +# The move of a finished chunk's issue. +Move = How | ToStatus def issue_move(landed: Landed, automated: bool, merged: str | None, opened: str | None, finishing: bool) -> Move: @@ -380,49 +382,50 @@ def issue_move(landed: Landed, automated: bool, merged: str | None, opened: str |---|---|---|---| | the epic's finishing, which has no issue | either | either | LEFT | | a human's task | yes | either | LEFT: the human moves it | - | landed on the epic's working branch | either | yes | TO_STATUS merged, through opened | + | landed on the epic's working branch | either | yes | ToStatus merged, through opened | | landed on the epic's working branch | yes | no | STUCK: the automation doesn't see that merge | | landed on the default branch | yes | either | AWAITED | | any other | either | either | TO_DONE | A chunk that never parked left its issue before the open status, from which a workflow may offer no way to the merged one: hence through.""" if finishing or (landed is Landed.WITH_A_HUMAN and automated): - return Move(How.LEFT) + return How.LEFT if landed is Landed.ON_EPIC_BRANCH and merged: - return Move(How.TO_STATUS, merged, opened or None) + return ToStatus(merged, opened or None) if landed is Landed.ON_EPIC_BRANCH and automated: - return Move(How.STUCK) + return How.STUCK if landed is Landed.ON_DEFAULT_BRANCH and automated: - return Move(How.AWAITED) - return Move(How.TO_DONE) + return How.AWAITED + return How.TO_DONE def handed_on(key: str, epic: EpicRun, landed: Landed = Landed.NOWHERE) -> Stop: """The stop of a do-epic whose chunk finished. It first moves the chunk's issue to done (the epic's finishing has none), and its parent too where the parent's sub-tasks now let it move (`parents_settled`), so that no finished chunk starts again and what they block may start, then starts each chunk that may start now. Where the team's automation moves issues, others move two kinds of issue. The automation moves the issue of a chunk whose work landed on the default branch, from its pull request: the stop waits for that move (`moved_by_automation`). The human moves their own task: the stop doesn't move or await anything. A chunk without a repo has no pull request, so its issue moves to done as ever, and so does a split item, once Jira counts each of its sub-tasks done. The automation doesn't see a pull request that merged into an epic's working branch: the stop moves that chunk's issue to the status `jira-pull-request-merged-status` names. Where none is named, it moves the issue to done, or stops where the automation moves issues, since then nobody would move it. do-epic's window closes as it exits.""" move = issue_move(landed, epic.config.automation_moves, epic.config.pull_merged_status, epic.config.pull_open_status, finishing=key == epic.key) issues: list[EpicIssue] | Failure - if move.how is How.LEFT: - issues = epic.store.read() - elif move.how is How.TO_STATUS and (status := move.status): - moved = epic.store.move_issue(key, status) - if isinstance(moved, Failure) and move.through and not isinstance(epic.store.move_issue(key, move.through), Failure): + match move: + case How.LEFT: + issues = epic.store.read() + case ToStatus(status, through): moved = epic.store.move_issue(key, status) - if isinstance(moved, Failure): - return Stop(1, f"the chunk finished, but its issue could not move to {status!r}: {moved.reason}; once it has that status in Jira, run `do-epic {epic.key}` to start the chunks it blocks") - issues = epic.store.read() - # A search may not show the move yet, so the issue counts as moved here whatever the read says. - issues = issues if isinstance(issues, Failure) else [dataclasses.replace(each, status=status) if each.key == key else each for each in issues] - elif move.how is How.STUCK: - return Stop(1, f"the chunk finished, but its issue stays as it is: its pull request merged into the epic's working branch, where the team's automation moves no issue, and do-epic's config names no `{PULL_MERGED_STATUS}` to move it to. Move {key} in Jira, then run `do-epic {epic.key}` to start the chunks it blocks") - elif move.how is How.AWAITED: - issues = moved_by_automation(key, epic) - else: - moved = epic.store.finish_issue(key) - if isinstance(moved, Failure): - return Stop(1, f"the chunk finished, but its issue could not move to done: {moved.reason}; once it is done in Jira, run `do-epic {epic.key}` to start the chunks it blocks") - issues = epic.store.read() - # A search may not show the move yet, so the issue counts as done here whatever the read says. - issues = issues if isinstance(issues, Failure) else [dataclasses.replace(each, done=True) if each.key == key else each for each in issues] + if isinstance(moved, Failure) and through and not isinstance(epic.store.move_issue(key, through), Failure): + moved = epic.store.move_issue(key, status) + if isinstance(moved, Failure): + return Stop(1, f"the chunk finished, but its issue could not move to {status!r}: {moved.reason}; once it has that status in Jira, run `do-epic {epic.key}` to start the chunks it blocks") + issues = epic.store.read() + # A search may not show the move yet, so the issue counts as moved here whatever the read says. + issues = issues if isinstance(issues, Failure) else [dataclasses.replace(each, status=status) if each.key == key else each for each in issues] + case How.STUCK: + return Stop(1, f"the chunk finished, but its issue stays as it is: its pull request merged into the epic's working branch, where the team's automation moves no issue, and do-epic's config names no `{PULL_MERGED_STATUS}` to move it to. Move {key} in Jira, then run `do-epic {epic.key}` to start the chunks it blocks") + case How.AWAITED: + issues = moved_by_automation(key, epic) + case How.TO_DONE: + moved = epic.store.finish_issue(key) + if isinstance(moved, Failure): + return Stop(1, f"the chunk finished, but its issue could not move to done: {moved.reason}; once it is done in Jira, run `do-epic {epic.key}` to start the chunks it blocks") + issues = epic.store.read() + # A search may not show the move yet, so the issue counts as done here whatever the read says. + issues = issues if isinstance(issues, Failure) else [dataclasses.replace(each, done=True) if each.key == key else each for each in issues] if isinstance(issues, Failure): return Stop(1, f"the chunk finished, but the next could not start: {issues.reason}") closed = parents_settled(epic, issues) diff --git a/bin/do_epic/parking.py b/bin/do_epic/parking.py index 55df9e6f..ec7eef0b 100644 --- a/bin/do_epic/parking.py +++ b/bin/do_epic/parking.py @@ -11,6 +11,9 @@ from loop_effects.effects import say from agent_cycle.stop import Stop from agent_cycle import tmux +# How the news for a chunk that was parked opens. +DRIVER_PARKED = f"{chunk_prompt.DRIVER} parked the chunk while" + def parked_through(repo: str, loop: Loop, epic: EpicRun, told: str | None, finished: bool, based: str | None) -> str | Stop: """Keeps the chunk in loop's window parked. Its work is in the repo called repo. It stays parked for as long as its pull request waits on a gate, and returns once its worker has something to do: what to tell that worker, or empty where the chunk was never parked. told is the news its last cycle's worker got, None where the window just started, and finished says the judge ruled the chunk finished. based is the epic's working branch that `epic_based` recorded as the chunk's base when the window started, None where it recorded none. A window that just started parks the chunk only if its file says so: the forge isn't read for a chunk that starts afresh. @@ -124,10 +127,6 @@ def resumed_news(poll: Poll, on: str, shown: str | None) -> str | Stop: poll.epic.effects.sleep(POLL_SECONDS) -# How the news for a chunk that was parked opens. -DRIVER_PARKED = f"{chunk_prompt.DRIVER} parked the chunk while" - - def resumed(repo: str, loop: Loop, epic: EpicRun) -> str | None: """scheduler.resume for the parked chunk in loop's window, whose work is in the repo called repo, on the epic's cap and repos read afresh: None once it holds a running slot, else why it stays parked.""" # A chunk that resumes starts no other, so it needs no start order. diff --git a/bin/do_epic/test_main.py b/bin/do_epic/test_main.py index df62b4b8..b814070a 100644 --- a/bin/do_epic/test_main.py +++ b/bin/do_epic/test_main.py @@ -1243,29 +1243,32 @@ class TheMoveOfAFinishedChunksIssue(unittest.TestCase): def test_the_epics_finishing_has_no_issue_to_move(self) -> None: for automated in (False, True): - self.assertEqual(self.move(main.Landed.NOWHERE, automated, "Release Ready", "In Review", finishing=True), main.Move(main.How.LEFT)) + with self.subTest(automated=automated): + self.assertEqual(self.move(main.Landed.NOWHERE, automated, "Release Ready", "In Review", finishing=True), main.How.LEFT) def test_a_humans_task_is_left_where_the_automation_moves_issues_and_done_otherwise(self) -> None: - self.assertEqual(self.move(main.Landed.WITH_A_HUMAN, True, "Release Ready"), main.Move(main.How.LEFT)) - self.assertEqual(self.move(main.Landed.WITH_A_HUMAN, False, "Release Ready"), main.Move(main.How.TO_DONE)) + self.assertEqual(self.move(main.Landed.WITH_A_HUMAN, True, "Release Ready"), main.How.LEFT) + self.assertEqual(self.move(main.Landed.WITH_A_HUMAN, False, "Release Ready"), main.How.TO_DONE) def test_a_chunk_without_a_repo_moves_to_done(self) -> None: for automated in (False, True): - self.assertEqual(self.move(main.Landed.NOWHERE, automated, "Release Ready", "In Review"), main.Move(main.How.TO_DONE)) + with self.subTest(automated=automated): + self.assertEqual(self.move(main.Landed.NOWHERE, automated, "Release Ready", "In Review"), main.How.TO_DONE) def test_work_on_the_default_branch_awaits_the_automation_or_moves_to_done(self) -> None: - self.assertEqual(self.move(main.Landed.ON_DEFAULT_BRANCH, True, "Release Ready", "In Review"), main.Move(main.How.AWAITED)) - self.assertEqual(self.move(main.Landed.ON_DEFAULT_BRANCH, False, "Release Ready", "In Review"), main.Move(main.How.TO_DONE)) + self.assertEqual(self.move(main.Landed.ON_DEFAULT_BRANCH, True, "Release Ready", "In Review"), main.How.AWAITED) + self.assertEqual(self.move(main.Landed.ON_DEFAULT_BRANCH, False, "Release Ready", "In Review"), main.How.TO_DONE) def test_work_on_the_epics_branch_moves_to_the_merged_status_through_the_open_one_where_named(self) -> None: for automated in (False, True): - self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, automated, "Release Ready", "In Review"), main.Move(main.How.TO_STATUS, "Release Ready", "In Review")) - self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, automated, "Release Ready"), main.Move(main.How.TO_STATUS, "Release Ready")) + with self.subTest(automated=automated): + self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, automated, "Release Ready", "In Review"), main.ToStatus("Release Ready", "In Review")) + self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, automated, "Release Ready"), main.ToStatus("Release Ready", None)) def test_work_on_the_epics_branch_with_no_merged_status_is_stuck_under_automation_and_done_otherwise(self) -> None: - self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, True, None, "In Review"), main.Move(main.How.STUCK)) - self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, True, "", "In Review"), main.Move(main.How.STUCK)) - self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, False, None, "In Review"), main.Move(main.How.TO_DONE)) + self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, True, None, "In Review"), main.How.STUCK) + self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, True, "", "In Review"), main.How.STUCK) + self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, False, None, "In Review"), main.How.TO_DONE) class TheStatus(DoEpicTest): diff --git a/bin/task_bench/digest.py b/bin/task_bench/digest.py index 24f7b26c..197dc04b 100644 --- a/bin/task_bench/digest.py +++ b/bin/task_bench/digest.py @@ -8,6 +8,7 @@ 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 @@ -40,7 +41,7 @@ class Bug(typing.NamedTuple): runs: list[Run] -def digest(sides: dict[str, str], table: list[str], bugs: list[Bug], is_file: typing.Callable[[str], bool]) -> str: +def digest(sides: dict[Side, str], table: list[str], bugs: list[Bug], is_file: typing.Callable[[str], bool]) -> str: """The digest of a bench of the commits sides names: where each side's code is, the table of its figures, then each bug. is_file says whether a path in the project names a file.""" code = f"Base {sides['base']}, head {sides['head']}. A bug's name gives its line at the base. Each side's code without the bugs is in `trees/base` and `trees/head` in the bench's folder." diff --git a/bin/task_bench/figures.py b/bin/task_bench/figures.py index 1a65f1c5..2988c56d 100644 --- a/bin/task_bench/figures.py +++ b/bin/task_bench/figures.py @@ -3,7 +3,7 @@ import dataclasses import statistics import typing -from claude_code.entries import Entry, json_object, tool_calls, ToolCall +from claude_code.entries import Entry, entry_from, tool_calls, ToolCall from failure import Failure from task_bench.runs import HOME, WORK from reading_cost.measure import reads_of @@ -11,7 +11,9 @@ from claude_code.tokens import Tokens, tokens_of # The tools that read or search without a shell. A Bash call counts where `reads_of` finds a file it reads. READING_TOOLS = frozenset({"Glob", "Grep", "Read"}) -SIDES = ("base", "head") +# A bench's two sides: the commit before the change and the one after it. +Side = typing.Literal["base", "head"] +SIDES: tuple[Side, Side] = ("base", "head") @dataclasses.dataclass(frozen=True) @@ -31,7 +33,7 @@ class Result(typing.NamedTuple): holds what its stream tells, for the digest.""" task: int - side: str + side: Side run: int passed: bool figures: Figures | None @@ -60,13 +62,12 @@ COLUMNS = ( HEADINGS = ["Bug", "Side", "Passed", *(column.heading for column in COLUMNS)] -def figures(stream: bytes, entries: typing.Sequence[Entry], bug_file: str) -> Figures | None | Failure: - """The figures of the run whose claude printed stream, which parses into entries, with bug_file the bug's file as the run's +def figures(events: list[dict], bug_file: str) -> Figures | None | Failure: + """The figures of the run whose claude printed events, its stream's JSON lines, with bug_file the bug's file as the run's container names it. None where the stream holds no result. A Failure where the API refused the run, as on a token it doesn't take: such a run doesn't measure anything, and every later run would end the same.""" - events = [event for line in stream.splitlines() if (event := json_object(line))] result = next((event for event in reversed(events) if event.get("type") == "result"), None) if result is None: return None @@ -75,7 +76,7 @@ def figures(stream: bytes, entries: typing.Sequence[Entry], bug_file: str) -> Fi return Failure(f"claude could not use the API: {result.get('result')}") # {"type": "system", "subtype": "init", "model": "claude-haiku-5-5", "claude_code_version": "2.1.330", ...} init = next((event for event in events if event.get("subtype") == "init"), {}) - calls = [call for _, call in tool_calls(entries)] + calls = [call for _, call in tool_calls([entry_from(event) for event in events])] return Figures(str(init.get("claude_code_version", "")), str(init.get("model", "")), tokens_of(result.get("usage")), int(result.get("num_turns") or 0), (result.get("duration_ms") or 0) / 1000, reads_before(calls, bug_file)) diff --git a/bin/task_bench/main.py b/bin/task_bench/main.py index 52d353a7..14a01955 100644 --- a/bin/task_bench/main.py +++ b/bin/task_bench/main.py @@ -87,10 +87,10 @@ from task_bench.bench_folder import clear_left, held from machine_load.slots import CPUS_PER_SLOT from git_cli.git_repo import default_ref, Git, top from task_bench.gather import DIGEST, gather, run_claude -from claude_code.entries import entries_of +from claude_code.entries import entry_from, json_objects from mutate_changes.tool_process import failed, Ran, run_tool from failure import Failure -from task_bench.figures import figures, Result, SIDES, table +from task_bench.figures import figures, Result, Side, SIDES, table from git_cli import git_repo from review_rules.review_folder import made_review_folder, REPORTS from larv_review.history_commands import read_places @@ -111,8 +111,8 @@ class Task: """A bug to fix: its number from 1, the mutant at the base, and per side the planted tree and what Haiku is told there.""" number: int mutant: Mutant - trees: dict[str, str] - messages: dict[str, str] + trees: dict[Side, str] + messages: dict[Side, str] def named(self) -> str: return f"{self.mutant.path}:{self.mutant.line}:{self.mutant.column} {self.mutant.mutator}" @@ -128,14 +128,15 @@ class Asked(typing.NamedTuple): @dataclasses.dataclass(frozen=True) class Bench: """What a bench's phases share: the checkout, per side its commit and its tree without a bug, what the caller asked, the - containers, the bench's folder and git.""" + containers, the bench's folder, git, and say, which tells the caller each run's outcome as it finishes.""" checkout: str - sides: dict[str, str] - trees: dict[str, str] + sides: dict[Side, str] + trees: dict[Side, str] asked: Asked containers: Containers folder: pathlib.Path git: Git + say: typing.Callable[[str], None] class Fixes(typing.NamedTuple): @@ -190,8 +191,22 @@ def options(argv: list[str], env: typing.Mapping[str, str]) -> dict[str, str] | return given -def bench(given: dict[str, str], env: typing.Mapping[str, str], places: str, home: pathlib.Path) -> list[str] | Failure: - """The report of one bench of the checkout the process runs in, with `places` what `larv-review places` prints there.""" +def progress(line: str) -> None: + """Prints a line of a bench's progress to stderr, apart from its report on stdout.""" + print(line, file=sys.stderr) + + +def on_disk[T](doing: str, act: typing.Callable[[], T]) -> T | Failure: + """act's answer, or a Failure that says what could not be done where the filesystem refuses act.""" + try: + return act() + except OSError as failure: + return Failure(f"could not {doing}: {failure}") + + +def bench(given: dict[str, str], env: typing.Mapping[str, str], places: str, home: pathlib.Path, say: typing.Callable[[str], None] = progress) -> list[str] | Failure: + """The report of one bench of the checkout the process runs in, with `places` what `larv-review places` prints there; say + tells the caller the bench's progress.""" git = functools.partial(git_repo.git, env=env) checkout = top(git) if isinstance(checkout, Failure): @@ -199,7 +214,7 @@ def bench(given: dict[str, str], env: typing.Mapping[str, str], places: str, hom sides = commits(given, checkout, git) if isinstance(sides, Failure): return sides - print(f"task-bench: base {sides['base'][:12]}, head {sides['head'][:12]}.", file=sys.stderr) + say(f"task-bench: base {sides['base'][:12]}, head {sides['head'][:12]}.") review = made_review_folder(checkout, home) if isinstance(review, Failure): return review @@ -207,37 +222,34 @@ def bench(given: dict[str, str], env: typing.Mapping[str, str], places: str, hom if isinstance(folder, Failure): return folder clear_left(home / REPORTS) - return bench_in(folder, given, env, places, checkout, sides, git) + return bench_in(folder, given, env, places, checkout, sides, git, say) -def bench_in(folder: pathlib.Path, given: dict[str, str], env: typing.Mapping[str, str], places: str, checkout: str, sides: dict[str, str], git: Git) -> list[str] | Failure: +def bench_in(folder: pathlib.Path, given: dict[str, str], env: typing.Mapping[str, str], places: str, checkout: str, sides: dict[Side, str], git: Git, say: typing.Callable[[str], None]) -> list[str] | Failure: """The report of a bench of the commits sides names, which empties folder and keeps its runs there.""" containers = Containers(docker_cli(env), f"task-bench-{uuid.uuid4().hex[:12]}", given["--test"], int(env.get(SHARE_VARIABLE) or MEMORY_MIB), f"{os.getuid()}:{os.getgid()}") + shutil.rmtree(folder, ignore_errors=True) + trees: dict[Side, str] = {} + for side, commit in sides.items(): + tree = archived(commit, folder / "trees" / side, checkout, git) + if isinstance(tree, Failure): + return tree + trees[side] = tree + files = [path for path in place_files(places) if pathlib.Path(trees["base"], path).is_file()] + if not files: + return Failure("The places the seats found hard name no Go file that the base holds, so there is nowhere to plant a bug.") + run = functools.partial(run_tool, prefix=given.get("--prefix"), env=env, killpg=os.killpg) + mutants = killed_mutants(trees["base"], files, run, CPUS_PER_SLOT) + if isinstance(mutants, Failure): + return mutants try: - shutil.rmtree(folder, ignore_errors=True) - trees: dict[str, str] = {} - for side, commit in sides.items(): - tree = archived(commit, folder / "trees" / side, checkout, git) - if isinstance(tree, Failure): - return tree - trees[side] = tree - files = [path for path in place_files(places) if pathlib.Path(trees["base"], path).is_file()] - if not files: - return Failure("The places the seats found hard name no Go file that the base holds, so there is nowhere to plant a bug.") - run = functools.partial(run_tool, prefix=given.get("--prefix"), env=env, killpg=os.killpg) - mutants = killed_mutants(trees["base"], files, run, CPUS_PER_SLOT) - if isinstance(mutants, Failure): - return mutants - try: - found = opened(containers, given["--image"]) or benched(Bench(checkout, sides, trees, Asked(int(given["--seed"]), int(given["--bugs"]), int(given["--runs"])), containers, folder, git), mutants) - finally: - closed(containers) - except OSError as failure: - return Failure(f"could not write under {folder}: {failure}") + found = opened(containers, given["--image"]) or benched(Bench(checkout, sides, trees, Asked(int(given["--seed"]), int(given["--bugs"]), int(given["--runs"])), containers, folder, git, say), mutants) + finally: + closed(containers) return found if isinstance(found, Failure) else [*found, f"{KEPT}{folder}"] -def commits(given: dict[str, str], checkout: str, git: Git) -> dict[str, str] | Failure: +def commits(given: dict[str, str], checkout: str, git: Git) -> dict[Side, str] | Failure: """The base's commit and the head's.""" head = git("rev-parse", "--verify", f"{given.get('--head', 'HEAD')}^{{commit}}", cwd=checkout) against = given.get("--base") or default_ref(cwd=checkout, run=git) @@ -252,7 +264,9 @@ def commits(given: dict[str, str], checkout: str, git: Git) -> dict[str, str] | def archived(commit: str, into: pathlib.Path, checkout: str, git: Git) -> str | Failure: """Makes `into` the tree at commit, as `git archive` holds it, and returns its path: without git's own data, and without a path the project marks `export-ignore`.""" - into.mkdir(parents=True) + made = on_disk(f"make {into}", lambda: into.mkdir(parents=True)) + if isinstance(made, Failure): + return made archive = into.with_suffix(".tar") wrote = git("archive", "--format=tar", "--output", str(archive), commit, cwd=checkout) if isinstance(wrote, Failure): @@ -260,9 +274,9 @@ def archived(commit: str, into: pathlib.Path, checkout: str, git: Git) -> str | try: with tarfile.open(archive) as held: held.extractall(into, filter="tar") - except tarfile.TarError as failure: + archive.unlink() + except (tarfile.TarError, OSError) as failure: return Failure(f"could not unpack the tree at {commit}: {failure}") - archive.unlink() return str(into) @@ -278,7 +292,8 @@ def benched(bench: Bench, mutants: list[Mutant]) -> list[str] | Failure: if fixes.stopped and not fixes.results: return fixes.stopped names = {task.number: task.named() for task in tasks} - kept(bench, tasks, fixes.results) + if failure := kept(bench, tasks, names, fixes.results): + return failure if fixes.stopped: return stopped_report(fixes.stopped, fixes.results, total, names, bench.folder) return report(bench.sides, names, bench.asked, fixes.results) @@ -316,19 +331,24 @@ def ran_fixes(bench: Bench, tasks: list[Task], total: int) -> Fixes: if isinstance(result, Failure): return Fixes(results, result) results.append(result) - print(f"task-bench: run {len(results)} of {total}, bug {task.number} at the {side}: {'passed' if result.passed else 'not passed'}.", file=sys.stderr) + bench.say(f"task-bench: run {len(results)} of {total}, bug {task.number} at the {side}: {'passed' if result.passed else 'not passed'}.") return Fixes(results, None) -def kept(bench: Bench, tasks: list[Task], results: list[Result]) -> None: - """Writes results.json and the digest into the bench's folder.""" - names = {task.number: task.named() for task in tasks} - (bench.folder / "results.json").write_text(json.dumps({"sides": bench.sides, "seed": bench.asked.seed, "bugs": names, "runs": [recorded(result) for result in results]}, indent="\t") + "\n", encoding="utf-8") +def kept(bench: Bench, tasks: list[Task], names: dict[int, str], results: list[Result]) -> Failure | None: + """Writes results.json and the digest into the bench's folder, with names the bugs' names by number.""" in_a_tree = lambda path: any(pathlib.Path(tree, path).is_file() for tree in bench.trees.values()) - (bench.folder / DIGEST).write_text(digest(bench.sides, table(results, names), [digested(task, results, bench.folder) for task in tasks], in_a_tree), encoding="utf-8", errors="replace") + recorded_runs = json.dumps({"sides": bench.sides, "seed": bench.asked.seed, "bugs": names, "runs": [recorded(result) for result in results]}, indent="\t") + "\n" + digest_text = digest(bench.sides, table(results, names), [digested(task, results, bench.folder) for task in tasks], in_a_tree) + try: + (bench.folder / "results.json").write_text(recorded_runs, encoding="utf-8") + (bench.folder / DIGEST).write_text(digest_text, encoding="utf-8", errors="replace") + except OSError as failure: + return Failure(f"could not write the results under {bench.folder}: {failure}") + return None -def report(sides: dict[str, str], names: dict[int, str], asked: Asked, results: list[Result]) -> list[str]: +def report(sides: dict[Side, str], names: dict[int, str], asked: Asked, results: list[Result]) -> list[str]: """What a finished bench prints: the commits, the bugs named in names, what ran them, and the table.""" ran_on = sorted({f"{found.model} in Claude Code {found.version}" for result in results if (found := result.figures)}) short = [] if len(names) == asked.bugs else [f"Planted {len(names)} of the {asked.bugs} bugs asked for: no other mutant the tests kill becomes one."] @@ -352,11 +372,14 @@ def planted(bench: Bench, number: int, mutant: Mutant) -> Task | Failure | None: diff = bench.git("diff", "-U0", "--no-color", "--no-ext-diff", "--no-textconv", bench.sides["base"], bench.sides["head"], "--", mutant.path, cwd=bench.checkout, errors="replace") if isinstance(diff, Failure): return diff - sources = {side: source.read_bytes() if (source := pathlib.Path(tree, mutant.path)).is_file() else None for side, tree in bench.trees.items()} + sources = on_disk(f"read {mutant.path}", lambda: {side: source.read_bytes() if (source := pathlib.Path(tree, mutant.path)).is_file() else None for side, tree in bench.trees.items()}) + if isinstance(sources, Failure): + return sources bugs = bug_at_sides(mutant, diff, sources) if bugs is None: return None - trees, messages = {}, {} + trees: dict[Side, str] = {} + messages: dict[Side, str] = {} for side, changed in bugs.items(): tree = bench.folder / "bugs" / str(number) / side message = planted_tree(bench, side, tree, mutant.path, changed) @@ -366,12 +389,15 @@ def planted(bench: Bench, number: int, mutant: Mutant) -> Task | Failure | None: return Task(number, mutant, trees, messages) -def planted_tree(bench: Bench, side: str, tree: pathlib.Path, path: str, changed: bytes) -> str | Failure | None: +def planted_tree(bench: Bench, side: Side, tree: pathlib.Path, path: str, changed: bytes) -> str | Failure | None: """Makes tree a copy of the side's with the file at path holding changed, committed once, and returns what the failing test prints there; None where it prints no message to tell Haiku.""" shutil.rmtree(tree, ignore_errors=True) - shutil.copytree(bench.trees[side], tree, symlinks=True) - (tree / path).write_bytes(changed) + try: + shutil.copytree(bench.trees[side], tree, symlinks=True) + (tree / path).write_bytes(changed) + except OSError as failure: + return Failure(f"could not plant the bug in {tree}: {failure}") ran = tests_in_copy(bench.containers, str(tree), bench.folder) # Tests that never end under the bug have no message. if isinstance(ran, TimedOut): @@ -391,30 +417,40 @@ def planted_tree(bench: Bench, side: str, tree: pathlib.Path, path: str, changed def tests_in_copy(containers: Containers, tree: str, folder: pathlib.Path) -> Ran | Failure: """The test command's run in a copy of tree, removed afterwards, so what the tests write stays out of tree.""" copy = folder / "tested" - shutil.copytree(tree, copy, symlinks=True) + copied = on_disk(f"copy {tree} to test it", lambda: shutil.copytree(tree, copy, symlinks=True)) + if isinstance(copied, Failure): + return copied try: return ran_tests(containers, str(copy)) finally: shutil.rmtree(copy, ignore_errors=True) -def fixed(task: Task, side: str, number: int, containers: Containers, folder: pathlib.Path) -> Result | Failure: +def fixed(task: Task, side: Side, number: int, containers: Containers, folder: pathlib.Path) -> Result | Failure: """One run: Haiku's fix of task at side in a copy of its planted tree, then the tests over what it changed. The stream stays in folder; the copy is removed. Tests that run out of time don't pass.""" stream = stream_of(Result(task.number, side, number, False, None), folder) - stream.parent.mkdir(exist_ok=True) copy, check = folder / "copy", folder / "check" try: - shutil.copytree(task.trees[side], copy, symlinks=True) + try: + stream.parent.mkdir(exist_ok=True) + shutil.copytree(task.trees[side], copy, symlinks=True) + except OSError as failure: + return Failure(f"could not copy bug {task.number}'s tree at the {side}: {failure}") attempted = fix_attempted(containers, str(copy), task.messages[side], stream) if isinstance(attempted, Failure): return attempted - raw = stream.read_bytes() - entries = entries_of(raw) - found = figures(raw, entries, os.path.join(WORK, task.mutant.path)) + raw = on_disk(f"read {stream}", stream.read_bytes) + if isinstance(raw, Failure): + return raw + events = json_objects(raw) + entries = [entry_from(event) for event in events] + found = figures(events, os.path.join(WORK, task.mutant.path)) if isinstance(found, Failure): return found - checked_tree(task.trees[side], str(copy), str(check)) + checked = on_disk(f"make the tree that checks bug {task.number}'s fix at the {side}", lambda: checked_tree(task.trees[side], str(copy), str(check))) + if isinstance(checked, Failure): + return checked ran = ran_tests(containers, str(check)) if isinstance(ran, Failure) and not isinstance(ran, TimedOut): return ran diff --git a/bin/task_bench/plant.py b/bin/task_bench/plant.py index 65e46017..ebd2ba24 100644 --- a/bin/task_bench/plant.py +++ b/bin/task_bench/plant.py @@ -9,6 +9,7 @@ from failure import Failure from mutate_changes.in_diff_tools import gremlins_mutants from mutate_changes.changed_lines import is_test from mutate_changes.tool_process import Run +from task_bench.figures import Side # A place as `larv-review places` prints it: `:` in backticks. PLACE = re.compile(r"`([^`\s:]+):\d+`") @@ -86,7 +87,7 @@ def mutated(source: bytes, mutant: Mutant) -> bytes | None: return b"\n".join(lines) -def bug_at_sides(mutant: Mutant, diff: str, sources: dict[str, bytes | None]) -> dict[str, bytes] | None: +def bug_at_sides(mutant: Mutant, diff: str, sources: dict[Side, bytes | None]) -> dict[Side, bytes] | None: """The file of mutant with the bug in it, at the base and at the head, from the file at each side, None where the side has none, and the diff of it from base to head. None where the mutant doesn't become a bug at one side or the other. @@ -94,8 +95,9 @@ def bug_at_sides(mutant: Mutant, diff: str, sources: dict[str, bytes | None]) -> at_head = line_at_head(diff, mutant.line) if at_head is None: return None - bugs = {} - for side, placed in (("base", mutant), ("head", mutant._replace(line=at_head))): + bugs: dict[Side, bytes] = {} + placings: tuple[tuple[Side, Mutant], ...] = (("base", mutant), ("head", mutant._replace(line=at_head))) + for side, placed in placings: changed = None if (source := sources[side]) is None else mutated(source, placed) if changed is None: return None diff --git a/bin/task_bench/test_figures.py b/bin/task_bench/test_figures.py index 29f68dd8..789236b7 100644 --- a/bin/task_bench/test_figures.py +++ b/bin/task_bench/test_figures.py @@ -7,9 +7,9 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from task_bench import figures as bench_figures -from claude_code.entries import entries_of from failure import Failure from task_bench.figures import Figures, Result, table +from claude_code.entries import json_objects from claude_code.tokens import Tokens INIT = {"type": "system", "subtype": "init", "cwd": "/work", "model": "claude-haiku-5-5", "claude_code_version": "2.1.330"} @@ -26,7 +26,7 @@ def stream(*events: dict) -> bytes: def figures(raw: bytes, bug_file: str) -> Figures | None | Failure: - return bench_figures.figures(raw, entries_of(raw), bug_file) + return bench_figures.figures(json_objects(raw), bug_file) class FiguresTest(unittest.TestCase): diff --git a/bin/task_bench/test_task_bench.py b/bin/task_bench/test_task_bench.py index 9df98188..dacae2e9 100644 --- a/bin/task_bench/test_task_bench.py +++ b/bin/task_bench/test_task_bench.py @@ -450,7 +450,7 @@ class RunOutcomesTest(unittest.TestCase): return Containers(InTurn(*runs), "bench", "go test ./...", 512, "1000:1000") def bench(self, *runs: Ran | Failure) -> main.Bench: - return main.Bench("", {"base": "b", "head": "h"}, self.trees, main.Asked(seed=1, bugs=1, runs=1), self.containers(*runs), self.folder, lambda *args, **given: "") + return main.Bench("", {"base": "b", "head": "h"}, self.trees, main.Asked(seed=1, bugs=1, runs=1), self.containers(*runs), self.folder, lambda *args, **given: "", lambda line: None) def test_a_fix_whose_tests_run_out_of_time_does_not_pass(self): late = TimedOut("docker run still ran after 30 min") @@ -659,5 +659,17 @@ class ApiProxyTest(unittest.IsolatedAsyncioTestCase): self.assertEqual(await self.answered(request), b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n") +class OnDisk(unittest.TestCase): + def test_a_refused_file_operation_is_a_failure_that_says_what_could_not_be_done(self): + with tempfile.TemporaryDirectory() as folder: + missing = pathlib.Path(folder, "gone", "file") + found = main.on_disk(f"read {missing}", missing.read_bytes) + self.assertIsInstance(found, Failure) + self.assertTrue(found.reason.startswith(f"could not read {missing}: "), found.reason) + + def test_an_operation_that_succeeds_gives_its_answer(self): + self.assertEqual(main.on_disk("count", lambda: 3), 3) + + if __name__ == "__main__": unittest.main() -- 2.52.0 From b7993aaf933745b1ae0524f2c6d52bc8d6b6639a Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 23 Nov 2026 01:40:09 +0100 Subject: [PATCH 06/11] =?UTF-8?q?Answer=20principles=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20every=20ans?= =?UTF-8?q?wer=20holds?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From cc23e80fb89a46c2470a16ddb86c9d62d206aa07 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 23 Nov 2026 01:58:57 +0100 Subject: [PATCH 07/11] Test that each file task-bench cannot copy, read or write fails the bench and names what could not be done --- bin/task_bench/test_task_bench.py | 42 +++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/bin/task_bench/test_task_bench.py b/bin/task_bench/test_task_bench.py index dacae2e9..945ca53a 100644 --- a/bin/task_bench/test_task_bench.py +++ b/bin/task_bench/test_task_bench.py @@ -2,6 +2,7 @@ fix is checked in, and the proxy that reaches only the API.""" import asyncio import contextlib +import dataclasses import io import json import os @@ -472,6 +473,47 @@ class RunOutcomesTest(unittest.TestCase): broke = Failure("docker could not start: No such file or directory") self.assertEqual(main.planted(self.bench(broke), 1, self.MUTANT), broke) + def assertFailsWith(self, found, start: str): + self.assertIsInstance(found, Failure) + self.assertTrue(found.reason.startswith(start), found.reason) + + def test_a_tree_that_cannot_be_copied_for_a_fix_fails_the_bench_naming_the_bug_and_side(self): + task = dataclasses.replace(self.task, trees={"base": str(self.folder / "gone"), "head": str(self.tree)}) + self.assertFailsWith(main.fixed(task, "base", 1, self.containers(), self.folder), "could not copy bug 1's tree at the base: ") + + def test_a_tree_that_checks_a_fix_that_cannot_be_made_fails_the_bench_naming_the_bug_and_side(self): + (self.folder / "check").mkdir() + self.assertFailsWith(main.fixed(self.task, "base", 1, self.containers(Ran(0, "")), self.folder), "could not make the tree that checks bug 1's fix at the base: ") + + def test_results_that_cannot_be_written_fail_the_bench_naming_the_folder(self): + bench = dataclasses.replace(self.bench(), folder=self.folder / "gone") + self.assertFailsWith(main.kept(bench, [], {}, []), f"could not write the results under {self.folder / 'gone'}: ") + + def test_a_bug_that_cannot_be_planted_fails_the_bench_naming_the_tree(self): + (self.folder / "file").write_text("") + tree = self.folder / "file" / "base" + self.assertFailsWith(main.planted_tree(self.bench(), "base", tree, "calc.go", b""), f"could not plant the bug in {tree}: ") + + def test_a_tree_that_cannot_be_copied_for_its_tests_fails_the_bench_naming_it(self): + gone = str(self.folder / "gone") + self.assertFailsWith(main.tests_in_copy(self.containers(), gone, self.folder), f"could not copy {gone} to test it: ") + + def test_a_tree_whose_folder_cannot_be_made_fails_the_bench_naming_it(self): + (self.folder / "file").write_text("") + into = self.folder / "file" / "base" + self.assertFailsWith(main.archived("b", into, "", lambda *args, **given: ""), f"could not make {into}: ") + + def test_a_mutant_in_a_file_that_cannot_be_read_fails_the_bench_naming_the_file(self): + (self.tree / "calc.go").chmod(0) + self.addCleanup((self.tree / "calc.go").chmod, 0o644) + self.assertFailsWith(main.planted(self.bench(), 1, self.MUTANT), "could not read calc.go: ") + + def test_a_mutant_in_a_file_the_head_lacks_is_passed_over(self): + head = self.folder / "head" + head.mkdir() + bench = dataclasses.replace(self.bench(), trees={"base": str(self.tree), "head": str(head)}) + self.assertIsNone(main.planted(bench, 1, self.MUTANT)) + class ContainersTest(unittest.TestCase): IN_TREE = ["--memory", "512m", "--memory-swap", "512m", "--user", "1000:1000", "--env", "HOME=/tmp", "--volume", "/tree:/work", "--workdir", "/work"] -- 2.52.0 From ba50eacafe8e16107697bb16306c019b3b37988b Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 23 Nov 2026 02:30:52 +0100 Subject: [PATCH 08/11] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=204=20=F0=9F=9F=A1=20(0=20misread);=20test=20the?= =?UTF-8?q?=20digest's=20half=20surrogate,=20git's=20diff=20settings=20and?= =?UTF-8?q?=20literal=20report=20rows,=20and=20guard=20the=20permissions?= =?UTF-8?q?=20test=20against=20root?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/task_bench/test_task_bench.py | 36 ++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/bin/task_bench/test_task_bench.py b/bin/task_bench/test_task_bench.py index 945ca53a..05ede27b 100644 --- a/bin/task_bench/test_task_bench.py +++ b/bin/task_bench/test_task_bench.py @@ -16,12 +16,12 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from task_bench import api_proxy, bench_folder, main, runs +from test_env import assert_not_root, isolated_env from task_bench.runs import checked_tree, closed, Containers, docker_cli, fix_attempted, opened, ran_tests, TimedOut from task_bench.plant import drawn, Mutant -from claude_code.entries import Entry +from claude_code.entries import Entry, entry_from from failure import Failure -from task_bench.figures import Figures, Result, table -from test_env import isolated_env +from task_bench.figures import Figures, Result from mutate_changes.tool_process import Ran from claude_code.tokens import Tokens @@ -166,6 +166,16 @@ class BenchTest(unittest.TestCase): self.assertEqual((folder / "runs/bug-1-base-1.stderr").read_bytes(), b"") self.assertEqual(os.readlink(folder / "bugs/1/head/dangling"), "missing") + def test_plants_the_bug_on_the_same_line_at_the_head_whatever_the_callers_git_does_to_a_diff(self): + # Colour, an external diff and a textconv that numbers the lines each change what `git diff` prints, and so where the head's line is. + self.git("config", "color.diff", "always") + self.git("config", "diff.external", "false") + self.git("config", "diff.numbered.textconv", "cat -n") + (self.repo / ".git/info/attributes").write_text("*.go diff=numbered\n") + report = self.bench() + self.assertNotIsInstance(report, Failure, report) + self.assertIn("| 1: calc.go:4:11 ARITHMETIC_BASE | head | 2/2 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | 1 |", report) + def test_writes_a_digest_of_the_runs_with_each_bugs_decoys_and_traces(self): folder = pathlib.Path(self.bench()[-1].removeprefix(main.KEPT)) digest = (folder / "digest.md").read_text().splitlines() @@ -351,10 +361,19 @@ class ReportTest(unittest.TestCase): SIDES = {"base": "b" * 40, "head": "h" * 40} NAMES = {1: "calc.go:4:11 ARITHMETIC_BASE"} RESULTS = [Result(1, "base", 1, True, Figures("2.1.330", "claude-haiku-5-5", Tokens(40, 0, 9000, 52000, 800), 7, 61.5, 2)), Result(1, "head", 1, False, None)] + TABLE = [ + "| Bug | Side | Passed | Input | Cache write | Cache read | Output | Turns | Wall, s | Reads |", + "|---|---|---|---|---|---|---|---|---|---|", + "| 1: calc.go:4:11 ARITHMETIC_BASE | base | 1/1 | 40 | 9000 | 52000 | 800 | 7 | 61.5 | 2 |", + "| 1: calc.go:4:11 ARITHMETIC_BASE | head | 0/1 | - | - | - | - | - | - | - |", + "| All | base | 1/1 | 40 | 9000 | 52000 | 800 | 7 | 61.5 | 2 |", + "| All | head | 0/1 | - | - | - | - | - | - | - |", + "| All | change | -1 | - | - | - | - | - | - | - |", + ] def test_names_the_commits_the_bugs_the_runs_and_what_ran_them_above_the_table(self): told = main.report(self.SIDES, self.NAMES, main.Asked(seed=1, bugs=1, runs=2), self.RESULTS) - self.assertEqual(told, ["task-bench: base bbbbbbbbbbbb, head hhhhhhhhhhhh. 1 bug, each run 2 times at each side by claude-haiku-5-5 in Claude Code 2.1.330.", "", *table(self.RESULTS, self.NAMES), ""]) + self.assertEqual(told, ["task-bench: base bbbbbbbbbbbb, head hhhhhhhhhhhh. 1 bug, each run 2 times at each side by claude-haiku-5-5 in Claude Code 2.1.330.", "", *self.TABLE, ""]) def test_says_where_fewer_bugs_were_planted_than_asked_for_and_where_no_run_finished(self): told = main.report(self.SIDES, self.NAMES, main.Asked(seed=1, bugs=3, runs=1), self.RESULTS[1:]) @@ -362,7 +381,7 @@ class ReportTest(unittest.TestCase): def test_a_stopped_bench_tells_why_then_how_far_it_came_then_the_table(self): told = main.stopped_report(Failure("claude could not use the API: Invalid bearer token"), self.RESULTS, 10, self.NAMES, pathlib.Path("/reviews/task-bench")) - self.assertEqual(told, Failure("\n".join(["claude could not use the API: Invalid bearer token", "task-bench stopped after 2 of 10 runs, which results.json holds in /reviews/task-bench:", "", *table(self.RESULTS, self.NAMES)]))) + self.assertEqual(told, Failure("\n".join(["claude could not use the API: Invalid bearer token", "task-bench stopped after 2 of 10 runs, which results.json holds in /reviews/task-bench:", "", *self.TABLE]))) class MainTest(unittest.TestCase): @@ -504,10 +523,17 @@ class RunOutcomesTest(unittest.TestCase): self.assertFailsWith(main.archived("b", into, "", lambda *args, **given: ""), f"could not make {into}: ") def test_a_mutant_in_a_file_that_cannot_be_read_fails_the_bench_naming_the_file(self): + assert_not_root(self) (self.tree / "calc.go").chmod(0) self.addCleanup((self.tree / "calc.go").chmod, 0o644) self.assertFailsWith(main.planted(self.bench(), 1, self.MUTANT), "could not read calc.go: ") + def test_a_digest_quoting_half_of_a_surrogate_pair_is_written_with_a_question_mark_in_its_place(self): + # Claude Code may cut a string between the halves of an emoji's pair, and JSON parses the half it keeps into a lone surrogate. + said = entry_from(json.loads('{"type": "assistant", "message": {"content": [{"type": "text", "text": "half \\ud83d pair"}]}}')) + self.assertIsNone(main.kept(self.bench(), [self.task], {1: "calc.go:4:11 ARITHMETIC_BASE"}, [Result(1, "base", 1, False, None, [said])])) + self.assertIn("half ? pair", (self.folder / "digest.md").read_text(encoding="utf-8")) + def test_a_mutant_in_a_file_the_head_lacks_is_passed_over(self): head = self.folder / "head" head.mkdir() -- 2.52.0 From 83194a11a5c50f84791d6ee72308753bec0438aa Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 23 Nov 2026 02:30:59 +0100 Subject: [PATCH 09/11] =?UTF-8?q?Answer=20prose=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=2012=20=F0=9F=9F=A1=20(0=20misread);=20keep=20a?= =?UTF-8?q?=20{}=20line=20as=20an=20entry,=20point=20handed=5Fon=20and=20p?= =?UTF-8?q?arked=5Fthrough=20at=20the=20docstrings=20that=20hold=20their?= =?UTF-8?q?=20rules,=20split=20news=5Fafter's=20two=20kinds=20of=20news,?= =?UTF-8?q?=20say=20what=20each=20parameter=20is,=20reword=20item=20517's?= =?UTF-8?q?=20way=20out,=20and=20report=20a=20.tar=20left=20behind=20as=20?= =?UTF-8?q?its=20own=20failure?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- bin/claude_code/entries.py | 2 +- bin/claude_code/test_claude_code.py | 4 ++-- bin/do_epic/main.py | 8 ++++---- bin/do_epic/parking.py | 8 ++++++-- bin/do_epic/test_parking.py | 4 ++-- bin/larv_review/reviewer_header.py | 2 +- bin/larv_review/scoring_due.py | 2 +- bin/task_bench/figures.py | 4 ++-- bin/task_bench/main.py | 12 ++++++------ bin/task_bench/plant.py | 6 ++++-- bin/task_bench/test_plant.py | 2 +- bin/task_bench/test_task_bench.py | 6 +++--- todo.md | 4 ++-- 14 files changed, 36 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 145b579f..15d6349d 100644 --- a/README.md +++ b/README.md @@ -243,7 +243,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`. - `deploy_release` imports `release_plan`'s `release_standing`. - `do_epic/` holds `do-epic`, the tool that drives one Jira epic: - - `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `epic_run.py` holds what one run of do-epic keeps, and starts the chunks that may start now. + - `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `epic_run.py` holds what stays the same through one run of do-epic, such as its config, its Jira store and its paths, and starts the chunks that may start now. - `planning.py` settles, before the chunks start, where each open issue is worked, its scores and the order the issues start in, through `split.py`, `repo_pick.py`, `issue_scores.py` and `ranking.py`. - `scheduler.py` says which issues run now: as many as the epic's cap and each repo's `parallel-chunks` allow, and none in a repo where loop-claude runs chunks. - `gates.py` reads once whether a chunk's pull request waits on its checks, an approval or a new review, and `parked.py` keeps each chunk that does in a state file, so it takes no running slot while it waits and goes on waiting after a reboot. `parking.py` parks such a chunk after a cycle and polls the gate until its worker has something to do. diff --git a/bin/claude_code/entries.py b/bin/claude_code/entries.py index 43d21637..1d5aced4 100644 --- a/bin/claude_code/entries.py +++ b/bin/claude_code/entries.py @@ -86,7 +86,7 @@ def parse_entry(raw: str | bytes) -> Entry | None: def json_objects(raw: bytes) -> list[dict]: """The lines of a transcript or a stream-json stream that are JSON objects, parsed.""" - return [found for line in raw.splitlines() if (found := json_object(line))] + return [found for line in raw.splitlines() if (found := json_object(line)) is not None] def entries_of(raw: bytes) -> list[Entry]: diff --git a/bin/claude_code/test_claude_code.py b/bin/claude_code/test_claude_code.py index 186b6b47..7ce0780e 100644 --- a/bin/claude_code/test_claude_code.py +++ b/bin/claude_code/test_claude_code.py @@ -100,8 +100,8 @@ class Parse(unittest.TestCase): self.assertIsNone(entries.parse_entry("[1, 2]")) def test_a_stream_parses_into_an_entry_per_line_that_is_a_json_object(self): - raw = b'{"type": "user", "message": {"content": "do it"}}\nnot json\n\n{"type": "summary"}\n' - self.assertEqual(entries.entries_of(raw), [entries.HumanTurn(text="do it"), entries.Entry()]) + raw = b'{"type": "user", "message": {"content": "do it"}}\nnot json\n\n{"type": "summary"}\n{}\n' + self.assertEqual(entries.entries_of(raw), [entries.HumanTurn(text="do it"), entries.Entry(), entries.Entry()]) self.assertEqual(entries.entries_of(b""), []) diff --git a/bin/do_epic/main.py b/bin/do_epic/main.py index 52fd6900..d0e33725 100644 --- a/bin/do_epic/main.py +++ b/bin/do_epic/main.py @@ -353,7 +353,7 @@ class Landed(enum.Enum): class How(enum.Enum): - """How a finished chunk's issue moves, where it moves to no status the config names.""" + """How a finished chunk's issue moves when it doesn't move to a status the config names.""" # do-epic neither moves nor awaits it. LEFT = enum.auto() # Nobody would move it, so the loop stops. @@ -366,7 +366,7 @@ class How(enum.Enum): @dataclasses.dataclass(frozen=True) class ToStatus: - """do-epic moves a finished chunk's issue to status, trying a failed move again by way of through, None where there is none.""" + """do-epic moves a finished chunk's issue to status. Where that move fails, it moves the issue to through first and tries again; through is None where the config names no open status.""" status: str through: str | None @@ -376,7 +376,7 @@ Move = How | ToStatus def issue_move(landed: Landed, automated: bool, merged: str | None, opened: str | None, finishing: bool) -> Move: - """The move of the issue of a finished chunk whose work landed as landed says. automated says the team's automation moves issues, merged and opened are the statuses `jira-pull-request-merged-status` and `jira-pull-request-open-status` name, each None where the config names none, and finishing says the chunk is the epic's finishing. The first row that fits: + """The move of a finished chunk's issue. landed says where the chunk's work landed, automated says the team's automation moves issues, merged and opened are the statuses `jira-pull-request-merged-status` and `jira-pull-request-open-status` name, each None where the config names none, and finishing says the chunk is the epic's finishing. The first row that fits: | The chunk | The automation moves issues | A merged status is named | Move | |---|---|---|---| @@ -400,7 +400,7 @@ def issue_move(landed: Landed, automated: bool, merged: str | None, opened: str def handed_on(key: str, epic: EpicRun, landed: Landed = Landed.NOWHERE) -> Stop: - """The stop of a do-epic whose chunk finished. It first moves the chunk's issue to done (the epic's finishing has none), and its parent too where the parent's sub-tasks now let it move (`parents_settled`), so that no finished chunk starts again and what they block may start, then starts each chunk that may start now. Where the team's automation moves issues, others move two kinds of issue. The automation moves the issue of a chunk whose work landed on the default branch, from its pull request: the stop waits for that move (`moved_by_automation`). The human moves their own task: the stop doesn't move or await anything. A chunk without a repo has no pull request, so its issue moves to done as ever, and so does a split item, once Jira counts each of its sub-tasks done. The automation doesn't see a pull request that merged into an epic's working branch: the stop moves that chunk's issue to the status `jira-pull-request-merged-status` names. Where none is named, it moves the issue to done, or stops where the automation moves issues, since then nobody would move it. do-epic's window closes as it exits.""" + """The stop of a do-epic whose chunk finished. It first moves the chunk's issue as `issue_move` says, and the issue's parent too where the parent's sub-tasks now let it move (`parents_settled`), so that no finished chunk starts again and what they block may start. Then it starts each chunk that may start now. Where the team's automation moves the issue, the stop waits for that move (`moved_by_automation`). do-epic's window closes as it exits.""" move = issue_move(landed, epic.config.automation_moves, epic.config.pull_merged_status, epic.config.pull_open_status, finishing=key == epic.key) issues: list[EpicIssue] | Failure match move: diff --git a/bin/do_epic/parking.py b/bin/do_epic/parking.py index ec7eef0b..d24d529c 100644 --- a/bin/do_epic/parking.py +++ b/bin/do_epic/parking.py @@ -18,7 +18,7 @@ DRIVER_PARKED = f"{chunk_prompt.DRIVER} parked the chunk while" def parked_through(repo: str, loop: Loop, epic: EpicRun, told: str | None, finished: bool, based: str | None) -> str | Stop: """Keeps the chunk in loop's window parked. Its work is in the repo called repo. It stays parked for as long as its pull request waits on a gate, and returns once its worker has something to do: what to tell that worker, or empty where the chunk was never parked. told is the news its last cycle's worker got, None where the window just started, and finished says the judge ruled the chunk finished. based is the epic's working branch that `epic_based` recorded as the chunk's base when the window started, None where it recorded none. A window that just started parks the chunk only if its file says so: the forge isn't read for a chunk that starts afresh. - Where a person merges, a worker ends its run with the pull request open, so the judge may rule the chunk finished before it is. For such a finished chunk, a gate that cannot be read is read again until it can, and a pull request no longer open, in a worktree that still stands, is news the worker hasn't been told: the worker removes the worktree. A pull request that doesn't merge into its base is news after every cycle that leaves it so: the worker levels the branch. + Where a person merges, a worker ends its run with the pull request open, so the judge may rule the chunk finished before it is. For such a finished chunk, a gate that cannot be read is read again until it can (`Poll.first_gate`), and what the worker must still do is news (`news_after`). A chunk parks in three steps: its file is written, its window is shown as parked, and the epic's next chunks start in the slot it frees. It resumes in the reverse order: `scheduler.resume` gives it a running slot, then its file is removed. So a window that ends in between finds the chunk parked when it starts again. """ @@ -54,7 +54,11 @@ def parked_through(repo: str, loop: Loop, epic: EpicRun, told: str | None, finis def news_after(entered: gates.Open | Failure | None, finished: bool, by_human: bool, told: str | None) -> str: - """What to tell the worker of a chunk that isn't parked as its cycle ends, empty where there isn't anything. entered is what was read instead of a gate, None where the window just started. Only a chunk the judge ruled finished, whose pull request a person merges, has news: that its pull request doesn't merge into its base, after every cycle that leaves it so, or that its worktree stands though no pull request is open, unless told, the news its last worker got, says so already.""" + """What to tell the worker of a chunk that isn't parked as its cycle ends, empty where there isn't anything. entered is what was read instead of a gate, None where the window just started, and told is the news the last worker got. + + Only a chunk the judge ruled finished, whose pull request a person merges, has news, of one of two kinds: + - its pull request doesn't merge into its base: news after every cycle that leaves it so, and the worker levels the branch; + - its worktree stands though no pull request is open: news once, unless told says so already, and the worker removes the worktree.""" if not (finished and by_human): return "" if isinstance(entered, gates.Unmergeable): diff --git a/bin/do_epic/test_parking.py b/bin/do_epic/test_parking.py index 4a7d2154..53e58bce 100644 --- a/bin/do_epic/test_parking.py +++ b/bin/do_epic/test_parking.py @@ -19,12 +19,12 @@ class TheNewsOfAChunkThatIsNotParked(unittest.TestCase): def test_a_window_that_just_started_has_no_news(self) -> None: self.assertEqual(news_after(None, finished=True, by_human=True, told=None), "") - def test_a_gate_that_cannot_be_read_or_a_pull_request_with_news_of_its_own_adds_none(self) -> None: + def test_a_gate_that_cannot_be_read_or_one_that_lets_the_chunk_go_on_does_not_add_any_news(self) -> None: for entered in (Failure("no network"), Open("a reviewer requested changes")): with self.subTest(entered): self.assertEqual(news_after(entered, finished=True, by_human=True, told=""), "") - def test_an_unfinished_chunk_or_one_no_person_merges_has_no_news(self) -> None: + def test_an_unfinished_chunk_or_one_that_merges_without_a_person_has_no_news(self) -> None: for entered in (UNOPENED, UNMERGEABLE): for finished, by_human in ((False, True), (True, False), (False, False)): with self.subTest(entered=entered, finished=finished, by_human=by_human): diff --git a/bin/larv_review/reviewer_header.py b/bin/larv_review/reviewer_header.py index 872ca8cb..d80b2239 100644 --- a/bin/larv_review/reviewer_header.py +++ b/bin/larv_review/reviewer_header.py @@ -81,7 +81,7 @@ def unanswered_round(titles: list[str], pass_: str) -> int | Failure: def branch_summaries(default: str, home: pathlib.Path) -> list[str] | Failure: - """The branch's commit titles since default, each read as its summary in the project's title templates, so round titles count under any template. rule-hook's round-cap reads them its own way: guarded, and counting none where git fails.""" + """The branch's commit titles since default, each read as its summary in the project's title templates, so round titles count under any template. rule-hook's round-cap reads them its own way: guarded, and counting zero rounds where git fails.""" titles = branch_titles(default) if isinstance(titles, Failure): return titles diff --git a/bin/larv_review/scoring_due.py b/bin/larv_review/scoring_due.py index 2d7a17f7..b5d75b73 100644 --- a/bin/larv_review/scoring_due.py +++ b/bin/larv_review/scoring_due.py @@ -1,4 +1,4 @@ -"""When the plan calls a scoring run: a chunk that ships a floor item, one that empties a release work has landed towards, or one after a release cut unmeasured; and each reason it gives.""" +"""When the plan calls a scoring run: a chunk that ships a floor item, one that empties a release that work has already landed towards, or one after a release cut unmeasured; and each reason it gives.""" import pathlib diff --git a/bin/task_bench/figures.py b/bin/task_bench/figures.py index 2988c56d..f57d5c69 100644 --- a/bin/task_bench/figures.py +++ b/bin/task_bench/figures.py @@ -30,7 +30,7 @@ class Figures: class Result(typing.NamedTuple): """One run of a task at a side. figures is None where its claude ended without a result, as when it ran out of time. entries - holds what its stream tells, for the digest.""" + holds the entries of its stream, which the digest quotes.""" task: int side: Side @@ -63,7 +63,7 @@ HEADINGS = ["Bug", "Side", "Passed", *(column.heading for column in COLUMNS)] def figures(events: list[dict], bug_file: str) -> Figures | None | Failure: - """The figures of the run whose claude printed events, its stream's JSON lines, with bug_file the bug's file as the run's + """The figures of the run whose claude printed events, the objects parsed from its stream's lines, with bug_file the bug's file as the run's container names it. None where the stream holds no result. A Failure where the API refused the run, as on a token it doesn't take: such a run diff --git a/bin/task_bench/main.py b/bin/task_bench/main.py index 14a01955..2d501de6 100644 --- a/bin/task_bench/main.py +++ b/bin/task_bench/main.py @@ -61,7 +61,7 @@ Each bench empties its own folder first, and removes the folder every earlier be not, unless a bench or a gather is using it. So gather a bench before the next one starts. Exit 1, saying why, on an unknown or repeated argument, a missing --image or --test, a --seed, --bugs or --runs that is no whole -number from 1, or no token; and where git, docker or Gremlins fails, the seats' places name no Go file, the tests fail at a side +number from 1, or no token; and where git, docker or Gremlins fails, the seats' places don't name any Go file, the tests fail at a side without a bug, or no mutant becomes a bug. Where the API refuses a run, the bench stops there and exits 1 too, after the table of the runs that finished. gather exits 1, saying why, outside a checkout, without a digest, where loop-claude has saved no model for the project or the @@ -237,7 +237,7 @@ def bench_in(folder: pathlib.Path, given: dict[str, str], env: typing.Mapping[st trees[side] = tree files = [path for path in place_files(places) if pathlib.Path(trees["base"], path).is_file()] if not files: - return Failure("The places the seats found hard name no Go file that the base holds, so there is nowhere to plant a bug.") + return Failure("The places the seats found hard don't name any Go file that the base holds, so there is nowhere to plant a bug.") run = functools.partial(run_tool, prefix=given.get("--prefix"), env=env, killpg=os.killpg) mutants = killed_mutants(trees["base"], files, run, CPUS_PER_SLOT) if isinstance(mutants, Failure): @@ -274,10 +274,10 @@ def archived(commit: str, into: pathlib.Path, checkout: str, git: Git) -> str | try: with tarfile.open(archive) as held: held.extractall(into, filter="tar") - archive.unlink() except (tarfile.TarError, OSError) as failure: return Failure(f"could not unpack the tree at {commit}: {failure}") - return str(into) + removed = on_disk(f"remove {archive}", archive.unlink) + return removed if isinstance(removed, Failure) else str(into) def benched(bench: Bench, mutants: list[Mutant]) -> list[str] | Failure: @@ -300,7 +300,7 @@ def benched(bench: Bench, mutants: list[Mutant]) -> list[str] | Failure: def baseline_failure(bench: Bench) -> Failure | None: - """Why a side's tests don't pass without a planted bug; None where both sides' pass.""" + """Why a side's tests don't pass without a planted bug; None where they pass at both sides.""" for side, tree in bench.trees.items(): ran = tests_in_copy(bench.containers, tree, bench.folder) if isinstance(ran, Failure) or ran.code: @@ -336,7 +336,7 @@ def ran_fixes(bench: Bench, tasks: list[Task], total: int) -> Fixes: def kept(bench: Bench, tasks: list[Task], names: dict[int, str], results: list[Result]) -> Failure | None: - """Writes results.json and the digest into the bench's folder, with names the bugs' names by number.""" + """Writes results.json and the digest into the bench's folder. names holds each bug's name by its number.""" in_a_tree = lambda path: any(pathlib.Path(tree, path).is_file() for tree in bench.trees.values()) recorded_runs = json.dumps({"sides": bench.sides, "seed": bench.asked.seed, "bugs": names, "runs": [recorded(result) for result in results]}, indent="\t") + "\n" digest_text = digest(bench.sides, table(results, names), [digested(task, results, bench.folder) for task in tasks], in_a_tree) diff --git a/bin/task_bench/plant.py b/bin/task_bench/plant.py index ebd2ba24..7f650369 100644 --- a/bin/task_bench/plant.py +++ b/bin/task_bench/plant.py @@ -88,8 +88,10 @@ def mutated(source: bytes, mutant: Mutant) -> bytes | None: def bug_at_sides(mutant: Mutant, diff: str, sources: dict[Side, bytes | None]) -> dict[Side, bytes] | None: - """The file of mutant with the bug in it, at the base and at the head, from the file at each side, None where the side has - none, and the diff of it from base to head. None where the mutant doesn't become a bug at one side or the other. + """The file of mutant with the bug in it, at the base and at the head. None where the mutant doesn't become a bug at one side + or the other. + + sources holds the file at each side, None where the side lacks it; diff is the file's diff from base to head. The bug is the same change to the same line at both sides, so only the code around it differs between them.""" at_head = line_at_head(diff, mutant.line) diff --git a/bin/task_bench/test_plant.py b/bin/task_bench/test_plant.py index e6316ca1..4f60a573 100644 --- a/bin/task_bench/test_plant.py +++ b/bin/task_bench/test_plant.py @@ -170,7 +170,7 @@ class BugAtSidesTest(unittest.TestCase): def test_a_line_the_head_changed_holds_no_bug(self): self.assertIsNone(bug_at_sides(self.MUTANT, "@@ -3 +3 @@\n-\treturn a + b\n+\treturn b + a\n", {"base": self.BASE, "head": self.BASE})) - def test_a_side_without_the_file_or_without_the_token_holds_no_bug(self): + def test_a_side_without_the_file_or_without_the_operator_the_mutant_changes_holds_no_bug(self): self.assertIsNone(bug_at_sides(self.MUTANT, "", {"base": self.BASE, "head": None})) self.assertIsNone(bug_at_sides(self.MUTANT, "", {"base": self.BASE, "head": b"package calc\n\n\treturn sum(a, b)\n"})) diff --git a/bin/task_bench/test_task_bench.py b/bin/task_bench/test_task_bench.py index 05ede27b..b42a85e2 100644 --- a/bin/task_bench/test_task_bench.py +++ b/bin/task_bench/test_task_bench.py @@ -232,7 +232,7 @@ class BenchTest(unittest.TestCase): def test_the_command_line_fails_with_the_reason_where_the_places_or_the_bench_fail(self): argv = [part for name, value in self.given.items() for part in (name, value)] - for places, said in ((Failure("no history"), "no history\n"), ("- `gone.go:1` `Gone`: removed\n", "The places the seats found hard name no Go file that the base holds, so there is nowhere to plant a bug.\n")): + for places, said in ((Failure("no history"), "no history\n"), ("- `gone.go:1` `Gone`: removed\n", "The places the seats found hard don't name any Go file that the base holds, so there is nowhere to plant a bug.\n")): with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as errors: self.assertEqual(main.main(argv, self.env, lambda home: places), 1) self.assertEqual((out.getvalue(), errors.getvalue().splitlines(keepends=True)[-1]), ("", said)) @@ -302,7 +302,7 @@ class BenchTest(unittest.TestCase): def test_fails_where_the_places_name_no_go_file_of_the_base(self): with contextlib.redirect_stderr(io.StringIO()): found = main.bench({**self.given, "--base": "main"}, self.env, "- `gone.go:1` `Gone`: removed\n- `README.md:1` `Calc`: thin\n", self.home) - self.assertEqual(found, Failure("The places the seats found hard name no Go file that the base holds, so there is nowhere to plant a bug.")) + self.assertEqual(found, Failure("The places the seats found hard don't name any Go file that the base holds, so there is nowhere to plant a bug.")) self.assertFalse(self.log.exists()) def test_fails_where_the_tests_fail_without_a_bug(self): @@ -500,7 +500,7 @@ class RunOutcomesTest(unittest.TestCase): task = dataclasses.replace(self.task, trees={"base": str(self.folder / "gone"), "head": str(self.tree)}) self.assertFailsWith(main.fixed(task, "base", 1, self.containers(), self.folder), "could not copy bug 1's tree at the base: ") - def test_a_tree_that_checks_a_fix_that_cannot_be_made_fails_the_bench_naming_the_bug_and_side(self): + def test_failing_to_make_the_tree_that_checks_a_fix_fails_the_bench_naming_the_bug_and_side(self): (self.folder / "check").mkdir() self.assertFailsWith(main.fixed(self.task, "base", 1, self.containers(Ran(0, "")), self.folder), "could not make the tree that checks bug 1's fix at the base: ") diff --git a/todo.md b/todo.md index 9934733e..aa2e8c1b 100644 --- a/todo.md +++ b/todo.md @@ -109,8 +109,8 @@ This release changes what `task-bench`'s All change row means: it is now the mean of the bugs' own head/base changes, where 0.15.0 printed the change of the two All rows' medians. Semver read strictly lets only a minor change what exists before 1.0.0, so a patch can't ship it. The release review's architecture pass found this (`technical-principles.md`, "Semantic versioning, read strictly"). Two ways out: -- Ship this release as 0.16.0. Recommended: the old figure swung up to three times as far in tokens, so restoring it brings back a figure the release found misleading. -- Keep 0.15.1: restore the old row under its old label, add the new figure as a row of its own, and leave the new row's meaning for 0.16.0. +- Ship this release as 0.16.0. Recommended: with the same code at both sides, the old figure swung up to three times as far as the new one in tokens (`docs/decisions.md`, "Spread by bugs × runs"), so restoring it brings back a figure this release found misleading. +- Keep 0.15.1: restore the old row as 0.15.0 printed it, and ship the new figure in 0.16.0 instead. Adding the new figure as a row of its own is a minor change too, so it can't stay in 0.15.1. Touches: - `CHANGELOG.md`: `## Unreleased` (small) -- 2.52.0 From 4dd8b73054a131e38df1918207e4a9d9b110fb38 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 23 Nov 2026 02:31:00 +0100 Subject: [PATCH 10/11] =?UTF-8?q?Answer=20product-owner=20round=201:=200?= =?UTF-8?q?=20=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20note=20i?= =?UTF-8?q?n=20the=20changelog=20that=20a=20bench=20that=20can't=20copy,?= =?UTF-8?q?=20read=20or=20write=20a=20file=20names=20it=20and=20keeps=20th?= =?UTF-8?q?e=20finished=20runs'=20table?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 234df3f1..18f0180d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ - `task-bench`'s table prints the mean of the bugs' own head/base changes as its All change, in place of the change of the two All rows' medians, which swung up to three times as far in tokens. The All rows per side stay, so the change row is no longer their difference, and a change from before 0.15.1 can't be compared with one from after it. - `task-bench` now stops with a Failure on a run whose final result says `terminal_reason: "api_error"`, even where it holds no `api_error_status`, so a token the API refuses no longer lets the bench run on for hours with empty runs. - `task-bench`'s `--help` now says how far a bench of a commit against itself swings, in 19 cases of 20, with the default 5 bugs and 5 runs, and that a Gremlins run on a large project needs 16 GB of memory. +- When `task-bench` can't copy, read or write a file in the middle of a bench, it now names that file and still prints the table of the runs that finished, where 0.15.0 lost them all behind `could not write under `. ## 0.15.0 -- 2.52.0 From fa2ead69c9461a8b7eccb73201c69b256afc4cb0 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 23 Nov 2026 02:34:11 +0100 Subject: [PATCH 11/11] Record the comprehension check: paired ruling better at 4dd8b730 against 5b61b476, both seats better on every dimension --- docs/comprehension-history.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/docs/comprehension-history.md b/docs/comprehension-history.md index 5c0b3447..a03bd5f5 100644 --- a/docs/comprehension-history.md +++ b/docs/comprehension-history.md @@ -4339,3 +4339,36 @@ Inherited architect, would restructure first: - Locality: `bin/rule_hook/round_cap.py:28` `earlier_titles`: three callers count rounds from titles fetched three ways - Navigation, Shape: `README.md:234` "Packages under bin/": about 95 entries at one level, tool and shared packages side by side - Shape: `bin/larv_review/plan.py:1` module: decides whether a scoring run is due, not anything about the plan + +## 2026-11-23T01:34:06Z, PR #695 at 4dd8b730, against 5b61b476 + +Ruling: better + +| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall | +|---|---|---|---|---|---| +| Mid A | better | better | better | better | better | +| Inherited architect | better | better | better | better | better | + +Mid A, decided by: + +- Locality, Shape: `bin/task_bench/main.py:283` `benched`: six named steps over one Bench record, where the base did all of them in one body under a catch-all OSError several frames up +- Locality, Self-sufficiency: `bin/task_bench/main.py:199` `on_disk`: each file action names its own failure where it happens +- Locality, Self-sufficiency: `bin/task_bench/figures.py:53` `COLUMNS`: each column carries its heading, value and change kind, where the base tied three lists together by position +- Locality, Shape, Self-sufficiency: `bin/do_epic/main.py:378` `issue_move`: the move decision is a pure function with its table in the docstring; `How` says little on its own +- Navigation, Shape: `bin/do_epic/parking.py:18` `parked_through`: parking has a module of its own, though `parking.py` beside `parked.py` takes opening both +- Self-sufficiency, Locality: `bin/do_epic/parking.py:56` `news_after`: the two kinds of news are a pure function, not a nested branch +- Navigation, Shape: `bin/larv_review/scoring_due.py:1` module docstring: the name says what it decides, where `plan.py` clashed with the `plan` package +- Locality: `bin/larv_review/reviewer_header.py:83` `branch_summaries`: one shared function where two copies were +- Locality, Navigation: `bin/task_bench/main.py:468` `digested`: each stream is parsed once and carried in Result; `Side` lives in figures.py + +Inherited architect, decided by: + +- Locality, Self-sufficiency: `bin/do_epic/main.py:378` `issue_move`: the decision is pure, with its first-row-wins table in its docstring, and `handed_on` only matches on it +- Locality, Self-sufficiency: `bin/task_bench/figures.py:53` `COLUMNS`: one row per column, where `column not in (4, 6)` needed three places read together +- Navigation, Shape: `bin/do_epic/parking.py:18` `parked_through`: a parked chunk's symptom leads to a module named for it, and main.py drops from 699 to 563 lines +- Self-sufficiency, Locality: `bin/do_epic/parking.py:56` `news_after`: a pure function whose docstring lists the two kinds of news +- Navigation: `bin/larv_review/scoring_due.py:1` module docstring: the name no longer means two things +- Shape, Locality: `bin/task_bench/main.py:283` `benched`: a Bench record and named phases that each fit on a screen +- Navigation, Shape: `bin/do_epic/epic_run.py:21` `EpicRun`: the shared run record has one named place both main.py and parking.py import +- Locality: `bin/claude_code/entries.py:87` `json_objects`: stream parsing done once in one module +- Shape: `bin/task_bench/main.py:199` `on_disk`: sits beside hand-written try/except OSError blocks, two ways for one job; plant.py imports `Side` from the measuring module -- 2.52.0