Release review of 0.16.0 #732
+3
-2
@@ -157,8 +157,9 @@
|
||||
!bin/subagent_rung/*.py
|
||||
!bin/task-bench
|
||||
!bin/task_bench/
|
||||
!bin/task_bench/*.py
|
||||
!bin/task_bench/gather-prompt.md
|
||||
!bin/task_bench/**/
|
||||
!bin/task_bench/**/*.py
|
||||
!bin/task_bench/figures/gather-prompt.md
|
||||
!bin/test_*.py
|
||||
!bin/text_files/
|
||||
!bin/text_files/*.py
|
||||
|
||||
+2
-1
@@ -8,7 +8,8 @@
|
||||
- task-bench leaves out of a fix a change Haiku makes to a Rust test module that stands in the file of the code it tests, and passes over a Rust mutant whose test modules it cannot tell apart.
|
||||
- loop-claude starts a chunk on a fresh session where its session's transcript is empty, in place of resuming a session claude cannot find, which failed three times and waited for the human.
|
||||
- larv-review's prose pass takes a second round after a fix that rewrites a claim a command or a source file can check, such as generated output, a number or a licence term.
|
||||
- `deploy-release --cut-patch <commits>` cuts the newest tag's next patch release, such as 0.15.2 after v0.15.1, holding only the commits named, for a fix that must ship before main's other unreleased work. It runs `ci.sh` on the patch, tags and pushes it, merges the tag back into main through a pull request, and moves `~/.claude` to it. Plain `--cut` now refuses a patch release, and a release review counts only for a release later than the last cut.
|
||||
- `deploy-release --cut-patch <commits>` cuts the newest tag's next patch release, such as 0.15.2 after v0.15.1, holding only the commits named, for a fix that must ship before main's other unreleased work. It runs `ci.sh` on the patch, tags and pushes it, merges the tag back into main through a pull request, and moves `~/.claude` to it. Plain `--cut` now refuses a patch release, and a release review counts only for the release its title names: `Release review of 0.16.0` reviews 0.16.0 and no other.
|
||||
- `deploy-release --cut` and `--cut-patch` keep each step, with its time in UTC, in a file under `~/.local/state/deploy-release/`, and `--cut-patch` stops `ci.sh` after 30 minutes, naming the log that holds its output.
|
||||
- `task-bench` plants bugs in Rust files too, from the mutants cargo-mutants catches, and tells Haiku the panic message `cargo test` prints.
|
||||
- `task-bench --tasks shipped-features` benches rebuilding features the project shipped: it takes each one's change out of the code, tells Haiku the tagline of its plan item, and checks the build with the tests that change holds. `--shipped <n>` sets how many it takes, and a feature whose branch landed by fast-forward starts after the latest earlier chunk that shipped an item or landed by a merge or a rebase, and is passed over where none comes before it or its branch merged the default branch into itself.
|
||||
- `task-bench` plants a Python mutant in a file whose lines end in CRLF, which it could not re-apply before, and a Go mutant there keeps applying.
|
||||
|
||||
@@ -196,7 +196,7 @@ Once the next release holds no item in `todo.md` and its release review has land
|
||||
bin/deploy-release --cut
|
||||
```
|
||||
|
||||
It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that through a pull request, since nobody can push to `main`. Then it tags the merged commit `v<version>`, pushes the tag, and moves this machine's `~/.claude` to it. Where a step fails it stops with the reason, and a rerun continues where it stopped. `deploy-release --help` lists the steps. Each other machine takes the release with Update.
|
||||
It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that through a pull request, since nobody can push to `main`. Then it tags the merged commit `v<version>`, pushes the tag, and moves this machine's `~/.claude` to it. Where a step fails it stops with the reason, and a rerun continues where it stopped. A cut keeps each step it finished, with its time in UTC, in a file of its own under `~/.local/state/deploy-release/`. `deploy-release --help` lists the steps. Each other machine takes the release with Update.
|
||||
|
||||
A fix that must ship before `main`'s other unreleased work goes out as a patch release, such as 0.15.2 after v0.15.1. File its item under that release, merge its chunk, then cut it at once with the commits the chunk merged, as a range or one commit. A range leaves out its first commit, as git's `..` does, so start it at the commit before the chunk's first:
|
||||
|
||||
@@ -243,15 +243,12 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
|
||||
|
||||
### Packages under `bin/`
|
||||
|
||||
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `agent_cycle/`, `atlassian/`, `branch_chunks/`, `chunk_driver/`, `claude_code/`, `command_lines/`, `forge/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, and a package's `doubles.py` holds the test doubles that other packages' tests use, so no module imports a `test_*` module of another package; `repo_checks/test_package_cycles.py` checks both. No Python file of the repo, `workflow-bench/`'s included, uses `mock.patch`, which `repo_checks/test_no_patched_globals.py` checks.
|
||||
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `agent_cycle/`, `atlassian/`, `branch_chunks/`, `chunk_driver/`, `claude_code/`, `command_lines/`, `forge/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, and a package's `doubles.py` holds the test doubles that other packages' tests use, so no module imports a `test_*` module of another package; `repo_checks/test_package_cycles.py` checks both. No Python file of the repo, `workflow-bench/`'s included, uses `mock.patch`, which `repo_checks/test_no_patched_globals.py` checks. Within each group below, the entries are in alphabetical order.
|
||||
|
||||
#### Driving chunks
|
||||
|
||||
- `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`. It builds the container's image inside a heavy slot.
|
||||
- `agent_cycle/` runs one cycle (`run.py`): a headless claude worker, then the judge of its transcript. It also holds the interrupt, the tmux window and the routing of the worker's rung. The entry point that runs the cycles supplies the prompts and file names of its own workflow (`worker_prompts.py`), and reads which items a worker took in. `loop_claude` and `do_epic` drive it; `agent_cycle` doesn't import either.
|
||||
- `atlassian/` holds what the Jira and Confluence backends share (`client.py`): one Atlassian account's credentials, the request both backends send, and each service's error messages. `jira.py` holds what every reader of Jira shares: a search read page by page, the key, fields, links and property of each issue it finds, checked for their shape, and the transition that finishes an issue, for `plan_store` and `do_epic`.
|
||||
- `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes`, `routing_figures` and `task_bench`. It imports `reading_cost`'s record path.
|
||||
- `chunk_driver/` holds what the entry points share. An entry point is a tool that drives chunks through `agent_cycle`: `loop_claude` and `do_epic` are the two. They share how a cycle starts (`cycle_start.py`) and closes (`chunk_run.py`), the claim on a checkout before a chunk starts in it (`claims.py`), the prompts every worker gets (`prompts.py`), and a checkout's premises, records and saved models (`project/`). It imports neither entry point, and `repo_checks` fails any package that imports one of the two. `agent_cycle` is the layer below it, and `repo_checks` fails `agent_cycle` where it imports `chunk_driver`, tests included.
|
||||
- `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`.
|
||||
- `deploy_release` imports `release_plan`'s `release_standing`.
|
||||
- `do_epic/` holds `do-epic`, the tool that drives one Jira epic:
|
||||
- `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `epic_run.py` holds what stays the same through one run of do-epic, such as its config, its Jira store and its paths, and starts the chunks that may start now.
|
||||
- `planning.py` settles, before the chunks start, where each open issue is worked, its scores and the order the issues start in, through `split.py`, `repo_pick.py`, `issue_scores.py` and `ranking.py`.
|
||||
@@ -267,29 +264,49 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
|
||||
- `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`.
|
||||
- `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, posts comments, moves a finished chunk's issue to done, and closes the epic.
|
||||
- `e2e/` holds `do-epic-e2e`.
|
||||
- `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), finds a pull request, lists the ready ones and reads its checks, once or until they settle (`pulls.py`), and reads a pull request's review state (`reviews.py`), for `chunk_preflight`, `chunk_pr`, `deploy_release`, `do_epic` and `larv_review`.
|
||||
- `git_cli/` runs git for every tool (`git_repo.py`), reads the git calls in a shell command (`git_command.py`), and keeps an epic's working branch level with the default branch (`epic_branch.py`).
|
||||
- `judge_replay` imports `agent_cycle`'s judge and verdicts, and `chunk_driver`'s premises, records and `ANSWER_DESTINATIONS`.
|
||||
- `loop_claude` runs `chunk-preflight` as a process of its own.
|
||||
- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, do-epic, both replay tools and `reviewer-merge-trials`' driver use it.
|
||||
- `loop_state/` holds where loop-claude and do-epic keep their files (`paths.py`), which `rung_replay` reads too.
|
||||
- `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy` and `adf_codec`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count.
|
||||
- `model_routing/` holds the shipped routing ladder (`routing-ladder.json`) and its steps (`ladder.py`), and reads a ladder from that file or a project's own (`ladder_file.py`), for loop-claude, `rule_hook`, `do_epic`, both replay tools and `subagent-rung`. It finds a project's config folder through `project_config`. It also holds the list prices, which `routing_figures` and `transcript_archive` read.
|
||||
- `notifier/` sends the human a DM through the notifier a project's config names, for `notify` and for loop-claude through `loop_effects`. Its backends are `mattermost.py` and `slack.py`.
|
||||
- `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry.
|
||||
|
||||
#### The plan, the records and releases
|
||||
|
||||
- `deploy_release` imports `release_plan`'s `release_standing`.
|
||||
- `plan/` is the plan's core, and imports neither `plan_store` nor `release_plan`. It holds an item and the items table's format (`todo_table.py`), releases (`release.py`), the ranking (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`), the paths an item's text names (`named_paths.py`), an item's `Touches:` prediction and where two overlap (`touches.py`), and `citations.py`, which holds `todo.md` and `docs/decisions.md` to each other. `goals_file.py` reads the goals file's sections, goals and goal weights, for the ranking and for `loop_claude`'s premises.
|
||||
- `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`). Every backend meets `plans.py`'s `PlanStore`: a markdown file (`todo_md.py`, which also ranks and checks the file in place, with its text edits in `markdown_edits.py`) or a Jira epic (`jira_epic.py`). `scoring.py` reads the goal weights that both backends rank by. `contract.py` holds the tests every backend that writes must pass; `jira_epic.py` doesn't yet, and its own tests stand in for Jira. `fakes.py` holds a plan in memory.
|
||||
- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them.
|
||||
- `record_store/` reads and writes a project's records, each through the store the project's config names (`stores.py`): a markdown file, a Confluence Cloud page (`confluence_page.py`), or, for the goals, a Jira epic's description (`jira_description.py`). `contract.py` holds the tests every backend must pass, and `fakes.py` a store in memory that the tests of other tools use.
|
||||
- `release_plan/` says which release is next and whether it is ready to cut (`release_standing.py`), from the plan, the changelog and the tags, picks the item the next chunk takes first (`next_chunk.py`), and marks each item that a ready pull request finishes (`awaiting_merge.py`), for `chunk_preflight` and `loop_claude`.
|
||||
- `repo_checks/` tests the repo itself.
|
||||
- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `notifier`, `atlassian` and `record_store`.
|
||||
- `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format.
|
||||
|
||||
#### Git, forges and Atlassian
|
||||
|
||||
- `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`. It builds the container's image inside a heavy slot.
|
||||
- `atlassian/` holds what the Jira and Confluence backends share (`client.py`): one Atlassian account's credentials, the request both backends send, and each service's error messages. `jira.py` holds what every reader of Jira shares: a search read page by page, the key, fields, links and property of each issue it finds, checked for their shape, and the transition that finishes an issue, for `plan_store` and `do_epic`.
|
||||
- `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), finds a pull request, lists the ready ones and reads its checks, once or until they settle (`pulls.py`), and reads a pull request's review state (`reviews.py`), for `chunk_preflight`, `chunk_pr`, `deploy_release`, `do_epic` and `larv_review`.
|
||||
- `git_cli/` runs git for every tool (`git_repo.py`), reads the git calls in a shell command (`git_command.py`), and keeps an epic's working branch level with the default branch (`epic_branch.py`).
|
||||
- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `notifier`, `atlassian` and `record_store`.
|
||||
|
||||
#### Measuring and replaying
|
||||
|
||||
- `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes`, `routing_figures` and `task_bench`. It imports `reading_cost`'s record path.
|
||||
- `judge_replay` imports `agent_cycle`'s judge and verdicts, and `chunk_driver`'s premises, records and `ANSWER_DESTINATIONS`.
|
||||
- `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls.
|
||||
- `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `agent_cycle`'s retry count and `chunk_driver`'s models file, and finds that file through `loop_state`'s paths. Its `archive.py` keeps each replay's runs and its report in a `replays/` folder of loop-claude's archive.
|
||||
- `task_bench/` holds `task-bench`, which plants bugs in a project's Go, PHP, Python, Rust, TypeScript and JavaScript files, or takes the project's bench features, its data sources or the features its history shipped, and has Haiku fix, build or add them in containers.
|
||||
- `test_env.py` serves the tests.
|
||||
- `task_bench/` holds `task-bench`, which has Haiku fix, build or add a task in containers: a bug planted in a project's Go, PHP, Python, Rust, TypeScript and JavaScript files (`bugs/`), or one of the project's bench features, its data sources or the features its history shipped (`features/`). `figures/` measures the runs and holds `task-bench gather`.
|
||||
|
||||
#### The shell, the machine and text
|
||||
|
||||
- `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`.
|
||||
- `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy` and `adf_codec`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count.
|
||||
- `text_files/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, reads the text piped into a command, stamps times in UTC, replaces a file in one step, private where it is new, and gzips a file beside its plain name, by which it reads it afterwards.
|
||||
- `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry.
|
||||
|
||||
#### Tests and tools of one file
|
||||
|
||||
- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them.
|
||||
- `repo_checks/` tests the repo itself.
|
||||
- `test_env.py` serves the tests.
|
||||
|
||||
## Test
|
||||
|
||||
|
||||
@@ -28,11 +28,14 @@ and prints that the release reviews and the cuts are the human's to call. It pri
|
||||
that todo.md has named at that cut or since, less a release its ## Renamed section marks renamed.
|
||||
Where nothing is cut, it is the earliest release todo.md has ever named, less those renamed, so a
|
||||
release whose items are all done still reads as next.
|
||||
Where the next release holds no item, it says so, naming it where todo.md named it since the cut:
|
||||
its release review due where changes are unreleased (the ## Unreleased entries, or else the
|
||||
commits since the cut) and no commit titled `Release review of <release>` followed the tag,
|
||||
finished and ready to cut once one did, and else to be planned first. On a branch with no tag,
|
||||
such a commit counts only where its <release> is after the version under the dated heading.
|
||||
Where the next release holds no item, it says so, and names the release where todo.md named it
|
||||
since the cut. Where no change is unreleased (the ## Unreleased entries, or else the commits
|
||||
since the cut), that release is to be planned first. Otherwise its release review is due, and
|
||||
once the review has landed the release is finished and ready to cut. The review has landed
|
||||
once a commit titled `Release review of <release>`, where <release> is exactly the next
|
||||
release, is on the default branch after the newest v* tag, or anywhere on a branch with no
|
||||
tag. The one exception: where todo.md named no next release since the cut, such a commit
|
||||
counts whichever release it names.
|
||||
Where todo.md files items under x.y.z or earlier, someone cut a release that still held them:
|
||||
they count as the next release, the earliest after x.y.z that todo.md names or has named
|
||||
since the cut, and a line says to move them there. Where there is no such release, it says todo.md files items under a release
|
||||
|
||||
@@ -705,7 +705,9 @@ class Plans(unittest.TestCase):
|
||||
def test_names_the_start_as_the_last_cut_where_nothing_is_cut(self):
|
||||
said = planned(EMPTY, LastCut(None, "", 4, [TODO]), "origin/main", BRANCH).why
|
||||
self.assertIn("release 0.2.0, the next after the start, since no release is cut yet,", said)
|
||||
self.assertIn("has landed yet.", said)
|
||||
self.assertIn("no commit titled `Release review of 0.2.0` has landed yet.", said)
|
||||
self.assertIn("`chunk-preflight --help`", said)
|
||||
self.assertIn("`Release review of <release>` has landed since the cut.", planned(EMPTY, LastCut("v0.1.0", "", 4, [EMPTY]), "origin/main", BRANCH).why, "todo.md named no release since the cut")
|
||||
self.assertIn("since the cut.", planned(EMPTY, LastCut(None, "## 0.1.0 - 2026-10-03\n", 4, [TODO]), "origin/main", BRANCH).why)
|
||||
|
||||
def test_finds_the_release_after_the_last_cut_finished_or_to_be_planned_where_the_plan_holds_no_item_for_it(self):
|
||||
@@ -722,7 +724,7 @@ class Plans(unittest.TestCase):
|
||||
)
|
||||
for todo, commits, todos, reviewed, fact, release in cases:
|
||||
with self.subTest(todo=todo, commits=commits, todos=todos, reviewed=reviewed):
|
||||
why = planned(todo, LastCut("v0.1.0", "", commits, todos, reviewed), "origin/main", BRANCH).why
|
||||
why = planned(todo, LastCut("v0.1.0", "", commits, todos, frozenset({(0, 2, 0)} if reviewed else ())), "origin/main", BRANCH).why
|
||||
self.assertIn(fact, why)
|
||||
self.assertIn(release, why)
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Run a patch's ci.sh with its output in a file the human can follow, and stop it where it runs too long."""
|
||||
import contextlib
|
||||
import os
|
||||
import pathlib
|
||||
import signal
|
||||
import subprocess
|
||||
import typing
|
||||
|
||||
from deploy_release.patch import Ci, CiRan
|
||||
from failure import Failure
|
||||
from deploy_release.trace import Say
|
||||
from forge.pulls import WAIT_SECONDS
|
||||
|
||||
# As long as a pull request's checks get, since they run the same ci.sh.
|
||||
CI_SECONDS = WAIT_SECONDS
|
||||
# How long a stopped ci.sh has to end on SIGINT before it is killed.
|
||||
GRACE_SECONDS = 10
|
||||
# How long docker has to remove a stopped ci.sh's container.
|
||||
REMOVE_SECONDS = 60
|
||||
# Where ci.sh reads the name to give its test container.
|
||||
CONTAINER = "CI_CONTAINER"
|
||||
|
||||
# Removes the container of a name, running or not; a Failure where it may still run.
|
||||
Remove = typing.Callable[[str], Failure | None]
|
||||
|
||||
|
||||
def ci_runner(log: pathlib.Path, seconds: float, say: Say, container: str, remove: Remove, grace: float = GRACE_SECONDS) -> Ci:
|
||||
"""Runs ci.sh in a worktree with its output in log, as it comes, and its test container named container. A Failure where it can't start, where log can't be written, or where it still runs after seconds. In that last case the runner stops ci.sh, each process ci.sh started, and that container."""
|
||||
def run(worktree: pathlib.Path) -> CiRan | Failure:
|
||||
say(f"ci.sh's output goes to {log}; it is stopped where it still runs after {lasting(seconds)}")
|
||||
try:
|
||||
with log.open("wb") as output:
|
||||
# In a session of its own, ci.sh and each process it starts share one process group, which `stopped` ends whole.
|
||||
process = subprocess.Popen(["sh", "ci.sh"], cwd=worktree, stdin=subprocess.DEVNULL, stdout=output, stderr=subprocess.STDOUT, start_new_session=True, env={**os.environ, CONTAINER: container})
|
||||
try:
|
||||
code = process.wait(timeout=seconds)
|
||||
except subprocess.TimeoutExpired:
|
||||
left = stopped(process, grace, container, remove)
|
||||
running = f", but its container {container} may still run: {left.reason}" if left else ""
|
||||
return Failure(f"ci.sh still ran after {lasting(seconds)} and was stopped{running}; {log} holds its output")
|
||||
except BaseException:
|
||||
# The cut is ending, as on Ctrl-C, which reaches only this process's group.
|
||||
stopped(process, grace, container, remove)
|
||||
raise
|
||||
return CiRan(code, log.read_text(encoding="utf-8", errors="replace"))
|
||||
except OSError as failure:
|
||||
return Failure(f"ci.sh could not run: {failure}")
|
||||
return run
|
||||
|
||||
|
||||
def stopped(process: subprocess.Popen[bytes], grace: float, container: str, remove: Remove) -> Failure | None:
|
||||
"""End process's whole group, SIGINT first, then SIGKILL once grace seconds have passed, and then its container; a Failure where the container may still run."""
|
||||
try:
|
||||
with contextlib.suppress(ProcessLookupError):
|
||||
os.killpg(process.pid, signal.SIGINT)
|
||||
with contextlib.suppress(subprocess.TimeoutExpired):
|
||||
process.wait(timeout=grace)
|
||||
finally:
|
||||
with contextlib.suppress(ProcessLookupError):
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.wait()
|
||||
# The daemon runs the container, outside the group, and no signal to ci.sh's docker CLI ends the tests in it. It is removed last, once nothing in the group can start it.
|
||||
left = remove(container)
|
||||
return left
|
||||
|
||||
|
||||
def removed_container(container: str, run: typing.Callable[..., subprocess.CompletedProcess[str]] = subprocess.run) -> Failure | None:
|
||||
"""Removes container with docker, running or not; None too where no such container exists."""
|
||||
argv = ["docker", "rm", "--force", container]
|
||||
try:
|
||||
ran = run(argv, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=REMOVE_SECONDS)
|
||||
except (OSError, subprocess.TimeoutExpired) as failure:
|
||||
return Failure(f"{' '.join(argv)} failed: {failure}")
|
||||
return Failure(f"{' '.join(argv)} failed: {ran.stderr.strip()}") if ran.returncode else None
|
||||
|
||||
|
||||
def lasting(seconds: float) -> str:
|
||||
count, unit = (seconds / 60, "minute") if seconds >= 60 else (seconds, "second")
|
||||
return f"{count:g} {unit}{'' if count == 1 else 's'}"
|
||||
+58
-39
@@ -3,9 +3,9 @@
|
||||
Each step first checks whether an earlier run did it, so a rerun continues where the last run stopped.
|
||||
"""
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import typing
|
||||
|
||||
@@ -17,17 +17,26 @@ from failure import Failure
|
||||
from plan_store.todo_md import FilePlan
|
||||
from record_store.stores import FileStore
|
||||
from forge.commands import forge_of, runner
|
||||
from plan.release import newest_tag, Release, tagged, UNRELEASED_HEADING, version
|
||||
from plan.release import newest_tag, Release, REVIEW_TITLE, tagged, UNRELEASED_HEADING, version
|
||||
from forge import pulls
|
||||
from deploy_release import release_pull
|
||||
from deploy_release.trace import Say
|
||||
from project_config import templates
|
||||
|
||||
|
||||
CUT_BODY = "Rename ## Unreleased in CHANGELOG.md to the version."
|
||||
|
||||
|
||||
def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None]) -> str | Failure:
|
||||
"""What the cut did, as the tool prints it; a Failure with git's, the forge's or the tool's reason where a step stopped."""
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Ready:
|
||||
"""The next release, which holds no item in todo.md while changes are unreleased."""
|
||||
release: Release
|
||||
# Whether its release review has landed.
|
||||
reviewed: bool
|
||||
|
||||
|
||||
def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None], say: Say) -> str | Failure:
|
||||
"""What the cut did, as the tool prints it; a Failure with git's, the forge's or the tool's reason where a step stopped. say takes each step as it finishes."""
|
||||
if isinstance(same := same_origin(clone, checkout), Failure):
|
||||
return same
|
||||
if isinstance(fetched := git("fetch", "--quiet", "--tags", "origin", cwd=clone), Failure):
|
||||
@@ -37,17 +46,20 @@ def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None]) -> str
|
||||
ref = default_ref(cwd=clone)
|
||||
if isinstance(ref, Failure):
|
||||
return ref
|
||||
release = ready_release(clone, ref)
|
||||
if isinstance(release, Failure):
|
||||
return release
|
||||
named = version(release)
|
||||
if isinstance(patched := patch_refusal(clone, ref, release), Failure):
|
||||
ready = ready_release(clone, ref)
|
||||
if isinstance(ready, Failure):
|
||||
return ready
|
||||
named = version(ready.release)
|
||||
# The patch refusal comes before the review's: a patch takes no release review, so "hasn't landed" would send the human the wrong way.
|
||||
if isinstance(patched := patch_refusal(clone, ref, ready.release), Failure):
|
||||
return patched
|
||||
if not ready.reviewed:
|
||||
return Failure(f"the release review of {named} hasn't landed: {ref} holds no commit titled `{REVIEW_TITLE}{named}` after the newest tag. `chunk-preflight --help` says which commit counts.")
|
||||
title, tag, branch = f"Cut release {named}", f"v{named}", f"release-{named}"
|
||||
merged = commit_titled(title, ref, clone)
|
||||
if merged is None:
|
||||
build = lambda replacing: push_cut_commit(clone, ref, branch, named, title, replacing)
|
||||
landed = land(clone, ref, branch, title, CUT_BODY, build, sleep)
|
||||
landed = land(clone, ref, branch, title, CUT_BODY, build, sleep, say)
|
||||
if isinstance(landed, Failure):
|
||||
return landed
|
||||
if isinstance(fetched := git("fetch", "--quiet", "origin", cwd=clone), Failure):
|
||||
@@ -59,13 +71,13 @@ def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None]) -> str
|
||||
return merged
|
||||
if isinstance(made := git("tag", "--annotate", "--message", title, tag, merged, cwd=clone), Failure):
|
||||
return made
|
||||
said(f"tagged {merged[:12]} {tag}")
|
||||
say(f"tagged {merged[:12]} {tag}")
|
||||
if isinstance(pushed := git("push", "--quiet", "origin", f"refs/tags/{tag}", cwd=clone), Failure):
|
||||
# Until a rerun, chunk-preflight would read a tag only the clone holds as cut.
|
||||
git("tag", "--delete", tag, cwd=clone)
|
||||
return pushed
|
||||
said(f"pushed the tag {tag}")
|
||||
delete_release_branch(clone, branch)
|
||||
say(f"pushed the tag {tag}")
|
||||
delete_release_branch(clone, branch, say)
|
||||
moved = deploy(checkout)
|
||||
if isinstance(moved, Failure):
|
||||
return Failure(f"cut and pushed {tag}, but moving {checkout} stopped: {moved.reason}. Fix that, then run a bare deploy-release.")
|
||||
@@ -83,21 +95,16 @@ def patch_refusal(clone: str, ref: str, release: Release) -> Failure | None:
|
||||
return None
|
||||
|
||||
|
||||
def said(step: str) -> None:
|
||||
"""Say on stderr that step finished, so the human sees how far the cut got before the changelog fills the screen."""
|
||||
print(f"deploy-release: {step}", file=sys.stderr)
|
||||
|
||||
|
||||
def delete_release_branch(clone: str, branch: str) -> None:
|
||||
def delete_release_branch(clone: str, branch: str, say: Say) -> None:
|
||||
"""Delete origin's merged branch, where it is still there; only warn where that fails, since the release is cut by then."""
|
||||
listed = branch_head(branch, clone)
|
||||
if listed is None:
|
||||
return
|
||||
deleted = listed if isinstance(listed, Failure) else git("push", "--quiet", "origin", "--delete", f"refs/heads/{branch}", cwd=clone)
|
||||
if isinstance(deleted, Failure):
|
||||
said(f"warning: the branch {branch} stays on origin: {deleted.reason}")
|
||||
say(f"warning: the branch {branch} stays on origin: {deleted.reason}")
|
||||
else:
|
||||
said(f"deleted the branch {branch} on origin")
|
||||
say(f"deleted the branch {branch} on origin")
|
||||
|
||||
|
||||
def drop_unpushed_cut_tags(clone: str) -> Failure | None:
|
||||
@@ -134,23 +141,23 @@ def clone_plan(clone: str) -> FilePlan:
|
||||
return FilePlan(pathlib.Path(clone, "todo.md"), "todo.md", goals, decisions, history, DEFAULT_FLOOR)
|
||||
|
||||
|
||||
def ready_release(clone: str, ref: str, review: bool = True) -> Release | Failure:
|
||||
"""The next release, as chunk-preflight works it out, where it is ready to cut: it holds no item in todo.md, its release review has landed, unless review is False, and changes are unreleased."""
|
||||
def ready_release(clone: str, ref: str) -> Ready | Failure:
|
||||
"""The next release, as chunk-preflight works it out, where it holds no item in todo.md and changes are unreleased, with whether its release review has landed: the caller decides whether the cut needs one."""
|
||||
# No project's config names the clone, so its changelog is read at the fixed path, on ref like the plan, and its titles as they stand.
|
||||
plan = default_plan(clone, ref, clone_plan(clone), FileStore(pathlib.Path(clone, "CHANGELOG.md"), "CHANGELOG.md"), templates.BARE)
|
||||
if isinstance(plan.plan, Failure):
|
||||
return Failure(f"todo.md on {ref} cannot be read: {plan.plan.reason}")
|
||||
match chunk_item(plan.plan.items, plan.cut):
|
||||
case ReadyToCut(release=release) if release is not None:
|
||||
return release
|
||||
return Ready(release, reviewed=True)
|
||||
case ReadyToCut():
|
||||
return Failure("todo.md names no release after the last one cut")
|
||||
case Next(release=release) if release is not None:
|
||||
return Failure(f"release {version(release)} still holds items in todo.md")
|
||||
case ReviewDue(release=release) if not review and release is not None:
|
||||
return release
|
||||
case ReviewDue(release=release):
|
||||
return Failure(f"the release review of {version(release) if release else 'the next release'} hasn't landed")
|
||||
case ReviewDue(release=release) if release is not None:
|
||||
return Ready(release, reviewed=False)
|
||||
case ReviewDue():
|
||||
return Failure("the release review of the next release hasn't landed")
|
||||
case Unplanned():
|
||||
return Failure("every change is released already: nothing has landed since the last release cut")
|
||||
case Cut(release=release):
|
||||
@@ -170,7 +177,7 @@ def commit_titled(title: str, ref: str, clone: str) -> str | None | Failure:
|
||||
return next((line.split(" ", 1)[0] for line in log.splitlines() if line.split(" ", 1)[1:] == [title]), None)
|
||||
|
||||
|
||||
def land(clone: str, ref: str, branch: str, title: str, body: str, build: typing.Callable[[str | None], Failure | None], sleep: typing.Callable[[float], None]) -> Failure | None:
|
||||
def land(clone: str, ref: str, branch: str, title: str, body: str, build: typing.Callable[[str | None], Failure | None], sleep: typing.Callable[[float], None], say: Say) -> Failure | None:
|
||||
"""Push branch and open its pull request, titled title with body, where an earlier run hasn't; then wait for its checks and merge it.
|
||||
|
||||
build pushes branch's commit, made on ref. It takes the commit origin's branch points at, which the push replaces, or None where origin has no such branch yet."""
|
||||
@@ -188,7 +195,7 @@ def land(clone: str, ref: str, branch: str, title: str, body: str, build: typing
|
||||
# Where main moved on, such as to fix a failed check, the branch could no longer merge fast-forward, so it is rebuilt on main.
|
||||
if isinstance(pushed := build(head), Failure):
|
||||
return pushed
|
||||
said(f"pushed the branch {branch}")
|
||||
say(f"pushed the branch {branch}")
|
||||
head = branch_head(branch, clone) or Failure(f"pushed {branch}, but origin holds no such branch")
|
||||
if isinstance(head, Failure):
|
||||
return head
|
||||
@@ -198,19 +205,19 @@ def land(clone: str, ref: str, branch: str, title: str, body: str, build: typing
|
||||
return created
|
||||
number = pulls.open_pull(on, branch, head, run) or Failure(f"opened a pull request for {branch}, but the forge lists none from origin at {head[:12]}")
|
||||
if isinstance(number, str):
|
||||
said(f"opened pull request {number}")
|
||||
say(f"opened pull request {number}")
|
||||
if isinstance(number, Failure):
|
||||
return number
|
||||
required = pulls.required_checks(on, base, run)
|
||||
if isinstance(required, Failure):
|
||||
return required
|
||||
said(f"waiting for the checks of pull request {number}" + (f"; {base} requires {', '.join(sorted(required))}" if required else ""))
|
||||
say(f"waiting for the checks of pull request {number}" + (f"; {base} requires {', '.join(sorted(required))}" if required else ""))
|
||||
if isinstance(passed := pulls.checks_passed(on, number, head, required, run, sleep), Failure):
|
||||
return passed
|
||||
said(f"the checks of pull request {number} passed")
|
||||
say(f"the checks of pull request {number} passed")
|
||||
if isinstance(merged := release_pull.merge(on, number, head, run), Failure):
|
||||
return merged
|
||||
said(f"merged pull request {number}")
|
||||
say(f"merged pull request {number}")
|
||||
return None
|
||||
|
||||
|
||||
@@ -232,16 +239,28 @@ def push_cut_commit(clone: str, ref: str, branch: str, named: str, title: str, r
|
||||
with scratch_worktree(clone, ref) as worktree:
|
||||
if isinstance(worktree, Failure):
|
||||
return worktree
|
||||
changelog = worktree / "CHANGELOG.md"
|
||||
renamed, count = UNRELEASED_HEADING.subn(f"## {named}", changelog.read_text() if changelog.exists() else "", count=1)
|
||||
if not count:
|
||||
return Failure(f"CHANGELOG.md on {ref} has no ## Unreleased section to rename")
|
||||
changelog.write_text(renamed)
|
||||
def renamed(changelog: str | None) -> str | Failure:
|
||||
text, count = UNRELEASED_HEADING.subn(f"## {named}", changelog or "", count=1)
|
||||
return text if count else Failure(f"CHANGELOG.md on {ref} has no ## Unreleased section to rename")
|
||||
if isinstance(written := rewritten(worktree / "CHANGELOG.md", f"rename ## Unreleased to ## {named} in the cut's worktree", "Nothing is pushed.", renamed), Failure):
|
||||
return written
|
||||
if isinstance(committed := git("commit", "--quiet", "-am", title, cwd=str(worktree)), Failure):
|
||||
return committed
|
||||
return push_branch(worktree, branch, replacing)
|
||||
|
||||
|
||||
def rewritten(file: pathlib.Path, doing: str, outcome: str, rewrite: typing.Callable[[str | None], str | Failure]) -> Failure | None:
|
||||
"""Replace file's text with what rewrite makes of it, or of None where there is no such file. Where rewrite gives a Failure, return it and leave the file. Where the file can't be read or written, the Failure names doing, the step that stopped, then the file, and ends with outcome, a sentence on where that leaves the run."""
|
||||
try:
|
||||
text = rewrite(file.read_text(encoding="utf-8") if file.exists() else None)
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
file.write_text(text, encoding="utf-8")
|
||||
except (OSError, UnicodeError) as failure:
|
||||
return Failure(f"could not {doing}: {failure}" + ("" if str(file) in str(failure) else f" ({file})") + f". {outcome}")
|
||||
return None
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def scratch_worktree(clone: str, at: str) -> typing.Iterator[pathlib.Path | Failure]:
|
||||
"""A worktree of clone, detached at at, in a folder of its own that is removed afterwards, so the clone's checkout stays as it is; a Failure where git can't add it."""
|
||||
|
||||
@@ -18,7 +18,7 @@ memory, stay as they are.
|
||||
|
||||
--cut runs in the development clone, and refuses where that clone's origin isn't <checkout>'s. It cuts the next release, as chunk-preflight works it out, and
|
||||
refuses without changing anything, unless that release holds no item in todo.md, its release review has
|
||||
landed and changes are unreleased. The release names the version; the tool doesn't choose one. It also refuses a
|
||||
landed, as chunk-preflight --help counts one, and changes are unreleased. The release names the version; the tool doesn't choose one. It also refuses a
|
||||
release that is a patch of the newest tag, such as 0.15.2 after v0.15.1, since it would ship all of main: cut that
|
||||
with --cut-patch.
|
||||
1. On a fresh origin/main, it renames ## Unreleased in CHANGELOG.md to the version, commits that
|
||||
@@ -33,6 +33,9 @@ with --cut-patch.
|
||||
deletes the branch on origin, then moves <checkout> to the tag as above. A failed delete only warns.
|
||||
It says on stderr as each step finishes, and ends stdout, after the changelog, with the line
|
||||
`Done: v<version> is cut and pushed, and <checkout> is on it.`
|
||||
It keeps each of those lines, with its time in UTC, in the run's trace: a file of its own under
|
||||
$XDG_STATE_HOME/deploy-release (default ~/.local/state/deploy-release), named by when the run began. --cut-patch does too.
|
||||
Where Ctrl-C or an unexpected fault ends the run, the trace ends with a line that starts `stopped:`.
|
||||
Where a step fails it stops, exit 1, with git's or the forge's reason, and leaves the pull request
|
||||
and the branch as they are. A rerun continues: it takes the branch's open pull request and a cut
|
||||
commit already merged, and drops a cut tag an earlier run made but never pushed. Once the tag is pushed, the release is cut: where only the
|
||||
@@ -51,7 +54,8 @@ doesn't hold, and on a GitHub origin, whose rebase merge would drop the tag from
|
||||
2. In a worktree of its own at the tag, it applies each commit's changes, except to CHANGELOG.md, todo.md,
|
||||
docs/comprehension-history.md and docs/reading-cost.md, heads CHANGELOG.md with the release's section, and commits that
|
||||
titled `Cut release <version>`. Where a commit doesn't apply, it stops, names it, and says how to cut the patch by hand.
|
||||
3. It runs ci.sh on that commit, and stops where it fails, before anything is tagged.
|
||||
3. It runs ci.sh on that commit and names on stderr the file, beside the run's trace, that takes ci.sh's output. It
|
||||
stops where ci.sh fails or still runs after 30 minutes, before anything is tagged.
|
||||
4. It tags the commit v<version>, annotated `Cut release <version>`, and pushes only the tag.
|
||||
5. On a fresh origin/main it merges the tag keeping main's files, moves the release's entries from ## Unreleased to a
|
||||
## <version> section below it, commits that titled `Merge release <version> into main`, and lands it through the branch
|
||||
@@ -62,13 +66,16 @@ pull request. Once the merge-back has merged, the release is cut: where only the
|
||||
"""
|
||||
import os
|
||||
import pathlib
|
||||
import shlex
|
||||
import sys
|
||||
import time
|
||||
|
||||
from deploy_release.ci_script import ci_runner, CI_SECONDS, removed_container
|
||||
from deploy_release.cut import cut
|
||||
from deploy_release.patch import cut_patch
|
||||
from deploy_release.deploy import deploy
|
||||
from failure import Failure
|
||||
from deploy_release import trace
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
@@ -82,12 +89,33 @@ def main(argv: list[str]) -> int:
|
||||
print("deploy-release: usage: deploy-release [--cut | --cut-patch <commits>] [<checkout>]", file=sys.stderr)
|
||||
return 1
|
||||
checkout = rest[0] if rest else str(pathlib.Path.home() / ".claude")
|
||||
if commits is not None:
|
||||
moved = cut_patch(os.getcwd(), checkout, commits, time.sleep)
|
||||
else:
|
||||
moved = cut(os.getcwd(), checkout, time.sleep) if cutting else deploy(checkout)
|
||||
if not cutting and commits is None:
|
||||
moved = deploy(checkout)
|
||||
if isinstance(moved, Failure):
|
||||
print(f"deploy-release: {moved.reason}", file=sys.stderr)
|
||||
return 1
|
||||
print(moved)
|
||||
return 0
|
||||
clone, now = os.getcwd(), time.time
|
||||
folder, name = trace.trace_folder(os.environ, pathlib.Path.home()), trace.run_name(now(), os.getpid())
|
||||
begun = trace.started(folder, name, f"deploy-release {shlex.join([*argv[:2 if patching else 1], checkout])} in {clone}", now)
|
||||
if isinstance(begun, Failure):
|
||||
print(f"deploy-release: warning: {begun.reason}", file=sys.stderr)
|
||||
file = None if isinstance(begun, Failure) else begun
|
||||
say = trace.saying(file, now, sys.stderr)
|
||||
try:
|
||||
if commits is not None:
|
||||
moved = cut_patch(clone, checkout, commits, time.sleep, say, ci_runner(folder / f"{name}-ci.log", CI_SECONDS, say, f"deploy-release-ci-{name}", removed_container))
|
||||
else:
|
||||
moved = cut(clone, checkout, time.sleep, say)
|
||||
except BaseException as stopped:
|
||||
# Ctrl-C or a fault nobody foresaw: its traceback reaches only the terminal, so the trace says the run ended here.
|
||||
trace.kept(file, f"stopped: {stopped!r}", now, sys.stderr)
|
||||
raise
|
||||
if isinstance(moved, Failure):
|
||||
print(f"deploy-release: {moved.reason}", file=sys.stderr)
|
||||
say(moved.reason)
|
||||
return 1
|
||||
print(moved)
|
||||
# The ending is on stdout already, so only the trace takes it.
|
||||
trace.kept(file, moved.splitlines()[-1], now, sys.stderr)
|
||||
return 0
|
||||
|
||||
+67
-34
@@ -5,15 +5,15 @@ A rerun takes the tag an earlier run pushed, once it checks the tag lists the sa
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
import typing
|
||||
|
||||
from git_cli.git_repo import default_ref, git
|
||||
from deploy_release.cut import delete_release_branch, drop_unpushed_cut_tags, land, push_branch, ready_release, said, same_origin, scratch_worktree
|
||||
from deploy_release.cut import delete_release_branch, drop_unpushed_cut_tags, land, push_branch, ready_release, rewritten, same_origin, scratch_worktree
|
||||
from deploy_release.deploy import deploy
|
||||
from failure import Failure
|
||||
from forge.commands import forge_of
|
||||
from plan.release import newest_tag, tagged, UNRELEASED_TITLE, version
|
||||
from deploy_release.trace import Say
|
||||
from text_files.markdown_text import section
|
||||
|
||||
# The files a patch leaves as the tag holds them: the changelog, whose section the cut writes itself; the plan; and the records each chunk appends to, which seldom apply on an older tag.
|
||||
@@ -36,29 +36,42 @@ class Patch:
|
||||
entries: list[str]
|
||||
|
||||
|
||||
def cut_patch(clone: str, checkout: str, commits: str, sleep: typing.Callable[[float], None]) -> str | Failure:
|
||||
"""What the patch cut did, as the tool prints it; a Failure with git's, the forge's, ci.sh's or the tool's reason where a step stopped. commits is a range as git log reads it, or one commit."""
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class CiRan:
|
||||
code: int
|
||||
# stdout and stderr, as ci.sh interleaved them.
|
||||
output: str
|
||||
|
||||
|
||||
class Ci(typing.Protocol):
|
||||
"""Runs the ci.sh that worktree holds, as ci_script.ci_runner's does: a Failure where it could not start or was stopped."""
|
||||
|
||||
def __call__(self, worktree: pathlib.Path) -> CiRan | Failure: ...
|
||||
|
||||
|
||||
def cut_patch(clone: str, checkout: str, commits: str, sleep: typing.Callable[[float], None], say: Say, ci: Ci) -> str | Failure:
|
||||
"""What the patch cut did, as the tool prints it; a Failure with git's, the forge's, ci.sh's or the tool's reason where a step stopped. commits is a range as git log reads it, or one commit. say takes each step as it finishes, and ci runs the patch's ci.sh."""
|
||||
patch = planned(clone, checkout, commits)
|
||||
if isinstance(patch, Failure):
|
||||
return patch
|
||||
for commit in patch.commits:
|
||||
subject = git("log", "-1", "--format=%h %s", commit, cwd=clone)
|
||||
said(f"ships {'' if isinstance(subject, Failure) else subject.strip()}")
|
||||
say(f"ships {'' if isinstance(subject, Failure) else subject.strip()}")
|
||||
tag, branch = f"v{patch.named}", f"release-{patch.named}"
|
||||
pushed = git("ls-remote", "--tags", "--refs", "origin", f"refs/tags/{tag}", cwd=clone)
|
||||
if isinstance(pushed, Failure):
|
||||
return pushed
|
||||
made = tagged_entries(clone, patch) if pushed.strip() else tag_patch(clone, patch)
|
||||
made = tagged_entries(clone, patch) if pushed.strip() else tag_patch(clone, patch, say, ci)
|
||||
if isinstance(made, Failure):
|
||||
return made
|
||||
build = lambda replacing: push_merge_back(clone, patch, replacing)
|
||||
if isinstance(landed := land(clone, patch.ref, branch, f"Merge release {patch.named} into main", MERGE_BACK_BODY, build, sleep), Failure):
|
||||
if isinstance(landed := land(clone, patch.ref, branch, f"Merge release {patch.named} into main", MERGE_BACK_BODY, build, sleep, say), Failure):
|
||||
return landed
|
||||
if isinstance(fetched := git("fetch", "--quiet", "origin", cwd=clone), Failure):
|
||||
return fetched
|
||||
if isinstance(git("merge-base", "--is-ancestor", tag, patch.ref, cwd=clone), Failure):
|
||||
return Failure(f"the merge-back merged, but {patch.ref} doesn't hold {tag}, so the next cut can't read it as cut")
|
||||
delete_release_branch(clone, branch)
|
||||
delete_release_branch(clone, branch, say)
|
||||
moved = deploy(checkout)
|
||||
if isinstance(moved, Failure):
|
||||
return Failure(f"cut and pushed {tag}, but moving {checkout} stopped: {moved.reason}. Fix that, then run a bare deploy-release.")
|
||||
@@ -88,12 +101,12 @@ def planned(clone: str, checkout: str, commits: str) -> Patch | Failure:
|
||||
if base is None or cut is None:
|
||||
return Failure(f"{ref}'s newest tag, {base}, names no release x.y.z to cut a patch of" if base else f"{ref} holds no v* tag to cut a patch of")
|
||||
named = version((cut[0], cut[1], cut[2] + 1))
|
||||
# A patch holds only fixes, and the release review reads the whole project, so a patch is cut without one.
|
||||
release = ready_release(clone, ref, review=False)
|
||||
if isinstance(release, Failure):
|
||||
return release
|
||||
if version(release) != named:
|
||||
return Failure(f"the next release in todo.md is {version(release)}, not {named}, the patch of {base}: file the fix under {named}")
|
||||
ready = ready_release(clone, ref)
|
||||
if isinstance(ready, Failure):
|
||||
return ready
|
||||
# A patch holds only fixes, and the release review reads the whole project, so a patch is cut whether or not ready.reviewed.
|
||||
if version(ready.release) != named:
|
||||
return Failure(f"the next release in todo.md is {version(ready.release)}, not {named}, the patch of {base}: file the fix under {named}")
|
||||
picked = patch_commits(clone, ref, base, commits)
|
||||
if isinstance(picked, Failure):
|
||||
return picked
|
||||
@@ -118,7 +131,7 @@ def patch_commits(clone: str, ref: str, base: str, commits: str) -> list[str] |
|
||||
|
||||
|
||||
def changelog_entries(clone: str, ref: str, commits: list[str]) -> list[str] | Failure:
|
||||
"""The entries under ref's ## Unreleased in CHANGELOG.md that commits added, in the order ref lists them; a Failure where they added none."""
|
||||
"""The entries under ref's ## Unreleased in CHANGELOG.md that commits added, in the order ref lists them; a Failure where they added none, or where ref's CHANGELOG.md has no such section, which the merge-back moves the entries out of."""
|
||||
added: set[str] = set()
|
||||
for commit in commits:
|
||||
diff = git("diff", f"{commit}^", commit, "--", "CHANGELOG.md", cwd=clone)
|
||||
@@ -128,7 +141,11 @@ def changelog_entries(clone: str, ref: str, commits: list[str]) -> list[str] | F
|
||||
changelog = git("show", f"{ref}:CHANGELOG.md", cwd=clone)
|
||||
if isinstance(changelog, Failure):
|
||||
return changelog
|
||||
entries = [line for line in section(changelog, UNRELEASED_TITLE) or [] if line in added]
|
||||
unreleased = section(changelog, UNRELEASED_TITLE)
|
||||
# The merge-back finds the heading with unreleased_start only after the tag is pushed, so check it here first.
|
||||
if unreleased is None or unreleased_start(changelog.split("\n")) is None:
|
||||
return Failure(f"CHANGELOG.md on {ref} has no ## Unreleased section, which the patch's entries come from: add it on {ref}")
|
||||
entries = [line for line in unreleased if line in added]
|
||||
return entries or Failure(f"the commits add no entry under ## Unreleased in CHANGELOG.md on {ref}: name the commit that finished the fix's item too")
|
||||
|
||||
|
||||
@@ -143,7 +160,7 @@ def tagged_entries(clone: str, patch: Patch) -> Failure | None:
|
||||
return None
|
||||
|
||||
|
||||
def tag_patch(clone: str, patch: Patch) -> Failure | None:
|
||||
def tag_patch(clone: str, patch: Patch, say: Say, ci: Ci) -> Failure | None:
|
||||
"""In a worktree at the base tag, apply patch's commits but for LEFT_AS_TAGGED, head CHANGELOG.md with its section, commit that titled `Cut release <version>`, test it with ci.sh, then tag it and push the tag."""
|
||||
title, tag = f"Cut release {patch.named}", f"v{patch.named}"
|
||||
with scratch_worktree(clone, patch.base) as worktree:
|
||||
@@ -152,21 +169,22 @@ def tag_patch(clone: str, patch: Patch) -> Failure | None:
|
||||
for commit in patch.commits:
|
||||
if isinstance(applied := apply_commit(clone, worktree, commit, patch), Failure):
|
||||
return applied
|
||||
changelog = worktree / "CHANGELOG.md"
|
||||
changelog.write_text(headed(changelog.read_text() if changelog.exists() else "# Changelog\n", patch.entries, patch.named))
|
||||
head = lambda changelog: headed("# Changelog\n" if changelog is None else changelog, patch.entries, patch.named)
|
||||
if isinstance(written := rewritten(worktree / "CHANGELOG.md", f"head CHANGELOG.md with ## {patch.named} in the patch's worktree", "Nothing is tagged.", head), Failure):
|
||||
return written
|
||||
if isinstance(committed := git("commit", "--quiet", "--all", "--message", title, cwd=str(worktree)), Failure):
|
||||
return committed
|
||||
said(f"applied the commits on {patch.base}; testing them with ci.sh")
|
||||
if isinstance(tested := run_ci(worktree, patch.ref), Failure):
|
||||
say(f"applied the commits on {patch.base}; testing them with ci.sh")
|
||||
if isinstance(tested := run_ci(worktree, patch.ref, ci), Failure):
|
||||
return tested
|
||||
said("ci.sh passed")
|
||||
say("ci.sh passed")
|
||||
if isinstance(made := git("tag", "--annotate", "--message", title, tag, "HEAD", cwd=str(worktree)), Failure):
|
||||
return made
|
||||
if isinstance(pushed := git("push", "--quiet", "origin", f"refs/tags/{tag}", cwd=clone), Failure):
|
||||
# Until a rerun, chunk-preflight would read a tag only the clone holds as cut.
|
||||
git("tag", "--delete", tag, cwd=clone)
|
||||
return pushed
|
||||
said(f"pushed the tag {tag}")
|
||||
say(f"pushed the tag {tag}")
|
||||
return None
|
||||
|
||||
|
||||
@@ -187,7 +205,8 @@ def apply_commit(clone: str, worktree: pathlib.Path, commit: str, patch: Patch)
|
||||
if not diff:
|
||||
return None
|
||||
patch_file = worktree.parent / "commit.patch"
|
||||
patch_file.write_text(diff)
|
||||
if isinstance(written := rewritten(patch_file, f"write {commit[:12]}'s changes to a file to apply", "Nothing is tagged.", lambda _: diff), Failure):
|
||||
return written
|
||||
if isinstance(applied := git("apply", "--3way", "--index", str(patch_file), cwd=str(worktree)), Failure):
|
||||
subject = git("log", "-1", "--format=%s", commit, cwd=clone)
|
||||
return Failure(
|
||||
@@ -199,14 +218,16 @@ def apply_commit(clone: str, worktree: pathlib.Path, commit: str, patch: Patch)
|
||||
return None
|
||||
|
||||
|
||||
def run_ci(worktree: pathlib.Path, ref: str) -> Failure | None:
|
||||
"""None where the patch's ci.sh passes on its committed head; a Failure with the end of its output where it fails."""
|
||||
def run_ci(worktree: pathlib.Path, ref: str, ci: Ci) -> Failure | None:
|
||||
"""None where the patch's ci.sh passes on its committed head, run by ci; a Failure with the end of its output where it fails, or with ci's reason where it could not run or was stopped."""
|
||||
if not (worktree / "ci.sh").exists():
|
||||
return Failure("the patch holds no ci.sh to test it with")
|
||||
ran = subprocess.run(["sh", "ci.sh"], capture_output=True, cwd=worktree, text=True, errors="replace")
|
||||
if ran.returncode == 0:
|
||||
ran = ci(worktree)
|
||||
if isinstance(ran, Failure):
|
||||
return Failure(f"{ran.reason}. Nothing is tagged: fix that and rerun.")
|
||||
if ran.code == 0:
|
||||
return None
|
||||
tail = "\n".join((ran.stdout + ran.stderr).strip().splitlines()[-30:])
|
||||
tail = "\n".join(ran.output.strip().splitlines()[-30:])
|
||||
return Failure(f"ci.sh failed on the patch, so nothing is tagged. Fix it on {ref}, then rerun naming the fix's commits too. The end of its output:\n{tail}")
|
||||
|
||||
|
||||
@@ -217,19 +238,31 @@ def push_merge_back(clone: str, patch: Patch, replacing: str | None) -> Failure
|
||||
return worktree
|
||||
if isinstance(merged := git("merge", "--quiet", "--no-ff", "--no-commit", "--strategy", "ours", f"v{patch.named}", cwd=str(worktree)), Failure):
|
||||
return merged
|
||||
changelog = worktree / "CHANGELOG.md"
|
||||
changelog.write_text(moved_entries(changelog.read_text(), patch.entries, patch.named))
|
||||
# The tag is pushed by now, so each stop here says that a rerun with the same commits takes it and builds only this merge-back again.
|
||||
rerun = f"v{patch.named} is pushed, and a rerun with the same commits merges it back."
|
||||
def move(changelog: str | None) -> str | Failure:
|
||||
moved = moved_entries(changelog or "", patch.entries, patch.named, patch.ref)
|
||||
return Failure(f"{moved.reason}: add the heading there. {rerun}") if isinstance(moved, Failure) else moved
|
||||
if isinstance(written := rewritten(worktree / "CHANGELOG.md", f"move the entries of {patch.named} out of ## Unreleased in the merge-back's worktree", rerun, move), Failure):
|
||||
return written
|
||||
if isinstance(committed := git("commit", "--quiet", "--all", "--message", f"Merge release {patch.named} into main", cwd=str(worktree)), Failure):
|
||||
return committed
|
||||
return push_branch(worktree, f"release-{patch.named}", replacing)
|
||||
|
||||
|
||||
def moved_entries(changelog: str, entries: list[str], named: str) -> str:
|
||||
"""changelog with entries taken out of its ## Unreleased section and put in a ## named section right below that section."""
|
||||
def moved_entries(changelog: str, entries: list[str], named: str, ref: str) -> str | Failure:
|
||||
"""changelog, as ref holds it, with entries taken out of its ## Unreleased section and put in a ## named section right below that section; a Failure where it has no such heading."""
|
||||
lines = changelog.split("\n")
|
||||
start = next(index for index, line in enumerate(lines) if re.fullmatch(f"## {UNRELEASED_TITLE}", line))
|
||||
start = unreleased_start(lines)
|
||||
if start is None:
|
||||
return Failure(f"CHANGELOG.md on {ref} has no ## Unreleased heading to move the entries of {named} from")
|
||||
end = next((index for index in range(start + 1, len(lines)) if lines[index].startswith("## ")), len(lines))
|
||||
kept = [line for line in lines[start + 1:end] if line not in entries]
|
||||
while kept and not kept[-1].strip():
|
||||
kept.pop()
|
||||
return "\n".join([*lines[:start + 1], *kept, "", f"## {named}", "", *entries, "", *lines[end:]])
|
||||
|
||||
|
||||
def unreleased_start(lines: list[str]) -> int | None:
|
||||
"""The index in lines of a changelog's ## Unreleased heading; None where it has none."""
|
||||
return next((index for index, line in enumerate(lines) if re.fullmatch(f"## {UNRELEASED_TITLE}", line)), None)
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import typing
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from deploy_release import ci_script, cut, patch, trace
|
||||
from failure import Failure
|
||||
from test_env import isolated_env
|
||||
from deploy_release import patch
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "deploy-release"
|
||||
|
||||
@@ -244,7 +250,7 @@ class Cut(unittest.TestCase):
|
||||
(fake / name).write_text(FAKE_FORGE)
|
||||
(fake / name).chmod(0o755)
|
||||
(self.temp / "gitconfig").write_text("[user]\n\tname = t\n\temail = t@t\n")
|
||||
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": str(self.temp / "gitconfig"), "GIT_CONFIG_NOSYSTEM": "1", "PATH": f"{fake}:{os.environ['PATH']}"}
|
||||
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": str(self.temp / "gitconfig"), "GIT_CONFIG_NOSYSTEM": "1", "PATH": f"{fake}:{os.environ['PATH']}", "XDG_STATE_HOME": str(self.temp / "state")}
|
||||
self.forge_state({"origin": str(self.origin), "pulls": [], "checks": "none", "calls": []})
|
||||
self.git(self.temp, "init", "-q", "--bare", "-b", "main", str(self.origin))
|
||||
self.clone = self.temp / "claude-config"
|
||||
@@ -470,6 +476,77 @@ class Cut(unittest.TestCase):
|
||||
self.assertEqual(self.cut().returncode, 1, "0.2.0 is cut, so a second run refuses")
|
||||
self.assertEqual(self.git(self.clone, "tag", "-l", "v0.2.0", "v9.9.9").split(), ["v0.2.0", "v9.9.9"])
|
||||
|
||||
def traces(self) -> list[str]:
|
||||
"""The text of each run's trace, oldest first."""
|
||||
return [file.read_text() for file in sorted((self.temp / "state" / "deploy-release").glob("*.log")) if not file.name.endswith("-ci.log")]
|
||||
|
||||
def test_keeps_each_step_of_a_cut_with_its_time_in_a_file_of_the_run(self):
|
||||
self.assert_cut(self.cut())
|
||||
[kept] = self.traces()
|
||||
lines = kept.splitlines()
|
||||
self.assertRegex(lines[0], rf"^[0-9]{{4}}-[0-9]{{2}}-[0-9]{{2}}T[0-9:]{{8}}Z deploy-release --cut {self.target} in {self.clone}$")
|
||||
self.assertRegex(kept, r"(?m)^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]{8}Z pushed the tag v0\.2\.0$")
|
||||
self.assertIn("Done: v0.2.0 is cut and pushed", lines[-1])
|
||||
[file] = (self.temp / "state" / "deploy-release").glob("*.log")
|
||||
self.assertRegex(file.name, r"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}-[0-9]{2}-[0-9]{2}Z-[0-9]+\.log$")
|
||||
|
||||
def test_keeps_the_reason_a_cut_stopped_in_its_trace_and_a_rerun_writes_its_own(self):
|
||||
self.assert_cut(self.cut())
|
||||
self.assertEqual(self.cut().returncode, 1)
|
||||
first, second = self.traces()
|
||||
self.assertTrue(second.endswith(" release 0.3.0 still holds items in todo.md\n"), second)
|
||||
self.assertNotIn("still holds items", first)
|
||||
|
||||
def test_refuses_a_release_whose_review_has_not_landed_naming_the_commit_title_that_counts(self):
|
||||
self.assert_cut(self.cut())
|
||||
self.git(self.clone, "pull", "-q", "--ff-only", "origin", "main")
|
||||
self.commit({"CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Third.\n\n## 0.2.0\n\n- Second.\n\n## 0.1.0\n\n- First.\n", "todo.md": TODO}, "Ship item 2")
|
||||
self.git(self.clone, "push", "-q", "origin", "main")
|
||||
ran = self.cut()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("the release review of 0.3.0 hasn't landed", ran.stderr)
|
||||
self.assertIn("`Release review of 0.3.0`", ran.stderr)
|
||||
self.assertIn("`chunk-preflight --help`", ran.stderr)
|
||||
|
||||
def test_a_cut_stopped_by_ctrl_c_ends_its_trace_saying_so(self):
|
||||
self.set_checks("pending")
|
||||
process = subprocess.Popen([sys.executable, str(TOOL), "--cut", str(self.target)], cwd=self.clone, env=self.env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
self.addCleanup(process.kill)
|
||||
deadline = time.monotonic() + 30
|
||||
while not any("waiting for the checks" in kept for kept in self.traces()) and time.monotonic() < deadline:
|
||||
time.sleep(0.05)
|
||||
process.send_signal(signal.SIGINT)
|
||||
self.assertNotEqual(process.wait(timeout=30), 0)
|
||||
[kept] = self.traces()
|
||||
self.assertRegex(kept.splitlines()[-1], r"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]{8}Z stopped: KeyboardInterrupt\(\)$")
|
||||
|
||||
def test_reads_whether_the_next_releases_review_landed_beside_the_release(self):
|
||||
self.assertEqual(cut.ready_release(str(self.clone), "origin/main"), cut.Ready((0, 2, 0), reviewed=True))
|
||||
self.plan_patch()
|
||||
self.assertEqual(cut.ready_release(str(self.clone), "origin/main"), cut.Ready((0, 1, 1), reviewed=False))
|
||||
|
||||
def test_says_why_no_release_is_ready_where_nothing_has_landed_or_no_release_is_named_and_reviewed(self):
|
||||
self.commit({"CHANGELOG.md": "# Changelog\n\n## 0.4.0\n\n- Second.\n\n## 0.1.0\n\n- First.\n", "todo.md": TODO}, "Cut release 0.4.0")
|
||||
self.git(self.clone, "tag", "-a", "v0.4.0", "-m", "Cut release 0.4.0")
|
||||
self.git(self.clone, "push", "-q", "origin", "main", "--tags")
|
||||
self.assertEqual(cut.ready_release(str(self.clone), "origin/main"), Failure("every change is released already: nothing has landed since the last release cut"))
|
||||
self.commit({"CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Third.\n\n## 0.4.0\n\n- Second.\n\n## 0.1.0\n\n- First.\n"}, "Ship a third change")
|
||||
self.git(self.clone, "push", "-q", "origin", "main")
|
||||
self.assertEqual(cut.ready_release(str(self.clone), "origin/main"), Failure("the release review of the next release hasn't landed"))
|
||||
|
||||
def test_refuses_before_any_change_where_mains_changelog_has_no_unreleased_heading(self):
|
||||
ran = self.cut_patch(self.plan_patch({"CHANGELOG.md": "# Changelog\n\n- Second.\n- Fixed.\n\n## 0.1.0\n\n- First.\n"}))
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("CHANGELOG.md on origin/main has no ## Unreleased section", ran.stderr)
|
||||
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
|
||||
|
||||
def test_says_where_ci_shs_output_goes_and_keeps_it_there(self):
|
||||
ran = self.cut_patch(self.plan_patch({"ci.sh": "echo the suite ran\nexit 0\n"}))
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
[log] = (self.temp / "state" / "deploy-release").glob("*-ci.log")
|
||||
self.assertEqual(log.read_text(), "the suite ran\n")
|
||||
self.assertIn(f"ci.sh's output goes to {log}", ran.stderr)
|
||||
|
||||
def plan_patch(self, fix: dict[str, str] | None = None) -> str:
|
||||
"""On top of setUp's main: a feature no patch may ship, item 3 filed under 0.1.1, then the commit that fixes tool.txt and finishes item 3, pushed. The revision range that names only the fix."""
|
||||
self.commit({"feature.txt": "new\n"}, "Add a feature")
|
||||
@@ -678,6 +755,285 @@ class Cut(unittest.TestCase):
|
||||
|
||||
|
||||
|
||||
def still_runs(pid: int) -> bool:
|
||||
"""Whether the process pid runs: one that ended and that nobody has waited for yet doesn't."""
|
||||
try:
|
||||
return pathlib.Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[0] != "Z"
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def typed(text: bytes) -> typing.Iterator[None]:
|
||||
"""This process's stdin holding text, as a terminal someone typed it at would, for what a child inherits."""
|
||||
kept = os.dup(0)
|
||||
reading, writing = os.pipe()
|
||||
os.write(writing, text)
|
||||
os.close(writing)
|
||||
os.dup2(reading, 0)
|
||||
os.close(reading)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
os.dup2(kept, 0)
|
||||
os.close(kept)
|
||||
|
||||
|
||||
class PatchCi(unittest.TestCase):
|
||||
"""The patch's ci.sh run, read in-process with the runner handed in, and the runner itself on a real ci.sh."""
|
||||
|
||||
def setUp(self):
|
||||
self.worktree = pathlib.Path(tempfile.mkdtemp())
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", str(self.worktree)])
|
||||
self.log = self.worktree / "ci.log"
|
||||
self.said: list[str] = []
|
||||
self.removed: list[str] = []
|
||||
self.remove = lambda container: self.removed.append(container)
|
||||
|
||||
def test_passes_where_ci_sh_exits_zero(self):
|
||||
(self.worktree / "ci.sh").write_text("exit 0\n")
|
||||
seen: list[pathlib.Path] = []
|
||||
self.assertIsNone(patch.run_ci(self.worktree, "origin/main", lambda worktree: seen.append(worktree) or patch.CiRan(0, "fine\n")))
|
||||
self.assertEqual(seen, [self.worktree])
|
||||
|
||||
def test_a_failed_ci_sh_gives_the_last_30_lines_of_its_output(self):
|
||||
(self.worktree / "ci.sh").write_text("exit 1\n")
|
||||
failed = patch.run_ci(self.worktree, "origin/main", lambda worktree: patch.CiRan(1, "".join(f"line {number}\n" for number in range(1, 41))))
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("ci.sh failed on the patch, so nothing is tagged. Fix it on origin/main", failed.reason)
|
||||
self.assertTrue(failed.reason.endswith("\nline 11\n" + "\n".join(f"line {number}" for number in range(12, 41))), failed.reason)
|
||||
self.assertNotIn("line 10\n", failed.reason)
|
||||
|
||||
def test_a_ci_sh_that_could_not_run_or_was_stopped_tags_nothing_and_gives_the_runners_reason(self):
|
||||
(self.worktree / "ci.sh").write_text("exit 0\n")
|
||||
failed = patch.run_ci(self.worktree, "origin/main", lambda worktree: Failure("ci.sh still ran after 30 minutes and was stopped; /state/run-ci.log holds its output"))
|
||||
self.assertEqual(failed, Failure("ci.sh still ran after 30 minutes and was stopped; /state/run-ci.log holds its output. Nothing is tagged: fix that and rerun."))
|
||||
|
||||
def test_refuses_a_patch_without_ci_sh_before_running_anything(self):
|
||||
self.assertEqual(patch.run_ci(self.worktree, "origin/main", lambda worktree: self.fail("ran")), Failure("the patch holds no ci.sh to test it with"))
|
||||
|
||||
def test_the_runner_writes_ci_shs_output_to_the_log_as_it_runs_and_gives_its_exit_code(self):
|
||||
(self.worktree / "ci.sh").write_text("echo out\necho err >&2\nexit 3\n")
|
||||
ran = ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove)(self.worktree)
|
||||
self.assertEqual(ran, patch.CiRan(3, "out\nerr\n"))
|
||||
self.assertEqual(self.log.read_text(), "out\nerr\n")
|
||||
self.assertEqual(self.said, [f"ci.sh's output goes to {self.log}; it is stopped where it still runs after 30 seconds"])
|
||||
|
||||
def test_the_runner_stops_a_ci_sh_that_hangs_with_what_it_started_and_says_so(self):
|
||||
(self.worktree / "ci.sh").write_text("echo started\nsleep 60 &\necho $! >child.pid\nwait\n")
|
||||
began = time.monotonic()
|
||||
ran = ci_script.ci_runner(self.log, 0.5, self.said.append, "ci-of-a-test", self.remove, grace=0.2)(self.worktree)
|
||||
self.assertLess(time.monotonic() - began, 20)
|
||||
self.assertEqual(ran, Failure(f"ci.sh still ran after 0.5 seconds and was stopped; {self.log} holds its output"))
|
||||
self.assertEqual(self.log.read_text(), "started\n")
|
||||
child = int((self.worktree / "child.pid").read_text())
|
||||
deadline = time.monotonic() + 5
|
||||
while still_runs(child) and time.monotonic() < deadline:
|
||||
time.sleep(0.05)
|
||||
self.assertFalse(still_runs(child), "the process ci.sh started still runs")
|
||||
|
||||
def test_the_runner_kills_a_stopped_ci_sh_that_ignores_the_interrupt_once_its_grace_has_passed(self):
|
||||
(self.worktree / "ci.sh").write_text("trap '' INT\necho started\nsleep 60\n")
|
||||
began = time.monotonic()
|
||||
ran = ci_script.ci_runner(self.log, 0.5, self.said.append, "ci-of-a-test", self.remove, grace=0.2)(self.worktree)
|
||||
self.assertLess(time.monotonic() - began, 20)
|
||||
self.assertEqual(ran, Failure(f"ci.sh still ran after 0.5 seconds and was stopped; {self.log} holds its output"))
|
||||
self.assertEqual(self.removed, ["ci-of-a-test"])
|
||||
|
||||
def test_the_runner_stops_ci_sh_and_removes_its_container_where_the_cut_is_interrupted(self):
|
||||
(self.worktree / "ci.sh").write_text("trap '' INT\necho started\nsleep 60\n")
|
||||
def interrupt_once_ci_sh_runs():
|
||||
while not (self.log.exists() and self.log.read_bytes()):
|
||||
time.sleep(0.02)
|
||||
os.kill(os.getpid(), signal.SIGINT)
|
||||
began = time.monotonic()
|
||||
threading.Thread(target=interrupt_once_ci_sh_runs, daemon=True).start()
|
||||
with self.assertRaises(KeyboardInterrupt):
|
||||
ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove, grace=0.2)(self.worktree)
|
||||
self.assertLess(time.monotonic() - began, 20)
|
||||
self.assertEqual(self.removed, ["ci-of-a-test"])
|
||||
|
||||
def test_stopping_a_ci_sh_that_ended_already_still_removes_its_container(self):
|
||||
process = subprocess.Popen(["true"], start_new_session=True)
|
||||
process.wait()
|
||||
self.assertIsNone(ci_script.stopped(process, 0.2, "ci-of-a-test", self.remove))
|
||||
self.assertEqual(self.removed, ["ci-of-a-test"])
|
||||
|
||||
def test_the_runner_gives_ci_sh_no_input_to_wait_for(self):
|
||||
(self.worktree / "ci.sh").write_text('read line\necho "read: $line"\n')
|
||||
with typed(b"typed\n"):
|
||||
ran = ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove)(self.worktree)
|
||||
self.assertEqual(ran, patch.CiRan(0, "read: \n"))
|
||||
|
||||
def test_the_runner_gives_output_that_is_not_utf_8_with_each_such_byte_replaced(self):
|
||||
(self.worktree / "ci.sh").write_text("printf 'caf\\351 ok\\n'\n")
|
||||
ran = ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove)(self.worktree)
|
||||
self.assertEqual(ran, patch.CiRan(0, "caf\ufffd ok\n"))
|
||||
|
||||
def test_the_runner_says_its_bound_in_minutes_from_a_minute_up(self):
|
||||
(self.worktree / "ci.sh").write_text("exit 0\n")
|
||||
for seconds, lasting in ((1800, "30 minutes"), (60, "1 minute"), (59, "59 seconds"), (1, "1 second")):
|
||||
with self.subTest(seconds=seconds):
|
||||
self.said.clear()
|
||||
ci_script.ci_runner(self.log, seconds, self.said.append, "ci-of-a-test", self.remove)(self.worktree)
|
||||
self.assertEqual(self.said, [f"ci.sh's output goes to {self.log}; it is stopped where it still runs after {lasting}"])
|
||||
|
||||
def test_the_runner_names_ci_shs_container_and_removes_it_where_it_stops_ci_sh(self):
|
||||
(self.worktree / "ci.sh").write_text('echo "$CI_CONTAINER"\nsleep 60\n')
|
||||
ran = ci_script.ci_runner(self.log, 0.5, self.said.append, "ci-of-a-test", self.remove, grace=0.2)(self.worktree)
|
||||
self.assertEqual(ran, Failure(f"ci.sh still ran after 0.5 seconds and was stopped; {self.log} holds its output"))
|
||||
self.assertEqual(self.log.read_text(), "ci-of-a-test\n")
|
||||
self.assertEqual(self.removed, ["ci-of-a-test"])
|
||||
|
||||
def test_the_runner_says_where_the_container_of_a_stopped_ci_sh_may_still_run(self):
|
||||
(self.worktree / "ci.sh").write_text("sleep 60\n")
|
||||
ran = ci_script.ci_runner(self.log, 0.5, self.said.append, "ci-of-a-test", lambda container: Failure("docker rm --force ci-of-a-test failed: no daemon"), grace=0.2)(self.worktree)
|
||||
self.assertEqual(ran, Failure(f"ci.sh still ran after 0.5 seconds and was stopped, but its container ci-of-a-test may still run: docker rm --force ci-of-a-test failed: no daemon; {self.log} holds its output"))
|
||||
|
||||
def test_the_runner_removes_no_container_where_ci_sh_ends_in_time(self):
|
||||
(self.worktree / "ci.sh").write_text("exit 0\n")
|
||||
ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove)(self.worktree)
|
||||
self.assertEqual(self.removed, [])
|
||||
|
||||
def test_removing_a_container_gives_a_failure_where_docker_fails_and_none_where_it_removes(self):
|
||||
asked: list[list[str]] = []
|
||||
def docker(code: int, stderr: str):
|
||||
return lambda argv, **options: asked.append(argv) or subprocess.CompletedProcess(argv, code, "", stderr)
|
||||
self.assertIsNone(ci_script.removed_container("ci-of-a-test", docker(0, "")))
|
||||
self.assertEqual(asked, [["docker", "rm", "--force", "ci-of-a-test"]])
|
||||
self.assertEqual(ci_script.removed_container("ci-of-a-test", docker(1, "Cannot connect to the Docker daemon\n")), Failure("docker rm --force ci-of-a-test failed: Cannot connect to the Docker daemon"))
|
||||
|
||||
def test_removing_a_container_gives_a_failure_where_docker_cannot_start(self):
|
||||
def no_docker(argv, **options):
|
||||
raise FileNotFoundError("docker")
|
||||
self.assertEqual(ci_script.removed_container("ci-of-a-test", no_docker), Failure("docker rm --force ci-of-a-test failed: docker"))
|
||||
|
||||
def test_removing_a_container_gives_dockers_own_error_and_no_input_to_wait_for(self):
|
||||
fake = self.worktree / "fake-bin"
|
||||
fake.mkdir()
|
||||
(fake / "docker").write_text('#!/bin/sh\nread line\necho "no daemon for $*, read: $line" >&2\nexit 1\n')
|
||||
(fake / "docker").chmod(0o755)
|
||||
found_first = lambda argv, **options: subprocess.run(argv, env={**os.environ, "PATH": f"{fake}:{os.environ['PATH']}"}, **options)
|
||||
with typed(b"typed\n"):
|
||||
left = ci_script.removed_container("ci-of-a-test", found_first)
|
||||
self.assertEqual(left, Failure("docker rm --force ci-of-a-test failed: no daemon for rm --force ci-of-a-test, read:"))
|
||||
|
||||
def test_removing_a_container_gives_a_failure_where_docker_takes_longer_than_a_minute(self):
|
||||
def slow_docker(argv, **options):
|
||||
raise subprocess.TimeoutExpired(argv, options["timeout"])
|
||||
left = ci_script.removed_container("ci-of-a-test", slow_docker)
|
||||
self.assertIsInstance(left, Failure)
|
||||
self.assertTrue(left.reason.startswith("docker rm --force ci-of-a-test failed: "), left.reason)
|
||||
self.assertIn("timed out after 60 seconds", left.reason)
|
||||
|
||||
def test_ci_sh_names_its_container_only_where_it_is_given_a_name(self):
|
||||
script = (pathlib.Path(__file__).resolve().parents[2] / "ci.sh").read_text()
|
||||
self.assertIn('${CI_CONTAINER:+--name "$CI_CONTAINER"}', script)
|
||||
|
||||
def test_the_runner_gives_a_failure_where_ci_sh_cannot_start(self):
|
||||
ran = ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove)(self.worktree / "gone")
|
||||
self.assertIsInstance(ran, Failure)
|
||||
self.assertIn("ci.sh could not run: ", ran.reason)
|
||||
self.assertIn(str(self.worktree / "gone"), ran.reason)
|
||||
|
||||
def test_the_runner_gives_a_failure_where_the_log_cannot_be_written(self):
|
||||
(self.worktree / "ci.sh").write_text("exit 0\n")
|
||||
ran = ci_script.ci_runner(self.worktree / "no-folder" / "ci.log", 30, self.said.append, "ci-of-a-test", self.remove)(self.worktree)
|
||||
self.assertIsInstance(ran, Failure)
|
||||
self.assertIn(str(self.worktree / "no-folder" / "ci.log"), ran.reason)
|
||||
|
||||
|
||||
class Trace(unittest.TestCase):
|
||||
"""What a cut says, in-process, with the clock and stderr handed in."""
|
||||
|
||||
def setUp(self):
|
||||
self.temp = pathlib.Path(tempfile.mkdtemp())
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", str(self.temp)])
|
||||
# 2026-11-27T09:30:05Z, in seconds since the epoch.
|
||||
self.now = lambda: 1795771805.0
|
||||
|
||||
def test_keeps_traces_under_the_state_folder_xdg_names_else_under_homes(self):
|
||||
self.assertEqual(trace.trace_folder({"XDG_STATE_HOME": "/x/state"}, pathlib.Path("/home/u")), pathlib.Path("/x/state/deploy-release"))
|
||||
self.assertEqual(trace.trace_folder({}, pathlib.Path("/home/u")), pathlib.Path("/home/u/.local/state/deploy-release"))
|
||||
|
||||
def test_names_a_run_by_its_start_and_its_process(self):
|
||||
self.assertEqual(trace.run_name(self.now(), 4711), "2026-11-27T09-30-05Z-4711")
|
||||
|
||||
def test_starts_a_trace_with_the_command_then_appends_each_step_with_its_time_and_says_it(self):
|
||||
file = trace.started(self.temp / "state" / "deploy-release", "run", "deploy-release --cut", self.now)
|
||||
self.assertEqual(file, self.temp / "state" / "deploy-release" / "run.log")
|
||||
out = io.StringIO()
|
||||
say = trace.saying(file, self.now, out)
|
||||
say("pushed the tag v0.2.0")
|
||||
say("merged pull request 3")
|
||||
self.assertEqual(out.getvalue(), "deploy-release: pushed the tag v0.2.0\ndeploy-release: merged pull request 3\n")
|
||||
self.assertEqual(file.read_text(), "2026-11-27T09:30:05Z deploy-release --cut\n2026-11-27T09:30:05Z pushed the tag v0.2.0\n2026-11-27T09:30:05Z merged pull request 3\n")
|
||||
|
||||
def test_starts_a_later_runs_trace_beside_the_earlier_one(self):
|
||||
folder = self.temp / "state" / "deploy-release"
|
||||
first = trace.started(folder, "first", "deploy-release --cut", self.now)
|
||||
second = trace.started(folder, "second", "deploy-release --cut-patch a..b", self.now)
|
||||
self.assertEqual((first, second), (folder / "first.log", folder / "second.log"))
|
||||
self.assertEqual(second.read_text(), "2026-11-27T09:30:05Z deploy-release --cut-patch a..b\n")
|
||||
self.assertEqual(first.read_text(), "2026-11-27T09:30:05Z deploy-release --cut\n")
|
||||
|
||||
def test_a_trace_that_cannot_be_started_is_a_failure_naming_the_file(self):
|
||||
(self.temp / "state").write_text("a file where the folder goes\n")
|
||||
made = trace.started(self.temp / "state" / "deploy-release", "run", "deploy-release --cut", self.now)
|
||||
self.assertIsInstance(made, Failure)
|
||||
self.assertIn(str(self.temp / "state" / "deploy-release" / "run.log"), made.reason)
|
||||
|
||||
def test_still_says_each_step_where_there_is_no_trace_or_it_cannot_be_written(self):
|
||||
out = io.StringIO()
|
||||
trace.saying(None, self.now, out)("pushed the tag v0.2.0")
|
||||
trace.saying(self.temp / "gone" / "run.log", self.now, out)("merged pull request 3")
|
||||
self.assertEqual(out.getvalue().splitlines()[:2], ["deploy-release: pushed the tag v0.2.0", "deploy-release: merged pull request 3"])
|
||||
self.assertIn(f"warning: the trace {self.temp / 'gone' / 'run.log'} could not be written", out.getvalue().splitlines()[2])
|
||||
|
||||
|
||||
class Rewritten(unittest.TestCase):
|
||||
"""A cut's file edits, where the filesystem refuses one."""
|
||||
|
||||
def setUp(self):
|
||||
self.temp = pathlib.Path(tempfile.mkdtemp())
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", str(self.temp)])
|
||||
|
||||
def test_replaces_a_files_text_and_hands_none_for_a_file_that_is_not_there(self):
|
||||
file = self.temp / "CHANGELOG.md"
|
||||
self.assertIsNone(cut.rewritten(file, "head CHANGELOG.md", "Nothing is tagged.", lambda text: f"{text!r} new\n"))
|
||||
self.assertEqual(file.read_text(), "None new\n")
|
||||
self.assertIsNone(cut.rewritten(file, "head CHANGELOG.md", "Nothing is tagged.", lambda text: text.upper()))
|
||||
self.assertEqual(file.read_text(), "NONE NEW\n")
|
||||
|
||||
def test_a_file_that_cannot_be_read_or_written_is_a_failure_naming_the_step_and_the_file(self):
|
||||
folder = self.temp / "CHANGELOG.md"
|
||||
folder.mkdir()
|
||||
# A folder can't be read as a file, and a file in a folder that isn't there can't be written.
|
||||
for file in (folder, self.temp / "gone" / "commit.patch"):
|
||||
with self.subTest(file=file):
|
||||
failed = cut.rewritten(file, "head CHANGELOG.md with ## 0.1.1", "Nothing is tagged.", lambda text: "new\n")
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertTrue(failed.reason.startswith("could not head CHANGELOG.md with ## 0.1.1: "), failed.reason)
|
||||
self.assertEqual(failed.reason.count(str(file)), 1, failed.reason)
|
||||
self.assertTrue(failed.reason.endswith(f"'{file}'. Nothing is tagged."), failed.reason)
|
||||
|
||||
def test_a_file_that_is_not_utf_8_is_a_failure_naming_the_step_and_the_file(self):
|
||||
file = self.temp / "CHANGELOG.md"
|
||||
file.write_bytes(b"caf\xe9\n")
|
||||
failed = cut.rewritten(file, "head CHANGELOG.md", "Nothing is tagged.", lambda text: "new\n")
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertTrue(failed.reason.startswith("could not head CHANGELOG.md: "), failed.reason)
|
||||
self.assertTrue(failed.reason.endswith(f" ({file}). Nothing is tagged."), failed.reason)
|
||||
self.assertEqual(failed.reason.count(str(file)), 1, failed.reason)
|
||||
self.assertEqual(file.read_bytes(), b"caf\xe9\n")
|
||||
|
||||
def test_gives_the_rewrites_own_failure_and_leaves_the_file(self):
|
||||
file = self.temp / "CHANGELOG.md"
|
||||
file.write_text("old\n")
|
||||
self.assertEqual(cut.rewritten(file, "x", "y", lambda text: Failure("no heading")), Failure("no heading"))
|
||||
self.assertEqual(file.read_text(), "old\n")
|
||||
|
||||
|
||||
class PatchChangelog(unittest.TestCase):
|
||||
"""The changelog edits of a patch cut, read in-process, so a mutation tester reaches them."""
|
||||
|
||||
@@ -689,14 +1045,17 @@ class PatchChangelog(unittest.TestCase):
|
||||
|
||||
def test_moves_the_patchs_entries_from_unreleased_to_a_section_after_it(self):
|
||||
changelog = "# Changelog\n\n## Unreleased\n\n- Second.\n- Fixed.\n\n## 0.1.0\n\n- First.\n"
|
||||
self.assertEqual(patch.moved_entries(changelog, ["- Fixed."], "0.1.1"), "# Changelog\n\n## Unreleased\n\n- Second.\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- First.\n")
|
||||
self.assertEqual(patch.moved_entries(changelog, ["- Fixed."], "0.1.1", "origin/main"), "# Changelog\n\n## Unreleased\n\n- Second.\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- First.\n")
|
||||
|
||||
def test_leaves_an_older_section_entry_that_reads_the_same(self):
|
||||
changelog = "# Changelog\n\n## Unreleased\n\n- Fixed.\n\n## 0.1.0\n\n- Fixed.\n"
|
||||
self.assertEqual(patch.moved_entries(changelog, ["- Fixed."], "0.1.1"), "# Changelog\n\n## Unreleased\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- Fixed.\n")
|
||||
self.assertEqual(patch.moved_entries(changelog, ["- Fixed."], "0.1.1", "origin/main"), "# Changelog\n\n## Unreleased\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- Fixed.\n")
|
||||
|
||||
def test_puts_the_section_last_where_unreleased_is_the_last_section(self):
|
||||
self.assertEqual(patch.moved_entries("# Changelog\n\n## Unreleased\n\n- Fixed.\n", ["- Fixed."], "0.1.1"), "# Changelog\n\n## Unreleased\n\n## 0.1.1\n\n- Fixed.\n")
|
||||
self.assertEqual(patch.moved_entries("# Changelog\n\n## Unreleased\n\n- Fixed.\n", ["- Fixed."], "0.1.1", "origin/main"), "# Changelog\n\n## Unreleased\n\n## 0.1.1\n\n- Fixed.\n")
|
||||
|
||||
def test_a_changelog_without_an_unreleased_heading_is_a_failure_that_names_it(self):
|
||||
self.assertEqual(patch.moved_entries("# Changelog\n\n## 0.1.0\n\n- First.\n", ["- Fixed."], "0.1.1", "origin/main"), Failure("CHANGELOG.md on origin/main has no ## Unreleased heading to move the entries of 0.1.1 from"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"""What a cut says as each step finishes: on stderr, and in a file of the run's own, so the steps outlast the terminal."""
|
||||
import pathlib
|
||||
import time
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from text_files import utc_stamp
|
||||
|
||||
# Says that one step of a cut finished, as `saying` makes it.
|
||||
Say = typing.Callable[[str], None]
|
||||
# The time now, in seconds since the epoch, as time.time gives it.
|
||||
Clock = typing.Callable[[], float]
|
||||
|
||||
|
||||
def trace_folder(env: typing.Mapping[str, str], home: pathlib.Path) -> pathlib.Path:
|
||||
"""The folder each cut keeps its trace in, under the state folder as run-heavy finds it."""
|
||||
state = env.get("XDG_STATE_HOME") or str(home / ".local" / "state")
|
||||
return pathlib.Path(state) / "deploy-release"
|
||||
|
||||
|
||||
def run_name(began: float, pid: int) -> str:
|
||||
"""The name of the files one run keeps, which sorts by when it began: that time in UTC, with no colon, so the name is valid on every disk."""
|
||||
return f"{time.strftime('%Y-%m-%dT%H-%M-%SZ', time.gmtime(began))}-{pid}"
|
||||
|
||||
|
||||
def stamped(at: float, line: str) -> str:
|
||||
return f"{utc_stamp.utc(at)} {line}\n"
|
||||
|
||||
|
||||
def started(folder: pathlib.Path, name: str, command: str, now: Clock) -> pathlib.Path | Failure:
|
||||
"""A new trace, <folder>/<name>.log, whose first line is command; a Failure where it can't be written."""
|
||||
file = folder / f"{name}.log"
|
||||
try:
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
file.write_text(stamped(now(), command), encoding="utf-8")
|
||||
except OSError as failure:
|
||||
return Failure(f"the trace {file} could not be started: {failure}")
|
||||
return file
|
||||
|
||||
|
||||
def kept(trace: pathlib.Path | None, line: str, now: Clock, out: typing.TextIO) -> None:
|
||||
"""Append line with its time, in UTC, to trace, where there is one. A trace that can't be written only warns on out, since the cut's own steps count."""
|
||||
if trace is None:
|
||||
return
|
||||
try:
|
||||
with trace.open("a", encoding="utf-8") as file:
|
||||
file.write(stamped(now(), line))
|
||||
except OSError as failure:
|
||||
print(f"deploy-release: warning: the trace {trace} could not be written: {failure}", file=out)
|
||||
|
||||
|
||||
def saying(trace: pathlib.Path | None, now: Clock, out: typing.TextIO) -> Say:
|
||||
"""Says each step on out, so the human sees how far the cut got before the changelog fills the screen, and keeps it in trace."""
|
||||
def say(step: str) -> None:
|
||||
print(f"deploy-release: {step}", file=out)
|
||||
kept(trace, step, now, out)
|
||||
return say
|
||||
@@ -8,11 +8,10 @@ from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown
|
||||
from plan_store.jira_epic import BLOCKS, FILED_BY, scores as held_scores, PROPERTY
|
||||
from project_config.settings import DEFAULT_ISSUE_TYPE, Epic, Finish, JIRA_FINDING_TYPE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, JIRA_REVIEW_TYPE
|
||||
from atlassian.jira import DONE, edit_issue, entry_of, finishing_transition, ISSUE_KEY, issue_type_refusal, issue_types_of, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, SHAPE, status_category, unshaped
|
||||
from do_epic.backend.protocol import EpicIssue, no_blocker, no_child, no_parent, no_scores, no_words, unfit, unfit_label
|
||||
from do_epic.backend.protocol import EpicIssue, no_blocker, no_child, no_parent, no_scores, no_words, REVIEW_LABEL, unfit, unfit_label
|
||||
from failure import Failure
|
||||
from do_epic.backend.jira_status import moved_by, moved_to
|
||||
from plan.todo_table import MOVES
|
||||
from do_epic.repo_pick import REVIEW_LABEL
|
||||
from do_epic.backend.jira_start import Start, started
|
||||
|
||||
FIELDS = ["summary", "description", "labels", "assignee", "status", "parent", "issuelinks"]
|
||||
|
||||
@@ -9,6 +9,8 @@ from plan.todo_table import Exempt, item_fields, ItemFields, Moves, MOVES
|
||||
from failure import Failure
|
||||
from plan_store.jira_epic import SET_SCORES
|
||||
|
||||
# Marks the issue that asks for a repo's release review, beside the label that names the repo (finish.py). Not `release-review`, which could pass for the team's own release process: three readers, seated as the human, as a chunk's worker and as one of the client's team, picked this one 3-0 from four.
|
||||
REVIEW_LABEL = "do-epic-release-review"
|
||||
# What a tracker accepts as a label: Jira refuses a label holding white space.
|
||||
LABEL = re.compile(r"\S+")
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ from do_epic.backend.contract import EpicStoreContract
|
||||
from failure import Failure
|
||||
from do_epic.backend.jira import JiraEpic
|
||||
from adf_codec.convert import Refused
|
||||
from do_epic.repo_pick import REVIEW_LABEL
|
||||
from do_epic.backend.protocol import REVIEW_LABEL
|
||||
from do_epic.backend.jira_start import Start
|
||||
|
||||
SITE = "https://acme.atlassian.net"
|
||||
|
||||
@@ -34,8 +34,8 @@ import types
|
||||
|
||||
from project_config.settings import anywhere, CONFIG, DEFAULT_ISSUE_TYPE, DO_EPIC, ENV_FILE, Finish, finish_faults, finish_of, JIRA_FINDING_TYPE, JIRA_FINISH, JIRA_REVIEW_TYPE, LANGUAGE, language_fault, lies_in, name_of, parsed, PROJECTS, SITE, type_fault
|
||||
from failure import Failure
|
||||
from do_epic.backend.protocol import LABEL
|
||||
from do_epic.repo_pick import LabelRepos, of_label, REPO_NAME, REVIEW_LABEL
|
||||
from do_epic.backend.protocol import LABEL, REVIEW_LABEL
|
||||
from do_epic.repo_pick import LabelRepos, of_label, REPO_NAME
|
||||
from text_files.markdown_text import listed
|
||||
from model_routing.ladder_file import read_ladder, SHIPPED
|
||||
from do_epic.split import SPLIT_LABEL
|
||||
|
||||
@@ -7,8 +7,8 @@ import fcntl
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from do_epic.repo_pick import CLAUDE_LABEL, HUMAN_LABEL, label_of, LabelRepos, of_label, REPO_PREFIX, REVIEW_LABEL, team_label
|
||||
from do_epic.backend.protocol import EpicIssue, EpicStore
|
||||
from do_epic.repo_pick import CLAUDE_LABEL, HUMAN_LABEL, label_of, LabelRepos, of_label, REPO_PREFIX, team_label
|
||||
from do_epic.backend.protocol import EpicIssue, EpicStore, REVIEW_LABEL
|
||||
from do_epic.epic_record import EpicRecord
|
||||
from failure import Failure
|
||||
from text_files.markdown_text import listed
|
||||
|
||||
@@ -12,13 +12,14 @@ import pathlib
|
||||
import typing
|
||||
|
||||
from do_epic.chunk_prompt import DRIVER
|
||||
from do_epic.backend.protocol import EpicIssue, EpicStore
|
||||
from do_epic.backend.protocol import EpicIssue, EpicStore, REVIEW_LABEL
|
||||
from failure import Failure
|
||||
from do_epic import findings
|
||||
from do_epic.split import finished
|
||||
from do_epic.repo_pick import label_of, LabelRepos, recorded, Repo, REVIEW_LABEL
|
||||
from do_epic.repo_pick import label_of, LabelRepos, recorded, Repo
|
||||
from text_files.markdown_text import listed
|
||||
from text_files.piped_text import piped
|
||||
from plan.release import REVIEW_TITLE
|
||||
|
||||
# Not `--close`, which reads as closing the run or one issue: three readers, seated as the human, as a chunk's worker and as one of the client's team, picked this one from four, 2-1 over it.
|
||||
CLOSE = "--close-epic"
|
||||
@@ -67,7 +68,7 @@ def task(epic: str, issues: list[EpicIssue], team: LabelRepos, launcher: pathlib
|
||||
f"{opening} Each repo the epic changed takes a release review first, and {listed(lacking, 'and')} {'has' if len(lacking) == 1 else 'have'} none. "
|
||||
f"File one issue per such repo, with `{launcher} {epic} {findings.FILE} \"<summary>\" {findings.LABEL} <label> {findings.LABEL} {REVIEW_LABEL}` and its detail on stdin, both in {language}, the epic's language. "
|
||||
f"The `<label>` is {listed([f'`{label_of(Repo(name), team)}` for {name}' for name in lacking], 'and')}. "
|
||||
f"The detail asks for a release review of the whole repo, as the epic's issues left it: the one `~/.claude/skills/larv-review/SKILL.md` → \"Release review\" describes. The epic's key stands in place of the release there, so the review's branch opens with an empty commit titled `Release review of {epic}`. "
|
||||
f"The detail asks for a release review of the whole repo, as the epic's issues left it: the one `~/.claude/skills/larv-review/SKILL.md` → \"Release review\" describes. The epic's key stands in place of the release there, so the review's branch opens with an empty commit titled `{REVIEW_TITLE}{epic}`. "
|
||||
"Where filing fails and says the issue may exist, ask the human to look before you file it again. "
|
||||
f"The chunk is finished once each issue is filed: {DRIVER} works them, and starts this chunk again once the epic holds no open issue."
|
||||
)
|
||||
|
||||
+35
-18
@@ -104,33 +104,50 @@ class Poll:
|
||||
|
||||
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
|
||||
told = Told(poll, shown)
|
||||
while True:
|
||||
now = poll.gate()
|
||||
if isinstance(now, gates.Gate):
|
||||
awaits, stays = now.on, None
|
||||
if isinstance(now, gates.Open):
|
||||
full = resumed(poll.repo, poll.loop, poll.epic)
|
||||
if full is None:
|
||||
return unparked(poll, on, now)
|
||||
told.tell(parked.SLOT, f"{now.news}, but the chunk stays parked: {full}")
|
||||
elif isinstance(now, Failure):
|
||||
told.tell(told.awaits or on, f"cannot read the gate: {now.reason}")
|
||||
else:
|
||||
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
|
||||
told.tell(now.on, None)
|
||||
poll.epic.effects.sleep(POLL_SECONDS)
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class Told:
|
||||
"""What the human has been told of a parked chunk, so that each read of its gate tells only what changed: what its window's name says it awaits, None where nothing yet, and the last reason said for staying parked."""
|
||||
poll: Poll
|
||||
awaits: str | None
|
||||
reason: str | None = None
|
||||
|
||||
def tell(self, awaits: str, reason: str | None) -> None:
|
||||
"""Names the window after what the chunk awaits, and says the reason it stays parked, None where the gate says it all. It skips what it told last."""
|
||||
if awaits != self.awaits:
|
||||
tmux.park(self.poll.loop.window, awaits, self.poll.epic.effects.tmux)
|
||||
self.awaits = awaits
|
||||
if reason is not None and reason != self.reason:
|
||||
say(f"{reason}; trying again every {POLL_SECONDS} seconds", self.poll.epic.effects, stdout=True)
|
||||
self.reason = reason
|
||||
|
||||
|
||||
def unparked(poll: Poll, on: str, now: gates.Open) -> str | Stop:
|
||||
"""Removes the file of the chunk that was parked on the gate on: what to tell its worker, which now says why it resumes."""
|
||||
failed = parked.unpark(poll.folder, poll.key)
|
||||
if failed is not None:
|
||||
return Stop(1, failed.reason)
|
||||
return f"{DRIVER_PARKED} its pull request awaited {"a person's merge" if on == gates.MERGE else on}. It resumes now: {now.news}."
|
||||
|
||||
|
||||
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.
|
||||
|
||||
@@ -16,8 +16,6 @@ from claude_code.entries import structured_output
|
||||
REPO_PREFIX = "repo:"
|
||||
CLAUDE_LABEL = "do-epic-claude"
|
||||
HUMAN_LABEL = "do-epic-human"
|
||||
# Marks the issue that asks for a repo's release review, beside the label that names the repo (finish.py). Not `release-review`, which could pass for the team's own release process: three readers, seated as the human, as a chunk's worker and as one of the client's team, picked this one 3-0 from four.
|
||||
REVIEW_LABEL = "do-epic-release-review"
|
||||
# A repo's name is a folder name and part of a clone address, so claude's answer or a label a person typed must not hold a slash, a colon or a leading dot.
|
||||
REPO_NAME = re.compile(r"\w[\w.-]*")
|
||||
|
||||
|
||||
@@ -12,6 +12,8 @@ DATED = re.compile(rf"({VERSION}) - " + "-".join(f"[0-9]{{{digits}}}" for digits
|
||||
TAG = re.compile(rf"v({VERSION})")
|
||||
# The title of CHANGELOG.md's section for news not yet released: Unreleased, or a title that says unreleased, such as `0.6.0 (unreleased)`, as a project's own changelog may head it; and its ## heading.
|
||||
UNRELEASED_TITLE = r"(?i:.*unreleased.*)"
|
||||
# What opens the title of a release review's first commit, before the release it reviews, or the epic's key in do-epic's finishing chunk. release_standing counts a review by it.
|
||||
REVIEW_TITLE = "Release review of "
|
||||
UNRELEASED_HEADING = re.compile(rf"^## {UNRELEASED_TITLE}$", re.M)
|
||||
|
||||
|
||||
|
||||
@@ -230,6 +230,7 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
|
||||
formula, bar = values.get(JIRA_SCORE_FORMULA), values.get(JIRA_SCORE_BAR)
|
||||
scoring = JiraScoring(formula, bar_value) if isinstance(formula, str) and (bar_value := bar_of(bar)) is not None else None
|
||||
faults = [
|
||||
# First what is wrong with a setting by itself, then with the settings together, then with the two that score a plan in Jira.
|
||||
*(f"`{name}` is missing" for name in SETTINGS if name not in values),
|
||||
*(f"`{name}` is not a setting" for name in values if name not in (*SETTINGS, *OPTIONAL)),
|
||||
*(f"`{scalar.name}` is {values[scalar.name]!r}, {read.reason}" for scalar, read in scalars.items() if isinstance(read, Unfit)),
|
||||
@@ -238,7 +239,26 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
|
||||
*(f"`{name}` is {values[name]!r}, not {SPELLING}, or {PAGE_SPELLING}" for name in RECORDS if name in values and paths[name] is None and name not in pages),
|
||||
*([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not {OUTSIDE}"] if misplaced else []),
|
||||
*([f"`{CODING_CONVENTIONS}` is {values[CODING_CONVENTIONS]!r}, not a list of paths, each {SPELLING}"] if conventions is None else []),
|
||||
# Each setting that reaches a service needs the file that holds its credentials.
|
||||
*combination_faults(values, epics, pages),
|
||||
*([f"`{JIRA_SCORE_FORMULA}` is {formula!r}: {fault}"] if JIRA_SCORE_FORMULA in values and (fault := formula_fault(formula)) else []),
|
||||
*([f"`{JIRA_SCORE_BAR}` is {bar!r}, not a bare number, such as `{JIRA_SCORE_BAR} = 1`"] if JIRA_SCORE_BAR in values and bar_of(bar) is None else []),
|
||||
]
|
||||
if faults:
|
||||
return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}, and optionally {', '.join(OPTIONAL[:-1])} and {OPTIONAL[-1]}.")
|
||||
# faults names a formula or bar a plan in Jira lacks or misspells.
|
||||
assert scoring is not None or not epics["plan"]
|
||||
defaulted = ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, epic=epics["plan"], goals_epic=epics["goals-and-audience"], jira_finish=finish_of(values), jira_scoring=scoring, pages=pages, coding_conventions=conventions or ())
|
||||
return dataclasses.replace(defaulted, **{scalar.field: read for scalar, read in scalars.items()})
|
||||
|
||||
|
||||
def combination_faults(values: dict[str, object], epics: dict[str, Epic | None], pages: dict[str, Page]) -> list[str]:
|
||||
"""Which of a config's settings may not stand together, as `project-config --help` says of each. values is the config, epics the Jira epic each of EPIC_SPELLINGS names, None where it names none, and pages the Confluence page of each record kept on one.
|
||||
|
||||
Three rules, in the order of the faults:
|
||||
- a setting that reaches a service needs `env-file`;
|
||||
- the goals in a Jira epic, a ranked record on a Confluence page and each of JIRA_PLAN_ONLY need `plan` to name a Jira epic, and such a plan needs both of JIRA_SCORE;
|
||||
- the two JIRA_FINISH settings come together, and `review-request-comment` needs `epic-branch`."""
|
||||
return [
|
||||
*(f"`{name}` names a Jira epic, so `{ENV_FILE}` must name the file that holds its credentials" for name, epic in epics.items() if epic and ENV_FILE not in values),
|
||||
*(f"`{name}` names a Confluence page, so `{ENV_FILE}` must name the file that holds its credentials" for name in pages if ENV_FILE not in values),
|
||||
*([f"`{NOTIFIER}` names a notifier, so `{ENV_FILE}` must name the file that holds its credentials"] if NOTIFIER in values and ENV_FILE not in values else []),
|
||||
@@ -249,15 +269,7 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
|
||||
*(f"`plan` names a Jira epic, so `{name}` must be set, as `project-config --help` shows" for name in JIRA_SCORE if epics["plan"] and name not in values),
|
||||
*finish_faults(values),
|
||||
*([f"`{REVIEW_REQUEST_COMMENT}` is set, so `{EPIC_BRANCH}` must be set: the comment goes on pull requests into that branch"] if REVIEW_REQUEST_COMMENT in values and EPIC_BRANCH not in values else []),
|
||||
*([f"`{JIRA_SCORE_FORMULA}` is {formula!r}: {fault}"] if JIRA_SCORE_FORMULA in values and (fault := formula_fault(formula)) else []),
|
||||
*([f"`{JIRA_SCORE_BAR}` is {bar!r}, not a bare number, such as `{JIRA_SCORE_BAR} = 1`"] if JIRA_SCORE_BAR in values and bar_of(bar) is None else []),
|
||||
]
|
||||
if faults:
|
||||
return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}, and optionally {', '.join(OPTIONAL[:-1])} and {OPTIONAL[-1]}.")
|
||||
# faults names a formula or bar a plan in Jira lacks or misspells.
|
||||
assert scoring is not None or not epics["plan"]
|
||||
defaulted = ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, epic=epics["plan"], goals_epic=epics["goals-and-audience"], jira_finish=finish_of(values), jira_scoring=scoring, pages=pages, coding_conventions=conventions or ())
|
||||
return dataclasses.replace(defaulted, **{scalar.field: read for scalar, read in scalars.items()})
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
|
||||
@@ -6,7 +6,7 @@ from failure import Failure
|
||||
from plan.todo_table import Item, NoItemsTable
|
||||
from text_files.markdown_text import listed
|
||||
from plan_store.plans import Plan
|
||||
from plan.release import Release, version
|
||||
from plan.release import Release, REVIEW_TITLE, version
|
||||
from project_config import templates
|
||||
|
||||
|
||||
@@ -78,7 +78,8 @@ def planned(read: Plan | Failure, cut: LastCut, default: str, branch: str, outsi
|
||||
if isinstance(pick, ReadyToCut | ReviewDue | Unplanned):
|
||||
upcoming = f"release {version(pick.release)}, the next after {last_cut}" if pick.release else f"the next release after {last_cut}"
|
||||
if isinstance(pick, ReviewDue):
|
||||
return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, so that release's release review is due: no commit titled `Release review of <release>` has landed {'since the cut' if named is not None else 'yet'}. This chunk is that review, as `~/.claude/skills/larv-review/SKILL.md` → \"Release review\" says; once it merges and the release holds no item, the release is ready to cut.")
|
||||
awaited = version(pick.release) if pick.release else "<release>"
|
||||
return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, so that release's release review is due: no commit titled `{REVIEW_TITLE}{awaited}` has landed {'since the cut' if named is not None else 'yet'}. `chunk-preflight --help` says which commit counts. This chunk is that review, as `~/.claude/skills/larv-review/SKILL.md` → \"Release review\" says; once it merges and the release holds no item, the release is ready to cut.")
|
||||
if isinstance(pick, ReadyToCut):
|
||||
return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, and its release review has landed, so that release is finished and ready to cut. The working loop stops here. If todo.md renamed that release instead, add `- <old release> renamed to <new release>` to todo.md's `## Renamed` section.")
|
||||
return NoItem(f"{where} holds no item for {upcoming}, and no change is unreleased, so that release is to be planned first.")
|
||||
|
||||
@@ -3,7 +3,7 @@ import dataclasses
|
||||
|
||||
from release_plan.awaiting_merge import awaiting, marked
|
||||
from git_cli.git_repo import commits_since, file_at, git, Git
|
||||
from plan.release import dated, dated_heading_pattern, newest_tag, parsed, Release, tagged, UNRELEASED_TITLE
|
||||
from plan.release import dated, dated_heading_pattern, newest_tag, parsed, Release, REVIEW_TITLE, tagged, UNRELEASED_TITLE
|
||||
from failure import Failure
|
||||
from forge.commands import forge_of, Run
|
||||
from plan.todo_table import Item, items, next_item, renames
|
||||
@@ -31,8 +31,8 @@ class LastCut:
|
||||
commits: int | Failure
|
||||
# todo.md's text at the tag and at each later commit that changed it, oldest first, as named_releases reads them; where the branch has no tag, at each commit that changed it. Empty where the tags cannot be read, and where no commit holds the plan.
|
||||
todos_since: list[str] | Failure
|
||||
# Whether a release review has landed since the tag, as release_reviewed reads it.
|
||||
reviewed: bool | Failure = False
|
||||
# The releases whose release review has landed since the cut, as reviewed_releases reads them.
|
||||
reviews: frozenset[Release] | Failure = frozenset()
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -70,7 +70,7 @@ class ReadyToCut:
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ReviewDue:
|
||||
"""The next release holds no item and work has landed towards it, but no release review has landed since the cut: `~/.claude/skills/larv-review/SKILL.md` → "Release review"."""
|
||||
"""The next release holds no item and work has landed towards it, but its release review has not landed, as pick_from reads it: `~/.claude/skills/larv-review/SKILL.md` → "Release review"."""
|
||||
# The next release, None where todo.md has named none since the cut.
|
||||
release: Release | None
|
||||
|
||||
@@ -122,8 +122,8 @@ def default_plan(root: str, ref: str, plan: plans.PlanStore, changelog: stores.R
|
||||
after = dated_cut(tag, changes)
|
||||
since = tag if after is None else heading_commit(after, ref, changelog, root, run)
|
||||
commits = since if isinstance(since, Failure) else commits_since(since, ref, root, run)
|
||||
reviewed = tag if isinstance(tag, Failure) else release_reviewed(tag, ref, root, titles, after, run)
|
||||
return DefaultPlan(plan_stores.held_at(ref, plan, root, run), LastCut(tag, changes, commits, todos_since(tag, ref, plan.tracked, root, run), reviewed))
|
||||
reviews = tag if isinstance(tag, Failure) else reviewed_releases(tag, ref, root, titles, after, run)
|
||||
return DefaultPlan(plan_stores.held_at(ref, plan, root, run), LastCut(tag, changes, commits, todos_since(tag, ref, plan.tracked, root, run), reviews))
|
||||
|
||||
|
||||
def heading_commit(release: Release, ref: str, changelog: stores.RecordStore, cwd: str, run: Git = git) -> str | None | Failure:
|
||||
@@ -135,18 +135,18 @@ def heading_commit(release: Release, ref: str, changelog: stores.RecordStore, cw
|
||||
return added if isinstance(added, Failure) else next(iter(added.split()), None)
|
||||
|
||||
|
||||
def release_reviewed(tag: str | None, ref: str, cwd: str, titles: templates.Titles, after: Release | None = None, run: Git = git) -> bool | Failure:
|
||||
"""Whether ref holds a commit titled as a release review opens, `Release review of <release>`: after tag, or anywhere where tag is None. A title that names no version, such as an epic's `Release review of ABC-12` (do_epic/finish.py), reviews no release.
|
||||
def reviewed_releases(tag: str | None, ref: str, cwd: str, titles: templates.Titles, after: Release | None = None, run: Git = git) -> frozenset[Release] | Failure:
|
||||
"""LastCut.reviews: each release that a commit on ref names in its title, as a release review opens, `Release review of <release>`. The commits read are those after tag, or all of them where tag is None. A title that names no version, such as an epic's `Release review of ABC-12` (do_epic/finish.py), reviews no release.
|
||||
|
||||
titles holds the project's title templates, and each commit title is read as the summary they give. after is the version a branch with no tag counts as cut, or None. A title counts only where its release is later than after, or than tag's version where after is None. A patch release cut beside the default branch and merged back leaves on ref, after its tag, the review of that patch, which reviews no later release.
|
||||
titles holds the project's title templates, and each commit title is read as the summary they give. after is the version a branch with no tag counts as cut, or None. A release counts only where it is later than after, or than tag's version where after is None. A patch release cut beside the default branch and merged back leaves on ref, after its tag, the review of that patch, which reviews no later release. pick_from needs that where the next release has no name.
|
||||
"""
|
||||
log = run("log", "--format=%s", f"{tag}..{ref}" if tag else ref, cwd=cwd)
|
||||
if isinstance(log, Failure):
|
||||
return log
|
||||
summaries = [titles.summary(line) for line in log.splitlines()]
|
||||
reviews = [summary.removeprefix("Release review of ") for summary in summaries if summary.startswith("Release review of ")]
|
||||
reviews = [summary.removeprefix(REVIEW_TITLE) for summary in summaries if summary.startswith(REVIEW_TITLE)]
|
||||
floor = after if after is not None else tagged(tag)
|
||||
return any((named := parsed(review)) is not None and (floor is None or named > floor) for review in reviews)
|
||||
return frozenset(named for review in reviews if (named := parsed(review)) is not None and (floor is None or named > floor))
|
||||
|
||||
|
||||
def todos_since(tag: str | None | Failure, ref: str, plan: str | None, cwd: str, run: Git = git) -> list[str] | Failure:
|
||||
@@ -200,7 +200,7 @@ def chunk_item(found: list[Item], cut: LastCut) -> Pick:
|
||||
def picked(weighed: Standing, cut: LastCut) -> Pick:
|
||||
"""chunk_item's pick, from the plan's items already weighed against cut."""
|
||||
upcoming = next_release(weighed, cut)
|
||||
return pick_from(upcoming, next_item(weighed.carried), cut.reviewed) if isinstance(upcoming, Upcoming) else upcoming
|
||||
return pick_from(upcoming, next_item(weighed.carried), cut.reviews) if isinstance(upcoming, Upcoming) else upcoming
|
||||
|
||||
|
||||
def next_release(weighed: Standing, cut: LastCut) -> Upcoming | Cut | Unknown:
|
||||
@@ -249,9 +249,10 @@ def has_unreleased(cut: LastCut) -> bool | Failure:
|
||||
return changes if isinstance(changes, Failure) else changes > 0
|
||||
|
||||
|
||||
def pick_from(upcoming: Upcoming, first: Item | None, reviewed: bool | Failure) -> Next | ReadyToCut | ReviewDue | Unplanned | Unknown:
|
||||
"""How the plan stands to upcoming, the next release. first is next_item's pick, which the pick holds where it is Next.
|
||||
def pick_from(upcoming: Upcoming, first: Item | None, reviews: frozenset[Release] | Failure) -> Next | ReadyToCut | ReviewDue | Unplanned | Unknown:
|
||||
"""How the plan stands to upcoming, the next release. first is next_item's pick, which the pick holds where it is Next. reviews is LastCut.reviews.
|
||||
|
||||
The next release's review has landed where reviews holds that release. Where the next release has no name, no title can name it, so a review of any release in reviews counts.
|
||||
Unknown where the next release holds no item and the unreleased changes cannot be counted, or work has landed and git cannot say whether a release review has.
|
||||
"""
|
||||
if upcoming.plan_is_current:
|
||||
@@ -260,8 +261,9 @@ def pick_from(upcoming: Upcoming, first: Item | None, reviewed: bool | Failure)
|
||||
return Unknown()
|
||||
if not upcoming.unreleased:
|
||||
return Unplanned(upcoming.release)
|
||||
if isinstance(reviewed, Failure):
|
||||
if isinstance(reviews, Failure):
|
||||
return Unknown()
|
||||
reviewed = bool(reviews) if upcoming.release is None else upcoming.release in reviews
|
||||
return ReadyToCut(upcoming.release) if reviewed else ReviewDue(upcoming.release)
|
||||
|
||||
|
||||
|
||||
@@ -145,16 +145,22 @@ class ChunkItem(unittest.TestCase):
|
||||
)
|
||||
for tag, changes, earliest, named, stands in cases:
|
||||
with self.subTest(tag=tag, changes=changes, earliest=earliest, named=named):
|
||||
self.assertEqual(release_standing.chunk_item(plan_under(earliest), release_standing.LastCut(tag, "", changes, naming(named), reviewed=True)), stands)
|
||||
self.assertEqual(release_standing.chunk_item(plan_under(earliest), release_standing.LastCut(tag, "", changes, naming(named), frozenset({(0, 9, 3), (1, 2, 4), (1, 3, 0)}))), stands)
|
||||
|
||||
def test_calls_a_release_review_due_where_the_next_release_holds_no_item_and_none_landed_since_the_cut(self):
|
||||
cut = lambda reviewed: release_standing.LastCut("v1.2.3", "", 4, naming({(1, 3, 0)}), reviewed)
|
||||
self.assertEqual(release_standing.chunk_item([], cut(False)), release_standing.ReviewDue((1, 3, 0)))
|
||||
self.assertEqual(release_standing.chunk_item([], cut(True)), release_standing.ReadyToCut((1, 3, 0)))
|
||||
cut = lambda reviews: release_standing.LastCut("v1.2.3", "", 4, naming({(1, 3, 0)}), reviews)
|
||||
self.assertEqual(release_standing.chunk_item([], cut(frozenset())), release_standing.ReviewDue((1, 3, 0)))
|
||||
self.assertEqual(release_standing.chunk_item([], cut(frozenset({(1, 3, 0)}))), release_standing.ReadyToCut((1, 3, 0)))
|
||||
self.assertEqual(release_standing.chunk_item([], cut(frozenset({(1, 2, 4), (1, 4, 0)}))), release_standing.ReviewDue((1, 3, 0)), "a review of another release reviews none of 1.3.0")
|
||||
self.assertEqual(release_standing.chunk_item([], cut(Failure("log unreadable"))), release_standing.Unknown())
|
||||
self.assertEqual(release_standing.chunk_item(plan_under((1, 3, 0)), cut(False)), release_standing.Next((1, 3, 0), one((1, 3, 0))), "a review matters only once the release's items run out")
|
||||
self.assertEqual(release_standing.chunk_item(plan_under((1, 3, 0)), cut(frozenset())), release_standing.Next((1, 3, 0), one((1, 3, 0))), "a review matters only once the release's items run out")
|
||||
self.assertEqual(release_standing.chunk_item([], release_standing.LastCut("v1.2.3", "", 0, naming({(1, 3, 0)}))), release_standing.Unplanned((1, 3, 0)))
|
||||
|
||||
def test_counts_any_later_release_review_where_the_next_release_has_no_name(self):
|
||||
cut = lambda reviews: release_standing.LastCut("v1.2.3", "", 4, [], reviews)
|
||||
self.assertEqual(release_standing.chunk_item([], cut(frozenset())), release_standing.ReviewDue(None))
|
||||
self.assertEqual(release_standing.chunk_item([], cut(frozenset({(1, 3, 0)}))), release_standing.ReadyToCut(None))
|
||||
|
||||
def test_takes_an_item_of_any_release_on_a_branch_with_no_tag(self):
|
||||
for release in ((0, 0, 0), (0, 0, 1), (0, 1, 0)):
|
||||
with self.subTest(release=release):
|
||||
@@ -166,10 +172,11 @@ class ChunkItem(unittest.TestCase):
|
||||
|
||||
def test_calls_a_release_that_never_had_a_tag_finished_once_the_plan_files_no_item_under_it(self):
|
||||
history = [HEADER + ROW.format(id=1, release="0.1.0") + ROW.format(id=2, release="0.1.1"), HEADER + ROW.format(id=2, release="0.1.1")]
|
||||
cut = lambda reviewed: release_standing.LastCut(None, "", 4, history, reviewed)
|
||||
self.assertEqual(release_standing.chunk_item(plan_under((0, 1, 1)), cut(False)), release_standing.ReviewDue((0, 1, 0)))
|
||||
self.assertEqual(release_standing.chunk_item(plan_under((0, 1, 1)), cut(True)), release_standing.ReadyToCut((0, 1, 0)))
|
||||
self.assertEqual(release_standing.chunk_item(plan_under((0, 1, 0)), cut(False)), release_standing.Next((0, 1, 0), one((0, 1, 0))))
|
||||
cut = lambda reviews: release_standing.LastCut(None, "", 4, history, reviews)
|
||||
self.assertEqual(release_standing.chunk_item(plan_under((0, 1, 1)), cut(frozenset())), release_standing.ReviewDue((0, 1, 0)))
|
||||
self.assertEqual(release_standing.chunk_item(plan_under((0, 1, 1)), cut(frozenset({(0, 1, 1)}))), release_standing.ReviewDue((0, 1, 0)))
|
||||
self.assertEqual(release_standing.chunk_item(plan_under((0, 1, 1)), cut(frozenset({(0, 1, 0)}))), release_standing.ReadyToCut((0, 1, 0)))
|
||||
self.assertEqual(release_standing.chunk_item(plan_under((0, 1, 0)), cut(frozenset())), release_standing.Next((0, 1, 0), one((0, 1, 0))))
|
||||
|
||||
def test_counts_a_dated_changelog_heading_as_cut_on_a_branch_with_no_tag(self):
|
||||
changelog = "# Changelog\n\n## Unreleased\n\n## 0.0.1 - 2026-10-03\n\n- Shipped.\n"
|
||||
@@ -211,30 +218,30 @@ class ChunkItem(unittest.TestCase):
|
||||
run = lambda *args: subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, cwd=repo, env=isolated_env(), text=True)
|
||||
run("init", "-q", "-b", "main")
|
||||
run("commit", "-q", "--allow-empty", "-m", "Release review of ABC-12")
|
||||
self.assertIs(release_standing.release_reviewed(None, "main", repo, BARE), False, "an epic's review reviews no release")
|
||||
self.assertEqual(release_standing.reviewed_releases(None, "main", repo, BARE), frozenset(), "an epic's review reviews no release")
|
||||
run("commit", "-q", "--allow-empty", "-m", "Release review of 0.1.0")
|
||||
run("tag", "v0.1.0")
|
||||
run("commit", "-q", "--allow-empty", "-m", "Ship item 4")
|
||||
self.assertIs(release_standing.release_reviewed("v0.1.0", "main", repo, BARE), False, "a review before the cut reviewed that release")
|
||||
self.assertEqual(release_standing.reviewed_releases("v0.1.0", "main", repo, BARE), frozenset(), "a review before the cut reviewed that release")
|
||||
run("commit", "-q", "--allow-empty", "-m", "Release review of 0.2.0")
|
||||
run("commit", "-q", "--allow-empty", "-m", "Answer architecture round 1: 0 🔴, 1 🟡 (0 misread); split loader")
|
||||
self.assertIs(release_standing.release_reviewed("v0.1.0", "main", repo, BARE), True)
|
||||
self.assertIs(release_standing.release_reviewed(None, "main", repo, BARE), True)
|
||||
self.assertEqual(release_standing.reviewed_releases("v0.1.0", "main", repo, BARE), frozenset({(0, 2, 0)}))
|
||||
self.assertEqual(release_standing.reviewed_releases(None, "main", repo, BARE), frozenset({(0, 1, 0), (0, 2, 0)}))
|
||||
run("commit", "-q", "--allow-empty", "-m", "Release review of ABC-12")
|
||||
self.assertIs(release_standing.release_reviewed("v0.1.0", "main", repo, BARE), True)
|
||||
self.assertIsInstance(release_standing.release_reviewed("v9.9.9", "main", repo, BARE), Failure)
|
||||
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut.reviewed, True)
|
||||
self.assertEqual(release_standing.reviewed_releases("v0.1.0", "main", repo, BARE), frozenset({(0, 2, 0)}))
|
||||
self.assertIsInstance(release_standing.reviewed_releases("v9.9.9", "main", repo, BARE), Failure)
|
||||
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut.reviews, frozenset({(0, 2, 0)}))
|
||||
run("tag", "v0.2.0")
|
||||
run("commit", "-q", "--allow-empty", "-m", "PAY-9 - Release review of 0.3.0")
|
||||
self.assertIs(release_standing.release_reviewed("v0.2.0", "main", repo, BARE), False)
|
||||
self.assertIs(release_standing.release_reviewed("v0.2.0", "main", repo, Titles("PAY-{id} - {summary}", "{summary}")), True)
|
||||
self.assertIs(release_standing.release_reviewed("v0.2.0", "main", repo, Titles("{summary}", "PAY-{id} - {summary}")), True, "a squash merge titles the commit as the pull request")
|
||||
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), Titles("PAY-{id} - {summary}", "{summary}")).cut.reviewed, True)
|
||||
self.assertEqual(release_standing.reviewed_releases("v0.2.0", "main", repo, BARE), frozenset())
|
||||
self.assertEqual(release_standing.reviewed_releases("v0.2.0", "main", repo, Titles("PAY-{id} - {summary}", "{summary}")), frozenset({(0, 3, 0)}))
|
||||
self.assertEqual(release_standing.reviewed_releases("v0.2.0", "main", repo, Titles("{summary}", "PAY-{id} - {summary}")), frozenset({(0, 3, 0)}), "a squash merge titles the commit as the pull request")
|
||||
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), Titles("PAY-{id} - {summary}", "{summary}")).cut.reviews, frozenset({(0, 3, 0)}))
|
||||
paths = {setting: pathlib.Path(repo, setting) for setting in SETTINGS} | {"plan": pathlib.Path(repo, "todo.md"), "changelog": pathlib.Path(repo, "CHANGELOG.md")}
|
||||
config = ProjectConfig("acme", pathlib.Path(repo, "folder"), pathlib.Path(repo), paths)
|
||||
self.assertIs(release_standing.project_plan(config, "main", repo).cut.reviewed, False)
|
||||
self.assertIs(release_standing.project_plan(dataclasses.replace(config, commit_title="PAY-{id} - {summary}"), "main", repo).cut.reviewed, True)
|
||||
self.assertIs(release_standing.project_plan(dataclasses.replace(config, pull_request_title="PAY-{id} - {summary}"), "main", repo).cut.reviewed, True)
|
||||
self.assertEqual(release_standing.project_plan(config, "main", repo).cut.reviews, frozenset())
|
||||
self.assertEqual(release_standing.project_plan(dataclasses.replace(config, commit_title="PAY-{id} - {summary}"), "main", repo).cut.reviews, frozenset({(0, 3, 0)}))
|
||||
self.assertEqual(release_standing.project_plan(dataclasses.replace(config, pull_request_title="PAY-{id} - {summary}"), "main", repo).cut.reviews, frozenset({(0, 3, 0)}))
|
||||
|
||||
def test_counts_no_release_review_of_the_patch_release_cut_beside_main_as_a_review_of_the_next(self):
|
||||
repo = tempfile.mkdtemp()
|
||||
@@ -250,9 +257,29 @@ class ChunkItem(unittest.TestCase):
|
||||
run("switch", "-q", "main")
|
||||
run("merge", "-q", "--strategy", "ours", "--no-ff", "-m", "Merge release 0.15.2 into main", "v0.15.2")
|
||||
# v0.15.2..main holds the review, which reviewed 0.15.2 itself, so 0.16.0 still waits for its own.
|
||||
self.assertIs(release_standing.release_reviewed("v0.15.2", "main", repo, BARE), False)
|
||||
self.assertEqual(release_standing.reviewed_releases("v0.15.2", "main", repo, BARE), frozenset())
|
||||
run("commit", "-q", "--allow-empty", "-m", "Release review of 0.16.0")
|
||||
self.assertIs(release_standing.release_reviewed("v0.15.2", "main", repo, BARE), True)
|
||||
self.assertEqual(release_standing.reviewed_releases("v0.15.2", "main", repo, BARE), frozenset({(0, 16, 0)}))
|
||||
|
||||
def test_counts_a_release_review_only_where_it_names_the_next_release(self):
|
||||
repo = tempfile.mkdtemp()
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", repo])
|
||||
run = lambda *args: subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, cwd=repo, env=isolated_env(), text=True)
|
||||
run("init", "-q", "-b", "main")
|
||||
pathlib.Path(repo, "todo.md").write_text(HEADER + ROW.format(id=1, release="0.16.0"))
|
||||
run("add", "todo.md")
|
||||
run("commit", "-q", "-m", "Cut release 0.15.1")
|
||||
run("tag", "v0.15.1")
|
||||
pathlib.Path(repo, "todo.md").write_text(HEADER)
|
||||
run("commit", "-q", "-a", "-m", "Ship item 1")
|
||||
pick = lambda: release_standing.chunk_item([], release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut)
|
||||
self.assertEqual(pick(), release_standing.ReviewDue((0, 16, 0)))
|
||||
run("commit", "-q", "--allow-empty", "-m", "Release review of 0.15.1")
|
||||
self.assertEqual(pick(), release_standing.ReviewDue((0, 16, 0)), "a review opened before todo.md renamed the release names the cut one")
|
||||
run("commit", "-q", "--allow-empty", "-m", "Release review of 0.17.0")
|
||||
self.assertEqual(pick(), release_standing.ReviewDue((0, 16, 0)), "a review of 0.17.0 reviews none of 0.16.0")
|
||||
run("commit", "-q", "--allow-empty", "-m", "Release review of 0.16.0")
|
||||
self.assertEqual(pick(), release_standing.ReadyToCut((0, 16, 0)))
|
||||
|
||||
def test_counts_no_release_review_of_a_release_cut_under_a_dated_heading_on_a_branch_with_no_tag(self):
|
||||
repo = tempfile.mkdtemp()
|
||||
@@ -263,13 +290,13 @@ class ChunkItem(unittest.TestCase):
|
||||
pathlib.Path(repo, "CHANGELOG.md").write_text("# Changelog\n\n## 0.0.1 - 2026-10-03\n")
|
||||
run("add", "CHANGELOG.md")
|
||||
run("commit", "-q", "-m", "Cut 0.0.1")
|
||||
self.assertIs(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut.reviewed, False, "that review reviewed 0.0.1, which is cut")
|
||||
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut.reviews, frozenset(), "that review reviewed 0.0.1, which is cut")
|
||||
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut.commits, 0, "no commit follows the one that cut 0.0.1")
|
||||
self.assertEqual(release_standing.chunk_item([], release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut), release_standing.Unplanned(None))
|
||||
run("commit", "-q", "--allow-empty", "-m", "Ship item 2")
|
||||
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut.commits, 1)
|
||||
run("commit", "-q", "--allow-empty", "-m", "Release review of 0.1.0")
|
||||
self.assertIs(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut.reviewed, True)
|
||||
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut.reviews, frozenset({(0, 1, 0)}))
|
||||
|
||||
def test_counts_from_the_commit_on_the_named_branch_that_first_added_the_dated_heading_to_changelog_md(self):
|
||||
repo = tempfile.mkdtemp()
|
||||
@@ -319,16 +346,41 @@ class ChunkItem(unittest.TestCase):
|
||||
pathlib.Path(repo, "todo.md").write_text(HEADER + ROW.format(id=1, release="0.2.0"))
|
||||
run("add", "todo.md")
|
||||
run("commit", "-q", "-m", "Plan")
|
||||
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut, release_standing.LastCut(None, "", 1, [HEADER + ROW.format(id=1, release="0.2.0")], False))
|
||||
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut, release_standing.LastCut(None, "", 1, [HEADER + ROW.format(id=1, release="0.2.0")], frozenset()))
|
||||
run("tag", "v0.1.0")
|
||||
pathlib.Path(repo, "CHANGELOG.md").write_text("# Changelog\n\n## 0.2.0 - 2026-10-03\n")
|
||||
run("add", "CHANGELOG.md")
|
||||
run("commit", "-q", "-m", "Date 0.2.0")
|
||||
held = release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE)
|
||||
self.assertEqual(held.plan, plan_of(HEADER + ROW.format(id=1, release="0.2.0")))
|
||||
self.assertEqual(held.cut, release_standing.LastCut("v0.1.0", "# Changelog\n\n## 0.2.0 - 2026-10-03\n", 1, [HEADER + ROW.format(id=1, release="0.2.0")], False))
|
||||
self.assertEqual(held.cut, release_standing.LastCut("v0.1.0", "# Changelog\n\n## 0.2.0 - 2026-10-03\n", 1, [HEADER + ROW.format(id=1, release="0.2.0")], frozenset()))
|
||||
self.assertEqual(release_standing.chunk_item(plan_under((0, 2, 0)), held.cut), release_standing.Next((0, 2, 0), one((0, 2, 0))))
|
||||
|
||||
def test_reads_the_plan_as_the_last_tag_holds_it_and_as_each_later_commit_left_it(self):
|
||||
repo = tempfile.mkdtemp()
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", repo])
|
||||
run = lambda *args: subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, cwd=repo, env=isolated_env(), text=True)
|
||||
run("init", "-q", "-b", "main")
|
||||
before, tagged, after = (HEADER + ROW.format(id=1, release=release) for release in ("0.1.0", "0.2.0", "0.3.0"))
|
||||
for text, title in ((before, "Plan 0.1.0"), (tagged, "Plan 0.2.0")):
|
||||
pathlib.Path(repo, "todo.md").write_text(text)
|
||||
run("add", "todo.md")
|
||||
run("commit", "-q", "-m", title)
|
||||
run("tag", "v0.1.0")
|
||||
pathlib.Path(repo, "todo.md").write_text(after)
|
||||
run("commit", "-q", "-am", "Plan 0.3.0")
|
||||
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut.todos_since, [tagged, after])
|
||||
|
||||
def test_gives_gits_own_failure_as_the_reviews_where_the_tags_cannot_be_read(self):
|
||||
repo = tempfile.mkdtemp()
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", repo])
|
||||
run = lambda *args: subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, cwd=repo, env=isolated_env(), text=True)
|
||||
run("init", "-q", "-b", "main")
|
||||
run("commit", "-q", "--allow-empty", "-m", "Release review of 0.2.0")
|
||||
no_tags = lambda *args, cwd: Failure("git tag failed: no tags") if "tag" in args else release_standing.git(*args, cwd=cwd)
|
||||
cut = release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE, no_tags).cut
|
||||
self.assertEqual((cut.tag, cut.reviews), (Failure("git tag failed: no tags"), Failure("git tag failed: no tags")))
|
||||
|
||||
def test_reads_a_plan_and_a_changelog_outside_the_checkout_as_they_stand(self):
|
||||
repo, folder = tempfile.mkdtemp(), pathlib.Path(tempfile.mkdtemp())
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", repo, str(folder)])
|
||||
@@ -339,13 +391,13 @@ class ChunkItem(unittest.TestCase):
|
||||
run("commit", "-q", "-m", "A todo.md the project's owners keep")
|
||||
held = release_standing.default_plan(repo, "main", plan_at(folder / "todo.md", None), FileStore(folder / "CHANGELOG.md", None), BARE)
|
||||
self.assertIsInstance(held.plan, NoItemsTable, "neither file exists yet")
|
||||
self.assertEqual(held.cut, release_standing.LastCut(None, "", 1, [], False))
|
||||
self.assertEqual(held.cut, release_standing.LastCut(None, "", 1, [], frozenset()))
|
||||
plan = HEADER + ROW.format(id=2, release="0.2.0")
|
||||
(folder / "todo.md").write_text(plan)
|
||||
(folder / "CHANGELOG.md").write_text("# Changelog\n\n## 0.1.0 - 2026-10-03\n")
|
||||
held = release_standing.default_plan(repo, "main", plan_at(folder / "todo.md", None), FileStore(folder / "CHANGELOG.md", None), BARE)
|
||||
self.assertEqual(held.plan, plan_of(plan))
|
||||
self.assertEqual(held.cut, release_standing.LastCut(None, "# Changelog\n\n## 0.1.0 - 2026-10-03\n", 1, [], False), "no commit holds an earlier plan")
|
||||
self.assertEqual(held.cut, release_standing.LastCut(None, "# Changelog\n\n## 0.1.0 - 2026-10-03\n", 1, [], frozenset()), "no commit holds an earlier plan")
|
||||
(folder / "todo.md").write_bytes(b"\xff")
|
||||
unreadable = release_standing.default_plan(repo, "main", plan_at(folder / "todo.md", None), changelog_of(repo), BARE)
|
||||
self.assertEqual((unreadable.plan, unreadable.cut.todos_since), (Failure(f"{folder}/todo.md: not UTF-8"), []))
|
||||
@@ -363,7 +415,7 @@ class ChunkItem(unittest.TestCase):
|
||||
# Only this git knows where the checkout is, so a read that goes round it fails.
|
||||
there = lambda *args, cwd: release_standing.git(*args, cwd=repo)
|
||||
held = release_standing.default_plan("/nowhere", "main", plan_in("/nowhere"), changelog_of("/nowhere"), BARE, there)
|
||||
self.assertEqual(held, release_standing.DefaultPlan(plan_of(plan), release_standing.LastCut(None, "# Changelog\n\n## 0.1.0 - 2026-10-03\n", 0, [plan], False)))
|
||||
self.assertEqual(held, release_standing.DefaultPlan(plan_of(plan), release_standing.LastCut(None, "# Changelog\n\n## 0.1.0 - 2026-10-03\n", 0, [plan], frozenset())))
|
||||
|
||||
def test_counts_the_changes_unreleased_since_the_last_cut_by_unreleased_entries_and_else_by_commits(self):
|
||||
changelog = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n"
|
||||
|
||||
@@ -31,6 +31,36 @@ def package_imports(bin_folder: pathlib.Path) -> dict[str, set[str]]:
|
||||
return imported
|
||||
|
||||
|
||||
def imported_names(module: pathlib.Path) -> list[str]:
|
||||
"""The dotted name of each thing the file module imports, as `a.b.c` for `from a.b import c`. A deferred import inside a function counts."""
|
||||
found: list[str] = []
|
||||
for node in ast.walk(ast.parse(module.read_text(encoding="utf-8"))):
|
||||
found += [alias.name for alias in node.names] if isinstance(node, ast.Import) else [f"{node.module}.{alias.name}" for alias in node.names] if isinstance(node, ast.ImportFrom) and node.level == 0 and node.module else []
|
||||
return found
|
||||
|
||||
|
||||
def part_imports(package: pathlib.Path) -> dict[str, set[str]]:
|
||||
"""Each part of the package, with the other parts of it that its modules import, tests aside. A part is a module at the package's top, or a folder there with every module under it: a folder states that its modules belong together, so the top may not lean on a folder that leans on the top."""
|
||||
imported: dict[str, set[str]] = {}
|
||||
for module in package.rglob("*.py"):
|
||||
if module.name.startswith("test_"):
|
||||
continue
|
||||
part = module.relative_to(package).parts[0].removesuffix(".py")
|
||||
inside = [name.split(".")[1] for name in imported_names(module) if name.startswith(f"{package.name}.")]
|
||||
imported.setdefault(part, set()).update(other for other in inside if other != part)
|
||||
return imported
|
||||
|
||||
|
||||
def part_cycles(bin_folder: pathlib.Path) -> dict[str, list[str]]:
|
||||
"""Each package under bin_folder whose parts import in a cycle, with the parts along one."""
|
||||
found = {}
|
||||
for package in sorted(init.parent for init in bin_folder.glob("*/__init__.py")):
|
||||
imported = part_imports(package)
|
||||
if cycle(imported):
|
||||
found[package.name] = cycle(imported)
|
||||
return found
|
||||
|
||||
|
||||
# The entry points that drive chunks. What two of them need lives in bin/chunk_driver/, so no other package imports one, its tests included.
|
||||
DRIVERS = ("do_epic", "loop_claude")
|
||||
|
||||
@@ -62,18 +92,16 @@ def imports_of_test_modules(bin_folder: pathlib.Path) -> list[str]:
|
||||
found = []
|
||||
for module in sorted(bin_folder.rglob("*.py")):
|
||||
package = module.relative_to(bin_folder).parts[0]
|
||||
for node in ast.walk(ast.parse(module.read_text(encoding="utf-8"))):
|
||||
names = [alias.name for alias in node.names] if isinstance(node, ast.Import) else [f"{node.module}.{alias.name}" for alias in node.names] if isinstance(node, ast.ImportFrom) and node.level == 0 and node.module else []
|
||||
for name in names:
|
||||
top, *below = name.split(".")
|
||||
tests = [part for part in below if part.startswith("test_")]
|
||||
if tests and top != package:
|
||||
found.append(f"{module.relative_to(bin_folder)} imports {name[:name.index(tests[0]) + len(tests[0])]}")
|
||||
for name in imported_names(module):
|
||||
top, *below = name.split(".")
|
||||
tests = [part for part in below if part.startswith("test_")]
|
||||
if tests and top != package:
|
||||
found.append(f"{module.relative_to(bin_folder)} imports {name[:name.index(tests[0]) + len(tests[0])]}")
|
||||
return sorted(set(found))
|
||||
|
||||
|
||||
def cycle(imported: dict[str, set[str]]) -> list[str]:
|
||||
"""One cycle among the packages, as the packages along it; empty where there is none."""
|
||||
"""One cycle among the packages or parts that imported names, as those along it; empty where there is none."""
|
||||
try:
|
||||
graphlib.TopologicalSorter(imported).prepare()
|
||||
except graphlib.CycleError as found:
|
||||
@@ -135,6 +163,21 @@ class PackageCycles(unittest.TestCase):
|
||||
})
|
||||
self.assertEqual(package_imports(folder), {"a": {"b"}, "b": {"a"}, "c": set()})
|
||||
|
||||
def test_no_part_of_a_package_imports_one_that_imports_it_back(self):
|
||||
self.assertEqual(part_cycles(ROOT / "bin"), {}, "move what both parts need into a module at the package's top that imports neither")
|
||||
|
||||
def test_reads_a_folder_of_a_package_as_one_part_and_a_module_at_its_top_as_another(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
folder = pathlib.Path(temp)
|
||||
tree(folder, {
|
||||
"a/__init__.py": "", "a/main.py": "from a.kind.plant import x\nfrom a import shared\nimport b.kind\n",
|
||||
"a/shared.py": "def f():\n\tfrom a.kind import plant\n",
|
||||
"a/kind/__init__.py": "", "a/kind/plant.py": "import a.shared\nfrom a.kind.deep import other\n", "a/kind/deep/other.py": "import a.kind.plant\n",
|
||||
"a/test_shared.py": "import a.main\n", "a/kind/test_plant.py": "import a.main\n",
|
||||
})
|
||||
self.assertEqual(part_imports(folder / "a"), {"__init__": set(), "main": {"kind", "shared"}, "shared": {"kind"}, "kind": {"shared"}})
|
||||
self.assertEqual(sorted(cycle(part_imports(folder / "a"))[:2]), ["kind", "shared"])
|
||||
|
||||
def test_a_cycle_through_a_deferred_import_is_found(self):
|
||||
self.assertEqual(sorted(cycle({"a": {"b"}, "b": {"a"}})[:2]), ["a", "b"])
|
||||
self.assertEqual(cycle({"a": {"b"}, "b": set()}), [])
|
||||
|
||||
@@ -7,7 +7,7 @@ import re
|
||||
from failure import Failure
|
||||
from mutate_changes import in_diff_tools
|
||||
from mutate_changes.changed_lines import is_test
|
||||
from task_bench.planted_mutant import Mutant
|
||||
from task_bench.bugs.planted_mutant import Mutant
|
||||
from mutate_changes.tool_process import Run
|
||||
|
||||
# What each of Gremlins v0.6.0's mutators writes in place of a token: `tokenMutations` in its internal/engine/mappings.go, under the
|
||||
@@ -7,8 +7,8 @@ import re
|
||||
from mutate_changes.tool_process import failed, remove, Run
|
||||
from failure import Failure
|
||||
from mutate_changes import in_diff_tools
|
||||
from task_bench.planted_mutant import Mutant
|
||||
from task_bench.scratch_copy import scratch_copy
|
||||
from task_bench.bugs.planted_mutant import Mutant
|
||||
from task_bench.bugs.scratch_copy import scratch_copy
|
||||
|
||||
# Where Infection writes its JSON log, from the copy's top.
|
||||
LOG = "infection-log.json"
|
||||
@@ -6,9 +6,9 @@ import re
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from task_bench import go_bugs, php_bugs, python_bugs, rust_bugs, typescript_bugs
|
||||
from task_bench.bugs import go_bugs, php_bugs, python_bugs, rust_bugs, typescript_bugs
|
||||
from mutate_changes.changed_lines import is_test, STRYKER
|
||||
from task_bench.planted_mutant import Mutant
|
||||
from task_bench.bugs.planted_mutant import Mutant
|
||||
from mutate_changes.tool_process import Run
|
||||
|
||||
# A place as `larv-review places` prints it: `<path>:<line>` in backticks.
|
||||
@@ -2,7 +2,7 @@
|
||||
import re
|
||||
import typing
|
||||
|
||||
from task_bench.figures import Side
|
||||
from task_bench.tasks import Side
|
||||
|
||||
HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@", re.MULTILINE)
|
||||
|
||||
@@ -4,7 +4,7 @@ import re
|
||||
|
||||
from failure import Failure
|
||||
from mutate_changes.mutmut_tool import killed_by_mutmut
|
||||
from task_bench.planted_mutant import Mutant
|
||||
from task_bench.bugs.planted_mutant import Mutant
|
||||
from mutate_changes.tool_process import Run
|
||||
|
||||
# pytest's report of the failed tests, in its default form or with --tb=short: under this heading, a section per test.
|
||||
@@ -5,7 +5,7 @@ import re
|
||||
|
||||
from failure import Failure
|
||||
from mutate_changes import in_diff_tools
|
||||
from task_bench.planted_mutant import Mutant
|
||||
from task_bench.bugs.planted_mutant import Mutant
|
||||
from mutate_changes.tool_process import remove, Run, scratch_folder
|
||||
|
||||
# What cargo-mutants 27.1.0 writes after the code it put in, as in `sum -= /* ~ changed by cargo-mutants ~ */ item;`. A planted
|
||||
@@ -5,12 +5,12 @@ import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
||||
|
||||
from failure import Failure
|
||||
from task_bench.go_bugs import go_files, killed_mutants, reapplied, task_text
|
||||
from task_bench.bugs.go_bugs import go_files, killed_mutants, reapplied, task_text
|
||||
from mutate_changes import in_diff_tools
|
||||
from task_bench.planted_mutant import Mutant
|
||||
from task_bench.bugs.planted_mutant import Mutant
|
||||
from mutate_changes.tool_process import Ran
|
||||
|
||||
# go test's report of an assertion that failed in a subtest, then of one whose message runs over two lines.
|
||||
@@ -8,11 +8,11 @@ import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
||||
|
||||
from task_bench.php_bugs import changed, killed_mutants, task_text
|
||||
from task_bench.bugs.php_bugs import changed, killed_mutants, task_text
|
||||
from failure import Failure
|
||||
from task_bench.planted_mutant import Mutant, mutated
|
||||
from task_bench.bugs.planted_mutant import Mutant, mutated
|
||||
from mutate_changes.tool_process import Ran
|
||||
|
||||
PICK = """<?php
|
||||
@@ -3,11 +3,11 @@ import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
||||
|
||||
from task_bench.plant import drawn, killed_mutants, Language, LANGUAGES, place_files, task_text
|
||||
from task_bench.bugs.plant import drawn, killed_mutants, Language, LANGUAGES, place_files, task_text
|
||||
from failure import Failure
|
||||
from task_bench.planted_mutant import Mutant
|
||||
from task_bench.bugs.planted_mutant import Mutant
|
||||
|
||||
PLACES = """## 2026-11-19T22:33:15Z, PR #646 at a357cc7b
|
||||
|
||||
@@ -3,9 +3,9 @@ import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
||||
|
||||
from task_bench.planted_mutant import bug_at_sides, line_at_head, Mutant, mutated
|
||||
from task_bench.bugs.planted_mutant import bug_at_sides, line_at_head, Mutant, mutated
|
||||
|
||||
|
||||
class MutatedTest(unittest.TestCase):
|
||||
@@ -4,11 +4,11 @@ import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
||||
|
||||
from failure import Failure
|
||||
from task_bench.python_bugs import killed_mutants, task_text
|
||||
from task_bench.planted_mutant import Mutant, mutated
|
||||
from task_bench.bugs.python_bugs import killed_mutants, task_text
|
||||
from task_bench.bugs.planted_mutant import Mutant, mutated
|
||||
from mutate_changes.tool_process import Ran
|
||||
|
||||
CALC = "def double(n):\n\treturn n * 2\n\n\ndef triple(n):\n\treturn (\n\t\tn * 3\n\t)\n"
|
||||
@@ -8,11 +8,11 @@ import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
||||
|
||||
from task_bench.rust_bugs import changed, killed_mutants, task_text
|
||||
from task_bench.bugs.rust_bugs import changed, killed_mutants, task_text
|
||||
from failure import Failure
|
||||
from task_bench.planted_mutant import Mutant, mutated
|
||||
from task_bench.bugs.planted_mutant import Mutant, mutated
|
||||
from mutate_changes.tool_process import Ran
|
||||
|
||||
PICK = b"""pub fn first(items: &[i32]) -> Option<i32> {
|
||||
@@ -6,10 +6,10 @@ import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
||||
|
||||
from failure import Failure
|
||||
from task_bench.scratch_copy import scratch_copy
|
||||
from task_bench.bugs.scratch_copy import scratch_copy
|
||||
|
||||
|
||||
class ScratchCopyTest(unittest.TestCase):
|
||||
+3
-3
@@ -9,11 +9,11 @@ import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
||||
|
||||
from task_bench.typescript_bugs import changed, killed_mutants, task_text
|
||||
from task_bench.bugs.typescript_bugs import changed, killed_mutants, task_text
|
||||
from failure import Failure
|
||||
from task_bench.planted_mutant import Mutant, mutated
|
||||
from task_bench.bugs.planted_mutant import Mutant, mutated
|
||||
from mutate_changes.tool_process import Ran
|
||||
|
||||
PICK = """export function pick(items: number[], floor: number): number {
|
||||
@@ -7,8 +7,8 @@ import re
|
||||
from mutate_changes.tool_process import failed, remove, Run
|
||||
from failure import Failure
|
||||
from mutate_changes import in_diff_tools
|
||||
from task_bench.planted_mutant import Mutant
|
||||
from task_bench.scratch_copy import scratch_copy
|
||||
from task_bench.bugs.planted_mutant import Mutant
|
||||
from task_bench.bugs.scratch_copy import scratch_copy
|
||||
|
||||
# Where Stryker 10.1.1's json reporter writes, from the folder it runs in. Only the project's own Stryker config can set another
|
||||
# path, so the planter reads this one.
|
||||
@@ -3,21 +3,20 @@ that builds it, and acceptance tests Haiku never sees. A feature counts at the t
|
||||
at both before it is built, and pass at both with the reference patch.
|
||||
|
||||
A data source Haiku adds is such a folder too, with a `generate-register` beside the three parts: the script that writes the
|
||||
register Haiku imports, as task_bench.registers runs it. It counts as a feature does, in trees that hold its register."""
|
||||
register Haiku imports, as task_bench.features.registers runs it. It counts as a feature does, in trees that hold its register."""
|
||||
import itertools
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import typing
|
||||
|
||||
from task_bench.tasks import Bench, check_made, committed, DATA_SOURCE, FEATURE, Kind, on_disk, Planned, Task
|
||||
from task_bench.tasks import Bench, check_made, committed, DATA_SOURCE, FEATURE, Kind, on_disk, Planned, Side, SIDES, Task
|
||||
from project_config.settings import BENCH_TASKS, CONFIG
|
||||
from failure import Failure
|
||||
from task_bench.registers import GENERATE, NotGenerated, registered_trees
|
||||
from task_bench.features.registers import GENERATE, NotGenerated, registered_trees
|
||||
from project_config.main import located
|
||||
from mutate_changes.tool_process import Ran
|
||||
from task_bench.runs import ran_tests, TimedOut
|
||||
from task_bench.figures import Side, SIDES
|
||||
|
||||
SPEC = "spec.md"
|
||||
PATCH = "reference.patch"
|
||||
@@ -5,10 +5,9 @@ import os
|
||||
import pathlib
|
||||
import shutil
|
||||
|
||||
from task_bench.tasks import Bench, committed, on_disk
|
||||
from task_bench.tasks import Bench, committed, on_disk, Side, SIDES
|
||||
from task_bench.runs import Containers, entries, in_tree, NotStarted, run_in_image, TimedOut
|
||||
from failure import Failure
|
||||
from task_bench.figures import Side, SIDES
|
||||
|
||||
# A panel of three readers, seated as the README's audience, picked the name on 2026-11-23: each had it first or second, over
|
||||
# `register`, which reads as a data file, and `generate-source`, which two read as generating source code.
|
||||
@@ -1,6 +1,6 @@
|
||||
"""The features task-bench has Haiku rebuild: those the project shipped, read from its history. A shipped feature is a chunk on
|
||||
the base's first-parent line that took an item out of the plan, as branch_chunks cuts that line. Once its change is out of each
|
||||
side's tree, it is a feature as task_bench.feature_tasks has it. `task-bench --help` says what Haiku is told and how a rebuild
|
||||
side's tree, it is a feature as task_bench.features.feature_tasks has it. `task-bench --help` says what Haiku is told and how a rebuild
|
||||
is checked."""
|
||||
import functools
|
||||
import os
|
||||
@@ -9,8 +9,8 @@ import re
|
||||
import shutil
|
||||
import typing
|
||||
|
||||
from task_bench.feature_tasks import ACCEPTANCE, Feature, PATCH, why_passed_over
|
||||
from task_bench.tasks import Bench, committed, on_disk, Planned, Task
|
||||
from task_bench.features.feature_tasks import ACCEPTANCE, Feature, PATCH, why_passed_over
|
||||
from task_bench.tasks import Bench, committed, on_disk, Planned, Side, SIDES, Task
|
||||
from branch_chunks.read import cut_with_shipped, unsupported
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import Git
|
||||
@@ -18,7 +18,6 @@ from plan.todo_table import Item, tagline_text
|
||||
from project_config.main import located
|
||||
from task_bench.runs import of_tests
|
||||
from project_config.settings import RECORDS
|
||||
from task_bench.figures import Side, SIDES
|
||||
|
||||
# Why a feature that landed by fast-forward is passed over: no earlier chunk says where its commits start, or its branch merged
|
||||
# the default branch into itself, so its commits hold what other features built.
|
||||
+3
-3
@@ -12,13 +12,13 @@ import tempfile
|
||||
import textwrap
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
||||
|
||||
from task_bench.tasks import Asked, Bench, FEATURE
|
||||
from task_bench.test_task_bench import BASE_CODE, DOCKER, HEAD_CODE, InTurn, TESTS
|
||||
from task_bench.runs import Containers, TimedOut
|
||||
from failure import Failure
|
||||
from task_bench.feature_tasks import Feature, features, why_passed_over
|
||||
from task_bench.features.feature_tasks import Feature, features, why_passed_over
|
||||
from test_env import isolated_env
|
||||
from task_bench import main
|
||||
from mutate_changes.tool_process import Ran
|
||||
@@ -121,7 +121,7 @@ class BenchOfTasksCase(unittest.TestCase):
|
||||
|
||||
def bench(self, **given: str):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as self.progress:
|
||||
return main.bench({**self.given, **given}, self.env, lambda home: "", self.home)
|
||||
return main.bench({**self.given, **given}, self.env, lambda home: "", self.home, "task-bench-0123456789ab", "1234:5678")
|
||||
|
||||
|
||||
class FeatureBenchTest(BenchOfTasksCase):
|
||||
@@ -8,14 +8,14 @@ import tempfile
|
||||
import textwrap
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
||||
|
||||
from task_bench.test_feature_tasks import added, BenchOfTasksCase, feature
|
||||
from task_bench.features.test_feature_tasks import added, BenchOfTasksCase, feature
|
||||
from task_bench.tasks import Asked, Bench, DATA_SOURCE
|
||||
from task_bench.runs import Containers, TimedOut
|
||||
from failure import Failure
|
||||
from task_bench.feature_tasks import features
|
||||
from task_bench.registers import generated, NotGenerated, registered_trees
|
||||
from task_bench.features.feature_tasks import features
|
||||
from task_bench.features.registers import generated, NotGenerated, registered_trees
|
||||
from task_bench import main
|
||||
from mutate_changes.tool_process import Ran
|
||||
|
||||
+3
-3
@@ -10,14 +10,14 @@ import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
||||
|
||||
from task_bench.test_feature_tasks import ACCEPTANCE, BenchOfTasksCase
|
||||
from task_bench.features.test_feature_tasks import ACCEPTANCE, BenchOfTasksCase
|
||||
from task_bench.test_task_bench import BASE_CODE, HEAD_CODE
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import git
|
||||
from task_bench import main
|
||||
from task_bench.shipped_features import MERGED_IN, read_shipped
|
||||
from task_bench.features.shipped_features import MERGED_IN, read_shipped
|
||||
from branch_chunks.read import READ_AT
|
||||
|
||||
HEADER = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves |\n|---|---|---|---|---|---|---|---|---|---|---|\n"
|
||||
@@ -8,7 +8,7 @@ import typing
|
||||
from claude_code.entries import AssistantTurn, Entry, Text, tool_calls, ToolCall, ToolResult, ToolResults
|
||||
from task_bench.runs import HOME, WORK
|
||||
from reading_cost.measure import reads_of
|
||||
from task_bench.figures import Side
|
||||
from task_bench.tasks import Side
|
||||
|
||||
# A trace keeps the first TEXT_LINES lines of the model's text between two calls, and the first TEXT_WIDTH characters of each.
|
||||
TEXT_LINES = 3
|
||||
@@ -5,7 +5,7 @@ import typing
|
||||
|
||||
from review_rules.comprehension_history import appended
|
||||
from task_bench.tasks import BUG, KINDS
|
||||
from task_bench.gather import DIGEST
|
||||
from task_bench.figures.gather import DIGEST
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import Git
|
||||
from record_store.held import Held
|
||||
@@ -13,12 +13,12 @@ from larv_review.history_commands import held_history
|
||||
from record_store.stores import RecordStore
|
||||
from text_files.utc_stamp import utc
|
||||
|
||||
# The digest's line that names the commits, as task_bench.digest.digest writes it.
|
||||
# The digest's line that names the commits, as task_bench.figures.digest.digest writes it.
|
||||
SIDES = re.compile(r"^Base ([0-9a-f]{7,40}), head ([0-9a-f]{7,40})\.", re.M)
|
||||
# How the table's three rows over every task open, as task_bench.figures.table writes them: the base, the head and the head's change.
|
||||
# How the table's three rows over every task open, as task_bench.figures.run_figures.table writes them: the base, the head and the head's change.
|
||||
OVER_ALL = "| All |"
|
||||
COMMIT_LENGTH = 8
|
||||
# What a bench's name says its tasks are, by how its table's header opens, as task_bench.figures.table writes it. A bench of
|
||||
# What a bench's name says its tasks are, by how its table's header opens, as task_bench.figures.run_figures.table writes it. A bench of
|
||||
# bugs has the bare name.
|
||||
TASKS_NAMED = {f"| {kind.noun.capitalize()} |": f" {tasks}" for tasks, kind in KINDS.items() if kind is not BUG}
|
||||
|
||||
@@ -7,13 +7,11 @@ from claude_code.entries import Entry, entry_from, tool_calls, ToolCall
|
||||
from failure import Failure
|
||||
from task_bench.runs import HOME, WORK
|
||||
from reading_cost.measure import reads_of
|
||||
from task_bench.tasks import Side, SIDES
|
||||
from claude_code.tokens import Tokens, tokens_of
|
||||
|
||||
# The tools that read or search without a shell. A Bash call counts where `reads_of` finds a file it reads.
|
||||
READING_TOOLS = frozenset({"Glob", "Grep", "Read"})
|
||||
# A bench's two sides: the commit before the change and the one after it.
|
||||
Side = typing.Literal["base", "head"]
|
||||
SIDES: tuple[Side, Side] = ("base", "head")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -4,9 +4,9 @@ import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
||||
|
||||
from task_bench.digest import decoys, digest, Run, TaskRuns, trace
|
||||
from task_bench.figures.digest import decoys, digest, Run, TaskRuns, trace
|
||||
from claude_code.entries import entries_of, Entry
|
||||
|
||||
|
||||
@@ -9,10 +9,10 @@ import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
||||
|
||||
from failure import Failure
|
||||
from task_bench.gather import gather, PROMPT
|
||||
from task_bench.figures.gather import gather, PROMPT
|
||||
from test_env import isolated_env
|
||||
from task_bench import main
|
||||
|
||||
+2
-2
@@ -6,9 +6,9 @@ import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
||||
|
||||
from task_bench.record_figures import bench_appended, bench_entry, recorded_bench
|
||||
from task_bench.figures.record_figures import bench_appended, bench_entry, recorded_bench
|
||||
from review_rules.comprehension_history import entries
|
||||
from failure import Failure
|
||||
from record_store.held import Held
|
||||
@@ -4,11 +4,11 @@ import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
||||
|
||||
from task_bench import figures as bench_figures
|
||||
from task_bench.figures import run_figures as bench_figures
|
||||
from failure import Failure
|
||||
from task_bench.figures import Figures, Result, table
|
||||
from task_bench.figures.run_figures import Figures, Result, table
|
||||
from claude_code.entries import json_objects
|
||||
from claude_code.tokens import Tokens
|
||||
|
||||
+165
-82
@@ -159,7 +159,7 @@ features the heading reads `task-bench features of <branch>: ...` instead, for o
|
||||
of <branch>: ...`, and for one of shipped features `task-bench shipped-features of <branch>: ...`. No tool reads the entry as a ruling or a scoring run. The bench's last line says where the entry went. A bench that fails or stops doesn't record anything.
|
||||
|
||||
`task-bench gather`, run in the same checkout, turns the digest into plan items. It starts a claude on the project's rung, the
|
||||
cheapest rung of the model loop-claude runs the project on, with the digest and the prompt in gather-prompt.md beside this file.
|
||||
cheapest rung of the model loop-claude runs the project on, with the digest and the prompt in bin/task_bench/figures/gather-prompt.md.
|
||||
That claude files an item with `todo-item add` for each place the runs show to be hard, and leaves the plan's file uncommitted.
|
||||
gather prints that claude's answer and removes the bench's folder. Where claude fails, the folder stays, for another try.
|
||||
|
||||
@@ -196,26 +196,26 @@ import time
|
||||
import typing
|
||||
import uuid
|
||||
|
||||
from task_bench.tasks import Asked, Bench, BUG, check_made, committed, Kind, KINDS, on_disk, Planned, SHIPPED, Task, tests_in_copy
|
||||
from task_bench.planted_mutant import bug_at_sides, Mutant
|
||||
from task_bench.tasks import Asked, Bench, BUG, check_made, committed, DATA_SOURCE, FEATURE, Kind, KINDS, on_disk, Planned, SHIPPED, Side, SIDES, Task, tests_in_copy
|
||||
from task_bench.bugs.planted_mutant import bug_at_sides, Mutant
|
||||
from claude_code.reply import Claude
|
||||
from task_bench.bench_folder import clear_left, held
|
||||
from task_bench.runs import closed, Containers, docker_cli, fix_attempted, MEMORY_MIB, opened, ran_tests, TimedOut, TOKEN, WORK
|
||||
from task_bench.digest import counted, digest, Run, TaskRuns
|
||||
from task_bench.figures.digest import counted, digest, Run, TaskRuns
|
||||
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, place_files, task_text
|
||||
from claude_code.entries import entry_from, json_objects
|
||||
from task_bench.figures.gather import DIGEST, gather, run_claude
|
||||
from task_bench.bugs.plant import drawn, killed_mutants, place_files, task_text
|
||||
from claude_code.entries import Entry, entry_from, json_objects
|
||||
from mutate_changes.tool_process import failed, Ran, run_tool
|
||||
from failure import Failure
|
||||
from task_bench.feature_tasks import feature_tasks, Features, read_features
|
||||
from task_bench.figures import figures, Result, Side, SIDES, table
|
||||
from task_bench.features.feature_tasks import feature_tasks, Features, read_features
|
||||
from task_bench.figures.run_figures import Figures, figures, Result, 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
|
||||
from task_bench.shipped_features import read_shipped, shipped_tasks, ShippedFeatures
|
||||
from task_bench.record_figures import recorded_bench
|
||||
from task_bench.features.shipped_features import read_shipped, shipped_tasks
|
||||
from task_bench.figures.record_figures import recorded_bench
|
||||
from run_heavy.capped_docker import SHARE_VARIABLE
|
||||
from task_bench.rust_test_modules import tells_apart
|
||||
|
||||
@@ -234,15 +234,43 @@ KEPT = "The digest, and each run's result and stream, until `task-bench gather`
|
||||
ONLY_FOR = {"--seed": BUG, "--bugs": BUG, "--prefix": BUG, "--shipped": SHIPPED}
|
||||
|
||||
|
||||
# What plans a bench's tasks, once the bench has opened its containers.
|
||||
Planner = typing.Callable[[Bench], Planned | Failure]
|
||||
# What makes a kind's planner from each side's tree, once the trees stand.
|
||||
Planning = typing.Callable[[dict[Side, str]], Planner | Failure]
|
||||
# What reads a kind's tasks once the bench knows its checkout and its sides' commits, with git to read them by.
|
||||
Source = typing.Callable[[str, dict[Side, str], Git], Planning | Failure]
|
||||
|
||||
|
||||
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:
|
||||
class Call(typing.NamedTuple):
|
||||
"""What a bench was called with: its options, the environment its tools run in, what reads what `larv-review places` prints,
|
||||
and the home folder."""
|
||||
given: dict[str, str]
|
||||
env: typing.Mapping[str, str]
|
||||
read: typing.Callable[[pathlib.Path], str | Failure]
|
||||
home: pathlib.Path
|
||||
|
||||
|
||||
def new_name() -> str:
|
||||
"""A name no other bench's containers have."""
|
||||
return f"task-bench-{uuid.uuid4().hex[:12]}"
|
||||
|
||||
|
||||
def host_user() -> str:
|
||||
"""The user and group this process runs as, as docker's --user takes them."""
|
||||
return f"{os.getuid()}:{os.getgid()}"
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path], str | Failure] = read_places, claude: Claude = run_claude, name: typing.Callable[[], str] = new_name, user: typing.Callable[[], str] = host_user) -> int:
|
||||
"""Runs task-bench with the arguments argv; git, docker and the mutation tool run in the environment env, `read` reads what
|
||||
`larv-review places` prints for the checkout, and `claude` runs the claude that gathers."""
|
||||
`larv-review places` prints for the checkout, and `claude` runs the claude that gathers. `name` names a bench's containers,
|
||||
and `user` is the user they run as."""
|
||||
if argv in (["-h"], ["--help"]):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
@@ -254,7 +282,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], read: typing.Callable[[
|
||||
if isinstance(given, Failure):
|
||||
print(f"{given.reason}; {USAGE}", file=sys.stderr)
|
||||
return 1
|
||||
report = bench(given, env, read, home)
|
||||
report = bench(given, env, read, home, name(), user())
|
||||
if isinstance(report, Failure):
|
||||
print(report.reason, file=sys.stderr)
|
||||
return 1
|
||||
@@ -263,6 +291,13 @@ def main(argv: list[str], env: typing.Mapping[str, str], read: typing.Callable[[
|
||||
|
||||
|
||||
def options(argv: list[str], env: typing.Mapping[str, str]) -> dict[str, str] | Failure:
|
||||
"""The options argv gives, with each default filled in; a Failure where argv cannot be read, or asks what no bench does."""
|
||||
given = parsed(argv)
|
||||
return given if isinstance(given, Failure) else checked(given, env)
|
||||
|
||||
|
||||
def parsed(argv: list[str]) -> dict[str, str] | Failure:
|
||||
"""Each option argv names, with its value, given as `--name value` or `--name=value`."""
|
||||
given: dict[str, str] = {}
|
||||
rest = list(argv)
|
||||
while rest:
|
||||
@@ -279,23 +314,36 @@ def options(argv: list[str], env: typing.Mapping[str, str]) -> dict[str, str] |
|
||||
if not equals and not rest:
|
||||
return Failure(f"{name} needs a value")
|
||||
given[name] = value if equals else rest.pop(0)
|
||||
return given
|
||||
|
||||
|
||||
def checked(given: dict[str, str], env: typing.Mapping[str, str]) -> dict[str, str] | Failure:
|
||||
"""given with each default filled in, where it holds what a bench of its kind needs and env holds the token."""
|
||||
for name in ("--image", "--test"):
|
||||
if not given.get(name):
|
||||
return Failure(f"{name} is missing")
|
||||
if given.setdefault(TASKS, "bugs") not in KINDS:
|
||||
return Failure(f"{TASKS} takes {', '.join(list(KINDS)[:-1])} or {list(KINDS)[-1]}, not {given[TASKS]}")
|
||||
kind = KINDS[given[TASKS]]
|
||||
tasks = given.get(TASKS, "bugs")
|
||||
if tasks not in KINDS:
|
||||
return Failure(f"{TASKS} takes {', '.join(list(KINDS)[:-1])} or {list(KINDS)[-1]}, not {tasks}")
|
||||
kind = KINDS[tasks]
|
||||
for name, only in ONLY_FOR.items():
|
||||
if only is not kind and name in given:
|
||||
return Failure(f"{name} is for a bench of {only.noun}s, so it doesn't go with {TASKS} {given[TASKS]}")
|
||||
for name, default in COUNTS.items():
|
||||
if ONLY_FOR.get(name, kind) is not kind:
|
||||
continue
|
||||
if not given.setdefault(name, default).isdecimal() or int(given[name]) < 1:
|
||||
return Failure(f"{name} takes a whole number from 1, not {given[name]}")
|
||||
if not env.get(TOKEN):
|
||||
return Failure(f"{TOKEN} holds no token")
|
||||
return given
|
||||
return Failure(f"{name} is for a bench of {only.noun}s, so it doesn't go with {TASKS} {tasks}")
|
||||
filled = {TASKS: tasks, **count_defaults(kind), **given}
|
||||
return counts_failure(filled) or (filled if env.get(TOKEN) else Failure(f"{TOKEN} holds no token"))
|
||||
|
||||
|
||||
def count_defaults(kind: Kind) -> dict[str, str]:
|
||||
"""The default of each count a bench of kind takes."""
|
||||
return {name: default for name, default in COUNTS.items() if ONLY_FOR.get(name, kind) is kind}
|
||||
|
||||
|
||||
def counts_failure(filled: dict[str, str]) -> Failure | None:
|
||||
"""A Failure where a count filled holds is no whole number from 1."""
|
||||
for name in COUNTS:
|
||||
if name in filled and (not filled[name].isdecimal() or int(filled[name]) < 1):
|
||||
return Failure(f"{name} takes a whole number from 1, not {filled[name]}")
|
||||
return None
|
||||
|
||||
|
||||
def progress(line: str) -> None:
|
||||
@@ -303,16 +351,14 @@ def progress(line: str) -> None:
|
||||
print(line, file=sys.stderr)
|
||||
|
||||
|
||||
def bench(given: dict[str, str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path], str | Failure], home: pathlib.Path) -> list[str] | Failure:
|
||||
"""The report of one bench of the checkout the process runs in, where `read` reads what `larv-review places` prints. It tells
|
||||
its progress on stderr."""
|
||||
# Only bugs are planted at the seats' places; features and data sources come from the project's folder, and shipped features from its history. Each kind reads what it makes its tasks from before anything is copied or built,
|
||||
# so a fault there stops the bench at once.
|
||||
def bench(given: dict[str, str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path], str | Failure], home: pathlib.Path, name: str, user: str) -> list[str] | Failure:
|
||||
"""The report of one bench of the checkout the process runs in, where `read` reads what `larv-review places` prints. Its
|
||||
containers are named name and run as user. It tells its progress on stderr."""
|
||||
kind = KINDS[given[TASKS]]
|
||||
# Shipped features are read from the base's history, once the base is known.
|
||||
tasks_from: str | Features | ShippedFeatures | Failure | None = None if kind is SHIPPED else read(home) if kind is BUG else read_features(home, kind)
|
||||
if isinstance(tasks_from, Failure):
|
||||
return tasks_from
|
||||
# Each kind reads what it makes its tasks from before anything is copied or built, so a fault there stops the bench at once.
|
||||
source = SOURCES[kind](Call(given, env, read, home), kind)
|
||||
if isinstance(source, Failure):
|
||||
return source
|
||||
git = functools.partial(git_repo.git, env=env)
|
||||
checkout = top(git)
|
||||
if isinstance(checkout, Failure):
|
||||
@@ -320,10 +366,9 @@ def bench(given: dict[str, str], env: typing.Mapping[str, str], read: typing.Cal
|
||||
sides = commits(given, checkout, git)
|
||||
if isinstance(sides, Failure):
|
||||
return sides
|
||||
if tasks_from is None:
|
||||
tasks_from = read_shipped(home, checkout, sides["base"], git)
|
||||
if isinstance(tasks_from, Failure):
|
||||
return tasks_from
|
||||
planning = source(checkout, sides, git)
|
||||
if isinstance(planning, Failure):
|
||||
return planning
|
||||
progress(f"task-bench: base {sides['base'][:12]}, head {sides['head'][:12]}.")
|
||||
review = made_review_folder(checkout, home)
|
||||
if isinstance(review, Failure):
|
||||
@@ -332,15 +377,14 @@ def bench(given: dict[str, str], env: typing.Mapping[str, str], read: typing.Cal
|
||||
if isinstance(folder, Failure):
|
||||
return folder
|
||||
clear_left(home / REPORTS)
|
||||
run = functools.partial(bench_in, folder, given, env, tasks_from, checkout, sides, git)
|
||||
containers = Containers(docker_cli(env), name, given["--test"], int(env.get(SHARE_VARIABLE) or MEMORY_MIB), user)
|
||||
run = functools.partial(bench_in, folder, given["--image"], containers, Asked(kind, int(given["--runs"])), planning, checkout, sides, git)
|
||||
return recorded_bench(run, folder, git, home, time.time) if RECORD in given else run()
|
||||
|
||||
|
||||
def bench_in(folder: pathlib.Path, given: dict[str, str], env: typing.Mapping[str, str], tasks_from: str | Features | ShippedFeatures, checkout: str, sides: dict[Side, str], git: Git) -> list[str] | Failure:
|
||||
"""The report of a bench of the commits sides names, which empties folder and keeps its runs there. Where tasks_from is what
|
||||
`larv-review places` prints, the bench plants bugs at the places it names. Where tasks_from holds features, data sources or
|
||||
shipped features, the bench has Haiku build, add or rebuild them."""
|
||||
containers = Containers(docker_cli(env), f"task-bench-{uuid.uuid4().hex[:12]}", given["--test"], int(env.get(SHARE_VARIABLE) or MEMORY_MIB), f"{os.getuid()}:{os.getgid()}")
|
||||
def bench_in(folder: pathlib.Path, image: str, containers: Containers, asked: Asked, planning: Planning, checkout: str, sides: dict[Side, str], git: Git) -> list[str] | Failure:
|
||||
"""The report of a bench of the commits sides names, in containers of image, which empties folder and keeps its runs there.
|
||||
planning makes what plans the tasks of the kind asked."""
|
||||
shutil.rmtree(folder, ignore_errors=True)
|
||||
trees: dict[Side, str] = {}
|
||||
for side, commit in sides.items():
|
||||
@@ -348,23 +392,47 @@ def bench_in(folder: pathlib.Path, given: dict[str, str], env: typing.Mapping[st
|
||||
if isinstance(tree, Failure):
|
||||
return tree
|
||||
trees[side] = tree
|
||||
planned: typing.Callable[[Bench], Planned | Failure] | Failure
|
||||
if isinstance(tasks_from, Features):
|
||||
asked, planned = Asked(KINDS[given[TASKS]], int(given["--runs"])), features_planner(tasks_from, checkout, trees)
|
||||
elif isinstance(tasks_from, ShippedFeatures):
|
||||
asked, planned = Asked(SHIPPED, int(given["--runs"])), functools.partial(shipped_tasks, shipped=tasks_from, count=int(given["--shipped"]))
|
||||
else:
|
||||
asked, planned = Asked(BUG, int(given["--runs"])), bugs_planner(given, env, tasks_from, trees["base"])
|
||||
planned = planning(trees)
|
||||
if isinstance(planned, Failure):
|
||||
return planned
|
||||
try:
|
||||
found = opened(containers, given["--image"]) or benched(Bench(checkout, sides, trees, asked, containers, folder, git, progress), planned)
|
||||
found = opened(containers, image) or benched(Bench(checkout, sides, trees, asked, containers, folder, git, progress), planned)
|
||||
finally:
|
||||
closed(containers)
|
||||
return found if isinstance(found, Failure) else [*found, f"{KEPT}{folder}"]
|
||||
|
||||
|
||||
def features_planner(features: Features, checkout: str, trees: dict[Side, str]) -> typing.Callable[[Bench], Planned | Failure]:
|
||||
def bugs_source(call: Call, kind: Kind) -> Source | Failure:
|
||||
"""Reads the seats' places, the only places bugs are planted."""
|
||||
places = call.read(call.home)
|
||||
if isinstance(places, Failure):
|
||||
return places
|
||||
return lambda checkout, sides, git: functools.partial(bugs_planner, call.given, call.env, places)
|
||||
|
||||
|
||||
def features_source(call: Call, kind: Kind) -> Source | Failure:
|
||||
"""Reads the features, or the data sources where kind is DATA_SOURCE, from the project's folder."""
|
||||
features = read_features(call.home, kind)
|
||||
if isinstance(features, Failure):
|
||||
return features
|
||||
return lambda checkout, sides, git: functools.partial(features_planner, features, checkout)
|
||||
|
||||
|
||||
def shipped_source(call: Call, kind: Kind) -> Source:
|
||||
"""Shipped features are read from the base's history, so only once the base is known."""
|
||||
def source(checkout: str, sides: dict[Side, str], git: Git) -> Planning | Failure:
|
||||
shipped = read_shipped(call.home, checkout, sides["base"], git)
|
||||
if isinstance(shipped, Failure):
|
||||
return shipped
|
||||
return lambda trees: functools.partial(shipped_tasks, shipped=shipped, count=int(call.given["--shipped"]))
|
||||
return source
|
||||
|
||||
|
||||
# What reads each kind's tasks. A kind without an entry stops the bench before it reads anything.
|
||||
SOURCES: dict[Kind, typing.Callable[[Call, Kind], Source | Failure]] = {BUG: bugs_source, FEATURE: features_source, DATA_SOURCE: features_source, SHIPPED: shipped_source}
|
||||
|
||||
|
||||
def features_planner(features: Features, checkout: str, trees: dict[Side, str]) -> Planner:
|
||||
"""What plans a bench of features in trees, each side's. It takes the features' folder, with its acceptance tests and
|
||||
reference patches, out of trees first, so Haiku's copy leaves it out."""
|
||||
if features.folder.is_relative_to(checkout):
|
||||
@@ -374,10 +442,11 @@ def features_planner(features: Features, checkout: str, trees: dict[Side, str])
|
||||
return functools.partial(feature_tasks, found=features.found, folder=features.folder)
|
||||
|
||||
|
||||
def bugs_planner(given: dict[str, str], env: typing.Mapping[str, str], places: str, base: str) -> typing.Callable[[Bench], Planned | Failure] | Failure:
|
||||
"""What plans a bench of bugs. The bugs' files are those of the tree at base that hold a place in places and are in a language
|
||||
of plant's LANGUAGES. Of the mutants the tests kill in those files, the ones --seed draws first become bugs, until --bugs of
|
||||
them have."""
|
||||
def bugs_planner(given: dict[str, str], env: typing.Mapping[str, str], places: str, trees: dict[Side, str]) -> Planner | Failure:
|
||||
"""What plans a bench of bugs. The bugs' files are those of the base's tree in trees that hold a place in places and are in a
|
||||
language of plant's LANGUAGES. Of the mutants the tests kill in those files, the ones --seed draws first become bugs, until
|
||||
--bugs of them have."""
|
||||
base = trees["base"]
|
||||
files = [path for path in place_files(places) if pathlib.Path(base, path).is_file()]
|
||||
if not files:
|
||||
return Failure("The places the seats found hard don't name any file at the base in a language the bench plants bugs in, so there is nowhere to plant a bug.")
|
||||
@@ -417,7 +486,7 @@ def archived(commit: str, into: pathlib.Path, checkout: str, git: Git) -> str |
|
||||
return removed if isinstance(removed, Failure) else str(into)
|
||||
|
||||
|
||||
def benched(bench: Bench, planned: typing.Callable[[Bench], Planned | Failure]) -> list[str] | Failure:
|
||||
def benched(bench: Bench, planned: Planner) -> list[str] | Failure:
|
||||
"""Makes the tasks that planned plans, runs each, writes the results into the bench's folder and returns the report."""
|
||||
if failure := baseline_failure(bench):
|
||||
return failure
|
||||
@@ -557,34 +626,48 @@ def fixed(task: Task, side: Side, number: int, containers: Containers, folder: p
|
||||
stream = stream_of(Result(task.number, side, number, False, None), folder, kind.key)
|
||||
copy, check = folder / "copy", folder / "check"
|
||||
try:
|
||||
try:
|
||||
stream.parent.mkdir(exist_ok=True)
|
||||
shutil.copytree(task.trees[side], copy, symlinks=True)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not copy {kind.noun} {task.number}'s tree at the {side}: {failure}")
|
||||
attempted = fix_attempted(containers, str(copy), kind.prompt.format(told=task.told[side]), stream)
|
||||
if isinstance(attempted, Failure):
|
||||
return attempted
|
||||
raw = on_disk(f"read {stream}", stream.read_bytes)
|
||||
if isinstance(raw, Failure):
|
||||
return raw
|
||||
events = json_objects(raw)
|
||||
entries = [entry_from(event) for event in events]
|
||||
found = figures(events, task.file and os.path.join(WORK, task.file))
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
checked = on_disk(f"make the tree that checks {kind.noun} {task.number}'s fix at the {side}", lambda: check_made(task.trees[side], str(copy), str(check), task.acceptance))
|
||||
if isinstance(checked, Failure):
|
||||
return checked
|
||||
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, tuple(entries))
|
||||
worked = attempt(task, side, containers, copy, stream, kind)
|
||||
if isinstance(worked, Failure):
|
||||
return worked
|
||||
passed = verdict(task, side, containers, copy, check, kind)
|
||||
if isinstance(passed, Failure):
|
||||
return passed
|
||||
return Result(task.number, side, number, passed, *worked)
|
||||
finally:
|
||||
shutil.rmtree(copy, ignore_errors=True)
|
||||
shutil.rmtree(check, ignore_errors=True)
|
||||
|
||||
|
||||
def attempt(task: Task, side: Side, containers: Containers, copy: pathlib.Path, stream: pathlib.Path, kind: Kind) -> tuple[Figures | None, tuple[Entry, ...]] | Failure:
|
||||
"""Haiku's work on task in copy, made a copy of the side's tree: the figures of its run, None where it didn't finish, and
|
||||
the entries of its stream, which it writes to the file stream."""
|
||||
try:
|
||||
stream.parent.mkdir(exist_ok=True)
|
||||
shutil.copytree(task.trees[side], copy, symlinks=True)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not copy {kind.noun} {task.number}'s tree at the {side}: {failure}")
|
||||
attempted = fix_attempted(containers, str(copy), kind.prompt.format(told=task.told[side]), stream)
|
||||
if isinstance(attempted, Failure):
|
||||
return attempted
|
||||
raw = on_disk(f"read {stream}", stream.read_bytes)
|
||||
if isinstance(raw, Failure):
|
||||
return raw
|
||||
events = json_objects(raw)
|
||||
found = figures(events, task.file and os.path.join(WORK, task.file))
|
||||
return found if isinstance(found, Failure) else (found, tuple(entry_from(event) for event in events))
|
||||
|
||||
|
||||
def verdict(task: Task, side: Side, containers: Containers, copy: pathlib.Path, check: pathlib.Path, kind: Kind) -> bool | Failure:
|
||||
"""Whether the tests pass over check, made the side's tree with what Haiku changed in copy. Tests that run out of time don't."""
|
||||
checked = on_disk(f"make the tree that checks {kind.noun} {task.number}'s fix at the {side}", lambda: check_made(task.trees[side], str(copy), str(check), task.acceptance))
|
||||
if isinstance(checked, Failure):
|
||||
return checked
|
||||
ran = ran_tests(containers, str(check))
|
||||
if isinstance(ran, Failure) and not isinstance(ran, TimedOut):
|
||||
return ran
|
||||
return isinstance(ran, Ran) and ran.code == 0
|
||||
|
||||
|
||||
def stream_of(result: Result, folder: pathlib.Path, key: str) -> pathlib.Path:
|
||||
"""The file that holds the stream of the run result names, of a task whose kind has that key. Its name without the suffix is
|
||||
the run's id in the digest."""
|
||||
|
||||
@@ -9,8 +9,10 @@ from task_bench.runs import checked_tree, Containers, ran_tests
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import Git
|
||||
from mutate_changes.tool_process import Ran
|
||||
from task_bench.figures import Side
|
||||
|
||||
# A bench's two sides: the commit before the change and the one after it.
|
||||
Side = typing.Literal["base", "head"]
|
||||
SIDES: tuple[Side, Side] = ("base", "head")
|
||||
# The one commit of a task's tree doesn't name anyone, and neither a hook nor a signing key of the caller's reaches it.
|
||||
COMMIT = ["-c", "user.name=task-bench", "-c", "user.email=task-bench@localhost", "-c", "commit.gpgsign=false", "-c", "core.hooksPath=/dev/null", "commit", "--quiet", "--message", "Import"]
|
||||
|
||||
|
||||
@@ -18,11 +18,11 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
from task_bench import api_proxy, bench_folder, main, runs
|
||||
from test_env import assert_not_root, isolated_env
|
||||
from task_bench.runs import checked_tree, closed, Containers, docker_cli, fix_attempted, opened, ran_tests, TimedOut
|
||||
from task_bench.plant import drawn
|
||||
from task_bench.bugs.plant import drawn
|
||||
from claude_code.entries import Entry, entry_from
|
||||
from failure import Failure
|
||||
from task_bench.figures import Figures, Result
|
||||
from task_bench.planted_mutant import Mutant
|
||||
from task_bench.figures.run_figures import Figures, Result
|
||||
from task_bench.bugs.planted_mutant import Mutant
|
||||
from mutate_changes.tool_process import Ran
|
||||
from claude_code.tokens import Tokens
|
||||
|
||||
@@ -90,6 +90,8 @@ CLAUDE = textwrap.dedent("""\
|
||||
usage = {"input_tokens": 40, "cache_creation_input_tokens": 9000, "cache_read_input_tokens": 52000, "output_tokens": 800}
|
||||
print(json.dumps({"type": "result", "subtype": "success", "is_error": False, "num_turns": 3, "duration_ms": 61500, "usage": usage, "result": "Fixed."}))
|
||||
""")
|
||||
# The name of a bench's containers and the user they run as, where a test fixes them.
|
||||
NAME, USER = "task-bench-0123456789ab", "1234:5678"
|
||||
PLACES = "## 2026-10-08T12:00:00Z, PR #1 at aaaaaaa\n\nJunior A, hardest first:\n\n- `calc.go:3` `Add`: long\n- `gone.go:1` `Gone`: removed since\n- `README.md:1` `Calc`: thin\n"
|
||||
|
||||
|
||||
@@ -131,7 +133,7 @@ class BenchTest(unittest.TestCase):
|
||||
|
||||
def bench(self, **given: str):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as self.progress:
|
||||
return main.bench({**self.given, "--base": "main", **given}, self.env, lambda home: PLACES, self.home)
|
||||
return main.bench({**self.given, "--base": "main", **given}, self.env, lambda home: PLACES, self.home, NAME, USER)
|
||||
|
||||
def calls(self) -> list[list[str]]:
|
||||
return [json.loads(line) for line in self.log.read_text().splitlines()]
|
||||
@@ -223,6 +225,20 @@ class BenchTest(unittest.TestCase):
|
||||
self.assertTrue((reports / "crashed/task-bench.lock").exists())
|
||||
self.assertTrue((reports / "running/task-bench/trees/task-bench").exists())
|
||||
|
||||
def test_the_command_line_names_its_containers_afresh_and_runs_them_as_the_hosts_user(self):
|
||||
self.assertRegex(main.new_name(), r"^task-bench-[0-9a-f]{12}$")
|
||||
self.assertNotEqual(main.new_name(), main.new_name())
|
||||
self.assertEqual(main.host_user(), f"{os.getuid()}:{os.getgid()}")
|
||||
argv = [part for name, value in {**self.given, "--runs": "1"}.items() for part in (name, value)]
|
||||
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertEqual(main.main(argv, self.env, lambda home: PLACES, name=lambda: "task-bench-other", user=lambda: "7:8"), 0)
|
||||
calls = self.calls()
|
||||
self.assertEqual(calls[1], ["network", "create", "--internal", "task-bench-other"])
|
||||
self.assertIn(["--user", "7:8"], [call[at:at + 2] for call in calls if "claude" in call for at in range(len(call))])
|
||||
|
||||
def test_each_kind_of_task_has_what_reads_its_tasks(self):
|
||||
self.assertEqual(set(main.SOURCES), set(main.KINDS.values()))
|
||||
|
||||
def test_the_command_line_runs_the_bench_on_the_seats_places_and_prints_its_report(self):
|
||||
argv = [part for name, value in self.given.items() for part in (name, value)]
|
||||
homes = []
|
||||
@@ -282,11 +298,11 @@ class BenchTest(unittest.TestCase):
|
||||
fixes = [call for call in calls if "claude" in call]
|
||||
self.assertEqual(len(fixes), 2)
|
||||
name = fixes[0][fixes[0].index("--network") + 1]
|
||||
self.assertRegex(name, r"^task-bench-[0-9a-f]{12}$")
|
||||
self.assertEqual(name, NAME)
|
||||
image = fixes[0].index(f"{name}:throwaway")
|
||||
self.assertEqual(fixes[0][image + 1:], ["claude", "-p", "--strict-mcp-config", "--disable-slash-commands", "--no-session-persistence", "--model", "claude-haiku-5-5", "--effort", "low", "--output-format", "stream-json", "--verbose", "--permission-mode", "bypassPermissions", "A test of this project fails with the message below. Find the bug in the code and fix it. Change no test.\n\nAdd(1, 2) = -1, want 3"])
|
||||
options = fixes[0][:image]
|
||||
for expected in (["--memory", "2048m"], ["--memory-swap", "2048m"], ["--user", f"{os.getuid()}:{os.getgid()}"], ["--env", "HOME=/tmp"], ["--env", "CLAUDE_CODE_OAUTH_TOKEN"], ["--env", f"HTTPS_PROXY=http://{name}-proxy:8080"], ["--workdir", "/work"]):
|
||||
for expected in (["--memory", "2048m"], ["--memory-swap", "2048m"], ["--user", USER], ["--env", "HOME=/tmp"], ["--env", "CLAUDE_CODE_OAUTH_TOKEN"], ["--env", f"HTTPS_PROXY=http://{name}-proxy:8080"], ["--workdir", "/work"]):
|
||||
self.assertIn(expected, [options[at:at + 2] for at in range(len(options))])
|
||||
self.assertNotIn("sk-secret-token", self.log.read_text())
|
||||
self.assertEqual(calls[0][:1] + calls[0][-3:], ["build", "--tag", f"{name}:throwaway", "-"])
|
||||
@@ -308,7 +324,7 @@ class BenchTest(unittest.TestCase):
|
||||
|
||||
def test_fails_where_the_places_name_no_file_of_the_base_in_a_language_the_bench_plants_in(self):
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
found = main.bench({**self.given, "--base": "main"}, self.env, lambda home: "- `gone.go:1` `Gone`: removed\n- `README.md:1` `Calc`: thin\n", self.home)
|
||||
found = main.bench({**self.given, "--base": "main"}, self.env, lambda home: "- `gone.go:1` `Gone`: removed\n- `README.md:1` `Calc`: thin\n", self.home, NAME, USER)
|
||||
self.assertEqual(found, Failure("The places the seats found hard don't name any file at the base in a language the bench plants bugs in, so there is nowhere to plant a bug."))
|
||||
self.assertFalse(self.log.exists())
|
||||
|
||||
@@ -441,6 +457,12 @@ class MainTest(unittest.TestCase):
|
||||
self.assertEqual(self.run_main("--test", "go test ./...")[1].partition(";")[0], "--image is missing")
|
||||
self.assertEqual(self.run_main("--image", "golang:1.27.4")[1].partition(";")[0], "--test is missing")
|
||||
|
||||
def test_fills_in_each_default_of_the_kind_and_leaves_what_it_was_given_as_it_was(self):
|
||||
given = {"--image": "i", "--test": "t", "--runs": "7"}
|
||||
filled = main.checked(given, {"CLAUDE_CODE_OAUTH_TOKEN": "t"})
|
||||
self.assertEqual(given, {"--image": "i", "--test": "t", "--runs": "7"})
|
||||
self.assertEqual(filled, {"--image": "i", "--test": "t", "--tasks": "bugs", "--runs": "7", "--bugs": "5", "--seed": "1"})
|
||||
|
||||
def test_refuses_a_count_that_is_no_whole_number_from_1(self):
|
||||
for name, value in (("--bugs", "0"), ("--runs", "-1"), ("--seed", "x")):
|
||||
self.assertEqual(self.run_main("--image", "i", "--test", "t", name, value)[1].partition(";")[0], f"{name} takes a whole number from 1, not {value}")
|
||||
@@ -538,6 +560,14 @@ class RunOutcomesTest(unittest.TestCase):
|
||||
task = dataclasses.replace(self.task, trees={"base": str(self.folder / "gone"), "head": str(self.tree)})
|
||||
self.assertFailsWith(main.fixed(task, "base", 1, self.containers(), self.folder, main.BUG), "could not copy bug 1's tree at the base: ")
|
||||
|
||||
def test_a_stream_that_cannot_be_read_after_the_fix_fails_the_bench_naming_the_stream(self):
|
||||
stream = self.folder / "runs" / "bug-1-base-1.jsonl"
|
||||
def removing_the_stream(args, *, seconds, stdin=None, stdout=None, stderr=None):
|
||||
stream.unlink(missing_ok=True)
|
||||
return Ran(0, "")
|
||||
containers = dataclasses.replace(self.containers(), docker=removing_the_stream)
|
||||
self.assertFailsWith(main.fixed(self.task, "base", 1, containers, self.folder, main.BUG), f"could not read {stream}: ")
|
||||
|
||||
def test_failing_to_make_the_tree_that_checks_a_fix_fails_the_bench_naming_the_bug_and_side(self):
|
||||
(self.folder / "check").mkdir()
|
||||
self.assertFailsWith(main.fixed(self.task, "base", 1, self.containers(Ran(0, "")), self.folder, main.BUG), "could not make the tree that checks bug 1's fix at the base: ")
|
||||
|
||||
@@ -9,7 +9,8 @@ cd "$(dirname "$0")"
|
||||
socket=/var/run/docker.sock
|
||||
# An untagged image, which docker image prune removes, since a cancelled run skips any cleanup.
|
||||
image=$(printf 'FROM docker:29.1.3-cli AS docker\nFROM python:3.14.8\nCOPY --from=docker /usr/local/bin/docker /usr/local/bin/docker\n' | docker build --quiet --memory 1g --memory-swap 1g -)
|
||||
git bundle create - HEAD | docker run --rm -i --memory 4g --memory-swap 4g --user "$(id -u):$(id -g)" --group-add "$(stat -c %g "$socket")" -v "$socket:$socket" -e HOME=/tmp "$image" sh -euc '
|
||||
# deploy-release names the container in CI_CONTAINER, to remove it where it stops a run that hangs: stopping this script and its docker client leaves the container running. CI gives no name.
|
||||
git bundle create - HEAD | docker run --rm -i ${CI_CONTAINER:+--name "$CI_CONTAINER"} --memory 4g --memory-swap 4g --user "$(id -u):$(id -g)" --group-add "$(stat -c %g "$socket")" -v "$socket:$socket" -e HOME=/tmp "$image" sh -euc '
|
||||
cat >/tmp/head.bundle
|
||||
git -c init.defaultBranch=main -c advice.detachedHead=false clone --quiet /tmp/head.bundle /tmp/repo
|
||||
cd /tmp/repo
|
||||
|
||||
@@ -4479,3 +4479,37 @@ Inherited architect, would restructure first:
|
||||
- Shape: `bin/chunk_driver/cycle_start.py:96` `cycle_of`: ten keyword arguments on one line
|
||||
- Shape: `bin/agent_cycle/run.py:33` `Cycle`: 17 fields, allowed by a decision the reader must open the log to read
|
||||
- Locality: `bin/loop_claude/loop/reload.py:85` `fingerprint`: an edit to any `.py` under `bin/` reloads the running loop, through a handover format that already carries history
|
||||
|
||||
## 2026-11-27T13:55:16Z, PR #732 at 4a35c74f, against 606cf25e
|
||||
|
||||
Ruling: better
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Mid A | better | better | better | same | better |
|
||||
| Inherited architect | better | better | better | same | better |
|
||||
|
||||
Mid A, decided by:
|
||||
|
||||
- Locality: `bin/deploy_release/cut.py:38` `cut`: each step reports through a `say` argument decided once in main, where the base's module-level `said` printed to stderr as a hidden side effect
|
||||
- Locality, Shape: `bin/deploy_release/cut.py:144` `ready_release`: one function answers one question, where the base's `review` flag switched a match case; each caller decides what an unreviewed release means
|
||||
- Locality, Navigation: `bin/deploy_release/patch.py:221` `run_ci`: the timeout, kill and container clean-up have their own file, ci_script.py, where the base ran ci.sh inline; `CI_CONTAINER` links to ci.sh through the environment
|
||||
- Navigation, Shape: `bin/task_bench/main.py:1` task_bench split into bugs/, features/ and figures/: a symptom picks a subfolder first, where the base held about 22 modules side by side
|
||||
- Locality, Shape: `bin/task_bench/main.py:432` `SOURCES`: the kind is settled once in one table, where the base checked it twice with isinstance; the Source, Planning, Planner chain of lambdas and near-synonym names holds the gain back
|
||||
- Shape, Locality: `bin/task_bench/main.py:320` `checked`: parsing, checking and defaults are separate functions without in-place mutation, where the base's `options` filled `given` with setdefault
|
||||
- Shape: `bin/do_epic/parking.py:127` `Told`: loop-local mutable state became a small object, and the loop body reads as three cases
|
||||
- Locality: `bin/plan/release.py:16` `REVIEW_TITLE`: one constant shared by four modules, where the base hard-coded the title
|
||||
- Shape: `bin/task_bench/tasks.py:14` `Side`: the shared type moved from the figures module to the module of shared task types
|
||||
- Navigation: `bin/do_epic/backend/protocol.py:13` `REVIEW_LABEL`: one of do-epic's labels now sits apart from the other two, and its copied comment fits its new spot less well
|
||||
- Self-sufficiency: `bin/task_bench/figures/record_figures.py:16` `SIDES`: its comment names a path the move made stale, offset by the new docstrings on the trace and the ci.sh limit
|
||||
|
||||
Inherited architect, decided by:
|
||||
|
||||
- Locality, Shape: `bin/task_bench/main.py:432` `SOURCES`: each kind's reading stays in one function, where the base's `tasks_from` union and its isinstance checks had to be edited in two functions in step
|
||||
- Shape: `bin/task_bench/main.py:237` `Planner`: the most expensive read of the change; three nested callables per kind, unwound through functools.partial, and `kind` parameters two sources never use
|
||||
- Navigation, Shape: `bin/task_bench/main.py:1` task_bench split into bugs/, features/ and figures/: nine files and three named folders at the top, where the base had about 38 files flat; figures/gather.py filing plan items isn't "figures"
|
||||
- Locality: `bin/deploy_release/patch.py:52` `cut_patch`: `say` and `ci` come in from the caller, where the base printed from module level and ran ci.sh inline without a timeout or a record
|
||||
- Navigation: `bin/deploy_release/ci_script.py:27` `ci_runner`: a hung ci.sh or a dead cut leads to files named for it, ci_script.py and trace.py; `CI_CONTAINER` couples to ci.sh, commented at both ends
|
||||
- Locality: `bin/task_bench/main.py:293` `options`: each step is a pure function, where the base's single loop changed `given` as it went and made checks order-dependent
|
||||
- Shape: `bin/task_bench/tasks.py:14` `Side`: the core type sits with what the task kinds share, not in the report module
|
||||
- Shape: `bin/release_plan/release_standing.py:138` `reviewed_releases`: returns the reviewed releases, where the base's bool said only that some review landed
|
||||
|
||||
+4
-2
@@ -154,7 +154,9 @@ Valid while `~/.claude` is a checkout of this repo.
|
||||
|
||||
2026-11-08, lilleman, todo item 271. Serves goal 1.5 and goal 2. Nobody can push to `main` on the remote, and it merges only by fast-forward, so a cut that commits on `main` and pushes no longer works. The tool cuts only the release `chunk-preflight` would call ready to cut, through `bin/release_plan/release_standing.py`, so the two never disagree on which release is next or whether it is ready; the version is that release's, never the tool's choice. It builds the cut commit in a worktree of its own, so the clone's checkout stays as it is. It finds the merged commit on `main` by its title, `Cut release <version>`, since GitHub's nearest merge, a rebase merge, may give the commit a new hash. It takes only a pull request from origin's own branch whose head is the commit that branch points at, and has the forge merge it only while its head is still that commit, so a fork's pull request from a branch of the same name, or a push after the checks passed, is never merged and deployed. Each step first checks whether an earlier run did it, so a rerun continues. Releases stay the human's, so the human runs it, and the forge credentials stay theirs. Valid while `main` takes changes only through a pull request.
|
||||
|
||||
2026-11-24, lilleman, todo item 536. `deploy-release --cut-patch <commits>` cuts the newest tag's next patch release, holding only the commits named, for a fix that must ship before `main`'s other unreleased work. Before it, 0.15.1 was cut by those steps by hand. The patch's commit has the tag as its parent, not `main`'s head, so no pull request into `main` can merge it, and CI runs only on pull requests: the tool runs `ci.sh` on it, as CI does, before it tags. Then it merges the tag back into `main` with `-s ours` through a pull request, so the tag is in `main`'s history, where the next cut and `chunk-preflight` read it, and a release review on `main` counts only for a release later than the last cut. GitHub's rebase merge would drop that merge commit, so the tool refuses a GitHub origin. A patch skips the release review: `chunk-preflight` still calls it due until the patch is cut, so cut a patch as soon as its fix merges. Plain `--cut` refuses a patch of the newest tag, since it would ship all of `main` under a patch number. A panel of three readers seated as the owner picked the spelling `--cut-patch` over `--cut --patch` and `--hotfix`: one flag that names the action, which can't be read as a plain `--cut`.
|
||||
2026-11-24, lilleman, todo item 536. `deploy-release --cut-patch <commits>` cuts the newest tag's next patch release, holding only the commits named, for a fix that must ship before `main`'s other unreleased work. Before it, 0.15.1 was cut by those steps by hand. The patch's commit has the tag as its parent, not `main`'s head, so no pull request into `main` can merge it, and CI runs only on pull requests: the tool runs `ci.sh` on it, as CI does, before it tags. Then it merges the tag back into `main` with `-s ours` through a pull request, so the tag is in `main`'s history, where the next cut and `chunk-preflight` read it. GitHub's rebase merge would drop that merge commit, so the tool refuses a GitHub origin. A patch skips the release review: `chunk-preflight` still calls it due until the patch is cut, so cut a patch as soon as its fix merges. Plain `--cut` refuses a patch of the newest tag, since it would ship all of `main` under a patch number. A panel of three readers seated as the owner picked the spelling `--cut-patch` over `--cut --patch` and `--hotfix`: one flag that names the action, which can't be read as a plain `--cut`.
|
||||
|
||||
2026-11-27, lilleman, the release review of 0.16.0. A release review on `main` counts only for the release its title names, which must be exactly the next release, as `chunk-preflight --help` states. So the patch's own review, which the merge leaves on `main` after the tag, doesn't review any later release, and neither does a review opened under a release name todo.md has since changed. Where todo.md names no next release, a review of any release after the last cut counts.
|
||||
|
||||
## do-epic: drives one Jira epic whose items span repos, or have none, ranked by the epic's goals, then code health, then each repo's goals, and closes the epic only once the human confirms every goal
|
||||
|
||||
@@ -533,7 +535,7 @@ The base is the last measured commit: the default branch's newest merged change
|
||||
|
||||
## review: the architecture and principles passes run only in the release review, a release's last chunk, which must land before the release is ready to cut; between releases the product-owner pass reviews changes to what consumers rely on
|
||||
|
||||
2026-10-29, lilleman. Serves goals 1.4 and 1.5, and code health. The principles audit read the whole project on every chunk that changed code, because small changes had let a project drift; it was the costliest reviewer after the worker, and it filed findings unrelated to the chunk. A per-chunk architecture trigger needs judgment about what a change carries, which a worker knows only after the work, and a planner or worker asking for the review would pile up agents. So both passes run once, over the whole project, in the release review: the chunk that runs once a release holds no item and changes are unreleased. They may refactor boldly, five rounds each, and their fixes take the stability, security, overrides and prose passes, two rounds each. The human sets how much drift a review must catch through how big a release is. Between releases, the product-owner pass reviews changes to what consumers rely on, such as routes, file formats and CLI flags, which the architecture trigger used to cover. `chunk-preflight` reports a release review due until a commit titled `Release review of <release>` follows the newest `v*` tag, and only then the release ready to cut. A project that deploys every merge, as this repo does, carries drift into production until its release review; lilleman means to move such projects onto releases. Valid while drift a release's chunks leave stays small enough for one review to fix.
|
||||
2026-10-29, lilleman. Serves goals 1.4 and 1.5, and code health. The principles audit read the whole project on every chunk that changed code, because small changes had let a project drift; it was the costliest reviewer after the worker, and it filed findings unrelated to the chunk. A per-chunk architecture trigger needs judgment about what a change carries, which a worker knows only after the work, and a planner or worker asking for the review would pile up agents. So both passes run once, over the whole project, in the release review: the chunk that runs once a release holds no item and changes are unreleased. They may refactor boldly, five rounds each, and their fixes take the stability, security, overrides and prose passes, two rounds each. The human sets how much drift a review must catch through how big a release is. Between releases, the product-owner pass reviews changes to what consumers rely on, such as routes, file formats and CLI flags, which the architecture trigger used to cover. `chunk-preflight` reports a release review due until that review has landed, and only then the release ready to cut; `chunk-preflight --help` says which commit counts. A project that deploys every merge, as this repo does, carries drift into production until its release review; lilleman means to move such projects onto releases. Valid while drift a release's chunks leave stays small enough for one review to fix.
|
||||
|
||||
## review: the principles audit runs only in the release review, and reads the project whole with one auditor checking the goals and every principles file that applies
|
||||
|
||||
|
||||
@@ -3686,3 +3686,17 @@ Read most (opens and searches):
|
||||
- `bin/task_bench/go_bugs.py` 2
|
||||
- `bin/task_bench/tasks.py` 2
|
||||
- `bin/task_bench/test_go_bugs.py` 2
|
||||
|
||||
## Reading cost, chunk f6f944a18249, finished 2026-11-26T15:21:17Z
|
||||
|
||||
215178 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `README.md` 4
|
||||
- `bin/task_bench/registers.py` 3
|
||||
- `docs/decisions.md` 2
|
||||
- `CHANGELOG.md` 1
|
||||
- `bin/task_bench/feature_tasks.py` 1
|
||||
- `bin/task_bench/tasks.py` 1
|
||||
- `todo.md` 1
|
||||
|
||||
+25
-13
@@ -99,20 +99,32 @@ Give a reviewer without Bash `git ls-files`'s output in its prompt, since some h
|
||||
- **Done.** A pass is done when its latest round leaves no 🔴 or 🟡 standing: none was reported, or each was shown factually wrong, declined, filed, or named under the bar per "Findings", or settled in the PR summary per "Comprehension check" → "Places", or, for the prose pass and a pass at its cap, fixed. A stability pass whose round's fixes skip the next round per "Re-entry" → "Mechanical answers" is done once that rule's run is clean. Resolve that round's 🟢s and ❓s per "Findings" too.
|
||||
- **Cap.** A pass takes at most two rounds per chunk, and the release review's architecture and principles passes five; don't ask the user for more. Answer its last round's findings per "Findings": those fixes merge once the gate passes, unreviewed by that pass. rule-hook's `round-cap` refuses a round commit that would take a pass past its cap, and no override waives it. A review the auto-reviewer posts after its second isn't a round: fix none of it and rerun no pass for it, but file a security finding it raises per `~/.claude/CLAUDE.md` → "Working loop", and any other 🔴 in `todo.md`.
|
||||
|
||||
**Re-entry.** A fix is a change no pass has seen. A fix for a 🟢 or a ❓ doesn't rerun any pass, whatever it changes. A fix for a 🟡 of a pass other than prose meets only the 🟡 row below, and a fix for a prose finding, of any severity, only the last row. A round's fixes for 🔴 findings, its 🟡 fixes that meet that row, and its prose fixes that meet the last row, re-enter together: run every pass that a row below names for any of them, a done pass included, in the waves of "Waves", then §4; "Mechanical answers" below names the one exception. A pass at its cap doesn't run again ("Round cap" → "Cap").
|
||||
**Re-entry.** A fix is a change no pass has seen. It reruns the pass of every row below that it fits in both columns:
|
||||
|
||||
| The fix | Reruns |
|
||||
|---------|--------|
|
||||
| answers a 🔴 of a pass other than prose | that pass |
|
||||
| answers a 🟡 of a pass other than prose, and removes or loosens an assertion, changes an expected value, or skips, deletes or guards a test or assertion with a condition or a catch, unless it only kills a named mutant or makes a named failing test pass | that pass |
|
||||
| carries an architectural decision, in the release review | Architecture |
|
||||
| changes code, config or tests, in the release review | Principles |
|
||||
| opens an untrusted-input boundary or touches authn/authz, secrets or crypto | Security, unless the full scan reruns on it |
|
||||
| made rule-hook log an override | Overrides |
|
||||
| changes behaviour: what the code or its tests do | Stability |
|
||||
| answers a prose finding by rewriting what a claim says, where a command or a source file can check the claim, such as what generated output holds, a number or a licence term; rewording that keeps what it says doesn't count | Prose, as its second and last round |
|
||||
| The fix answers | and | Reruns |
|
||||
|-----------------|-----|--------|
|
||||
| a 🔴 of a pass other than prose | changes anything | that pass |
|
||||
| a 🔴 of a pass other than prose | carries an architectural decision, in the release review | Architecture |
|
||||
| a 🔴 of a pass other than prose | changes code, config or tests, in the release review | Principles |
|
||||
| a 🔴 of a pass other than prose | opens an untrusted-input boundary or touches authn/authz, secrets or crypto | Security, unless the full scan reruns on it |
|
||||
| a 🔴 of a pass other than prose | made rule-hook log an override | Overrides |
|
||||
| a 🔴 of a pass other than prose | changes behaviour: what the code or its tests do | Stability |
|
||||
| a 🟡 of a pass other than prose | removes or loosens an assertion, changes an expected value, or skips, deletes or guards a test or assertion with a condition or a catch | that pass |
|
||||
| a prose finding, of any severity | rewrites what a claim says, where a command or a source file can check the claim, such as what generated output holds, a number or a licence term | Prose, as its second and last round |
|
||||
|
||||
A fix meets every row it fits, except the two fixes named above, each of which meets only its one row. Such a fix meets no row once §2's tests and mutation command run clean on it and the named failing test is unedited ("Mechanical answers"); a skipped test kills no mutant. A comment or doc edit inside a fix for another pass's finding doesn't rerun any pass. Example: a fix for a stability 🔴 that changes code and a comment reruns Principles and Stability.
|
||||
Example: in the release review, a fix for a stability 🔴 that changes code and a comment reruns Stability and Principles.
|
||||
|
||||
A fix that fits no row doesn't rerun any pass. So none of these does:
|
||||
|
||||
- a fix for a 🟢 or a ❓, whatever it changes;
|
||||
- a fix for a 🟡 that does none of what the 🟡 row lists;
|
||||
- a fix for a prose finding that rewords a claim and keeps what it says.
|
||||
|
||||
A comment or doc edit inside a fix for another pass's finding adds no pass: no row reruns Prose for it.
|
||||
|
||||
One fix fits the 🟡 row and still doesn't rerun the pass: a fix that only kills a named mutant or makes a named failing test pass, once §2's tests and mutation command run clean on it and the named failing test is unedited ("Mechanical answers"). A skipped test kills no mutant.
|
||||
|
||||
A round's fixes re-enter together: run every pass the table names for any of them, a done pass included, in the waves of "Waves", then §4. "Mechanical answers" below names the one case where the fixes for a 🔴 don't rerun its pass. A pass at its cap doesn't run again ("Round cap" → "Cap").
|
||||
|
||||
**Mechanical answers.** A stability round's fixes may skip the next stability round. That holds where the round reported a 🔴, and each of its 🔴 and 🟡 findings asked only that a named mutant be killed or a named failing test pass. Run §2's tests and mutation command on the fixes, and fix again per §2 until they leave no failing test and no surviving mutant that changes behaviour. Each named failing test must pass as the round found it, not edited or deleted. Then the stability pass doesn't run again, and the round's answer commit title ends `; tests and mutants clean at <commit>`. The fixes still rerun each other pass whose row they meet. Where the run can't be made clean, or a fix edits a named failing test, the stability pass runs again as the table says.
|
||||
|
||||
@@ -140,7 +152,7 @@ A fix meets every row it fits, except the two fixes named above, each of which m
|
||||
|
||||
The release review is a release's last chunk, run once the release holds no item and changes are unreleased, before it is ready to cut. It looks for the drift the release's small changes left, and fixes it.
|
||||
|
||||
- **When.** `chunk-preflight` reports a release review due. It counts one as landed once a commit titled `Release review of <release>` follows the newest `v*` tag on the default branch.
|
||||
- **When.** `chunk-preflight` reports a release review due. `chunk-preflight --help` says which commit counts as the review having landed.
|
||||
- **Branch.** `release-review-<release>`, off the default branch. Open it with `git commit --allow-empty -m "Release review of <release>"`.
|
||||
- **Passes.** Architecture, then Principles, each over the whole project, per "Waves". Tell both to refactor boldly where the code needs it. Each takes up to five rounds.
|
||||
- **Their fixes** re-enter Stability, Security, Overrides and Prose per "Re-entry", each at most two rounds.
|
||||
|
||||
@@ -262,7 +262,7 @@ Touches:
|
||||
|
||||
### 544. Leave out of a `task-bench` fix a change Haiku makes to a PHP or JavaScript test that PHPUnit or `node --test` finds by a name `is_test` does not know.
|
||||
|
||||
PHPUnit finds a test by `*Test.php`, wherever it stands, and `node --test` also by `*-test.js`, `*_test.js`, `test-*.js` and `test.js`, with `.ts`, `.mjs` and `.cjs` alike. `mutate_changes.changed_lines.is_test` tells a test by a folder named `test`, `tests` or `__tests__`, or by a name such as `*.test.*`, so `src/PickTest.php` and `src/pick-test.js` count as code. `checked_tree` in `bin/task_bench/runs.py` then takes such a file as Haiku left it, so a fix that edits or deletes the failing test passes, at both sides alike, and `place_files` in `bin/task_bench/plant.py` may hand the file to the mutation tool as code. The help's Check paragraph says so.
|
||||
PHPUnit finds a test by `*Test.php`, wherever it stands, and `node --test` also by `*-test.js`, `*_test.js`, `test-*.js` and `test.js`, with `.ts`, `.mjs` and `.cjs` alike. `mutate_changes.changed_lines.is_test` tells a test by a folder named `test`, `tests` or `__tests__`, or by a name such as `*.test.*`, so `src/PickTest.php` and `src/pick-test.js` count as code. `checked_tree` in `bin/task_bench/runs.py` then takes such a file as Haiku left it, so a fix that edits or deletes the failing test passes, at both sides alike, and `place_files` in `bin/task_bench/bugs/plant.py` may hand the file to the mutation tool as code. The help's Check paragraph says so.
|
||||
|
||||
Recommended: tell these names as tests inside task-bench, for a `.php` file and for the suffixes Stryker covers, and keep `is_test` as it is, since changing it would change what `mutate-changes` skips; item 539 does the same for Rust. A product-owner finding on item 527's chunk raised this.
|
||||
|
||||
@@ -468,7 +468,7 @@ Seats launch as `general-purpose`, so they hide inside that type: $301.24 of the
|
||||
|
||||
### 323. Count a release review as landed once its pull request has merged, whatever its commits are titled.
|
||||
|
||||
`release_reviewed` in `bin/release_plan/release_standing.py` counts a release review only by a commit titled `Release review of <release>` on the default branch. In a replay of archived interrupts (`judge-field-trials/`), in two projects whose release review had merged, the default branch held no such commit, so `chunk-preflight` and routing read ReviewDue, and the next loop would run the release review again. `skills/larv-review/SKILL.md` opens the review's branch with an empty commit of that title, but a worker may skip it, and a rebase or squash merge, which `chunk-pr` uses where the forge allows no merge commit, may drop it. Detect the review by something every merge method keeps, and check the fix against both projects' histories. Until then the judge keeps `release_ready` (docs/decisions.md → `routing: loop-claude reads the items a chunk takes …`).
|
||||
`reviewed_releases` in `bin/release_plan/release_standing.py` counts a release review only by a commit titled `Release review of <release>` on the default branch. In a replay of archived interrupts (`judge-field-trials/`), in two projects whose release review had merged, the default branch held no such commit, so `chunk-preflight` and routing read ReviewDue, and the next loop would run the release review again. `skills/larv-review/SKILL.md` opens the review's branch with an empty commit of that title, but a worker may skip it, and a rebase or squash merge, which `chunk-pr` uses where the forge allows no merge commit, may drop it. Detect the review by something every merge method keeps, and check the fix against both projects' histories. Until then the judge keeps `release_ready` (docs/decisions.md → `routing: loop-claude reads the items a chunk takes …`).
|
||||
|
||||
### 342. Research the tooling agents read, search and run commands with once more, and file an item for each tool that cuts tokens a replay shows keep quality.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user