diff --git a/.gitignore b/.gitignore index 77a404e4..1e647053 100644 --- a/.gitignore +++ b/.gitignore @@ -30,6 +30,8 @@ !bin/adf_codec/node_shim/package-lock.json !bin/adf_codec/node_shim/package.json !bin/adf_codec/node_shim/shim.mjs +!bin/atlassian/ +!bin/atlassian/*.py !bin/branch_chunks/ !bin/branch_chunks/*.py !bin/chunk-pr @@ -67,8 +69,6 @@ !bin/loop_state/*.py !bin/machine_load/ !bin/machine_load/*.py -!bin/mattermost_dm/ -!bin/mattermost_dm/*.py !bin/metric-bench !bin/metric_bench/ !bin/metric_bench/*.py @@ -81,6 +81,8 @@ !bin/notifier/ !bin/notifier/*.py !bin/notify +!bin/plan/ +!bin/plan/*.py !bin/plan_store/ !bin/plan_store/*.py !bin/project-config @@ -126,8 +128,6 @@ !bin/score_outcomes/*.py !bin/settings_filter.py !bin/setup.cfg -!bin/slack_dm/ -!bin/slack_dm/*.py !bin/statusline.py !bin/subagent-rung !bin/subagent_rung/ diff --git a/CHANGELOG.md b/CHANGELOG.md index a01e3bc3..b7a4cded 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,7 @@ - A project's config may keep each of its five records on a Confluence Cloud page: set, for example, `decisions = "confluence:https:///wiki/spaces//pages/"`, with the credentials in the config's `env-file`. `decisions` and `comprehension-history` may name a page only where `plan` names a Jira epic. The loop reads and writes the page as markdown, so a save replaces a mention or a macro on it with plain text. It never overwrites a teammate's edit: where someone saved the page since the loop read it, `project-record save` refuses and the loop asks you. - `todo-item add` files an item into a plan kept in a Jira epic: a Task under the epic, under the project's Fix Version for the release, labelled `security` for a security finding and linked to each item that blocks it. Editing an issue still happens in Jira. - An item of the next release may predict the files and parts it will touch, under a `Touches:` line in its detail. `chunk-preflight` then names the items that may start chunks at once, and the new `touch-predictions record` keeps each prediction beside what the merged chunk touched, in the record a project's config places with `touch-predictions`. -- CLAUDE.md and the todo-items rule define the plan as a todo.md or a Jira epic, and say plan where todo.md was false for a Jira plan. +- CLAUDE.md, the todo-items rule, and loop-claude's worker and judge prompts and `--help` define the plan as a todo.md or a Jira epic, and say plan where todo.md was false for a Jira plan. - Reviewers without a shell read the plan from a listing that larv-review writes into the review folder, whichever store holds it. - A project's config may set `tooling-on-host = true`, so the loop runs a legacy project's language runtime, package manager, tests and task runner directly on the host. - A project's config may set `readability-floor` to a number from 1 to 10: the comprehension score under which code health is very important. It is 7.0 where left out. @@ -30,6 +30,7 @@ - In a client project, the loop reads the team's own `CLAUDE.md` and `AGENTS.md` and proposes each change that aligns them with this setup in a pull request of its own. Where the team declines or doesn't answer, the loop follows the team's rule unless it breaks a project goal, and records the conflict as a decision in the `decisions` record. - The new `project-record open ` prints the file in which an agent reads and edits one of a project's five records (`decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`), and `project-record save ` stores the edit. Every tool now reads and writes a record the same one way, so that a later release can keep a record outside files. No config needs a change. - `loop-inbox` is gone. loop-claude now asks its questions only on its own terminal. A line typed there answers a question, and `/talk` opens the worker's session. The DM still tells you a loop waits. To upgrade, quit any `loop-inbox` still open and remove your `~/.local/bin/loop-inbox` link. +- rule-hook's `run-heavy` rule also refuses a heavy command run through `uv run`, `poetry run`, `sudo` or `doas` outside `run-heavy`, such as `uv run mutmut run` or `sudo docker build`. Run it as `~/.claude/bin/run-heavy uv run mutmut run`. - rule-hook refuses a Read or a Grep of `~/.claude/.env` or of the `env-file` any project's config names, and a Bash command that names either or searches a folder holding either with `ag`, `grep -r` or `rg`, unless the tool skips the file as hidden or ignored, so that a worker doesn't put a credential in its transcript in passing. A command that hides the path, such as behind a glob or a variable, still goes through. - A project's config names the service for loop-claude's DMs: `notifier = "mattermost"` or `"slack"`, with the bot's token and the recipient in the `env-file`. To upgrade, move the Mattermost keys from `~/.claude/.env` into a file outside the checkout and the config's folder, such as `~/.claude-projects/.env`, name it as `env-file` and add `notifier = "mattermost"`. A project with no `notifier` gets no DM, and `~/.claude/.env` is no longer read. A failure names each missing key and holds no token. - `mattermost-dm` is now `notify`, which sends through the project's `notifier`; `notify --help` names the keys. diff --git a/README.md b/README.md index a580fadc..a6af369c 100644 --- a/README.md +++ b/README.md @@ -194,12 +194,13 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `touch-predictions record ...` appends what a chunk's items were predicted to touch, under `Touches:` in their details, beside the files and parts its branch touched, to the record the config names as `touch-predictions`; `touch-predictions --help` shows the spelling and how a part is named. `chunk-preflight` reads the same predictions to name the items that may start chunks at once. - `wait-for [] [--timeout ]` waits until a file a background job writes holds a line matching the pattern, and prints it. -`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. `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. +`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. `atlassian/`, `branch_chunks/`, `claude_code/`, `command_lines/`, `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, which `repo_checks/test_package_cycles.py` checks. - `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. - `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` and `routing_figures`. It imports `reading_cost`'s record path. -- `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`. - `chunk_pr` imports `deploy_release`'s forge calls, and `forge_of` as `deploy_release` does. +- `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 `chunk_preflight`'s `forge_of`, which tells a GitHub origin from a Gitea one, and `release_plan`'s `release_standing`. - `git_cli/` runs git for every tool (`git_repo.py`), and reads the git calls in a shell command (`git_command.py`). - `judge_replay` imports `loop_claude`'s judge, verdicts, premises and records. @@ -208,13 +209,14 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `loop_state/` holds where loop-claude keeps its 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`, 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`; `mattermost_dm/` and `slack_dm/` are its two backends. -- `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`), with the markdown file's edits in `markdown_edits.py`. `contract.py` holds the tests every backend that writes must pass, which `jira_epic.py` doesn't yet, since it changes no link, and `fakes.py` a plan in memory. +- `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`. +- `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`) 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, which `jira_epic.py` doesn't yet, since it changes no link, and `fakes.py` 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/` reads `todo.md`'s items table and release versions, says which release is next and whether it is ready to cut (`release_standing.py`), and ranks the plan (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`). `goals_file.py` reads the goals file's sections, goals and goal weights, for the ranking and for `loop_claude`'s premises, and `citations.py` holds `todo.md` and `docs/decisions.md` to each other. `plan_file.py` ranks, checks and writes a `todo.md`, for `larv_review`, `rank_todo.py` and `rule_hook`. +- `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, and picks the item the next chunk takes first (`next_chunk.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 `mattermost_dm`, `slack_dm`, `plan_store` and `record_store`. +- `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. - `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 `loop_claude`'s retry count and models file, and finds that file through `loop_state`'s paths. diff --git a/bin/mattermost_dm/__init__.py b/bin/atlassian/__init__.py similarity index 100% rename from bin/mattermost_dm/__init__.py rename to bin/atlassian/__init__.py diff --git a/bin/atlassian/client.py b/bin/atlassian/client.py new file mode 100644 index 00000000..77ee1678 --- /dev/null +++ b/bin/atlassian/client.py @@ -0,0 +1,51 @@ +"""What the Jira and Confluence backends share: one Atlassian account's credentials, the request both backends send, and each service's error messages.""" +import base64 +import pathlib +import typing + +from failure import Failure +from rest_client import json_request +from rest_client.env_file import read_env +from adf_codec.convert import Refused + +# One pair of keys for Jira and Confluence: one Atlassian account's API token opens both. +KEYS = ("ATLASSIAN_EMAIL", "ATLASSIAN_API_TOKEN") +# Seconds each connect and each read may wait. +TIMEOUT = 30 + +# Sends a request with the Authorization header given, the body as JSON where there is one, and returns the JSON answer, None where the answer has no body, or a Failure saying why there is none. +Http = typing.Callable[[str, str, str, object], object] +ToMarkdown = typing.Callable[[list[dict[str, typing.Any]]], list[str] | Refused | Failure] +ToAdf = typing.Callable[[str], dict[str, typing.Any] | Failure] + + +def basic_auth(env_file: pathlib.Path) -> str | Failure: + """The Authorization header for the email and API token that env_file holds.""" + values = read_env(env_file, KEYS, "an API token") + if isinstance(values, Failure): + return values + return "Basic " + base64.b64encode(":".join(values[key] for key in KEYS).encode()).decode() + + +def jira_json(method: str, url: str, authorization: str, body: object) -> object: + return json_request.http_json(method, url, authorization, body, TIMEOUT, jira_errors) + + +def jira_errors(answer: object) -> str: + """Jira's messages in the JSON of an error answer; empty where it holds none.""" + if not isinstance(answer, dict): + return "" + messages, errors = answer.get("errorMessages"), answer.get("errors") + found = [*(messages if isinstance(messages, list) else []), *(errors.values() if isinstance(errors, dict) else [])] + return "; ".join(text for text in found if isinstance(text, str)) + + +def confluence_json(method: str, url: str, authorization: str, body: object) -> object: + return json_request.http_json(method, url, authorization, body, TIMEOUT, confluence_errors) + + +def confluence_errors(answer: object) -> str: + """Confluence's messages in the JSON of an error answer; empty where it holds none.""" + errors = answer.get("errors") if isinstance(answer, dict) else None + found = [error.get("title") for error in errors if isinstance(error, dict)] if isinstance(errors, list) else [answer.get("message")] if isinstance(answer, dict) else [] + return "; ".join(text for text in found if isinstance(text, str)) diff --git a/bin/atlassian/test_client.py b/bin/atlassian/test_client.py new file mode 100644 index 00000000..fbf91612 --- /dev/null +++ b/bin/atlassian/test_client.py @@ -0,0 +1,65 @@ +import base64 +import json +import pathlib +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from atlassian import client +from rest_client.json_request import ErrorAnswer +from failure import Failure +from rest_client.test_json_request import Served + +AUTHORIZATION = "Basic " + base64.b64encode(b"me@example.com:s3cret").decode() + + +class Credentials(unittest.TestCase): + def test_builds_basic_auth_from_the_env_files_email_and_token(self): + with tempfile.TemporaryDirectory() as temp: + env = pathlib.Path(temp, "acme.env") + env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n") + env.chmod(0o600) + self.assertEqual(client.basic_auth(env), AUTHORIZATION) + + def test_a_missing_env_file_fails(self): + self.assertIsInstance(client.basic_auth(pathlib.Path("/nonexistent/acme.env")), Failure) + + +class Jira(Served): + def test_an_error_answer_fails_with_jiras_messages_and_its_status(self): + base = self.serve((400, b'{"errorMessages": ["One."], "errors": {"jql": "Two."}}')) + self.assertEqual(client.jira_json("POST", f"{base}/rest/api/3/search/jql", AUTHORIZATION, {"jql": "x"}), ErrorAnswer("POST /rest/api/3/search/jql answered 400: One.; Two.", 400)) + [(_, _, headers, body)] = self.server.got # type: ignore[attr-defined] + self.assertEqual((headers["Authorization"], json.loads(body)), (AUTHORIZATION, {"jql": "x"})) + + def test_reads_jiras_messages_from_an_error_answer(self): + cases = ( + ({"errorMessages": ["Issue does not exist or you do not have permission to see it."], "errors": {}}, "Issue does not exist or you do not have permission to see it."), + ({"errorMessages": ["One."], "errors": {"jql": "Two."}}, "One.; Two."), + ({"errorMessages": "One.", "errors": ["Two."]}, ""), + ({"errorMessages": [7, "One."]}, "One."), + (["One."], ""), + ) + for answer, message in cases: + with self.subTest(answer=answer): + self.assertEqual(client.jira_errors(answer), message) + + +class Confluence(Served): + def test_an_error_answer_fails_with_confluences_messages_and_its_status(self): + base = self.serve((409, b'{"errors": [{"status": 409, "title": "Version must be incremented"}]}')) + self.assertEqual(client.confluence_json("PUT", f"{base}/wiki/api/v2/pages/1", AUTHORIZATION, {"version": {"number": 2}}), ErrorAnswer("PUT /wiki/api/v2/pages/1 answered 409: Version must be incremented", 409)) + [(_, _, headers, body)] = self.server.got # type: ignore[attr-defined] + self.assertEqual((headers["Authorization"], json.loads(body)), (AUTHORIZATION, {"version": {"number": 2}})) + + def test_reads_confluences_messages_from_an_error_answer(self): + self.assertEqual(client.confluence_errors({"errors": [{"status": 409, "title": "Version must be incremented"}, {"title": "and more"}, "odd"]}), "Version must be incremented; and more") + self.assertEqual(client.confluence_errors({"message": "Not Found"}), "Not Found") + self.assertEqual(client.confluence_errors({"errors": "odd"}), "") + self.assertEqual(client.confluence_errors(["odd"]), "") + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/branch_chunks/cut.py b/bin/branch_chunks/cut.py index fa9f5ba4..040d1f32 100644 --- a/bin/branch_chunks/cut.py +++ b/bin/branch_chunks/cut.py @@ -4,7 +4,7 @@ import typing from failure import Failure from review_rules.comprehension_history import HISTORY -from release_plan.todo_table import Item, items +from plan.todo_table import Item, items from reading_cost.figures import RECORD from project_config import templates from text_files.utc_stamp import utc diff --git a/bin/branch_chunks/fixes.py b/bin/branch_chunks/fixes.py index cfc06e9d..787bee8b 100644 --- a/bin/branch_chunks/fixes.py +++ b/bin/branch_chunks/fixes.py @@ -5,7 +5,7 @@ import re import typing from branch_chunks.cut import Branch, BranchChunk, NOT_WORK -from release_plan.todo_table import Exempt, Item +from plan.todo_table import Exempt, Item from review_rules.round_titles import title_counts # The Exempt cells, per ~/.claude/rules/todo-items.md, that mark an item fixing a defect. diff --git a/bin/branch_chunks/test_branch_chunks.py b/bin/branch_chunks/test_branch_chunks.py index ff69e07d..429900d3 100644 --- a/bin/branch_chunks/test_branch_chunks.py +++ b/bin/branch_chunks/test_branch_chunks.py @@ -17,7 +17,7 @@ from project_config.test_project_config import configured from failure import Failure from git_cli.git_repo import git from test_env import isolated_env -from release_plan.todo_table import Item +from plan.todo_table import Item HEADER = "| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n" WITHOUT_C = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|\n" diff --git a/bin/chunk_pr/approval.py b/bin/chunk_pr/approval.py index 6ce41058..a10118c8 100644 --- a/bin/chunk_pr/approval.py +++ b/bin/chunk_pr/approval.py @@ -8,22 +8,16 @@ from failure import Failure from chunk_preflight.gathered import Forge from deploy_release.forge import Run -BIN = pathlib.Path(__file__).resolve().parents[1] # A human answers in hours, so merge polls once a minute and gives up after 90 minutes. That leaves half an hour for the queue and the checks inside the 2 hours a background command may run; a run that needs more is killed before the give-up message prints, and its next run goes on from what it pushed. POLL_SECONDS = 60 WAIT_SECONDS = 90 * 60 -def awaited(forge: Forge, run: Run) -> bool | Failure: - """Whether merge waits for an approval: the project config's `wait-for-approval`. A config that cannot be read fails, so that merge never skips an approval the config may require. chunk-pr reads approvals on GitHub only, so a Gitea project that sets it fails too.""" - answer = run([str(BIN / "project-config"), "wait-for-approval"]) - if isinstance(answer, Failure): - return answer - if answer.strip() not in ("true", "false"): - return Failure(f"project-config wait-for-approval printed {answer.strip()[:80]!r}, not true or false") - if answer.strip() == "true" and forge != "gh": +def awaited(forge: Forge, wait_for_approval: bool) -> bool | Failure: + """Whether merge waits for an approval: the project config's `wait-for-approval`. chunk-pr reads approvals on GitHub only, so a Gitea project that sets it fails, and merge never skips an approval the config requires.""" + if wait_for_approval and forge != "gh": return Failure("the project's config sets wait-for-approval, but chunk-pr reads approvals on GitHub only, so it cannot merge this pull request; ask the human to merge it") - return answer.strip() == "true" + return wait_for_approval # Each review thread, with whether it is resolved and who wrote its last comment, beside who opened the pull request. gh fills {owner} and {repo} from the checkout. diff --git a/bin/chunk_pr/main.py b/bin/chunk_pr/main.py index b813694b..17dd9072 100644 --- a/bin/chunk_pr/main.py +++ b/bin/chunk_pr/main.py @@ -76,6 +76,7 @@ It prints what it did, exit 0, or why it failed, exit 1. import contextlib import dataclasses import fcntl +import functools import json import os import pathlib @@ -88,6 +89,9 @@ from deploy_release.forge import checks_passed, gitea, merged_pull, open_pull, r from failure import Failure from chunk_preflight.gathered import Forge from chunk_preflight.choices import forge_of +from project_config.main import located +from project_config.settings import ProjectConfig +from plan_store.plans import says_no_item from project_config import templates BIN = pathlib.Path(__file__).resolve().parents[1] @@ -100,6 +104,8 @@ QUEUE_SECONDS = 30 * 60 QUEUE_POLL_SECONDS = 10 # The line record-ruling writes into the comprehension history, as git's -G reads it. RULING = "^Ruling: " +# The project's config, loaded once per step, on the first call that needs it. +Config = typing.Callable[[], ProjectConfig | Failure] USAGE = "usage: chunk-pr open [<body>] | chunk-pr sync | chunk-pr ready [<title>] | chunk-pr merge [--finish <ID> [--changelog <bullet> | --no-changelog]]... | chunk-pr clean" # Each forge's merge methods in the order merge prefers them, as the repository setting that allows the method and the method's name in the forge's merge call. A merge commit and a fast-forward keep the branch's commits as they are; a rebase or a squash rewrites them. @@ -113,7 +119,7 @@ def main(argv: list[str]) -> int: if argv[:1] in (["-h"], ["--help"]): print(__doc__.strip()) return 0 - done = step(argv, runner(os.getcwd())) + done = step(argv, runner(os.getcwd()), functools.cache(lambda: located(os.getcwd(), pathlib.Path.home()))) if isinstance(done, Failure): print(f"chunk-pr: {done.reason}", file=sys.stderr) return 1 @@ -121,32 +127,34 @@ def main(argv: list[str]) -> int: return 0 -def step(argv: list[str], run: Run) -> str | Failure: +def step(argv: list[str], run: Run, config: Config) -> str | Failure: """Run the step argv names: the line to print, or a Failure. A malformed argv doesn't run anything.""" match argv: case ["open", title, *body] if len(body) <= 1 and not title.startswith("-"): - return Failure("give a title of one line") if not one_line(title) else misfit(title, run) or opened(title, body[0] if body else "", run) + return Failure("give a title of one line") if not one_line(title) else misfit(title, run, config) or opened(title, body[0] if body else "", run) case ["sync"]: - return synced(run) + return synced(run, config) case ["ready", *title] if len(title) <= 1 and not any(given.startswith("-") for given in title): - return Failure("give a title of one line") if title and not one_line(title[0]) else (misfit(title[0], run) if title else None) or marked_ready(run, title[0] if title else None) + return Failure("give a title of one line") if title and not one_line(title[0]) else (misfit(title[0], run, config) if title else None) or marked_ready(run, title[0] if title else None) case ["merge", *given]: finishes = finishes_of(given) - return Failure(USAGE) if finishes is None else merged(run, finishes=finishes) + return Failure(USAGE) if finishes is None else merged(run, config, finishes=finishes) case ["clean"]: return cleaned(run) return Failure(USAGE) -def misfit(title: str, run: Run) -> Failure | None: - """Why title doesn't fit the `pull-request-title` template the project's config names; None where it fits. A branch that doesn't fit the config's `branch` template is no plan item's, so it has no ID for {id}, and any title fits there. A config that cannot be read fails, so that no pull request reaches the project's owners under a title they don't use.""" - read = [run([str(BIN / "project-config"), "pull-request-title"]), run([str(BIN / "project-config"), "branch"]), run(["git", "symbolic-ref", "--short", "HEAD"])] - if failed := next((answer for answer in read if isinstance(answer, Failure)), None): - return failed - template, branch_template, branch = (answer.strip("\n") for answer in read if isinstance(answer, str)) - if not templates.branch_fits(branch_template, branch) or templates.fits(template, title.strip()): +def misfit(title: str, run: Run, config: Config) -> Failure | None: + """Why title doesn't fit the `pull-request-title` template the project's config names, as templates.misfits rules; None where it fits. A config that cannot be read fails, so that no pull request reaches the project's owners under a title they don't use.""" + loaded = config() + if isinstance(loaded, Failure): + return loaded + branch = run(["git", "symbolic-ref", "--short", "HEAD"]) + if isinstance(branch, Failure): + return branch + if not templates.misfits(loaded.pull_request_title, loaded.branch, branch.strip("\n"), title): return None - return Failure(f"title the pull request as the project's config asks, `{template}`, where {{id}} is the ID of the chunk's first item; {title.strip()!r} doesn't fit") + return Failure(f"title the pull request as the project's config asks, `{loaded.pull_request_title}`, where {{id}} is the ID of the chunk's first item; {title.strip()!r} doesn't fit") def one_line(title: str) -> bool: @@ -217,7 +225,7 @@ def opened(title: str, body: str, run: Run) -> str | Failure: return number if isinstance(number, Failure) else f"Opened draft pull request #{number}." -def synced(run: Run) -> str | Failure: +def synced(run: Run, config: Config) -> str | Failure: found = checkout(run) if isinstance(found, Failure): return found @@ -231,11 +239,12 @@ def synced(run: Run) -> str | Failure: if isinstance(level, Failure): return level done = f"Merged origin/{base} into {branch}." if level else f"{branch} already holds origin/{base}." - plan = run([str(BIN / "project-config"), "plan"]) - if isinstance(plan, Failure): - return Failure(f"{done.removesuffix('.')}, but the plan to check cannot be found: {plan.reason}") - todo = pathlib.Path(plan.strip()) - if not todo.is_file(): + loaded = config() + if isinstance(loaded, Failure): + return Failure(f"{done.removesuffix('.')}, but the plan to check cannot be found: {loaded.reason}") + todo = loaded.plan_file + # A plan in Jira is no file, and Jira's backlog ranks it. + if todo is None or not todo.is_file(): return done ranked = run([str(BIN / "rank_todo.py"), "--check", str(todo)]) if isinstance(ranked, Failure): @@ -295,13 +304,16 @@ def finishes_of(given: list[str]) -> list[list[str]] | None: return finishes -def merged(run: Run, sleep: typing.Callable[[float], None] = time.sleep, finishes: typing.Sequence[list[str]] = ()) -> str | Failure: +def merged(run: Run, config: Config, sleep: typing.Callable[[float], None] = time.sleep, finishes: typing.Sequence[list[str]] = ()) -> str | Failure: """Merge the branch's pull request in the project's merge queue. Each pass of the loop is one turn in the queue; a pull request that still wants its approval leaves the queue while it waits, so the next chunk merges meanwhile, and takes a new turn once approved.""" found = pull(run) if isinstance(found, Failure): return found forge, number, _ = found - waits = awaited(forge, run) + loaded = config() + if isinstance(loaded, Failure): + return loaded + waits = awaited(forge, loaded.wait_for_approval) if isinstance(waits, Failure): return waits method = merge_method(forge, run) @@ -318,53 +330,82 @@ def merged(run: Run, sleep: typing.Callable[[float], None] = time.sleep, finishe if isinstance(absent, Failure): return absent file = pathlib.Path(queue[0]) / QUEUE + pull_request = Merging(forge, number, method, str(base), required, waits) while True: - try: - with turn(file, number, sleep): - head = levelled_and_finished(run, str(base), finishes) - checked = head if isinstance(head, Failure) else checks_passed(forge, number, head, required, run, sleep, NO_CHECKS_SECONDS) - if isinstance(checked, Failure): - return checked - ready = approval(number, run) if waits else True - asked = unanswered(number, run) if waits and ready is True else None - if isinstance(ready, Failure): - return ready - if asked is not None: - return asked - if ready and forge == "gh": - done = run(["gh", "pr", "merge", number, method, "--match-head-commit", str(head)]) - elif ready: - done = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{number}/merge", f"Do={method}", f"head_commit_id={head}") - if ready: - return done if isinstance(done, Failure) else f"Merged pull request #{number} ({method.removeprefix('--')}).{absent}" - except Held as held: - return Failure(f"the merge queue stayed held for {QUEUE_SECONDS // 60} minutes, last by pull request #{held.args[0] or '?'}, so this one took no turn; run chunk-pr merge again") - except OSError as failure: - return Failure(f"cannot take a turn in the merge queue, {file}: {failure.strerror}") + with turn(file, number, sleep) as untaken: + taken = untaken or merge_turn(pull_request, finishes, loaded, run, sleep) + if not isinstance(taken, AwaitsApproval): + return taken if isinstance(taken, Failure) else taken + absent + # Out of the queue, so the project's other chunks merge while this one waits. waited = approved(number, run, sleep) if isinstance(waited, Failure): return waited +@dataclasses.dataclass(frozen=True) +class Merging: + """A pull request that merge takes turns for: its forge and number, the merge method, the default branch it merges into with the checks that branch requires, and whether it waits for an approval.""" + forge: Forge + number: str + method: str + base: str + required: set[str] + waits: bool + + +@dataclasses.dataclass(frozen=True) +class AwaitsApproval: + """The pull request passed its checks but awaits a human's approval, so merge leaves the queue until it has one.""" + + +def merge_turn(pull_request: Merging, finishes: typing.Sequence[list[str]], config: ProjectConfig, run: Run, sleep: typing.Callable[[float], None]) -> str | AwaitsApproval | Failure: + """One turn in the queue: level the branch and finish its items, wait for its checks, and merge it where nothing still waits. What merged it, or why it waits or fails.""" + head = levelled_and_finished(run, pull_request.base, finishes, config) + checked = head if isinstance(head, Failure) else checks_passed(pull_request.forge, pull_request.number, head, pull_request.required, run, sleep, NO_CHECKS_SECONDS) + if isinstance(checked, Failure): + return checked + ready = approval(pull_request.number, run) if pull_request.waits else True + if isinstance(ready, Failure): + return ready + if not ready: + return AwaitsApproval() + asked = unanswered(pull_request.number, run) if pull_request.waits else None + if asked is not None: + return asked + if pull_request.forge == "gh": + done = run(["gh", "pr", "merge", pull_request.number, pull_request.method, "--match-head-commit", str(head)]) + else: + done = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{pull_request.number}/merge", f"Do={pull_request.method}", f"head_commit_id={head}") + return done if isinstance(done, Failure) else f"Merged pull request #{pull_request.number} ({pull_request.method.removeprefix('--')})." + + def unplanned(run: Run, finishes: typing.Sequence[list[str]]) -> str | Failure: """A sentence for merge's last line, naming each item of finishes the plan doesn't hold as merge begins: an earlier run finished it, or its ID is mistyped, and only the reader can tell which. Empty where the plan holds them all.""" absent = [] for finish in finishes: shown = run([str(BIN / "todo-item"), "show", finish[0]]) - if isinstance(shown, Failure) and f"holds no item {finish[0]}" not in shown.reason: + if isinstance(shown, Failure) and not says_no_item(shown.reason, finish[0]): return shown absent += [finish[0]] if isinstance(shown, Failure) else [] return f" The plan held no item {', '.join(absent)} when merge began, so merge left the plan as it was there." if absent else "" -class Held(Exception): - """Other merges kept the queue for QUEUE_SECONDS; the argument is the number of the pull request that held it last.""" - - @contextlib.contextmanager -def turn(queue: pathlib.Path, number: str, sleep: typing.Callable[[float], None]) -> typing.Iterator[None]: - """Hold the project's merge queue as pull request number: wait until no other chunk-pr merge on this machine holds it, and free it on the way out, however that is. Raises Held where another one still holds it after QUEUE_SECONDS, and OSError where the file cannot be opened or locked.""" - fd = os.open(queue, os.O_RDWR | os.O_CREAT, 0o644) +def turn(queue: pathlib.Path, number: str, sleep: typing.Callable[[float], None]) -> typing.Iterator[Failure | None]: + """Hold the project's merge queue as pull request number: wait until no other chunk-pr merge on this machine holds it, and free it on the way out, however that is. Gives None while it holds the queue; a Failure, without the queue, where another merge still holds it after QUEUE_SECONDS or the file cannot be opened or locked.""" + try: + fd = os.open(queue, os.O_RDWR | os.O_CREAT, 0o644) + except OSError as failure: + yield Failure(f"cannot take a turn in the merge queue, {queue}: {failure.strerror}") + return + try: + yield held_turn(fd, queue, number, sleep) + finally: + os.close(fd) + + +def held_turn(fd: int, queue: pathlib.Path, number: str, sleep: typing.Callable[[float], None]) -> Failure | None: + """Lock the open queue file fd for pull request number and write its number there, for a merge that waits to name; None once held, else why it isn't.""" try: for waited in range(0, QUEUE_SECONDS + 1, QUEUE_POLL_SECONDS): try: @@ -372,16 +413,17 @@ def turn(queue: pathlib.Path, number: str, sleep: typing.Callable[[float], None] break except BlockingIOError: if waited == QUEUE_SECONDS: - raise Held(os.pread(fd, 20, 0).decode(errors="replace").strip()) from None + holder = os.pread(fd, 20, 0).decode(errors="replace").strip() + return Failure(f"the merge queue stayed held for {QUEUE_SECONDS // 60} minutes, last by pull request #{holder or '?'}, so this one took no turn; run chunk-pr merge again") sleep(QUEUE_POLL_SECONDS) os.ftruncate(fd, 0) os.pwrite(fd, number.encode(), 0) - yield - finally: - os.close(fd) + except OSError as failure: + return Failure(f"cannot take a turn in the merge queue, {queue}: {failure.strerror}") + return None -def levelled_and_finished(run: Run, base: str, finishes: typing.Sequence[list[str]]) -> str | Failure: +def levelled_and_finished(run: Run, base: str, finishes: typing.Sequence[list[str]], config: ProjectConfig) -> str | Failure: """What merge does to the branch inside its turn, before the checks: merge origin's base into it, finish the plan items, and push. The head to merge, or why the worker must act first. Whatever it committed is pushed before it fails, so the pull request's head stays the commit checked out.""" found = checkout(run) if isinstance(found, Failure): @@ -390,7 +432,7 @@ def levelled_and_finished(run: Run, base: str, finishes: typing.Sequence[list[st moved = levelled(run, branch, base, "resolve them, commit, push, and run chunk-pr merge again") if isinstance(moved, Failure): return moved - failed = next((failure for finish in finishes if (failure := finished(run, branch, finish))), None) + failed = next((failure for finish in finishes if (failure := finished(run, branch, finish, config))), None) head = answers(run, ["rev-parse", "HEAD"]) if isinstance(head, Failure): return head @@ -401,22 +443,21 @@ def levelled_and_finished(run: Run, base: str, finishes: typing.Sequence[list[st owed = failed or run([str(BIN / "larv-review"), "scoring-run-owed"]) if isinstance(owed, Failure): return owed - return remeasure(run, base) or head[0] + return remeasure(run, base, config) or head[0] -def finished(run: Run, branch: str, finish: list[str]) -> Failure | None: +def finished(run: Run, branch: str, finish: list[str], config: ProjectConfig) -> Failure | None: """Finish one plan item with `todo-item finish` and commit what that changed. An item the plan no longer holds was finished by an earlier run of merge, which may have stopped before its commit: so the plan and the changelog are committed either way.""" shown = run([str(BIN / "todo-item"), "show", finish[0]]) - if isinstance(shown, Failure) and f"holds no item {finish[0]}" not in shown.reason: + if isinstance(shown, Failure) and not says_no_item(shown.reason, finish[0]): return shown - read = ["" if isinstance(shown, Failure) else run([str(BIN / "todo-item"), "finish", *finish]), run([str(BIN / "project-config"), "commit-title"]), run([str(BIN / "project-config"), "branch"]), run([str(BIN / "project-config"), "plan"]), run([str(BIN / "project-config"), "changelog"])] - if failed := next((answer for answer in read if isinstance(answer, Failure)), None): - return failed - _, template, branch_template, *records = (str(answer).strip() for answer in read) - summary = f"Finish item {finish[0]} in the plan" - # A branch that doesn't fit the config's `branch` template has no ID for {id}, so its titles are the summary alone, as CLAUDE.md → "Git, commits, and PRs" says. - title = template.replace(templates.ID, finish[0]).replace(templates.SUMMARY, summary) if templates.branch_fits(branch_template, branch) else summary - return committed(run, title, [pathlib.Path(record) for record in records if pathlib.Path(record).is_file()]) + finishing = "" if isinstance(shown, Failure) else run([str(BIN / "todo-item"), "finish", *finish]) + if isinstance(finishing, Failure): + return finishing + title = templates.title_of(config.commit_title, config.branch, branch, finish[0], f"Finish item {finish[0]} in the plan") + # A plan in Jira, or a changelog on a Confluence page, is no file to commit. + records = [record for record in (config.plan_file, config.paths.get("changelog")) if record is not None and record.is_file()] + return committed(run, title, records) def committed(run: Run, title: str, files: list[pathlib.Path]) -> Failure | None: @@ -435,15 +476,16 @@ def committed(run: Run, title: str, files: list[pathlib.Path]) -> Failure | None return None -def remeasure(run: Run, base: str) -> Failure | None: +def remeasure(run: Run, base: str, config: ProjectConfig) -> Failure | None: """A Failure where origin's base has moved since the branch last recorded a paired ruling: that ruling read a head that no longer merges. None where the branch recorded none, or the project keeps its history outside the checkout.""" - history = run([str(BIN / "project-config"), "comprehension-history"]) - if isinstance(history, Failure): - return history + history = config.paths.get("comprehension-history") + # A history on a Confluence page is outside the checkout. + if history is None: + return None top = answers(run, ["rev-parse", "--show-toplevel"]) - if isinstance(top, Failure) or not pathlib.Path(history.strip()).resolve().is_relative_to(top[0]): + if isinstance(top, Failure) or not history.resolve().is_relative_to(top[0]): return top if isinstance(top, Failure) else None - ruled = answers(run, ["log", "-1", "--format=%H", "-G", RULING, f"origin/{base}..HEAD", "--", history.strip()]) + ruled = answers(run, ["log", "-1", "--format=%H", "-G", RULING, f"origin/{base}..HEAD", "--", str(history)]) if isinstance(ruled, Failure) or not ruled[0].strip(): return ruled if isinstance(ruled, Failure) else None since = answers(run, ["rev-list", "--count", f"{ruled[0].strip()}..origin/{base}"]) diff --git a/bin/chunk_pr/test_chunk_pr.py b/bin/chunk_pr/test_chunk_pr.py index 13090807..79b886ea 100644 --- a/bin/chunk_pr/test_chunk_pr.py +++ b/bin/chunk_pr/test_chunk_pr.py @@ -14,6 +14,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from chunk_pr.main import cleaned, merged, QUEUE, step, turn, USAGE from failure import Failure from test_env import isolated_env +from project_config.settings import ProjectConfig from deploy_release.forge import Run from chunk_pr.approval import THREADS @@ -33,6 +34,8 @@ OWED = [str(pathlib.Path(__file__).resolve().parents[1] / "larv-review"), "scori TITLE = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "pull-request-title"] BRANCH = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "branch"] WAITS = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "wait-for-approval"] +# The settings a fake checkout's answers hold, each under `project-config <setting>` as the tool once read it. +PROJECT_CONFIG = str(pathlib.Path(__file__).resolve().parents[1] / "project-config") GH_DECISION = ["gh", "pr", "view", "12", "--json", "reviewDecision"] GH_THREADS = ["gh", "api", "graphql", "-f", f"query={THREADS}", "-F", "owner={owner}", "-F", "repo={repo}", "-F", "number=12"] BEHIND = ["git", "rev-list", "--count", "HEAD..origin/main"] @@ -71,6 +74,15 @@ class Checkout: ("git", "rev-parse", "--show-toplevel"): "/checkout\n", } + def config(self) -> ProjectConfig | Failure: + """The project's config, from the settings the answers hold under PROJECT_CONFIG; a Failure where one of them is, as where no config names the checkout.""" + named = {key[1]: answer for key, answer in self.answers.items() if key[0] == PROJECT_CONFIG} + if failed := next((answer for answer in named.values() if isinstance(answer, Failure)), None): + return failed + texts = {name: str(answer).strip() for name, answer in named.items()} + paths = {name: pathlib.Path(texts[name]) for name in ("plan", "changelog", "comprehension-history") if texts.get(name, "").startswith("/")} + return ProjectConfig("proj", pathlib.Path("/config"), pathlib.Path("/checkout"), paths, wait_for_approval=texts.get("wait-for-approval") == "true", commit_title=texts.get("commit-title", "{summary}"), pull_request_title=texts.get("pull-request-title", "{summary}"), branch=texts.get("branch", "item-{id}")) + def __call__(self, command: list[str]) -> str | Failure: self.ran.append(command) if command[0] == ("tea" if self.github else "gh"): @@ -110,32 +122,32 @@ class Open(unittest.TestCase): checkout = Checkout(GITHUB, open=argv[0] == "ready") checkout.answers[tuple(TITLE)] = "PAY-{id} - {summary}\n" checkout.answers[tuple(BRANCH)] = "feature/PAY-{id}\n" - self.assertNotIsInstance(step(argv, checkout), Failure) + self.assertNotIsInstance(step(argv, checkout, checkout.config), Failure) checkout.answers[("git", "symbolic-ref", "--short", "HEAD")] = "feature/PAY-7\n" - refused = step(argv, checkout) + refused = step(argv, checkout, checkout.config) assert isinstance(refused, Failure), refused self.assertIn("'Release review of 0.3.0' doesn't fit", refused.reason) def test_github_pushes_and_opens_a_draft_into_the_default_branch(self): checkout = Checkout(GITHUB, open=False) - opened = step(["open", "ABC-1 - Do it", "The body."], checkout) + opened = step(["open", "ABC-1 - Do it", "The body."], checkout, checkout.config) self.assertEqual(checkout.acted(), [PUSH, ["gh", "pr", "create", "--draft", "--head", "item-7", "--base", "main", "--title", "ABC-1 - Do it", "--body", "The body."]]) self.assertEqual(opened, "Opened draft pull request #12.") def test_gitea_opens_a_draft_with_tea(self): checkout = Checkout(GITEA, open=False) - self.assertEqual(step(["open", "Do it"], checkout), "Opened draft pull request #12.") + self.assertEqual(step(["open", "Do it"], checkout, checkout.config), "Opened draft pull request #12.") self.assertEqual(checkout.acted(), [PUSH, ["tea", "pulls", "create", "--draft", "--head", "item-7", "--base", "main", "--title", "Do it", "--description", ""]]) def test_an_open_pull_request_is_kept(self): checkout = Checkout(GITEA, open=True) - self.assertEqual(step(["open", "Do it"], checkout), "Pull request #12 is open already.") + self.assertEqual(step(["open", "Do it"], checkout, checkout.config), "Pull request #12 is open already.") self.assertEqual(checkout.acted(), [PUSH]) def test_on_the_default_branch_it_refuses_and_pushes_nothing(self): checkout = Checkout(GITEA, open=False) checkout.answers[("git", "symbolic-ref", "--short", "HEAD")] = "main\n" - self.assertIsInstance(step(["open", "Do it"], checkout), Failure) + self.assertIsInstance(step(["open", "Do it"], checkout, checkout.config), Failure) self.assertEqual(checkout.acted(), []) def test_a_title_that_does_not_fit_the_configs_template_is_refused_before_anything_runs(self): @@ -143,75 +155,75 @@ class Open(unittest.TestCase): with self.subTest(argv=argv): checkout = Checkout(GITHUB, open=argv[0] == "ready") checkout.answers[tuple(TITLE)] = "PAY-{id} - {summary}\n" - refused = step(argv, checkout) + refused = step(argv, checkout, checkout.config) assert isinstance(refused, Failure), refused self.assertIn("`PAY-{id} - {summary}`", refused.reason) self.assertEqual(checkout.acted(), []) - self.assertNotIsInstance(step([argv[0], "PAY-7 - Do it"], checkout), Failure) + self.assertNotIsInstance(step([argv[0], "PAY-7 - Do it"], checkout, checkout.config), Failure) checkout.answers[tuple(TITLE)] = Failure("no config names the checkout") - self.assertEqual(step(argv, checkout), Failure("no config names the checkout")) + self.assertEqual(step(argv, checkout, checkout.config), Failure("no config names the checkout")) checkout.answers[tuple(TITLE)] = "PAY-{id} - {summary}\n" checkout.answers[tuple(BRANCH)] = Failure("`branch` is 'x', which holds no {id}") - self.assertEqual(step(argv, checkout), Failure("`branch` is 'x', which holds no {id}")) + self.assertEqual(step(argv, checkout, checkout.config), Failure("`branch` is 'x', which holds no {id}")) untitled = Checkout(GITHUB, open=True) untitled.answers[tuple(TITLE)] = Failure("no config names the checkout") - self.assertNotIsInstance(step(["ready"], untitled), Failure) + self.assertNotIsInstance(step(["ready"], untitled, untitled.config), Failure) def test_a_title_of_more_than_one_line_or_a_second_body_is_refused_before_anything_runs(self): for argv, refusal in ((["open", "Do it\nand more"], "give a title of one line"), (["open", " "], "give a title of one line"), (["open", "Do it", "Body", "More"], USAGE)): with self.subTest(argv): checkout = Checkout(GITHUB, open=False) - self.assertEqual(step(argv, checkout), Failure(refusal)) + self.assertEqual(step(argv, checkout, checkout.config), Failure(refusal)) self.assertEqual(checkout.ran, []) def test_a_failed_listing_after_the_create_is_returned(self): checkout = Checkout(GITHUB, open=False) checkout.answers[("gh", "pr", "create", "--draft", "--head", "item-7", "--base", "main", "--title", "Do it", "--body", "")] = Failure("gh pr create: done") - self.assertEqual(step(["open", "Do it"], checkout), Failure("gh pr create: done")) + self.assertEqual(step(["open", "Do it"], checkout, checkout.config), Failure("gh pr create: done")) checkout = Checkout(GITHUB, open=False) listings = iter(["", Failure("gh pr list: offline")]) original = checkout.__call__ checkout_call = lambda command: next(listings) if command == GH_LIST else original(command) - self.assertEqual(step(["open", "Do it"], checkout_call), Failure("gh pr list: offline")) + self.assertEqual(step(["open", "Do it"], checkout_call, checkout.config), Failure("gh pr list: offline")) class Ready(unittest.TestCase): def test_github_marks_it_ready(self): checkout = Checkout(GITHUB, open=True) - self.assertEqual(step(["ready"], checkout), "Marked pull request #12 ready.") + self.assertEqual(step(["ready"], checkout, checkout.config), "Marked pull request #12 ready.") self.assertEqual(checkout.acted(), [["gh", "pr", "ready", "12"]]) def test_gitea_marks_it_ready_with_tea(self): checkout = Checkout(GITEA, open=True) - self.assertEqual(step(["ready"], checkout), "Marked pull request #12 ready.") + self.assertEqual(step(["ready"], checkout, checkout.config), "Marked pull request #12 ready.") self.assertEqual(checkout.acted(), [["tea", "pulls", "edit", "12", "--ready"]]) def test_github_sets_a_given_title_then_marks_it_ready(self): checkout = Checkout(GITHUB, open=True) - self.assertEqual(step(["ready", "Ship it"], checkout), "Marked pull request #12 ready, titled “Ship it”.") + self.assertEqual(step(["ready", "Ship it"], checkout, checkout.config), "Marked pull request #12 ready, titled “Ship it”.") self.assertEqual(checkout.acted(), [["gh", "pr", "edit", "12", "--title", "Ship it"], ["gh", "pr", "ready", "12"]]) def test_gitea_sets_a_given_title_in_the_call_that_marks_it_ready(self): checkout = Checkout(GITEA, open=True) - self.assertEqual(step(["ready", "Ship it"], checkout), "Marked pull request #12 ready, titled “Ship it”.") + self.assertEqual(step(["ready", "Ship it"], checkout, checkout.config), "Marked pull request #12 ready, titled “Ship it”.") self.assertEqual(checkout.acted(), [["tea", "pulls", "edit", "12", "--title", "Ship it", "--ready"]]) def test_a_title_of_more_than_one_line_or_none_is_refused_before_anything_runs(self): for argv, refusal in ((["ready", "Ship\nit"], "give a title of one line"), (["ready", " "], "give a title of one line"), (["ready", "Ship it", "twice"], USAGE)): with self.subTest(argv=argv): checkout = Checkout(GITHUB, open=True) - self.assertEqual(step(argv, checkout), Failure(refusal)) + self.assertEqual(step(argv, checkout, checkout.config), Failure(refusal)) self.assertEqual(checkout.ran, []) def test_a_failed_title_edit_on_github_leaves_it_a_draft(self): checkout = Checkout(GITHUB, open=True) checkout.answers[("gh", "pr", "edit", "12", "--title", "Ship it")] = Failure("gh pr edit: denied") - self.assertEqual(step(["ready", "Ship it"], checkout), Failure("gh pr edit: denied")) + self.assertEqual(step(["ready", "Ship it"], checkout, checkout.config), Failure("gh pr edit: denied")) self.assertNotIn(["gh", "pr", "ready", "12"], checkout.ran) def test_without_an_open_pull_request_at_the_head_it_fails_naming_the_branch(self): checkout = Checkout(GITHUB, open=False) - ready = step(["ready"], checkout) + ready = step(["ready"], checkout, checkout.config) self.assertIsInstance(ready, Failure) self.assertIn("item-7", ready.reason) self.assertEqual(checkout.acted(), []) @@ -219,10 +231,10 @@ class Ready(unittest.TestCase): def test_a_failed_ready_or_git_call_is_returned(self): checkout = Checkout(GITEA, open=True) checkout.answers[("tea", "pulls", "edit", "12", "--ready")] = Failure("tea pulls edit: denied") - self.assertEqual(step(["ready"], checkout), Failure("tea pulls edit: denied")) + self.assertEqual(step(["ready"], checkout, checkout.config), Failure("tea pulls edit: denied")) checkout = Checkout(GITEA, open=True) checkout.answers[("git", "symbolic-ref", "--short", "HEAD")] = Failure("git symbolic-ref: HEAD is detached") - self.assertEqual(step(["ready"], checkout), Failure("git symbolic-ref: HEAD is detached")) + self.assertEqual(step(["ready"], checkout, checkout.config), Failure("git symbolic-ref: HEAD is detached")) self.assertEqual(checkout.acted(), []) @@ -249,34 +261,34 @@ class Sync(unittest.TestCase): def test_a_branch_behind_the_default_branch_merges_it(self): checkout = self.checkout(behind=3) - self.assertEqual(step(["sync"], checkout), "Merged origin/main into item-7.") + self.assertEqual(step(["sync"], checkout, checkout.config), "Merged origin/main into item-7.") self.assertEqual(checkout.acted(), [FETCH, MERGE]) def test_a_branch_that_holds_the_default_branch_merges_nothing(self): checkout = self.checkout(behind=0) - self.assertEqual(step(["sync"], checkout), "item-7 already holds origin/main.") + self.assertEqual(step(["sync"], checkout, checkout.config), "item-7 already holds origin/main.") self.assertEqual(checkout.acted(), [FETCH]) def test_a_worktree_with_a_todo_md_runs_the_rank_check_after_the_merge(self): checkout = self.checkout(behind=1, todo=True) - self.assertEqual(step(["sync"], checkout), f"Merged origin/main into item-7.\nrank_todo.py --check todo.md passed.") + self.assertEqual(step(["sync"], checkout, checkout.config), f"Merged origin/main into item-7.\nrank_todo.py --check todo.md passed.") self.assertEqual(checkout.acted(), [FETCH, MERGE, [RANK, "--check", self.todo]]) def test_a_checkout_no_config_names_fails_naming_what_it_did(self): checkout = self.checkout(behind=0, todo=True) checkout.answers[PLAN] = Failure("no config names the checkout") - self.assertEqual(step(["sync"], checkout), Failure("item-7 already holds origin/main, but the plan to check cannot be found: no config names the checkout")) + self.assertEqual(step(["sync"], checkout, checkout.config), Failure("item-7 already holds origin/main, but the plan to check cannot be found: no config names the checkout")) def test_a_failing_rank_check_fails_naming_what_it_did(self): checkout = self.checkout(behind=0, todo=True) checkout.answers[(RANK, "--check", self.todo)] = Failure("rank_todo.py --check: item 3 is out of order") - self.assertEqual(step(["sync"], checkout), Failure("item-7 already holds origin/main, but rank_todo.py --check todo.md failed: rank_todo.py --check: item 3 is out of order")) + self.assertEqual(step(["sync"], checkout, checkout.config), Failure("item-7 already holds origin/main, but rank_todo.py --check todo.md failed: rank_todo.py --check: item 3 is out of order")) def test_a_conflict_leaves_the_merge_in_progress_and_names_the_conflicted_files(self): checkout = self.checkout(behind=2, todo=True) checkout.answers[tuple(MERGE)] = Failure("git merge --quiet: CONFLICT") checkout.answers[CONFLICTED] = "todo.md\nREADME.md\n" - self.assertEqual(step(["sync"], checkout), Failure("merging origin/main into item-7 conflicts in todo.md, README.md; the merge stays in progress: resolve them and commit")) + self.assertEqual(step(["sync"], checkout, checkout.config), Failure("merging origin/main into item-7 conflicts in todo.md, README.md; the merge stays in progress: resolve them and commit")) self.assertNotIn([RANK, "--check", self.todo], checkout.ran) self.assertNotIn(["git", "merge", "--abort"], checkout.ran) @@ -284,18 +296,18 @@ class Sync(unittest.TestCase): checkout = self.checkout(behind=2) checkout.answers[tuple(MERGE)] = Failure("git merge --quiet: untracked files would be overwritten") checkout.answers[CONFLICTED] = "" - self.assertEqual(step(["sync"], checkout), Failure("git merge --quiet: untracked files would be overwritten")) + self.assertEqual(step(["sync"], checkout, checkout.config), Failure("git merge --quiet: untracked files would be overwritten")) def test_on_the_default_branch_it_refuses_and_fetches_nothing(self): checkout = self.checkout(behind=0) checkout.answers[("git", "symbolic-ref", "--short", "HEAD")] = "main\n" - self.assertEqual(step(["sync"], checkout), Failure("main is origin's default branch; sync the chunk's branch")) + self.assertEqual(step(["sync"], checkout, checkout.config), Failure("main is origin's default branch; sync the chunk's branch")) self.assertNotIn(FETCH, checkout.ran) def test_a_failed_fetch_is_returned(self): checkout = self.checkout(behind=0) checkout.answers[tuple(FETCH)] = Failure("git fetch --quiet: could not read from remote") - self.assertEqual(step(["sync"], checkout), Failure("git fetch --quiet: could not read from remote")) + self.assertEqual(step(["sync"], checkout, checkout.config), Failure("git fetch --quiet: could not read from remote")) def changes(checkout: Checkout) -> list[list[str]]: @@ -306,31 +318,31 @@ def changes(checkout: Checkout) -> list[list[str]]: class Merge(unittest.TestCase): def test_the_gate_passed_flag_it_no_longer_takes_is_refused_before_anything_runs(self): checkout = Checkout(GITHUB, open=True) - self.assertIsInstance(step(["merge", "--gate-passed"], checkout), Failure) + self.assertIsInstance(step(["merge", "--gate-passed"], checkout, checkout.config), Failure) self.assertEqual(checkout.ran, []) def test_an_option_given_as_a_title_runs_nothing(self): for argv in (["ready", "--help"], ["open", "-h"]): checkout = Checkout(GITHUB, open=True) - self.assertEqual(step(argv, checkout), Failure(USAGE)) + self.assertEqual(step(argv, checkout, checkout.config), Failure(USAGE)) self.assertEqual(checkout.ran, []) def test_github_waits_for_the_checks_before_merging(self): checkout = Checkout(GITHUB, open=True) - self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).") + self.assertEqual(step(["merge"], checkout, checkout.config), "Merged pull request #12 (merge).") self.assertEqual(checkout.ran[-2:], [GH_CHECKS, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]]) def test_a_failed_check_on_github_leaves_it_unmerged(self): checkout = Checkout(GITHUB, open=True) checkout.answers[tuple(GH_CHECKS)] = Failure("gh pr checks 12: CI / tests\tfail") - self.assertEqual(step(["merge"], checkout), Failure("gh pr checks 12: CI / tests\tfail")) + self.assertEqual(step(["merge"], checkout, checkout.config), Failure("gh pr checks 12: CI / tests\tfail")) self.assertEqual(changes(checkout), []) def test_github_waits_a_minute_for_checks_to_report_before_taking_none_as_passed(self): checkout = Checkout(GITHUB, open=True) checkout.answers[tuple(GH_CHECKS)] = Failure("no checks reported on the 'item-7' branch") slept: list[float] = [] - self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).") + self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).") self.assertEqual(sum(slept), 60) self.assertEqual(checkout.ran.count(GH_CHECKS), 7) @@ -338,7 +350,7 @@ class Merge(unittest.TestCase): checkout = Checkout(GITEA, open=True) checkout.statuses = [json.dumps({"total_count": 0, "state": "pending", "statuses": []})] * 7 slept: list[float] = [] - self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).") + self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).") self.assertEqual(sum(slept), 60) def requiring_approval(self, origin: str = GITHUB, *decisions: str) -> Checkout: @@ -351,24 +363,24 @@ class Merge(unittest.TestCase): def test_a_project_without_wait_for_approval_never_reads_the_review_decision(self): checkout = Checkout(GITHUB, open=True) checkout.decisions = ["REVIEW_REQUIRED"] - self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).") + self.assertEqual(step(["merge"], checkout, checkout.config), "Merged pull request #12 (merge).") self.assertNotIn(GH_DECISION, checkout.ran) def test_an_approved_pull_request_merges_after_the_checks_and_the_approval(self): checkout = self.requiring_approval() - self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).") + self.assertEqual(step(["merge"], checkout, checkout.config), "Merged pull request #12 (merge).") self.assertEqual(checkout.ran[-4:], [GH_CHECKS, GH_DECISION, GH_THREADS, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]]) def test_it_waits_a_minute_at_a_time_while_the_branch_protection_still_wants_a_review(self): checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED", "REVIEW_REQUIRED", "APPROVED") slept: list[float] = [] - self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).") + self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).") self.assertEqual(slept, [60]) def test_an_approval_that_never_comes_leaves_it_unmerged_after_90_minutes(self): checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED") slept: list[float] = [] - failed = merged(checkout, slept.append) + failed = merged(checkout, checkout.config, slept.append) self.assertIsInstance(failed, Failure) self.assertIn("90 minutes", failed.reason) self.assertEqual(sum(slept), 90 * 60) @@ -377,7 +389,7 @@ class Merge(unittest.TestCase): def test_an_approval_that_comes_in_the_last_minute_still_merges(self): checkout = self.requiring_approval(GITHUB, *["REVIEW_REQUIRED"] * 91, "APPROVED") slept: list[float] = [] - self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).") + self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).") self.assertEqual(sum(slept), 90 * 60) def test_a_review_decision_it_cannot_read_or_does_not_know_leaves_it_unmerged(self): @@ -385,13 +397,13 @@ class Merge(unittest.TestCase): with self.subTest(answer): checkout = self.requiring_approval() checkout.unreadable = answer - self.assertIsInstance(step(["merge"], checkout), Failure) + self.assertIsInstance(step(["merge"], checkout, checkout.config), Failure) self.assertEqual(changes(checkout), []) def test_requested_changes_leave_it_unmerged_without_waiting(self): checkout = self.requiring_approval(GITHUB, "CHANGES_REQUESTED") slept: list[float] = [] - failed = merged(checkout, slept.append) + failed = merged(checkout, checkout.config, slept.append) self.assertIsInstance(failed, Failure) self.assertIn("requested changes", failed.reason) self.assertEqual((slept, changes(checkout)), ([], [])) @@ -400,25 +412,23 @@ class Merge(unittest.TestCase): for decision in ("", None): with self.subTest(decision): checkout = self.requiring_approval(GITHUB, decision) - failed = step(["merge"], checkout) + failed = step(["merge"], checkout, checkout.config) self.assertIsInstance(failed, Failure) self.assertIn("requires no review", failed.reason) self.assertEqual(changes(checkout), []) def test_gitea_with_wait_for_approval_leaves_it_unmerged_since_chunk_pr_reads_approvals_on_github_only(self): checkout = self.requiring_approval(GITEA) - failed = step(["merge"], checkout) + failed = step(["merge"], checkout, checkout.config) self.assertIsInstance(failed, Failure) self.assertIn("GitHub", failed.reason) self.assertEqual(changes(checkout), []) - def test_a_config_it_cannot_read_or_that_prints_neither_true_nor_false_leaves_it_unmerged(self): - for answer in (Failure("no config names the checkout"), "maybe\n", ""): - with self.subTest(answer): - checkout = Checkout(GITHUB, open=True) - checkout.answers[tuple(WAITS)] = answer - self.assertIsInstance(step(["merge"], checkout), Failure) - self.assertEqual(changes(checkout), []) + def test_a_config_it_cannot_read_leaves_it_unmerged(self): + checkout = Checkout(GITHUB, open=True) + checkout.answers[tuple(WAITS)] = Failure("no config names the checkout") + self.assertEqual(step(["merge"], checkout, checkout.config), Failure("no config names the checkout")) + self.assertEqual(changes(checkout), []) def protected(self, *reads: list[tuple[str, str]]) -> Checkout: """A Gitea Checkout whose main requires a check matching CI / tests*, its status at HEAD holding each of reads in turn.""" @@ -434,32 +444,32 @@ class Merge(unittest.TestCase): def test_gitea_waits_until_the_required_check_reports_and_passes_then_merges(self): checkout = self.protected([], [("CI / tests (pull_request)", "pending")], [("CI / tests (pull_request)", "success")]) slept: list[float] = [] - self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).") + self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).") self.assertEqual(len(slept), 2) self.assertEqual(checkout.ran.count(TEA_STATUS), 3) def test_a_failed_check_on_gitea_leaves_it_unmerged(self): checkout = self.protected([("CI / tests (pull_request)", "pending")], [("CI / tests (pull_request)", "failure")]) - self.assertIsInstance(merged(checkout, lambda _: None), Failure) + self.assertIsInstance(merged(checkout, checkout.config, lambda _: None), Failure) self.assertEqual(changes(checkout), []) def test_a_branch_protection_it_cannot_read_leaves_it_unmerged(self): checkout = Checkout(GITEA, open=True) checkout.answers[tuple(TEA_BRANCH)] = Failure("tea api: 500") - self.assertEqual(merged(checkout, self.fail), Failure("tea api: 500")) + self.assertEqual(merged(checkout, checkout.config, self.fail), Failure("tea api: 500")) self.assertNotIn(TEA_STATUS, checkout.ran) self.assertEqual(changes(checkout), []) def test_an_unknown_default_branch_leaves_it_unmerged_reading_no_checks(self): checkout = Checkout(GITEA, open=True) checkout.answers[("git", "symbolic-ref", "--short", "refs/remotes/origin/HEAD")] = Failure("no such ref") - self.assertEqual(merged(checkout, self.fail), Failure("origin records no default branch; set it with `git remote set-head origin --auto`: no such ref")) + self.assertEqual(merged(checkout, checkout.config, self.fail), Failure("origin records no default branch; set it with `git remote set-head origin --auto`: no such ref")) self.assertNotIn(TEA_STATUS, checkout.ran) self.assertEqual(changes(checkout), []) def test_gitea_checks_that_never_pass_leave_it_unmerged(self): checkout = self.protected(*[[("CI / tests (pull_request)", "pending")]] * 1000) - failed = merged(checkout, lambda _: None) + failed = merged(checkout, checkout.config, lambda _: None) self.assertIsInstance(failed, Failure) self.assertIn("gave up on pull request 12", failed.reason) self.assertEqual(changes(checkout), []) @@ -469,43 +479,43 @@ class Merge(unittest.TestCase): with self.subTest(origin=origin): checkout = Checkout(origin, open=True) checkout.answers[tuple(OWED)] = Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs") - self.assertEqual(step(["merge"], checkout), Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs")) + self.assertEqual(step(["merge"], checkout, checkout.config), Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs")) self.assertEqual(changes(checkout), []) def test_github_merges_with_a_merge_commit_pinned_to_the_head(self): checkout = Checkout(GITHUB, open=True, allowed=("squashMergeAllowed", "mergeCommitAllowed")) - self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).") + self.assertEqual(step(["merge"], checkout, checkout.config), "Merged pull request #12 (merge).") self.assertEqual(changes(checkout), [["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]]) def test_github_without_merge_commits_rebases(self): checkout = Checkout(GITHUB, open=True, allowed=("squashMergeAllowed", "rebaseMergeAllowed")) - step(["merge"], checkout) + step(["merge"], checkout, checkout.config) self.assertEqual(changes(checkout), [["gh", "pr", "merge", "12", "--rebase", "--match-head-commit", HEAD]]) def test_gitea_merges_fast_forward_only_where_only_that_and_squash_are_allowed(self): checkout = Checkout(GITEA, open=True, allowed=("allow_squash_merge", "allow_fast_forward_only_merge")) - self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (fast-forward-only).") + self.assertEqual(step(["merge"], checkout, checkout.config), "Merged pull request #12 (fast-forward-only).") self.assertEqual(changes(checkout), [["tea", "api", "--method", "POST", "--field", "Do=fast-forward-only", "--field", f"head_commit_id={HEAD}", "repos/{owner}/{repo}/pulls/12/merge"]]) def test_a_repository_allowing_no_known_method_is_refused_unmerged(self): checkout = Checkout(GITEA, open=True, allowed=("allow_manual_merge",)) - self.assertIsInstance(step(["merge"], checkout), Failure) + self.assertIsInstance(step(["merge"], checkout, checkout.config), Failure) self.assertEqual(changes(checkout), []) def test_a_forge_failure_is_returned(self): checkout = Checkout(GITHUB, open=True) checkout.answers[("gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD)] = Failure("gh pr merge: head moved") - self.assertEqual(step(["merge"], checkout), Failure("gh pr merge: head moved")) + self.assertEqual(step(["merge"], checkout, checkout.config), Failure("gh pr merge: head moved")) checkout = Checkout(GITHUB, open=True) checkout.answers[tuple(GH_SETTINGS)] = "not json" - self.assertIsInstance(step(["merge"], checkout), Failure) + self.assertIsInstance(step(["merge"], checkout, checkout.config), Failure) def test_a_failed_settings_read_is_returned_unmerged(self): for origin, settings in ((GITHUB, GH_SETTINGS), (GITEA, TEA_SETTINGS)): with self.subTest(origin): checkout = Checkout(origin, open=True) checkout.answers[tuple(settings)] = Failure("settings: denied") - self.assertEqual(step(["merge"], checkout), Failure("settings: denied")) + self.assertEqual(step(["merge"], checkout, checkout.config), Failure("settings: denied")) self.assertEqual(changes(checkout), []) @@ -568,12 +578,12 @@ class MergeQueue(unittest.TestCase): for flags in (["--finish"], ["--finish", "abc"], ["--changelog", "Bullet."], ["12"], ["--finish", "--no-changelog"], ["--finish", "7", "--changelog"], ["--finish", "7", "--no-changelog", "--changelog", "Bullet."]): with self.subTest(flags): checkout = Checkout(GITHUB, open=True) - self.assertEqual(step(["merge", *flags], checkout), Failure(USAGE)) + self.assertEqual(step(["merge", *flags], checkout, checkout.config), Failure(USAGE)) self.assertEqual(checkout.ran, []) def test_a_branch_behind_the_default_branch_merges_it_in_and_pushes_before_the_checks(self): checkout = self.moved(Checkout(GITHUB, open=True)) - self.assertEqual(merged(checkout.__call__), "Merged pull request #12 (merge).") + self.assertEqual(merged(checkout.__call__, checkout.config), "Merged pull request #12 (merge).") self.assertEqual(changes(checkout), [MERGE, self.PUSHED, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", "decaf"]]) self.assertLess(checkout.ran.index(self.PUSHED), checkout.ran.index(GH_CHECKS)) @@ -581,7 +591,7 @@ class MergeQueue(unittest.TestCase): checkout = self.moved(Checkout(GITHUB, open=True)) checkout.answers[tuple(MERGE)] = Failure("git merge --quiet: CONFLICT") checkout.answers[("git", "diff", "--name-only", "--diff-filter=U")] = "bin/tool.py\n" - failed = merged(checkout.__call__) + failed = merged(checkout.__call__, checkout.config) self.assertIsInstance(failed, Failure) self.assertIn("conflicts in bin/tool.py; the merge stays in progress: resolve them, commit, push, and run chunk-pr merge again", failed.reason) self.assertEqual((changes(checkout), MERGE in checkout.ran), ([], True)) @@ -590,7 +600,7 @@ class MergeQueue(unittest.TestCase): def test_a_finished_item_is_committed_under_the_configs_title_and_pushed_before_the_merge(self): checkout, folder = self.with_plan(Checkout(GITHUB, open=True)) files = [f"{folder}/todo.md", f"{folder}/CHANGELOG.md"] - self.assertEqual(merged(checkout.__call__, finishes=[["7", "--changelog", "Exports keep their order."]]), "Merged pull request #12 (merge).") + self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7", "--changelog", "Exports keep their order."]]), "Merged pull request #12 (merge).") self.assertEqual(changes(checkout)[:1], [[self.TODO_ITEM, "finish", "7", "--changelog", "Exports keep their order."]]) self.assertEqual(changes(checkout)[-4:], [ ["git", "-C", folder, "add", "--", *files], @@ -602,12 +612,12 @@ class MergeQueue(unittest.TestCase): def test_the_flags_reach_todo_item_as_given(self): checkout, _ = self.with_plan(Checkout(GITHUB, open=True)) checkout.answers.update({(self.TODO_ITEM, "show", "8"): "From todo.md:\n", (self.TODO_ITEM, "show", "9"): "From todo.md:\n"}) - self.assertEqual(step(["merge", "--finish", "7", "--no-changelog", "--finish", "8", "--finish", "9", "--changelog", "Exports keep their order."], checkout.__call__), "Merged pull request #12 (merge).") + self.assertEqual(step(["merge", "--finish", "7", "--no-changelog", "--finish", "8", "--finish", "9", "--changelog", "Exports keep their order."], checkout.__call__, checkout.config), "Merged pull request #12 (merge).") self.assertEqual([command[1:] for command in checkout.ran if command[:2] == [self.TODO_ITEM, "finish"]], [["finish", "7", "--no-changelog"], ["finish", "8"], ["finish", "9", "--changelog", "Exports keep their order."]]) def test_an_item_the_plan_no_longer_holds_is_named_on_the_last_line_and_what_an_earlier_run_left_uncommitted_is_committed(self): checkout, folder = self.with_plan(Checkout(GITHUB, open=True), held=False) - self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), "Merged pull request #12 (merge). The plan held no item 7 when merge began, so merge left the plan as it was there.") + self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7"]]), "Merged pull request #12 (merge). The plan held no item 7 when merge began, so merge left the plan as it was there.") self.assertNotIn([self.TODO_ITEM, "finish", "7"], checkout.ran) self.assertEqual([command[3] for command in changes(checkout)[:-1]], ["add", "commit", "origin"]) self.assertEqual(changes(checkout)[-1], ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", "f00d"]) @@ -615,7 +625,7 @@ class MergeQueue(unittest.TestCase): def test_each_item_the_plan_no_longer_holds_is_named(self): checkout, _ = self.with_plan(Checkout(GITHUB, open=True), held=False) checkout.answers[(self.TODO_ITEM, "show", "8")] = Failure("todo-item show 8: todo.md holds no item 8") - self.assertIn("The plan held no item 7, 8 when merge began", str(merged(checkout.__call__, finishes=[["7"], ["8"]]))) + self.assertIn("The plan held no item 7, 8 when merge began", str(merged(checkout.__call__, checkout.config, finishes=[["7"], ["8"]]))) def test_a_plan_that_turns_unreadable_inside_the_turn_leaves_it_unmerged(self): checkout, _ = self.with_plan(Checkout(GITHUB, open=True)) @@ -623,7 +633,7 @@ class MergeQueue(unittest.TestCase): def run_whose_second_show_fails(command: list[str]) -> str | Failure: shows.extend([command] if command[1:2] == ["show"] else []) return Failure("todo-item show 7: unreadable") if command[1:2] == ["show"] and len(shows) == 2 else run(command) - self.assertEqual(merged(run_whose_second_show_fails, finishes=[["7"]]), Failure("todo-item show 7: unreadable")) + self.assertEqual(merged(run_whose_second_show_fails, checkout.config, finishes=[["7"]]), Failure("todo-item show 7: unreadable")) self.assertNotIn([self.TODO_ITEM, "finish", "7"], checkout.ran) def test_a_finish_that_changes_no_file_commits_and_pushes_nothing(self): @@ -634,13 +644,13 @@ class MergeQueue(unittest.TestCase): checkout.answers[("git", "-C", folder, "status", "--porcelain", "--", f"{folder}/todo.md", f"{folder}/CHANGELOG.md")] = "\n" else: checkout.answers.update({(self.CONFIG, "plan"): "PAY-1\n", (self.CONFIG, "changelog"): f"{folder}/none.md\n"}) - self.assertEqual(merged(checkout.__call__, finishes=[["7", "--no-changelog"]]), "Merged pull request #12 (merge).") + self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7", "--no-changelog"]]), "Merged pull request #12 (merge).") self.assertEqual(changes(checkout), [[self.TODO_ITEM, "finish", "7", "--no-changelog"], ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]]) def test_a_branch_outside_the_branch_template_titles_the_finish_with_the_summary_alone(self): checkout, folder = self.with_plan(Checkout(GITHUB, open=True)) checkout.answers[tuple(BRANCH)] = "feature/PAY-{id}\n" - merged(checkout.__call__, finishes=[["7"]]) + merged(checkout.__call__, checkout.config, finishes=[["7"]]) self.assertIn("Finish item 7 in the plan", [command[6] for command in checkout.ran if command[3:4] == ["commit"]]) def test_a_plan_it_cannot_read_or_an_item_it_cannot_finish_leaves_it_unmerged(self): @@ -648,35 +658,35 @@ class MergeQueue(unittest.TestCase): with self.subTest(failing): checkout, _ = self.with_plan(Checkout(GITHUB, open=True)) checkout.answers[(self.TODO_ITEM, failing, "7")] = Failure(f"todo-item {failing} 7: no config names the checkout") - self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), Failure(f"todo-item {failing} 7: no config names the checkout")) + self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7"]]), Failure(f"todo-item {failing} 7: no config names the checkout")) self.assertNotIn(self.PUSHED, checkout.ran) def test_a_step_of_the_turn_that_fails_leaves_it_unmerged_with_that_failure(self): _, folder = self.with_plan(Checkout(GITHUB, open=True)) - for failing in (FETCH, BEHIND, COMMON, self.PUSHED, ["git", "-C", "<plan>", "rev-parse", "--show-toplevel"], ["git", "-C", "<plan>", "add"], ["git", "-C", "<plan>", "commit"], [self.CONFIG, "comprehension-history"]): + for failing in (FETCH, BEHIND, COMMON, self.PUSHED, ["git", "-C", "<plan>", "rev-parse", "--show-toplevel"], ["git", "-C", "<plan>", "add"], ["git", "-C", "<plan>", "commit"]): with self.subTest(failing): checkout, folder = self.with_plan(Checkout(GITHUB, open=True)) run = checkout.__call__ def failing_run(command: list[str]) -> str | Failure: asked = ["<plan>" if part == folder else part for part in command] return Failure("that step failed") if tuple(asked[:len(failing)]) == tuple(failing) else run(command) - self.assertEqual(merged(failing_run, finishes=[["7"]]), Failure("that step failed")) + self.assertEqual(merged(failing_run, checkout.config, finishes=[["7"]]), Failure("that step failed")) self.assertNotIn("merge", [command[2] for command in checkout.ran if command[0] == "gh"]) def test_a_finish_that_fails_after_the_default_branch_was_merged_in_still_pushes_the_branch(self): checkout, _ = self.with_plan(self.moved(Checkout(GITHUB, open=True))) checkout.answers[(self.TODO_ITEM, "finish", "7")] = Failure("todo-item finish 7: a decision cites item 7") - self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), Failure("todo-item finish 7: a decision cites item 7")) + self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7"]]), Failure("todo-item finish 7: a decision cites item 7")) self.assertEqual(changes(checkout), [MERGE, self.PUSHED]) def test_the_scoring_run_is_asked_for_once_the_finish_is_committed_and_one_owed_leaves_it_unmerged(self): checkout, _ = self.with_plan(Checkout(GITHUB, open=True)) commit = lambda: next(index for index, command in enumerate(checkout.ran) if command[3:4] == ["commit"]) - self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), "Merged pull request #12 (merge).") + self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7"]]), "Merged pull request #12 (merge).") self.assertLess(commit(), checkout.ran.index(OWED)) checkout, _ = self.with_plan(Checkout(GITHUB, open=True)) checkout.answers[tuple(OWED)] = Failure("the chunk owes 1 scoring run") - self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), Failure("the chunk owes 1 scoring run")) + self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7"]]), Failure("the chunk owes 1 scoring run")) self.assertEqual(changes(checkout)[-1], self.PUSHED) def test_a_merge_holds_the_queue_through_the_checks_and_frees_it_while_it_waits_for_an_approval(self): @@ -688,7 +698,7 @@ class MergeQueue(unittest.TestCase): if command == GH_CHECKS: free.setdefault("during the checks", queue_is_free()) return checkout(command) - self.assertEqual(merged(run, lambda seconds: free.setdefault("waiting for the approval", queue_is_free())), "Merged pull request #12 (merge).") + self.assertEqual(merged(run, checkout.config, lambda seconds: free.setdefault("waiting for the approval", queue_is_free())), "Merged pull request #12 (merge).") self.assertEqual(free, {"during the checks": False, "waiting for the approval": True}) self.assertEqual(checkout.ran.count(FETCH), 2) @@ -698,19 +708,19 @@ class MergeQueue(unittest.TestCase): checkout.decisions = ["REVIEW_REQUIRED"] checkout.threads = [self.thread("bin/asked.py", "reviewer"), self.thread("bin/answered.py", "worker"), self.thread("bin/resolved.py", "reviewer", resolved=True)] slept: list[float] = [] - failed = merged(checkout, slept.append) + failed = merged(checkout, checkout.config, slept.append) self.assertIsInstance(failed, Failure) self.assertIn("waits for an answer, in bin/asked.py;", failed.reason) self.assertEqual((slept, changes(checkout)), ([], [])) checkout.threads = checkout.threads[1:] checkout.decisions = ["REVIEW_REQUIRED", "REVIEW_REQUIRED", "APPROVED"] - self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).") + self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).") def test_an_approved_pull_request_with_a_comment_that_waits_for_an_answer_stays_unmerged(self): checkout = Checkout(GITHUB, open=True) checkout.answers[tuple(WAITS)] = "true\n" checkout.threads = [self.thread("bin/asked.py", "reviewer")] - failed = merged(checkout) + failed = merged(checkout, checkout.config) self.assertIsInstance(failed, Failure) self.assertIn("waits for an answer, in bin/asked.py;", failed.reason) self.assertEqual(changes(checkout), []) @@ -721,7 +731,7 @@ class MergeQueue(unittest.TestCase): checkout = Checkout(GITHUB, open=True) checkout.answers.update({tuple(WAITS): "true\n", tuple(GH_THREADS): answer}) checkout.decisions = ["REVIEW_REQUIRED"] - self.assertEqual(merged(checkout, lambda seconds: None), Failure(reason)) + self.assertEqual(merged(checkout, checkout.config, lambda seconds: None), Failure(reason)) self.assertEqual(changes(checkout), []) def test_a_default_branch_that_moved_after_the_branchs_last_paired_ruling_stops_for_a_new_one(self): @@ -736,7 +746,7 @@ class MergeQueue(unittest.TestCase): with self.subTest(name): checkout = Checkout(GITHUB, open=True) checkout.answers.update({(self.CONFIG, "comprehension-history"): f"{history}\n", **answers}) - done = merged(checkout.__call__) + done = merged(checkout.__call__, checkout.config) self.assertEqual(isinstance(done, Failure) and "run the paired ruling again" in done.reason, stops, done) self.assertEqual(changes(checkout), [] if stops else [["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]]) @@ -744,14 +754,14 @@ class MergeQueue(unittest.TestCase): ruled = ("git", "log", "-1", "--format=%H", "-G", "^Ruling: ", "origin/main..HEAD", "--", "/checkout/history.md") checkout = Checkout(GITHUB, open=True) checkout.answers[(self.CONFIG, "comprehension-history")] = "/elsewhere/history.md\n" - self.assertEqual(merged(checkout.__call__), "Merged pull request #12 (merge).") + self.assertEqual(merged(checkout.__call__, checkout.config), "Merged pull request #12 (merge).") self.assertNotIn("log", [command[1] for command in checkout.ran]) for failing in (ruled, ("git", "rev-list", "--count", "bead..origin/main"), ("git", "rev-parse", "--show-toplevel")): with self.subTest(failing): checkout = Checkout(GITHUB, open=True) checkout.answers.update({(self.CONFIG, "comprehension-history"): "/checkout/history.md\n", ruled: "bead\n"}) checkout.answers[failing] = Failure("git failed") - self.assertEqual(merged(checkout.__call__), Failure("git failed")) + self.assertEqual(merged(checkout.__call__, checkout.config), Failure("git failed")) def test_a_turn_keeps_every_other_merge_out_until_it_ends_even_by_an_error(self): with self.assertRaises(ValueError): @@ -766,7 +776,7 @@ class MergeQueue(unittest.TestCase): with turn(pathlib.Path(GIT_FOLDER.name) / QUEUE, "1234", lambda seconds: None): pass with turn(pathlib.Path(GIT_FOLDER.name) / QUEUE, "31", lambda seconds: None): - failed = merged(checkout, slept.append) + failed = merged(checkout, checkout.config, slept.append) self.assertEqual(failed, Failure("the merge queue stayed held for 30 minutes, last by pull request #31, so this one took no turn; run chunk-pr merge again")) self.assertEqual((sum(slept), set(slept), changes(checkout)), (30 * 60, {10}, [])) @@ -774,12 +784,12 @@ class MergeQueue(unittest.TestCase): checkout = Checkout(GITHUB, open=True) holder = contextlib.ExitStack() holder.enter_context(turn(pathlib.Path(GIT_FOLDER.name) / QUEUE, "31", lambda seconds: None)) - self.assertEqual(merged(checkout, lambda seconds: holder.close()), "Merged pull request #12 (merge).") + self.assertEqual(merged(checkout, checkout.config, lambda seconds: holder.close()), "Merged pull request #12 (merge).") def test_a_queue_it_cannot_open_leaves_it_unmerged(self): checkout = Checkout(GITHUB, open=True) checkout.answers[tuple(COMMON)] = "/nonexistent/folder\n" - self.assertEqual(merged(checkout), Failure("cannot take a turn in the merge queue, /nonexistent/folder/chunk-pr-merge-queue: No such file or directory")) + self.assertEqual(merged(checkout, checkout.config), Failure("cannot take a turn in the merge queue, /nonexistent/folder/chunk-pr-merge-queue: No such file or directory")) self.assertEqual(checkout.acted(), []) diff --git a/bin/chunk_preflight/choices.py b/bin/chunk_preflight/choices.py index 8c57cb91..b8a48c57 100644 --- a/bin/chunk_preflight/choices.py +++ b/bin/chunk_preflight/choices.py @@ -1,68 +1,12 @@ """The pure choices the preflight's steps act on.""" import pathlib -from release_plan.release_standing import carried, chunk_item, Cut, dated_cut, LastCut, ReadyToCut, ReviewDue, Unknown, Unplanned -from chunk_preflight.gathered import CarriedOver, Forge, NoItem, Plan -from failure import Failure -from release_plan.todo_table import NoItemsTable -from plan_store import stores as plan_stores -from release_plan.release import version +from chunk_preflight.gathered import Forge # The command each forge's CLI lists pull requests with; pulls_command adds the flags that pick their rows and fields. PULLS_LIST: dict[Forge, tuple[str, ...]] = {"gh": ("gh", "pr", "list"), "tea": ("tea", "pulls", "list")} -def cut_name(cut: LastCut) -> str | None: - """How the preflight names the last cut: the tag, or the version under its dated CHANGELOG.md heading; None where nothing is cut.""" - if cut.tag is not None: - return None if isinstance(cut.tag, Failure) else cut.tag - headed = dated_cut(cut.tag, cut.changelog) - return None if headed is None else f"{version(headed)} (dated in CHANGELOG.md)" - - -def plan_name(default: str, outside: str | None) -> str: - """How the preflight names the plan it read: the default branch's todo.md, or the file or Jira epic, where the project's config puts it outside the checkout.""" - return outside if outside else f"{default}'s todo.md" - - -def planned(todo: plan_stores.Plan | Failure, cut: LastCut, default: str, branch: str, outside: str | None = None, item_id: int | None = None) -> Plan | NoItem: - """todo, which is the project's plan as its store read it and which plan_name names, with the item the next chunk takes first: the item of item_id where one is given, else release_standing.chunk_item's pick. Else why there is none. branch is the project's `branch` template.""" - where = plan_name(default, outside) - if isinstance(todo, NoItemsTable): - return NoItem(f"{where} holds no items table.") - if isinstance(todo, Failure): - return NoItem(f"{where} cannot be read: {todo.reason}.") - found = todo.items - if isinstance(cut.tag, Failure): - return NoItem(f"{default}'s tags cannot be read: {cut.tag.reason}. So which release is next cannot be told. Find the next release yourself.") - named = cut_name(cut) - last_cut = f"the last cut, {named}" if named is not None else "the start, since no release is cut yet" - pick = chunk_item(found, cut) - if isinstance(pick, Cut): - return NoItem(f"{where} files items under release {version(pick.release)}, which is not after {last_cut}; ask the human which release they belong to.") - if isinstance(pick, Unknown): - return NoItem(f"{where} may hold no item for the next release after {last_cut}: todo.md's texts since then, or the count of changes since then, cannot be read. Find the next release yourself.") - 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.") - 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.") - first = pick.item - if first is None: - return NoItem(f"every item of release {version(pick.release)} in {where} waits." if pick.release is not None else f"{where}'s items table holds no item.") - held = carried(found, cut) - moved = [(was, now) for was, now in zip(found, held) if was.release != now.release] - # Every carried item takes one release, the next. - over = CarriedOver(moved[0][1].release, tuple(was.id for was, _ in moved)) if moved else None - if item_id is not None: - first = next((item for item in held if item.id == item_id), None) - if first is None: - return NoItem(f"{where} holds no item {item_id}, the one --item names; it may have shipped.") - return Plan(held, first, f"{first.tagline}\n\n{first.detail}".strip(), branch, over, item_id is not None) - - def worktree_on(porcelain: str, branch: str) -> pathlib.Path | None: """The worktree on branch, in what `git worktree list --porcelain` printed; None where none is.""" for block in porcelain.split("\n\n"): diff --git a/bin/chunk_preflight/facts.py b/bin/chunk_preflight/facts.py index 46fc1143..33f8c3ba 100644 --- a/bin/chunk_preflight/facts.py +++ b/bin/chunk_preflight/facts.py @@ -1,12 +1,13 @@ """The lines the preflight prints, stated from what it gathered.""" -from release_plan.todo_table import bundle_candidates, BUNDLE_MAX_R, Item, ships_alone +from plan.todo_table import bundle_candidates, BUNDLE_MAX_R, Item, ships_alone from touch_predictions.beside import chunks_beside -from chunk_preflight.choices import cut_name, PULLS_LIST +from release_plan.next_chunk import cut_name, NextChunk, NoItem from release_plan.release_standing import dated_cut, LastCut, unreleased_entries, UNSEEN_RELEASES from failure import Failure -from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran +from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, Ran from text_files.markdown_text import listed, quoted -from release_plan.release import version +from chunk_preflight.choices import PULLS_LIST +from plan.release import version # CLAUDE.md → "Working loop" lets up to ten tiny items share a chunk, so a worker never needs more. A release with 24 joinable items would otherwise put about 155 lines of detail in every prompt. @@ -58,7 +59,7 @@ def item_lines(plan: str, item: ItemFacts) -> list[str]: ] -def carried_lines(plan: Plan) -> list[str]: +def carried_lines(plan: NextChunk) -> list[str]: """What the worker does about the items of a release someone cut while it held them.""" over = plan.carried if over is None: @@ -67,7 +68,7 @@ def carried_lines(plan: Plan) -> list[str]: return [f"- {items} filed under a release already cut, so {count} as release {version(over.into)}'s, the next. Move {them} there as this chunk's first change, with `~/.claude/bin/todo-item move`, and say so in the chunk's opening line. Where todo-item cannot move this plan's items, as in a Jira plan, leave {them} and ask the human, in the chunk's summary, to move {them}."] -def joining_details(plan: Plan) -> list[str]: +def joining_details(plan: NextChunk) -> list[str]: """The detail of each of the first JOINING_DETAILS items that may join the chunk, in the table's order, and what the worker lacks: an item with no detail, or the items left out.""" joining = bundle_candidates(plan.items, plan.first) if not joining: @@ -100,7 +101,7 @@ def open_pulls(stdout: str, forge: Forge, branch: str) -> list[str]: return [f"#{row[0]} {row[2]}" for row in rows if len(row) == 3 and row[1] == branch] -def bundled(plan: Plan) -> list[str]: +def bundled(plan: NextChunk) -> list[str]: first, candidates = plan.first, bundle_candidates(plan.items, plan.first) if ships_alone(first): return [f"- Item {first.id} has R above {BUNDLE_MAX_R}, so it ships alone."] @@ -110,7 +111,7 @@ def bundled(plan: Plan) -> list[str]: return [f'- The items of release {version(first.release)} that may join the chunk of item {first.id}, where `~/.claude/CLAUDE.md` → "Working loop" lets them share it:', *listed] -def beside(plan: Plan) -> list[str]: +def beside(plan: NextChunk) -> list[str]: """The items that may start chunks while first's runs, by touch_predictions' pick; no line where none of the release's items holds a prediction.""" first = plan.first found = chunks_beside(plan.items, first) diff --git a/bin/chunk_preflight/gathered.py b/bin/chunk_preflight/gathered.py index 698d5a3e..0656e15e 100644 --- a/bin/chunk_preflight/gathered.py +++ b/bin/chunk_preflight/gathered.py @@ -4,10 +4,8 @@ import pathlib import typing from failure import Failure -from release_plan.todo_table import Item from release_plan.release_standing import LastCut -from release_plan.release import Release -from project_config import templates +from release_plan.next_chunk import NextChunk, NoItem # The CLI that lists a forge's pull requests: gh for a github.com origin, tea for any other. Forge = typing.Literal["gh", "tea"] @@ -21,38 +19,6 @@ class Ran: stderr: str -@dataclasses.dataclass(frozen=True) -class CarriedOver: - """The items, by ID in the plan's order, that the plan files under a release already cut, and that count as `into`'s, the next release: release_standing.carried.""" - into: Release - ids: tuple[int, ...] - - -@dataclasses.dataclass(frozen=True) -class Plan: - """The default branch's plan items, each with its detail, and `first`: the item the next chunk takes first.""" - items: list[Item] - first: Item - # first's tagline and detail. - text: str - branch_template: str - # The items of a release already cut, which `items` and `first` hold as the next release's. None where every item's release is after the last cut. - carried: CarriedOver | None = None - # Whether --item named first, in place of the next release's first item that does not wait. - named: bool = False - - @property - def branch(self) -> str: - """The branch first's worktree is on.""" - return templates.branch_of(self.branch_template, self.first.id) - - -@dataclasses.dataclass(frozen=True) -class NoItem: - """Why the plan names no item for the next chunk, as a sentence the worker reads.""" - why: str - - @dataclasses.dataclass(frozen=True) class Worktree: path: pathlib.Path @@ -72,7 +38,7 @@ class NamedPath: @dataclasses.dataclass(frozen=True) class ItemFacts: """What the preflight found or made for the plan's first item.""" - plan: Plan + plan: NextChunk worktree: Worktree | Failure # The forge whose CLI listed the open pull requests, and how it ran; None without an origin remote. pulls: tuple[Forge, Ran | Failure] | None @@ -91,7 +57,7 @@ class Gathered: cut: LastCut # What was found or made for the plan's first item; else why the plan names none. item: ItemFacts | NoItem - # The plan that was read, as choices.plan_name names it. + # The plan that was read, as release_plan.next_chunk.plan_name names it. plan: str # Each path the project's config sets, and the epic of a plan kept in Jira, by its setting: in the item's worktree where one was made or continued, else in the checkout. places: dict[str, str] diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py index 385e3990..c1490a77 100644 --- a/bin/chunk_preflight/main.py +++ b/bin/chunk_preflight/main.py @@ -78,11 +78,12 @@ import typing from git_cli.git_repo import commit_exists, default_branch, file_at, git, top from failure import Failure -from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran, Worktree -from chunk_preflight.choices import forge_of, plan_name, planned, pulls_command, worktree_add, worktree_on +from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, Ran, Worktree +from chunk_preflight.choices import forge_of, pulls_command, worktree_add, worktree_on from chunk_preflight.facts import JOINING_DETAILS, render from project_config.main import located -from release_plan.named_code import named_paths +from plan.named_paths import named_paths +from release_plan.next_chunk import NextChunk, NoItem, plan_name, planned from release_plan.release_standing import project_plan BIN = pathlib.Path(__file__).resolve().parents[1] @@ -142,14 +143,14 @@ def preflight(root: pathlib.Path, timeout: float, make: bool, item_id: int | Non return config outside = None if config.tracked("plan") else config.plan_label held = project_plan(config, ref, str(root)) - plan = planned(held.todo, held.cut, ref, config.branch, outside, item_id) + plan = planned(held.plan, held.cut, ref, config.branch, outside, item_id) item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout, make) # A `checkout:` path lands in the worktree the chunk works in. made = located(str(item.worktree.path), pathlib.Path.home()) if isinstance(item, ItemFacts) and isinstance(item.worktree, Worktree) else config return render(Gathered(ref, note, held.cut, item, plan_name(ref, outside), (config if isinstance(made, Failure) else made).places, outside is not None, config.texts)) -def item_facts(root: pathlib.Path, default: str, plan: Plan, timeout: float, make: bool) -> ItemFacts: +def item_facts(root: pathlib.Path, default: str, plan: NextChunk, timeout: float, make: bool) -> ItemFacts: worktree = item_worktree(root, plan.branch, default) if make else Failure(f"none made, since it ran without {WORKTREE}.") path = worktree.path if isinstance(worktree, Worktree) else None return ItemFacts(plan, worktree, pull_listing(root, plan.branch, timeout), named_files(plan.text, path or root), tools_run(plan.first.id, path, timeout) if path else []) diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index 71314bd3..5157f150 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -10,15 +10,17 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from project_config.templates import BRANCH -from chunk_preflight.gathered import CarriedOver, Gathered, ItemFacts, NamedPath, NoItem, Ran, Worktree +from release_plan.next_chunk import CarriedOver, NoItem from chunk_preflight import choices from failure import Failure from chunk_preflight.choices import forge_of, worktree_add +from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, Ran, Worktree from test_env import isolated_env from release_plan.release_standing import LastCut, UNSEEN_RELEASES from chunk_preflight.main import line_count, ran, seconds, TIMEOUT +from release_plan import next_chunk from chunk_preflight.facts import open_pulls, render -from plan_store.stores import plan_of +from plan_store.todo_md import plan_of from project_config.test_project_config import write_config BIN = pathlib.Path(__file__).resolve().parents[1] @@ -388,8 +390,8 @@ class ChunkPreflightTool(unittest.TestCase): def planned(todo, *rest): - """choices.planned for the plan a todo.md's text holds, or for the Failure given.""" - return choices.planned(plan_of(todo) if isinstance(todo, str) else todo, *rest) + """next_chunk.planned for the plan a todo.md's text holds, or for the Failure given.""" + return next_chunk.planned(plan_of(todo) if isinstance(todo, str) else todo, *rest) def item_facts(todo=TODO, **fields): diff --git a/bin/command_lines/shell_command.py b/bin/command_lines/shell_command.py index 9da375b4..d853cec2 100644 --- a/bin/command_lines/shell_command.py +++ b/bin/command_lines/shell_command.py @@ -5,8 +5,8 @@ import re import shlex import typing -# Launchers that run the tool named later in their words, such as uvx --with pytest mutmut run. -LAUNCHERS = frozenset({"bunx", "env", "nice", "npx", "pipx", "pnpm", "run-heavy", "time", "timeout", "uvx", "yarn"}) +# Launchers that run the tool named later in their words, such as uvx --with pytest mutmut run, uv run mutmut run or sudo docker build. +LAUNCHERS = frozenset({"bunx", "doas", "env", "nice", "npx", "pipx", "pnpm", "poetry", "run-heavy", "sudo", "time", "timeout", "uv", "uvx", "yarn"}) HEREDOC = re.compile(r"<<-?[ \t]*([\"']?)([A-Za-z_]\w*)\1[^\n]*\n.*?^[ \t]*\2[ \t]*$", re.DOTALL | re.MULTILINE) ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=") OPERATOR = set("\n();&|<>") diff --git a/bin/deploy_release/cut.py b/bin/deploy_release/cut.py index 8910d21e..c39a8fd6 100644 --- a/bin/deploy_release/cut.py +++ b/bin/deploy_release/cut.py @@ -3,7 +3,6 @@ Each step first checks whether an earlier run did it, so a rerun continues where the last run stopped. """ import pathlib -import re import shutil import sys import tempfile @@ -13,11 +12,11 @@ from project_config.settings import DEFAULT_FLOOR from git_cli.git_repo import default_ref, git from deploy_release.deploy import deploy from failure import Failure -from plan_store.stores import FilePlan +from plan_store.todo_md import FilePlan from record_store.stores import FileStore from deploy_release import forge from chunk_preflight.choices import forge_of -from release_plan.release import newest_tag, Release, version +from plan.release import newest_tag, Release, UNRELEASED_HEADING, version from project_config import templates @@ -119,9 +118,9 @@ def ready_release(clone: str, ref: str) -> 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 and changes are unreleased.""" # 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.todo, Failure): - return Failure(f"todo.md on {ref} cannot be read: {plan.todo.reason}") - match chunk_item(plan.todo.items, plan.cut): + 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 case ReadyToCut(): @@ -211,7 +210,7 @@ def push_cut_commit(clone: str, ref: str, branch: str, named: str, title: str, r if isinstance(added := git("worktree", "add", "--quiet", "--detach", str(worktree), ref, cwd=clone), Failure): return added changelog = worktree / "CHANGELOG.md" - renamed, count = re.subn(r"^## Unreleased$", f"## {named}", changelog.read_text() if changelog.exists() else "", count=1, flags=re.MULTILINE) + 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) diff --git a/bin/deploy_release/deploy.py b/bin/deploy_release/deploy.py index faaaf756..945db887 100644 --- a/bin/deploy_release/deploy.py +++ b/bin/deploy_release/deploy.py @@ -1,7 +1,7 @@ """Move a checkout to this repo's newest release, as a bare `deploy-release` does.""" from failure import Failure from git_cli.git_repo import git -from release_plan.release import newest_tag, parsed, tagged +from plan.release import newest_tag, parsed, tagged from text_files.markdown_text import sections diff --git a/bin/larv_review/history_commands.py b/bin/larv_review/history_commands.py index 53072fed..cbc39cf2 100644 --- a/bin/larv_review/history_commands.py +++ b/bin/larv_review/history_commands.py @@ -7,11 +7,11 @@ from larv_review.plan import checkout_plan, plan_reasons from git_cli.git_repo import commit_exists from larv_review.ruling import counted, overall, ruling, split, surplus, votes from failure import Failure +from plan_store.stores import file_plan, store as plan_store from larv_review.seats import FIRST_SEATS, scores, seats_file, SeatsFile from larv_review.scoring import floor_step, means, under_floor +from record_store.held import Held from project_config.main import located -from release_plan import plan_file -from plan_store.stores import store as plan_store from record_store.stores import RecordStore, store from larv_review.scoring_setup import removed_setup @@ -84,10 +84,11 @@ def rerank(home: pathlib.Path, warn: Say) -> Failure | None: if todo is None: # A plan in Jira is ranked by Jira's backlog, which no score moves. return None - ranked = plan_file.rank_file(todo, config) + plan = file_plan(config, todo) + ranked = plan.rank() if isinstance(ranked, Failure): return Failure(f"recorded the run, but rank_todo.py cannot rank {todo}: {ranked.reason}. Fix what that names, then run rank_todo.py on {todo}, not record-scoring again") - for line in plan_file.report_lines(todo, ranked): + for line in plan.reported(ranked): warn(line) if ranked.under_bar: return Failure(f"recorded the run and ranked {todo}, but the lines above name items now under the bar. Settle each as its line says, then run rank_todo.py on {todo}, not record-scoring again") @@ -145,22 +146,29 @@ def read_agreement(home: pathlib.Path) -> str | Failure: def history_file(home: pathlib.Path) -> tuple[RecordStore, str] | Failure: """The store the project's config names for its comprehension history, and the history's text, empty where there is none yet.""" + held = held_history(home) + return held if isinstance(held, Failure) else (held[0], held[1].text) + + +def held_history(home: pathlib.Path) -> tuple[RecordStore, Held] | Failure: + """The store the project's config names for its comprehension history, and the history as it stands, with the version a write over it names.""" config = located(None, home) if isinstance(config, Failure): return config history = store(config, "comprehension-history") - text = history.read() - return text if isinstance(text, Failure) else (history, text) + held = history.held() + return held if isinstance(held, Failure) else (history, held) def append(read: str, entry: str, home: pathlib.Path) -> str | Failure: """Appends entry and returns the line the tool prints; a Failure where the history already holds an entry on what the seats read.""" - read_history = history_file(home) - if isinstance(read_history, Failure): - return read_history - history, text = read_history - if recorded(text, read): + read_history = held_history(home) + return read_history if isinstance(read_history, Failure) else appended_to(*read_history, read, entry) + + +def appended_to(history: RecordStore, held: Held, read: str, entry: str) -> str | Failure: + """Writes entry onto held, the history as history's store read it, over held's version; the line the tool prints, or why the entry isn't written.""" + if recorded(held.text, read): return Failure(f"{history.label} already holds an entry on {read}; record each ruling or run once") - if unwritten := history.write(appended(text, entry)): - return unwritten - return f"Appended to {history.label}." + written = history.write(appended(held.text, entry), held.version) + return written if isinstance(written, Failure) else f"Appended to {history.label}." diff --git a/bin/larv_review/owed.py b/bin/larv_review/owed.py index ec1ad8da..a1e30dfb 100644 --- a/bin/larv_review/owed.py +++ b/bin/larv_review/owed.py @@ -1,13 +1,14 @@ import pathlib import typing -from larv_review.plan import EMPTIED_WORDS, plan_reasons +from larv_review.plan import Emptied, plan_reasons from review_rules.comprehension_history import entries from failure import Failure from git_cli.git_repo import file_at, git from project_config.main import located -from release_plan.todo_table import NoItemsTable -from plan_store.stores import store as plan_store, PlanStore +from plan.todo_table import NoItemsTable +from plan_store.stores import store as plan_store +from plan_store.plans import PlanStore from record_store.stores import store @@ -48,7 +49,7 @@ def owed_scoring_run(default: str, home: pathlib.Path, warn: typing.Callable[[st def shortfall(reasons: list[str], recorded: int) -> Failure | None: """Which scoring runs the plan's reasons call that recorded, the count the branch added to the history, leaves unrecorded; None where it holds them all.""" - needed = 2 if any(reason.endswith(EMPTIED_WORDS) for reason in reasons) else 1 + needed = 2 if any(isinstance(reason, Emptied) for reason in reasons) else 1 if recorded >= needed: return None return Failure(f"the chunk owes {needed} scoring run{'s' if needed > 1 else ''} and the branch's committed history records {max(recorded, 0)}: it {' and '.join(reasons)}. larv-review's SKILL.md → 'Scoring run' says how to run and record {'them' if needed > 1 else 'it'}{"; → 'Second run' says how the second is titled" if needed > 1 else ""}") diff --git a/bin/larv_review/plan.py b/bin/larv_review/plan.py index d858c620..bbe378b8 100644 --- a/bin/larv_review/plan.py +++ b/bin/larv_review/plan.py @@ -1,23 +1,27 @@ import pathlib -from release_plan.release_standing import Cut, LastCut, next_release, project_plan, Unknown +from release_plan.release_standing import Cut, LastCut, next_release, project_plan, standing_of, Unknown from failure import Failure from larv_review.scoring import is_floor_item -from release_plan.todo_table import Item, NoItemsTable +from plan.todo_table import Item, NoItemsTable from project_config.main import located -from release_plan.goals_file import OPTED_OUT -from plan_store.stores import Plan, PlanStore +from plan.goals_file import OPTED_OUT +from plan_store.plans import Plan, PlanStore from plan_store import stores as plan_stores from project_config.settings import ProjectConfig -from release_plan.release import Release, version +from plan.release import Release, version from record_store import stores from larv_review.unmeasured import unmeasured_cut -# The words that end the reason a chunk empties a release. Such a chunk is due two scoring runs; a chunk with any other reason, one. +# The words that end the reason a chunk empties a release; SKILL.md → "Second run" quotes them. EMPTIED_WORDS = "with no plan item" +class Emptied(str): + """The reason a chunk empties a release, which makes it due two scoring runs; a chunk with only other reasons is due one.""" + + def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed_release: Release | None, renamed: frozenset[Release], unmeasured: str | None = None) -> list[str] | Failure: """Why the plan calls a scoring run, empty when it does not. @@ -34,8 +38,7 @@ def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], lan reasons.append(f"follows {unmeasured}") for release in emptied(before, after, shipped, renamed): if work_landed(release, shipped, landed_release): - # SKILL.md → "Second run" keys on this wording. - reasons.append(f"leaves release {version(release)} {EMPTIED_WORDS}") + reasons.append(Emptied(f"leaves release {version(release)} {EMPTIED_WORDS}")) return reasons @@ -49,7 +52,7 @@ def landed_towards(found: list[Item], cut: LastCut) -> Release | None | Failure: """The next release on the default branch, once work has landed towards it: once one or more changes are unreleased, as `release_standing.unreleased_changes` counts them. None where there is no next release, or no change is unreleased. found is the default branch's plan.""" if isinstance(cut.tag, Failure): return Failure(f"could not tell the next release: the default branch's tags cannot be read: {cut.tag.reason}") - upcoming = next_release(found, cut) + upcoming = next_release(standing_of(found, cut), cut) if isinstance(upcoming, Unknown): return Failure("could not tell the next release: the default branch's todo.md history cannot be read") # Cut's release is the last cut's version or earlier, so no work lands towards it. @@ -86,7 +89,7 @@ def plan_reasons(ref: str, ids: list[int] | None, home: pathlib.Path) -> list[st if OPTED_OUT.search(decisions): return [] held = project_plan(config, ref, checkout) - before = held.todo + before = held.plan read = checkout_plan(plan_stores.store(config)) if isinstance(read, Failure): return read diff --git a/bin/larv_review/plan_listing.py b/bin/larv_review/plan_listing.py index 693ea1f0..1e3193b5 100644 --- a/bin/larv_review/plan_listing.py +++ b/bin/larv_review/plan_listing.py @@ -1,8 +1,8 @@ """The plan as a listing a reviewer reads with the Read tool, whatever store holds the plan.""" from failure import Failure -from release_plan.todo_table import Item -from plan_store.stores import PlanStore -from release_plan.release import version +from plan.todo_table import Item +from plan_store.plans import PlanStore +from plan.release import version def plan_listing(plan: PlanStore) -> str: diff --git a/bin/larv_review/scoring.py b/bin/larv_review/scoring.py index 52754cf4..62613bca 100644 --- a/bin/larv_review/scoring.py +++ b/bin/larv_review/scoring.py @@ -1,7 +1,7 @@ import decimal from review_rules.comprehension_history import DIMENSIONS -from release_plan.todo_table import Item +from plan.todo_table import Item # A floor item's tagline opens with this phrase, which a tagline quoting or mentioning the floor never does; a floor item's chunk runs a scoring run. FLOOR_ITEM = "Reach the comprehension floor:" diff --git a/bin/larv_review/test_larv_review.py b/bin/larv_review/test_larv_review.py index b964cd6c..03002506 100644 --- a/bin/larv_review/test_larv_review.py +++ b/bin/larv_review/test_larv_review.py @@ -15,18 +15,20 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from larv_review.agreement import agreement_report, ruling_agreement, run_agreement from review_rules.comprehension_history import appended, entries, HistoryChange, latest_places, Place, recorded, ruling_entry, scoring_entry, ScoringRun, Seat -from larv_review.plan import checkout_plan, EMPTIED_WORDS, landed_towards, plan_reasons, scoring_run_due +from larv_review.history_commands import appended_to +from larv_review.plan import checkout_plan, Emptied, EMPTIED_WORDS, landed_towards, plan_reasons, scoring_run_due from review_rules import comprehension_history from project_config.test_project_config import configured from larv_review.ruling import counted, ruling, split, surplus, votes from larv_review.history_commands import decided, rerank from project_config.settings import DEFAULT_FLOOR from failure import Failure -from plan_store.stores import FilePlan +from plan_store.todo_md import FilePlan from record_store.stores import FileStore from larv_review.scoring import floor_step, means, under_floor +from record_store.held import Held from test_env import isolated_env -from release_plan.todo_table import Item, items, NoItemsTable +from plan.todo_table import Item, items, NoItemsTable from release_plan.release_standing import LastCut from larv_review.ruling_base import measured_commit from record_store.fakes import MemoryStore @@ -459,13 +461,23 @@ class LandedTowards(unittest.TestCase): self.assertEqual(landed_towards(plan, LastCut(Failure("fatal: bad object"), "", 3, [])), Failure("could not tell the next release: the default branch's tags cannot be read: fatal: bad object")) +class AppendedTo(unittest.TestCase): + def test_writes_the_entry_over_the_version_the_history_was_read_at(self): + history = MemoryStore(label="history.md", version=5) + self.assertEqual(appended_to(history, Held("", "5"), "PR #2 at abcdef1\n", "## an entry\n"), "Appended to history.md.") + self.assertEqual(history.overs, ["5"]) + + class Shortfall(unittest.TestCase): def test_skill_md_names_the_words_that_end_the_reason_a_release_empties(self): self.assertIn(EMPTIED_WORDS, (pathlib.Path(__file__).resolve().parents[2] / "skills" / "larv-review" / "SKILL.md").read_text(encoding="utf-8")) def test_a_chunk_that_empties_a_release_owes_two_runs_and_any_other_reason_one(self): - emptied = ["leaves release 0.1.0 with no plan item"] + emptied = [Emptied("leaves release 0.1.0 with no plan item")] floor = ["ships item 2, a floor item"] + # The type, not the words, makes a reason call two runs. + self.assertIn("owes 1 scoring run and", shortfall(["leaves release 0.1.0 with no plan item"], 0).reason) + self.assertIsInstance(scoring_run_due([item(1, (0, 1, 0))], [], [], (0, 1, 0), set())[0], Emptied) self.assertIn("owes 2 scoring runs and the branch's committed history records 1", shortfall(emptied + floor, 1).reason) self.assertIn("owes 1 scoring run and", shortfall(floor, 0).reason) self.assertIn("records 0:", shortfall(floor, -1).reason) diff --git a/bin/larv_review/test_plan_listing.py b/bin/larv_review/test_plan_listing.py index 9a365365..6401caa9 100644 --- a/bin/larv_review/test_plan_listing.py +++ b/bin/larv_review/test_plan_listing.py @@ -4,7 +4,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from plan_store.stores import BLOCKED_BY +from plan.todo_table import BLOCKED_BY from plan_store.contract import FIRST, SECOND from plan_store.fakes import MemoryPlan from larv_review.plan_listing import plan_listing diff --git a/bin/loop_claude/cycle/chunk_items.py b/bin/loop_claude/cycle/chunk_items.py index e384915e..4511329d 100644 --- a/bin/loop_claude/cycle/chunk_items.py +++ b/bin/loop_claude/cycle/chunk_items.py @@ -1,10 +1,10 @@ -"""The todo.md items a chunk takes: those the worker names on its latest `Chunk items:` line, scored as todo.md scores them (docs/decisions.md → `routing: loop-claude reads the items a chunk takes`).""" +"""The plan items a chunk takes: those the worker names on its latest `Chunk items:` line, scored as the plan scores them (docs/decisions.md → `routing: loop-claude reads the items a chunk takes`).""" import re from claude_code.entries import AssistantTurn, Entry, Text from failure import Failure from loop_claude.quotes import plain -from plan_store.stores import Plan +from plan_store.plans import Plan from loop_claude.verdicts import TakenIn # The label opening the line; prompts.NAME_THE_ITEMS asks the worker for it. diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index 26af250e..b8e3d26f 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -31,7 +31,7 @@ INTERRUPT_RULES = ( "- it is blocked on something only the human can supply: a credential, a version bump, a choice " "outside the repo, or a release ready to cut, which only the human may publish\n" "- it flags that the goals need changing\n" - "- it flags that the plan in todo.md or the task itself is unclear or missing, and recommends no way on\n\n" + "- it flags that the plan or the task itself is unclear or missing, and recommends no way on\n\n" "interrupt=false otherwise. A choice in the repo that no rule reserves for the human is the worker's to make, " "so its taking its own recommendation on one is no reason to interrupt. Where it asks about such a choice and " "recommends an answer, quote the sentence of that rule telling it to take the option it would recommend, even " diff --git a/bin/loop_claude/cycle/prompts.py b/bin/loop_claude/cycle/prompts.py index 3010ac93..1eeced61 100644 --- a/bin/loop_claude/cycle/prompts.py +++ b/bin/loop_claude/cycle/prompts.py @@ -12,7 +12,7 @@ from claude_code.transcript import Typed # Where the judge may quote an answer from, named as the human and the worker see them; of the goals file the judge sees only the premises. QUOTE_SOURCES = listed(("the goals file's Goals and Audience", *RECORD_FILES, *HUMAN_RULE_NAMES), "or") # Where the worker may write an answer the human typed, so it counts as recorded. -ANSWER_DESTINATIONS = "the goals file's Goals or Audience, " + ", ".join(RECORD_FILES) + ", todo.md or a comment" +ANSWER_DESTINATIONS = "the goals file's Goals or Audience, " + ", ".join(RECORD_FILES) + ", the plan or a comment" ANSWERS_RECORDED = f"every answer the human typed in it that a later chunk could need is recorded in {ANSWER_DESTINATIONS} at the one place it governs" # How review_launches names the reviews: "each reviewer" covers every pass with an agent. EACH_REVIEWER = "each reviewer" @@ -23,7 +23,7 @@ THE_SECURITY_PASS = "the security pass's subagent" # Workers only, not CLAUDE.md, which reviewers load too: a reviewer under a like rule missed findings. READING_RULE = "Read in small pieces: never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context." # chunk_items reads the latest such line; three fresh readers picked the label (docs/decisions.md → `routing: loop-claude reads the items a chunk takes`). -NAME_THE_ITEMS = f"Name every todo.md item this chunk takes on one line, as in `{CHUNK_ITEMS} 297 (L 3, E + I 5), 298 (L 3, E + I 7)`, and write the whole line again whenever the set changes." +NAME_THE_ITEMS = f"Name every plan item this chunk takes on one line, as in `{CHUNK_ITEMS} 297 (L 3, E + I 5), 298 (L 3, E + I 7)`, and write the whole line again whenever the set changes." AFTER_CODE_HEALTH = 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless the goals file voids it' @@ -33,7 +33,7 @@ def fresh(task: str, premises: str, route: Route, ladder: Ladder, project: Rung """A chunk's first prompt; facts is preflight_facts' or preflight_failed's text.""" routed = f"{routed_by(route, ladder, project)} {recount(route)}" if route.item else " ".join(rung_sentences(route, ladder, project)) opening = f"{routed}\n\n" if routed else "" - return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one. {READING_RULE} {NAME_THE_ITEMS}\n\n{opening}{facts}\n\nThe chunk's todo.md items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom the goals file, {premises}" + return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one. {READING_RULE} {NAME_THE_ITEMS}\n\n{opening}{facts}\n\nThe chunk's plan items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom the goals file, {premises}" def routed_by(route: Route, ladder: Ladder, project: Rung | None) -> str: @@ -45,7 +45,7 @@ def routed_by(route: Route, ladder: Ladder, project: Rung | None) -> str: def recount(route: Route) -> str: """Has the worker count the routing item's size again once it knows the code, since the L that routed it was scored before anyone read that code.""" - return f"After your first read of the code, count item {route.item}'s size again: the lines, files and components you will change. Where that count would change its L, have a subagent that scores todo.md items re-score it; a re-score whose L picks a rung above yours is escalation trigger 1." + return f"After your first read of the code, count item {route.item}'s size again: the lines, files and components you will change. Where that count would change its L, have a subagent that scores plan items re-score it; a re-score whose L picks a rung above yours is escalation trigger 1." def preflight_facts(printed: str) -> str: @@ -77,8 +77,8 @@ def scan_launch(choice: ReviewChoice, route: Route) -> list[str]: def planning_launch(route: Route, ladder: Ladder, project: Rung) -> list[str]: - """Where the worker runs below the project's rung, the sentence naming where to launch a subagent that files or scores todo.md items. On an Opus 5.5 project: `Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints.`""" - return [f"Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan {project.model} <L>` prints."] if ladder.position(route.rung) < ladder.position(project) else [] + """Where the worker runs below the project's rung, the sentence naming where to launch a subagent that files or scores plan items. On an Opus 5.5 project: `Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints.`""" + return [f"Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan {project.model} <L>` prints."] if ladder.position(route.rung) < ladder.position(project) else [] def markdown_launch(choice: ReviewChoice) -> list[str]: diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index ac780bb1..8560e56a 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -17,7 +17,7 @@ from loop_claude.routing import judge_rung, next_route, step_up, StepUp from model_routing.ladder import Ladder, Rung from transcript_archive.read import last_spent from transcript_archive import outcomes -from plan_store.stores import Plan +from plan_store.plans import Plan from loop_claude.cycle import prompts from claude_code.transcript import read_transcript from loop_claude.cycle.retry import retried @@ -51,8 +51,8 @@ class Cycle: route: Route session: Session task: str - # todo.md on the default branch as the cycle starts, which scores the items the worker names. - todo: Plan | Failure + # The plan on the default branch as the cycle starts, which scores the items the worker names. + plan: Plan | Failure # Empty when the previous cycle's verdict was not Unfinished. unfinished_evidence: str # The tmux window the loop runs in, which an interrupt marks. @@ -160,7 +160,7 @@ def rule(cycle: Cycle, transcript_path: str, quoted_answers: int) -> Ruled | Sto if isinstance(verdict, Stop): return verdict if not isinstance(verdict, Finished): - verdict = dataclasses.replace(verdict, taken_in=chunk_items.taken_in(entries, cycle.todo)) + verdict = dataclasses.replace(verdict, taken_in=chunk_items.taken_in(entries, cycle.plan)) if not isinstance(verdict, Interrupt | QuotedAnswer): return Ruled(verdict) annotation = annotation_of(cycle, transcript_path, entries, verdict.judged) diff --git a/bin/loop_claude/loop/chunk_start.py b/bin/loop_claude/loop/chunk_start.py index c58c70ae..bf7b61a4 100644 --- a/bin/loop_claude/loop/chunk_start.py +++ b/bin/loop_claude/loop/chunk_start.py @@ -7,14 +7,14 @@ from release_plan.release_standing import DefaultPlan, project_plan, UNSEEN_RELE from loop_effects.effects import Effects, say from failure import Failure from loop_claude.routing import first_route, kept, routed_item -from plan_store.stores import held_at, Plan, store as plan_store from loop_claude.loop.chunk_windows import held_beside, item_of from chunk_preflight.main import ITEM -from release_plan.todo_table import Item +from plan.todo_table import Item from model_routing.ladder import Ladder, Rung from transcript_archive.read import latest_worker from project_config.main import located from loop_claude.loop.this_loop import Loop +from plan_store.plans import Plan from loop_claude.cycle import prompts from model_routing.route import Route, route_from from claude_code.session import session_open, transcript_file @@ -23,17 +23,12 @@ from claude_code.session import session_open, transcript_file ORIGIN_TIMEOUT = 60 -def fetched_todo(loop: Loop) -> Plan | Failure: - """The plan, which scores the items a chunk takes: on the default branch as last fetched, or as it stands where the project's config puts it outside the checkout. fetched_plan reads it too, but also the release tag, CHANGELOG.md and each todo.md since the tag, which scoring the items doesn't need. Where it can't be read or scored, it says why.""" - ref = default_ref(loop.root, ORIGIN_TIMEOUT, run=loop.effects.git) - config = located(loop.root, loop.paths.home) - if isinstance(config, Failure): - todo: Plan | Failure = config - else: - todo = ref if isinstance(ref, Failure) else held_at(ref, plan_store(config), loop.root, loop.effects.git) - if isinstance(todo, Failure): - say(f"the items the worker names lift no rung: {todo.reason}", loop.effects) - return todo +def scored_plan(default: DefaultPlan | Failure, effects: Effects) -> Plan | Failure: + """The plan, which scores the items a chunk takes, from what the default branch holds; where it can't be read or scored, it says why.""" + plan = default.plan if isinstance(default, DefaultPlan) else default + if isinstance(plan, Failure): + say(f"the items the worker names lift no rung: {plan.reason}", effects) + return plan def routed(route: Route | None, ladder: Ladder, project: Rung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route: @@ -60,10 +55,10 @@ def archived_route(archive_folder: pathlib.Path, loop: Loop) -> Route | None: return route -def chunk_start(loop: Loop) -> tuple[str, typing.Callable[[], Item | None]]: - """The facts for a fresh worker's prompt, empty where the session is open, and the reader of the item that routes the chunk. The reader reads the default branch as last fetched: for a fresh chunk, by the preflight that runs first; for an open session, which runs none, by whatever fetched last.""" - facts = "" if session_open(loop.session) else chunk_facts(loop) - return facts, lambda: plan_item(fetched_plan(loop), item_of(loop.window.name), loop.effects) +def chunk_start(loop: Loop) -> tuple[str, DefaultPlan | Failure]: + """The facts for a fresh worker's prompt, empty where the session is open, and what the default branch holds, read once for the cycle: it routes the chunk, through plan_item, and scores the items the worker names, through scored_plan. It reads the default branch as last fetched: for a fresh chunk, by the preflight that runs first; for an open session, which runs none, by whatever fetched last.""" + fresh = not session_open(loop.session) + return chunk_facts(loop) if fresh else "", fetched_plan(loop, fresh) def chunk_facts(loop: Loop) -> str: @@ -75,12 +70,12 @@ def chunk_facts(loop: Loop) -> str: return facts + (prompts.held_by_others(held) if held else "") -def fetched_plan(loop: Loop) -> DefaultPlan | Failure: - """What the default branch, as last fetched, holds for routing; the plan and the changelog as they stand where the project's config puts them outside the checkout. It says UNSEEN_RELEASES for such a plan.""" +def fetched_plan(loop: Loop, announce: bool = True) -> DefaultPlan | Failure: + """What the default branch, as last fetched, holds for routing; the plan and the changelog as they stand where the project's config puts them outside the checkout. Where announce is True, as when a chunk starts, it says UNSEEN_RELEASES for such a plan, so the human reads it once per chunk, not every cycle.""" config = located(loop.root, loop.paths.home) if isinstance(config, Failure): return config - if config.tracked("plan") is None: + if announce and config.tracked("plan") is None: say(UNSEEN_RELEASES, loop.effects) ref = default_ref(loop.root, ORIGIN_TIMEOUT, run=loop.effects.git) return ref if isinstance(ref, Failure) else project_plan(config, ref, loop.root, loop.effects.git) @@ -92,7 +87,7 @@ def plan_item(plan: DefaultPlan | Failure, window_item: int | None, effects: Eff if isinstance(plan, Failure): item: Item | Failure | None = plan else: - item = routed_item(plan.todo, plan.cut, window_item) + item = routed_item(plan.plan, plan.cut, window_item) if isinstance(item, Failure): say(f"routing on the project's rung: {item.reason}", effects) return None diff --git a/bin/loop_claude/loop/chunk_windows.py b/bin/loop_claude/loop/chunk_windows.py index 31f88601..1020aa94 100644 --- a/bin/loop_claude/loop/chunk_windows.py +++ b/bin/loop_claude/loop/chunk_windows.py @@ -1,5 +1,6 @@ """The chunks of one project that run at once, each in its own tmux window: which may start now, and how each starts (docs/decisions.md → `loop-claude: each chunk runs in its own tmux window`).""" import contextlib +import dataclasses import fcntl import pathlib import re @@ -12,10 +13,9 @@ from loop_effects.effects import Effects, say from failure import Failure from project_config.main import located from loop_claude.loop.reload import LoopRun -from chunk_preflight.gathered import NoItem, Plan +from release_plan.next_chunk import NextChunk, NoItem, planned from touch_predictions.prediction import overlaps, predicted, Touches from loop_state.paths import Paths -from chunk_preflight.choices import planned from transcript_archive.project_key import project_key from release_plan.release_standing import project_plan from claude_code.transcript import read_transcript @@ -72,17 +72,40 @@ def held_items(chunks: typing.Iterable[str], key: str, claude_code_transcripts: return held -def may_start(plan: Plan | NoItem, running: list[str], held: set[int], limit: int) -> list[str]: - """The chunks to start now beside the running ones, whose chunks hold the items in held: the plan's next item and the items touch_predictions picks to run beside it, in the plan's order, up to limit chunks running at once. Each leaves out an item in held, and one whose `Touches:` prediction overlaps a held item's, or where either has none. A plan without an item starts NO_ITEM, and only alone.""" +@dataclasses.dataclass(frozen=True) +class Room: + """What a project's windows leave room for, under its limit of chunks at once.""" + # The chunks whose windows run. + running: list[str] + # The chunks whose windows are dead: their loop stopped or failed, and the window keeps its last lines and its items. + stopped: list[str] + # The stopped chunks to start again, before any chunk from the plan. + restart: list[str] + # How many chunks from the plan may start beside them. + left: int + + +def room_of(windows: list[tmux.Listed], own: str | None, leaving: bool, limit: int) -> Room: + """The room windows leave under limit. own is the chunk of the loop that asks, None for the human's loop-claude <task>. leaving is True where own's chunk finished: its window no longer counts as running, and no stopped chunk starts again, since only a loop that isn't leaving, such as the human's loop-claude <task>, restarts one.""" + running = [window.name for window in windows if not window.dead and not (leaving and window.name == own)] + # Below 0 where the config lowered parallel-chunks while more chunks ran. + room = max(limit - len(running), 0) + stopped = [window.name for window in windows if window.dead] + restart = [] if leaving else stopped[:room] + return Room(running, stopped, restart, room - len(restart)) + + +def may_start(plan: NextChunk | NoItem, running: list[str], held: set[int], room: int) -> list[str]: + """The chunks to start now beside the running ones, whose chunks hold the items in held: the plan's next item and the items touch_predictions picks to run beside it, in the plan's order, up to room of them. Each leaves out an item in held, and one whose `Touches:` prediction overlaps a held item's, or where either has none. A plan without an item starts NO_ITEM, and only alone.""" if isinstance(plan, NoItem): - return [] if running else [NO_ITEM] + return [] if running or room < 1 else [NO_ITEM] beside = chunks_beside(plan.items, plan.first) picked = [plan.first.id, *(beside.picked if isinstance(beside, Beside) else [])] details = {item.id: item.detail for item in plan.items} # chunks_beside checks overlaps against the plan's next item only, and a running chunk's item may no longer be that one once an item merged. A held item that left the plan overlaps nothing. theirs = [predicted(details[item_id]) for item_id in sorted(held) if item_id in details] free = [item_id for item_id in picked if item_id not in held and clear_of(predicted(details[item_id]), theirs)] - return [window_name(item_id) for item_id in free][: max(limit - len(running), 0)] + return [window_name(item_id) for item_id in free][: max(room, 0)] def clear_of(ours: Touches | Failure | None, theirs: list[Touches | Failure | None]) -> bool: @@ -90,7 +113,7 @@ def clear_of(ours: Touches | Failure | None, theirs: list[Touches | Failure | No return not theirs or (isinstance(ours, dict) and all(isinstance(touches, dict) and not overlaps(ours, touches) for touches in theirs)) -def next_plan(root: str, home: pathlib.Path, effects: Effects) -> Plan | NoItem | Failure: +def next_plan(root: str, home: pathlib.Path, effects: Effects) -> NextChunk | NoItem | Failure: """The plan on the default branch, fetched now where origin answers, with its next item, as chunk-preflight reads it.""" config = located(root, home) if isinstance(config, Failure): @@ -101,7 +124,7 @@ def next_plan(root: str, home: pathlib.Path, effects: Effects) -> Plan | NoItem if isinstance(ref, Failure): return ref held = project_plan(config, ref, root, effects.git) - return planned(held.todo, held.cut, ref, config.branch, None if config.tracked("plan") else config.plan_label) + return planned(held.plan, held.cut, ref, config.branch, None if config.tracked("plan") else config.plan_label) def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Mapping[str, str], launcher: pathlib.Path, effects: Effects) -> list[str] | Failure: @@ -117,20 +140,16 @@ def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Map windows = tmux.listed(session, effects.tmux) if windows and (owned := tmux.owner(session, effects.tmux)) != loop_run.root: return Failure(f"the tmux session {session} runs the chunks of {owned or 'another checkout'}, whose key maps to the same session name; rename one of the two checkouts' folders") - running = [window.name for window in windows if not window.dead and not (leaving and window.name == loop_run.chunk)] - # Below 0 where the config lowered parallel-chunks while more chunks ran. - room = max(config.parallel_chunks - len(running), 0) - # A loop that the human stopped, or that failed, keeps its window, dead, with its last lines and its items. Only the human's loop-claude <task> starts it again, before any other chunk. - stopped = [window.name for window in windows if window.dead] - chunks = [] if leaving else stopped[:room] - if len(chunks) < room: + room = room_of(windows, loop_run.chunk, leaving, config.parallel_chunks) + chunks = list(room.restart) + if room.left: plan = next_plan(loop_run.root, paths.home, effects) if isinstance(plan, Failure): # Such as in a checkout without a default branch, where chunk-preflight fails too: the worker is told why and finds the facts itself. say(f"starting a chunk without a plan item, since the plan cannot be read: {plan.reason}", effects) plan = NoItem(plan.reason) - held = held_items(running + stopped, key, paths.claude_code_transcripts) - chunks += [chunk for chunk in may_start(plan, running + chunks, held, config.parallel_chunks) if chunk not in stopped] + held = held_items(room.running + room.stopped, key, paths.claude_code_transcripts) + chunks += [chunk for chunk in may_start(plan, room.running + room.restart, held, room.left) if chunk not in room.stopped] for chunk in chunks: stale = [window for window in windows if window.name == chunk and window.dead] for window in stale: @@ -148,7 +167,12 @@ def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Map def held_beside(chunk: str, root: str, paths: Paths, effects: Effects) -> list[int]: """The plan items that the project's other chunks hold now, running or stopped, which a chunk starting as `chunk` leaves to them. It waits for a loop that is starting windows, so chunks started together see each other. Where the lock cannot be taken, it reads the windows without it.""" key = project_key(root, paths.home) - with contextlib.suppress(OSError), starting(paths.home, key): - pass + wait_for_starts(paths.home, key) others = [window.name for window in tmux.listed(tmux.session_name(key), effects.tmux) if window.name != chunk] return sorted(held_items(others, key, paths.claude_code_transcripts)) + + +def wait_for_starts(home: pathlib.Path, key: str) -> None: + """Returns once no loop of the project is starting windows: start_chunks holds LOCK while it starts them. Where the lock cannot be taken, it returns at once.""" + with contextlib.suppress(OSError), starting(home, key): + pass diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 6843a8e8..579e08f6 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -3,10 +3,10 @@ import pathlib import typing from transcript_archive.location import archive_root, project_archive -from loop_claude.loop.chunk_start import archived_route, chunk_start, fetched_todo, routed +from loop_claude.loop.chunk_start import archived_route, chunk_start, plan_item, routed, scored_plan from loop_claude.loop.routing_check import check_routing from loop_claude.project.checkout import checkout_root -from loop_claude.loop.chunk_windows import CHUNK_FLAG, chunk_session, start_chunks +from loop_claude.loop.chunk_windows import CHUNK_FLAG, chunk_session, item_of, start_chunks from loop_claude.loop.close import closed_cycle from loop_claude.cycle.run import Cycle, run_cycle from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG @@ -122,14 +122,13 @@ def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop: return Stop(1, ladder.reason) archive_folder = project_archive(loop.root, loop.paths.home, loop.env) # After the reads above, so a loop that stops on one makes no worktree. - facts, item = chunk_start(loop) + facts, default = chunk_start(loop) project = ladder.project_rung(models.worker) - route = routed(loop_run.route, ladder, project, models.worker, lambda: archived_route(archive_folder, loop), item) + route = routed(loop_run.route, ladder, project, models.worker, lambda: archived_route(archive_folder, loop), lambda: plan_item(default, item_of(loop.window.name), loop.effects)) say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", loop.effects, stdout=True) if ladder_file != SHIPPED: say(own_ladder(ladder_file, models.worker, project is None), loop.effects) - todo = fetched_todo(loop) - return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge_model=models.judge, ladder=ladder, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=loop_run.task, todo=todo, unfinished_evidence=loop_run.unfinished_evidence, window=loop.window) + return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge_model=models.judge, ladder=ladder, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=loop_run.task, plan=scored_plan(default, loop.effects), unfinished_evidence=loop_run.unfinished_evidence, window=loop.window) def own_ladder(file: pathlib.Path, model: str, unrouted: bool) -> str: diff --git a/bin/loop_claude/loop/usage.py b/bin/loop_claude/loop/usage.py index 437d26f2..9c0b5f99 100644 --- a/bin/loop_claude/loop/usage.py +++ b/bin/loop_claude/loop/usage.py @@ -8,13 +8,13 @@ as goals-and-audience: a file, or a Jira epic's description. `project-config goa prints where it is. The task runs at the checkout root. Each cycle a worker runs the task. A chunk's first worker prompt also quotes the premises. They, with code health (~/.claude/CLAUDE.md → "Shared goal") ranked first unless the goals file voids it, choose between ways to deliver the -chunk's todo.md items, or else the task, and never widen them. A judge then reads the transcript's +chunk's plan items, or else the task, and never widen them. A judge then reads the transcript's end, the premises, and the records: the project's AGENTS.md and docs/decisions.md, and the human's ~/.claude/CLAUDE.md and ~/.claude/rules/*.md, then the .md files in the folder of review standards the project's config sets, where they exist. It rules whether the chunk, the work of one PR, is finished. A chunk stays unfinished until each answer the human typed in it that a later chunk could need is recorded: the premises or the records hold it, or the transcript shows the worker writing it -into the premises, AGENTS.md, docs/decisions.md, todo.md or a code comment. A choice the worker made +into the premises, AGENTS.md, docs/decisions.md, the plan or a comment. A choice the worker made that the premises or the records settle is not asked about. When the worker asks a question they answer, the judge quotes the answer, loop-claude prints it, and the worker resumes with it. A quote they do not hold word for word is dropped, and the question goes to the human. So does a question @@ -94,7 +94,7 @@ both set, nothing is asked. The routing ladder is a list of rungs, least competent first, each a model at an effort. Where the project's model is on it, the worker and the session /talk opens run on -the rung that the chunk's todo.md item picks, and the judge of some +the rung that the chunk's plan item picks, and the judge of some models on another; a chunk no item routes runs on the project's model. The worker's prompts name the rungs it launches its reviews on. The worker's rung steps up as a chunk stays unfinished, when the worker names on its `Chunk items:` line an item that picks a higher rung, or when the judge finds @@ -104,7 +104,7 @@ each review's rung in bin/model_routing/review_choice.py, and the prompts' wordi bin/loop_claude/cycle/prompts.py. Each verdict, interrupt, quoted answer, stop and step-up in the archive ends with a Worker: line, the route as JSON (Route.worker_line in bin/model_routing/route.py); a rerun resumes an open chunk on the latest route named there. A -todo.md or an archive that cannot be read or parsed is said on stderr, and the chunk is routed +plan or an archive that cannot be read or parsed is said on stderr, and the chunk is routed without it. The ladder is a JSON file, each rung a model's full name and an effort of low, medium, high, xhigh diff --git a/bin/loop_claude/project/premises.py b/bin/loop_claude/project/premises.py index 41beafad..ab7154b4 100644 --- a/bin/loop_claude/project/premises.py +++ b/bin/loop_claude/project/premises.py @@ -3,7 +3,7 @@ import pathlib from failure import Failure from record_store.stores import goals_store from project_config.main import located -from release_plan.goals_file import section +from plan.goals_file import section def read_premises(root: str, home: pathlib.Path) -> str | Failure: diff --git a/bin/loop_claude/project/records.py b/bin/loop_claude/project/records.py index 5c058e5d..f2c28226 100644 --- a/bin/loop_claude/project/records.py +++ b/bin/loop_claude/project/records.py @@ -5,10 +5,10 @@ from project_config.main import located from loop_claude.project.text_file import read_utf8 from record_store.stores import store -# The records the judge reads beside the premises: these project files, then the human's rules below. -RECORD_FILES = ("AGENTS.md", "docs/decisions.md") -# The setting in the project's config that places each of RECORD_FILES. -RECORD_SETTINGS = ("working-rules", "decisions") +# The records the judge reads beside the premises, by the name that heads each, with the setting in the project's config that places it; then the human's rules below. +WORKING_RULES = ("AGENTS.md", "working-rules") +DECISIONS = ("docs/decisions.md", "decisions") +RECORD_FILES = (WORKING_RULES[0], DECISIONS[0]) # The human's rules, in the order the judge reads them: ~/.claude/CLAUDE.md, each .md file in ~/.claude/rules/, # then each .md file in the review standards folder the project's config sets. HUMAN_RULES_FILE = "CLAUDE.md" @@ -27,8 +27,8 @@ def read_records(root: str, home: pathlib.Path, claude_dir: pathlib.Path) -> str if isinstance(config, Failure): return Failure(f"{config.reason} - {CONSEQUENCE}.") rules = [claude_dir / HUMAN_RULES_FILE, *sorted((claude_dir / HUMAN_RULE_DIR).glob("*.md")), *sorted(config.paths["standards"].glob("*.md"))] - decisions = store(config, RECORD_SETTINGS[1]).read() - texts = [(RECORD_FILES[0], file_text(config.paths[RECORD_SETTINGS[0]])), (RECORD_FILES[1], Failure(f"{decisions.reason} - {CONSEQUENCE}.") if isinstance(decisions, Failure) else decisions)] + decisions = store(config, DECISIONS[1]).read() + texts = [(WORKING_RULES[0], file_text(config.paths[WORKING_RULES[1]])), (DECISIONS[0], Failure(f"{decisions.reason} - {CONSEQUENCE}.") if isinstance(decisions, Failure) else decisions)] texts += [(named(rule, home, claude_dir), file_text(rule)) for rule in rules] records = [] for heading, text in texts: diff --git a/bin/loop_claude/routing.py b/bin/loop_claude/routing.py index 52f769a9..0589fd5b 100644 --- a/bin/loop_claude/routing.py +++ b/bin/loop_claude/routing.py @@ -33,9 +33,9 @@ from release_plan.release_standing import chunk_item, LastCut, Next from loop_claude import escalation_mark from failure import Failure from loop_claude.verdicts import Interrupt, QuotedAnswer, Unfinished -from release_plan.todo_table import Item, NoItemsTable +from plan.todo_table import Item, NoItemsTable from model_routing.ladder import Ladder, Rung -from plan_store.stores import Plan +from plan_store.plans import Plan from model_routing.route import Route UNFINISHED_PER_STEP = 2 diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index c490bd4a..fee2dc6a 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -455,7 +455,7 @@ class Cycles(unittest.TestCase): self.assertIsNone(argument(workers[1], "--name")) self.assertEqual(argument(workers[2], "--session-id"), session) self.assertTrue(argument(workers[0], "-p").startswith(f"{TASK}\n\nContinue any open draft PR")) - self.assertTrue(argument(workers[0], "-p").endswith("The chunk's todo.md items, or else the task above, set its scope. The goals below, " 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless the goals file voids it' ", choose between ways to deliver that scope, and never widen it.\n\nFrom the goals file, " f"{checkout.root}/README.md:\n## Goals\n1. Work.\n\n## Audience\nMe.")) + self.assertTrue(argument(workers[0], "-p").endswith("The chunk's plan items, or else the task above, set its scope. The goals below, " 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless the goals file voids it' ", choose between ways to deliver that scope, and never widen it.\n\nFrom the goals file, " f"{checkout.root}/README.md:\n## Goals\n1. Work.\n\n## Audience\nMe.")) self.assertIn("main or master", argument(workers[0], "-p")) self.assertNotIn(TASK, argument(workers[1], "-p")) self.assertIn("Even then, it is finished only once every answer the human typed in it", argument(workers[1], "-p")) diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 30c2ecd5..2e0a0cdb 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -28,15 +28,15 @@ from loop_effects.effects import Effects, PYTHON_TIMEOUT from claude_code import entries, reply, session from failure import Failure from loop_claude.verdicts import Finished, Interrupt, Judged, QuotedAnswer, TakenIn, Unfinished -from chunk_preflight import gathered from git_cli.git_repo import git from loop_claude.cycle import interrupt, judge, prompts, retry, run, spend, states, worker from claude_code.reply import Limited from loop_claude.loop import main, reload, routing_check, this_loop, usage from machine_load import memory +from release_plan import next_chunk from transcript_archive import outcomes, write from loop_state import paths -from plan_store.stores import plan_of +from plan_store.todo_md import plan_of from transcript_archive.location import project_archive from model_routing.ladder_file import read_ladder, SHIPPED from model_routing.route import Route, route_from, WorkerLine @@ -286,7 +286,7 @@ class Cycles(unittest.TestCase): self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {}) def cycle(self, fake, records="", unfinished_evidence="", facts="- A preflight fact."): - return run.Cycle(config=CONFIG, window=WINDOW, effects=fake.effects(), facts=facts, judge_model="judge-model", ladder=LADDER, premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", todo=plan_of(""), unfinished_evidence=unfinished_evidence) + return run.Cycle(config=CONFIG, window=WINDOW, effects=fake.effects(), facts=facts, judge_model="judge-model", ladder=LADDER, premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", plan=plan_of(""), unfinished_evidence=unfinished_evidence) def archived_outcomes(self): return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md")) @@ -1165,22 +1165,16 @@ class RouteSources(unittest.TestCase): def test_routes_a_window_named_for_an_item_on_that_item_whatever_the_plan_takes_next(self): plan = DefaultPlan(plan_of(TODO), LastCut("v0.1.0", "", 3, [TODO])) - later = next(item.id for item in plan.todo.items if item.id != 3) + later = next(item.id for item in plan.plan.items if item.id != 3) self.assertEqual(chunk_start.plan_item(plan, later, FakeEffects().effects()).id, later) # An item that left the plan, as once it shipped. self.assertIsNone(chunk_start.plan_item(plan, 999, FakeEffects().effects())) + # A chunk start reads the default branch once, for routing and for scoring the items the worker names. with unittest.mock.patch.object(chunk_start, "session_open", return_value=True), unittest.mock.patch.object(chunk_start, "fetched_plan", return_value=plan) as fetched: - for window, routed in ((tmux.Window("loop-proj", f"item-{later}", "%4"), later), (tmux.Window("loop-proj", "no-item", "%4"), 3)): - with self.subTest(window=window.name): - loop = a_loop(FakeEffects().effects(), window=window) - facts, reader = chunk_start.chunk_start(loop) - self.assertEqual((facts, reader().id), ("", routed)) - fetched.assert_called_with(loop) - # Where the plan cannot be read, the reader says so through the loop's effects, and routes on the project's rung. - fetched.return_value = Failure("no origin remote") - with contextlib.redirect_stderr(io.StringIO()) as said: - self.assertIsNone(chunk_start.chunk_start(a_loop(FakeEffects().effects()))[1]()) - self.assertIn("routing on the project's rung: no origin remote", said.getvalue()) + loop = a_loop(FakeEffects().effects()) + self.assertEqual(chunk_start.chunk_start(loop), ("", plan)) + # An open session is no fresh chunk, so the human isn't told again of releases the plan cannot show. + fetched.assert_called_once_with(loop, False) unreadable = Failure("git show origin/main:todo.md printed text that is not UTF-8") for plan, said in ((DefaultPlan(plan_of(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |")), NO_CUT), "routing on the project's rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (DefaultPlan(unreadable, NO_CUT), f"routing on the project's rung: {unreadable.reason}\n"), (Failure("no origin remote"), "routing on the project's rung: no origin remote\n")): with self.subTest(said=said): @@ -1189,13 +1183,13 @@ class RouteSources(unittest.TestCase): self.assertTrue(stderr.getvalue().startswith(f"{STAMP} {said}"), stderr.getvalue()) def test_says_why_the_items_the_worker_names_lift_no_rung(self): - fetched = ["origin\n", "origin/main\n", "", "todo.md\n"] - for git, said in ((fetched + [TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |")], "the items the worker names lift no rung: item 3's L 'x' is not a whole number from 1 to 4\n"), ([Failure("no git")], "the items the worker names lift no rung: no git\n"), (fetched + [TODO], "")): - with self.subTest(said=said), tempfile.TemporaryDirectory() as root: - home = configured(self, pathlib.Path(root)).parents[1] + unscored = plan_of(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |")) + for default, said in ((DefaultPlan(unscored, NO_CUT), "the items the worker names lift no rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (Failure("no git"), "the items the worker names lift no rung: no git\n"), (DefaultPlan(plan_of(TODO), NO_CUT), "")): + with self.subTest(said=said): with contextlib.redirect_stderr(io.StringIO()) as stderr: - chunk_start.fetched_todo(a_loop(FakeEffects(git=git).effects(), root=root, paths=paths.paths_from(home))) + scored = chunk_start.scored_plan(default, FakeEffects().effects()) self.assertEqual(stderr.getvalue(), f"{STAMP} {said}" if said else "") + self.assertEqual(scored, default.plan if isinstance(default, DefaultPlan) else default) def test_reads_the_changelog_the_default_branch_holds_through_the_loops_git(self): def git(*args, **options): @@ -1219,16 +1213,19 @@ class RouteSources(unittest.TestCase): self.assertEqual(stderr.getvalue(), "", "a plan git tracks hides no release") config.write_text(config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"')) (folder / "todo.md").write_text(TODO) - self.assertEqual(chunk_start.fetched_todo(loop), plan_of(TODO)) unread = Failure("no git") standing = a_loop(FakeEffects(git=["origin\n", "origin/main\n", unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[1])) with contextlib.redirect_stderr(io.StringIO()) as stderr: held = chunk_start.fetched_plan(standing) - self.assertEqual((held.todo, held.cut.todos_since, held.cut.changelog), (plan_of(TODO), [], ""), "the plan as it stands, whatever git answers") + self.assertEqual((held.plan, held.cut.todos_since, held.cut.changelog), (plan_of(TODO), [], ""), "the plan as it stands, whatever git answers") self.assertEqual(stderr.getvalue(), f"{STAMP} {UNSEEN_RELEASES}\n", "a release review loop-claude cannot call due is never skipped silently") + quiet = a_loop(FakeEffects(git=["origin\n", "origin/main\n", unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[1])) + with contextlib.redirect_stderr(io.StringIO()) as stderr: + chunk_start.fetched_plan(quiet, announce=False) + self.assertEqual(stderr.getvalue(), "", "said once per chunk, as it starts") config.unlink() with contextlib.redirect_stderr(io.StringIO()) as stderr: - self.assertIn("no config names the checkout", chunk_start.fetched_todo(loop).reason) + self.assertIn("no config names the checkout", chunk_start.scored_plan(chunk_start.fetched_plan(loop), loop.effects).reason) self.assertIn("the items the worker names lift no rung: no config names the checkout", stderr.getvalue()) self.assertIn("no config names the checkout", chunk_start.fetched_plan(loop).reason) @@ -1308,6 +1305,17 @@ class TmuxCommands(unittest.TestCase): self.assertEqual(tmux.start_window(window, "/r", {}, ["x"], True, failed), Failure("tmux could not start the window loop-proj:item-7: duplicate session: loop-proj")) self.assertEqual(tmux.start_window(window, "/r", {}, ["x"], True, silent), Failure("tmux could not start the window loop-proj:item-7: it exited 2")) + def test_fails_where_it_cannot_mark_a_session_it_made_as_the_checkouts_but_not_where_remain_on_exit_fails(self): + def answering(failing: str): + def run(args): + fails = args[:1] == ["set-option"] and failing in args + return subprocess.CompletedProcess(args, 1 if fails else 0, "" if fails else "@9\n", "no such session\n" if fails else "") + return run + window = tmux.Window("loop-proj", "item-7", "") + self.assertEqual(tmux.start_window(window, "/r", {}, ["x"], True, answering(tmux.OWNER)), Failure("tmux started the session loop-proj but could not mark it as this checkout's: no such session")) + self.assertIsNone(tmux.start_window(window, "/r", {}, ["x"], True, answering("remain-on-exit"))) + self.assertIsNone(tmux.start_window(window, "/r", {}, ["x"], False, answering(tmux.OWNER))) + def test_reads_the_checkout_the_session_names(self): fake = FakeEffects(owner="/c/proj") self.assertEqual(tmux.owner("loop-proj", fake.tmux), "/c/proj") @@ -1330,7 +1338,7 @@ class ChunkWindows(unittest.TestCase): def plan(self, *touched): """A plan of items 1, 2 and on, each predicted to touch the path given for it.""" items = touch_plan(*((number, "1.0.0", "", f"- `{path}`") for number, path in enumerate(touched, 1))) - return gathered.Plan(items=items, first=items[0], text="", branch_template="") + return next_chunk.NextChunk(items=items, first=items[0], text="", branch_template="") def test_starts_the_next_item_and_those_picked_beside_it_up_to_the_limit(self): # Item 2 overlaps item 1, so it waits for it; items 3 and 4 run beside it. @@ -1339,26 +1347,39 @@ class ChunkWindows(unittest.TestCase): self.assertEqual(chunk_windows.may_start(plan, [], set(), 2), ["item-1", "item-3"]) self.assertEqual(chunk_windows.may_start(plan, [], set(), 9), ["item-1", "item-3", "item-4"]) - def test_leaves_the_items_running_chunks_hold_and_counts_them_against_the_limit(self): + def test_leaves_the_items_running_chunks_hold_and_starts_only_as_many_as_the_room_left(self): plan = self.plan("a.py", "a.py", "c.py", "d.py") - self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1, 3}, 2), ["item-4"]) - self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1}, 3), ["item-3", "item-4"]) - self.assertEqual(chunk_windows.may_start(plan, ["item-1", "item-3"], {1, 3}, 2), []) - self.assertEqual(chunk_windows.may_start(plan, ["item-1", "item-3", "item-4"], {1, 3, 4}, 2), []) + self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1, 3}, 1), ["item-4"]) + self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1}, 2), ["item-3", "item-4"]) + self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1}, 0), []) + + def test_counts_the_running_chunks_against_the_limit_and_restarts_stopped_ones_first(self): + windows = [tmux.Listed("item-1", "", False), tmux.Listed("item-3", "", True), tmux.Listed("item-4", "", True)] + self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 3), chunk_windows.Room(["item-1"], ["item-3", "item-4"], ["item-3", "item-4"], 0)) + self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 2), chunk_windows.Room(["item-1"], ["item-3", "item-4"], ["item-3"], 0)) + self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 5), chunk_windows.Room(["item-1"], ["item-3", "item-4"], ["item-3", "item-4"], 2)) + + def test_a_loop_whose_chunk_finished_leaves_its_room_and_restarts_no_stopped_chunk(self): + windows = [tmux.Listed("item-1", "", False), tmux.Listed("item-3", "", True)] + self.assertEqual(chunk_windows.room_of(windows, "item-1", True, 2), chunk_windows.Room([], ["item-3"], [], 2)) + + def test_leaves_no_room_where_more_chunks_run_than_the_limit(self): + windows = [tmux.Listed(f"item-{n}", "", False) for n in (1, 2, 3)] + self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 2).left, 0) def test_starts_no_item_that_overlaps_a_running_chunks_items(self): # Item 1 merged, so 2 is the plan's next item; it overlaps item 3, which still runs, at c.py. items = touch_plan((2, "1.0.0", "", "- `a.py`\n- `c.py`"), (3, "1.0.0", "", "- `c.py`"), (4, "1.0.0", "", "- `d.py`")) - plan = gathered.Plan(items=items, first=items[0], text="", branch_template="") - self.assertEqual(chunk_windows.may_start(plan, ["item-3"], {3}, 3), ["item-4"]) + plan = next_chunk.NextChunk(items=items, first=items[0], text="", branch_template="") + self.assertEqual(chunk_windows.may_start(plan, ["item-3"], {3}, 2), ["item-4"]) # A running chunk's item without a prediction leaves no other item free to start beside it. unpredicted = touch_plan((2, "1.0.0", "", "- `a.py`"), (3, "1.0.0", "", None)) - self.assertEqual(chunk_windows.may_start(gathered.Plan(items=unpredicted, first=unpredicted[0], text="", branch_template=""), ["item-3"], {3}, 3), []) + self.assertEqual(chunk_windows.may_start(next_chunk.NextChunk(items=unpredicted, first=unpredicted[0], text="", branch_template=""), ["item-3"], {3}, 2), []) # A held item that left the plan, as once it merged, overlaps nothing. - self.assertEqual(chunk_windows.may_start(plan, ["item-9"], {9}, 3), ["item-2", "item-4"]) + self.assertEqual(chunk_windows.may_start(plan, ["item-9"], {9}, 2), ["item-2", "item-4"]) def test_a_plan_without_an_item_starts_one_chunk_and_only_alone(self): - none = gathered.NoItem("release 1.0.0 has no items") + none = next_chunk.NoItem("release 1.0.0 has no items") self.assertEqual(chunk_windows.may_start(none, [], set(), 3), ["no-item"]) self.assertEqual(chunk_windows.may_start(none, ["item-1"], {1}, 3), []) @@ -1489,6 +1510,11 @@ class StartChunks(unittest.TestCase): fake = FakeEffects(windows="item-5\t1\t@3\n") self.assertEqual(self.start(fake), ["item-5", "item-1"]) + def test_a_plan_with_no_item_starts_nothing_beside_a_restarted_chunk(self): + self.limit(2) + fake = FakeEffects(windows="item-5\t1\t@3\n") + self.assertEqual(self.start(fake, plan=next_chunk.NoItem("release 1.0.0 has no items")), ["item-5"]) + def test_a_finishing_chunk_leaves_a_stopped_chunk_and_its_items_to_the_human(self): self.limit(2) transcripts = paths.paths_from(self.home).claude_code_transcripts @@ -1501,7 +1527,7 @@ class StartChunks(unittest.TestCase): self.assertEqual(self.start(fake, chunk="item-7", leaving=True), ["item-3"]) self.assertEqual([call for call in fake.tmux_calls if call[0] == "kill-window"], []) fake = FakeEffects(windows="item-7\t0\t@1\nno-item\t1\t@3\n") - self.assertEqual(self.start(fake, chunk="item-7", leaving=True, plan=gathered.NoItem("release 1.0.0 has no items")), []) + self.assertEqual(self.start(fake, chunk="item-7", leaving=True, plan=next_chunk.NoItem("release 1.0.0 has no items")), []) def test_starts_the_chunk_without_a_plan_item_where_the_plan_cannot_be_read(self): fake = FakeEffects() @@ -1697,7 +1723,7 @@ class WorkerArgs(unittest.TestCase): def test_keeps_every_review_on_the_projects_rung_while_the_worker_runs_below_it(self): opus = Rung("claude-opus-5-5", "medium") below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), LADDER, opus, self.FACTS) - self.assertIn(f"item 3's L of 2. Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.{self.SCAN} Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger", below) + self.assertIn(f"item 3's L of 2. Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.{self.SCAN} Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger", below) self.assertNotIn("Launch each", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), LADDER, opus, self.FACTS)) def test_launches_reviewers_on_the_rung_the_items_e_plus_i_picks_above_the_workers(self): diff --git a/bin/loop_claude/tmux.py b/bin/loop_claude/tmux.py index 1f2e0519..d2eebcf0 100644 --- a/bin/loop_claude/tmux.py +++ b/bin/loop_claude/tmux.py @@ -66,7 +66,7 @@ def listed(session: str, run: Tmux) -> list[Listed]: def start_window(window: Window, cwd: str, env: typing.Mapping[str, str], command: list[str], first: bool, run: Tmux) -> Failure | None: - """Starts command in a new window of window's session, in cwd with env added to its environment, and leaves the client where it is. first makes the session too. A Failure says why tmux started none.""" + """Starts command in a new window of window's session, in cwd with env added to its environment, and leaves the client where it is. first makes the session too. A Failure says why tmux started none, or why it could not mark a session it made as this checkout's.""" make = ["new-session", "-d", "-s", window.session] if first else ["new-window", "-d", "-t", f"={window.session}:"] variables = [flag for name, value in env.items() for flag in ("-e", f"{name}={value}")] # tmux reads a `;` that ends an argument as the end of the command, unless a backslash precedes it. @@ -74,11 +74,13 @@ def start_window(window: Window, cwd: str, env: typing.Mapping[str, str], comman done = run([*make, "-n", window.name, "-c", cwd, *variables, "-P", "-F", "#{window_id}", "--", *words]) if done.returncode: return Failure(f"tmux could not start the window {window.target}: {done.stderr.strip() or f'it exited {done.returncode}'}") - if first: - # set-option and show-options read a target as a pane's, so `=session` alone names no session. - run(["set-option", "-t", f"={window.session}:", OWNER, cwd]) - # By the ID, since a window of the same name may still be closing. A loop that fails before the option is set closes its window, and its stop is still sent as a DM. + # set-option and show-options read a target as a pane's, so `=session` alone names no session. + owned = run(["set-option", "-t", f"={window.session}:", OWNER, cwd]) if first else None + # By the ID, since a window of the same name may still be closing. A failed remain-on-exit doesn't matter: a loop that fails before it is set closes its window, and its stop is still sent as a DM. run(["set-option", "-w", "-t", done.stdout.strip(), "remain-on-exit", "failed"]) + # Without the owner, start_chunks cannot tell this checkout's session from another's, so no further chunk may start in it. + if owned is not None and owned.returncode: + return Failure(f"tmux started the session {window.session} but could not mark it as this checkout's: {owned.stderr.strip() or f'it exited {owned.returncode}'}") return None diff --git a/bin/loop_claude/verdicts.py b/bin/loop_claude/verdicts.py index d027f199..9d06aaca 100644 --- a/bin/loop_claude/verdicts.py +++ b/bin/loop_claude/verdicts.py @@ -6,7 +6,7 @@ from claude_code.tokens import Tokens @dataclasses.dataclass(frozen=True) class TakenIn: - """The levels of the todo.md items the worker names on its latest `Chunk items:` line, as cycle.chunk_items reads them. The item the chunk was routed on counts only where the worker names it.""" + """The highest L, and the highest E + I, among the plan items the worker names on its latest `Chunk items:` line, as cycle.chunk_items reads them. The item the chunk was routed on counts only where the worker names it.""" # The highest L among them, 0 for none: an escalation steps up from the rung that L picks, and an unfinished verdict also raises the worker to it. highest_likelihood: int = 0 # The highest E + I among them, 0 for none: after an unfinished verdict, it routes the next cycle's reviewers. diff --git a/bin/model_routing/route.py b/bin/model_routing/route.py index 45e29068..f2662520 100644 --- a/bin/model_routing/route.py +++ b/bin/model_routing/route.py @@ -3,7 +3,7 @@ import dataclasses import json import typing -from release_plan.todo_table import LEVELS +from plan.todo_table import LEVELS from model_routing.ladder import REVIEW_STEPS, Rung # How a worker opens the prompt of a subagent it escalates a task to, `Escalation trigger 2: …`: docs/decisions.md → `routing: a worker hands a task one rung up`. diff --git a/bin/model_routing/test_ladder.py b/bin/model_routing/test_ladder.py index 0bdc33ca..deb0472d 100644 --- a/bin/model_routing/test_ladder.py +++ b/bin/model_routing/test_ladder.py @@ -4,7 +4,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from release_plan.todo_table import LEVELS +from plan.todo_table import LEVELS from model_routing.ladder_file import read_ladder, SHIPPED from review_rules.review_passes import REVIEWERS from model_routing.ladder import Rung, WORKER_STEPS diff --git a/bin/mattermost_dm/dm.py b/bin/notifier/mattermost.py similarity index 100% rename from bin/mattermost_dm/dm.py rename to bin/notifier/mattermost.py diff --git a/bin/notifier/notify.py b/bin/notifier/notify.py index 59f1bd84..7c8af0bc 100644 --- a/bin/notifier/notify.py +++ b/bin/notifier/notify.py @@ -3,12 +3,11 @@ import dataclasses import pathlib import typing +from project_config.settings import CONFIG, Notifier, NOTIFIER, NOTIFIERS, ProjectConfig from failure import Failure from rest_client.json_request import Http from project_config.main import located -import mattermost_dm.dm -from project_config.settings import Notifier, NOTIFIER, NOTIFIERS, ProjectConfig -import slack_dm.dm +from notifier import mattermost, slack # Sends one message, with the credentials already read. Sender = typing.Callable[[str], Failure | None] @@ -25,8 +24,8 @@ class Backend[C]: # The one place each notifier is wired to the network: a caller that tests a send passes a table with its own `http`. BACKENDS: dict[Notifier, Backend[typing.Any]] = { - "mattermost": Backend(mattermost_dm.dm.read_config, mattermost_dm.dm.send, mattermost_dm.dm.http_json, mattermost_dm.dm.KEYS), - "slack": Backend(slack_dm.dm.read_config, slack_dm.dm.send, slack_dm.dm.http_json, slack_dm.dm.KEYS), + "mattermost": Backend(mattermost.read_config, mattermost.send, mattermost.http_json, mattermost.KEYS), + "slack": Backend(slack.read_config, slack.send, slack.http_json, slack.KEYS), } assert tuple(BACKENDS) == NOTIFIERS @@ -34,9 +33,9 @@ assert tuple(BACKENDS) == NOTIFIERS def sender_of(project: ProjectConfig, backends: typing.Mapping[Notifier, Backend[typing.Any]]) -> Sender | Failure: """A sender through the project's notifier in backends, with the credentials in its env file read. A Failure where the project names no notifier or its env file cannot be used.""" if project.notifier is None: - return Failure(f"{project.folder / 'config.toml'} sets no `{NOTIFIER}`; set `notifier` to {' or '.join(NOTIFIERS)}, and `env-file` to the file that holds that service's keys ({'; '.join(f'{name}: {', '.join(backend.keys)}' for name, backend in backends.items())})") + return Failure(f"{project.folder / CONFIG} sets no `{NOTIFIER}`; set `notifier` to {' or '.join(NOTIFIERS)}, and `env-file` to the file that holds that service's keys ({'; '.join(f'{name}: {', '.join(backend.keys)}' for name, backend in backends.items())})") if project.env_file is None: - return Failure(f"{project.folder / 'config.toml'} sets `{NOTIFIER}` but no `env-file`, the file that holds its credentials") + return Failure(f"{project.folder / CONFIG} sets `{NOTIFIER}` but no `env-file`, the file that holds its credentials") backend = backends[project.notifier] config = backend.read_config(project.env_file) if isinstance(config, Failure): diff --git a/bin/slack_dm/dm.py b/bin/notifier/slack.py similarity index 100% rename from bin/slack_dm/dm.py rename to bin/notifier/slack.py diff --git a/bin/mattermost_dm/test_mattermost_dm.py b/bin/notifier/test_mattermost.py similarity index 99% rename from bin/mattermost_dm/test_mattermost_dm.py rename to bin/notifier/test_mattermost.py index 62089bdc..f1619864 100644 --- a/bin/mattermost_dm/test_mattermost_dm.py +++ b/bin/notifier/test_mattermost.py @@ -6,7 +6,7 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from mattermost_dm import dm +from notifier import mattermost as dm from failure import Failure CONFIG = dm.Config("https://chat.example", "secret-token", "lilleman") diff --git a/bin/notifier/test_notifier.py b/bin/notifier/test_notifier.py index b20403a3..44b1bd3c 100644 --- a/bin/notifier/test_notifier.py +++ b/bin/notifier/test_notifier.py @@ -16,9 +16,9 @@ from rest_client.json_request import Http from test_env import isolated_env from project_config.main import located from notifier import main, notify -from mattermost_dm.test_mattermost_dm import mattermost +from notifier.test_mattermost import mattermost from project_config.settings import Notifier -from slack_dm.test_slack_dm import Slack +from notifier.test_slack import Slack from loop_effects.effects import system_effects TOOL = pathlib.Path(__file__).resolve().parents[1] / "notify" diff --git a/bin/slack_dm/test_slack_dm.py b/bin/notifier/test_slack.py similarity index 99% rename from bin/slack_dm/test_slack_dm.py rename to bin/notifier/test_slack.py index 8d73fed7..298f9837 100644 --- a/bin/slack_dm/test_slack_dm.py +++ b/bin/notifier/test_slack.py @@ -6,7 +6,7 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from slack_dm import dm +from notifier import slack as dm from failure import Failure CONFIG = dm.Config("xoxb-secret", "U0123ABCD") diff --git a/bin/slack_dm/__init__.py b/bin/plan/__init__.py similarity index 100% rename from bin/slack_dm/__init__.py rename to bin/plan/__init__.py diff --git a/bin/release_plan/blockers.py b/bin/plan/blockers.py similarity index 97% rename from bin/release_plan/blockers.py rename to bin/plan/blockers.py index 1a9ee335..c72f2a0c 100644 --- a/bin/release_plan/blockers.py +++ b/bin/plan/blockers.py @@ -3,8 +3,8 @@ import dataclasses import graphlib from failure import Failure -from release_plan.todo_table import Item -from release_plan.release import version +from plan.todo_table import Item +from plan.release import version def blockers_first(scored: list[tuple[Item, float]]) -> list[tuple[Item, float]] | Failure: diff --git a/bin/release_plan/citations.py b/bin/plan/citations.py similarity index 96% rename from bin/release_plan/citations.py rename to bin/plan/citations.py index 547004c0..c94918a9 100644 --- a/bin/release_plan/citations.py +++ b/bin/plan/citations.py @@ -1,7 +1,7 @@ import re from failure import Failure -from release_plan.todo_table import Item +from plan.todo_table import Item def check_citations(items: list[Item], decisions: str) -> Failure | None: diff --git a/bin/release_plan/formula.py b/bin/plan/formula.py similarity index 100% rename from bin/release_plan/formula.py rename to bin/plan/formula.py diff --git a/bin/release_plan/goals_file.py b/bin/plan/goals_file.py similarity index 99% rename from bin/release_plan/goals_file.py rename to bin/plan/goals_file.py index 47d95c32..09fb5f0d 100644 --- a/bin/release_plan/goals_file.py +++ b/bin/plan/goals_file.py @@ -4,7 +4,7 @@ import decimal import re import typing -from release_plan.todo_table import CODE_HEALTH +from plan.todo_table import CODE_HEALTH from failure import Failure from text_files.markdown_text import sections diff --git a/bin/release_plan/named_code.py b/bin/plan/named_paths.py similarity index 100% rename from bin/release_plan/named_code.py rename to bin/plan/named_paths.py diff --git a/bin/release_plan/ranking.py b/bin/plan/ranking.py similarity index 95% rename from bin/release_plan/ranking.py rename to bin/plan/ranking.py index bfc41c7c..0e9ebb73 100644 --- a/bin/release_plan/ranking.py +++ b/bin/plan/ranking.py @@ -7,15 +7,15 @@ import math import re import typing -from release_plan.todo_table import BLOCKED_BY, cells, CODE_HEALTH, DETAILS, Exempt, HEADER_START, Item, item_details, items_table, MOVES, OLD_SHAPE, parse_row, renames, risk, Shape, SHAPE, shape_of, Table, table_rows -from release_plan.blockers import blocked_through, blockers_first -from release_plan.citations import check_citations -from release_plan.formula import evaluate, parse_formula +from plan.todo_table import BLOCKED_BY, cells, CODE_HEALTH, detail_heading, DETAILS, Exempt, HEADER_START, Item, item_details, items_table, MOVES, OLD_SHAPE, parse_row, renames, risk, row_cells, Shape, SHAPE, shape_of, Table, table_rows, tagline_text +from plan.blockers import blocked_through, blockers_first +from plan.citations import check_citations +from plan.formula import evaluate, parse_formula from failure import Failure -from release_plan.goals_file import goal_weights, Mark, ranked_goals +from plan.goals_file import goal_weights, Mark, ranked_goals from review_rules.comprehension_history import latest_overall from text_files.markdown_text import listed -from release_plan.release import version +from plan.release import version # What a point of an item's move on a maintain goal is worth. A defect that restores the goal weighs it at least this much per point. docs/decisions.md records the choice and its data. MAINTAIN_WEIGHT = 0.5 @@ -331,7 +331,7 @@ def cited_goals_failure(item: Item, scoring: Scoring, name: str = "") -> Failure def render_item(item: Item, value: float, shape: Shape, columns: tuple[str, ...]) -> str: """The item's row, each cell under its column.""" - written = {"ID": str(item.id), "Release": version(item.release), BLOCKED_BY: ", ".join(map(str, item.blocked_by)), "Exempt": item.exempt, "Item": item.tagline, **{name: str(score) for name, score in item.scores.items()}, shape.goals_column: shape.write_goals(item.moves), "Score": f"{value:.1f}"} + written = row_cells(item, shape) | {"Score": f"{value:.1f}"} return "| " + " | ".join(written[column] for column in columns) + " |" @@ -342,7 +342,7 @@ def rank_details(text: str, items: list[Item]) -> str | Failure: return details if isinstance(details, Failure) else text if unknown := sorted(set(details) - {item.id for item in items}): return Failure(f"## Details holds item {', '.join(map(str, unknown))}, which the items table does not") - headed = [f"### {item.id}. {item.tagline.strip('*').replace(chr(92) + '|', '|')}\n\n{details[item.id]}\n" for item in items if item.id in details] + headed = [f"{detail_heading(item.id, tagline_text(item.tagline))}\n\n{details[item.id]}\n" for item in items if item.id in details] ranked = "\n" + "\n".join(headed) if headed else "\n" tail = "\n" if section.end() < len(text) else "" return text[:section.start(1)] + ranked + tail + text[section.end():] diff --git a/bin/release_plan/release.py b/bin/plan/release.py similarity index 88% rename from bin/release_plan/release.py rename to bin/plan/release.py index 53ccc116..062246bb 100644 --- a/bin/release_plan/release.py +++ b/bin/plan/release.py @@ -10,6 +10,9 @@ VERSION = r"[0-9]+\.[0-9]+\.[0-9]+" DATE_DIGITS = (4, 2, 2) DATED = re.compile(rf"({VERSION}) - " + "-".join(f"[0-9]{{{digits}}}" for digits in DATE_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.*)" +UNRELEASED_HEADING = re.compile(rf"^## {UNRELEASED_TITLE}$", re.M) def release_of(version: str) -> Release: diff --git a/bin/release_plan/test_blockers.py b/bin/plan/test_blockers.py similarity index 98% rename from bin/release_plan/test_blockers.py rename to bin/plan/test_blockers.py index f6680cd6..587c9746 100644 --- a/bin/release_plan/test_blockers.py +++ b/bin/plan/test_blockers.py @@ -5,10 +5,10 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from release_plan.test_ranking import DECISIONS, README, TODO +from plan.test_ranking import DECISIONS, README, TODO from project_config.settings import DEFAULT_FLOOR from failure import Failure -from release_plan import ranking, todo_table +from plan import ranking, todo_table class Blockers(unittest.TestCase): diff --git a/bin/release_plan/test_formula.py b/bin/plan/test_formula.py similarity index 94% rename from bin/release_plan/test_formula.py rename to bin/plan/test_formula.py index 2250c2ca..52d0f8e8 100644 --- a/bin/release_plan/test_formula.py +++ b/bin/plan/test_formula.py @@ -4,10 +4,10 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from release_plan.test_ranking import DECISIONS, README, TODO +from plan.test_ranking import DECISIONS, README, TODO from project_config.settings import DEFAULT_FLOOR from failure import Failure -from release_plan import ranking +from plan import ranking class Formula(unittest.TestCase): diff --git a/bin/release_plan/test_goals_file.py b/bin/plan/test_goals_file.py similarity index 93% rename from bin/release_plan/test_goals_file.py rename to bin/plan/test_goals_file.py index 63ff4ff4..a69aa3d6 100644 --- a/bin/release_plan/test_goals_file.py +++ b/bin/plan/test_goals_file.py @@ -1,7 +1,7 @@ import unittest from failure import Failure -from release_plan.goals_file import section +from plan.goals_file import section GOALS_FILE = "# P\n## Goals\n1. g\n## Audience\nme\n" diff --git a/bin/release_plan/test_named_code.py b/bin/plan/test_named_paths.py similarity index 94% rename from bin/release_plan/test_named_code.py rename to bin/plan/test_named_paths.py index 26fdea0e..bbb59633 100644 --- a/bin/release_plan/test_named_code.py +++ b/bin/plan/test_named_paths.py @@ -4,7 +4,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from release_plan.named_code import named_files, named_paths +from plan.named_paths import named_files, named_paths class NamedPaths(unittest.TestCase): diff --git a/bin/release_plan/test_ranking.py b/bin/plan/test_ranking.py similarity index 99% rename from bin/release_plan/test_ranking.py rename to bin/plan/test_ranking.py index 1a7210de..83ba4dae 100644 --- a/bin/release_plan/test_ranking.py +++ b/bin/plan/test_ranking.py @@ -12,10 +12,11 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from project_config.test_project_config import configured from project_config.settings import DEFAULT_FLOOR from failure import Failure -from release_plan import goals_file, plan_file, ranking +from plan_store.stores import file_plan +from plan import goals_file, ranking from project_config.main import located from repo_checks import ROOT -from release_plan import todo_table +from plan import todo_table # Voids code health, so these tests weigh only the project's own goals; class CodeHealth weighs it. VOID = "**Void:** code health, since a test project has no code to read.\n\n" @@ -378,7 +379,7 @@ class CodeHealth(unittest.TestCase): pathlib.Path(temp, "docs").mkdir() pathlib.Path(temp, "docs", "comprehension-history.md").write_text(SCORED.format(overall="7.00")) with contextlib.redirect_stderr(io.StringIO()): - ranked = plan_file.rank_file(todo, located(temp, pathlib.Path.home())) + ranked = file_plan(located(temp, pathlib.Path.home()), todo).rank() self.assertIsInstance(ranked, ranking.Ranked) self.assertEqual(ranked.under_bar, []) self.assertIn("| code health by 1 | 25.4 |", todo.read_text()) @@ -395,10 +396,10 @@ class CodeHealth(unittest.TestCase): pathlib.Path(temp, "docs").mkdir() pathlib.Path(temp, "docs", "comprehension-history.md").write_text(SCORED.format(overall="6.50")) with contextlib.redirect_stderr(io.StringIO()): - ranked = plan_file.rank_file(todo, located(temp, pathlib.Path.home())) + ranked = file_plan(located(temp, pathlib.Path.home()), todo).rank() self.assertIsInstance(ranked, ranking.Ranked) self.assertIn("| code health by 1 | 25.4 |", todo.read_text()) - self.assertEqual(plan_file.check_failures(todo, located(temp, pathlib.Path.home())), []) + self.assertEqual(file_plan(located(temp, pathlib.Path.home()), todo).check(), []) class Risk(unittest.TestCase): diff --git a/bin/release_plan/test_release.py b/bin/plan/test_release.py similarity index 96% rename from bin/release_plan/test_release.py rename to bin/plan/test_release.py index d49dd2f8..2605cf39 100644 --- a/bin/release_plan/test_release.py +++ b/bin/plan/test_release.py @@ -7,7 +7,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from test_env import isolated_env -from release_plan.release import newest_tag, tagged +from plan.release import newest_tag, tagged class NewestTag(unittest.TestCase): diff --git a/bin/release_plan/todo_table.py b/bin/plan/todo_table.py similarity index 76% rename from bin/release_plan/todo_table.py rename to bin/plan/todo_table.py index 85419569..d28986d9 100644 --- a/bin/release_plan/todo_table.py +++ b/bin/plan/todo_table.py @@ -4,7 +4,7 @@ import typing from failure import Failure from text_files.markdown_text import FENCE, sections -from release_plan.release import parsed, Release, release_of, VERSION +from plan.release import parsed, Release, release_of, version, VERSION # Each score a Shape names, and each goal's move, runs from 1 to TOP_SCORE, but for the levels L, E and I, which run from 1 to their LEVELS: ~/.claude/rules/todo-items.md defines each level. TOP_SCORE = 10 @@ -43,7 +43,7 @@ class Shape: risk_columns: tuple[str, ...] # The scores rank_todo.py works out and writes, so a blank cell reads as no score yet. derived: tuple[str, ...] - # The column naming the goals an item serves; read_goals reads it, given the item's ID to name in a failure, and write_goals writes it back. + # The column naming the goals an item serves; read_goals reads it, given what a failure calls the item, and write_goals writes it back. goals_column: str read_goals: typing.Callable[[str, str], Moves | Failure] write_goals: typing.Callable[[Moves], str] @@ -59,17 +59,17 @@ class Shape: return tuple(column for column in self.columns if column not in self.optional) -def parse_moves(id_: str, cell: str) -> Moves | Failure: +def parse_moves(label: str, cell: str) -> Moves | Failure: """A Moves cell: empty, or each goal the item moves, named once, and how far. ranking.py's cited_goals_failure holds the rules that need the goals file.""" matches = [re.fullmatch(rf"([0-9]+(?:\.[0-9]+)*|{CODE_HEALTH}) by ([0-9]+)", move) for move in cell.split(", ")] if cell else [] moves = tuple((match.group(1), int(match.group(2))) for match in matches if match) if len(moves) < len(matches) or any(not 1 <= by <= TOP_SCORE for _, by in moves): - return Failure(f"item {id_}'s {MOVES} {cell!r} is not empty or goals such as `1.1 by 8, {CODE_HEALTH} by 5`, each moved by a whole number from 1 to {TOP_SCORE}") + return Failure(f"{label}'s {MOVES} {cell!r} is not empty or goals such as `1.1 by 8, {CODE_HEALTH} by 5`, each moved by a whole number from 1 to {TOP_SCORE}") goals = [goal for goal, _ in moves] if repeated := [goal for goal in goals if goals.count(goal) > 1]: - return Failure(f"item {id_} cites goal {repeated[0]} twice; name each goal once") + return Failure(f"{label} cites goal {repeated[0]} twice; name each goal once") if nested := [(parent, goal) for parent in goals for goal in goals if goal.startswith(parent + ".")]: - return Failure(f"item {id_} names goal {nested[0][0]} and its sub-goal {nested[0][1]}; name one, never both: the sub-goal where the move serves it, else the parent") + return Failure(f"{label} names goal {nested[0][0]} and its sub-goal {nested[0][1]}; name one, never both: the sub-goal where the move serves it, else the parent") return moves @@ -77,7 +77,7 @@ def write_moves(moves: Moves) -> str: return ", ".join(f"{goal} by {by}" for goal, by in moves) -def parse_cited(id_: str, cell: str) -> Moves: +def parse_cited(label: str, cell: str) -> Moves: """An old-shape Goals cell, such as `2.1, 1`: each goal it cites, with no move.""" return tuple((goal.strip(), None) for goal in cell.split(",")) @@ -268,49 +268,64 @@ def parse_row(row: str, table: Table) -> Item | Failure: if isinstance(found, Failure): return found named = dict(zip(table.columns, found)) - exempt = check_cells(row, named) - if isinstance(exempt, Failure): - return exempt + id_, tagline = named["ID"], named["Item"] + if not re.fullmatch(r"[0-9]+", id_) or int(id_) < 1: + return Failure(f"the ID {id_!r} is not a positive whole number: {row}") + if not re.fullmatch(r"\*\*[^*].*[^*]\*\*", tagline): + return Failure(f"item {id_}'s Item cell is not one bold tagline: {tagline}") shape = shape_of(table.columns) - scores = parse_scores(named["ID"], {name: cell for name, cell in named.items() if cell or name not in shape.derived}, shape.score_columns) + fields = item_fields({name: cell for name, cell in named.items() if cell or name not in shape.derived}, f"item {id_}", shape, int(id_)) + if isinstance(fields, Failure): + return fields + assert fields.release is not None, "table_rows refuses a table without a Release column" + return Item(int(id_), fields.release, fields.exempt, tagline, fields.scores, fields.moves, fields.blocked_by) + + +@dataclasses.dataclass(frozen=True) +class ItemFields: + """The cells of an item that a caller named, each held to the items table's format. A cell it didn't name reads as empty, and the release as None.""" + release: Release | None = None + exempt: Exempt = "" + scores: dict[str, int] = dataclasses.field(default_factory=dict) + moves: Moves = () + blocked_by: tuple[int, ...] = () + + +def item_fields(named: dict[str, str], label: str, shape: Shape = SHAPE, id_: int | None = None) -> ItemFields | Failure: + """Each of the Release, Exempt, score, goals and Blocked-by cells that named holds by column name, held to shape's format; the one check every plan backend makes of an item's cells. label opens each message, such as "item 12" or "the item to file". id_ is the item's own ID, which its Blocked by may not name.""" + release = named.get("Release") + if release is not None and parsed(release) is None: + return Failure(f"{label}'s Release {release!r} is not a semver version, such as 1.2.0") + exempt = named.get("Exempt", "") + if not is_exempt(exempt): + return Failure(f"{label}'s Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}") + scores = parse_scores(label, named, shape.score_columns) if isinstance(scores, Failure): return scores - blocked_by = parse_blockers(named["ID"], named.get(BLOCKED_BY, "")) - if isinstance(blocked_by, Failure): - return blocked_by - moves = shape.read_goals(named["ID"], named[shape.goals_column]) + moves = shape.read_goals(label, named.get(shape.goals_column, "")) if isinstance(moves, Failure): return moves - return Item(int(named["ID"]), release_of(named["Release"]), exempt, named["Item"], scores, moves, blocked_by) + blocked_by = parse_ids(named.get(BLOCKED_BY, "")) + if blocked_by is None: + return Failure(f"{label}'s {BLOCKED_BY} {named[BLOCKED_BY]!r} is not empty or IDs separated by \", \"") + if id_ in blocked_by: + return Failure(f"{label} is blocked by itself; drop {id_} from its {BLOCKED_BY}") + return ItemFields(None if release is None else release_of(release), exempt, scores, moves, blocked_by) def is_exempt(cell: str) -> typing.TypeGuard[Exempt]: return cell in EXEMPTIONS -def check_cells(row: str, named: dict[str, str]) -> Exempt | Failure: - """Holds the row's ID, Release, Exempt and Item cells to the format: the row's Exempt cell, or why a cell breaks it.""" - id_, release, exempt, tagline = named["ID"], named["Release"], named["Exempt"], named["Item"] - if not re.fullmatch(r"[0-9]+", id_) or int(id_) < 1: - return Failure(f"the ID {id_!r} is not a positive whole number: {row}") - if parsed(release) is None: - return Failure(f"item {id_}'s release {release!r} is not a semver version") - if not is_exempt(exempt): - return Failure(f"item {id_}'s Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}") - if not re.fullmatch(r"\*\*[^*].*[^*]\*\*", tagline): - return Failure(f"item {id_}'s Item cell is not one bold tagline: {tagline}") - return exempt - - -def parse_scores(id_: str, named: dict[str, str], names: tuple[str, ...]) -> dict[str, int] | Failure: - """Each score in names that the row holds; only an optional one may be missing, since the table holds every needed column.""" +def parse_scores(label: str, named: dict[str, str], names: tuple[str, ...]) -> dict[str, int] | Failure: + """Each score in names that named holds; only an optional one may be missing, since the table holds every needed column.""" scores: dict[str, int] = {} for name in names: if name not in named: continue top = LEVELS.get(name, TOP_SCORE) if not re.fullmatch(r"[0-9]+", named[name]) or not 1 <= int(named[name]) <= top: - return Failure(f"item {id_}'s {name} {named[name]!r} is not a whole number from 1 to {top}") + return Failure(f"{label}'s {name} {named[name]!r} is not a whole number from 1 to {top}") scores[name] = int(named[name]) return scores @@ -322,10 +337,21 @@ def parse_ids(cell: str) -> tuple[int, ...] | None: return tuple(int(id_) for id_ in cell.split(", ") if id_) -def parse_blockers(id_: str, cell: str) -> tuple[int, ...] | Failure: - blocked_by = parse_ids(cell) - if blocked_by is None: - return Failure(f"item {id_}'s {BLOCKED_BY} {cell!r} is not empty or IDs separated by \", \"") - if int(id_) in blocked_by: - return Failure(f"item {id_} is blocked by itself; drop {id_} from its {BLOCKED_BY}") - return blocked_by +def row_cells(item: Item, shape: Shape) -> dict[str, str]: + """item's cells by column name, as a row of a table in shape holds them; the Score, which only ranking works out, aside.""" + return {"ID": str(item.id), "Release": version(item.release), BLOCKED_BY: ", ".join(map(str, item.blocked_by)), "Exempt": item.exempt, "Item": item.tagline, **{name: str(score) for name, score in item.scores.items()}, shape.goals_column: shape.write_goals(item.moves)} + + +def tagline_text(cell: str) -> str: + """The tagline an Item cell holds, as plain text: without the bold, each | unescaped.""" + return cell.strip().removeprefix("**").removesuffix("**").replace("\\|", "|") + + +def detail_heading(id_: int, tagline: str) -> str: + """The heading under ## Details that opens item id_'s detail; tagline is plain text.""" + return f"### {id_}. {tagline}" + + +def items_shape(found: list[Item]) -> Shape: + """The shape a table of found needs: OLD_SHAPE where an item holds a score only that shape has, as a plan not yet reshaped does.""" + return OLD_SHAPE if any(set(item.scores) - set(SHAPE.score_columns) for item in found) else SHAPE diff --git a/bin/plan_store/contract.py b/bin/plan_store/contract.py index aca8f197..1d8efe6a 100644 --- a/bin/plan_store/contract.py +++ b/bin/plan_store/contract.py @@ -1,10 +1,10 @@ """What every plan backend must hold, as tests. A backend's test case inherits PlanStoreContract and unittest.TestCase, and builds its store in new_store. record_store.contract is its twin for records.""" import typing -from release_plan.todo_table import BLOCKED_BY, Item, MOVES +from plan.todo_table import BLOCKED_BY, Item, MOVES from failure import Failure -from plan_store.stores import Plan, PlanStore, TAGLINE, Written -from release_plan.release import release_of +from plan_store.plans import Plan, PlanStore, TAGLINE, Written +from plan.release import release_of FIRST = {"Release": "0.1.0", TAGLINE: "Count the runs.", "L": "1", "E": "2", "I": "3", "S": "1", MOVES: "1 by 9"} SECOND = {"Release": "0.2.0", TAGLINE: "Ship the later thing.", "L": "2", "E": "1", "I": "1", "S": "2", MOVES: "1 by 8", "Exempt": "owner"} diff --git a/bin/plan_store/fakes.py b/bin/plan_store/fakes.py index 24435aa5..ac74c552 100644 --- a/bin/plan_store/fakes.py +++ b/bin/plan_store/fakes.py @@ -2,9 +2,9 @@ import dataclasses from plan_store.markdown_edits import bold_cell, plain -from plan_store.stores import cells, Plan, Written +from plan_store.plans import cells, no_item, Plan, Written from failure import Failure -from release_plan.todo_table import Item, parse_row, SHAPE, Table +from plan.todo_table import Item, parse_row, SHAPE, Table @dataclasses.dataclass @@ -30,7 +30,7 @@ class MemoryPlan: def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure: if id_ not in self.rows: - return Failure(f"{self.label} holds no item {id_}") + return Failure(no_item(self.label, id_)) written = self.put(id_, self.rows[id_] | cells(fields), self.details.get(id_, "") if detail is None else detail) if comment is not None and isinstance(written, Written): self.comments.setdefault(id_, []).append(comment) @@ -38,7 +38,7 @@ class MemoryPlan: def finish(self, id_: int) -> Written | Failure: if self.fails or id_ not in self.rows: - return Failure(self.fails or f"{self.label} holds no item {id_}") + return Failure(self.fails or no_item(self.label, id_)) del self.rows[id_] self.details.pop(id_, None) return Written(id_) diff --git a/bin/plan_store/jira_epic.py b/bin/plan_store/jira_epic.py index fb96b92b..c60d6451 100644 --- a/bin/plan_store/jira_epic.py +++ b/bin/plan_store/jira_epic.py @@ -3,30 +3,24 @@ An item is an open child issue. Its ID is the issue's number, so every child must be in the epic's own Jira project: ABC-34 is item 34 of the plan under ABC-12. The summary is the tagline, the description the detail, the earliest Fix Version the release, and an "is blocked by" link a blocker. L, E, I, S, Moves and Exempt sit in one issue property, PROPERTY, which needs no Jira admin to set up; an issue a person filed holds none, and reads as an item without scores. `add` files an item as a new child issue, marked with FILED_BY, and ranks it among the issues the loop filed, by the score the config's formula gives, as `placing` says. `finish` moves an item's issue to a done status. `edit` changes an issue the loop filed, but never its links. Of an issue a person filed it sets only the scores, with a comment that tells the team why.""" -import base64 import dataclasses import pathlib import re import typing from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused -from release_plan.todo_table import BLOCKED_BY, EXEMPTIONS, is_exempt, Item, MOVES, parse_ids, parse_moves, parse_scores, SHAPE +from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown +from plan.todo_table import BLOCKED_BY, Item, item_fields, ItemFields, MOVES, SHAPE from plan_store.markdown_edits import bold_cell, plain, unfit_text -from plan_store.stores import cells, Plan, Written +from plan_store.plans import cells, no_item, Plan, Written from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION from failure import Failure -from rest_client import json_request -from release_plan.release import parsed, Release, tagged -from release_plan import ranking -from rest_client.env_file import read_env +from plan.release import parsed, Release, tagged +from plan import ranking -# One pair of keys for Jira and Confluence: one Atlassian account's API token opens both. -KEYS = ("ATLASSIAN_EMAIL", "ATLASSIAN_API_TOKEN") # The issue property that holds an item's scores, as a JSON object such as {"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1.6 by 4", "Exempt": ""}. PROPERTY = "plan-item" ISSUE_KEY = re.compile(r"([A-Z][A-Z0-9_]*)-([0-9]+)") -# Seconds each connect and each read may wait. -TIMEOUT = 30 PAGE = 100 # The pages one read asks for at most, so an answer that never names a last page ends the read. MAX_PAGES = 100 @@ -50,30 +44,12 @@ SET_SCORES = tuple(name for name in SHAPE.score_columns if name not in SHAPE.der # The fields of PROPERTY's value that an edit may set. SCORED = (*SET_SCORES, MOVES, "Exempt") -# Sends a request with the Authorization header given, the body as JSON where there is one, and returns the JSON answer, None where the answer has no body, or a Failure saying why there is none. -Http = typing.Callable[[str, str, str, object], object] -ToMarkdown = typing.Callable[[list[dict[str, typing.Any]]], list[str] | Refused | Failure] -ToAdf = typing.Callable[[str], dict[str, typing.Any] | Failure] - class ReadsScoring(typing.Protocol): def read(self) -> ranking.Scoring | Failure: """The scoring `add` scores an item by: the config's formula and bar, with the goal weights that the goals file, the decision log and the comprehension history give.""" -def http_json(method: str, url: str, authorization: str, body: object) -> object: - return json_request.http_json(method, url, authorization, body, TIMEOUT, error_message) - - -def error_message(answer: object) -> str: - """Jira's messages in the JSON of an error answer; empty where it holds none.""" - if not isinstance(answer, dict): - return "" - messages, errors = answer.get("errorMessages"), answer.get("errors") - found = [*(messages if isinstance(messages, list) else []), *(errors.values() if isinstance(errors, dict) else [])] - return "; ".join(text for text in found if isinstance(text, str)) - - @dataclasses.dataclass(frozen=True) class Issue: """A child issue as Jira answered it, checked to hold what an item is read from.""" @@ -84,7 +60,7 @@ class Issue: # The key of each issue this one "is blocked by". blockers: tuple[str, ...] # PROPERTY's value; an empty object where the issue holds none. - scores: object + scores: dict[str, typing.Any] @property def number(self) -> int: @@ -96,7 +72,7 @@ class JiraPlan: """The plan under epic, read and written with the credentials env_file holds.""" epic: Epic env_file: pathlib.Path - http: Http = http_json + http: Http = jira_json to_markdown: ToMarkdown = adfs_to_markdown to_adf: ToAdf = markdown_to_adf # How a finished item moves; None where the config doesn't say, and then `finish` is a Failure. @@ -138,12 +114,10 @@ class JiraPlan: authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization - issue_fields = filing.fields - if detail.strip(): - description = self.to_adf(detail) - if isinstance(description, Failure): - return Failure(f"cannot convert the item's detail to a Jira description: {description.reason}") - issue_fields = issue_fields | {"description": description} + description = self.description_of(detail) + if isinstance(description, Failure): + return description + issue_fields = filing.fields | ({"description": description} if description else {}) version = self.fix_version(filing.release, authorization) if isinstance(version, Failure): return version @@ -195,6 +169,22 @@ class JiraPlan: names = {name for version in versions if isinstance(version, dict) and isinstance(name := version.get("name"), str)} if isinstance(versions, list) else set() return next((name for name in (release, f"v{release}") if name in names), None) or Failure(f"the Jira project {project} has no Fix Version {release} or v{release}; create it in Jira, or name a release it has") + def child(self, id_: int, authorization: str) -> dict[str, typing.Any] | Failure: + """Item id_'s issue, as the epic's open children answer it; a Failure where none of them is item id_.""" + answered = children(self.epic, authorization, self.http) + if isinstance(answered, Failure): + return answered + key = f"{project_of(self.epic.key)}-{id_}" + found = next((raw for raw in answered if isinstance(raw, dict) and raw.get("key") == key), None) + return Failure(no_item(self.label, id_)) if found is None else found + + def description_of(self, detail: str) -> dict[str, typing.Any] | None | Failure: + """The Jira description that holds detail, as ADF; None for a blank detail, which leaves an issue without one.""" + if not detail.strip(): + return None + description = self.to_adf(detail) + return Failure(f"cannot convert the item's detail to a Jira description: {description.reason}") if isinstance(description, Failure) else description + def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure: """Sets the fields and the detail in one request, so Jira takes all of the edit or none, and then posts comment on the issue. `revision_of` says what an edit may set. @@ -202,24 +192,21 @@ class JiraPlan: authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization - answered = children(self.epic, authorization, self.http) - if isinstance(answered, Failure): - return answered - key = f"{project_of(self.epic.key)}-{id_}" - raw = next((raw for raw in answered if isinstance(raw, dict) and raw.get("key") == key), None) - if raw is None: - return Failure(f"{self.label} holds no item {id_}") + raw = self.child(id_, authorization) + if isinstance(raw, Failure): + return raw issue = issue_of(raw) if isinstance(issue, Failure): return issue + key = issue.key revision = revision_of(issue, cells(fields), detail, comment) if isinstance(revision, Failure): return revision body = revision.body if detail is not None: - description = self.to_adf(detail) if detail.strip() else None + description = self.description_of(detail) if isinstance(description, Failure): - return Failure(f"cannot convert the item's detail to a Jira description: {description.reason}") + return description body = body | {"fields": body.get("fields", {}) | {"description": description}} said = self.to_adf(comment) if comment and comment.strip() else None if isinstance(said, Failure): @@ -245,12 +232,10 @@ class JiraPlan: authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization - answered = children(self.epic, authorization, self.http) - if isinstance(answered, Failure): - return answered + raw = self.child(id_, authorization) + if isinstance(raw, Failure): + return raw key = f"{project_of(self.epic.key)}-{id_}" - if not any(isinstance(raw, dict) and raw.get("key") == key for raw in answered): - return Failure(f"{self.label} holds no item {id_}") url = f"{self.epic.site}/rest/api/3/issue/{key}/transitions" offered = self.http("GET", url, authorization, None) if isinstance(offered, Failure): @@ -285,27 +270,16 @@ def filing_of(fields: dict[str, str], detail: str, epic: Epic) -> Filing | Failu if unfit := unfit_text(summary, detail): return unfit release = named.get("Release", "") - version = parsed(release) - if version is None: - return Failure(f"the item's Release {release!r} is not a version such as 1.2.0") - # Named so the shared messages read "item to file's L": they open with "item" and an ID, which this item has none of yet. - levels = parse_scores("to file", named, SHAPE.score_columns) - if isinstance(levels, Failure): - return levels - moves, exempt = named.get(MOVES, ""), named.get("Exempt", "") - if isinstance(parsed_moves := parse_moves("to file", moves), Failure): - return parsed_moves - if not is_exempt(exempt): - return Failure(f"the item's Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}") - blockers = parse_ids(named.get(BLOCKED_BY, "")) - if blockers is None: - return Failure(f"the item's {BLOCKED_BY} {named[BLOCKED_BY]!r} is not empty or IDs separated by \", \"") + checked = item_fields(named | {"Release": release}, "the item to file") + if isinstance(checked, Failure): + return checked + assert checked.release is not None, "item_fields refuses an empty Release" project = project_of(epic.key) issue_fields: dict[str, typing.Any] = {"project": {"key": project}, "parent": {"key": epic.key}, "issuetype": {"name": ISSUE_TYPE}, "summary": summary} - if exempt == SECURITY: + if checked.exempt == SECURITY: issue_fields["labels"] = [SECURITY] - value = levels | {MOVES: moves, "Exempt": exempt, FILED_BY[0]: FILED_BY[1]} - return Filing(issue_fields, release, value, tuple(f"{project}-{blocker}" for blocker in blockers), Item(0, version, exempt, summary, levels, parsed_moves, blockers)) + value = checked.scores | {MOVES: named.get(MOVES, ""), "Exempt": checked.exempt, FILED_BY[0]: FILED_BY[1]} + return Filing(issue_fields, release, value, tuple(f"{project}-{blocker}" for blocker in checked.blocked_by), Item(0, checked.release, checked.exempt, summary, checked.scores, checked.moves, checked.blocked_by)) def filed_score(item: Item, scoring: ranking.Scoring) -> float | Failure: @@ -327,19 +301,18 @@ def placing(answered: list[object], new: Item, value: float, scoring: ranking.Sc issue = issue_of(raw) if isinstance(issue, Failure): return issue - if not isinstance(issue.scores, dict) or issue.scores.get(FILED_BY[0]) != FILED_BY[1]: + if issue.scores.get(FILED_BY[0]) != FILED_BY[1]: continue scored = scores(issue.key, issue.scores) if isinstance(scored, Failure): return scored - levels, moves, exempt = scored - if missing := next((name for name in SET_SCORES if name not in levels), None): + if missing := next((name for name in SET_SCORES if name not in scored.scores), None): return Failure(f"{issue.key} holds no {missing}") # Only the scores and the moves change a score. - other = ranking.item_score(dataclasses.replace(new, scores=levels, moves=moves), scoring, issue.key) + other = ranking.item_score(dataclasses.replace(new, scores=scored.scores, moves=scored.moves), scoring, issue.key) if isinstance(other, Failure): return other - if (ranking.FIRST.get(exempt, len(ranking.FIRST)), -other) > place: + if (ranking.FIRST.get(scored.exempt, len(ranking.FIRST)), -other) > place: return issue.key return None @@ -358,8 +331,6 @@ def revision_of(issue: Issue, named: dict[str, str], detail: str | None, comment The summary, description and Fix Version of an issue a person filed are the team's, so there an edit may set only SCORED. Jira's screens don't show PROPERTY, so such an edit needs a comment, which tells the team. L, E, I and S are set together, so no issue is left partly scored. An issue the loop filed also keeps the label SECURITY in step with its Exempt. No edit changes a link.""" held = issue.scores - if not isinstance(held, dict): - return Failure(f"{issue.key}'s issue property {PROPERTY} is not a JSON object") if BLOCKED_BY in named: return Failure(f"the loop doesn't change an issue's links: link {issue.key} in Jira") own = held.get(FILED_BY[0]) == FILED_BY[1] @@ -376,21 +347,19 @@ def revision_of(issue: Issue, named: dict[str, str], detail: str | None, comment if unfit := unfit_text(named.get("Item", ""), detail or ""): return unfit release = named.get("Release") - if release is not None and parsed(release) is None: - return Failure(f"the item's Release {release!r} is not a version such as 1.2.0") - if not is_exempt(named.get("Exempt", "")): - return Failure(f"the item's Exempt {named['Exempt']!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}") + if isinstance(checked := item_fields({name: named[name] for name in ("Release", "Exempt") if name in named}, f"item {issue.key}"), Failure): + return checked if any(name in named for name in SCORED): texts = {name: str(value) for name, value in held.items()} | {name: named[name] for name in SCORED if name in named} scored = scores(issue.key, texts) if isinstance(scored, Failure): return scored - if scored[0] and any(name not in scored[0] for name in SET_SCORES): + if scored.scores and any(name not in scored.scores for name in SET_SCORES): return Failure(f"{issue.key} would hold some of {', '.join(SET_SCORES)} and not the rest: set them together") - value = held | scored[0] | {MOVES: texts.get(MOVES, ""), "Exempt": scored[2]} + value = held | scored.scores | {MOVES: texts.get(MOVES, ""), "Exempt": scored.exempt} body["properties"] = [{"key": PROPERTY, "value": value}] - if own and (scored[2] == SECURITY) != (held.get("Exempt") == SECURITY): - body["update"] = {"labels": [{"add" if scored[2] == SECURITY else "remove": SECURITY}]} + if own and (scored.exempt == SECURITY) != (held.get("Exempt") == SECURITY): + body["update"] = {"labels": [{"add" if scored.exempt == SECURITY else "remove": SECURITY}]} return Revision(body, release) @@ -428,14 +397,6 @@ def project_of(key: str) -> str: return key.rpartition("-")[0] -def basic_auth(env_file: pathlib.Path) -> str | Failure: - """The Authorization header for the email and API token that env_file holds.""" - values = read_env(env_file, KEYS, "an API token") - if isinstance(values, Failure): - return values - return "Basic " + base64.b64encode(":".join(values[key] for key in KEYS).encode()).decode() - - def children(epic: Epic, authorization: str, http: Http) -> list[object] | Failure: """The epic's open child issues in backlog order, which the team ranks, apart from where add ranks an issue it files. An issue in a done status is a finished item, so it is no longer in the plan.""" # The search answers no issues for an epic the account cannot see, as for one whose children are all done; asking for the epic itself tells them apart. @@ -465,14 +426,19 @@ def children(epic: Epic, authorization: str, http: Http) -> list[object] | Failu def issue_of(raw: object) -> Issue | Failure: """The issue in one entry of the search's answer, or which issue is not in the shape Jira documents, and how.""" key = raw.get("key") if isinstance(raw, dict) else None - if not isinstance(key, str) or not ISSUE_KEY.fullmatch(key): + if not isinstance(raw, dict) or not isinstance(key, str) or not ISSUE_KEY.fullmatch(key): return Failure("the search answered an issue without an issue key") + # The answer's nested fields are read as Jira documents them; one missing or of another type ends the read here, as a Failure, so no later step meets it. try: - fields = typing.cast(dict[str, typing.Any], raw)["fields"] + fields = raw["fields"] blockers = tuple(link["inwardIssue"]["key"] for link in fields["issuelinks"] if "inwardIssue" in link and link["type"]["inward"] == "is blocked by") - issue = Issue(key, fields["summary"].strip(), fields["description"], tuple(version["name"] for version in fields["fixVersions"]), blockers, typing.cast(dict[str, typing.Any], raw).get("properties", {}).get(PROPERTY, {})) + held = raw.get("properties", {}).get(PROPERTY, {}) + summary, description, versions = fields["summary"].strip(), fields["description"], tuple(version["name"] for version in fields["fixVersions"]) except (AttributeError, KeyError, TypeError) as failure: return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: {failure!r}") + if not isinstance(held, dict): + return Failure(f"{key}'s issue property {PROPERTY} is not a JSON object") + issue = Issue(key, summary, description, versions, blockers, held) if not isinstance(issue.description, dict | None) or not all(isinstance(name, str) for name in issue.fix_versions + issue.blockers) or not all(ISSUE_KEY.fullmatch(blocker) for blocker in issue.blockers): return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: its description, a Fix Version's name or a linked issue's key holds another kind of value") return issue @@ -518,7 +484,7 @@ def item(issue: Issue, project: str, ids: set[int]) -> Item | Failure: if isinstance(scored, Failure): return scored blockers = {number(key) for key in issue.blockers if project_of(key) == project} - return Item(issue.number, release, scored[2], bold_cell(issue.summary), scored[0], scored[1], tuple(sorted(blockers & ids)), "") + return Item(issue.number, release, scored.exempt, bold_cell(issue.summary), scored.scores, scored.moves, tuple(sorted(blockers & ids)), "") def earliest_release(names: tuple[str, ...]) -> Release | None: @@ -527,18 +493,9 @@ def earliest_release(names: tuple[str, ...]) -> Release | None: return min(releases, default=None) -def scores(key: str, held: object) -> tuple[dict[str, int], typing.Any, typing.Any] | Failure: +def scores(key: str, held: dict[str, typing.Any]) -> ItemFields | Failure: """The scores, Moves and Exempt that an issue's PROPERTY value holds, each in the format the items table of a todo.md takes.""" - if not isinstance(held, dict): - return Failure(f"{key}'s issue property {PROPERTY} is not a JSON object") - named = {name: str(value) for name, value in held.items()} - levels = parse_scores(key, named, SHAPE.score_columns) - if isinstance(levels, Failure): - return levels - moves = parse_moves(key, named.get(MOVES, "")) - if isinstance(moves, Failure): - return moves - exempt = named.get("Exempt", "") - if not is_exempt(exempt): - return Failure(f"{key}'s issue property {PROPERTY} holds the Exempt {exempt!r}, which is not empty or one of {', '.join(EXEMPTIONS[1:])}") - return levels, moves, exempt + named = {name: str(value) for name, value in held.items() if name in (*SHAPE.score_columns, MOVES, "Exempt")} + checked = item_fields(named, f"item {key}") + # Jira's screens don't show PROPERTY, so the message says where the value is. + return Failure(f"{checked.reason}; {key} holds it in its issue property {PROPERTY}") if isinstance(checked, Failure) else checked diff --git a/bin/plan_store/markdown_edits.py b/bin/plan_store/markdown_edits.py index ac96966e..67075946 100644 --- a/bin/plan_store/markdown_edits.py +++ b/bin/plan_store/markdown_edits.py @@ -1,9 +1,10 @@ """The text edits behind the markdown plan: filing an item in todo.md, changing one and removing one. Each returns new text; ranking.rank then orders the table and details and writes the derived cells.""" import re -from release_plan.todo_table import cells, DETAILS, item_details, items_table, Table +from plan.todo_table import cells, detail_heading, DETAILS, item_details, items_table, Table, tagline_text from failure import Failure -from release_plan.ranking import stated +from plan_store.plans import no_item +from plan.ranking import stated # A line that would end ## Details (##) or could open another item's detail (###). HEADING = re.compile(r"^#{2,3} ", re.M) @@ -47,7 +48,7 @@ def edited(todo: str, id_: int, named: dict[str, str], detail: str | None, label if isinstance(details, Failure): return details row = dict(zip(table.columns, held)) - tagline = plain(named["Item"]) if "Item" in named else plain(row["Item"]).replace("\\|", "|") + tagline = plain(named["Item"]) if "Item" in named else tagline_text(row["Item"]) kept = details.get(id_, "") if detail is None else detail if unfit := unfit_text(tagline, "" if detail is None else detail): return unfit @@ -90,7 +91,7 @@ def with_detail(text: str, id_: int, tagline: str, detail: str) -> str: """text with detail first under ## Details, headed by id_ and tagline; text itself where detail is blank.""" if not detail.strip(): return text - entry = f"### {id_}. {tagline}\n\n{detail.strip()}\n" + entry = f"{detail_heading(id_, tagline)}\n\n{detail.strip()}\n" section = DETAILS.search(text) if section is None: return text.rstrip("\n") + f"\n\n## Details\n\n{entry}" @@ -113,7 +114,7 @@ def row_index(table: Table, id_: int, label: str) -> int | Failure: return found if found[0] == str(id_): return at - return Failure(f"{label} holds no item {id_}") + return Failure(no_item(label, id_)) def held_table(lines: list[str], label: str) -> Table | Failure: diff --git a/bin/plan_store/plans.py b/bin/plan_store/plans.py new file mode 100644 index 00000000..8dd38ab0 --- /dev/null +++ b/bin/plan_store/plans.py @@ -0,0 +1,73 @@ +"""What every plan backend reads and writes: a Plan, a Written, the PlanStore protocol they all meet, and the fields a caller may set on an item.""" +import dataclasses +import typing + +from plan.todo_table import BLOCKED_BY, Item, MOVES +from failure import Failure +from plan.release import Release + +TAGLINE = "Tagline" +# What a caller may set on an item, each as text in the format `rank_todo.py --help` states for the cell of that name. TAGLINE is the Item cell, bold or not. +FIELDS = ("Release", BLOCKED_BY, "Exempt", TAGLINE, "L", "E", "I", "S", MOVES) + + +@dataclasses.dataclass(frozen=True) +class Plan: + """A plan as one read found it.""" + # Each item with its detail, in the order the backend supplies: by release and then by rank for a markdown file, by backlog rank for a tracker. + items: list[Item] + # The releases the plan marks renamed. Such a release holds no item because its items moved, not because it is finished. + renamed: frozenset[Release] = frozenset() + + +@dataclasses.dataclass(frozen=True) +class Written: + """A write that landed.""" + id: int + # What the backend says of the plan after the write, for stderr, such as an item now under the bar. + notes: tuple[str, ...] = () + + +class PlanStore(typing.Protocol): + """A project's plan. plan_store.contract holds every backend that writes to the same behaviour; `jira_epic` doesn't hold it yet: it changes no link, and its own tests stand in for Jira. A write that fails leaves the plan as it was, except where its Failure says the tracker may have taken the write all the same, as when Jira's answer to a new issue, an edit or a finish is lost.""" + + @property + def label(self) -> str: + """What a message calls the plan, such as its path.""" + + @property + def tracked(self) -> str | None: + """The plan's path from the checkout's top, as git names a file in a commit; None where no commit holds a version of it, as for a file outside the checkout or a tracker.""" + + def read(self) -> Plan | Failure: + """The plan as it stands. A NoItemsTable where the project has not set one up.""" + + def add(self, fields: dict[str, str], detail: str) -> Written | Failure: + """Files an item under an ID the backend picks. fields holds each of FIELDS the caller sets; detail may be empty.""" + + def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure: + """Sets item id_'s fields to those given, and its detail unless None, leaving the rest. Moving an item sets its Release. + + comment tells the plan's other readers why, in the project's language. A tracker posts it on the item's issue; a backend with no place for comments drops it.""" + + def finish(self, id_: int) -> Written | Failure: + """Removes item id_ with its detail.""" + + +def no_item(label: str, id_: int | str) -> str: + """What every store says of an item id_ that the plan label names doesn't hold. `chunk-pr merge` reads `todo-item show`'s answer by it, through says_no_item.""" + return f"{label} holds no item {id_}" + + +def says_no_item(reason: str, id_: int | str) -> bool: + """Whether a failure's reason, such as `todo-item show`'s, says the plan doesn't hold item id_, as no_item words it.""" + return no_item("", id_) in reason + + +def cells(fields: dict[str, str]) -> dict[str, str]: + """fields by the items table's column names.""" + unknown = set(fields) - set(FIELDS) + if unknown: + # A programming error, so nothing catches it: a caller takes its fields from FIELDS. + raise ValueError(f"{', '.join(sorted(unknown))}: not a field; the fields are {', '.join(FIELDS)}") + return {"Item" if name == TAGLINE else name: value for name, value in fields.items()} diff --git a/bin/plan_store/scoring.py b/bin/plan_store/scoring.py new file mode 100644 index 00000000..f6db0056 --- /dev/null +++ b/bin/plan_store/scoring.py @@ -0,0 +1,39 @@ +"""The goal weights a plan is ranked by, read from the goals file, the decision log and the comprehension history, for the markdown plan and for the scoring of a plan in Jira.""" +import dataclasses +import decimal + +from failure import Failure +from project_config.settings import JiraScoring +from plan import ranking +from record_store.stores import RecordStore + +# What the reader of a missing or empty goals file is told. +GOALS_HINT = "rank_todo.py weighs goals from the goals file the project's config names as goals-and-audience" + + +@dataclasses.dataclass(frozen=True) +class StatedScoring: + """The scoring of a plan in Jira: the formula and bar the project's config states, with goal weights that ranking reads from the goals file, the decision log and the comprehension history.""" + stated: JiraScoring + goals: RecordStore + decisions: RecordStore + history: RecordStore + floor: decimal.Decimal + + def read(self) -> ranking.Scoring | Failure: + weighing = weighing_texts(self.goals, self.decisions, self.history) + return weighing if isinstance(weighing, Failure) else ranking.config_scoring(self.stated.formula, self.stated.bar, *weighing, self.floor) + + +def weighing_texts(goals: RecordStore, decisions: RecordStore, history: RecordStore) -> tuple[str, str, str] | Failure: + """What ranking weighs the goals by: the goals file, the decision log and the comprehension history. The last two are empty when missing; a goals file that is missing or empty is a Failure.""" + goals_text = goals.read() + if isinstance(goals_text, Failure): + return goals_text + if not goals_text: + return Failure(f"{goals.label}: missing or empty; {GOALS_HINT}") + decisions_text = decisions.read() + if isinstance(decisions_text, Failure): + return decisions_text + history_text = history.read() + return history_text if isinstance(history_text, Failure) else (goals_text, decisions_text, history_text) diff --git a/bin/plan_store/stores.py b/bin/plan_store/stores.py index e1d08846..f4bcee17 100644 --- a/bin/plan_store/stores.py +++ b/bin/plan_store/stores.py @@ -1,182 +1,24 @@ """The one way a tool reads or writes a project's plan: through the store its config names. -The config's `plan` setting names the backend. A path names a markdown file, todo.md. `jira:` and an epic's address name a Jira epic, whose open child issues are the plan: `jira_epic` reads them, and files an item as a new child issue. An agent reads and changes the plan with `todo-item`, which works through the same store. +The config's `plan` setting names the backend. A path names a markdown file, todo.md, which `todo_md` keeps. `jira:` and an epic's address name a Jira epic, whose open child issues are the plan: `jira_epic` reads them, and files an item as a new child issue. An agent reads and changes the plan with `todo-item`, which works through the same store. -A tool that reads what a past commit held, such as `score-outcomes`, still parses that commit's todo.md itself, with `release_plan.todo_table`: only the markdown backend has commits, and todo.md's items 365, 366 and 368 port those tools to the other backends.""" -import dataclasses -import decimal +A tool that reads what a past commit held, such as `score-outcomes`, still parses that commit's todo.md itself, with `plan.todo_table`: only the markdown backend has commits, and todo.md's items 365, 366 and 368 port those tools to the other backends.""" import pathlib -import typing -from release_plan.todo_table import BLOCKED_BY, Item, item_details, items, MOVES, NoItemsTable, renames from failure import Failure from git_cli.git_repo import file_at, git, Git -from record_store.stores import goals_store, store as record_store, RecordStore -from project_config.settings import JiraScoring, ProjectConfig -from plan_store import markdown_edits -from release_plan import ranking -from release_plan.release import Release -from text_files.file_writes import replace_file - -TAGLINE = "Tagline" -# What a caller may set on an item, each as text in the format `rank_todo.py --help` states for the cell of that name. TAGLINE is the Item cell, bold or not. -FIELDS = ("Release", BLOCKED_BY, "Exempt", TAGLINE, "L", "E", "I", "S", MOVES) - - -# What the reader of a missing todo.md is told. -MISSING = "every project keeps a todo.md, and rank_todo.py --help shows one" -# What the reader of a missing or empty goals file is told. -GOALS_HINT = "rank_todo.py weighs goals from the goals file the project's config names as goals-and-audience" - - -@dataclasses.dataclass(frozen=True) -class Plan: - """A plan as one read found it.""" - # Each item with its detail, in the order the backend supplies: by release and then by rank for a markdown file, by backlog rank for a tracker. - items: list[Item] - # The releases the plan marks renamed. Such a release holds no item because its items moved, not because it is finished. - renamed: frozenset[Release] = frozenset() - - -@dataclasses.dataclass(frozen=True) -class Written: - """A write that landed.""" - id: int - # What the backend says of the plan after the write, for stderr, such as an item now under the bar. - notes: tuple[str, ...] = () - - -class PlanStore(typing.Protocol): - """A project's plan. plan_store.contract holds every backend that writes to the same behaviour; `jira_epic` doesn't hold it yet: it changes no link, and its own tests stand in for Jira. A write that fails leaves the plan as it was, except where its Failure says the tracker may have taken the write all the same, as when Jira's answer to a new issue, an edit or a finish is lost.""" - - @property - def label(self) -> str: - """What a message calls the plan, such as its path.""" - - @property - def tracked(self) -> str | None: - """The plan's path from the checkout's top, as git names a file in a commit; None where no commit holds a version of it, as for a file outside the checkout or a tracker.""" - - def read(self) -> Plan | Failure: - """The plan as it stands. A NoItemsTable where the project has not set one up.""" - - def add(self, fields: dict[str, str], detail: str) -> Written | Failure: - """Files an item under an ID the backend picks. fields holds each of FIELDS the caller sets; detail may be empty.""" - - def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure: - """Sets item id_'s fields to those given, and its detail unless None, leaving the rest. Moving an item sets its Release. - - comment tells the plan's other readers why, in the project's language. A tracker posts it on the item's issue; a backend with no place for comments drops it.""" - - def finish(self, id_: int) -> Written | Failure: - """Removes item id_ with its detail.""" - - -@dataclasses.dataclass(frozen=True) -class FilePlan: - """A plan kept as a markdown file at path, in the shape `rank_todo.py --help` shows. Every write ranks the file, reading the goals file from goals, the decision log and the comprehension history.""" - path: pathlib.Path - tracked: str | None - goals: RecordStore - decisions: RecordStore - history: RecordStore - # The project's readability floor: while the comprehension overall is under it, ranking weighs code health 4 times as much. - floor: decimal.Decimal - - @property - def label(self) -> str: - return str(self.path) - - def read(self) -> Plan | Failure: - if not self.path.exists(): - return NoItemsTable(f"{self.path}: not found; {MISSING}") - text = read_text(self.path, MISSING) - return text if isinstance(text, Failure) else plan_of(text) - - def add(self, fields: dict[str, str], detail: str) -> Written | Failure: - texts = self.texts() - if isinstance(texts, Failure): - return texts - filed = markdown_edits.added(texts[0], cells(fields), detail, self.label) - return filed if isinstance(filed, Failure) else self.kept(*filed, texts) - - def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure: - texts = self.texts() - if isinstance(texts, Failure): - return texts - text = markdown_edits.edited(texts[0], id_, cells(fields), detail, self.label) - return text if isinstance(text, Failure) else self.kept(id_, text, texts) - - def kept(self, id_: int, text: str, texts: tuple[str, str, str, str]) -> Written | Failure: - """Ranks text, the file with item id_ filed or edited, and writes it where the item scores at the bar or above.""" - ranked = ranking.rank(text, *texts[1:], self.floor) - if isinstance(ranked, Failure): - return ranked - # The write may lower another item under the bar, which the notes then say; the write is refused only where the written item itself scores under the bar. - if under := [line for line in ranked.under_bar if line.startswith(f"item {id_} ")]: - return Failure(under[0]) - return self.written(id_, ranked) - - def finish(self, id_: int) -> Written | Failure: - texts = self.texts() - if isinstance(texts, Failure): - return texts - text = markdown_edits.finished(texts[0], id_, self.label) - if isinstance(text, Failure): - return text - ranked = ranking.rank(text, *texts[1:], self.floor) - return ranked if isinstance(ranked, Failure) else self.written(id_, ranked) - - def written(self, id_: int, ranked: ranking.Ranked) -> Written | Failure: - """Writes ranked's text to the file.""" - unwritten = replace_file(self.path.resolve(), ranked.text.encode("utf-8")) - if unwritten: - return Failure(f"{self.path}: {unwritten.reason}") - return Written(id_, tuple(f"{self.path}: {line}" for line in ranked.notes + ranked.under_bar)) - - def texts(self) -> tuple[str, str, str, str] | Failure: - """What ranking reads: the file, the goals file, the decision log and the comprehension history. The last two are empty when missing; a missing plan, or a goals file that is missing or empty, is a Failure.""" - plan = read_text(self.path, MISSING) - if isinstance(plan, Failure): - return plan - weighing = weighing_texts(self.goals, self.decisions, self.history) - return weighing if isinstance(weighing, Failure) else (plan, *weighing) - - -@dataclasses.dataclass(frozen=True) -class StatedScoring: - """The scoring of a plan in Jira: the formula and bar the project's config states, with goal weights that ranking reads from the goals file, the decision log and the comprehension history.""" - stated: JiraScoring - goals: RecordStore - decisions: RecordStore - history: RecordStore - floor: decimal.Decimal - - def read(self) -> ranking.Scoring | Failure: - weighing = weighing_texts(self.goals, self.decisions, self.history) - return weighing if isinstance(weighing, Failure) else ranking.config_scoring(self.stated.formula, self.stated.bar, *weighing, self.floor) - - -def weighing_texts(goals: RecordStore, decisions: RecordStore, history: RecordStore) -> tuple[str, str, str] | Failure: - """What ranking weighs the goals by: the goals file, the decision log and the comprehension history. The last two are empty when missing; a goals file that is missing or empty is a Failure.""" - goals_text = goals.read() - if isinstance(goals_text, Failure): - return goals_text - if not goals_text: - return Failure(f"{goals.label}: missing or empty; {GOALS_HINT}") - decisions_text = decisions.read() - if isinstance(decisions_text, Failure): - return decisions_text - history_text = history.read() - return history_text if isinstance(history_text, Failure) else (goals_text, decisions_text, history_text) +from plan_store.todo_md import FilePlan, plan_of +from record_store.stores import goals_store, store as record_store +from plan_store.jira_epic import JiraPlan +from plan_store.plans import Plan, PlanStore +from project_config.settings import ProjectConfig +from plan_store.scoring import StatedScoring def store(config: ProjectConfig) -> PlanStore: """The store config names for the plan.""" if config.epic is None: return file_plan(config) - # Imported here, since jira_epic builds on this module's Plan and Written. - from plan_store.jira_epic import JiraPlan # load refuses a config that names an epic and no env-file. assert config.env_file is not None # load refuses a config that names an epic and no formula or bar. @@ -196,38 +38,3 @@ def held_at(revision: str, plan: PlanStore, cwd: str, run: Git = git) -> Plan | return plan.read() text = file_at(revision, plan.tracked, cwd, run) return text if isinstance(text, Failure) else plan_of(text) - - -def plan_of(todo: str) -> Plan | Failure: - """The plan a todo.md's text holds.""" - found = items(todo) - if isinstance(found, Failure): - return found - details = item_details(todo) - if isinstance(details, Failure): - return details - marked = renames(todo) - if isinstance(marked, Failure): - return marked - return Plan([dataclasses.replace(item, detail=details.get(item.id, "")) for item in found], frozenset(marked)) - - -def cells(fields: dict[str, str]) -> dict[str, str]: - """fields by the items table's column names.""" - unknown = set(fields) - set(FIELDS) - if unknown: - # A programming error, so nothing catches it: a caller takes its fields from FIELDS. - raise ValueError(f"{', '.join(sorted(unknown))}: not a field; the fields are {', '.join(FIELDS)}") - return {"Item" if name == TAGLINE else name: value for name, value in fields.items()} - - -def read_text(path: pathlib.Path, missing: str) -> str | Failure: - """path's text; where it is missing, a Failure saying missing.""" - try: - return path.read_text(encoding="utf-8") - except FileNotFoundError: - return Failure(f"{path}: not found; {missing}") - except OSError as failure: - return Failure(f"{path}: {failure.strerror}") - except UnicodeDecodeError: - return Failure(f"{path}: not UTF-8") diff --git a/bin/plan_store/test_jira_epic.py b/bin/plan_store/test_jira_epic.py index bbd2ab70..66878e0f 100644 --- a/bin/plan_store/test_jira_epic.py +++ b/bin/plan_store/test_jira_epic.py @@ -9,13 +9,13 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from project_config.settings import DEFAULT_FLOOR, Epic, Finish -from release_plan.todo_table import EXEMPTIONS +from plan.todo_table import EXEMPTIONS from failure import Failure from plan_store import jira_epic -from plan_store.stores import Plan, Written -from release_plan import ranking +from plan_store.plans import Plan, Written +from plan import ranking from adf_codec.convert import Refused -from release_plan.release import release_of +from plan.release import release_of EPIC = Epic("https://acme.atlassian.net", "ABC-12") SEARCH = "https://acme.atlassian.net/rest/api/3/search/jql" @@ -144,7 +144,7 @@ class JiraPlan(unittest.TestCase): self.assertIn("ABC-34", failure.reason) # type: ignore[union-attr] def test_an_exempt_out_of_format_fails_naming_the_reasons_it_may_hold(self): - self.assertEqual(self.read(issue("ABC-34", scores={"Exempt": "because"})), Failure("ABC-34's issue property plan-item holds the Exempt 'because', which is not empty or one of decision, defect, owner, principle, question, security")) + self.assertEqual(self.read(issue("ABC-34", scores={"Exempt": "because"})), Failure("item ABC-34's Exempt 'because' is not empty or one of decision, defect, owner, principle, question, security; ABC-34 holds it in its issue property plan-item")) def test_reads_every_page(self): self.pages = [{"issues": [issue("ABC-1")], "nextPageToken": "t1"}, {"issues": [issue("ABC-2")]}] @@ -315,9 +315,9 @@ class Filing(unittest.TestCase): def test_each_field_out_of_format_fails_saying_how(self): cases = ( ({"Tagline": "** **"}, "the item has no tagline"), - ({"L": "9"}, "item to file's L '9' is not a whole number from 1 to 4"), - ({"Exempt": "whim"}, f"the item's Exempt 'whim' is not empty or one of {', '.join(EXEMPTIONS[1:])}"), - ({"Blocked by": "ABC-34"}, "the item's Blocked by 'ABC-34' is not empty or IDs separated by \", \""), + ({"L": "9"}, "the item to file's L '9' is not a whole number from 1 to 4"), + ({"Exempt": "whim"}, f"the item to file's Exempt 'whim' is not empty or one of {', '.join(EXEMPTIONS[1:])}"), + ({"Blocked by": "ABC-34"}, "the item to file's Blocked by 'ABC-34' is not empty or IDs separated by \", \""), ) for change, reason in cases: with self.subTest(change=change): @@ -334,7 +334,7 @@ class Filing(unittest.TestCase): self.add(FIELDS | {"Colour": "red"}) def test_an_item_without_a_release_fails_naming_the_field(self): - self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Release"}), Failure("the item's Release '' is not a version such as 1.2.0")) + self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Release"}), Failure("the item to file's Release '' is not a semver version, such as 1.2.0")) def test_a_detail_that_does_not_convert_fails_before_any_request(self): self.to_adf = lambda markdown: Failure("docker is not running") # type: ignore[method-assign] @@ -460,7 +460,7 @@ class Filing(unittest.TestCase): for open_, reason in ( (filed("ABC-34", moves="3 by 1", s=2), "ABC-34 cites goal 3, which the goals file's ## Goals does not number"), (issue("ABC-34", scores=unscored), "ABC-34 holds no S"), - (issue("ABC-34", scores=PROPERTY | {"L": 11}), "item ABC-34's L '11' is not a whole number from 1 to 4"), + (issue("ABC-34", scores=PROPERTY | {"L": 11}), "item ABC-34's L '11' is not a whole number from 1 to 4; ABC-34 holds it in its issue property plan-item"), ): with self.subTest(reason=reason): self.calls.clear() @@ -597,8 +597,8 @@ class Editing(unittest.TestCase): for fields, detail, reason in ( ({"L": "9"}, None, "item ABC-34's L '9' is not a whole number from 1 to 4"), ({"Moves": "much"}, None, "item ABC-34's Moves 'much' is not"), - ({"Exempt": "tired"}, None, f"the item's Exempt 'tired' is not empty or one of {', '.join(EXEMPTIONS[1:])}"), - ({"Release": "soon"}, None, "the item's Release 'soon' is not a version such as 1.2.0"), + ({"Exempt": "tired"}, None, f"item ABC-34's Exempt 'tired' is not empty or one of {', '.join(EXEMPTIONS[1:])}"), + ({"Release": "soon"}, None, "item ABC-34's Release 'soon' is not a semver version, such as 1.2.0"), ({"Tagline": " "}, None, "the item has no tagline"), ({"Tagline": "Count\nruns."}, None, "the tagline holds a line break; keep it on one line"), ({}, "## Why", "the detail holds a ## or ### heading"), @@ -724,24 +724,6 @@ class Finishing(unittest.TestCase): self.assertEqual(self.calls, []) -class Requests(unittest.TestCase): - def test_sends_each_request_through_the_shared_client_with_jiras_error_messages(self): - with unittest.mock.patch.object(jira_epic.json_request, "http_json", return_value={"issues": []}) as sent: - self.assertEqual(jira_epic.http_json("POST", SEARCH, AUTHORIZATION, {"jql": "x"}), {"issues": []}) - sent.assert_called_once_with("POST", SEARCH, AUTHORIZATION, {"jql": "x"}, 30, jira_epic.error_message) - - def test_reads_jiras_messages_from_an_error_answer(self): - cases = ( - ({"errorMessages": ["Issue does not exist or you do not have permission to see it."], "errors": {}}, "Issue does not exist or you do not have permission to see it."), - ({"errorMessages": ["One."], "errors": {"jql": "Two."}}, "One.; Two."), - ({"errorMessages": "One.", "errors": ["Two."]}, ""), - ({"errorMessages": [7, "One."]}, "One."), - (["One."], ""), - ) - for answer, message in cases: - with self.subTest(answer=answer): - self.assertEqual(jira_epic.error_message(answer), message) - if __name__ == "__main__": unittest.main() diff --git a/bin/plan_store/test_stores.py b/bin/plan_store/test_stores.py index bf31cd24..755d6c9e 100644 --- a/bin/plan_store/test_stores.py +++ b/bin/plan_store/test_stores.py @@ -15,16 +15,16 @@ from plan_store.contract import FIRST, MOVES, PlanStoreContract, SECOND from plan_store.jira_epic import JiraPlan from plan_store.fakes import MemoryPlan from record_store.fakes import MemoryStore -from release_plan.todo_table import NoItemsTable -from release_plan.test_ranking import README, SCORED, VOID -from release_plan.release import release_of -from plan_store import stores +from plan.todo_table import NoItemsTable +from plan_store import plans, scoring, stores, todo_md +from plan.test_ranking import README, SCORED, VOID +from plan.release import release_of EMPTY = "# todo\n\n## Scoring\n\n`Score = 100 * V / 2**S`\n\n`Bar = 2`\n\n`Next ID = 1`\n\n## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n" class MemoryPlanContract(PlanStoreContract, unittest.TestCase): - def new_store(self) -> stores.PlanStore: + def new_store(self) -> plans.PlanStore: return MemoryPlan() @@ -32,10 +32,10 @@ class FilePlanContract(PlanStoreContract, unittest.TestCase): def setUp(self) -> None: self.folder = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) - def new_store(self) -> stores.FilePlan: + def new_store(self) -> todo_md.FilePlan: (self.folder / "todo.md").write_text(EMPTY) (self.folder / "README.md").write_text(README) - return stores.FilePlan(self.folder / "todo.md", "todo.md", FileStore(self.folder / "README.md", None), MemoryStore(), MemoryStore(), DEFAULT_FLOOR) + return todo_md.FilePlan(self.folder / "todo.md", "todo.md", FileStore(self.folder / "README.md", None), MemoryStore(), MemoryStore(), DEFAULT_FLOOR) class FilePlan(FilePlanContract): @@ -62,7 +62,7 @@ class FilePlan(FilePlanContract): def test_an_edited_tagline_heads_the_detail_too(self): store = self.new_store() id_ = self.filed(store, FIRST, "Why it counts.") - store.edit(id_, {stores.TAGLINE: "Count `a | b` runs."}, None) + store.edit(id_, {plans.TAGLINE: "Count `a | b` runs."}, None) text = (self.folder / "todo.md").read_text() self.assertIn("| **Count `a \\| b` runs.** |", text) self.assertIn(f"### {id_}. Count `a | b` runs.\n\nWhy it counts.\n", text) @@ -84,7 +84,7 @@ class FilePlan(FilePlanContract): self.assertEqual(self.filed(store, FIRST), 10) todo.write_text("".join(line.replace("| 4 | 1 | 1 by 9 |", "| 4 | 10 | 1 by 9 |") if line.startswith("| 10 ") else line for line in todo.read_text().splitlines(keepends=True))) written = store.edit(first, {"E": "2"}, None) - assert isinstance(written, stores.Written), written + assert isinstance(written, plans.Written), written self.assertIn("item 10 ", written.notes[0]) def test_an_id_it_holds_no_item_for_fails_naming_the_file(self): @@ -118,7 +118,7 @@ class FilePlan(FilePlanContract): def test_reads_the_releases_marked_renamed(self): store = self.new_store() (self.folder / "todo.md").write_text(EMPTY + "\n## Renamed\n\n- 0.2.1 renamed to 0.3.0\n") - self.assertEqual(store.read(), stores.Plan([], frozenset({release_of("0.2.1")}))) + self.assertEqual(store.read(), plans.Plan([], frozenset({release_of("0.2.1")}))) def test_a_field_it_does_not_know_is_a_programming_error(self): with self.assertRaises(ValueError): @@ -130,9 +130,9 @@ class FilePlan(FilePlanContract): id_ = self.filed(store, FIRST) before = (self.folder / "todo.md").read_text() broken, split = "the tagline holds a line break; keep it on one line", "the detail holds a ## or ### heading, which would split ## Details; use #### or drop the #s" - self.assertEqual(store.add(FIRST | {stores.TAGLINE: "Count\nthe runs."}, ""), Failure(broken)) + self.assertEqual(store.add(FIRST | {plans.TAGLINE: "Count\nthe runs."}, ""), Failure(broken)) self.assertEqual(store.add(FIRST, "## Why\n"), Failure(split)) - self.assertEqual(store.edit(id_, {stores.TAGLINE: "Count\nthe runs."}, None), Failure(broken)) + self.assertEqual(store.edit(id_, {plans.TAGLINE: "Count\nthe runs."}, None), Failure(broken)) self.assertEqual(store.edit(id_, {}, "### Why\n"), Failure(split)) self.assertEqual((self.folder / "todo.md").read_text(), before) @@ -157,7 +157,7 @@ class FilePlan(FilePlanContract): (self.folder / "README.md").write_text(README.replace(VOID, "")) kept, finished = self.filed(store, FIRST | {MOVES: "code health by 1"}), self.filed(store, SECOND) row = [line for line in (self.folder / "todo.md").read_text().splitlines() if line.startswith(f"| {kept} ")] - self.assertIsInstance(store.finish(finished), stores.Written) + self.assertIsInstance(store.finish(finished), plans.Written) self.assertIn(row[0], (self.folder / "todo.md").read_text()) return row[0] self.assertNotEqual(health_row("6.0"), health_row("7.0")) @@ -200,7 +200,7 @@ class Store(unittest.TestCase): def test_a_path_picks_the_markdown_file(self): config = self.config() picked = stores.store(dataclasses.replace(config, paths=config.paths | {"plan": pathlib.Path("/checkout/todo.md")})) - self.assertEqual((type(picked), picked.label, picked.tracked), (stores.FilePlan, "/checkout/todo.md", "todo.md")) + self.assertEqual((type(picked), picked.label, picked.tracked), (todo_md.FilePlan, "/checkout/todo.md", "todo.md")) def test_the_markdown_file_ranks_with_the_configs_floor(self): self.assertEqual(stores.file_plan(self.config(readability_floor=decimal.Decimal("6.5")), pathlib.Path("/checkout/todo.md")).floor, decimal.Decimal("6.5")) @@ -218,26 +218,26 @@ class Store(unittest.TestCase): def test_an_epic_scores_by_the_configs_formula_and_bar_and_the_projects_records(self): config = self.config(epic=Epic("https://acme.atlassian.net", "ABC-12"), env_file=pathlib.Path("/secrets/acme.env"), jira_scoring=JiraScoring("V / 2**S", 1.5), readability_floor=decimal.Decimal("6.5")) picked = stores.store(config) - self.assertEqual(picked.scoring, stores.StatedScoring(JiraScoring("V / 2**S", 1.5), goals_store(config), record_store(config, "decisions"), record_store(config, "comprehension-history"), decimal.Decimal("6.5"))) + self.assertEqual(picked.scoring, scoring.StatedScoring(JiraScoring("V / 2**S", 1.5), goals_store(config), record_store(config, "decisions"), record_store(config, "comprehension-history"), decimal.Decimal("6.5"))) class StatedScoring(unittest.TestCase): def test_weighs_the_goals_the_goals_file_holds(self): - scoring = stores.StatedScoring(JiraScoring("V / 2**S", 1.5), MemoryStore(README), MemoryStore(), MemoryStore(), DEFAULT_FLOOR).read() - assert not isinstance(scoring, Failure), scoring - self.assertEqual((scoring.bar, list(scoring.goals)), (1.5, ["1", "2", "2.1"])) + weighed = scoring.StatedScoring(JiraScoring("V / 2**S", 1.5), MemoryStore(README), MemoryStore(), MemoryStore(), DEFAULT_FLOOR).read() + assert not isinstance(weighed, Failure), weighed + self.assertEqual((weighed.bar, list(weighed.goals)), (1.5, ["1", "2", "2.1"])) def test_weighs_code_health_by_the_history_and_the_floor_it_is_given(self): for floor, under in ((DEFAULT_FLOOR, True), (decimal.Decimal("6.0"), False)): with self.subTest(floor=floor): - scoring = stores.StatedScoring(JiraScoring("V", 1), MemoryStore("## Goals\n\n1. **Achieve:** A.\n"), MemoryStore(), MemoryStore(SCORED.format(overall="6.99")), floor).read() - assert not isinstance(scoring, Failure), scoring - self.assertEqual(scoring.weights["code health"] > scoring.weights["1"] * 2, under) + weighed = scoring.StatedScoring(JiraScoring("V", 1), MemoryStore("## Goals\n\n1. **Achieve:** A.\n"), MemoryStore(), MemoryStore(SCORED.format(overall="6.99")), floor).read() + assert not isinstance(weighed, Failure), weighed + self.assertEqual(weighed.weights["code health"] > weighed.weights["1"] * 2, under) def test_a_goals_file_that_is_empty_or_cannot_be_read_fails(self): for goals, reason in ((MemoryStore(), "the record in memory: missing or empty"), (MemoryStore(fails="Jira answered 403"), "Jira answered 403")): with self.subTest(reason=reason): - read = stores.StatedScoring(JiraScoring("V", 1), goals, MemoryStore(), MemoryStore(), DEFAULT_FLOOR).read() + read = scoring.StatedScoring(JiraScoring("V", 1), goals, MemoryStore(), MemoryStore(), DEFAULT_FLOOR).read() assert isinstance(read, Failure), read self.assertTrue(read.reason.startswith(reason), read.reason) diff --git a/bin/plan_store/todo_md.py b/bin/plan_store/todo_md.py new file mode 100644 index 00000000..63692370 --- /dev/null +++ b/bin/plan_store/todo_md.py @@ -0,0 +1,141 @@ +"""A plan kept as a markdown file, todo.md, in the shape `rank_todo.py --help` shows: read, filed into, edited, finished, and ranked or checked in place.""" +import dataclasses +import decimal +import pathlib + +from plan_store.plans import cells, Plan, Written +from failure import Failure +from plan.todo_table import item_details, items, NoItemsTable, renames +from plan_store import markdown_edits +from plan import ranking +from record_store.stores import RecordStore +from text_files.file_writes import replace_file +from plan_store.scoring import weighing_texts + +# What the reader of a missing todo.md is told. +MISSING = "every project keeps a todo.md, and rank_todo.py --help shows one" + + +@dataclasses.dataclass(frozen=True) +class FilePlan: + """A plan kept as a markdown file at path. Every write ranks the file, reading the goals file from goals, the decision log and the comprehension history.""" + path: pathlib.Path + tracked: str | None + goals: RecordStore + decisions: RecordStore + history: RecordStore + # The project's readability floor: while the comprehension overall is under it, ranking weighs code health 4 times as much. + floor: decimal.Decimal + + @property + def label(self) -> str: + return str(self.path) + + def read(self) -> Plan | Failure: + if not self.path.exists(): + return NoItemsTable(f"{self.path}: not found; {MISSING}") + text = read_text(self.path, MISSING) + return text if isinstance(text, Failure) else plan_of(text) + + def add(self, fields: dict[str, str], detail: str) -> Written | Failure: + texts = self.texts() + if isinstance(texts, Failure): + return texts + filed = markdown_edits.added(texts[0], cells(fields), detail, self.label) + return filed if isinstance(filed, Failure) else self.kept(*filed, texts) + + def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure: + texts = self.texts() + if isinstance(texts, Failure): + return texts + text = markdown_edits.edited(texts[0], id_, cells(fields), detail, self.label) + return text if isinstance(text, Failure) else self.kept(id_, text, texts) + + def kept(self, id_: int, text: str, texts: tuple[str, str, str, str]) -> Written | Failure: + """Ranks text, the file with item id_ filed or edited, and writes it where the item scores at the bar or above.""" + ranked = ranking.rank(text, *texts[1:], self.floor) + if isinstance(ranked, Failure): + return ranked + # The write may lower another item under the bar, which the notes then say; the write is refused only where the written item itself scores under the bar. + if under := [line for line in ranked.under_bar if line.startswith(f"item {id_} ")]: + return Failure(under[0]) + return self.written(id_, ranked) + + def finish(self, id_: int) -> Written | Failure: + texts = self.texts() + if isinstance(texts, Failure): + return texts + text = markdown_edits.finished(texts[0], id_, self.label) + if isinstance(text, Failure): + return text + ranked = ranking.rank(text, *texts[1:], self.floor) + return ranked if isinstance(ranked, Failure) else self.written(id_, ranked) + + def rank(self) -> ranking.Ranked | Failure: + """Ranks the file in place, writing it where ranking changed it. The caller prints `reported`'s lines.""" + texts = self.texts() + if isinstance(texts, Failure): + return texts + ranked = ranking.rank(*texts, self.floor) + if isinstance(ranked, Failure): + return ranked + if ranked.text != texts[0] and (unwritten := self.replaced(ranked.text)): + return unwritten + return ranked + + def check(self) -> list[str]: + """Why `rank_todo.py --check` fails on the file, empty when it passes: the file is not ranked, or an item scores under the bar.""" + texts = self.texts() + if isinstance(texts, Failure): + return [texts.reason] + ranked = ranking.rank(*texts, self.floor) + if isinstance(ranked, Failure): + return [ranked.reason] + unranked = [] if ranked.text == texts[0] else [f"{self.path}: not ranked; run rank_todo.py on it"] + return unranked + [f"{self.path}: {line}" for line in ranked.under_bar] + + def reported(self, ranked: ranking.Ranked) -> list[str]: + """Ranking's notes and under-bar lines, each prefixed with the file's path, as a tool prints them on stderr.""" + return [f"{self.path}: {line}" for line in ranked.notes + ranked.under_bar] + + def written(self, id_: int, ranked: ranking.Ranked) -> Written | Failure: + """Writes ranked's text to the file.""" + return self.replaced(ranked.text) or Written(id_, tuple(self.reported(ranked))) + + def replaced(self, text: str) -> Failure | None: + unwritten = replace_file(self.path.resolve(), text.encode("utf-8")) + return Failure(f"{self.path}: {unwritten.reason}") if unwritten else None + + def texts(self) -> tuple[str, str, str, str] | Failure: + """What ranking reads: the file, the goals file, the decision log and the comprehension history. The last two are empty when missing; a missing plan, or a goals file that is missing or empty, is a Failure.""" + plan = read_text(self.path, MISSING) + if isinstance(plan, Failure): + return plan + weighing = weighing_texts(self.goals, self.decisions, self.history) + return weighing if isinstance(weighing, Failure) else (plan, *weighing) + + +def plan_of(todo: str) -> Plan | Failure: + """The plan a todo.md's text holds.""" + found = items(todo) + if isinstance(found, Failure): + return found + details = item_details(todo) + if isinstance(details, Failure): + return details + marked = renames(todo) + if isinstance(marked, Failure): + return marked + return Plan([dataclasses.replace(item, detail=details.get(item.id, "")) for item in found], frozenset(marked)) + + +def read_text(path: pathlib.Path, missing: str) -> str | Failure: + """path's text; where it is missing, a Failure saying missing.""" + try: + return path.read_text(encoding="utf-8") + except FileNotFoundError: + return Failure(f"{path}: not found; {missing}") + except OSError as failure: + return Failure(f"{path}: {failure.strerror}") + except UnicodeDecodeError: + return Failure(f"{path}: not UTF-8") diff --git a/bin/project_config/main.py b/bin/project_config/main.py index f5e35141..6b3e0120 100644 --- a/bin/project_config/main.py +++ b/bin/project_config/main.py @@ -140,7 +140,7 @@ from 1 to 10, or sets `parallel-chunks` to anything but a whole number of 1 or m import pathlib import sys -from project_config.settings import CONFIG, DEFAULT_FLOOR, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, JIRA_SCORE_BAR, JIRA_SCORE_FORMULA, load, NOTIFIER, OPTIONAL, PARALLEL_CHUNKS, ProjectConfig, READABILITY_FLOOR, SETTINGS, TOOLING_ON_HOST, Unnamed, WAIT_FOR_APPROVAL +from project_config.settings import CONFIG, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, JIRA_SCORE_BAR, JIRA_SCORE_FORMULA, load, OPTIONAL, ProjectConfig, SCALARS, SETTINGS, Unnamed from failure import Failure from git_cli.git_repo import git, Git from project_config import templates @@ -157,26 +157,17 @@ def main(argv: list[str]) -> int: if isinstance(config, Failure): print(config.reason, file=sys.stderr) return 1 - switches = {WAIT_FOR_APPROVAL: config.wait_for_approval, TOOLING_ON_HOST: config.tooling_on_host} - if argv and argv[0] in switches: - print("true" if switches[argv[0]] else "false") - return 0 - if argv == [READABILITY_FLOOR]: - print(config.readability_floor) - return 0 - if argv == [PARALLEL_CHUNKS]: - print(config.parallel_chunks) - return 0 - if argv and argv[0] in config.texts: - print(config.texts[argv[0]]) - return 0 - paths = {**config.places, **({ENV_FILE: str(config.env_file)} if config.env_file else {}), **({NOTIFIER: config.notifier} if config.notifier else {}), **({JIRA_SCORE_FORMULA: config.jira_scoring.formula, JIRA_SCORE_BAR: f"{config.jira_scoring.bar:g}"} if config.jira_scoring else {}), **({JIRA_FINISH_TRANSITION: config.jira_finish.transition, JIRA_FINISH_STATUS: config.jira_finish.status} if config.jira_finish else {})} - if argv and argv[0] not in paths: + # A one-value setting prints its value, its default where the config leaves it out; one without a default, as `notifier`, prints only where set. + scalars = {scalar.name: scalar.shown(value) for scalar in SCALARS if (value := getattr(config, scalar.field)) is not None} + paths = {**config.places, **({ENV_FILE: str(config.env_file)} if config.env_file else {}), **({JIRA_SCORE_FORMULA: config.jira_scoring.formula, JIRA_SCORE_BAR: f"{config.jira_scoring.bar:g}"} if config.jira_scoring else {}), **({JIRA_FINISH_TRANSITION: config.jira_finish.transition, JIRA_FINISH_STATUS: config.jira_finish.status} if config.jira_finish else {})} + shown = paths | scalars + if argv and argv[0] not in shown: print(f"{config.folder / CONFIG} sets no `{argv[0]}`", file=sys.stderr) return 1 - defaults = ProjectConfig(config.key, config.folder, config.top, {}).texts - listed = [f"{name}: {path}" for name, path in paths.items()] + [f"{name}: true" for name, on in switches.items() if on] + ([f"{READABILITY_FLOOR}: {config.readability_floor}"] if config.readability_floor != DEFAULT_FLOOR else []) + ([f"{PARALLEL_CHUNKS}: {config.parallel_chunks}"] if config.parallel_chunks != 1 else []) + [f"{name}: {text}" for name, text in config.texts.items() if text != defaults[name]] - print(paths[argv[0]] if argv else "\n".join(listed)) + # The listing leaves out each one-value setting at its default. + defaults = ProjectConfig(config.key, config.folder, config.top, {}) + listed = [*(f"{name}: {path}" for name, path in paths.items()), *(f"{scalar.name}: {scalars[scalar.name]}" for scalar in SCALARS if getattr(config, scalar.field) != getattr(defaults, scalar.field))] + print(shown[argv[0]] if argv else "\n".join(listed)) return 0 diff --git a/bin/project_config/settings.py b/bin/project_config/settings.py index 5948e4cf..dca9390c 100644 --- a/bin/project_config/settings.py +++ b/bin/project_config/settings.py @@ -10,10 +10,10 @@ import tomllib import typing from failure import Failure -from release_plan.formula import parse_formula -from release_plan.todo_table import SHAPE +from plan.formula import parse_formula +from plan.todo_table import SHAPE from project_config import templates -from release_plan.ranking import variables +from plan.ranking import variables PROJECTS = ".claude-projects" CONFIG = "config.toml" @@ -52,7 +52,8 @@ JIRA_FINISH = (JIRA_FINISH_TRANSITION, JIRA_FINISH_STATUS) JIRA_SCORE_FORMULA = "jira-score-formula" JIRA_SCORE_BAR = "jira-score-bar" JIRA_SCORE = (JIRA_SCORE_FORMULA, JIRA_SCORE_BAR) -OPTIONAL = (BRANCH, COMMIT_TITLE, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, JIRA_SCORE_BAR, JIRA_SCORE_FORMULA, LANGUAGE, NOTIFIER, PARALLEL_CHUNKS, PULL_REQUEST_TITLE, READABILITY_FLOOR, TOOLING_ON_HOST, TOUCH_PREDICTIONS, WAIT_FOR_APPROVAL) +# The settings allowed only where `plan` names a Jira epic. +JIRA_PLAN_ONLY = (*JIRA_FINISH, *JIRA_SCORE) # What opens a setting that names a Jira Cloud epic in place of a path: `jira:`, then the epic's address as the browser shows it. The settings below may name an epic; each reads its own part of it. JIRA = "jira:" EPIC_SPELLINGS = { @@ -193,48 +194,79 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo pages = {name: page for name in RECORDS if (page := page_of(values.get(name)))} env_file = anywhere(values.get(ENV_FILE), home) misplaced = ENV_FILE in values and (env_file is None or lies_in(env_file, top, main, file.parent)) - notifier = next((name for name in NOTIFIERS if name == values.get(NOTIFIER)), None) - waits = values.get(WAIT_FOR_APPROVAL, False) - on_host = values.get(TOOLING_ON_HOST, False) - floor = floor_of(values[READABILITY_FLOOR]) if READABILITY_FLOOR in values else DEFAULT_FLOOR - parallel = values.get(PARALLEL_CHUNKS, 1) + scalars = {scalar: scalar.read(values[scalar.name]) for scalar in SCALARS if scalar.name in values} finish = [name for setting in JIRA_FINISH if (name := name_of(values.get(setting)))] 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 - checks = {LANGUAGE: language_fault, COMMIT_TITLE: templates.title_fault, PULL_REQUEST_TITLE: templates.title_fault, BRANCH: templates.branch_fault} faults = [ *(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)), *(f"`{name}` is {values[name]!r}, not {SPELLING}" for name, path in paths.items() if path is None and name not in (*EPIC_SPELLINGS, *RECORDS)), *(f"`{name}` is {values[name]!r}, not {SPELLING}, or {EPIC_SPELLINGS[name]}" for name in EPIC_SPELLINGS if name in values and paths[name] is None and epics[name] is None), *(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 []), + # Each setting that reaches a service needs the file that holds its credentials. *(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 []), # rule-hook ranks a plan kept as a file before tool calls, inside the hook's time limit, which a read from Jira or Confluence mustn't hold up. *(["`goals-and-audience` names a Jira epic, so `plan` must name one too"] if epics["goals-and-audience"] and not epics["plan"] else []), *(f"`{name}` names a Confluence page, so `plan` must name a Jira epic" for name in RANKED if name in pages and not epics["plan"]), - *([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not {OUTSIDE}"] if misplaced else []), - *([f"`{NOTIFIER}` is {values[NOTIFIER]!r}, not {' or '.join(NOTIFIERS)}"] if NOTIFIER in values and values[NOTIFIER] not in NOTIFIERS else []), - *([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 []), + *(f"`{name}` is set, so `plan` must name a Jira epic" for name in JIRA_PLAN_ONLY if name in values and not epics["plan"]), + *(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), *(f"`{name}` is {values[name]!r}, not the name Jira shows, such as \"{example}\"" for name, example in zip(JIRA_FINISH, ("Mark as done", "Done")) if name in values and not name_of(values[name])), *(f"`{name}` is set, so `{other}` must be too" for name, other in (JIRA_FINISH, JIRA_FINISH[::-1]) if name in values and other not in values), - *(f"`{name}` is set, so `plan` must name a Jira epic" for name in JIRA_FINISH if name in values and not epics["plan"]), - *(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), - *(f"`{name}` is set, so `plan` must name a Jira epic" for name in JIRA_SCORE if name in values and not epics["plan"]), *([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 []), - *(f"`{name}` is {value!r}, not true or false" for name, value in ((WAIT_FOR_APPROVAL, waits), (TOOLING_ON_HOST, on_host)) if not isinstance(value, bool)), - *([f"`{READABILITY_FLOOR}` is {values[READABILITY_FLOOR]!r}, not a number from 1 to 10; write a bare number, such as `{READABILITY_FLOOR} = 7.0`"] if floor is None else []), - *([f"`{PARALLEL_CHUNKS}` is {parallel!r}, not a whole number of 1 or more, such as `{PARALLEL_CHUNKS} = 2`"] if type(parallel) is not int or parallel < 1 else []), - *(f"`{name}` is {values[name]!r}, {fault}" for name, check in checks.items() if name in values and (fault := check(values[name]))), ] if faults: return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}, and optionally {', '.join(OPTIONAL[:-1])} and {OPTIONAL[-1]}.") - # faults names a floor or a `parallel-chunks` value the config misspells, and a formula or bar a plan in Jira lacks or misspells. - assert floor is not None - assert isinstance(parallel, int) + # faults names a formula or bar a plan in Jira lacks or misspells. assert scoring is not None or not epics["plan"] - return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, waits is True, on_host is True, floor, parallel, **{name.replace("-", "_"): str(values[name]) for name in checks if name in values}, epic=epics["plan"], goals_epic=epics["goals-and-audience"], notifier=notifier, jira_finish=Finish(*finish) if finish else None, jira_scoring=scoring, pages=pages) + 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(*finish) if finish else None, jira_scoring=scoring, pages=pages) + return dataclasses.replace(defaulted, **{scalar.field: read for scalar, read in scalars.items()}) + + +@dataclasses.dataclass(frozen=True) +class Unfit: + """Why a setting's value doesn't fit it, as the end of the sentence "`<setting>` is <value>, <reason>".""" + reason: str + + +@dataclasses.dataclass(frozen=True) +class Scalar: + """An optional setting that holds one value, not a path: the ProjectConfig field it sets, whose default is its value where the config leaves it out, how its value is read, and how `project-config <name>` prints it.""" + name: str + field: str + # The value, or Unfit; typed Any, since each Scalar reads into its own field's type. + read: typing.Callable[[object], typing.Any] + shown: typing.Callable[[typing.Any], str] = str + + +def switch(value: object) -> bool | Unfit: + return value if isinstance(value, bool) else Unfit("not true or false") + + +def floor_read(value: object) -> decimal.Decimal | Unfit: + floor = floor_of(value) + return Unfit(f"not a number from 1 to 10; write a bare number, such as `{READABILITY_FLOOR} = 7.0`") if floor is None else floor + + +def parallel_read(value: object) -> int | Unfit: + return value if type(value) is int and value >= 1 else Unfit(f"not a whole number of 1 or more, such as `{PARALLEL_CHUNKS} = 2`") + + +def notifier_read(value: object) -> Notifier | Unfit: + return next((name for name in NOTIFIERS if name == value), None) or Unfit(f"not {' or '.join(NOTIFIERS)}") + + +def text_read(fault: typing.Callable[[object], str | None]) -> typing.Callable[[object], str | Unfit]: + """A text setting's reader, from the check that says why a value doesn't fit.""" + def read(value: object) -> str | Unfit: + found = fault(value) + return Unfit(found) if found else str(value) + return read def formula_fault(value: object) -> str | None: @@ -284,6 +316,21 @@ def language_fault(value: object) -> str | None: return None if named else 'not a language\'s English name in words of letters, such as "Swedish" or "Brazilian Portuguese"' +# Each one-value setting, in the order `project-config` lists them. +SCALARS = ( + Scalar(WAIT_FOR_APPROVAL, "wait_for_approval", switch, lambda on: "true" if on else "false"), + Scalar(TOOLING_ON_HOST, "tooling_on_host", switch, lambda on: "true" if on else "false"), + Scalar(READABILITY_FLOOR, "readability_floor", floor_read), + Scalar(PARALLEL_CHUNKS, "parallel_chunks", parallel_read), + Scalar(NOTIFIER, "notifier", notifier_read), + Scalar(LANGUAGE, "language", text_read(language_fault)), + Scalar(COMMIT_TITLE, "commit_title", text_read(templates.title_fault)), + Scalar(PULL_REQUEST_TITLE, "pull_request_title", text_read(templates.title_fault)), + Scalar(BRANCH, "branch", text_read(templates.branch_fault)), +) +OPTIONAL = tuple(sorted((ENV_FILE, TOUCH_PREDICTIONS, *JIRA_PLAN_ONLY, *(scalar.name for scalar in SCALARS)))) + + def lies_in(path: pathlib.Path, *places: pathlib.Path) -> bool: """Whether path lies in one of places. Both sides are resolved, so a symlink can't lead a path out of the place it names.""" return any(path.resolve().is_relative_to(place.resolve()) for place in places) diff --git a/bin/project_config/templates.py b/bin/project_config/templates.py index 34399b6d..8db21311 100644 --- a/bin/project_config/templates.py +++ b/bin/project_config/templates.py @@ -71,6 +71,16 @@ def fits(template: str, title: str) -> bool: return pattern(template).fullmatch(title) is not None +def misfits(template: str, branch_template: str, branch: str | None, title: str) -> bool: + """Whether title breaks template on branch, the checkout's branch or None where HEAD is detached. On a branch that fits branch_template, a plan item's, a title must fit template. Any other branch, such as a release review's, has no ID for {id}, so every title fits there (CLAUDE.md → "Git, commits, and PRs").""" + return branch is not None and branch_fits(branch_template, branch) and not fits(template, title.strip()) + + +def title_of(template: str, branch_template: str, branch: str, id_: str, summary: str) -> str: + """The title template makes of summary on branch, with id_ for {id}; summary alone on a branch that doesn't fit branch_template, as misfits allows.""" + return template.replace(ID, id_).replace(SUMMARY, summary) if branch_fits(branch_template, branch) else summary + + def summary_of(template: str, title: str) -> str: """title's summary. A title that doesn't fit template is its own summary, so a commit from before the config named the template reads as it always did.""" found = pattern(template).fullmatch(title) diff --git a/bin/project_record/main.py b/bin/project_record/main.py index b6754166..4690278d 100644 --- a/bin/project_record/main.py +++ b/bin/project_record/main.py @@ -21,8 +21,8 @@ as a file, there is nothing left to store, and save says so. Run it after every steps work wherever a project keeps the record. For a record kept on a Confluence page, save refuses where someone saved the page after open read -it, and the human decides what follows. The copy keeps the unsaved edit until open runs again and -writes the copy afresh. +it or after save last wrote it, and the human decides what follows. The copy keeps the unsaved edit +until open runs again and writes the copy afresh. Exit 2 on bad arguments, and 1, saying why, on any other failure. """ @@ -70,9 +70,9 @@ def performed(config: ProjectConfig, command: str, name: str, home: pathlib.Path def opened(config: ProjectConfig, name: str, home: pathlib.Path) -> tuple[RecordStore, pathlib.Path]: - """The store of the record called name, and the copy it gets where it isn't kept as a file. A store that keeps the version it read, for a later save, keeps it beside the copy.""" + """The store of the record called name, and the copy it gets where it isn't kept as a file.""" copy = home / COPIES / config.key / worktree_folder(config.top) / f"{name}.md" - return (goals_store(config) if name == GOALS else store(config, name, copy.with_suffix(".version"))), copy + return (goals_store(config) if name == GOALS else store(config, name)), copy def worktree_folder(top: pathlib.Path) -> str: diff --git a/bin/project_record/test_project_record.py b/bin/project_record/test_project_record.py index da07b45d..5a83f5fb 100644 --- a/bin/project_record/test_project_record.py +++ b/bin/project_record/test_project_record.py @@ -25,13 +25,12 @@ def worktree_config(top: str, **kept: Page) -> ProjectConfig: class Opened(unittest.TestCase): - def test_a_record_on_a_confluence_page_keeps_the_version_it_read_beside_its_copy(self): + def test_a_record_on_a_confluence_page_gets_a_copy_in_a_folder_of_its_worktree(self): page = Page("https://acme.atlassian.net", "2293761", "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761") record, copy = main.opened(worktree_config("/code/acme", decisions=page), "decisions", pathlib.Path("/home/me")) self.assertEqual((copy.parent.parent, copy.name), (COPIES, "decisions.md")) self.assertRegex(copy.parent.name, r"^acme-[0-9a-f]{8}$") - assert isinstance(record, ConfluencePage), record - self.assertEqual(record.kept, copy.with_suffix(".version")) + self.assertIsInstance(record, ConfluencePage) def test_the_goals_file_opens_through_the_goals_store(self): record, copy = main.opened(worktree_config("/code/acme"), "goals-and-audience", pathlib.Path("/home/me")) diff --git a/bin/rank_todo.py b/bin/rank_todo.py index a4b1ac05..a69ee88b 100755 --- a/bin/rank_todo.py +++ b/bin/rank_todo.py @@ -93,8 +93,8 @@ import pathlib import sys from failure import Failure +from plan_store.stores import file_plan from project_config.main import located -from release_plan import plan_file def main(argv: list[str]) -> int: @@ -116,15 +116,16 @@ def main(argv: list[str]) -> int: # The goals, decisions and history are this checkout's project's, so another project's plan would be ranked by them. if todo.resolve() != config.plan_file.resolve(): return fail(Failure(f"rank_todo.py: {todo} is not the plan this checkout's config names, {config.plan_file.resolve()}; run rank_todo.py in the checkout of the project whose plan it is")) + plan = file_plan(config, todo) if check: - failures = plan_file.check_failures(todo, config) + failures = plan.check() for line in failures: print(line, file=sys.stderr) return 1 if failures else 0 - ranked = plan_file.rank_file(todo, config) + ranked = plan.rank() if isinstance(ranked, Failure): return fail(ranked) - for line in plan_file.report_lines(todo, ranked): + for line in plan.reported(ranked): print(line, file=sys.stderr) return 1 if ranked.under_bar else 0 diff --git a/bin/reading_cost/main.py b/bin/reading_cost/main.py index 8f32acda..bed9a5d0 100644 --- a/bin/reading_cost/main.py +++ b/bin/reading_cost/main.py @@ -73,11 +73,11 @@ def main(argv: list[str]) -> int: def update(record: RecordStore, archive: pathlib.Path, checkout: Checkout, home: str, reset_at: str | None) -> Updated | Failure: - text = record.read() - if isinstance(text, Failure): - return text + held = record.held() + if isinstance(held, Failure): + return held # An empty record starts with its title. - text = text or "# Reading cost\n" + text = held.text or "# Reading cost\n" figures = new_figures(text, archive, checkout, home) if isinstance(figures, Failure): return figures @@ -86,9 +86,8 @@ def update(record: RecordStore, archive: pathlib.Path, checkout: Checkout, home: readings = readings_of(text) if isinstance(readings, Failure): return readings - if marks and (unwritten := record.write(text)): - return unwritten - return Updated(len(figures), readings) + written = record.write(text, held.version) if marks else None + return written if isinstance(written, Failure) else Updated(len(figures), readings) def new_figures(record: str, archive: pathlib.Path, checkout: Checkout, home: str) -> list[str] | Failure: diff --git a/bin/reading_cost/test_reading_cost.py b/bin/reading_cost/test_reading_cost.py index dafe4be9..b53aac7c 100644 --- a/bin/reading_cost/test_reading_cost.py +++ b/bin/reading_cost/test_reading_cost.py @@ -19,6 +19,7 @@ from reading_cost.measure import Checkout, Reading from failure import Failure from reading_cost import figures, main, measure from transcript_archive.read import finished_chunks, FinishedChunk +from record_store.held import Held from test_env import isolated_env from record_store.fakes import MemoryStore from transcript_archive import outcomes @@ -235,9 +236,15 @@ class Located(unittest.TestCase): class Update(unittest.TestCase): + def test_writes_over_the_version_it_read(self): + record = MemoryStore("# Reading cost\n", version=2) + archive = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) + self.assertNotIsInstance(main.update(record, archive, Checkout("/c/p", "/c/p", frozenset(), BRANCH), "/h", "2026-11-14T00:00:00Z"), Failure) + self.assertEqual(record.overs, ["2"]) + def test_fails_where_the_record_refuses_the_write(self): class Unwritable(MemoryStore): - def write(self, text: str) -> Failure | None: + def write(self, text: str, over: str | None) -> Held | Failure: return Failure("the wiki is down") archive = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) diff --git a/bin/record_store/confluence_page.py b/bin/record_store/confluence_page.py index f5240b3b..fb171ea5 100644 --- a/bin/record_store/confluence_page.py +++ b/bin/record_store/confluence_page.py @@ -1,54 +1,42 @@ """A record kept on one Confluence Cloud page, read and written as markdown over Confluence's REST API version 2, with the credentials of the config's env-file, and converted by the adf-codec shim. -A write never overwrites a teammate's edit: it sends the version it read, and Confluence refuses it where someone saved the page since. The human then decides (lilleman, 2026-11-12).""" +A write never overwrites a teammate's edit: it sends the version after the one held() read, and Confluence refuses it where someone saved the page since. The human then decides (lilleman, 2026-11-12).""" import dataclasses import json import pathlib import typing from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused -from plan_store.jira_epic import basic_auth, Http, TIMEOUT, ToAdf, ToMarkdown +from atlassian.client import basic_auth, confluence_json, Http, ToAdf, ToMarkdown from rest_client.json_request import ErrorAnswer from failure import Failure -from rest_client import json_request +from record_store.held import Held from project_config.settings import Page -from text_files.file_writes import replace_file # What Confluence answers to a write whose version isn't the one after the version it holds. CONFLICT = 409 SHAPE = "not in the shape Confluence Cloud's REST API version 2 documents" -def http_json(method: str, url: str, authorization: str, body: object) -> object: - return json_request.http_json(method, url, authorization, body, TIMEOUT, error_message) - - -def error_message(answer: object) -> str: - """Confluence's messages in the JSON of an error answer; empty where it holds none.""" - errors = answer.get("errors") if isinstance(answer, dict) else None - found = [error.get("title") for error in errors if isinstance(error, dict)] if isinstance(errors, list) else [answer.get("message")] if isinstance(answer, dict) else [] - return "; ".join(text for text in found if isinstance(text, str)) - - @dataclasses.dataclass(frozen=True) class Seen: - """The page's version number and title as the store last read or wrote them. A write needs both.""" + """The page's version number and title as a read found them or a write left them. A write needs both, so a Held's version holds both, as JSON.""" version: int title: str + @property + def token(self) -> str: + return json.dumps(dataclasses.asdict(self)) + @dataclasses.dataclass class ConfluencePage: - """The text of page as markdown, read and written with the credentials env_file holds. - - kept is a file that keeps the version the store read for a later process, such as `project-record save` after `project-record open`; None keeps it only in memory.""" + """The text of page as markdown, read and written with the credentials env_file holds.""" page: Page env_file: pathlib.Path - kept: pathlib.Path | None = None - http: Http = http_json + http: Http = confluence_json to_markdown: ToMarkdown = adfs_to_markdown to_adf: ToAdf = markdown_to_adf - seen: Seen | None = None @property def label(self) -> str: @@ -64,18 +52,19 @@ class ConfluencePage: def read(self) -> str | Failure: """The page's text as markdown; empty where the page is.""" + held = self.held() + return held if isinstance(held, Failure) else held.text + + def held(self) -> Held | Failure: + """The page's text as markdown, with its version and title as the version a write over it names.""" answer = self.fetched("?body-format=atlas_doc_format") if isinstance(answer, Failure): return answer - seen, held = answer - if not isinstance(held, str): + seen, body = answer + if not isinstance(body, str): return Failure(f"{self.label} is {SHAPE}: it holds no body in atlas_doc_format") - text = self.converted(held) - if isinstance(text, Failure): - return text - # Kept only once the text is in hand: a version kept for a read that failed would let a later write overwrite the save it saw. - unkept = self.keep(seen) - return unkept or text + text = self.converted(body) + return text if isinstance(text, Failure) else Held(text, seen.token) def converted(self, held: str) -> str | Failure: """The markdown of the body held, the JSON of an ADF document; empty where held is.""" @@ -92,14 +81,9 @@ class ConfluencePage: return Failure(f"cannot convert {self.label} to markdown: {texts.reason}") return texts[0] - def write(self, text: str) -> Failure | None: - """Replaces the page's text with text, as the version after the one the store read. Where the store hasn't read the page, it replaces the page as it stands.""" - seen = self.seen or self.recalled() - if seen is None: - fetched = self.fetched("") - if isinstance(fetched, Failure): - return fetched - seen = fetched[0] + def write(self, text: str, over: str | None) -> Held | Failure: + """Replaces the page's text with text, as the version after over, the one held() gave. Where over is None, it replaces the page as it stands.""" + seen = self.seen_of(over) if isinstance(seen, Failure): return seen document = self.to_adf(text) @@ -114,7 +98,7 @@ class ConfluencePage: return Failure(f"someone saved {self.label} since the loop read version {seen.version} of it, so the loop didn't write it: never overwrite their edit, but ask the human what to do ({answer.reason})") if isinstance(answer, Failure): return Failure(f"cannot write {self.label}: {answer.reason}") - return self.keep(Seen(seen.version + 1, seen.title)) + return Held(text, Seen(seen.version + 1, seen.title).token) def fetched(self, query: str) -> tuple[Seen, object] | Failure: """The page's version and title, and the value of its body in atlas_doc_format where query asks for it; None where it doesn't.""" @@ -133,25 +117,13 @@ class ConfluencePage: adf = body.get("atlas_doc_format") if isinstance(body, dict) else None return Seen(number, title), adf.get("value") if isinstance(adf, dict) else None - def keep(self, seen: Seen) -> Failure | None: - self.seen = seen - if self.kept is None: - return None + def seen_of(self, over: str | None) -> Seen | Failure: + """The version and title a write sends: those over holds, else the page's as it stands.""" + if over is None: + fetched = self.fetched("") + return fetched if isinstance(fetched, Failure) else fetched[0] try: - self.kept.parent.mkdir(parents=True, exist_ok=True) - except OSError as failure: - return Failure(f"cannot write {self.kept}: {failure.strerror}") - unwritten = replace_file(self.kept, json.dumps(dataclasses.asdict(seen)).encode()) - return Failure(f"cannot write {self.kept}: {unwritten.reason}") if unwritten else None - - def recalled(self) -> Seen | Failure | None: - """The version and title the file kept holds; None where kept is None or names no file.""" - if self.kept is None: - return None - try: - held: typing.Any = json.loads(self.kept.read_text(encoding="utf-8")) + held: typing.Any = json.loads(over) return Seen(int(held["version"]), str(held["title"])) - except FileNotFoundError: - return None - except (OSError, ValueError, KeyError, TypeError) as failure: - return Failure(f"cannot read the version of {self.label} that {self.kept} keeps: {failure}") + except (ValueError, KeyError, TypeError) as failure: + return Failure(f"cannot read the version of {self.label} to write over, {over!r}: {failure}") diff --git a/bin/record_store/contract.py b/bin/record_store/contract.py index 8a28e9ee..88085894 100644 --- a/bin/record_store/contract.py +++ b/bin/record_store/contract.py @@ -1,6 +1,7 @@ """What every record backend must hold, as tests. A backend's test case inherits RecordStoreContract and unittest.TestCase, and builds its store in new_store.""" import typing +from record_store.held import Held from record_store.stores import RecordStore @@ -8,6 +9,7 @@ class RecordStoreContract: """Runs against the store new_store returns: one that holds no record yet.""" assertEqual: typing.Callable[..., None] assertIsNone: typing.Callable[..., None] + assertIsInstance: typing.Callable[..., None] assertTrue: typing.Callable[..., None] def new_store(self) -> RecordStore: @@ -19,14 +21,23 @@ class RecordStoreContract: def test_reads_back_what_it_wrote_to_the_character(self) -> None: store = self.new_store() text = "# Decisions\n\n- Å, 🔴 and a | pipe\n\n\n" - self.assertIsNone(store.write(text)) + self.assertEqual(store.write(text, None), store.held()) self.assertEqual(store.read(), text) def test_a_write_replaces_the_whole_record(self) -> None: store = self.new_store() - store.write("first\nsecond\n") - self.assertIsNone(store.write("third\n")) + first = store.write("first\nsecond\n", None) + assert isinstance(first, Held), first + # A write over the version the last one left replaces the record, as a later save does. + self.assertIsInstance(store.write("third\n", first.version), Held) self.assertEqual(store.read(), "third\n") + def test_holds_its_text_with_the_version_a_write_over_it_names(self) -> None: + store = self.new_store() + store.write("text\n", None) + held = store.held() + assert isinstance(held, Held), held + self.assertEqual(held.text, "text\n") + def test_names_itself_for_a_message(self) -> None: self.assertTrue(self.new_store().label.strip()) diff --git a/bin/record_store/fakes.py b/bin/record_store/fakes.py index 07e560bf..0cc3e9eb 100644 --- a/bin/record_store/fakes.py +++ b/bin/record_store/fakes.py @@ -2,21 +2,30 @@ import dataclasses from failure import Failure +from record_store.held import Held @dataclasses.dataclass class MemoryStore: - """A record held in memory, as a backend outside git holds one. Set fails to make every read and write fail with that reason.""" + """A record held in memory, as a backend outside git holds one: versioned as a wiki page is, refusing a write over a version it no longer holds. Set fails to make every read and write fail with that reason. overs holds the version each write named, so a test can check that a caller wrote over the version it read.""" text: str = "" label: str = "the record in memory" tracked: str | None = None fails: str | None = None + version: int = 0 + overs: list[str | None] = dataclasses.field(default_factory=list) def read(self) -> str | Failure: return Failure(self.fails) if self.fails else self.text - def write(self, text: str) -> Failure | None: + def held(self) -> Held | Failure: + return Failure(self.fails) if self.fails else Held(self.text, str(self.version)) + + def write(self, text: str, over: str | None) -> Held | Failure: + self.overs.append(over) if self.fails: return Failure(self.fails) - self.text = text - return None + if over is not None and over != str(self.version): + return Failure(f"someone saved {self.label} since version {over}") + self.text, self.version = text, self.version + 1 + return Held(text, str(self.version)) diff --git a/bin/record_store/held.py b/bin/record_store/held.py new file mode 100644 index 00000000..caf914d2 --- /dev/null +++ b/bin/record_store/held.py @@ -0,0 +1,9 @@ +"""A record as a read found it or a write left it, which every record backend gives.""" +import dataclasses + + +@dataclasses.dataclass(frozen=True) +class Held: + """A record's text as one read found it or one write left it, with its version: what a write over it names, so the write refuses where someone saved the record since. None for a backend whose writes check no version, as a file's.""" + text: str + version: str | None = None diff --git a/bin/record_store/jira_description.py b/bin/record_store/jira_description.py index 1e748743..3f8580d9 100644 --- a/bin/record_store/jira_description.py +++ b/bin/record_store/jira_description.py @@ -5,9 +5,10 @@ import dataclasses import pathlib from adf_codec.convert import adfs_to_markdown, Refused -from plan_store.jira_epic import basic_auth, Http, http_json, ToMarkdown +from atlassian.client import basic_auth, Http, jira_json, ToMarkdown from project_config.settings import Epic from failure import Failure +from record_store.held import Held READ_ONLY = "goals and audience kept in Jira are only read: edit the epic's description in Jira" @@ -17,7 +18,7 @@ class EpicDescription: """The description of epic as markdown, read with the credentials env_file holds.""" epic: Epic env_file: pathlib.Path - http: Http = http_json + http: Http = jira_json to_markdown: ToMarkdown = adfs_to_markdown @property @@ -49,5 +50,9 @@ class EpicDescription: return Failure(f"cannot convert {key}'s description to markdown: {texts.reason}") return texts[0] - def write(self, text: str) -> Failure | None: + def held(self) -> Held | Failure: + text = self.read() + return text if isinstance(text, Failure) else Held(text) + + def write(self, text: str, over: str | None) -> Held | Failure: return Failure(READ_ONLY) diff --git a/bin/record_store/stores.py b/bin/record_store/stores.py index 53a1d7fc..124f8421 100644 --- a/bin/record_store/stores.py +++ b/bin/record_store/stores.py @@ -5,8 +5,11 @@ import dataclasses import pathlib import typing +from record_store.confluence_page import ConfluencePage +from record_store.jira_description import EpicDescription from failure import Failure from git_cli.git_repo import file_at, git, Git +from record_store.held import Held from project_config.settings import ProjectConfig, RECORDS, TOUCH_PREDICTIONS from text_files.file_writes import replace_file @@ -25,8 +28,11 @@ class RecordStore(typing.Protocol): def read(self) -> str | Failure: """The record's text as it stands, empty where it doesn't exist yet.""" - def write(self, text: str) -> Failure | None: - """Replaces the record's whole text, creating the record where it doesn't exist yet.""" + def held(self) -> Held | Failure: + """The record as it stands, with the version a write over it names.""" + + def write(self, text: str, over: str | None) -> Held | Failure: + """Replaces the record's whole text, creating the record where it doesn't exist yet, and gives the record as the write left it. over is the version held() gave: where someone saved the record since, the write refuses. None replaces the record as it stands, so a caller passes it only where it read no version.""" @dataclasses.dataclass(frozen=True) @@ -39,6 +45,10 @@ class FileStore: def label(self) -> str: return str(self.path) + def held(self) -> Held | Failure: + text = self.read() + return text if isinstance(text, Failure) else Held(text) + def read(self) -> str | Failure: try: return self.path.read_text(encoding="utf-8") @@ -49,26 +59,24 @@ class FileStore: except OSError as failure: return Failure(f"cannot read {self.path}: {failure.strerror}") - def write(self, text: str) -> Failure | None: + def write(self, text: str, over: str | None) -> Held | Failure: try: self.path.parent.mkdir(parents=True, exist_ok=True) except OSError as failure: return Failure(f"cannot write {self.path}: {failure.strerror}") unwritten = replace_file(self.path, text.encode("utf-8")) - return Failure(f"cannot write {self.path}: {unwritten.reason}") if unwritten else None + return Failure(f"cannot write {self.path}: {unwritten.reason}") if unwritten else Held(text) -def store(config: ProjectConfig, record: str, kept: pathlib.Path | None = None) -> RecordStore: - """The store config names for record, one of RECORDS. A record on a Confluence page keeps the version it read in the file the parameter kept names, for a later process that writes it; where kept is None, the store keeps the version only in memory.""" +def store(config: ProjectConfig, record: str) -> RecordStore: + """The store config names for record, one of RECORDS.""" if record not in RECORDS: raise ValueError(f"{record} is not a record; the records are {', '.join(RECORDS)}") if record not in config.pages: return FileStore(config.paths[record], config.tracked(record)) - # Imported here, as in goals_store. - from record_store.confluence_page import ConfluencePage # load refuses a config that names a page and no env-file. assert config.env_file is not None - return ConfluencePage(config.pages[record], config.env_file, kept) + return ConfluencePage(config.pages[record], config.env_file) def touch_predictions_store(config: ProjectConfig) -> RecordStore | None: @@ -82,8 +90,6 @@ def goals_store(config: ProjectConfig) -> RecordStore: """The store config names for the goals file, which holds ## Goals and ## Audience: a markdown file, or a Jira epic's description, which the store only reads.""" if config.goals_epic is None: return FileStore(config.paths["goals-and-audience"], config.tracked("goals-and-audience")) - # Imported here, since the Jira store builds on plan_store, which builds on this module. - from record_store.jira_description import EpicDescription # load refuses a config that names an epic and no env-file. assert config.env_file is not None return EpicDescription(config.goals_epic, config.env_file) @@ -95,27 +101,54 @@ def held_at(revision: str, record: RecordStore, cwd: str, run: Git = git) -> str def local_file(record: RecordStore, copy: pathlib.Path) -> pathlib.Path | Failure: - """A file holding record's text, for an agent, which reads and edits files: the record's own file where a file is its backend, else copy, written with the text as it stands. Neither exists where the record doesn't yet. `stored` puts an edited copy back.""" + """A file holding record's text, for an agent, which reads and edits files: the record's own file where a file is its backend, else copy, written with the text as it stands, and its version beside it, for `stored` to write over in a later process. Neither exists where the record doesn't yet. `stored` puts an edited copy back.""" if isinstance(record, FileStore): return record.path - text = record.read() - if isinstance(text, Failure): - return text - if text: - return FileStore(copy, None).write(text) or copy - try: - # An earlier copy would read as the record's text, and `stored` would put it back. - copy.unlink(missing_ok=True) - except OSError as failure: - return Failure(f"cannot remove {copy}: {failure.strerror}") - return copy + held = record.held() + if isinstance(held, Failure): + return held + if held.text: + written = FileStore(copy, None).write(held.text, None) + if isinstance(written, Failure): + return written + else: + try: + # An earlier copy would read as the record's text, and `stored` would put it back. + copy.unlink(missing_ok=True) + except OSError as failure: + return Failure(f"cannot remove {copy}: {failure.strerror}") + # Kept only once the copy holds the text: a newer version beside an older copy would let a later save overwrite the edit that version holds. + return kept(copy, held.version) or copy def stored(record: RecordStore, copy: pathlib.Path) -> Failure | None: - """Stores in record the text of copy, the file `local_file` gave for it. Where that is the record's own file, the edit is already the record.""" + """Stores in record the text of copy, the file `local_file` gave for it, over the version kept beside it. Where that is the record's own file, the edit is already the record. The version the write left is kept for the next save.""" if isinstance(record, FileStore): return None text = FileStore(copy, None).read() if isinstance(text, Failure): return text - return record.write(text) if text else Failure(f"{copy} is missing or empty, so nothing is stored in {record.label}") + if not text: + return Failure(f"{copy} is missing or empty, so nothing is stored in {record.label}") + over = FileStore(version_file(copy), None).read() + if isinstance(over, Failure): + return over + written = record.write(text, over.strip() or None) + return written if isinstance(written, Failure) else kept(copy, written.version) + + +def version_file(copy: pathlib.Path) -> pathlib.Path: + """The file beside copy that keeps the version of the record copy holds.""" + return copy.with_suffix(".version") + + +def kept(copy: pathlib.Path, version: str | None) -> Failure | None: + """Keeps version beside copy, or removes the file that kept an earlier one where version is None.""" + if version is not None: + written = FileStore(version_file(copy), None).write(version, None) + return written if isinstance(written, Failure) else None + try: + version_file(copy).unlink(missing_ok=True) + except OSError as failure: + return Failure(f"cannot remove {version_file(copy)}: {failure.strerror}") + return None diff --git a/bin/record_store/test_confluence_page.py b/bin/record_store/test_confluence_page.py index 6da75ef0..06cafb0d 100644 --- a/bin/record_store/test_confluence_page.py +++ b/bin/record_store/test_confluence_page.py @@ -7,12 +7,14 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from record_store.confluence_page import ConfluencePage, error_message +from record_store.confluence_page import ConfluencePage from rest_client.json_request import ErrorAnswer from failure import Failure +from record_store.held import Held from project_config.settings import Page from record_store.contract import RecordStoreContract from adf_codec.convert import Refused +from record_store import stores PAGE = Page("https://acme.atlassian.net", "2293761", "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761") URL = "https://acme.atlassian.net/wiki/api/v2/pages/2293761" @@ -57,11 +59,10 @@ class ConfluenceCase(unittest.TestCase): self.env = folder / "acme.env" self.env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n") self.env.chmod(0o600) - self.kept = folder / "state" / "acme" / "decisions.version" self.confluence = FakeConfluence() - def new_store(self, kept: pathlib.Path | None = None) -> ConfluencePage: - return ConfluencePage(PAGE, self.env, kept, self.confluence.http, to_markdown, to_adf) + def new_store(self) -> ConfluencePage: + return ConfluencePage(PAGE, self.env, self.confluence.http, to_markdown, to_adf) class ConfluencePageContract(ConfluenceCase, RecordStoreContract): @@ -74,60 +75,80 @@ class ConfluencePageTest(ConfluenceCase): self.assertEqual(self.new_store().read(), "# Decisions\n") self.assertEqual(self.confluence.calls, [("GET", f"{URL}?body-format=atlas_doc_format", AUTHORIZATION, None)]) - def test_writes_markdown_as_the_version_it_read_plus_one(self) -> None: + def test_writes_markdown_as_the_version_it_is_handed_plus_one(self) -> None: self.confluence.version = 7 store = self.new_store() - store.read() - self.assertIsNone(store.write("- a decision\n")) + held = store.held() + assert isinstance(held, Held), held + self.assertEqual(store.write("- a decision\n", held.version), Held("- a decision\n", '{"version": 8, "title": "Decisions"}')) self.assertEqual(self.confluence.calls[-1], ("PUT", URL, AUTHORIZATION, {"id": PAGE.page_id, "status": "current", "title": "Decisions", "body": {"representation": "atlas_doc_format", "value": json.dumps(to_adf("- a decision\n"))}, "version": {"number": 8}})) - def test_refuses_to_overwrite_a_teammates_save_since_its_read_and_says_to_ask_the_human(self) -> None: - store = self.new_store() - store.read() + def test_refuses_to_overwrite_a_teammates_save_since_the_version_it_is_handed_and_says_to_ask_the_human(self) -> None: + held = self.new_store().held() + assert isinstance(held, Held), held self.confluence.teammate_saves("their edit\n") - written = store.write("my edit\n") + written = self.new_store().write("my edit\n", held.version) assert isinstance(written, Failure), written self.assertIn("someone saved", written.reason) self.assertIn("ask the human", written.reason) self.assertIn(PAGE.spelling, written.reason) self.assertEqual(self.new_store().read(), "their edit\n") - def test_keeps_the_version_it_read_in_its_file_for_a_later_process(self) -> None: - self.new_store(self.kept).read() + def test_keeps_no_version_itself_so_a_read_never_moves_the_version_a_write_names(self) -> None: + store = self.new_store() + held = store.held() + assert isinstance(held, Held), held self.confluence.teammate_saves("their edit\n") - written = self.new_store(self.kept).write("my edit\n") + self.assertEqual(store.read(), "their edit\n") + written = store.write("my edit\n", held.version) assert isinstance(written, Failure), written self.assertIn("someone saved", written.reason) - def test_a_read_that_fails_keeps_the_version_an_earlier_read_kept(self) -> None: - self.new_store(self.kept).read() - self.confluence.teammate_saves("their edit\n") - failing = ConfluencePage(PAGE, self.env, self.kept, self.confluence.http, lambda _: Refused(0, Failure("adf-codec refused the input")), to_adf) - self.assertIsInstance(failing.read(), Failure) - self.confluence.value = "{not json" - self.assertIsInstance(self.new_store(self.kept).read(), Failure) - written = self.new_store(self.kept).write("my edit\n") - assert isinstance(written, Failure), written - self.assertIn("someone saved", written.reason) - self.assertEqual(self.confluence.version, 2) - - def test_a_later_process_writes_with_the_version_an_earlier_one_read_or_wrote(self) -> None: - self.new_store(self.kept).read() - self.assertIsNone(self.new_store(self.kept).write("first\n")) - self.assertIsNone(self.new_store(self.kept).write("second\n")) + def test_a_later_write_over_the_version_an_earlier_one_left_lands(self) -> None: + held = self.new_store().held() + assert isinstance(held, Held), held + first = self.new_store().write("first\n", held.version) + assert isinstance(first, Held), first + self.assertIsInstance(self.new_store().write("second\n", first.version), Held) self.assertEqual(self.new_store().read(), "second\n") self.assertEqual(self.confluence.title, "Decisions") + def test_each_save_of_an_opened_copy_writes_over_the_version_the_open_or_the_last_save_left(self) -> None: + copy = self.env.parent / "copies" / "decisions.md" + self.confluence.teammate_saves("first\n") + self.assertEqual(stores.local_file(self.new_store(), copy), copy) + for text in ("mine\n", "again\n"): + copy.write_text(text) + self.assertIsNone(stores.stored(self.new_store(), copy)) + self.assertEqual(self.new_store().read(), "again\n") + self.confluence.teammate_saves("theirs\n") + copy.write_text("third\n") + refused = stores.stored(self.new_store(), copy) + assert isinstance(refused, Failure), refused + self.assertIn("someone saved", refused.reason) + self.assertEqual(self.new_store().read(), "theirs\n") + + def test_an_open_that_fails_keeps_the_version_an_earlier_open_kept(self) -> None: + copy = self.env.parent / "copies" / "decisions.md" + stores.local_file(self.new_store(), copy) + self.confluence.teammate_saves("their edit\n") + self.confluence.value = "{not json" + self.assertIsInstance(stores.local_file(self.new_store(), copy), Failure) + copy.write_text("my edit\n") + refused = stores.stored(self.new_store(), copy) + assert isinstance(refused, Failure), refused + self.assertIn("someone saved", refused.reason) + def test_a_write_with_no_read_replaces_the_page_as_it_stands(self) -> None: self.confluence.teammate_saves("earlier\n") - self.assertIsNone(self.new_store().write("replaced\n")) + self.assertIsInstance(self.new_store().write("replaced\n", None), Held) self.assertEqual(self.confluence.calls[0], ("GET", URL, AUTHORIZATION, None)) self.assertEqual(self.new_store().read(), "replaced\n") def test_fails_on_an_answer_not_shaped_as_a_page(self) -> None: for answer in ({}, {"title": "Decisions", "version": {}, "body": {"atlas_doc_format": {"value": ""}}}, {"version": {"number": 3}, "body": {"atlas_doc_format": {"value": ""}}}, ["not", "a", "page"]): with self.subTest(answer): - store = ConfluencePage(PAGE, self.env, None, lambda *_: answer, to_markdown, to_adf) + store = ConfluencePage(PAGE, self.env, lambda *_: answer, to_markdown, to_adf) read = store.read() assert isinstance(read, Failure), read self.assertIn("not in the shape Confluence Cloud's REST API version 2 documents", read.reason) @@ -136,7 +157,7 @@ class ConfluencePageTest(ConfluenceCase): for body in ({}, "text", {"atlas_doc_format": "text"}, {"atlas_doc_format": {"value": 3}}): with self.subTest(body): answer = {"title": "Decisions", "version": {"number": 3}, "body": body} - store = ConfluencePage(PAGE, self.env, None, lambda *_: answer, to_markdown, to_adf) + store = ConfluencePage(PAGE, self.env, lambda *_: answer, to_markdown, to_adf) self.assertEqual(store.read(), Failure(f"{PAGE.spelling} is not in the shape Confluence Cloud's REST API version 2 documents: it holds no body in atlas_doc_format")) def test_fails_on_a_body_that_is_not_json(self) -> None: @@ -145,51 +166,34 @@ class ConfluencePageTest(ConfluenceCase): def test_fails_naming_the_page_where_the_text_cannot_be_converted(self) -> None: self.confluence.teammate_saves("text\n") - store = ConfluencePage(PAGE, self.env, None, self.confluence.http, lambda _: Failure("the shim is down"), lambda _: Failure("the shim is down")) + store = ConfluencePage(PAGE, self.env, self.confluence.http, lambda _: Failure("the shim is down"), lambda _: Failure("the shim is down")) self.assertEqual(store.read(), Failure(f"cannot convert {PAGE.spelling} to markdown: the shim is down")) - self.assertEqual(store.write("text\n"), Failure(f"cannot convert the text for {PAGE.spelling} to ADF: the shim is down")) + self.assertEqual(store.write("text\n", None), Failure(f"cannot convert the text for {PAGE.spelling} to ADF: the shim is down")) def test_fails_naming_the_page_where_adf_codec_refuses_its_document(self) -> None: self.confluence.teammate_saves("text\n") - store = ConfluencePage(PAGE, self.env, None, self.confluence.http, lambda _: Refused(0, Failure("adf-codec refused the input")), to_adf) + store = ConfluencePage(PAGE, self.env, self.confluence.http, lambda _: Refused(0, Failure("adf-codec refused the input")), to_adf) self.assertEqual(store.read(), Failure(f"{PAGE.spelling}: adf-codec refused the input")) - def test_fails_where_the_folder_of_its_file_cannot_be_made(self) -> None: - self.kept.parent.parent.mkdir(parents=True) - self.kept.parent.write_text("a file, not a folder") - read = self.new_store(self.kept).read() - assert isinstance(read, Failure), read - self.assertTrue(read.reason.startswith(f"cannot write {self.kept}: "), read.reason) - def test_a_write_confluence_refuses_otherwise_fails_naming_the_page_and_not_a_teammate(self) -> None: answers = iter([{"title": "Decisions", "version": {"number": 3}}, ErrorAnswer("PUT /wiki/api/v2/pages/2293761 answered 403: Forbidden", 403)]) - store = ConfluencePage(PAGE, self.env, None, lambda *_: next(answers), to_markdown, to_adf) - self.assertEqual(store.write("text\n"), Failure(f"cannot write {PAGE.spelling}: PUT /wiki/api/v2/pages/2293761 answered 403: Forbidden")) + store = ConfluencePage(PAGE, self.env, lambda *_: next(answers), to_markdown, to_adf) + self.assertEqual(store.write("text\n", None), Failure(f"cannot write {PAGE.spelling}: PUT /wiki/api/v2/pages/2293761 answered 403: Forbidden")) - def test_fails_where_its_file_cannot_keep_the_version(self) -> None: - self.kept.mkdir(parents=True) - read = self.new_store(self.kept).read() - assert isinstance(read, Failure), read - self.assertTrue(read.reason.startswith(f"cannot write {self.kept}: "), read.reason) - - def test_fails_on_a_kept_version_it_cannot_read_and_writes_nothing(self) -> None: - self.kept.parent.mkdir(parents=True) - self.kept.write_text("{}") - written = self.new_store(self.kept).write("text\n") + def test_fails_on_a_version_it_cannot_read_and_writes_nothing(self) -> None: + written = self.new_store().write("text\n", "{}") assert isinstance(written, Failure), written - self.assertTrue(written.reason.startswith(f"cannot read the version of {PAGE.spelling} that {self.kept} keeps: "), written.reason) + self.assertTrue(written.reason.startswith(f"cannot read the version of {PAGE.spelling} to write over, '{{}}': "), written.reason) self.assertEqual(self.confluence.calls, []) - def test_reads_confluences_messages_from_an_error_answer(self) -> None: - self.assertEqual(error_message({"errors": [{"status": 409, "title": "Version must be incremented"}, {"title": "and more"}, "odd"]}), "Version must be incremented; and more") - self.assertEqual(error_message({"message": "Not Found"}), "Not Found") - self.assertEqual(error_message({"errors": "odd"}), "") - self.assertEqual(error_message(["odd"]), "") - def test_fails_naming_the_page_when_confluence_answers_an_error(self) -> None: - store = ConfluencePage(PAGE, self.env, None, lambda *_: ErrorAnswer("GET /wiki/api/v2/pages/2293761 answered 404: Not Found", 404), to_markdown, to_adf) + store = ConfluencePage(PAGE, self.env, lambda *_: ErrorAnswer("GET /wiki/api/v2/pages/2293761 answered 404: Not Found", 404), to_markdown, to_adf) self.assertEqual(store.read(), Failure(f"cannot read {PAGE.spelling}: GET /wiki/api/v2/pages/2293761 answered 404: Not Found")) + def test_a_write_handed_no_version_fails_naming_the_page_where_its_version_cannot_be_read(self) -> None: + store = ConfluencePage(PAGE, self.env, lambda *_: ErrorAnswer("GET /wiki/api/v2/pages/2293761 answered 404: Not Found", 404), to_markdown, to_adf) + self.assertEqual(store.write("text\n", None), Failure(f"cannot read {PAGE.spelling}: GET /wiki/api/v2/pages/2293761 answered 404: Not Found")) + def test_fails_without_credentials_before_any_request(self) -> None: self.env.unlink() read = self.new_store().read() diff --git a/bin/record_store/test_jira_description.py b/bin/record_store/test_jira_description.py index 07bf1292..67bd40db 100644 --- a/bin/record_store/test_jira_description.py +++ b/bin/record_store/test_jira_description.py @@ -79,7 +79,7 @@ class EpicDescriptionTest(unittest.TestCase): self.assertEqual(self.calls, []) def test_writing_fails_since_the_store_only_reads(self) -> None: - found = self.store().write("## Goals\n") + found = self.store().write("## Goals\n", None) assert isinstance(found, Failure), found self.assertIn("Jira", found.reason) self.assertEqual(self.calls, []) diff --git a/bin/record_store/test_stores.py b/bin/record_store/test_stores.py index 64603554..62796778 100644 --- a/bin/record_store/test_stores.py +++ b/bin/record_store/test_stores.py @@ -10,6 +10,7 @@ from record_store.confluence_page import ConfluencePage from project_config.settings import Epic, Page, ProjectConfig from record_store.jira_description import EpicDescription from failure import Failure +from record_store.held import Held from record_store.fakes import MemoryStore from record_store.contract import RecordStoreContract from record_store import stores @@ -56,19 +57,19 @@ class FileStore(unittest.TestCase): def test_a_write_that_fails_is_a_failure_naming_it(self): (self.folder / "docs").write_text("a file where the folder goes") path = self.folder / "docs" / "decisions.md" - written = stores.FileStore(path, None).write("text\n") + written = stores.FileStore(path, None).write("text\n", None) self.assertIsInstance(written, Failure) self.assertIn(f"cannot write {path}: ", written.reason) def test_a_write_makes_each_folder_the_file_lacks(self): path = self.folder / "records" / "acme" / "decisions.md" - self.assertIsNone(stores.FileStore(path, None).write("text\n")) + self.assertEqual(stores.FileStore(path, None).write("text\n", None), Held("text\n")) self.assertEqual(path.read_text(), "text\n") def test_a_write_onto_a_folder_is_a_failure_naming_it(self): path = self.folder / "decisions.md" path.mkdir() - written = stores.FileStore(path, None).write("text\n") + written = stores.FileStore(path, None).write("text\n", None) self.assertIsInstance(written, Failure) self.assertIn(f"cannot write {path}: ", written.reason) @@ -112,7 +113,7 @@ class LocalFile(unittest.TestCase): def test_a_file_record_is_its_own_local_file_and_no_copy_is_made(self): record = stores.FileStore(self.folder / "decisions.md", None) - record.write("kept\n") + record.write("kept\n", None) self.assertEqual(stores.local_file(record, self.folder / "copies" / "decisions.md"), self.folder / "decisions.md") self.assertIsNone(stores.stored(record, self.folder / "copies" / "decisions.md")) self.assertEqual((record.read(), (self.folder / "copies").exists()), ("kept\n", False)) @@ -142,6 +143,13 @@ class LocalFile(unittest.TestCase): self.assertIsInstance(opened, Failure) self.assertIn(f"cannot write {copy}: ", opened.reason) + def test_a_version_that_cannot_be_kept_beside_the_copy_is_a_failure_naming_its_file(self): + copy = self.folder / "decisions.md" + (self.folder / "decisions.version").mkdir() + opened = stores.local_file(MemoryStore("# Decisions\n"), copy) + assert isinstance(opened, Failure), opened + self.assertTrue(opened.reason.startswith(f"cannot write {self.folder / 'decisions.version'}: "), opened.reason) + def test_storing_a_missing_copy_fails_and_leaves_the_record(self): record = MemoryStore("kept\n") self.assertIn("is missing or empty", stores.stored(record, self.folder / "decisions.md").reason) @@ -172,11 +180,10 @@ class Store(unittest.TestCase): stores.store(self.config(pathlib.Path("/code/acme"), pathlib.Path("/home/me/.claude-projects/acme")), "plan") self.assertEqual(str(refused.exception), "plan is not a record; the records are decisions, score-anchors, comprehension-history, reading-cost, changelog") - def test_a_record_on_a_confluence_page_is_that_page_keeping_its_version_where_asked(self): + def test_a_record_on_a_confluence_page_is_that_page(self): page = Page("https://acme.atlassian.net", "2293761", "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761") config = ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path("/code/acme"), {}, pathlib.Path("/home/me/acme.env"), pages={"decisions": page}) - kept = pathlib.Path("/home/me/decisions.version") - self.assertEqual(stores.store(config, "decisions", kept), ConfluencePage(page, pathlib.Path("/home/me/acme.env"), kept)) + self.assertEqual(stores.store(config, "decisions"), ConfluencePage(page, pathlib.Path("/home/me/acme.env"))) class GoalsStore(unittest.TestCase): diff --git a/bin/release_plan/next_chunk.py b/bin/release_plan/next_chunk.py new file mode 100644 index 00000000..c881e128 --- /dev/null +++ b/bin/release_plan/next_chunk.py @@ -0,0 +1,92 @@ +"""The next chunk's pick: the plan's items weighed against the last cut, with the item the next chunk takes first, or why there is none, as chunk-preflight states it and loop-claude starts chunks by it.""" +import dataclasses + +from release_plan.release_standing import Cut, dated_cut, LastCut, picked, ReadyToCut, ReviewDue, standing_of, Unknown, Unplanned +from failure import Failure +from plan.todo_table import Item, NoItemsTable +from plan_store.plans import Plan +from plan.release import Release, version +from project_config import templates + + +@dataclasses.dataclass(frozen=True) +class CarriedOver: + """The items, by ID in the plan's order, that the plan files under a release already cut, and that count as `into`'s, the next release: release_standing.Standing.moved.""" + into: Release + ids: tuple[int, ...] + + +@dataclasses.dataclass(frozen=True) +class NextChunk: + """The plan's items, each with its detail, and `first`: the item the next chunk takes first.""" + items: list[Item] + first: Item + # first's tagline and detail. + text: str + branch_template: str + # The items of a release already cut, which `items` and `first` hold as the next release's. None where every item's release is after the last cut. + carried: CarriedOver | None = None + # Whether --item named first, in place of the next release's first item that does not wait. + named: bool = False + + @property + def branch(self) -> str: + """The branch first's worktree is on.""" + return templates.branch_of(self.branch_template, self.first.id) + + +@dataclasses.dataclass(frozen=True) +class NoItem: + """Why the plan names no item for the next chunk, as a sentence the worker reads.""" + why: str + + +def cut_name(cut: LastCut) -> str | None: + """How the preflight names the last cut: the tag, or the version under its dated CHANGELOG.md heading; None where nothing is cut.""" + if cut.tag is not None: + return None if isinstance(cut.tag, Failure) else cut.tag + headed = dated_cut(cut.tag, cut.changelog) + return None if headed is None else f"{version(headed)} (dated in CHANGELOG.md)" + + +def plan_name(default: str, outside: str | None) -> str: + """How the preflight names the plan it read: the default branch's todo.md, or the file or Jira epic, where the project's config puts it outside the checkout.""" + return outside if outside else f"{default}'s todo.md" + + +def planned(read: Plan | Failure, cut: LastCut, default: str, branch: str, outside: str | None = None, item_id: int | None = None) -> NextChunk | NoItem: + """read, which is the project's plan as its store read it and which plan_name names, with the item the next chunk takes first: the item of item_id where one is given, else release_standing.chunk_item's pick. Else why there is none. branch is the project's `branch` template.""" + where = plan_name(default, outside) + if isinstance(read, NoItemsTable): + return NoItem(f"{where} holds no items table.") + if isinstance(read, Failure): + return NoItem(f"{where} cannot be read: {read.reason}.") + found = read.items + if isinstance(cut.tag, Failure): + return NoItem(f"{default}'s tags cannot be read: {cut.tag.reason}. So which release is next cannot be told. Find the next release yourself.") + named = cut_name(cut) + last_cut = f"the last cut, {named}" if named is not None else "the start, since no release is cut yet" + weighed = standing_of(found, cut) + pick = picked(weighed, cut) + if isinstance(pick, Cut): + return NoItem(f"{where} files items under release {version(pick.release)}, which is not after {last_cut}; ask the human which release they belong to.") + if isinstance(pick, Unknown): + return NoItem(f"{where} may hold no item for the next release after {last_cut}: todo.md's texts since then, or the count of changes since then, cannot be read. Find the next release yourself.") + 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.") + 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.") + first = pick.item + if first is None: + return NoItem(f"every item of release {version(pick.release)} in {where} waits." if pick.release is not None else f"{where}'s items table holds no item.") + held = weighed.carried + # Every carried item takes one release, the next. + over = CarriedOver(next(item.release for item in held if item.id == weighed.moved[0]), weighed.moved) if weighed.moved else None + if item_id is not None: + first = next((item for item in held if item.id == item_id), None) + if first is None: + return NoItem(f"{where} holds no item {item_id}, the one --item names; it may have shipped.") + return NextChunk(held, first, f"{first.tagline}\n\n{first.detail}".strip(), branch, over, item_id is not None) diff --git a/bin/release_plan/plan_file.py b/bin/release_plan/plan_file.py deleted file mode 100644 index 7da5af3a..00000000 --- a/bin/release_plan/plan_file.py +++ /dev/null @@ -1,43 +0,0 @@ -"""todo.md on disk, for the tools that work on the markdown file itself: rank or check it with the texts its FilePlan reads, write it back, and give the lines ranking reports.""" -import pathlib - -from failure import Failure -from plan_store.stores import file_plan -from project_config.settings import ProjectConfig -from release_plan.ranking import rank, Ranked -from text_files.file_writes import replace_file - - -def rank_file(todo: pathlib.Path, config: ProjectConfig) -> Ranked | Failure: - """Rank todo in place: rank the texts its FilePlan reads, and write todo where that changed it. The caller prints `report_lines`.""" - texts = file_plan(config, todo).texts() - if isinstance(texts, Failure): - return texts - ranked = rank(*texts, config.readability_floor) - if isinstance(ranked, Failure): - return ranked - if ranked.text != texts[0] and (unwritten := write(todo, ranked.text)): - return unwritten - return ranked - - -def report_lines(todo: pathlib.Path, ranked: Ranked) -> list[str]: - """Ranking's notes and under-bar lines, each prefixed with todo's path, as a tool prints them on stderr.""" - return [f"{todo}: {line}" for line in ranked.notes + ranked.under_bar] - - -def check_failures(todo: pathlib.Path, config: ProjectConfig) -> list[str]: - """Why --check fails on todo, empty when it passes.""" - texts = file_plan(config, todo).texts() - if isinstance(texts, Failure): - return [texts.reason] - ranked = rank(*texts, config.readability_floor) - if isinstance(ranked, Failure): - return [ranked.reason] - unranked = [] if ranked.text == texts[0] else [f"{todo}: not ranked; run rank_todo.py on it"] - return unranked + [f"{todo}: {line}" for line in ranked.under_bar] - - -def write(path: pathlib.Path, text: str) -> Failure | None: - unwritten = replace_file(path.resolve(), text.encode("utf-8")) - return Failure(f"{path}: {unwritten.reason}") if unwritten else None diff --git a/bin/release_plan/release_standing.py b/bin/release_plan/release_standing.py index aa682de9..fe371b57 100644 --- a/bin/release_plan/release_standing.py +++ b/bin/release_plan/release_standing.py @@ -2,13 +2,13 @@ import dataclasses from git_cli.git_repo import commits_since, file_at, git, Git -from release_plan.release import dated, dated_heading_pattern, newest_tag, parsed, Release, tagged +from plan.release import dated, dated_heading_pattern, newest_tag, parsed, Release, tagged, UNRELEASED_TITLE from failure import Failure -from release_plan.todo_table import Item, items, next_item, renames -from plan_store.stores import Plan -from plan_store import stores as plan_stores +from plan.todo_table import Item, items, next_item, renames +from plan_store.plans import Plan +from plan_store import stores as plan_stores, plans from project_config.settings import ProjectConfig -from text_files.markdown_text import sections +from text_files.markdown_text import section, sections from record_store import stores from project_config import templates @@ -38,8 +38,8 @@ class Upcoming: """The next release, and whether work has landed towards it, as `~/.claude/CLAUDE.md` → "Working loop" uses both.""" # The earliest release after the last cut that todo.md has named since that cut or the plan holds; without a cut, the earliest todo.md has named or the plan holds. None where there is none. release: Release | None - # Whether it is the plan's earliest release. Also True without a cut where todo.md has never named a release and the plan holds no item. - is_earliest: bool + # Whether the plan is current: the next release is the plan's earliest, so the plan holds its items. Also True without a cut where todo.md has never named a release and the plan holds no item, since there is no release to plan, review or cut yet. + plan_is_current: bool # Whether work has landed towards it: one or more changes are unreleased, as unreleased_changes counts them. unreleased: bool | Failure @@ -93,7 +93,7 @@ Pick = Next | Cut | ReadyToCut | ReviewDue | Unplanned | Unknown class DefaultPlan: """What the default branch, as last fetched, holds for chunk_item.""" # The plan, a NoItemsTable where the branch holds none. - todo: Plan | Failure + plan: Plan | Failure cut: LastCut @@ -102,7 +102,7 @@ def project_plan(config: ProjectConfig, ref: str, root: str, run: Git = git) -> return default_plan(root, ref, plan_stores.store(config), stores.store(config, "changelog"), config.titles, run) -def default_plan(root: str, ref: str, plan: plan_stores.PlanStore, changelog: stores.RecordStore, titles: templates.Titles, run: Git = git) -> DefaultPlan: +def default_plan(root: str, ref: str, plan: plans.PlanStore, changelog: stores.RecordStore, titles: templates.Titles, run: Git = git) -> DefaultPlan: """What ref, the default branch as last fetched, holds for the pick, read in the checkout at root through run. plan is the store the project's config names for its plan, changelog the store it names for the changelog, and titles its title templates.""" tag = newest_tag(root, merged_into=ref, run=run) changes = stores.held_at(ref, changelog, root, run) @@ -153,41 +153,57 @@ def todos_since(tag: str | None | Failure, ref: str, plan: str | None, cwd: str, return texts -def chunk_item(found: list[Item], cut: LastCut) -> Pick: - """The pick from todo.md's items, weighed against the last cut. Routing and chunk-preflight both pick with it, so they name one item.""" - upcoming = next_release(found, cut) - return standing(upcoming, next_item(carried(found, cut)), cut.reviewed) if isinstance(upcoming, Upcoming) else upcoming +@dataclasses.dataclass(frozen=True) +class Standing: + """The plan's items weighed once against the last cut, which next_release, picked and chunk-preflight all read.""" + # Which version is cut, as cut_version says. + version: Release | None + # The releases todo.md has named since the cut, as named_releases reads them. + named: set[Release] | Failure + # The plan's items, each one filed under the last cut's version or earlier moved to the next release: the earliest after the cut that the plan holds or todo.md has named since. Someone cut a release while it still held those items, and the loop works on (lilleman, 2026-11-16). Where nothing is cut, or no release after the cut is known, the items stay as the plan files them, since naming a release is the human's. + carried: list[Item] + # The IDs of the items carried files under another release than the plan does, in the plan's order. + moved: tuple[int, ...] -def carried(found: list[Item], cut: LastCut) -> list[Item]: - """found, with the release of each item that the plan files under the last cut's version, or an earlier one, replaced by the next release: the earliest after the cut that the plan holds or todo.md has named since it. - - Someone cut a release while it held those items, and the loop works on: lilleman's call, 2026-11-16. found itself where nothing is cut, and where no release after the cut is known, since naming one is the human's. - """ +def standing_of(found: list[Item], cut: LastCut) -> Standing: + """found, the plan's items, weighed against cut.""" version = cut_version(cut) named = named_releases(cut.todos_since) known = {item.release for item in found} | (set() if isinstance(named, Failure) else named) after = set() if version is None else {release for release in known if release > version} if not after or all(item.release >= min(after) for item in found): - return found - return [dataclasses.replace(item, release=max(item.release, min(after))) for item in found] + return Standing(version, named, found, ()) + held = [dataclasses.replace(item, release=max(item.release, min(after))) for item in found] + return Standing(version, named, held, tuple(was.id for was, now in zip(found, held) if was.release != now.release)) -def next_release(found: list[Item], cut: LastCut) -> Upcoming | Cut | Unknown: - """The next release after cut, and whether work has landed towards it. found holds the plan's items. +def chunk_item(found: list[Item], cut: LastCut) -> Pick: + """The pick from the plan's items, weighed against the last cut. Routing and chunk-preflight both pick with it, so they name one item.""" + return picked(standing_of(found, cut), cut) - Cut where the plan files items under the last cut's version or earlier and no later release is known for carried to file them under, and Unknown where the tags, or todo.md's texts since the cut, cannot be read. + +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 + + +def next_release(weighed: Standing, cut: LastCut) -> Upcoming | Cut | Unknown: + """The next release after cut, and whether work has landed towards it. weighed holds the plan's items, weighed against cut. + + Cut where the plan files items under the last cut's version or earlier and no later release is known to carry them to, and Unknown where the tags, or todo.md's texts since the cut, cannot be read. Where the branch has no tag, todos_since holds every version of todo.md, so a release todo.md named whose items are all done still reads as the next release. """ if isinstance(cut.tag, Failure): return Unknown() - earliest = min((item.release for item in carried(found, cut)), default=None) - version = cut_version(cut) + earliest = min((item.release for item in weighed.carried), default=None) + version = weighed.version if version is None: return Upcoming(earliest, True, has_unreleased(cut)) if earliest is not None and earliest <= version: return Cut(earliest) - named = named_releases(cut.todos_since) + named = weighed.named if isinstance(named, Failure): return Unknown() after = {release for release in named if release > version} @@ -219,12 +235,12 @@ def has_unreleased(cut: LastCut) -> bool | Failure: return changes if isinstance(changes, Failure) else changes > 0 -def standing(upcoming: Upcoming, first: Item | None, reviewed: bool | Failure) -> Next | ReadyToCut | ReviewDue | Unplanned | Unknown: +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. 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.is_earliest: + if upcoming.plan_is_current: return Next(upcoming.release, first) if isinstance(upcoming.unreleased, Failure): return Unknown() @@ -242,9 +258,9 @@ def unreleased_changes(cut: LastCut) -> int | Failure: def unreleased_entries(changelog: str) -> int | None: - """How many top-level `- ` entries CHANGELOG.md holds under ## Unreleased; None without that section.""" - found = sections(changelog).get("Unreleased") - return None if found is None else sum(line.startswith("- ") for line in found[0].splitlines()) + """How many top-level `- ` entries CHANGELOG.md holds under its unreleased section, whose heading's title UNRELEASED_TITLE matches; None without that section.""" + body = section(changelog, UNRELEASED_TITLE) + return None if body is None else sum(line.startswith("- ") for line in body) def named_releases(todos: list[str] | Failure) -> set[Release] | Failure: diff --git a/bin/release_plan/test_release_standing.py b/bin/release_plan/test_release_standing.py index b1f564c7..3c9491d5 100644 --- a/bin/release_plan/test_release_standing.py +++ b/bin/release_plan/test_release_standing.py @@ -10,20 +10,29 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from project_config.templates import BARE, Titles from project_config.settings import DEFAULT_FLOOR, ProjectConfig, SETTINGS from failure import Failure -from plan_store.stores import FilePlan, plan_of +from plan_store.todo_md import FilePlan, plan_of from record_store.stores import FileStore from test_env import isolated_env from record_store.fakes import MemoryStore -from release_plan.todo_table import NoItemsTable -from release_plan import release_standing -from release_plan import todo_table -from release_plan.release import version +from release_plan import next_chunk, release_standing +from plan.todo_table import NoItemsTable +from plan_store.plans import Plan +from plan import todo_table +from plan.release import version HEADER = "## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n" ROW = "| {id} | {release} | | | **Do {id}.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n" +def next_of(found: list[todo_table.Item], cut: release_standing.LastCut) -> release_standing.Upcoming | release_standing.Cut | release_standing.Unknown: + return release_standing.next_release(release_standing.standing_of(found, cut), cut) + + +def carried_of(found: list[todo_table.Item], cut: release_standing.LastCut) -> list[todo_table.Item]: + return release_standing.standing_of(found, cut).carried + + def plan_at(path: pathlib.Path, tracked: str | None) -> FilePlan: """The markdown plan at path, which these tests only read.""" return FilePlan(path, tracked, FileStore(path.parent / "README.md", None), MemoryStore(), MemoryStore(), DEFAULT_FLOOR) @@ -68,40 +77,41 @@ class NextRelease(unittest.TestCase): ) for tag, earliest, named, upcoming in cases: with self.subTest(tag=tag, earliest=earliest, named=named): - self.assertEqual(release_standing.next_release(plan_under(earliest), release_standing.LastCut(tag, "", 4, naming(named))), upcoming) + self.assertEqual(next_of(plan_under(earliest), release_standing.LastCut(tag, "", 4, naming(named))), upcoming) def test_says_work_has_landed_towards_it_where_a_change_is_unreleased(self): cut = lambda changes: release_standing.LastCut("v1.2.3", "", changes, naming({(1, 3, 0)})) - self.assertEqual(release_standing.next_release([one((1, 3, 0))], cut(4)), release_standing.Upcoming((1, 3, 0), True, True)) - self.assertEqual(release_standing.next_release([one((1, 3, 0))], cut(0)), release_standing.Upcoming((1, 3, 0), True, False)) - self.assertEqual(release_standing.next_release([one((1, 3, 0))], cut(Failure("count unreadable"))), release_standing.Upcoming((1, 3, 0), True, Failure("count unreadable"))) + self.assertEqual(next_of([one((1, 3, 0))], cut(4)), release_standing.Upcoming((1, 3, 0), True, True)) + self.assertEqual(next_of([one((1, 3, 0))], cut(0)), release_standing.Upcoming((1, 3, 0), True, False)) + self.assertEqual(next_of([one((1, 3, 0))], cut(Failure("count unreadable"))), release_standing.Upcoming((1, 3, 0), True, Failure("count unreadable"))) class Carried(unittest.TestCase): def test_files_each_item_of_a_release_already_cut_under_the_earliest_release_the_plan_names_after_the_cut(self): held = [dataclasses.replace(one((1, 2, 3)), id=1), dataclasses.replace(one((1, 2, 0)), id=2), dataclasses.replace(one((1, 4, 0)), id=3), dataclasses.replace(one((1, 3, 0)), id=4)] - carried = release_standing.carried(held, release_standing.LastCut("v1.2.3", "", 4, [])) + carried = carried_of(held, release_standing.LastCut("v1.2.3", "", 4, [])) self.assertEqual([(item.id, item.release) for item in carried], [(1, (1, 3, 0)), (2, (1, 3, 0)), (3, (1, 4, 0)), (4, (1, 3, 0))]) def test_leaves_the_plan_as_it_is_where_nothing_is_cut_or_it_names_no_release_after_the_cut(self): held = [one((1, 2, 3))] for tag in ("v1.2.3", "v1.2.2", None, Failure("tags unreadable")): with self.subTest(tag=tag): - self.assertIs(release_standing.carried(held, release_standing.LastCut(tag, "", 4, [])), held) + self.assertIs(carried_of(held, release_standing.LastCut(tag, "", 4, [])), held) def test_files_them_under_a_release_todo_md_named_since_the_cut_though_the_plan_holds_no_item_of_it(self): held = [one((1, 2, 3)), dataclasses.replace(one((1, 4, 0)), id=2)] cut = release_standing.LastCut("v1.2.3", "", 4, naming({(1, 2, 3), (1, 3, 0)})) - self.assertEqual([item.release for item in release_standing.carried(held, cut)], [(1, 3, 0), (1, 4, 0)]) + self.assertEqual([item.release for item in carried_of(held, cut)], [(1, 3, 0), (1, 4, 0)]) + self.assertEqual(release_standing.standing_of(held, cut).moved, (held[0].id,)) self.assertEqual(release_standing.chunk_item(held, cut), release_standing.Next((1, 3, 0), dataclasses.replace(held[0], release=(1, 3, 0)))) - self.assertEqual(release_standing.carried(held[:1], dataclasses.replace(cut, todos_since=Failure("log unreadable"))), held[:1]) + self.assertEqual(carried_of(held[:1], dataclasses.replace(cut, todos_since=Failure("log unreadable"))), held[:1]) def test_takes_the_cut_releases_item_first_as_the_next_releases(self): held = [dataclasses.replace(one((1, 2, 3)), id=1), dataclasses.replace(one((1, 3, 0)), id=2)] cut = release_standing.LastCut("v1.2.3", "", 4, []) self.assertEqual(release_standing.chunk_item(held, cut), release_standing.Next((1, 3, 0), dataclasses.replace(held[0], release=(1, 3, 0)))) - self.assertEqual(release_standing.next_release(held, cut), release_standing.Upcoming((1, 3, 0), True, True)) - self.assertEqual(release_standing.next_release(held[:1], cut), release_standing.Cut((1, 2, 3))) + self.assertEqual(next_of(held, cut), release_standing.Upcoming((1, 3, 0), True, True)) + self.assertEqual(next_of(held[:1], cut), release_standing.Cut((1, 2, 3))) class ChunkItem(unittest.TestCase): @@ -292,7 +302,7 @@ class ChunkItem(unittest.TestCase): 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.todo, plan_of(HEADER + ROW.format(id=1, release="0.2.0"))) + 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(release_standing.chunk_item(plan_under((0, 2, 0)), held.cut), release_standing.Next((0, 2, 0), one((0, 2, 0)))) @@ -305,17 +315,17 @@ class ChunkItem(unittest.TestCase): run("add", "todo.md") 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.todo, NoItemsTable, "neither file exists yet") + self.assertIsInstance(held.plan, NoItemsTable, "neither file exists yet") self.assertEqual(held.cut, release_standing.LastCut(None, "", 1, [], False)) 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.todo, plan_of(plan)) + 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") (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.todo, unreadable.cut.todos_since), (Failure(f"{folder}/todo.md: not UTF-8"), [])) + self.assertEqual((unreadable.plan, unreadable.cut.todos_since), (Failure(f"{folder}/todo.md: not UTF-8"), [])) def test_reads_the_checkout_only_through_the_git_it_is_given(self): repo = tempfile.mkdtemp() @@ -343,6 +353,10 @@ class ChunkItem(unittest.TestCase): self.assertEqual(release_standing.unreleased_entries("# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n"), 2) self.assertEqual(release_standing.unreleased_entries("# Changelog\n\n## Unreleased\n\n## 0.1.0\n\n- Old.\n"), 0) self.assertIsNone(release_standing.unreleased_entries("# Changelog\n\n## 0.1.0\n\n- Old.\n")) + # A heading inside a code fence doesn't end the section. + self.assertEqual(release_standing.unreleased_entries("# Changelog\n\n## Unreleased\n\n- One.\n\n```\n## 0.1.0\n```\n\n- Two.\n\n## 0.1.0\n\n- Old.\n"), 2) + # The section todo-item finish files a bullet under, as a project's own changelog may head it. + self.assertEqual(release_standing.unreleased_entries("# Changelog\n\n## 0.6.0 (unreleased)\n\n- One.\n\n## 0.5.0\n\n- Old.\n"), 1) def test_names_each_release_a_todo_md_since_the_last_cut_filed_items_under(self): texts = [HEADER + ROW.format(id=1, release="0.2.0"), "", "not a table | x |", HEADER + ROW.format(id=2, release="0.3.0")] @@ -367,3 +381,11 @@ class ChunkItem(unittest.TestCase): def test_fails_to_name_releases_when_the_newest_plan_marks_one_in_a_form_it_cannot_read(self): plan = "## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n| 1 | 0.3.0 | | | **Do 1.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n" self.assertIsInstance(release_standing.named_releases([plan, plan + "\n## Renamed\n\nsoon\n"]), Failure) + + +class NextChunk(unittest.TestCase): + def test_names_the_release_a_carried_item_moved_to_not_another_items(self): + later, carried, next_one = (dataclasses.replace(one(release), id=id_) for id_, release in ((9, (0, 4, 0)), (5, (0, 2, 0)), (3, (0, 3, 0)))) + planned = next_chunk.planned(Plan([later, carried, next_one]), release_standing.LastCut("v0.2.0", "", 4, []), "origin/main", "item-{id}") + assert isinstance(planned, next_chunk.NextChunk), planned + self.assertEqual(planned.carried, next_chunk.CarriedOver((0, 3, 0), (5,))) diff --git a/bin/repo_checks/test_package_cycles.py b/bin/repo_checks/test_package_cycles.py new file mode 100644 index 00000000..88636a3d --- /dev/null +++ b/bin/repo_checks/test_package_cycles.py @@ -0,0 +1,56 @@ +import ast +import graphlib +import pathlib +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from repo_checks import ROOT + + +def package_imports(bin_folder: pathlib.Path) -> dict[str, set[str]]: + """Each package under bin_folder, with the other packages its modules import, tests aside. A deferred import inside a function counts: it only hides a cycle.""" + packages = {init.parent.name for init in bin_folder.glob("*/__init__.py")} + imported: dict[str, set[str]] = {package: set() for package in packages} + for package in packages: + for module in (bin_folder / package).rglob("*.py"): + if module.name.startswith("test_"): + continue + 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 [node.module or ""] if isinstance(node, ast.ImportFrom) and node.level == 0 else [] + imported[package].update(top for name in names if (top := name.split(".")[0]) in packages and top != package) + return imported + + +def cycle(imported: dict[str, set[str]]) -> list[str]: + """One cycle among the packages, as the packages along it; empty where there is none.""" + try: + graphlib.TopologicalSorter(imported).prepare() + except graphlib.CycleError as found: + return list(found.args[1]) + return [] + + +class PackageCycles(unittest.TestCase): + def test_no_package_under_bin_imports_one_that_imports_it_back(self): + self.assertEqual(cycle(package_imports(ROOT / "bin")), [], "move what both packages need into a package that imports neither") + + def test_reads_an_import_deferred_into_a_function_and_leaves_out_tests(self): + with tempfile.TemporaryDirectory() as temp: + folder = pathlib.Path(temp) + for package, source in (("a", "def f():\n\tfrom b.mod import x\n"), ("b", "import a.mod\n"), ("c", "")): + (folder / package).mkdir() + (folder / package / "__init__.py").write_text("") + (folder / package / "mod.py").write_text(source) + (folder / "c" / "test_mod.py").write_text("import a\n") + self.assertEqual(package_imports(folder), {"a": {"b"}, "b": {"a"}, "c": set()}) + + 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()}), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/rest_client/test_json_request.py b/bin/rest_client/test_json_request.py index b98a0cc2..3e030eb9 100644 --- a/bin/rest_client/test_json_request.py +++ b/bin/rest_client/test_json_request.py @@ -30,6 +30,9 @@ class Recorded(http.server.BaseHTTPRequestHandler): def do_POST(self) -> None: self.answer() + def do_PUT(self) -> None: + self.answer() + def answer(self) -> None: length = int(self.headers.get("Content-Length") or 0) self.server.got.append((self.command, self.path, dict(self.headers), self.rfile.read(length))) # type: ignore[attr-defined] @@ -50,7 +53,9 @@ class Recorded(http.server.BaseHTTPRequestHandler): pass -class HttpJson(unittest.TestCase): +class Served(unittest.TestCase): + """A test case with a local server that answers by a script; it holds no test itself, so a test elsewhere may build on it.""" + def serve(self, *script: tuple[int, bytes]) -> str: server = http.server.HTTPServer(("127.0.0.1", 0), Recorded) server.script = list(script) # type: ignore[attr-defined] @@ -61,6 +66,8 @@ class HttpJson(unittest.TestCase): self.server = server return f"http://127.0.0.1:{server.server_port}" + +class HttpJson(Served): def test_sends_the_authorization_and_the_body_as_json_and_reads_the_json_answer(self): base = self.serve((201, b'{"id": "post-id"}')) self.assertEqual(send("POST", f"{base}/api/v4/posts", "secret-token", {"message": "hi"}), {"id": "post-id"}) diff --git a/bin/routing_figures/test_routing_figures.py b/bin/routing_figures/test_routing_figures.py index 2840812e..559b8793 100644 --- a/bin/routing_figures/test_routing_figures.py +++ b/bin/routing_figures/test_routing_figures.py @@ -25,7 +25,7 @@ from claude_code.entries import entry_from from failure import Failure from git_cli import git_repo from test_env import isolated_env -from release_plan.todo_table import Item +from plan.todo_table import Item from transcript_archive import outcomes, write from model_routing.ladder_file import read_ladder, SHIPPED from routing_figures.render import render diff --git a/bin/rule_hook/main.py b/bin/rule_hook/main.py index 8ad20317..93c95ea8 100644 --- a/bin/rule_hook/main.py +++ b/bin/rule_hook/main.py @@ -140,10 +140,12 @@ def commit_breaches(commit: CommitCall, home: pathlib.Path) -> list[Breach]: if isinstance(config, Failure) and not isinstance(config, Unnamed): unread = [Breach("commit-title", f"the project's config cannot be read, so the title is not checked against its template: {config.reason}", commit.directory)] titles = config.titles if isinstance(config, ProjectConfig) else templates.BARE - return unread + title_breaches(commit, titles, isinstance(config, ProjectConfig) and on_item_branch(commit.directory, config.branch)) + round_cap_breaches(commit, titles) + todo_breaches(commit.directory, home) + # A checkout no config names has no branch template, so no title of its must fit one. + branch = checkout_branch(commit.directory) if isinstance(config, ProjectConfig) else None + return unread + title_breaches(commit, titles, config.branch if isinstance(config, ProjectConfig) else templates.BRANCH, branch) + round_cap_breaches(commit, titles) + todo_breaches(commit.directory, home) -def on_item_branch(directory: str, template: str) -> bool: - """Whether directory's checkout is on a branch that fits template, the config's `branch`: a plan item's branch, whose commits carry the item's ID. Any other branch, such as a release review's, has no item to give {id}.""" +def checkout_branch(directory: str) -> str | None: + """The branch directory's checkout is on; None where HEAD is detached or git cannot tell.""" branch = guarded_git(directory, "symbolic-ref", "--quiet", "--short", "HEAD") - return not isinstance(branch, Failure) and templates.branch_fits(template, branch) + return None if isinstance(branch, Failure) else branch.strip() diff --git a/bin/rule_hook/rules.py b/bin/rule_hook/rules.py index 67341976..7a138522 100644 --- a/bin/rule_hook/rules.py +++ b/bin/rule_hook/rules.py @@ -7,7 +7,7 @@ from review_rules.round_titles import CAP, COUNTS, EXAMPLE, lacks_counts, OPENIN from git_cli.git_command import CommitCall from run_heavy.capped_docker import finds_this_docker from rule_hook.heavy_command import heavy -from command_lines.shell_command import launched, Simple +from command_lines.shell_command import launched, LAUNCHERS, Simple from review_rules.review_folder import REPORTS from project_config import templates from command_lines.docker_command import unlimited @@ -88,7 +88,7 @@ RULES: dict[RuleName, Rule] = { ), "run-heavy": Rule( "a heavy command, which loads the machine for minutes, runs under ~/.claude/bin/run-heavy, so sessions running at once cannot starve the machine", - "a docker build, docker buildx build or docker compose build, and a run of mutate-changes, or of cargo mutants, Infection, mutmut or Stryker, the mutation tools it runs, whether direct, through a launcher such as uvx, or inside docker run, docker exec or docker compose run or exec. A gate script is not checked, since no program can tell it from a light one", + "a docker build, docker buildx build or docker compose build, and a run of mutate-changes, or of cargo mutants, Infection, mutmut or Stryker, the mutation tools it runs, whether direct, through a launcher (" + ", ".join(sorted(LAUNCHERS - {"run-heavy"})) + "), or inside docker run, docker exec or docker compose run or exec. A gate script is not checked, since no program can tell it from a light one", ), "todo-rank-check": Rule( "while todo.md has changes, staged or not, a git commit waits until rank_todo.py --check passes on it: the checkout's own bin/rank_todo.py where the checkout is of this setup's repo, else ~/.claude/bin/rank_todo.py", @@ -165,15 +165,15 @@ def command_breaches(command: str, simples: list[Simple]) -> list[Breach]: return breaches -def title_breaches(commit: CommitCall, titles: templates.Titles, held: bool) -> list[Breach]: - """The breaches of the commit's message, read through titles, the project's title templates. held is whether the title must fit the commit template: it must on a branch that fits the config's `branch` template.""" +def title_breaches(commit: CommitCall, titles: templates.Titles, branch_template: str, branch: str | None) -> list[Breach]: + """The breaches of the commit's message, read through titles, the project's title templates. branch is the checkout's branch, None where it has none, and branch_template the config's `branch`: templates.misfits says when the title must fit the commit template.""" breaches = [] if commit.from_file: breaches.append(Breach("commit-one-line", "pass the message as one -m '<line>', not from a file", commit.directory)) elif len(commit.messages) > 1 or any("\n" in message.strip() for message in commit.messages): breaches.append(Breach("commit-one-line", "pass the message as one -m '<line>', with no heredoc, second -m or newline", commit.directory)) # A message of several lines breaks commit-one-line above, which says how to fix it. - if held and (misfit := [message for message in commit.messages[:1] if "\n" not in message.strip() and not templates.fits(titles.commit, message.strip())]): + if misfit := [message for message in commit.messages[:1] if "\n" not in message.strip() and templates.misfits(titles.commit, branch_template, branch, message)]: breaches.append(Breach("commit-title", f"title the commit as the project's config asks, `{titles.commit}`, where {{id}} is the ID of the chunk's first item; `{misfit[0].strip()[:80]}` doesn't fit", commit.directory)) if any(lacks_counts(titles.summary(message.strip())) for message in commit.messages): breaches.append(Breach("round-title-counts", f"open the summary after the round's colon with `{COUNTS}`, where <j> is at most <k> + <m>", commit.directory)) diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index 4e691b2e..4ed00ba6 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -20,7 +20,7 @@ from rule_hook.main import breaches_of from rule_hook.call import Call, parsed_call from git_cli.git_command import commit_message, CommitCall, commits from project_config.test_project_config import configured, write_config -from release_plan.test_ranking import DECISIONS, README, TODO +from plan.test_ranking import DECISIONS, README, TODO from rule_hook.git import guarded_git from test_env import isolated_env from rule_hook.override_log import LogLine, parsed_entry, this_chunks @@ -44,7 +44,7 @@ def committed(command: str, cwd: str = "/r") -> list[CommitCall]: def breaches(command: str, titles: Titles = BARE, held: bool = False) -> list[Breach]: """The command's breaches and those of each commit's title, read through titles; held is whether the title must fit the commit template.""" simples = simple_commands(command, "/r", "/h") - return command_breaches(command, simples) + [breach for commit in commits(simples, "/h") for breach in title_breaches(commit, titles, held)] + return command_breaches(command, simples) + [breach for commit in commits(simples, "/h") for breach in title_breaches(commit, titles, "item-{id}", "item-7" if held else "main")] def checked(command: str) -> list[str]: @@ -125,7 +125,7 @@ class CommandBreaches(unittest.TestCase): self.assertEqual(checked("git commit -m 'Answer the question in the README'"), []) def test_a_docker_build_or_a_mutation_run_outside_run_heavy_breaks_run_heavy(self): - for command in ["docker build -t x .", "cd /w && docker buildx build .", "docker compose build", "docker compose -f x.yml --verbose build app", "uvx --with pytest 'mutmut>=3,<4' run", "cargo mutants --in-diff d", "npx stryker run", "vendor/bin/infection --git-diff-lines", "docker compose run --rm app mutmut run", "docker run --rm -m 4g --memory-swap 4g -v /w:/w rust:1.90.0 cargo mutants", "docker compose exec app npx stryker run", "docker run -h box -m 4g --memory-swap 4g rust:1.90.0 cargo mutants", "nice -n 19 docker build .", "env DOCKER_BUILDKIT=1 docker build .", "time -p docker compose build", "docker --tlscacert ca.pem build .", "docker --tlscert c.pem --tlskey k.pem build .", "docker buildx --builder b build .", "docker container run -m 4g --memory-swap 4g rust:1.90.0 cargo mutants", "uvx mutmut --verbose run", "~/.claude/bin/mutate-changes", "cd /w && mutate-changes --base main"]: + for command in ["docker build -t x .", "sudo docker build -t x .", "doas docker build .", "uv run mutmut run", "uv run --with pytest mutmut run", "poetry run mutmut run", "cd /w && docker buildx build .", "docker compose build", "docker compose -f x.yml --verbose build app", "uvx --with pytest 'mutmut>=3,<4' run", "cargo mutants --in-diff d", "npx stryker run", "vendor/bin/infection --git-diff-lines", "docker compose run --rm app mutmut run", "docker run --rm -m 4g --memory-swap 4g -v /w:/w rust:1.90.0 cargo mutants", "docker compose exec app npx stryker run", "docker run -h box -m 4g --memory-swap 4g rust:1.90.0 cargo mutants", "nice -n 19 docker build .", "env DOCKER_BUILDKIT=1 docker build .", "time -p docker compose build", "docker --tlscacert ca.pem build .", "docker --tlscert c.pem --tlskey k.pem build .", "docker buildx --builder b build .", "docker container run -m 4g --memory-swap 4g rust:1.90.0 cargo mutants", "uvx mutmut --verbose run", "~/.claude/bin/mutate-changes", "cd /w && mutate-changes --base main"]: with self.subTest(command): self.assertEqual(checked(command), ["run-heavy"]) diff --git a/bin/rule_hook/todo_check.py b/bin/rule_hook/todo_check.py index a06468ab..0a938af3 100644 --- a/bin/rule_hook/todo_check.py +++ b/bin/rule_hook/todo_check.py @@ -6,11 +6,11 @@ import sys from rule_hook.rules import Breach from failure import Failure +from plan_store.stores import file_plan from git_cli.git_repo import git from rule_hook.git import guarded_git from project_config.settings import held, ProjectConfig from project_config.main import located -from release_plan import plan_file # The checkout this hook runs from: bin/rule_hook/ sits two folders below it. @@ -60,7 +60,7 @@ def check_failures(top: str, todo: pathlib.Path, config: ProjectConfig, own: pat """Why rank_todo.py --check fails on todo. A checkout of the repo the hook runs from checks with its own bin/rank_todo.py, so a branch that changes the table's shape is held to its own rules. Any other checkout checks with the hook's ranking: running its script would run its code before every commit.""" script = pathlib.Path(top) / "bin" / "rank_todo.py" if not script.is_file() or not same_repo(top, own): - return plan_file.check_failures(todo, config) + return file_plan(config, todo).check() try: ran = subprocess.run([sys.executable, str(script), "--check", str(todo)], capture_output=True, cwd=top, text=True, timeout=OWN_CHECK_SECONDS) except subprocess.TimeoutExpired: diff --git a/bin/score_outcomes/anchors.py b/bin/score_outcomes/anchors.py index f1929b32..c69ac495 100644 --- a/bin/score_outcomes/anchors.py +++ b/bin/score_outcomes/anchors.py @@ -1,6 +1,6 @@ import re -from release_plan.todo_table import cells, LEVELS, parse_ids +from plan.todo_table import cells, LEVELS, parse_ids from failure import Failure from score_outcomes.results import render, Result diff --git a/bin/score_outcomes/main.py b/bin/score_outcomes/main.py index 71d08e5f..d3c9452f 100644 --- a/bin/score_outcomes/main.py +++ b/bin/score_outcomes/main.py @@ -98,9 +98,9 @@ from branch_chunks.read import branch_chunks, unsupported from git_cli.git_repo import default_branch, full_history, git, top from failure import Failure from score_outcomes.results import file_lines, fixed_later, item_text, misreads, nearest, render, report, Result, results_of -from release_plan.todo_table import item_details, LEVELS, risk, TOP_SCORE +from plan.todo_table import item_details, LEVELS, risk, TOP_SCORE from text_files.markdown_text import listed -from release_plan.named_code import named_files +from plan.named_paths import named_files from project_config.main import project, title_templates from transcript_archive.location import project_archive from score_outcomes.reversals import reversal_lines diff --git a/bin/score_outcomes/results.py b/bin/score_outcomes/results.py index 05b725e5..ced5d19a 100644 --- a/bin/score_outcomes/results.py +++ b/bin/score_outcomes/results.py @@ -4,9 +4,9 @@ import typing from branch_chunks.cut import BranchChunk, Landing, NOT_WORK from review_rules.round_titles import Findings, round_findings, rounds_past_first -from release_plan.todo_table import Item +from plan.todo_table import Item from text_files.markdown_text import listed -from release_plan.named_code import named_files +from plan.named_paths import named_files # Fewest single-item chunks a score needs before its medians print: the 10 figures the reading-cost trend waits for; no published standard sets either. ENOUGH = 10 diff --git a/bin/score_outcomes/test_score_outcomes.py b/bin/score_outcomes/test_score_outcomes.py index 845b9e94..a2ac7adc 100644 --- a/bin/score_outcomes/test_score_outcomes.py +++ b/bin/score_outcomes/test_score_outcomes.py @@ -15,7 +15,7 @@ from failure import Failure from score_outcomes.results import file_lines, NamedCode, nearest, rank_correlation, render, report, Result, results_of from review_rules.round_titles import Findings from test_env import isolated_env -from release_plan.todo_table import Item +from plan.todo_table import Item from transcript_archive import outcomes from transcript_archive.location import project_archive from score_outcomes.main import read_anchors, report_text diff --git a/bin/subagent_rung/main.py b/bin/subagent_rung/main.py index 35c9d387..11620c24 100644 --- a/bin/subagent_rung/main.py +++ b/bin/subagent_rung/main.py @@ -23,7 +23,7 @@ import sys from failure import Failure from model_routing.ladder import Ladder -from release_plan.todo_table import LEVELS +from plan.todo_table import LEVELS from model_routing.ladder_file import project_ladder_file, read_ladder USAGE = f"usage: subagent-rung [--plan] <model> <L>, L a level from 1 to {LEVELS['L']}" diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py index 3d7d386e..0fd76442 100644 --- a/bin/test_rank_todo.py +++ b/bin/test_rank_todo.py @@ -8,9 +8,9 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from project_config.test_project_config import configured -from release_plan.test_ranking import DECISIONS, OLD_SHAPE, README, TODO +from plan.test_ranking import DECISIONS, OLD_SHAPE, README, TODO from project_config.settings import DEFAULT_FLOOR -from release_plan import goals_file, ranking +from plan import goals_file, ranking import rank_todo diff --git a/bin/todo_item/edits.py b/bin/todo_item/edits.py index 76bff07b..ff17f340 100644 --- a/bin/todo_item/edits.py +++ b/bin/todo_item/edits.py @@ -2,10 +2,11 @@ import re from failure import Failure +from plan.release import UNRELEASED_HEADING UNRELEASED = "## Unreleased" -# The changelog's section for news not yet released: ## Unreleased, or a release heading such as `## 0.6.0 (unreleased)`. -UNRELEASED_SECTION = re.compile(r"^## .*unreleased.*\n+", re.M | re.I) +# UNRELEASED_HEADING with the blank lines below it, after which a bullet goes first. +UNRELEASED_SECTION = re.compile(UNRELEASED_HEADING.pattern + r"\n+", UNRELEASED_HEADING.flags) def with_bullet(changelog: str, bullet: str) -> str | Failure: diff --git a/bin/todo_item/main.py b/bin/todo_item/main.py index 8ee84947..cde0c3ab 100644 --- a/bin/todo_item/main.py +++ b/bin/todo_item/main.py @@ -78,11 +78,12 @@ import pathlib import sys import typing -from release_plan.todo_table import BLOCKED_BY, MOVES +from plan.todo_table import BLOCKED_BY, MOVES from failure import Failure from project_config.main import located -from release_plan.release import parsed, Release, version as release_version -from plan_store.stores import store as plan_store, PlanStore, TAGLINE, Written +from plan_store.plans import no_item, PlanStore, TAGLINE, Written +from plan.release import parsed, Release, version as release_version +from plan_store.stores import store as plan_store from record_store.stores import RecordStore, store from todo_item.table import shown, table from todo_item.edits import with_bullet @@ -202,7 +203,7 @@ def show(args: argparse.Namespace, plan: PlanStore) -> str | Failure: if isinstance(read, Failure): return read found = next((item for item in read.items if item.id == args.id), None) - return Failure(f"{plan.label} holds no item {args.id}") if found is None else f"From {plan.label}:\n\n{shown(found)}" + return Failure(no_item(plan.label, args.id)) if found is None else f"From {plan.label}:\n\n{shown(found)}" def edit(args: argparse.Namespace, plan: PlanStore, text: str) -> str | Failure: @@ -217,9 +218,10 @@ def edit(args: argparse.Namespace, plan: PlanStore, text: str) -> str | Failure: def finish(args: argparse.Namespace, plan: PlanStore, changelog: RecordStore) -> str | Failure: - news = changelog.read() - if isinstance(news, Failure): - return Failure(f"not finished: {news.reason}") + held = changelog.held() + if isinstance(held, Failure): + return Failure(f"not finished: {held.reason}") + news = held.text if news and args.changelog is None and not args.no_changelog: return Failure(f"not finished: {changelog.label} exists; pass --changelog <bullet>, or --no-changelog where the repo doesn't publish anything or no chunk built the item") # The bullet is checked before the plan changes: where finish refuses the bullet, the plan and the changelog stay as they were. @@ -227,6 +229,7 @@ def finish(args: argparse.Namespace, plan: PlanStore, changelog: RecordStore) -> if isinstance(added, Failure): return Failure(f"not finished: {added.reason}") done = reported(plan.finish(args.id), "not finished", lambda written: f"Finished item {written.id} in {plan.label}.") - if not isinstance(done, Failure) and added is not None and (unwritten := changelog.write(added)): - return Failure(f"{unwritten.reason}; the plan no longer holds item {args.id}, so add its bullet by hand") + written = changelog.write(added, held.version) if not isinstance(done, Failure) and added is not None else None + if isinstance(written, Failure): + return Failure(f"{written.reason}; the plan no longer holds item {args.id}, so add its bullet by hand") return done diff --git a/bin/todo_item/table.py b/bin/todo_item/table.py index 7b1ab558..4d599876 100644 --- a/bin/todo_item/table.py +++ b/bin/todo_item/table.py @@ -1,28 +1,17 @@ """How todo-item prints items: as rows of the table `rank_todo.py --help` shows, whatever backend holds the plan, without the Score a markdown plan alone has.""" -from release_plan.todo_table import BLOCKED_BY, Item, OLD_SHAPE, SHAPE, Shape -from release_plan.release import version +from plan.todo_table import detail_heading, Item, items_shape, row_cells, tagline_text def table(items: list[Item]) -> str: """A markdown table of items, in their order.""" - shape = shape_of(items) + shape = items_shape(items) columns = [column for column in shape.columns if column != "Score"] - return "\n".join(["| " + " | ".join(columns) + " |", "|" + "---|" * len(columns), *(row(item, shape) for item in items)]) - - -def shape_of(items: list[Item]) -> Shape: - """OLD_SHAPE where an item holds a score only that shape has, as a plan not yet reshaped does.""" - return OLD_SHAPE if any(set(item.scores) - set(SHAPE.score_columns) for item in items) else SHAPE - - -def row(item: Item, shape: Shape) -> str: - named = {"ID": item.id, "Release": version(item.release), BLOCKED_BY: ", ".join(str(id_) for id_ in item.blocked_by), "Exempt": item.exempt, "Item": item.tagline, shape.goals_column: shape.write_goals(item.moves), **item.scores} - return "| " + " | ".join(str(named.get(column, "")) for column in shape.columns if column != "Score") + " |" + rows = [row_cells(item, shape) for item in items] + return "\n".join(["| " + " | ".join(columns) + " |", "|" + "---|" * len(columns), *("| " + " | ".join(row.get(column, "") for column in columns) + " |" for row in rows)]) def shown(item: Item) -> str: """item's row under the table's header, then its detail under the heading a markdown plan gives it; the row alone where it has no detail.""" if not item.detail: return table([item]) - tagline = item.tagline.removeprefix("**").removesuffix("**").replace("\\|", "|") - return f"{table([item])}\n\n### {item.id}. {tagline}\n\n{item.detail}" + return f"{table([item])}\n\n{detail_heading(item.id, tagline_text(item.tagline))}\n\n{item.detail}" diff --git a/bin/todo_item/test_todo_item.py b/bin/todo_item/test_todo_item.py index 39a5ec1a..f63a798b 100644 --- a/bin/todo_item/test_todo_item.py +++ b/bin/todo_item/test_todo_item.py @@ -8,14 +8,15 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent)) from project_config.test_project_config import configured -from release_plan.test_ranking import DECISIONS, README, TODO +from plan.test_ranking import DECISIONS, README, TODO from project_config.settings import DEFAULT_FLOOR from todo_item import edits, main from failure import Failure +from plan_store.stores import file_plan from project_config.main import located from plan_store.fakes import MemoryPlan -from release_plan import plan_file, ranking -from plan_store.stores import plan_of +from plan_store.todo_md import plan_of +from plan import ranking from todo_item.table import table ADD = ["add", "--release", "0.1.0", "--l", "1", "--e", "1", "--i", "1", "--s", "1", "--moves", "1 by 9", "Count the `a | b` runs."] @@ -58,7 +59,7 @@ class TodoItem(unittest.TestCase): return raised.exception.code def assert_ranked(self): - self.assertEqual(plan_file.check_failures(self.todo, located(str(self.folder), pathlib.Path.home())), []) + self.assertEqual(file_plan(located(str(self.folder), pathlib.Path.home()), self.todo).check(), []) def details(self): text = self.todo.read_text() @@ -457,7 +458,7 @@ class Move(TodoItem): def test_writes_nothing_where_it_refuses(self): before = self.todo.read_text() - self.assertEqual(self.run_main("move", "3", "--release", "soon"), (1, "", "not moved: item 3's release 'soon' is not a semver version\n")) + self.assertEqual(self.run_main("move", "3", "--release", "soon"), (1, "", "not moved: item 3's Release 'soon' is not a semver version, such as 1.2.0\n")) self.assertEqual(self.run_main("move", "99", "--release", "0.2.0"), (1, "", f"not moved: {self.todo} holds no item 99\n")) self.assertEqual(self.todo.read_text(), before) @@ -467,9 +468,9 @@ class OtherFile(TodoItem): config = located(str(self.folder), pathlib.Path.home()) other = self.folder / "other.md" other.write_text("not a plan\n") - self.assertNotEqual(plan_file.check_failures(other, config), []) - self.assertIsInstance(plan_file.rank_file(other, config), Failure) - self.assertEqual(plan_file.check_failures(self.todo, config), []) + self.assertNotEqual(file_plan(config, other).check(), []) + self.assertIsInstance(file_plan(config, other).rank(), Failure) + self.assertEqual(file_plan(config, self.todo).check(), []) class Table(unittest.TestCase): diff --git a/bin/touch_predictions/beside.py b/bin/touch_predictions/beside.py index 35150a66..5acae9cd 100644 --- a/bin/touch_predictions/beside.py +++ b/bin/touch_predictions/beside.py @@ -2,7 +2,7 @@ import dataclasses from failure import Failure -from release_plan.todo_table import Item, waiting +from plan.todo_table import Item, waiting from touch_predictions.prediction import LABEL, overlaps, predicted, Touches diff --git a/bin/touch_predictions/main.py b/bin/touch_predictions/main.py index 03bdc1ac..c24d79c6 100644 --- a/bin/touch_predictions/main.py +++ b/bin/touch_predictions/main.py @@ -44,8 +44,9 @@ cannot be read; or when git cannot name the merge base or the diff. """ import sys import time +import typing -from git_cli.git_repo import default_ref, git +from git_cli.git_repo import default_ref, git, Git from failure import Failure from plan_store.stores import store as plan_store from touch_predictions.prediction import predicted, together, Touches @@ -73,8 +74,8 @@ def main(argv: list[str]) -> int: return 0 -def recorded(config: ProjectConfig, ids: list[int]) -> str | Failure: - """Appends the entry of the chunk that takes the items ids, and says so; or says that the project keeps no record.""" +def recorded(config: ProjectConfig, ids: list[int], now: typing.Callable[[], float] = time.time, run: Git = git) -> str | Failure: + """Appends the entry of the chunk that takes the items ids, stamped at now and read from the commits run shows, and says so; or says that the project keeps no record.""" store = touch_predictions_store(config) if store is None: return f"The project's config sets no `{TOUCH_PREDICTIONS}`, so nothing is recorded." @@ -82,17 +83,17 @@ def recorded(config: ProjectConfig, ids: list[int]) -> str | Failure: if isinstance(prediction, Failure): return prediction cwd = str(config.top) - default = default_ref(cwd) - base = default if isinstance(default, Failure) else git("merge-base", default, "HEAD", cwd=cwd) - head = base if isinstance(base, Failure) else git("rev-parse", "--short", "HEAD", cwd=cwd) + default = default_ref(cwd, run=run) + base = default if isinstance(default, Failure) else run("merge-base", default, "HEAD", cwd=cwd) + head = base if isinstance(base, Failure) else run("rev-parse", "--short", "HEAD", cwd=cwd) if isinstance(base, Failure) or isinstance(head, Failure): return head if isinstance(head, Failure) else base # Every chunk writes the plan and the records, so they are left out of what a chunk touched. skipped = {path for name in ("plan", *RECORDS, TOUCH_PREDICTIONS) if (path := config.tracked(name))} - touches = touched(base.strip(), "HEAD", cwd, skipped) + touches = touched(base.strip(), "HEAD", cwd, skipped, run) if isinstance(touches, Failure): return touches - failed = record.append(store, ids, record.entry(ids, utc(time.time()), head.strip(), prediction, touches)) + failed = record.append(store, ids, record.entry(ids, utc(now()), head.strip(), prediction, touches)) return failed or f"Recorded what chunk {', '.join(map(str, ids))} was predicted to touch, and what it touched, in {store.label}." diff --git a/bin/touch_predictions/record.py b/bin/touch_predictions/record.py index ef274388..d0c1f2fc 100644 --- a/bin/touch_predictions/record.py +++ b/bin/touch_predictions/record.py @@ -20,8 +20,9 @@ def listed(label: str, touches: Touches | None) -> str: def append(store: RecordStore, items: list[int], text: str) -> Failure | None: """Appends text, the entry of the chunk that took items, in place of each entry the record holds for the same items: a fix after the first entry changes what the chunk touched.""" - held = store.read() + held = store.held() if isinstance(held, Failure): return held - kept = re.sub(rf"^## Chunk {', '.join(map(str, items))}, {STAMPED},.*?(?=^## |\Z)", "", held, flags=re.M | re.S) - return store.write(f"{kept.rstrip() or TITLE}\n\n{text}") + kept = re.sub(rf"^## Chunk {', '.join(map(str, items))}, {STAMPED},.*?(?=^## |\Z)", "", held.text, flags=re.M | re.S) + written = store.write(f"{kept.rstrip() or TITLE}\n\n{text}", held.version) + return written if isinstance(written, Failure) else None diff --git a/bin/touch_predictions/test_touch_predictions.py b/bin/touch_predictions/test_touch_predictions.py index b5ee5dbe..ea2109e4 100644 --- a/bin/touch_predictions/test_touch_predictions.py +++ b/bin/touch_predictions/test_touch_predictions.py @@ -9,12 +9,14 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from touch_predictions.beside import Beside, chunks_beside -from touch_predictions import diff_parts, file_parts, record +from touch_predictions import diff_parts, file_parts, main, record from failure import Failure from test_env import isolated_env +from project_config.main import located from record_store.fakes import MemoryStore from touch_predictions.prediction import overlaps, Part, predicted, rendered, together -from plan_store.stores import plan_of +from plan_store.todo_md import plan_of +from project_config.settings import ProjectConfig from project_config.test_project_config import write_config DETAIL = """A planning call. @@ -412,6 +414,11 @@ class EntryTest(unittest.TestCase): self.assertEqual([line.split(" at ")[1] for line in store.text.splitlines() if line.startswith("## ")], ["ccccccc", "ddddddd", "eeeeeee"]) self.assertEqual(store.text.count("\n\n\n"), 0) + def test_writes_over_the_version_it_read(self) -> None: + store = MemoryStore("", version=3) + record.append(store, [5], "## Chunk 5, 2026-01-01T00:00:00Z, at aaaaaaa\n") + self.assertEqual(store.overs, ["3"]) + def test_a_record_that_cannot_be_read_is_a_failure(self) -> None: self.assertEqual(record.append(MemoryStore(fails="no disk"), [5], "x"), Failure("no disk")) @@ -451,6 +458,13 @@ class RecordCommandTest(unittest.TestCase): assert entry is not None self.assertEqual(entry.group(1), "Predicted:\n\n- `app.py`: `run`\n\nTouched:\n\n- `app.py`: `run`, `stop`\n") + def test_stamps_the_entry_at_the_clock_it_is_handed(self) -> None: + path = self.set_record() + config = located(str(self.checkout), self.home) + assert isinstance(config, ProjectConfig), config + self.assertNotIsInstance(main.recorded(config, [3], now=lambda: 0.0), Failure) + self.assertIn("## Chunk 3, 1970-01-01T00:00:00Z, at ", path.read_text(encoding="utf-8")) + def test_a_second_run_replaces_the_entry_and_leaves_the_record_out_of_what_was_touched(self) -> None: path = self.set_record() self.record("record", "3") diff --git a/docs/comprehension-history.md b/docs/comprehension-history.md index c43bae3a..4ed80692 100644 --- a/docs/comprehension-history.md +++ b/docs/comprehension-history.md @@ -3979,3 +3979,35 @@ Inherited architect, would restructure first: - Locality: `bin/loop_claude/loop/close.py:18` `closed_cycle`: a second "close" beside `cycle/run.py:234` `close` - Navigation, Shape: `README.md:197` the `bin/` package list: 74 entries at one level with the README's list as the only index - Self-sufficiency: `bin/loop_claude/loop/routing_check.py:1` the module docstring: names `state.CYCLES_PER_CHECK` without saying which module `state` is + +## 2026-11-16T15:57:39Z, PR #562 at 31da587, against 64454f8 + +Ruling: better + +| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall | +|---|---|---|---|---|---| +| Mid A | better | better | better | same | better | +| Inherited architect | better | better | better | better | better | + +Mid A, decided by: + +- Locality, Shape: `bin/plan_store/stores.py:1` `store`: the 234-line module holding the protocol, the markdown backend, the Jira scoring and a deferred import of jira_epic is now a 40-line factory beside `plans.py`, `todo_md.py` and `scoring.py`, with no cycle to keep in mind +- Locality: `bin/record_store/stores.py:34` `RecordStore.write`: the Confluence store's hidden `seen` and `kept` file gave way to `held()` and `write(text, over)`, so a save is followed without knowing the store's history +- Navigation, Shape: `bin/release_plan/next_chunk.py:57` `planned`: the next chunk's pick moved out of chunk-preflight's internals beside the release standing, and its `Plan` became `NextChunk`, no longer clashing with the store's `Plan` +- Locality, Shape: `bin/release_plan/release_standing.py:169` `standing_of`: the plan is weighed against the cut once, where `carried`, `cut_version` and `named_releases` ran in three places +- Navigation, Shape: `bin/atlassian/client.py:1` `client`: Confluence's auth no longer lives in the Jira plan backend +- Navigation: `bin/notifier/notify.py:10` `BACKENDS`: both DM backends sit in the notifier's folder +- Shape: `bin/rank_todo.py:119` `main`: one write path, through `FilePlan.rank()`, in place of `plan_file.py`'s copy + +Inherited architect, decided by: + +- Locality, Shape: `bin/record_store/confluence_page.py:84` `ConfluencePage.write`: the concurrency check shows in the call signature, where it hung on which earlier read ran in which process +- Shape, Locality: `bin/repo_checks/test_package_cycles.py:13` `package_imports`: the deferred imports that hid the plan packages' cycles are gone, a neutral `atlassian` package holds the shared client, and a test enforces the rule +- Navigation, Shape: `bin/release_plan/next_chunk.py:57` `planned`: the pick no longer lives in one CLI's package, and its type is named `NextChunk` +- Shape: `bin/plan_store/stores.py:18` `store`: the store is split by purpose, and `release_plan/` is no longer a grab bag +- Locality: `bin/release_plan/release_standing.py:169` `standing_of`: weighed once, with `plan_is_current` and `pick_from` naming what they do +- Locality: `bin/plan/todo_table.py:294` `item_fields`: one check of an item's cells for every backend +- Locality: `bin/plan_store/plans.py:57` `no_item`: the coupling between chunk-pr and todo-item's message has a name +- Locality: `bin/chunk_pr/main.py:130` `step`: the config is passed in once, where `misfit` shelled out to `project-config` twice +- Shape: `bin/project_config/settings.py:320` `SCALARS`: one row per one-value setting, where `load` handled each at four sites +- Navigation, Self-sufficiency: `bin/chunk_preflight/gathered.py:60` `Gathered.plan`: a stale pointer to `choices.plan_name`, with two more in `next_chunk.py` and the README, small next to the gains diff --git a/docs/decisions.md b/docs/decisions.md index 7d384661..a0280db4 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -97,7 +97,7 @@ Valid while a chunk's worker runs `chunk-pr merge` itself, and one machine runs 2026-10-22, lilleman, through todo item 217. Serves goal 1.4: each review has a fixed cost, so more items per chunk cost less per item. Across the 165 finished chunks loop-claude archived up to that day, a chunk took a median of 1.30M tokens with one item and 1.33M with two, and three in four chunks shipped one item. The old rule also asked one PR title to state what the items achieve together; lilleman dropped it, since unrelated items that fire the same passes cost one review. -The cap is 5, `bin/release_plan/todo_table.py`'s `BUNDLE_MAX_R`, from the same chunks: by the highest R among a chunk's items, the median was 0.9M to 1.5M tokens at R 1 to 5, and 2.7M at R 6, where the 90th percentile was 8.8M. A risky item that runs long re-runs review over every item bundled with it. R 5 is also the least R an I 4 item gets, so an item that could take everything down shares a chunk only where its L + E is 3 or less, and an irreversible I 5 item, at R 7 or more, never does. Valid while a review's cost is mostly fixed per chunk; revisit once 30 chunks have shipped bundles under it. +The cap is 5, `bin/plan/todo_table.py`'s `BUNDLE_MAX_R`, from the same chunks: by the highest R among a chunk's items, the median was 0.9M to 1.5M tokens at R 1 to 5, and 2.7M at R 6, where the 90th percentile was 8.8M. A risky item that runs long re-runs review over every item bundled with it. R 5 is also the least R an I 4 item gets, so an item that could take everything down shares a chunk only where its L + E is 3 or less, and an irreversible I 5 item, at R 7 or more, never does. Valid while a review's cost is mostly fixed per chunk; revisit once 30 chunks have shipped bundles under it. ## comprehension floor: every dimension and the overall at the project's readability floor or above is the target, and no score blocks a merge or release @@ -220,7 +220,7 @@ Valid while cache reads cost a twentieth of input and Claude Code's compaction k ## machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available -2026-10-23, lilleman. Serves goal 1.5. On 2026-10-22 ai-sandbox, with 8 CPUs and 16 GiB, thrashed for hours: four to six loops ran mutation tests, full gates, `docker build`s and QEMU-booting e2e tests at once, and nothing told one loop how busy the machine was. lilleman chose both limits; no standard sets either, and GNU parallel's `--memfree`, which does the memory wait's job, has no default. A slot is a file lock, so a session that dies frees its slot. The memory wait reads `/proc/meminfo` only, and off Linux a worker starts at once. `bin/machine_load/` holds the slots and the memory share, `bin/run-heavy` takes a slot, `CLAUDE.md` → "Working with the codebase" has every session use it, and loop-claude's worker waits for the share. rule-hook's rule `run-heavy` blocks a `docker build`, and a run of a mutation tool stability-reviewer names, outside run-heavy, in the forms its `checked` text in `bin/rule_hook/rules.py` lists. 2026-11-04, lilleman: other forms, such as `uv run mutmut run` or `sudo docker build`, pass until one becomes a problem. No program can tell a gate script from a light one, so only `CLAUDE.md` asks a session to run a gate under run-heavy. Valid while one machine runs several loops at once. +2026-10-23, lilleman. Serves goal 1.5. On 2026-10-22 ai-sandbox, with 8 CPUs and 16 GiB, thrashed for hours: four to six loops ran mutation tests, full gates, `docker build`s and QEMU-booting e2e tests at once, and nothing told one loop how busy the machine was. lilleman chose both limits; no standard sets either, and GNU parallel's `--memfree`, which does the memory wait's job, has no default. A slot is a file lock, so a session that dies frees its slot. The memory wait reads `/proc/meminfo` only, and off Linux a worker starts at once. `bin/machine_load/` holds the slots and the memory share, `bin/run-heavy` takes a slot, `CLAUDE.md` → "Working with the codebase" has every session use it, and loop-claude's worker waits for the share. rule-hook's rule `run-heavy` blocks a `docker build`, and a run of a mutation tool stability-reviewer names, outside run-heavy, in the forms its `checked` text in `bin/rule_hook/rules.py` lists. 2026-11-16, lilleman: rule-hook checks a run through `uv run`, `poetry run`, `sudo` and `doas` too, such as `uv run mutmut run` and `sudo docker build`, since project principle 4 has a program enforce a rule it can check. The 2026-11-04 note had let such forms pass until one became a problem. No program can tell a gate script from a light one, so only `CLAUDE.md` asks a session to run a gate under run-heavy. Valid while one machine runs several loops at once. ## machine load: every container a session starts has a memory limit and a swap limit as large as its work needs; rule-hook's `docker-run-memory` blocks a `docker run` or `docker create` without them outside run-heavy, under which a container that lacks them gets the slot's share of three quarters of the memory; and no daemon-wide cap limits all containers together @@ -306,8 +306,8 @@ Valid while the later fixes per finished chunk, which `score-outcomes` and the r - **A bench of readers picked the spelling.** Three fresh readers, seated as the person who writes a client's `config.toml`, each picked `decisions = "confluence:https://<site>/wiki/spaces/<space>/pages/<page ID>"`, pasted from the browser with or without the title at its end, over the bare address, a page ID beside a `confluence-site` key, and a table. Each named the match with `jira:`. Any of the five records may name a page; the goals file, the plan, the working rules and the principles may not. - **`decisions` and `comprehension-history` may name a page only where `plan` names a Jira epic.** rule-hook ranks a plan kept as a file before tool calls, inside its 30-second limit, and ranking reads those two records. A Confluence read and two adf-codec container runs would hold up every guarded tool call, and fail it while Confluence is down. `load` refuses goals in Jira beside a plan in a file for the same reason. -- **A write sends the version number the store read, plus one, and Confluence refuses it with 409 where someone saved the page since.** The store then fails, saying to ask the human, and doesn't write the page; the loop never overwrites a teammate's edit on its own (lilleman, 2026-11-12). A write with no read before it replaces the page as it stands, as the record contract asks. -- **`project-record` keeps the version `open` read in a file beside its copy**, `~/.local/state/project-record/<key>/<worktree>/<record>.version`, since `save` runs in a later process. The store keeps the version itself, so `write` still takes only the text. Every other tool reads and writes a record in one process, and its store keeps the version in memory, so a read by another tool, such as larv-review's, never moves the version an edit in `project-record` rests on. The folder `<worktree>` is named for the worktree that ran `open`, and `open` removes the folders of worktrees git no longer lists, so a chunk's copy doesn't outlive its worktree. +- **A write sends the version number it writes over, plus one, and Confluence refuses it with 409 where someone saved the page since.** The store then fails, saying to ask the human, and doesn't write the page; the loop never overwrites a teammate's edit on its own (lilleman, 2026-11-12). A write handed no version replaces the page as it stands, as the record contract asks. +- **A store keeps no version: its caller hands each write the version it writes over.** lilleman chose this on 2026-11-16, when 0.11.0's release review found the version kept as the store's hidden state, which made a write rest on whichever read came before it. `project-record` keeps the version `open` read in a file beside its copy, `~/.local/state/project-record/<key>/<worktree>/<record>.version`, since `save` runs in a later process, and each save keeps the version it left for the next. Every other tool writes over the version its own read gave, so a read by another tool, such as larv-review's, never moves the version an edit in `project-record` rests on. The folder `<worktree>` is named for the worktree that ran `open`, and `open` removes the folders of worktrees git no longer lists, so a chunk's copy doesn't outlive its worktree. - **The page holds ADF, which adf-codec converts both ways**, so a teammate reads the record as Confluence renders it. Where adf-codec cannot convert the markdown, the write fails with adf-codec's error. A node markdown cannot hold reads as text: a mention as its name, a macro as `_(<macro> not included)_`. So the next write replaces it with that text, and a record page should hold only what markdown can. ## project config: a tool that reads a file's commits says where it does not support that file, and the work goes on @@ -405,7 +405,7 @@ Valid while Claude Code passes `agent_type` to hooks inside a subagent. Without ## review: the comprehension check records how hard a project is to read, and no score blocks a merge: a paired ruling against the last measured commit in the release review, and the four-seat scoring run, once when an item names the floor and twice on one head when a release's items run out -2026-10-08, lilleman. Serves goals 1.1 and 1.4. Two independent four-seat runs moved up to 0.4 on near-identical code, so a fall within that noise forced rounds that didn't change anything (PR #224). A seat reading both versions judges the difference on the same material, so the noise the versions share cancels. No conventional significance level lets a sign test settle with four votes, so the human chose a lead of two votes over every other ruling, same included. Two seats that agree settle it, so a PR that leaves the reading as it was costs two seats. A third seat alone can never settle it, so the third and fourth launch together. The scoring run also runs on a chunk shipping an item that names the floor, so the chunk that lifts a project to the floor can prove it. A chunk that removes a release's last item without shipping it runs the scoring run too, so no release ends unmeasured, unless `todo.md` marks that release renamed in a `## Renamed` section (`bin/release_plan/todo_table.py` → `renames`). Valid while seats reading both versions agree more often than two absolute runs do. +2026-10-08, lilleman. Serves goals 1.1 and 1.4. Two independent four-seat runs moved up to 0.4 on near-identical code, so a fall within that noise forced rounds that didn't change anything (PR #224). A seat reading both versions judges the difference on the same material, so the noise the versions share cancels. No conventional significance level lets a sign test settle with four votes, so the human chose a lead of two votes over every other ruling, same included. Two seats that agree settle it, so a PR that leaves the reading as it was costs two seats. A third seat alone can never settle it, so the third and fourth launch together. The scoring run also runs on a chunk shipping an item that names the floor, so the chunk that lifts a project to the floor can prove it. A chunk that removes a release's last item without shipping it runs the scoring run too, so no release ends unmeasured, unless `todo.md` marks that release renamed in a `## Renamed` section (`bin/plan/todo_table.py` → `renames`). Valid while seats reading both versions agree more often than two absolute runs do. 2026-10-13, lilleman. No published study validates simulated reader panels as a measure of how easy code is to understand, and no test of whether the panel's signal beats its noise has run. So no ruling, score or floor blocks a merge. The runs go on, so the history keeps the scores and the places the seats found hard, for later measurement. The architect, the stability reviewer and a session filing an item read the newest places: the newest scoring run's and each later ruling's places a seat voted worse. Those are the places a chunk can improve. The check runs once per chunk, on the branch as review left it. A chunk that leaves a touched place as hard says why in its PR summary, not in a decline's record, which would outlive the place. @@ -556,7 +556,7 @@ Since 2026-10-16 the reviewers may run above the worker's rung, on the one the h ## routing: loop-claude reads the items a chunk takes from the worker's latest `Chunk items:` line and scores them by `todo.md` as the default branch held it when the cycle started; the judge reports the escalation and whether a release is ready to cut -2026-11-11, claude. Serves goal 1.4 and code health. The judge's reply held three facts beside its verdict: the items the worker took into the chunk, with their highest L and E + I; whether a release was ready to cut; and any escalation the worker asked for. Routing lifts the worker's and the reviewers' rungs by the items' levels. Code now reads the items: each chunk's first prompt, and each prompt resuming it, asks the worker for a line opening `Chunk items:`, `bin/loop_claude/cycle/chunk_items.py` reads the latest such line in the worker's own text, and `release_plan.todo_table` scores the items. So the judge's reply is smaller, and every L and E + I that routing reads comes from `todo.md`, through one module. +2026-11-11, claude. Serves goal 1.4 and code health. The judge's reply held three facts beside its verdict: the items the worker took into the chunk, with their highest L and E + I; whether a release was ready to cut; and any escalation the worker asked for. Routing lifts the worker's and the reviewers' rungs by the items' levels. Code now reads the items: each chunk's first prompt, and each prompt resuming it, asks the worker for a line opening `Chunk items:`, `bin/loop_claude/cycle/chunk_items.py` reads the latest such line in the worker's own text, and `plan.todo_table` scores the items. So the judge's reply is smaller, and every L and E + I that routing reads comes from `todo.md`, through one module. The judge field trials (`judge-field-trials/`) read each fact by code over the 709 archived cases. Code was wrong in each of the 39 cases where it and the judge disagreed on an escalation, and read a release ready to cut in 3 of the 31 interrupts that asked about a cut, so the judge keeps both. Workers stated an item with its L and E + I in 413 cases, but also stated items they filed, finished or only mentioned, so the worker writes the items on a line that holds only them, which code reads. Three fresh readers picked its label `Chunk items:`, 3 to 0, because it says the items are the chunk's. @@ -600,7 +600,7 @@ A project's rung is its model's cheapest rung, which for Opus 5.5 is its default 2026-11-11, lilleman approved the rungs for Fable 5.2 from the index read that day. Its score and cost per task, for each effort from low to max: Sonnet 5.5 26 $0.51, 31 $0.78, 42 $1.64, 50 $4.09, 55 $10.02; Opus 5.5 35 $0.98, 48 $2.45, 52 $3.46, 57 $6.05, 59 $10.04; Fable 5.2 54 $3.10, 56 $3.80, 62 $9.08, 62 $14.83, 65 $26.54. The cut drops Opus 5.5 at high, since Fable 5.2 at low scores more for less; Opus 5.5 at max, since Fable 5.2 at high scores more for less; and Fable 5.2 at xhigh, which ties Fable 5.2 at high at a higher cost. Sonnet 5.5 at high stays the bottom rung, as the 2026-10-29 note chose. With Haiku 5.5 off, the cut alone would also keep Sonnet 5.5 at low and medium and Opus 5.5 at low, below it. On an Opus 5.5 project, an L 4 worker, an E + I 5 review and a worker's first escalation now run on Fable 5.2 at low, where they ran on Opus 5.5 at high; E + I 8 runs on Fable 5.2 at high, where it ran on Fable 5.1 at max. Three steps land on a rung the index scores lower than before: E + I 6 on Fable 5.2 at medium, 56 against Opus 5.5 at xhigh's 57; E + I 7 on Opus 5.5 at xhigh, 57 against Opus 5.5 at max's 59; and an L 3 worker's escalation stops, without lilleman's yes, at Fable 5.2 at medium, where it stopped at Opus 5.5 at xhigh. On a Sonnet 5.5 project, E + I 6 runs on Fable 5.2 at low, 54 against Opus 5.5 at high's 52; E + I 7 on Fable 5.2 at medium, 56 against Opus 5.5 at xhigh's 57; and E + I 8 on Opus 5.5 at xhigh, 57 against Opus 5.5 at max's 59. Fable 5.2 at max, on top, is reached only one rung up from Fable 5.2 at high, as by a reviewer's rerun. A Fable 5.2 project's rung is Fable 5.2 at low, so its L 1 and L 2 workers run on Opus 5.5 at medium. -2026-11-14, lilleman ruled that L 3 is to step one rung up and L 4 two up, in every project and for delegated subagents. The steps stated above, L 3 none and L 4 one up, hold until `bin/model_routing/ladder.py` changes. Then, on an Opus 5.5 project, an L 3 worker or subagent runs on Fable 5.2 at low, and an escalation stops without lilleman's yes at Opus 5.5 at xhigh. An L 4 one runs on Fable 5.2 at medium, and stops at Fable 5.2 at high. The ruling settles the two calls of the routing figures measured at 2026-11-14T00:59:50Z, which were not yet in `routing-calls-raised.md`; the chunk that settles them cites their stamp there. The figures came from 276 chunks finished since the 2026-10-29 reset. Chunks started on Opus 5.5 at medium, 79 of them, took a mean 0.8 review rounds past each pass's first, 0.3 unfinished verdicts and 0.2 later fixes. Chunks started on Fable 5.2 at low, 5 of them, took 0.4, 0.0 and 0.0. On an Opus 5.5 project only L 4 items start on Fable 5.2 at low, so it did better on harder items. Two things weaken the evidence: 5 chunks is the fewest a call allows, and the Opus 5.5 figures include chunks from before Fable 5.2 joined the ladder. On the 2026-11-11 index, an L 3 task's cost rises about 1.3 times, from $2.45 to $3.10, for fewer rounds and fewer unfinished verdicts (goal 1.4). The chunks started on Sonnet 5.5 at high, 164 of the 276, don't move. +2026-11-14, lilleman ruled that L 3 is to step one rung up and L 4 two up, in every project and for delegated subagents. The steps stated above, L 3 none and L 4 one up, hold until `bin/model_routing/ladder.py` changes, which `todo.md` item 393 does in 0.12.0, as lilleman chose on 2026-11-16. Then, on an Opus 5.5 project, an L 3 worker or subagent runs on Fable 5.2 at low, and an escalation stops without lilleman's yes at Opus 5.5 at xhigh. An L 4 one runs on Fable 5.2 at medium, and stops at Fable 5.2 at high. The ruling settles the two calls of the routing figures measured at 2026-11-14T00:59:50Z, which were not yet in `routing-calls-raised.md`; the chunk that settles them cites their stamp there. The figures came from 276 chunks finished since the 2026-10-29 reset. Chunks started on Opus 5.5 at medium, 79 of them, took a mean 0.8 review rounds past each pass's first, 0.3 unfinished verdicts and 0.2 later fixes. Chunks started on Fable 5.2 at low, 5 of them, took 0.4, 0.0 and 0.0. On an Opus 5.5 project only L 4 items start on Fable 5.2 at low, so it did better on harder items. Two things weaken the evidence: 5 chunks is the fewest a call allows, and the Opus 5.5 figures include chunks from before Fable 5.2 joined the ladder. On the 2026-11-11 index, an L 3 task's cost rises about 1.3 times, from $2.45 to $3.10, for fewer rounds and fewer unfinished verdicts (goal 1.4). The chunks started on Sonnet 5.5 at high, 164 of the 276, don't move. 2026-11-15, lilleman asked for the ladder as a file that a project can replace, on a day when an outage left only Fable 5.2 answering: the rungs were a constant in `bin/model_routing/ladder.py`, so no project could leave Sonnet 5.5 and Opus 5.5 without a release. The shipped ladder is `bin/model_routing/routing-ladder.json`, a JSON list of rungs, least competent first. A project that keeps a `routing-ladder.json` in its config's folder, `~/.claude-projects/<key>/`, runs on that ladder whole, and the steps count on it as on the shipped one. Every project still runs the same routing rules and steps, so the workflow of goal 1.3 holds; the ladder joins what a project's config folder may supply, which that goal's list does not name yet. lilleman chose a file per project over one per machine, so a single project can differ. A ladder holds one model of each family, since the Agent tool launches a subagent or a review by its family's name. The project's file is lilleman's to write, as any change to the ladder is, and the loop never commits it. loop-claude reads the project's ladder as each cycle starts; `subagent-rung` and rule-hook's `reviewer-rung` read it each time they run, from the checkout they run in. A ladder file that holds a fault stops each of them, since work routed on the shipped ladder in its place could run on a model the project cannot reach. The routing figures, `judge-replay` and `review-replay` span every project, so they read the shipped ladder: a rung only a project's own ladder holds is left out of the figures' calls, and no replay qualifies it. lilleman shipped the change as 0.10.1, a patch cut from the tag v0.10.0, on the day of the outage: it adds a file format and an exit 1 to `subagent-rung`, which the technical principles' semantic versioning gives a minor, and lilleman asked for the patch "even if that breaks semver", so that the release in use could run again without taking the unreleased work on `main`. @@ -748,9 +748,9 @@ Valid while loop-claude starts a project's chunks side by side by this pick (`bi 2026-10-15, lilleman. Serves goal 1.4: loop-claude routes a chunk's first cycle on the item the chunk takes (`routing: a chunk's worker runs on the rung its item's L picks`). An item lists the items that must be done before it starts in a Blocked by column, and `rank_todo.py` ranks each blocker above every item it blocks. The table's order is `todo.md`'s only order: `rank_todo.py` fails on text beside the table under `## Items`, since a prose order there, "Release 0.3.0 takes items 125, 114 and 124 first", contradicted the table and loop-claude could not read it. A decision that wants an order sets the scores instead. An item waits while it is marked `question` or a blocker of it is still in the table, whatever the rows' order, so a release's first row that does not wait is the item a chunk takes. A blocker the table no longer holds was finished or deleted, and is dropped, so the cell shows what still blocks. A panel of three readers seated as lilleman picked the spelling: two ranked "Blocked by" first, as the cell lists only what still blocks, and all three chose bare IDs such as `12, 14` in a column right after Release, read before the tagline and kept apart from the scores. `rank_todo.py` adds the column to a table without it. The tools read cells by column name, so a later column leaves a reader on an older release working; `rank_todo.py`, which writes every column, fails on one it does not know rather than drop it. -2026-10-18, PR #312. Serves goals 1.5 and 1.1: adf-codec renamed its next release, 0.2.1, to 0.3.0, and `chunk-preflight` then called 0.2.1 finished and stopped the loop on every cycle. A change that moves a release's last items elsewhere reads the same whether it renamed the release or deferred its leftovers, so the plan says which: a `## Renamed` section holds one line `- 0.2.1 renamed to 0.3.0` per rename, which `bin/release_plan/todo_table.py`'s `renames` reads. `chunk-preflight`, `loop-claude` and larv-review's scoring-run trigger skip a marked release; they read only the first version. A release whose items moved unmarked reads as finished: the loop stops, says so and names the fix, and the trigger calls a scoring run once work has landed. So a forgotten mark costs one interrupt and never lets a release end unmeasured. `rank_todo.py` fails on a line of another shape and on an item filed under a marked release, and a newest plan whose marks do not parse leaves the next release unknown. A line goes once a tag at or past its release is cut. Only a rename is marked, since an unmarked move is the deferral. A panel of three readers seated as lilleman picked the spelling 3-0 over `- 0.2.1 → 0.3.0` under `## Releases` and a `Renamed 0.2.1 = 0.3.0` line under `## Scoring`: plain words need no special character to type. Valid while a rename is the only move of a release's items that the tools must tell from finishing it. +2026-10-18, PR #312. Serves goals 1.5 and 1.1: adf-codec renamed its next release, 0.2.1, to 0.3.0, and `chunk-preflight` then called 0.2.1 finished and stopped the loop on every cycle. A change that moves a release's last items elsewhere reads the same whether it renamed the release or deferred its leftovers, so the plan says which: a `## Renamed` section holds one line `- 0.2.1 renamed to 0.3.0` per rename, which `bin/plan/todo_table.py`'s `renames` reads. `chunk-preflight`, `loop-claude` and larv-review's scoring-run trigger skip a marked release; they read only the first version. A release whose items moved unmarked reads as finished: the loop stops, says so and names the fix, and the trigger calls a scoring run once work has landed. So a forgotten mark costs one interrupt and never lets a release end unmeasured. `rank_todo.py` fails on a line of another shape and on an item filed under a marked release, and a newest plan whose marks do not parse leaves the next release unknown. A line goes once a tag at or past its release is cut. Only a rename is marked, since an unmarked move is the deferral. A panel of three readers seated as lilleman picked the spelling 3-0 over `- 0.2.1 → 0.3.0` under `## Releases` and a `Renamed 0.2.1 = 0.3.0` line under `## Scoring`: plain words need no special character to type. Valid while a rename is the only move of a release's items that the tools must tell from finishing it. -2026-11-09, lilleman. Serves goal 1.1: a test, gate leg or probe that guards a maintain goal proves the output holds it, and an item that adds one scored V 0 and ranked last. adf-codec's item 170 bundles the package with four bundlers to back its goal 8, runs on any JavaScript engine, and scored 0.0 beside items that move an achieve goal by 2. Such an item now names the maintain goal in Moves, by how much more confident the project becomes that the goal holds, 1 to 10, judged against the confidence it already has; `rules/todo-items.md` holds the scale. The goal weighs 0.5 per point of that move, `MAINTAIN_WEIGHT` in `bin/release_plan/ranking.py`. A defect that restores a broken maintain goal weighs it as the heaviest achieve goal, or 0.5 where that is lighter, since a broken goal outranks any achieve goal and any confidence gain; a maintain goal still vetoes an item that breaks it. The 0.5 comes from 150 distinct item and Moves pairs in 40 random `todo.md` commits from 2026-09-24 to 2026-11-09. The V their scores imply has quartiles 1.4, 2.6 and 4.5, and the median item earns 0.49 per point it moves a goal. At 0.5, a move of 10 is worth 5.0, about the third quartile; a move of 5 is worth 2.5, the median; a move of 1 is worth 0.5, under the tenth percentile, so only a cheap item ships. Valid while the achieve goals' weights and the formula's F keep the typical item's V near that distribution; a change to either revisits the 0.5. 2026-11-10, lilleman: the 0.5 does not change with the number of achieve goals. fejkdata has 11 achieve goals, code health included, and each weighs at most 0.105 per point, or 0.42 for code health while its comprehension overall is under 7.0, so a maintain goal's 0.5 outweighs each of them. Revisit the 0.5 when that becomes a problem, such as maintain items ranking above achieve items the human would take first. +2026-11-09, lilleman. Serves goal 1.1: a test, gate leg or probe that guards a maintain goal proves the output holds it, and an item that adds one scored V 0 and ranked last. adf-codec's item 170 bundles the package with four bundlers to back its goal 8, runs on any JavaScript engine, and scored 0.0 beside items that move an achieve goal by 2. Such an item now names the maintain goal in Moves, by how much more confident the project becomes that the goal holds, 1 to 10, judged against the confidence it already has; `rules/todo-items.md` holds the scale. The goal weighs 0.5 per point of that move, `MAINTAIN_WEIGHT` in `bin/plan/ranking.py`. A defect that restores a broken maintain goal weighs it as the heaviest achieve goal, or 0.5 where that is lighter, since a broken goal outranks any achieve goal and any confidence gain; a maintain goal still vetoes an item that breaks it. The 0.5 comes from 150 distinct item and Moves pairs in 40 random `todo.md` commits from 2026-09-24 to 2026-11-09. The V their scores imply has quartiles 1.4, 2.6 and 4.5, and the median item earns 0.49 per point it moves a goal. At 0.5, a move of 10 is worth 5.0, about the third quartile; a move of 5 is worth 2.5, the median; a move of 1 is worth 0.5, under the tenth percentile, so only a cheap item ships. Valid while the achieve goals' weights and the formula's F keep the typical item's V near that distribution; a change to either revisits the 0.5. 2026-11-10, lilleman: the 0.5 does not change with the number of achieve goals. fejkdata has 11 achieve goals, code health included, and each weighs at most 0.105 per point, or 0.42 for code health while its comprehension overall is under 7.0, so a maintain goal's 0.5 outweighs each of them. Revisit the 0.5 when that becomes a problem, such as maintain items ranking above achieve items the human would take first. ## todo.md: only a session or subagent on the project's rung or above scores or reshapes the plan; one below it drafts new items and changes to filed ones for a subagent at or above that rung to apply and score, and removes finished ones @@ -760,11 +760,11 @@ Three places carry the rule. `rules/todo-items.md` states it; it loads with `tod ## todo.md: tools and agents read and change the plan as it stands only through `bin/plan_store` and `todo-item`; a tool that reads what a past commit held, ranks the file or checks its rank still parses `todo.md` -2026-11-14, the worker of todo item 350. Serves goal 1.6: a client keeps its plan where its team works, so no tool or agent may assume a file. `bin/plan_store/stores.py` holds the interface, `PlanStore`, and its markdown backend, `FilePlan`; `contract.py` holds the tests every backend passes, as `bin/record_store/` does for the records. An agent reads and changes the plan with `todo-item`: `list`, `show`, `add`, `edit`, `move` and `finish`. `finish <ID> --no-changelog` also drops an item no chunk built. +2026-11-14, the worker of todo item 350. Serves goal 1.6: a client keeps its plan where its team works, so no tool or agent may assume a file. `bin/plan_store/plans.py` holds the interface, `PlanStore`. `todo_md.py` holds its markdown backend, `FilePlan`, and `stores.py` picks the backend the config names; `contract.py` holds the tests every backend passes, as `bin/record_store/` does for the records. An agent reads and changes the plan with `todo-item`: `list`, `show`, `add`, `edit`, `move` and `finish`. `finish <ID> --no-changelog` also drops an item no chunk built. Four choices the item left open: -- **Three kinds of tool still parse `todo.md`.** Four read what a past commit held: `score-outcomes`, the routing figures, `release_standing`'s `todos_since`, and larv-review's plan before the chunk. Only a markdown plan has commits, and todo items 365, 366 and 368 port those tools. Two rank the file: `rank_todo.py` and `larv-review record-scoring`. One checks its rank: rule-hook's `todo-rank-check`, whose Jira twin is todo item 367. +- **Three kinds of tool still parse `todo.md`.** Four read what a past commit held: `score-outcomes`, the routing figures, `release_standing`'s `todos_since`, and larv-review's plan before the chunk. Only a markdown plan has commits, and todo items 365, 366 and 368 port those tools. Two rank the file, through `FilePlan.rank`: `rank_todo.py` and `larv-review record-scoring`. One checks its rank, through `FilePlan.check`: rule-hook's `todo-rank-check`, whose Jira twin is todo item 367. - **`todos_since` is empty for a plan outside the checkout,** since no commit holds that plan. Before, it read the file as it stood in place of each past commit, which said the same as the plan itself. - **`list` and `show` print no Score.** The store hands items over in the backend's order, and a tracker has no score, so an item's place in `list` says how it ranks within its release. Whoever plans a release compares Scores across releases, and so opens `todo.md`, until a store hands over a score. - **The spellings `list [--release]`, `move <ID> --release`, and `edit <ID>` with one flag per cell, `--detail` from stdin and `--clear-detail`** are those a panel of three fresh readers, seated as the audience, picked over a positional release, `set` and `retarget`. `edit` refuses stdin text without `--detail`, and `--detail` without text, so no detail is dropped or wiped by mistake. diff --git a/judge-field-trials/release_ready.py b/judge-field-trials/release_ready.py index 645c04c5..45cfd41c 100644 --- a/judge-field-trials/release_ready.py +++ b/judge-field-trials/release_ready.py @@ -8,7 +8,7 @@ from cases import cases from transcript_archive.project_key import checkout_of from release_plan.release_standing import chunk_item, default_plan, ReadyToCut from git_cli.git_repo import default_ref, git -from release_plan.todo_table import items +from plan.todo_table import items ABOUT_CUT = re.compile(r"\bcut\b|ready to (?:cut|release|ship)|tag (?:it|v\d)|version bump", re.IGNORECASE) @@ -44,7 +44,7 @@ for outcomes, (stamp, kind, block), entries in cases(): table[("no checkout or commit", about)] += 1 continue plan = default_plan(root, commit.strip(), as_of(stamp)) - found = items(plan.todo) if isinstance(plan.todo, str) else plan.todo + found = items(plan.plan) if isinstance(plan.plan, str) else plan.plan pick = chunk_item(found, plan.cut) if isinstance(found, list) else found ready = isinstance(pick, ReadyToCut) table[(ready, about)] += 1 diff --git a/todo.md b/todo.md index f40f17a8..791d6457 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ `Bar = 0.1` -`Next ID = 392` +`Next ID = 394` ## Items @@ -21,6 +21,7 @@ | 339 | 0.12.0 | | | **Lower the reading cost of the files a chunk reads most before its first commit.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 3 | 1.0 | | 341 | 0.12.0 | | | **Hand each worker's claude a lower Read limit through `CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS`, kept only where replays of the archived review rounds find what two unchanged replays find.** | 2 | 2 | 3 | 5 | 3 | 1.4 by 3 | 1.0 | | 310 | 0.12.0 | | | **Compact a waiting worker's session shortly before its prompt cache expires, only when the human has not answered an interrupt by then.** | 3 | 2 | 3 | 6 | 4 | 1.4 by 3 | 0.9 | +| 393 | 0.12.0 | | decision | **Step an L 3 worker one rung up and an L 4 worker two up from the project's rung, as lilleman ruled on 2026-11-14.** | 2 | 1 | 3 | 4 | 4 | 1.4 by 3 | 0.9 | | 298 | 0.12.0 | | | **Send the judge only the decision entries and the transcript tail a verdict needs, and keep the cut only where `judge-replay` changes no verdict kind.** | 3 | 3 | 3 | 7 | 4 | 1.4 by 2, 1.5 by 1 | 0.9 | | 331 | 0.12.0 | | | **Reword four decisions to expire when the rungs their replays tested change, not whenever a model joins the ladder.** | 1 | 1 | 1 | 1 | 2 | 1.4 by 2 | 0.8 | | 381 | 0.12.0 | | | **Read a `Touches:` list from a plan kept in Jira as from one in todo.md, with a test that converts a description through `adf_codec`.** | 1 | 2 | 1 | 2 | 2 | 1.5 by 2 | 0.7 | @@ -49,6 +50,7 @@ | 342 | 0.14.0 | | | **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.** | 1 | 2 | 1 | 2 | 3 | 1.4 by 3, 1.5 by 2 | 1.7 | | 149 | 0.14.0 | | decision | **Fill each release by priority up to a capacity it states, in place of the bar, and move what does not fit to a later release.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 7 | 1.6 | | 165 | 0.14.0 | | | **Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 4, 1.4 by 3 | 1.6 | +| 392 | 0.14.0 | | owner | **Group bin/'s packages by concern into seven folders (plan, records, integrations, loop, review, forge and host), so a newcomer finds a tool's neighbours in one place.** | 3 | 1 | 3 | 5 | 7 | code health by 4 | 1.6 | | 151 | 0.14.0 | | decision | **Keep 10 to 20 settled decisions per project as its goals' test set, and rerun them after a goal changes.** | 3 | 2 | 2 | 5 | 5 | 1.2 by 7 | 1.6 | | 68 | 0.14.0 | | principle | **Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.** | 2 | 1 | 1 | 2 | 4 | 1.1 by 5 | 1.5 | | 102 | 0.14.0 | | | **Give loop-claude's retry delay, and the file it reads the machine's memory from, environment overrides, so the black-box test stops replacing `time.sleep` and `machine_load.memory.MEMINFO` through `sitecustomize`.** | 1 | 1 | 2 | 2 | 3 | 1.1 by 4 | 1.5 | @@ -131,6 +133,12 @@ lilleman, 2026-11-11: do it on a timer, so an answer that comes in time doesn't Probe first that `claude -p "/compact" --resume <id>` compacts a session: the Agent SDK documents `/compact` as a prompt, the CLI pages don't show it. Claude Code compacts idle interactive sessions itself ("Compacted while idle"), but not `-p` runs. Check: the cost entries of 20 chunks with an interrupt, before and after. +### 393. Step an L 3 worker one rung up and an L 4 worker two up from the project's rung, as lilleman ruled on 2026-11-14. + +lilleman ruled on 2026-11-14 (`docs/decisions.md` → the routing ladder entry, the 2026-11-14 note) that an L 3 task steps one rung up from the project's rung and an L 4 task two up, in every project and for delegated subagents. `bin/model_routing/ladder.py`'s `WORKER_STEPS` still reads `{1: -1, 2: -1, 3: 0, 4: 1}`. The 0.11.0 release review's principles pass found the gap, and lilleman chose on 2026-11-16 to file it for 0.12.0. + +Set `WORKER_STEPS` to `{1: -1, 2: -1, 3: 1, 4: 2}`. Then re-derive, from the ruling, the expected rungs of the 26 routing tests that pin the old steps: `bin/model_routing/test_ladder.py`, `bin/subagent_rung/test_subagent_rung.py`, and the routing, step and worker-argument tests in `bin/loop_claude/test_loop_claude.py` and `bin/loop_claude/test_black_box.py`. On an Opus 5.5 project, an L 3 worker or subagent then runs on Fable 5.2 at low, and an escalation stops without lilleman's yes at Opus 5.5 at xhigh; an L 4 one runs on Fable 5.2 at medium, and stops at Fable 5.2 at high. Reword the 2026-11-14 note's "hold until" sentence once the steps change, and cite the routing figures' stamp 2026-11-14T00:59:50Z in `routing-calls-raised.md` as settled. + ### 298. Send the judge only the decision entries and the transcript tail a verdict needs, and keep the cut only where `judge-replay` changes no verdict kind. 153 `Judge cost:` entries total $109.76, a median of about $0.76 a verdict at every rung, and the cost follows the size of the records, not the transcript: about 76k characters in log and 188k in claude-config. In 224 of 251 recent verdicts (89%) the evidence sits in the worker's final message. A missed interrupt is the costly error, so the bar is zero changed interrupts and zero new rejections across the replay. The judge is about 4.5% of dollars, so the saving is small; each cycle also gets faster. @@ -349,6 +357,22 @@ A release's capacity is a sum of its items' cost, as the formula counts it. Each A test audit across lilleman's projects on 2026-10-16 found 10 of 33 sampled tests in this repo pinning wording that is not the contract. Examples of these and other weak tests: many tests in `bin/loop_claude/test_loop_claude.py` pin whole sentences of the question, archive, prompt or help text, up to about 750 characters. `test_every_exit_1_stop_has_its_clause_in_help` and `test_every_failed_judge_run_has_its_clause_in_help` parse the source with `ast` and list each `Stop(...)` and `Failure(...)` call by function name. `bin/model_routing/test_ladder.py` asserts `len(LADDER) == 6`. Rewrite each to the technical principles' test bullet: assert the facts the text must carry, such as an item ID, a rung or a model argument, and delete a test no real bug could fail. Before and after rewriting a test, run the mutation tool on the code it covers: every mutant the old test killed, the new one kills. +### 392. Group bin/'s packages by concern into seven folders (plan, records, integrations, loop, review, forge and host), so a newcomer finds a tool's neighbours in one place. + +The 0.11.0 release review's architecture pass, round 1, finding 9: `bin/` holds 43 packages, about 20 launchers and 10 root files at one level, and the README's two lists are its only index. lilleman chose, during that review, to file this regrouping for a later release instead of doing it in 0.11.0, since it moves every package and no defect lies behind it. + +Group `bin/` by concern, one package level per group, with the launchers left at the root: + +- `plan/`: the plan core, with `plan_store`, `release_plan`, `todo_item` and `touch_predictions`. +- `records/`: `record_store`, `project_record` and `project_config`. +- `integrations/`: `atlassian`, `adf_codec`, `rest_client` and `notifier`. +- `loop/`: `loop_claude`, `loop_effects`, `loop_state`, `model_routing`, `transcript_archive` and `routing_figures`. +- `review/`: `larv_review`, `branch_chunks`, `review_rules`, `judge_replay`, `review_replay`, `rung_replay`, `score_outcomes`, `metric_bench`, `reading_cost`, `command_patterns` and `mutate_changes`. +- `forge/`: `chunk_pr`, `chunk_preflight` and `deploy_release`, where item 287's shared forge module lands. +- `host/`: `git_cli`, `command_lines`, `claude_code`, `machine_load`, `run_heavy`, `run_tests`, `text_files`, `wait_for`, `rule_hook` and `subagent_rung`. + +`repo_checks` stays at the root, since it tests the repo, not a tool. The README's `bin/` list then becomes seven short groups. That list is a place the comprehension seats found hard (`README.md` → the `bin/` package list): make it easier to read. + ### 151. Keep 10 to 20 settled decisions per project as its goals' test set, and rerun them after a goal changes. Each case is a question the project settled and the answer it chose. A fresh-context agent given only the README's premises answers each case; a case it answers differently says the goals no longer decide it. Written guidance can fail to change behaviour, which is why the goals get a test. @@ -381,7 +405,7 @@ The key names the project's session, archive folder and models entry. `project_k ### 156. Drop `rank_todo.py`'s ranking of an old-shape table once no project under `~/code` holds one. -While `rank_todo.py` ranks two shapes, projects follow two sets of scoring rules, against goal 1.3. Once every project has reshaped, drop `OLD_SHAPE`'s weighing from `bin/release_plan/ranking.py`, `RESHAPE`, and the old shape's lines in `rank_todo.py --help` and `rules/todo-items.md`. Keep `todo_table` reading old tables: `score_outcomes` reads every past merge's `todo.md`. PR #283's paired ruling found the old-shape path made `ranking.py`'s `score`, `Scoring.weights`, `unknown_columns` and `todo_table.py`'s `Moves` harder to read; leave each easier, with one shape and moves that are always moves, and the Moves cell's rules in one place. Release 0.3.0's seats named `ranking.py`'s `score`, `weigh` and `rank` and `todo_table.py`'s `OLD_SHAPE` for the same fork: "every rule exists twice for the old table shape" (Mid A). Make `weigh` and `rank` easier to read too. +While `rank_todo.py` ranks two shapes, projects follow two sets of scoring rules, against goal 1.3. Once every project has reshaped, drop `OLD_SHAPE`'s weighing from `bin/plan/ranking.py`, `RESHAPE`, and the old shape's lines in `rank_todo.py --help` and `rules/todo-items.md`. Keep `todo_table` reading old tables: `score_outcomes` reads every past merge's `todo.md`. PR #283's paired ruling found the old-shape path made `ranking.py`'s `score`, `Scoring.weights`, `unknown_columns` and `todo_table.py`'s `Moves` harder to read; leave each easier, with one shape and moves that are always moves, and the Moves cell's rules in one place. Release 0.3.0's seats named `ranking.py`'s `score`, `weigh` and `rank` and `todo_table.py`'s `OLD_SHAPE` for the same fork: "every rule exists twice for the old table shape" (Mid A). Make `weigh` and `rank` easier to read too. ### 388. Refuse an agent's Write or Edit of a routing ladder file in rule-hook, since a change to the ladder is the human's. @@ -435,7 +459,7 @@ The archive holds 277 chunk folders under `home/lilleman/.claude`, from 2026-09- ### 193. Narrow `numbered`'s mark to `Mark` by a typed lookup in place of `typing.cast`, so a mark added to the regex but not the lookup fails at run time, and one added to the lookup but not `Mark` fails mypy. -Found by review of PR #317. `bin/release_plan/goals_file.py`'s `numbered` writes `typing.cast(Mark, mark or None)`, which asserts the type `goal_weights` branches on without checking it: a mark added to the regex reaches `goal_weights` as a value `Mark` lacks. mypy does not read the regex, so no lookup lets it catch that. Replace the cast with a lookup typed `dict[str, Mark]`, from each mark the regex captures, and `""` for none, to its `Mark` value. A mark added to the regex but not the lookup then raises `KeyError` at run time, and a value added to the lookup but not `Mark` fails mypy. +Found by review of PR #317. `bin/plan/goals_file.py`'s `numbered` writes `typing.cast(Mark, mark or None)`, which asserts the type `goal_weights` branches on without checking it: a mark added to the regex reaches `goal_weights` as a value `Mark` lacks. mypy does not read the regex, so no lookup lets it catch that. Replace the cast with a lookup typed `dict[str, Mark]`, from each mark the regex captures, and `""` for none, to its `Mark` value. A mark added to the regex but not the lookup then raises `KeyError` at run time, and a value added to the lookup but not `Mark` fails mypy. ### 194. Make `test_waits_out_a_usage_limit_which_ends_a_run_of_failures` expect a usage-limit wait independent of the wall-clock time that passes during the run.