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.