diff --git a/.gitignore b/.gitignore index 69aab0d5..cf98e740 100644 --- a/.gitignore +++ b/.gitignore @@ -25,15 +25,14 @@ !bin/chunk_preflight/*.py !bin/claude_code/ !bin/claude_code/*.py -!bin/comprehension_history.py +!bin/command_lines/ +!bin/command_lines/*.py !bin/deploy-release !bin/deploy_release/ !bin/deploy_release/*.py -!bin/docker_command.py !bin/failure.py -!bin/file_writes.py -!bin/git_command.py -!bin/git_repo.py +!bin/git_cli/ +!bin/git_cli/*.py !bin/judge-replay !bin/judge_replay/ !bin/judge_replay/*.py @@ -49,27 +48,26 @@ !bin/loop_inbox/*.py !bin/machine_load/ !bin/machine_load/*.py -!bin/markdown_text.py !bin/metric-bench !bin/metric_bench/ !bin/metric_bench/*.py !bin/model_routing/ !bin/model_routing/*.py -!bin/project_key.py !bin/rank_todo.py !bin/reading-cost !bin/reading_cost/ !bin/reading_cost/*.py -!bin/release.py -!bin/release_standing.py +!bin/records/ +!bin/records/*.py +!bin/release_plan/ +!bin/release_plan/*.py !bin/repo_checks/ !bin/repo_checks/*.py !bin/review-replay -!bin/review_folder.py -!bin/review_passes.py !bin/review_replay/ !bin/review_replay/*.py -!bin/round_titles.py +!bin/review_rules/ +!bin/review_rules/*.py !bin/routing_figures/ !bin/routing_figures/*.py !bin/rule-hook @@ -86,16 +84,13 @@ !bin/score_outcomes/ !bin/score_outcomes/*.py !bin/settings_filter.py -!bin/shell_command.py !bin/statusline.py !bin/subagent-rung !bin/subagent_rung/ !bin/subagent_rung/*.py !bin/test_*.py -!bin/todo_table.py !bin/transcript_archive/ !bin/transcript_archive/*.py -!bin/utc_stamp.py !docs/ !docs/*.md !principles/ diff --git a/README.md b/README.md index b691494a..45a8ef76 100644 --- a/README.md +++ b/README.md @@ -125,22 +125,26 @@ pytest_add_cli_args=-k Then, in the copy: `uvx --with pytest==9.2.0 'mutmut>=3,<4' run && uvx --with pytest==9.2.0 'mutmut>=3,<4' results`, and `uvx --with pytest==9.2.0 'mutmut>=3,<4' show ` to see a mutant's change. The config keys are mutmut 3's. -`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. The non-test modules at `bin/`'s root, `claude_code/` 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` and `failure.py`. `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/`, `machine_load/`, `model_routing/`, `records/`, `release_plan/`, `review_rules/`, `rung_replay/` and `transcript_archive/` serve more than one tool. - `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. -- `deploy_release` imports `chunk_preflight`'s `forge_of`, which tells a GitHub origin from a Gitea one, and `release_standing.py`, which says whether the next release is ready to cut. +- `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `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. -- `larv_review` imports `rank_todo.py`'s ranking. - `loop_claude` runs `chunk-preflight` as a process of its own. - `loop_inbox` imports `loop_claude`'s question files (`waiting/`), the files a running loop lists itself in (`running_loops.py`, `session_lock.py`), its effects and paths, and `hand_over.py`, which opens claude for `/talk`. A change to any of them changes loop-inbox too. - `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for. - `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read. - `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them. +- `records/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, stamps times in UTC, and replaces a file in one step, private where it is new. +- `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`, which `rank_todo.py`, `larv_review` and `rule_hook` import). - `repo_checks/` tests the repo itself. +- `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. -- `rule_hook` imports `rank_todo.py`'s check. - `rung_replay/` holds what `judge_replay` and `review_replay` share: the rung search, the argument reader, the candidate rungs and the exits. It reads `loop_claude`'s retry count and models file. - `test_env.py` serves the tests. +- `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry. ## Tracking a new file diff --git a/bin/branch_chunks/cut.py b/bin/branch_chunks/cut.py index 80520f8f..910a6d79 100644 --- a/bin/branch_chunks/cut.py +++ b/bin/branch_chunks/cut.py @@ -3,10 +3,10 @@ import re import typing from failure import Failure -from comprehension_history import HISTORY -from todo_table import Item, items +from review_rules.comprehension_history import HISTORY +from release_plan.todo_table import Item, items from reading_cost.figures import RECORD -from utc_stamp import utc +from records.utc_stamp import utc # The plan, and the records tools append to: none of their lines are the chunk's work. NOT_WORK = ("todo.md", HISTORY, RECORD) diff --git a/bin/branch_chunks/fixes.py b/bin/branch_chunks/fixes.py index 8a306b36..660591b6 100644 --- a/bin/branch_chunks/fixes.py +++ b/bin/branch_chunks/fixes.py @@ -5,8 +5,8 @@ import re import typing from branch_chunks.cut import Branch, BranchChunk, NOT_WORK -from todo_table import Item -from round_titles import title_counts +from release_plan.todo_table import 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. FIXES = ("defect", "security") diff --git a/bin/branch_chunks/read.py b/bin/branch_chunks/read.py index 5c6ede36..d3262500 100644 --- a/bin/branch_chunks/read.py +++ b/bin/branch_chunks/read.py @@ -1,7 +1,7 @@ from branch_chunks.fixes import blamed, fixing_changes, FixingChange, removed_work, Traced, with_fixes from branch_chunks.cut import BranchChunk, cut_branch, LOG, plan_revisions, shipped_by from failure import Failure -from git_repo import Run, text_at +from git_cli.git_repo import Run, text_at def branch_chunks(default: str, run: Run) -> list[BranchChunk] | Failure: diff --git a/bin/branch_chunks/test_branch_chunks.py b/bin/branch_chunks/test_branch_chunks.py index 65251d0c..765bd00f 100644 --- a/bin/branch_chunks/test_branch_chunks.py +++ b/bin/branch_chunks/test_branch_chunks.py @@ -13,9 +13,9 @@ from branch_chunks.fixes import blamed, fixing_changes, removed, removed_work, T from branch_chunks.cut import Branch, chunk_log, Commit, cut_branch, landing, NOT_WORK, shipped, Span from branch_chunks.read import branch_chunks, traced_to from failure import Failure -from git_repo import git +from git_cli.git_repo import git from test_env import isolated_env -from todo_table import Item +from release_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_preflight/choices.py b/bin/chunk_preflight/choices.py index e1249d96..34d5e4bf 100644 --- a/bin/chunk_preflight/choices.py +++ b/bin/chunk_preflight/choices.py @@ -2,11 +2,11 @@ import pathlib import re -from release_standing import chunk_item, Cut, dated_cut, LastCut, ReadyToCut, ReviewDue, Unknown, Unplanned +from release_plan.release_standing import chunk_item, Cut, dated_cut, LastCut, ReadyToCut, ReviewDue, Unknown, Unplanned from failure import Failure from chunk_preflight.gathered import Forge, NoItem, Plan -from todo_table import item_details, items, NoItemsTable -from release import version +from release_plan.todo_table import item_details, items, NoItemsTable +from release_plan.release import version # 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")} diff --git a/bin/chunk_preflight/facts.py b/bin/chunk_preflight/facts.py index 359b63da..aa438777 100644 --- a/bin/chunk_preflight/facts.py +++ b/bin/chunk_preflight/facts.py @@ -1,11 +1,11 @@ """The lines the preflight prints, stated from what it gathered.""" -from todo_table import bundle_candidates, BUNDLE_MAX_R, Item, ships_alone +from release_plan.todo_table import bundle_candidates, BUNDLE_MAX_R, Item, ships_alone from chunk_preflight.choices import cut_name, PULLS_LIST -from release_standing import dated_cut, LastCut, unreleased_entries +from release_plan.release_standing import dated_cut, LastCut, unreleased_entries from failure import Failure from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran -from markdown_text import quoted -from release import version +from records.markdown_text import quoted +from release_plan.release import version def render(found: Gathered) -> list[str]: diff --git a/bin/chunk_preflight/gathered.py b/bin/chunk_preflight/gathered.py index 54278eda..0b5e59ad 100644 --- a/bin/chunk_preflight/gathered.py +++ b/bin/chunk_preflight/gathered.py @@ -4,8 +4,8 @@ import pathlib import typing from failure import Failure -from todo_table import Item -from release_standing import LastCut +from release_plan.todo_table import Item +from release_plan.release_standing import LastCut # The CLI that lists a forge's pull requests: gh for a github.com origin, tea for any other. Forge = typing.Literal["gh", "tea"] diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py index 20f72e92..d6c6fe56 100644 --- a/bin/chunk_preflight/main.py +++ b/bin/chunk_preflight/main.py @@ -57,8 +57,8 @@ import subprocess import sys import typing -from git_repo import commit_exists, default_branch, file_at, git, top -from release_standing import default_plan +from git_cli.git_repo import commit_exists, default_branch, file_at, git, top +from release_plan.release_standing import default_plan from failure import Failure from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran, Worktree from chunk_preflight.choices import forge_of, named_paths, planned, pulls_command, worktree_add, worktree_on diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index 31351290..1011bdb0 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -12,7 +12,7 @@ from failure import Failure from chunk_preflight.choices import forge_of, named_paths, planned, worktree_add from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, NoItem, Ran, Worktree from test_env import isolated_env -from release_standing import LastCut +from release_plan.release_standing import LastCut from chunk_preflight.main import line_count, ran, seconds, TIMEOUT from chunk_preflight.facts import open_pulls, render diff --git a/bin/command_lines/__init__.py b/bin/command_lines/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/docker_command.py b/bin/command_lines/docker_command.py similarity index 100% rename from bin/docker_command.py rename to bin/command_lines/docker_command.py diff --git a/bin/shell_command.py b/bin/command_lines/shell_command.py similarity index 100% rename from bin/shell_command.py rename to bin/command_lines/shell_command.py diff --git a/bin/test_docker_command.py b/bin/command_lines/test_docker_command.py similarity index 98% rename from bin/test_docker_command.py rename to bin/command_lines/test_docker_command.py index d87f8568..f81ae210 100644 --- a/bin/test_docker_command.py +++ b/bin/command_lines/test_docker_command.py @@ -1,6 +1,6 @@ import unittest -from docker_command import capped +from command_lines.docker_command import capped class Capped(unittest.TestCase): diff --git a/bin/deploy_release/cut.py b/bin/deploy_release/cut.py index 386408ec..1e1d5d2c 100644 --- a/bin/deploy_release/cut.py +++ b/bin/deploy_release/cut.py @@ -8,14 +8,14 @@ import shutil import sys import tempfile -from release_standing import chunk_item, Cut, default_plan, Next, ReadyToCut, ReviewDue, Unplanned -from git_repo import default_ref, git +from release_plan.release_standing import chunk_item, Cut, default_plan, Next, ReadyToCut, ReviewDue, Unplanned +from git_cli.git_repo import default_ref, git from deploy_release.deploy import deploy from failure import Failure from deploy_release import forge from chunk_preflight.choices import forge_of -from todo_table import items -from release import newest_tag, Release, version +from release_plan.todo_table import items +from release_plan.release import newest_tag, Release, version def cut(clone: str, checkout: str) -> str | Failure: diff --git a/bin/deploy_release/deploy.py b/bin/deploy_release/deploy.py index 308c3682..f6fdbcc8 100644 --- a/bin/deploy_release/deploy.py +++ b/bin/deploy_release/deploy.py @@ -1,8 +1,8 @@ """Move a checkout to this repo's newest release, as a bare `deploy-release` does.""" from failure import Failure -from git_repo import git -from release import newest_tag, parsed, tagged -from markdown_text import sections +from git_cli.git_repo import git +from release_plan.release import newest_tag, parsed, tagged +from records.markdown_text import sections def deploy(checkout: str) -> str | Failure: diff --git a/bin/git_cli/__init__.py b/bin/git_cli/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/git_command.py b/bin/git_cli/git_command.py similarity index 97% rename from bin/git_command.py rename to bin/git_cli/git_command.py index 886578b3..52f02163 100644 --- a/bin/git_command.py +++ b/bin/git_cli/git_command.py @@ -1,6 +1,6 @@ import dataclasses -from shell_command import resolved, Simple +from command_lines.shell_command import resolved, Simple # git's global options that take a value as the next word. GIT_VALUED = {"-C", "-c", "--exec-path", "--git-dir", "--namespace", "--work-tree"} diff --git a/bin/git_repo.py b/bin/git_cli/git_repo.py similarity index 100% rename from bin/git_repo.py rename to bin/git_cli/git_repo.py diff --git a/bin/test_git_repo.py b/bin/git_cli/test_git_repo.py similarity index 98% rename from bin/test_git_repo.py rename to bin/git_cli/test_git_repo.py index dcd22b90..7921e0a0 100644 --- a/bin/test_git_repo.py +++ b/bin/git_cli/test_git_repo.py @@ -5,10 +5,10 @@ import sys import tempfile import unittest -sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from failure import Failure -import git_repo +from git_cli import git_repo class Git(unittest.TestCase): diff --git a/bin/judge_replay/main.py b/bin/judge_replay/main.py index 7d2f2040..a8128b61 100644 --- a/bin/judge_replay/main.py +++ b/bin/judge_replay/main.py @@ -30,7 +30,7 @@ from transcript_archive.location import archive_root, transcript_of from transcript_archive.read import archived_outcomes from rung_replay.command import arguments_or_exit, down_from, failed, limited_exit, projects_on from judge_replay.replay import Case, case_from, Kind, report, reproduced, sample, verdict_kind -from project_key import checkout_of +from transcript_archive.project_key import checkout_of from loop_claude.effects import Effects from failure import Failure from rung_replay.search import first_reply, replayed diff --git a/bin/larv_review/agreement.py b/bin/larv_review/agreement.py index 1e3755be..d2ac408f 100644 --- a/bin/larv_review/agreement.py +++ b/bin/larv_review/agreement.py @@ -1,6 +1,6 @@ import decimal -from comprehension_history import by_time, counted_vote, entries, Entry, last_cells +from review_rules.comprehension_history import by_time, counted_vote, entries, Entry, last_cells from larv_review.seats import FIRST_SEATS # Matches score-outcomes, which waits for 10 finished chunks before it shows a median. diff --git a/bin/larv_review/history_changes.py b/bin/larv_review/history_changes.py index b39bc104..1a7f549d 100644 --- a/bin/larv_review/history_changes.py +++ b/bin/larv_review/history_changes.py @@ -1,6 +1,6 @@ from failure import Failure -from git_repo import file_at, full_history, git, top -from comprehension_history import HISTORY, HistoryChange +from git_cli.git_repo import file_at, full_history, git, top +from review_rules.comprehension_history import HISTORY, HistoryChange def history_changes(default: str) -> list[HistoryChange] | Failure: diff --git a/bin/larv_review/history_commands.py b/bin/larv_review/history_commands.py index 057a0ce3..b7aaa7da 100644 --- a/bin/larv_review/history_commands.py +++ b/bin/larv_review/history_commands.py @@ -2,15 +2,15 @@ import pathlib import time from larv_review.agreement import agreement_report -from comprehension_history import appended, DIMENSIONS, FLOOR, heading, Heading, HISTORY, latest_places, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text -from git_repo import commit_exists, top +from review_rules.comprehension_history import appended, DIMENSIONS, FLOOR, heading, Heading, HISTORY, latest_places, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text +from git_cli.git_repo import commit_exists, top from larv_review.ruling import counted, overall, ruling, split, surplus, votes from failure import Failure from larv_review.seats import FIRST_SEATS, scores, seats_file, SeatsFile from larv_review.scoring import means, under_floor from larv_review.plan import plan_reasons -import rank_todo -from file_writes import replace_file +from release_plan import ranking +from records.file_writes import replace_file def record_ruling(votes_file: pathlib.Path) -> Failure | None: @@ -61,7 +61,7 @@ def rerank() -> Failure | None: if isinstance(checkout, Failure): return checkout todo = pathlib.Path(checkout, "todo.md") - ranked = rank_todo.rank_file(todo) + ranked = ranking.rank_file(todo) 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") if ranked.under_bar: diff --git a/bin/larv_review/main.py b/bin/larv_review/main.py index a8e7c1ff..5b7b8bb5 100644 --- a/bin/larv_review/main.py +++ b/bin/larv_review/main.py @@ -103,17 +103,17 @@ import re import sys import typing -from git_repo import branch_titles, default_branch, git, top -from round_titles import cap, CAP, RELEASE_REVIEW_CAP, round_counts +from git_cli.git_repo import branch_titles, default_branch, git, top +from review_rules.round_titles import cap, CAP, RELEASE_REVIEW_CAP, round_counts from failure import Failure -from comprehension_history import FLOOR +from review_rules.comprehension_history import FLOOR from larv_review.history_changes import history_changes from larv_review.ruling_base import measured_commit from larv_review.agreement import MIN_PAIRS -from review_passes import PASSES +from review_rules.review_passes import PASSES from larv_review.plan import plan_reasons from larv_review.history_commands import record_ruling, record_scoring, show_agreement, show_places -from review_folder import REPORTS, review_folder +from review_rules.review_folder import REPORTS, review_folder USAGE = "usage: larv-review review-folder | ruling-base | round-count | needs-scoring-run [...] | record-ruling | record-scoring [...] | places | agreement" diff --git a/bin/larv_review/plan.py b/bin/larv_review/plan.py index 234cd125..0e1ab26f 100644 --- a/bin/larv_review/plan.py +++ b/bin/larv_review/plan.py @@ -1,10 +1,10 @@ import pathlib -from release_standing import Cut, default_plan, LastCut, next_release, Unknown +from release_plan.release_standing import Cut, default_plan, LastCut, next_release, Unknown from failure import Failure -from todo_table import Item, items, NoItemsTable, renames -from release import Release, version -from git_repo import top +from release_plan.todo_table import Item, items, NoItemsTable, renames +from release_plan.release import Release, version +from git_cli.git_repo import top def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed_release: Release | None, renamed: set[Release]) -> list[str] | Failure: diff --git a/bin/larv_review/ruling.py b/bin/larv_review/ruling.py index c64ff2e5..e55eb453 100644 --- a/bin/larv_review/ruling.py +++ b/bin/larv_review/ruling.py @@ -1,4 +1,4 @@ -from comprehension_history import DIMENSIONS, PLACE, place_dimensions, Seat +from review_rules.comprehension_history import DIMENSIONS, PLACE, place_dimensions, Seat from failure import Failure from larv_review.seats import FIRST_SEATS, SPLIT_SEATS, vote_line diff --git a/bin/larv_review/ruling_base.py b/bin/larv_review/ruling_base.py index 3b7211ec..3c623f26 100644 --- a/bin/larv_review/ruling_base.py +++ b/bin/larv_review/ruling_base.py @@ -1,4 +1,4 @@ -from comprehension_history import entries, HistoryChange +from review_rules.comprehension_history import entries, HistoryChange def measured_commit(changes: list[HistoryChange]) -> str | None: diff --git a/bin/larv_review/scoring.py b/bin/larv_review/scoring.py index 2614e015..f7453134 100644 --- a/bin/larv_review/scoring.py +++ b/bin/larv_review/scoring.py @@ -1,6 +1,6 @@ import decimal -from comprehension_history import DIMENSIONS, FLOOR +from review_rules.comprehension_history import DIMENSIONS, FLOOR def means(lines: list[list[str]]) -> list[decimal.Decimal]: diff --git a/bin/larv_review/seats.py b/bin/larv_review/seats.py index 2fe9fb58..e10316ab 100644 --- a/bin/larv_review/seats.py +++ b/bin/larv_review/seats.py @@ -2,7 +2,7 @@ import dataclasses import decimal import re -from comprehension_history import ARCHITECT, DIMENSIONS, JUNIOR, MID, Seat, SENIOR +from review_rules.comprehension_history import ARCHITECT, DIMENSIONS, JUNIOR, MID, Seat, SENIOR from failure import Failure SCORES = re.compile(", ".join(rf"{name} ([0-9]+(?:\.[0-9]+)?)" for name in DIMENSIONS)) diff --git a/bin/larv_review/test_larv_review.py b/bin/larv_review/test_larv_review.py index c4e93907..39bd629f 100644 --- a/bin/larv_review/test_larv_review.py +++ b/bin/larv_review/test_larv_review.py @@ -11,14 +11,14 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from larv_review.agreement import agreement_report, ruling_agreement, run_agreement -from comprehension_history import appended, entries, HistoryChange, latest_places, Place, recorded, ruling_entry, scoring_entry, ScoringRun, Seat -import comprehension_history +from review_rules.comprehension_history import appended, entries, HistoryChange, latest_places, Place, recorded, ruling_entry, scoring_entry, ScoringRun, Seat +from review_rules import comprehension_history from larv_review.ruling import counted, ruling, split, surplus, votes from failure import Failure from test_env import isolated_env -from todo_table import Item, items, NoItemsTable +from release_plan.todo_table import Item, items, NoItemsTable from larv_review.plan import landed_towards, plan_reasons, scoring_run_due -from release_standing import LastCut +from release_plan.release_standing import LastCut from larv_review.scoring import means, under_floor from larv_review.ruling_base import measured_commit from larv_review.seats import score_line, scores, seats_file diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index 810d3521..a0bc4484 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -9,7 +9,7 @@ from loop_claude.effects import Effects from loop_claude import escalation_mark from failure import Failure from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, TakenIn, Unfinished, Verdict -from todo_table import LEVELS +from release_plan.todo_table import LEVELS from model_routing.route import on_its_scale from claude_code.transcript import plain, verbatim from loop_claude.cycle.retry import retried diff --git a/bin/loop_claude/cycle/prompts.py b/bin/loop_claude/cycle/prompts.py index 73357cf4..7508f9e7 100644 --- a/bin/loop_claude/cycle/prompts.py +++ b/bin/loop_claude/cycle/prompts.py @@ -4,8 +4,8 @@ from model_routing.ladder import climbed, LADDER, position, Rung from model_routing.route import ESCALATION_MARKER, Route from loop_claude.routing import escalation_rungs from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES -from review_passes import INSTRUCTION_FILES, INSTRUCTION_FOLDERS -from markdown_text import listed, quoted +from review_rules.review_passes import INSTRUCTION_FILES, INSTRUCTION_FOLDERS +from records.markdown_text import listed, quoted from claude_code.transcript import Typed # Where the judge may quote an answer from, named as the human and the worker see them; of README.md the judge sees only the premises. diff --git a/bin/loop_claude/effects.py b/bin/loop_claude/effects.py index df00fefc..e5a77976 100644 --- a/bin/loop_claude/effects.py +++ b/bin/loop_claude/effects.py @@ -10,7 +10,7 @@ import time import typing import uuid -import git_repo +from git_cli import git_repo from machine_load.memory import Memory, read_memory # Seconds between a loop's looks for an answer from loop-inbox while it reads its terminal, and for the end of the claude loop-inbox opened. diff --git a/bin/loop_claude/loop/chunk_start.py b/bin/loop_claude/loop/chunk_start.py index 53223876..d189b3e3 100644 --- a/bin/loop_claude/loop/chunk_start.py +++ b/bin/loop_claude/loop/chunk_start.py @@ -2,12 +2,12 @@ import pathlib import typing -from release_standing import default_plan, DefaultPlan -from git_repo import default_ref, file_at +from release_plan.release_standing import default_plan, DefaultPlan +from git_cli.git_repo import default_ref, file_at from loop_claude.effects import Effects, say from failure import Failure from loop_claude.routing import first_route, kept, routed_item -from todo_table import Item +from release_plan.todo_table import Item from transcript_archive.read import latest_worker from loop_claude.cycle import prompts from model_routing.route import Route, route_from diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index db53a5ad..f042cb3a 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -15,7 +15,7 @@ from loop_claude.project.model_choice import get_or_ask_models from loop_claude.loop.usage import HELP from loop_claude.running_loops import Listed, shown_running from loop_claude.paths import Paths -from project_key import project_key +from transcript_archive.project_key import project_key from model_routing.ladder import project_rung from loop_claude.project.premises import read_premises from loop_claude.project.records import read_records diff --git a/bin/loop_claude/loop/routing_check.py b/bin/loop_claude/loop/routing_check.py index 7fa59cfa..211df4ed 100644 --- a/bin/loop_claude/loop/routing_check.py +++ b/bin/loop_claude/loop/routing_check.py @@ -13,7 +13,7 @@ from routing_figures.render import render from model_routing.ladder import Rung from routing_figures import state from loop_claude.stop import Stop -from utc_stamp import utc +from records.utc_stamp import utc def check_routing(root: pathlib.Path, checkout: str, session: str, rung: Rung, paths: Paths, questions: pathlib.Path, effects: Effects) -> Stop | None: diff --git a/bin/loop_claude/project/model_choice.py b/bin/loop_claude/project/model_choice.py index da63991f..268069d8 100644 --- a/bin/loop_claude/project/model_choice.py +++ b/bin/loop_claude/project/model_choice.py @@ -9,7 +9,7 @@ from loop_claude.effects import Effects, say from failure import Failure from loop_claude.stop import needs_human, needs_terminal, Stop from loop_claude.paths import Paths -from file_writes import replace_json +from records.file_writes import replace_json @dataclasses.dataclass(frozen=True) diff --git a/bin/loop_claude/project/premises.py b/bin/loop_claude/project/premises.py index 638ba198..c1ca72db 100644 --- a/bin/loop_claude/project/premises.py +++ b/bin/loop_claude/project/premises.py @@ -1,6 +1,6 @@ from failure import Failure from loop_claude.project.text_file import read_utf8 -from markdown_text import sections +from records.markdown_text import sections def read_premises(root: str) -> str | Failure: diff --git a/bin/loop_claude/routing.py b/bin/loop_claude/routing.py index a3fc112b..d7a542ad 100644 --- a/bin/loop_claude/routing.py +++ b/bin/loop_claude/routing.py @@ -9,12 +9,12 @@ The worker, and the session /talk opens, run on a Route (model_routing/route.py) """ import dataclasses -from release_standing import chunk_item, LastCut, Next +from release_plan.release_standing import chunk_item, LastCut, Next from model_routing.ladder import climbed, highest, LADDER, position, project_rung, review_floor, Rung, stepped_up, worker_rung from loop_claude import escalation_mark from failure import Failure from loop_claude.verdicts import Interrupt, QuotedAnswer, Unfinished -from todo_table import Item, items, NoItemsTable +from release_plan.todo_table import Item, items, NoItemsTable from model_routing.route import Route UNFINISHED_PER_STEP = 2 diff --git a/bin/loop_claude/running_loops.py b/bin/loop_claude/running_loops.py index 602f245f..fa5057f7 100644 --- a/bin/loop_claude/running_loops.py +++ b/bin/loop_claude/running_loops.py @@ -19,8 +19,8 @@ import typing from loop_claude.effects import Effects, say from loop_claude.session_lock import ended, held, running from failure import Failure -from todo_table import items -from file_writes import replace_json +from release_plan.todo_table import items +from records.file_writes import replace_json # How many times, 0.1 s apart, a loop tries to take its lock: loop-inbox takes it for a moment each time it checks whether the loop has ended. LOCK_TRIES = 10 diff --git a/bin/loop_claude/session_lock.py b/bin/loop_claude/session_lock.py index 6b9e665f..e603d8aa 100644 --- a/bin/loop_claude/session_lock.py +++ b/bin/loop_claude/session_lock.py @@ -9,7 +9,7 @@ import pathlib import typing from failure import Failure -from file_writes import make_private +from records.file_writes import make_private def lock_file(folder: pathlib.Path, session: str) -> pathlib.Path: diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index a96e6ceb..81c50650 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -914,7 +914,7 @@ class Reload(unittest.TestCase): worker(append=["loop-claude", "\ndef\n"]), judge(), worker(replace=["loop-claude", "\ndef\n", "\n# edited\n"]), judge(), worker(append=["loop_claude/nested/edited.py", "# edited\n"]), judge(), - worker(append=["file_writes.py", "# edited\n"]), judge(), + worker(append=["records/file_writes.py", "# edited\n"]), judge(), worker(), ]) self.assertEqual(run.code, 130) diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 56b2745f..089465cd 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -25,7 +25,7 @@ from routing_figures.calls import Call from loop_claude.project import checkout, model_choice, records from loop_claude.loop import chunk_start, close from loop_claude.waiting.answers import ClaudeEnded, ClaudeOpening, send, Typed -from release_standing import DefaultPlan, LastCut +from release_plan.release_standing import DefaultPlan, LastCut from loop_claude.effects import Effects, POLL_SECONDS, PYTHON_TIMEOUT, run_python, say, system_effects from claude_code import entries, reply, session from failure import Failure @@ -42,7 +42,7 @@ from transcript_archive.location import project_archive from model_routing.route import Route, route_from, WorkerLine from loop_claude.stop import Stop from loop_claude.running_loops import Taken -from utc_stamp import utc +from records.utc_stamp import utc from loop_claude.cycle.judge import verdict_from from loop_claude.waiting.listing import waiting diff --git a/bin/loop_claude/waiting/answers.py b/bin/loop_claude/waiting/answers.py index ca8a7cb2..eb02fde6 100644 --- a/bin/loop_claude/waiting/answers.py +++ b/bin/loop_claude/waiting/answers.py @@ -7,7 +7,7 @@ import pathlib from loop_claude.waiting.ask import Ask, tagged from failure import Failure -from file_writes import replace_json +from records.file_writes import replace_json @dataclasses.dataclass(frozen=True) diff --git a/bin/loop_claude/waiting/ask.py b/bin/loop_claude/waiting/ask.py index e67a228a..dd29796c 100644 --- a/bin/loop_claude/waiting/ask.py +++ b/bin/loop_claude/waiting/ask.py @@ -7,7 +7,7 @@ import pathlib import typing from loop_claude.hand_over import ClaudeCommand -from utc_stamp import seconds, utc +from records.utc_stamp import seconds, utc if typing.TYPE_CHECKING: from _typeshed import DataclassInstance diff --git a/bin/loop_claude/waiting/listing.py b/bin/loop_claude/waiting/listing.py index 041e3ae4..db5d1ff5 100644 --- a/bin/loop_claude/waiting/listing.py +++ b/bin/loop_claude/waiting/listing.py @@ -8,7 +8,7 @@ from loop_claude.waiting.ask import Ask, ask_fields, read_ask from loop_claude.effects import Effects, say from loop_claude.session_lock import ended, running from failure import Failure -from file_writes import make_private, replace_json +from records.file_writes import make_private, replace_json def ask_file(folder: pathlib.Path, session: str) -> pathlib.Path: diff --git a/bin/metric_bench/bench.py b/bin/metric_bench/bench.py index 93f86e65..f3244a2b 100644 --- a/bin/metric_bench/bench.py +++ b/bin/metric_bench/bench.py @@ -4,7 +4,7 @@ import dataclasses import os import statistics -from comprehension_history import Place +from review_rules.comprehension_history import Place from metric_bench.python_units import Unit METRICS: dict[str, Callable[[Unit, dict[str, int]], int]] = { diff --git a/bin/metric_bench/main.py b/bin/metric_bench/main.py index 20194ef0..971367ed 100644 --- a/bin/metric_bench/main.py +++ b/bin/metric_bench/main.py @@ -36,9 +36,9 @@ import statistics import sys from metric_bench.bench import bench, co_changed, medians, METRICS, RunScores, Score, tracked_places -from comprehension_history import entries, Entry +from review_rules.comprehension_history import entries, Entry from failure import Failure -from git_repo import git +from git_cli.git_repo import git from metric_bench.python_units import measured, python_units, Unit diff --git a/bin/metric_bench/test_metric_bench.py b/bin/metric_bench/test_metric_bench.py index 5151539b..b37d35e8 100644 --- a/bin/metric_bench/test_metric_bench.py +++ b/bin/metric_bench/test_metric_bench.py @@ -11,7 +11,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from metric_bench.bench import auc, bench, co_changed, top_k, tracked_places from metric_bench.python_units import cognitive, measured, python_units, Unit -from comprehension_history import entries, Place +from review_rules.comprehension_history import entries, Place from failure import Failure from test_env import isolated_env from metric_bench.main import scored_runs diff --git a/bin/model_routing/ladder.py b/bin/model_routing/ladder.py index b0cd1b77..1e046439 100644 --- a/bin/model_routing/ladder.py +++ b/bin/model_routing/ladder.py @@ -3,7 +3,7 @@ import dataclasses import re import typing -from review_passes import ReviewedPass +from review_rules.review_passes import ReviewedPass # How Rung.__str__ spells a rung that names an effort, and Rung.parse reads it back. WORDING = re.compile(r"(?P\S+) at (?P\S+) effort") diff --git a/bin/model_routing/route.py b/bin/model_routing/route.py index a435db6b..017e30a8 100644 --- a/bin/model_routing/route.py +++ b/bin/model_routing/route.py @@ -3,7 +3,7 @@ import dataclasses import json import typing -from todo_table import LEVELS +from release_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 6558016c..b4dba7a1 100644 --- a/bin/model_routing/test_ladder.py +++ b/bin/model_routing/test_ladder.py @@ -5,8 +5,8 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from model_routing.ladder import highest, LADDER, lowest_worker_rung, planning_rung, project_rung, review_floor, review_rung, Rung, stepped_up, worker_rung, WORKER_STEPS -from todo_table import LEVELS -from review_passes import REVIEWERS +from release_plan.todo_table import LEVELS +from review_rules.review_passes import REVIEWERS OPUS = Rung("claude-opus-5-5", "medium") diff --git a/bin/rank_todo.py b/bin/rank_todo.py index 88f4adf2..c6cffadf 100755 --- a/bin/rank_todo.py +++ b/bin/rank_todo.py @@ -81,60 +81,11 @@ docs/decisions.md that breaks the rules above, a scoring run on docs/comprehensi newest scored commit with no Mean row ending in its overall, an item that is not exempt scoring under the bar, or --check finding the file unranked. """ -import ast -import dataclasses -import decimal -import graphlib -import math import pathlib -import re import sys -import typing -from todo_table import BLOCKED_BY, cells, CODE_HEALTH, DETAILS, HEADER_START, Item, item_details, items_table, MOVES, OLD_SHAPE, parse_row, renames, risk, Shape, SHAPE, shape_of, Table, table_rows from failure import Failure -from comprehension_history import FLOOR, HISTORY, latest_overall -from markdown_text import listed, sections -from file_writes import replace_file -from release import version - -# What each achieve goal weighs of the one above it; docs/decisions.md records the choice. -GOAL_STEP = 0.97 -# Code health weighs this many times its weight by position while the comprehension panel's overall is under FLOOR, or unmeasured; lilleman's choice, which docs/decisions.md records. -UNDER_FLOOR = 4 -# Any **Void:** line of README.md's ## Goals; ranked_goals accepts only `**Void:** code health, since .`, as ~/.claude/CLAUDE.md → "Shared goal" spells it. -VOID = re.compile(r"^\*\*Void:\*\* (.*)$", re.M) -# A docs/decisions.md title opting the project out of the comprehension check, as larv-review's SKILL.md → "Opt-out" spells it. -OPTED_OUT = re.compile(r"^## review opt-out:.*\bcomprehension check\b", re.M) -LARGEST_FORMULA = 200 -LONGEST_FORMULA = 4 * LARGEST_FORMULA -OPERATORS = (ast.Add, ast.BinOp, ast.Div, ast.Expression, ast.Load, ast.Mult, ast.Pow, ast.Sub, ast.UAdd, ast.UnaryOp, ast.USub) -WEIGHTS_HEADER = "| Goal | W |" -# The Exempt reasons that rank ahead of the rest of their release, in this order: a question first, since its answer may change other items, then a security finding. -FIRST = {"question": 0, "security": 1} -# How README.md marks a goal; None where it marks it neither way. -Mark = typing.Literal["Maintain", "Achieve"] | None -RESHAPE = f"todo.md's items table is in the old shape, scoring A and G against goal weights todo.md states. Until todo.md has the shape rank_todo.py --help shows, reshaping it is the project's only work, as ~/.claude/CLAUDE.md → 'Working loop' says: mark README.md's goals **Maintain:** or **Achieve:**, name each item's {MOVES}, score its L, E and I in place of C, and set the bar below the score of every item to keep" - - -@dataclasses.dataclass(frozen=True) -class Scoring: - shape: Shape - formula: ast.Expression - bar: float - next_id: int - # Every goal in rank order, each with its mark: code health first, unless README.md voids it, then README.md's goals in reading order. In OLD_SHAPE an item may name only the goals weights holds. - goals: dict[str, Mark] - # The weight of each goal an item may name: in OLD_SHAPE each of README.md's goals, at the weight todo.md states; else each goal goal_weights weighs. - weights: dict[str, float] - - -@dataclasses.dataclass(frozen=True) -class Ranked: - text: str - under_bar: list[str] - # What ranking prints and --check does not: an old-shape table's call to reshape, a README that voids code health and marks no goal **Achieve:**, and each dropped blocker ID, since a mistyped ID drops the same way. - notes: list[str] +from release_plan import ranking def main(argv: list[str]) -> int: @@ -146,43 +97,16 @@ def main(argv: list[str]) -> int: return fail(args) check, todo = args if check: - failures = check_failures(todo) + failures = ranking.check_failures(todo) for line in failures: print(line, file=sys.stderr) return 1 if failures else 0 - ranked = rank_file(todo) + ranked = ranking.rank_file(todo) if isinstance(ranked, Failure): return fail(ranked) return 1 if ranked.under_bar else 0 -def rank_file(todo: pathlib.Path) -> Ranked | Failure: - """Rank todo in place: rank what read_all reads, write todo where that changed it, and print the notes and under-bar lines on stderr.""" - texts = read_all(todo) - if isinstance(texts, Failure): - return texts - ranked = rank(*texts) - if isinstance(ranked, Failure): - return ranked - if ranked.text != texts[0] and (unwritten := write(todo, ranked.text)): - return unwritten - for line in ranked.notes + ranked.under_bar: - print(f"{todo}: {line}", file=sys.stderr) - return ranked - - -def check_failures(todo: pathlib.Path) -> list[str]: - """Why --check fails on todo, empty when it passes.""" - texts = read_all(todo) - if isinstance(texts, Failure): - return [texts.reason] - ranked = rank(*texts) - 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 fail(failure: Failure) -> int: print(failure.reason, file=sys.stderr) return 1 @@ -195,466 +119,5 @@ def parse_args(argv: list[str]) -> tuple[bool, pathlib.Path] | Failure: return "--check" in argv, pathlib.Path(paths[0] if paths else "todo.md") -def read_all(todo: pathlib.Path) -> tuple[str, str, str, str] | Failure: - """todo.md, the README.md beside it, and its docs/decisions.md and docs/comprehension-history.md, each empty when there is none.""" - texts = [] - for path, missing in ((todo, "every project keeps a todo.md beside its README.md, and rank_todo.py --help shows one"), (todo.parent / "README.md", "rank_todo.py weighs goals from the README.md beside todo.md"), (todo.parent / "docs" / "decisions.md", None), (todo.parent / HISTORY, None)): - try: - texts.append(path.read_text(encoding="utf-8")) - except FileNotFoundError: - if missing: - return Failure(f"{path}: not found; {missing}") - texts.append("") - except OSError as failure: - return Failure(f"{path}: {failure.strerror}") - except UnicodeDecodeError: - return Failure(f"{path}: not UTF-8") - return texts[0], texts[1], texts[2], texts[3] - - -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 - - -def rank(text: str, readme: str, decisions: str, history: str) -> Ranked | Failure: - lines = text.split("\n") - table = read_table(lines) - if isinstance(table, Failure): - return table - shape = shape_of(table.columns) - scoring = read_scoring(text, lines, readme, decisions, history, shape) - if isinstance(scoring, Failure): - return scoring - items = read_items(table, scoring) - if isinstance(items, Failure): - return items - if uncited := check_citations(items, decisions): - return uncited - if isinstance(marked := renames(text), Failure): - return marked - if live := next((item for item in items if item.release in marked), None): - return Failure(f"todo.md marks release {version(live.release)} renamed but files item {live.id} under it; drop the mark or move the item") - scored = ordered(items, scoring) - if isinstance(scored, Failure): - return scored - ranked = rank_details(rewrite_table(lines, table, shape, scored), [item for item, _ in scored]) - if isinstance(ranked, Failure): - return ranked - under_bar = [under_the_bar(item, value, scoring.bar, items) for item, value in scored if not item.exempt and round(value, 1) < scoring.bar] - return Ranked(ranked, under_bar, notes(items, scoring)) - - -# The columns ranking fills itself, so a table without one gains it. -WRITTEN = (BLOCKED_BY, "R", "Score") - - -def rewrite_table(lines: list[str], table: Table, shape: Shape, scored: list[tuple[Item, float]]) -> str: - """lines with the table's rows in scored's order, under a header naming, in shape's order, each column the table holds and each of WRITTEN.""" - columns = tuple(column for column in shape.columns if column in table.columns or column in WRITTEN) - header = ["| " + " | ".join(columns) + " |", "|" + "---|" * len(columns)] - rows = [render_item(item, value, shape, columns) for item, value in scored] - return "\n".join(lines[:table.header] + header + rows + lines[table.start + len(table.rows):]) - - -def notes(items: list[Item], scoring: Scoring) -> list[str]: - held = {item.id for item in items} - dropped = [f"item {item.id}: dropped {', '.join(map(str, gone))} from its {BLOCKED_BY}; the table no longer holds {'it' if len(gone) == 1 else 'them'}" for item in items if (gone := sorted(set(item.blocked_by) - held))] - if scoring.shape is OLD_SHAPE: - return [RESHAPE] + dropped - # Printed so the under-bar lines it causes do not read as items of low value. - unweighed = [] if any(scoring.weights.values()) else ["README.md voids code health and marks no goal **Achieve:**, so every item scores V 0"] - return unweighed + dropped - - -def blocked_through(id_: int, items: list[Item]) -> set[int]: - """The IDs of the items id_ blocks, and of those they block in turn.""" - found: set[int] = set() - reached = {id_} - while reached: - reached = {other.id for other in items if reached.intersection(other.blocked_by)} - found - found |= reached - return found - - -def ordered(items: list[Item], scoring: Scoring) -> list[tuple[Item, float]] | Failure: - """Each item with its score, by release, then questions and security findings first, then by score from highest, then by ID; then each blocker above every item it blocks.""" - by_score = [] - for item in items: - value = score(scoring.formula, item, scoring) - if isinstance(value, Failure): - return value - by_score.append((item, value)) - by_score.sort(key=lambda pair: (pair[0].release, FIRST.get(pair[0].exempt, len(FIRST)), -pair[1], pair[0].id)) - return blockers_first(by_score) - - -def under_the_bar(item: Item, value: float, bar: float, items: list[Item]) -> str: - blocks = [str(id_) for id_ in sorted(blocked_through(item.id, items))] - blocked = f" and the items it blocks, directly or through another ({', '.join(blocks)})" if blocks else "" - return f"item {item.id} scores {value:.1f}, under the bar {bar:g}; delete it{blocked}, or mark it with a reason the bar does not apply" - - -def read_scoring(text: str, lines: list[str], readme: str, decisions: str, history: str, shape: Shape) -> Scoring | Failure: - goals = ranked_goals(readme, decisions) - if isinstance(goals, Failure): - return goals - formula = parse_formula(stated(text, "Score"), variables(shape)) - if isinstance(formula, Failure): - return formula - bar = number(stated(text, "Bar"), "the bar") - if isinstance(bar, Failure): - return bar - next_id = stated(text, "Next ID") - if isinstance(next_id, Failure) or not re.fullmatch(r"[0-9]+", next_id): - return next_id if isinstance(next_id, Failure) else Failure(f"Next ID {next_id!r} is not a whole number") - weights = weigh(lines, history, goals, shape) - if isinstance(weights, Failure): - return weights - return Scoring(shape, formula, bar, int(next_id), dict(goals), weights) - - -def ranked_goals(readme: str, decisions: str) -> list[tuple[str, Mark]] | Failure: - """Every goal in rank order, each with its mark: code health first, unless README.md voids it, then README.md's goals in reading order. A **Void:** line other than `**Void:** code health, since .` fails, and so does a docs/decisions.md that opts out of the comprehension check where README.md keeps code health, since the goal then has no signal.""" - goals = readme_goals(readme) - if isinstance(goals, Failure): - return goals - voids = VOID.findall("".join(sections(readme).get("Goals", []))) - if other := [void for void in voids if not void.startswith(f"{CODE_HEALTH}, since ")]: - if other[0].lower().startswith(CODE_HEALTH): - return Failure(f"README.md's ## Goals voids code health as `{other[0]}`; spell the void exactly `**Void:** {CODE_HEALTH}, since .`") - return Failure(f"README.md's ## Goals voids `{other[0]}`; only code health may be voided, as `**Void:** {CODE_HEALTH}, since .`") - if voids: - return goals - if OPTED_OUT.search(decisions): - return Failure(f"docs/decisions.md opts out of the comprehension check, so code health has no signal; void it in README.md's ## Goals with `**Void:** {CODE_HEALTH}, since .`, as ~/.claude/CLAUDE.md → 'Shared goal' says") - return [(CODE_HEALTH, "Achieve"), *goals] - - -def weigh(lines: list[str], history: str, goals: list[tuple[str, Mark]], shape: Shape) -> dict[str, float] | Failure: - """Each goal's weight. In OLD_SHAPE, README.md's goals weigh what todo.md states, and code health has no weight, so no item may name it. Otherwise goal_weights gives each its weight, at the overall latest_overall reads where the goals hold code health.""" - if shape is OLD_SHAPE: - return parse_weights(lines, [number for number, _ in goals if number != CODE_HEALTH]) - if WEIGHTS_HEADER in lines: - return Failure(f"todo.md holds a goal weights table beside a {MOVES} column; drop the table, since rank_todo.py weighs the goals itself, as its --help says") - overall = latest_overall(history) if CODE_HEALTH in dict(goals) else None - if isinstance(overall, Failure): - return overall - return goal_weights(goals, overall) - - -def read_table(lines: list[str]) -> Table | Failure: - """The items table, held to its shape's columns and alone under ## Items.""" - if "## Items" not in lines: - return Failure("todo.md is not in the scored-table format; rank_todo.py --help shows a valid one") - table = items_table(lines) - if table is None: - return Failure(f"## Items holds no table whose header opens {HEADER_START}; rank_todo.py --help shows a valid one") - if isinstance(table, Failure): - return table - shape = shape_of(table.columns) - if missing := [column for column in shape.risk_columns if column not in table.columns]: - old = older_columns(table, shape) - dropped = f", and drop {listed(old, 'and')}" if old else "" - columns = f"{listed(missing, 'and')} column; add it" if len(missing) == 1 else f"{listed(missing, 'and')} columns; add them" - return Failure(f"todo.md's items table has no {columns}, scoring each item's {listed(shape.risk_columns, 'and')} as rank_todo.py --help shows{dropped}") - return unknown_columns(table, shape) or outside_items(lines, table) or table - - -def unknown_columns(table: Table, shape: Shape) -> Failure | None: - """Why ranking, which writes only the columns of the table's shape, would drop one of the table's columns; None when it would drop none.""" - unknown = [column for column in table.columns if column not in shape.columns] - if old := older_columns(table, shape): - kind = "a column of an older shape; drop it" if len(old) == 1 else "columns of an older shape; drop them" - return Failure(f"todo.md's items table has {listed(old, 'and')}, {kind}, as rank_todo.py --help shows") - if unknown: - return Failure(f"todo.md's items table has the column {', '.join(unknown)}, which this rank_todo.py does not know; the columns it knows are {', '.join(shape.columns)}. Rename it, or move this machine to the release that added it") - return None - - -def older_columns(table: Table, shape: Shape) -> list[str]: - """The table's columns that only OLD_SHAPE knows, where the table is in SHAPE.""" - return [column for column in table.columns if column not in SHAPE.columns and column in OLD_SHAPE.columns] if shape is SHAPE else [] - - -def read_items(table: Table, scoring: Scoring) -> list[Item] | Failure: - items = [] - for row in table.rows: - item = parse_item(row, scoring, table) - if isinstance(item, Failure): - return item - items.append(item) - ids = {item.id for item in items} - if len(ids) < len(items): - return Failure("two items share an ID") - if ids and max(ids) >= scoring.next_id: - return Failure(f"item {max(ids)} is not under Next ID {scoring.next_id}; raise Next ID past every ID") - for item in items: - if unheld := [blocker for blocker in item.blocked_by if blocker >= scoring.next_id]: - return Failure(f"item {item.id} is blocked by item {unheld[0]}, which is not under Next ID {scoring.next_id}; name an item the table holds or held") - return items - - -def outside_items(lines: list[str], table: Table) -> Failure | None: - """Why the table does not stand alone under ## Items: the table's order is todo.md's only order.""" - heading = max((index for index in range(table.header) if lines[index].startswith("## ")), default=None) - if heading is None: - return Failure("the items table sits under no ## heading; move it under ## Items") - if lines[heading] != "## Items": - return Failure(f"the items table sits under {lines[heading]}, not ## Items; move it under ## Items") - after = lines[table.start + len(table.rows):] - section = after[:next((index for index, line in enumerate(after) if line.startswith("## ")), len(after))] - if any(line.strip() for line in lines[heading + 1:table.header] + section): - return Failure(f"## Items holds text beside its table; an order goes in the scores or the {BLOCKED_BY} column, and a note in the item's detail") - return None - - -def blockers_first(scored: list[tuple[Item, float]]) -> list[tuple[Item, float]] | Failure: - """scored, each blocker that ranks below an item it blocks moved up to just above the first such item; a blocker the table no longer holds was finished or deleted, and is dropped.""" - held = {item.id: (item, value) for item, value in scored} - position = {item.id: index for index, (item, _) in enumerate(scored)} - for item, _ in scored: - for blocker in item.blocked_by: - if blocker in held and held[blocker][0].release > item.release: - later, earlier = version(held[blocker][0].release), version(item.release) - return Failure(f"item {item.id}, in release {earlier}, is blocked by item {blocker}, in later release {later}; move item {blocker} to release {earlier} or earlier, or item {item.id} to release {later} or later") - if loop := blocking_loop(held): - return Failure(f"items {', '.join(map(str, loop[:-1]))} and {loop[-1]} block each other in a loop; drop one of the blockers") - placed: set[int] = set() - return [entry for item, _ in scored for entry in place(item.id, held, position, placed)] - - -def blocking_loop(held: dict[int, tuple[Item, float]]) -> list[int] | None: - """The IDs of items that block each other in a loop, sorted; None where there is no loop.""" - graph = {id_: {blocker for blocker in item.blocked_by if blocker in held} for id_, (item, _) in held.items()} - try: - graphlib.TopologicalSorter(graph).prepare() - except graphlib.CycleError as cycle: - return sorted(set(cycle.args[1])) - return None - - -def place(id_: int, held: dict[int, tuple[Item, float]], position: dict[int, int], placed: set[int]) -> list[tuple[Item, float]]: - """The item id_, unless placed holds it, preceded by those of its blockers placed doesn't hold yet, each in score order, and theirs before them. Each item it returns joins placed. blocking_loop has ruled out a loop.""" - if id_ in placed: - return [] - placed.add(id_) - item, value = held[id_] - blockers = sorted((blocker for blocker in set(item.blocked_by) if blocker in held), key=position.__getitem__) - before = [entry for blocker in blockers for entry in place(blocker, held, position, placed)] - return [*before, (dataclasses.replace(item, blocked_by=tuple(sorted(blockers))), value)] - - -def check_citations(items: list[Item], decisions: str) -> Failure | None: - """Holds todo.md and docs/decisions.md to each other: a cited item is exempt, a decision row is cited.""" - cited = set(cited_items(decisions)) - if gone := sorted(cited - {item.id for item in items}): - return Failure(f"docs/decisions.md cites \"`todo.md` item {gone[0]}\", which todo.md no longer holds; revise that decision to say what holds now") - for item in sorted(items, key=lambda item: item.id): - if item.id in cited and not item.exempt: - return Failure(f"docs/decisions.md cites \"`todo.md` item {item.id}\"; mark it decision, or another reason the bar does not apply") - if item.exempt == "decision" and item.id not in cited: - return Failure(f"item {item.id} is marked decision, but docs/decisions.md does not cite \"`todo.md` item {item.id}\"; cite it there, or mark it with another reason the bar does not apply") - return None - - -def readme_goals(readme: str) -> list[tuple[str, Mark]] | Failure: - """README.md's goals in reading order: each one's number, a sub-goal as 4.1, and its mark, Maintain, Achieve or None.""" - found = sections(readme).get("Goals", []) - if len(found) != 1: - return Failure(f"README.md has ## Goals {len(found)} times; it needs it once") - goals: list[tuple[str, Mark]] = [] - path: list[tuple[int, str]] = [] - for indent, position, mark in re.findall(r"^([ \t]*)(\d+)\. (?:\*\*(Maintain|Achieve):\*\*)?", found[0].expandtabs(4), re.M): - while path and path[-1][0] >= len(indent): - path.pop() - path.append((len(indent), position)) - goals.append((".".join(part for _, part in path), typing.cast(Mark, mark or None))) - numbers = [number for number, _ in goals] - if not goals: - return Failure("README.md's ## Goals has no numbered goal") - if len(set(numbers)) < len(numbers): - return Failure(f"README.md's ## Goals numbers {', '.join(numbers)}; number each goal by its position") - return goals - - -def goal_weights(goals: list[tuple[str, Mark]], overall: decimal.Decimal | None) -> dict[str, float] | Failure: - """Each achieve goal's weight: the one ranked k of n weighs GOAL_STEP ** (k - 1) / (1 + GOAL_STEP + ... + GOAL_STEP ** (n - 1)), so the weights sum to 1. Code health, where goals holds it, then weighs UNDER_FLOOR times that while the overall is under FLOOR or None, and the other goals keep their weights. Each maintain goal weighs as the heaviest achieve goal, since a broken one outranks any achieve goal; only a defect that restores it may name it. Every weight is 0 where goals holds no achieve goal, as where README.md voids code health and marks no goal **Achieve:**, so every item scores V 0 and only an exempt one passes the bar.""" - if unmarked := [number for number, mark in goals if mark is None]: - return Failure(f"README.md's goal {unmarked[0]} is marked neither **Maintain:** nor **Achieve:**; mark it, as ~/.claude/rules/goals-and-audience.md says, so rank_todo.py knows which goals score") - achieve = [number for number, mark in goals if mark == "Achieve"] - total = sum(GOAL_STEP**rank for rank in range(len(achieve))) - weights = {number: GOAL_STEP**rank / total for rank, number in enumerate(achieve)} - if CODE_HEALTH in weights and (overall is None or overall < FLOOR): - weights[CODE_HEALTH] *= UNDER_FLOOR - heaviest = max(weights.values(), default=0.0) - return weights | {number: heaviest for number, mark in goals if mark == "Maintain"} - - -def cited_items(decisions: str) -> list[int]: - return [int(id_) for cited in re.findall(r"`todo\.md` items? (\d+(?:(?:, | and )\d+)*)", decisions) for id_ in re.findall(r"\d+", cited)] - - -def stated(text: str, name: str) -> str | Failure: - found = re.findall(rf"^`{name} = ([^`]+)`$", text, re.M) - if len(found) != 1: - return Failure(f"todo.md states `{name} = ...` {len(found)} times; state it once, on a line of its own under ## Scoring") - return found[0] - - -def parse_formula(source: str | Failure, variables: tuple[str, ...]) -> ast.Expression | Failure: - if isinstance(source, Failure): - return source - # Deep nesting makes the parser itself run out of memory before LARGEST_FORMULA can count the parts. - if len(source) > LONGEST_FORMULA: - return Failure(f"the formula {source[:40]!r}... holds more than {LONGEST_FORMULA} characters") - try: - tree = ast.parse(source, mode="eval") - except (SyntaxError, ValueError): - return Failure(f"the formula {source!r} does not parse") - nodes = list(ast.walk(tree)) - if len(nodes) > LARGEST_FORMULA: - return Failure(f"the formula {source!r} holds more than {LARGEST_FORMULA} parts") - for node in nodes: - numeric = isinstance(node, ast.Constant) and isinstance(node.value, (int, float)) and not isinstance(node.value, bool) and abs(node.value) < 1e300 - if not (isinstance(node, OPERATORS) or numeric or (isinstance(node, ast.Name) and node.id in variables)): - return Failure(f"the formula {source!r} may hold only numbers, {', '.join(variables)}, + - * / ** and parentheses") - return tree - - -def evaluate(node: ast.AST, values: dict[str, float]) -> float: - """Evaluates a tree parse_formula accepted; a division by zero, and a power that overflows or has no real value, give nan.""" - match node: - case ast.Expression(body): - return evaluate(body, values) - case ast.Constant(value) if isinstance(value, (int, float)): - return float(value) - case ast.Name(name): - return values[name] - case ast.UnaryOp(ast.USub(), operand): - return -evaluate(operand, values) - case ast.UnaryOp(ast.UAdd(), operand): - return evaluate(operand, values) - case ast.BinOp(left, ast.Add(), right): - return evaluate(left, values) + evaluate(right, values) - case ast.BinOp(left, ast.Sub(), right): - return evaluate(left, values) - evaluate(right, values) - case ast.BinOp(left, ast.Mult(), right): - return evaluate(left, values) * evaluate(right, values) - case ast.BinOp(left, ast.Div(), right): - divisor = evaluate(right, values) - return evaluate(left, values) / divisor if divisor else math.nan - case ast.BinOp(left, ast.Pow(), right): - # math.pow raises on a negative base with a fractional exponent, zero to a negative power, and overflow; one catch covers all three. - base, exponent = evaluate(left, values), evaluate(right, values) - # A nan from a zero divisor stays nan, though math.pow(1, nan) and math.pow(nan, 0) give 1. - if math.isnan(base) or math.isnan(exponent): - return math.nan - try: - return math.pow(base, exponent) - except (OverflowError, ValueError): - return math.nan - return math.nan - - -def goal_term(shape: Shape) -> str: - """The name of the formula's goal term, which score builds: W in OLD_SHAPE, V in the current shape.""" - return "W" if shape is OLD_SHAPE else "V" - - -def variables(shape: Shape) -> tuple[str, ...]: - """The names the formula may use: the shape's scores but C, which stays out of the formula, and its goal term.""" - return tuple(sorted({*shape.score_columns} - {"C"} | {goal_term(shape)})) - - -def score(formula: ast.Expression, item: Item, scoring: Scoring) -> float | Failure: - if goal_term(scoring.shape) == "W": - # The old shape weighs an item by its heaviest cited goal. - term = max(scoring.weights[goal] for goal, _ in item.moves) - else: - # Only an OLD_SHAPE item names a goal without a move. - term = sum(scoring.weights[goal] * (by or 0) for goal, by in item.moves) - value = evaluate(formula, {**item.scores, goal_term(scoring.shape): term}) - return value if math.isfinite(value) else Failure(f"the formula gives item {item.id} no finite score") - - -def number(text: str | Failure, what: str) -> float | Failure: - if isinstance(text, Failure): - return text - try: - value = float(text) - except ValueError: - value = math.nan - return value if math.isfinite(value) else Failure(f"{what} {text!r} is not a finite number") - - -def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float] | Failure: - table = table_rows(lines, WEIGHTS_HEADER) - if isinstance(table, Failure): - return table - weights: dict[str, float] = {} - for row in table.rows: - found = cells(row, 2) - if isinstance(found, Failure): - return found - weight = number(found[1], f"goal {found[0]}'s weight") - if isinstance(weight, Failure): - return weight - if found[0] in weights: - return Failure(f"the goal weights list goal {found[0]} twice") - weights[found[0]] = weight - if list(weights) != goals: - default = "\n".join(f"| {goal} | {(len(goals) - index) / len(goals):.2f} |" for index, goal in enumerate(goals)) - return Failure(f"the goal weights list {', '.join(weights) or 'no goal'}, but README.md's goals are {', '.join(goals)}; by position they weigh:\n{WEIGHTS_HEADER}\n|---|---|\n{default}") - return weights - - -def parse_item(row: str, scoring: Scoring, table: Table) -> Item | Failure: - """The row as an item, refused where it names a goal it may not; in SHAPE, with the R its L, E and I give.""" - item = parse_row(row, table) - if isinstance(item, Failure): - return item - if broken := cited_goals_failure(item, scoring): - return broken - if scoring.shape is OLD_SHAPE: - return item - # R is written here, as the Score is, so --check finds a stale one, and a reader keeps the R the table stored. - return dataclasses.replace(item, scores=item.scores | {"R": risk(item.scores["L"], item.scores["E"], item.scores["I"])}) - - -def cited_goals_failure(item: Item, scoring: Scoring) -> Failure | None: - """Why the item may not name one of the goals it names, such as one README.md voids or does not number; None when it may name each. todo_table's parse_moves holds the rules a Moves cell keeps on its own.""" - if scoring.shape is OLD_SHAPE: - unknown = [goal for goal, _ in item.moves if goal not in scoring.weights] - return Failure(f"item {item.id} cites goal {', '.join(unknown)}, which the goal weights do not list") if unknown else None - for goal, _ in item.moves: - if goal == CODE_HEALTH and goal not in scoring.goals: - return Failure(f"item {item.id} names {CODE_HEALTH}, which README.md voids; drop it from the item's {MOVES}, or the void from README.md") - if goal not in scoring.goals: - return Failure(f"item {item.id} cites goal {goal}, which README.md's ## Goals does not number") - if scoring.goals[goal] == "Maintain" and item.exempt != "defect": - return Failure(f"item {item.id} cites goal {goal}, a maintain goal, which only a defect that restores it may name; name the achieve goals the item moves") - return None - - -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}"} - return "| " + " | ".join(written[column] for column in columns) + " |" - - -def rank_details(text: str, items: list[Item]) -> str | Failure: - section = DETAILS.search(text) - details = item_details(text) - if section is None or isinstance(details, 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] - 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():] - - if __name__ == "__main__": sys.exit(main(sys.argv[1:])) diff --git a/bin/reading_cost/figures.py b/bin/reading_cost/figures.py index 286baaa7..3710b62c 100644 --- a/bin/reading_cost/figures.py +++ b/bin/reading_cost/figures.py @@ -5,8 +5,8 @@ import statistics from failure import Failure from transcript_archive.read import FinishedChunk from reading_cost.measure import Reading -from markdown_text import sections -from utc_stamp import STAMPED +from records.markdown_text import sections +from records.utc_stamp import STAMPED FIGURE = re.compile(rf"^Reading cost, chunk (\w+), finished ({STAMPED})$") FIGURE_FILE = re.compile(r"^- `(.+)` (\d+)$") diff --git a/bin/reading_cost/main.py b/bin/reading_cost/main.py index 9a516c69..bbf94b12 100644 --- a/bin/reading_cost/main.py +++ b/bin/reading_cost/main.py @@ -32,10 +32,10 @@ from reading_cost.measure import Checkout, measure, Reading from failure import Failure from reading_cost.figures import figure, merged, readings_of, RECORD, RESET, trend, unheld from transcript_archive.read import finished_chunks, read_threads -from git_repo import git +from git_cli.git_repo import git from transcript_archive.location import project_archive -from file_writes import replace_file -from utc_stamp import utc +from records.file_writes import replace_file +from records.utc_stamp import utc @dataclasses.dataclass(frozen=True) class Updated: diff --git a/bin/reading_cost/measure.py b/bin/reading_cost/measure.py index 0b671703..4b241590 100644 --- a/bin/reading_cost/measure.py +++ b/bin/reading_cost/measure.py @@ -3,9 +3,9 @@ import dataclasses import re from claude_code.entries import assistant_parts, parse_entry, tool_call, usage_count -from git_command import commits +from git_cli.git_command import commits from reading_cost.shell_reads import Reads, shell_reads -from shell_command import resolved, simple_commands +from command_lines.shell_command import resolved, simple_commands diff --git a/bin/reading_cost/shell_reads.py b/bin/reading_cost/shell_reads.py index 69593060..9dba9726 100644 --- a/bin/reading_cost/shell_reads.py +++ b/bin/reading_cost/shell_reads.py @@ -3,7 +3,7 @@ import dataclasses import posixpath import re -from shell_command import resolved, simple_commands +from command_lines.shell_command import resolved, simple_commands NOT_A_PATH = re.compile(r"[*?\[\]{}$\\'\",=()<>|;&]|://|^\d+$") # Their first operand is a pattern or a program, unless -e or -f gives it. diff --git a/bin/records/__init__.py b/bin/records/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/file_writes.py b/bin/records/file_writes.py similarity index 100% rename from bin/file_writes.py rename to bin/records/file_writes.py diff --git a/bin/markdown_text.py b/bin/records/markdown_text.py similarity index 100% rename from bin/markdown_text.py rename to bin/records/markdown_text.py diff --git a/bin/test_file_writes.py b/bin/records/test_file_writes.py similarity index 83% rename from bin/test_file_writes.py rename to bin/records/test_file_writes.py index 420a62c7..9f87de33 100644 --- a/bin/test_file_writes.py +++ b/bin/records/test_file_writes.py @@ -4,10 +4,10 @@ import sys import tempfile import unittest -sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from failure import Failure -import file_writes +from records import file_writes class ReplaceFile(unittest.TestCase): diff --git a/bin/test_markdown_text.py b/bin/records/test_markdown_text.py similarity index 93% rename from bin/test_markdown_text.py rename to bin/records/test_markdown_text.py index 8b4dea08..92de02c5 100644 --- a/bin/test_markdown_text.py +++ b/bin/records/test_markdown_text.py @@ -2,9 +2,9 @@ import pathlib import sys import unittest -sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -import markdown_text +from records import markdown_text class Sections(unittest.TestCase): diff --git a/bin/utc_stamp.py b/bin/records/utc_stamp.py similarity index 100% rename from bin/utc_stamp.py rename to bin/records/utc_stamp.py diff --git a/bin/release_plan/__init__.py b/bin/release_plan/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/release_plan/ranking.py b/bin/release_plan/ranking.py new file mode 100644 index 00000000..9d4b1b41 --- /dev/null +++ b/bin/release_plan/ranking.py @@ -0,0 +1,544 @@ +"""Rank todo.md's items by the formula it states, weighing code health first and then README.md's achieve goals by their position, and hold them to its bar; rank_todo.py --help states the rules.""" +import ast +import dataclasses +import decimal +import graphlib +import math +import pathlib +import re +import sys +import typing + +from release_plan.todo_table import BLOCKED_BY, cells, CODE_HEALTH, DETAILS, HEADER_START, Item, item_details, items_table, MOVES, OLD_SHAPE, parse_row, renames, risk, Shape, SHAPE, shape_of, Table, table_rows +from failure import Failure +from review_rules.comprehension_history import FLOOR, HISTORY, latest_overall +from records.markdown_text import listed, sections +from records.file_writes import replace_file +from release_plan.release import version + +# What each achieve goal weighs of the one above it; docs/decisions.md records the choice. +GOAL_STEP = 0.97 +# Code health weighs this many times its weight by position while the comprehension panel's overall is under FLOOR, or unmeasured; lilleman's choice, which docs/decisions.md records. +UNDER_FLOOR = 4 +# Any **Void:** line of README.md's ## Goals; ranked_goals accepts only `**Void:** code health, since .`, as ~/.claude/CLAUDE.md → "Shared goal" spells it. +VOID = re.compile(r"^\*\*Void:\*\* (.*)$", re.M) +# A docs/decisions.md title opting the project out of the comprehension check, as larv-review's SKILL.md → "Opt-out" spells it. +OPTED_OUT = re.compile(r"^## review opt-out:.*\bcomprehension check\b", re.M) +LARGEST_FORMULA = 200 +LONGEST_FORMULA = 4 * LARGEST_FORMULA +OPERATORS = (ast.Add, ast.BinOp, ast.Div, ast.Expression, ast.Load, ast.Mult, ast.Pow, ast.Sub, ast.UAdd, ast.UnaryOp, ast.USub) +WEIGHTS_HEADER = "| Goal | W |" +# The Exempt reasons that rank ahead of the rest of their release, in this order: a question first, since its answer may change other items, then a security finding. +FIRST = {"question": 0, "security": 1} +# How README.md marks a goal; None where it marks it neither way. +Mark = typing.Literal["Maintain", "Achieve"] | None +RESHAPE = f"todo.md's items table is in the old shape, scoring A and G against goal weights todo.md states. Until todo.md has the shape rank_todo.py --help shows, reshaping it is the project's only work, as ~/.claude/CLAUDE.md → 'Working loop' says: mark README.md's goals **Maintain:** or **Achieve:**, name each item's {MOVES}, score its L, E and I in place of C, and set the bar below the score of every item to keep" + + +@dataclasses.dataclass(frozen=True) +class Scoring: + shape: Shape + formula: ast.Expression + bar: float + next_id: int + # Every goal in rank order, each with its mark: code health first, unless README.md voids it, then README.md's goals in reading order. In OLD_SHAPE an item may name only the goals weights holds. + goals: dict[str, Mark] + # The weight of each goal an item may name: in OLD_SHAPE each of README.md's goals, at the weight todo.md states; else each goal goal_weights weighs. + weights: dict[str, float] + + +@dataclasses.dataclass(frozen=True) +class Ranked: + text: str + under_bar: list[str] + # What ranking prints and --check does not: an old-shape table's call to reshape, a README that voids code health and marks no goal **Achieve:**, and each dropped blocker ID, since a mistyped ID drops the same way. + notes: list[str] + + +def rank_file(todo: pathlib.Path) -> Ranked | Failure: + """Rank todo in place: rank what read_all reads, write todo where that changed it, and print the notes and under-bar lines on stderr.""" + texts = read_all(todo) + if isinstance(texts, Failure): + return texts + ranked = rank(*texts) + if isinstance(ranked, Failure): + return ranked + if ranked.text != texts[0] and (unwritten := write(todo, ranked.text)): + return unwritten + for line in ranked.notes + ranked.under_bar: + print(f"{todo}: {line}", file=sys.stderr) + return ranked + + +def check_failures(todo: pathlib.Path) -> list[str]: + """Why --check fails on todo, empty when it passes.""" + texts = read_all(todo) + if isinstance(texts, Failure): + return [texts.reason] + ranked = rank(*texts) + 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 read_all(todo: pathlib.Path) -> tuple[str, str, str, str] | Failure: + """todo.md, the README.md beside it, and its docs/decisions.md and docs/comprehension-history.md, each empty when there is none.""" + texts = [] + for path, missing in ((todo, "every project keeps a todo.md beside its README.md, and rank_todo.py --help shows one"), (todo.parent / "README.md", "rank_todo.py weighs goals from the README.md beside todo.md"), (todo.parent / "docs" / "decisions.md", None), (todo.parent / HISTORY, None)): + try: + texts.append(path.read_text(encoding="utf-8")) + except FileNotFoundError: + if missing: + return Failure(f"{path}: not found; {missing}") + texts.append("") + except OSError as failure: + return Failure(f"{path}: {failure.strerror}") + except UnicodeDecodeError: + return Failure(f"{path}: not UTF-8") + return texts[0], texts[1], texts[2], texts[3] + + +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 + + +def rank(text: str, readme: str, decisions: str, history: str) -> Ranked | Failure: + lines = text.split("\n") + table = read_table(lines) + if isinstance(table, Failure): + return table + shape = shape_of(table.columns) + scoring = read_scoring(text, lines, readme, decisions, history, shape) + if isinstance(scoring, Failure): + return scoring + items = read_items(table, scoring) + if isinstance(items, Failure): + return items + if uncited := check_citations(items, decisions): + return uncited + if isinstance(marked := renames(text), Failure): + return marked + if live := next((item for item in items if item.release in marked), None): + return Failure(f"todo.md marks release {version(live.release)} renamed but files item {live.id} under it; drop the mark or move the item") + scored = ordered(items, scoring) + if isinstance(scored, Failure): + return scored + ranked = rank_details(rewrite_table(lines, table, shape, scored), [item for item, _ in scored]) + if isinstance(ranked, Failure): + return ranked + under_bar = [under_the_bar(item, value, scoring.bar, items) for item, value in scored if not item.exempt and round(value, 1) < scoring.bar] + return Ranked(ranked, under_bar, notes(items, scoring)) + + +# The columns ranking fills itself, so a table without one gains it. +WRITTEN = (BLOCKED_BY, "R", "Score") + + +def rewrite_table(lines: list[str], table: Table, shape: Shape, scored: list[tuple[Item, float]]) -> str: + """lines with the table's rows in scored's order, under a header naming, in shape's order, each column the table holds and each of WRITTEN.""" + columns = tuple(column for column in shape.columns if column in table.columns or column in WRITTEN) + header = ["| " + " | ".join(columns) + " |", "|" + "---|" * len(columns)] + rows = [render_item(item, value, shape, columns) for item, value in scored] + return "\n".join(lines[:table.header] + header + rows + lines[table.start + len(table.rows):]) + + +def notes(items: list[Item], scoring: Scoring) -> list[str]: + held = {item.id for item in items} + dropped = [f"item {item.id}: dropped {', '.join(map(str, gone))} from its {BLOCKED_BY}; the table no longer holds {'it' if len(gone) == 1 else 'them'}" for item in items if (gone := sorted(set(item.blocked_by) - held))] + if scoring.shape is OLD_SHAPE: + return [RESHAPE] + dropped + # Printed so the under-bar lines it causes do not read as items of low value. + unweighed = [] if any(scoring.weights.values()) else ["README.md voids code health and marks no goal **Achieve:**, so every item scores V 0"] + return unweighed + dropped + + +def blocked_through(id_: int, items: list[Item]) -> set[int]: + """The IDs of the items id_ blocks, and of those they block in turn.""" + found: set[int] = set() + reached = {id_} + while reached: + reached = {other.id for other in items if reached.intersection(other.blocked_by)} - found + found |= reached + return found + + +def ordered(items: list[Item], scoring: Scoring) -> list[tuple[Item, float]] | Failure: + """Each item with its score, by release, then questions and security findings first, then by score from highest, then by ID; then each blocker above every item it blocks.""" + by_score = [] + for item in items: + value = score(scoring.formula, item, scoring) + if isinstance(value, Failure): + return value + by_score.append((item, value)) + by_score.sort(key=lambda pair: (pair[0].release, FIRST.get(pair[0].exempt, len(FIRST)), -pair[1], pair[0].id)) + return blockers_first(by_score) + + +def under_the_bar(item: Item, value: float, bar: float, items: list[Item]) -> str: + blocks = [str(id_) for id_ in sorted(blocked_through(item.id, items))] + blocked = f" and the items it blocks, directly or through another ({', '.join(blocks)})" if blocks else "" + return f"item {item.id} scores {value:.1f}, under the bar {bar:g}; delete it{blocked}, or mark it with a reason the bar does not apply" + + +def read_scoring(text: str, lines: list[str], readme: str, decisions: str, history: str, shape: Shape) -> Scoring | Failure: + goals = ranked_goals(readme, decisions) + if isinstance(goals, Failure): + return goals + formula = parse_formula(stated(text, "Score"), variables(shape)) + if isinstance(formula, Failure): + return formula + bar = number(stated(text, "Bar"), "the bar") + if isinstance(bar, Failure): + return bar + next_id = stated(text, "Next ID") + if isinstance(next_id, Failure) or not re.fullmatch(r"[0-9]+", next_id): + return next_id if isinstance(next_id, Failure) else Failure(f"Next ID {next_id!r} is not a whole number") + weights = weigh(lines, history, goals, shape) + if isinstance(weights, Failure): + return weights + return Scoring(shape, formula, bar, int(next_id), dict(goals), weights) + + +def ranked_goals(readme: str, decisions: str) -> list[tuple[str, Mark]] | Failure: + """Every goal in rank order, each with its mark: code health first, unless README.md voids it, then README.md's goals in reading order. A **Void:** line other than `**Void:** code health, since .` fails, and so does a docs/decisions.md that opts out of the comprehension check where README.md keeps code health, since the goal then has no signal.""" + goals = readme_goals(readme) + if isinstance(goals, Failure): + return goals + voids = VOID.findall("".join(sections(readme).get("Goals", []))) + if other := [void for void in voids if not void.startswith(f"{CODE_HEALTH}, since ")]: + if other[0].lower().startswith(CODE_HEALTH): + return Failure(f"README.md's ## Goals voids code health as `{other[0]}`; spell the void exactly `**Void:** {CODE_HEALTH}, since .`") + return Failure(f"README.md's ## Goals voids `{other[0]}`; only code health may be voided, as `**Void:** {CODE_HEALTH}, since .`") + if voids: + return goals + if OPTED_OUT.search(decisions): + return Failure(f"docs/decisions.md opts out of the comprehension check, so code health has no signal; void it in README.md's ## Goals with `**Void:** {CODE_HEALTH}, since .`, as ~/.claude/CLAUDE.md → 'Shared goal' says") + return [(CODE_HEALTH, "Achieve"), *goals] + + +def weigh(lines: list[str], history: str, goals: list[tuple[str, Mark]], shape: Shape) -> dict[str, float] | Failure: + """Each goal's weight. In OLD_SHAPE, README.md's goals weigh what todo.md states, and code health has no weight, so no item may name it. Otherwise goal_weights gives each its weight, at the overall latest_overall reads where the goals hold code health.""" + if shape is OLD_SHAPE: + return parse_weights(lines, [number for number, _ in goals if number != CODE_HEALTH]) + if WEIGHTS_HEADER in lines: + return Failure(f"todo.md holds a goal weights table beside a {MOVES} column; drop the table, since rank_todo.py weighs the goals itself, as its --help says") + overall = latest_overall(history) if CODE_HEALTH in dict(goals) else None + if isinstance(overall, Failure): + return overall + return goal_weights(goals, overall) + + +def read_table(lines: list[str]) -> Table | Failure: + """The items table, held to its shape's columns and alone under ## Items.""" + if "## Items" not in lines: + return Failure("todo.md is not in the scored-table format; rank_todo.py --help shows a valid one") + table = items_table(lines) + if table is None: + return Failure(f"## Items holds no table whose header opens {HEADER_START}; rank_todo.py --help shows a valid one") + if isinstance(table, Failure): + return table + shape = shape_of(table.columns) + if missing := [column for column in shape.risk_columns if column not in table.columns]: + old = older_columns(table, shape) + dropped = f", and drop {listed(old, 'and')}" if old else "" + columns = f"{listed(missing, 'and')} column; add it" if len(missing) == 1 else f"{listed(missing, 'and')} columns; add them" + return Failure(f"todo.md's items table has no {columns}, scoring each item's {listed(shape.risk_columns, 'and')} as rank_todo.py --help shows{dropped}") + return unknown_columns(table, shape) or outside_items(lines, table) or table + + +def unknown_columns(table: Table, shape: Shape) -> Failure | None: + """Why ranking, which writes only the columns of the table's shape, would drop one of the table's columns; None when it would drop none.""" + unknown = [column for column in table.columns if column not in shape.columns] + if old := older_columns(table, shape): + kind = "a column of an older shape; drop it" if len(old) == 1 else "columns of an older shape; drop them" + return Failure(f"todo.md's items table has {listed(old, 'and')}, {kind}, as rank_todo.py --help shows") + if unknown: + return Failure(f"todo.md's items table has the column {', '.join(unknown)}, which this rank_todo.py does not know; the columns it knows are {', '.join(shape.columns)}. Rename it, or move this machine to the release that added it") + return None + + +def older_columns(table: Table, shape: Shape) -> list[str]: + """The table's columns that only OLD_SHAPE knows, where the table is in SHAPE.""" + return [column for column in table.columns if column not in SHAPE.columns and column in OLD_SHAPE.columns] if shape is SHAPE else [] + + +def read_items(table: Table, scoring: Scoring) -> list[Item] | Failure: + items = [] + for row in table.rows: + item = parse_item(row, scoring, table) + if isinstance(item, Failure): + return item + items.append(item) + ids = {item.id for item in items} + if len(ids) < len(items): + return Failure("two items share an ID") + if ids and max(ids) >= scoring.next_id: + return Failure(f"item {max(ids)} is not under Next ID {scoring.next_id}; raise Next ID past every ID") + for item in items: + if unheld := [blocker for blocker in item.blocked_by if blocker >= scoring.next_id]: + return Failure(f"item {item.id} is blocked by item {unheld[0]}, which is not under Next ID {scoring.next_id}; name an item the table holds or held") + return items + + +def outside_items(lines: list[str], table: Table) -> Failure | None: + """Why the table does not stand alone under ## Items: the table's order is todo.md's only order.""" + heading = max((index for index in range(table.header) if lines[index].startswith("## ")), default=None) + if heading is None: + return Failure("the items table sits under no ## heading; move it under ## Items") + if lines[heading] != "## Items": + return Failure(f"the items table sits under {lines[heading]}, not ## Items; move it under ## Items") + after = lines[table.start + len(table.rows):] + section = after[:next((index for index, line in enumerate(after) if line.startswith("## ")), len(after))] + if any(line.strip() for line in lines[heading + 1:table.header] + section): + return Failure(f"## Items holds text beside its table; an order goes in the scores or the {BLOCKED_BY} column, and a note in the item's detail") + return None + + +def blockers_first(scored: list[tuple[Item, float]]) -> list[tuple[Item, float]] | Failure: + """scored, each blocker that ranks below an item it blocks moved up to just above the first such item; a blocker the table no longer holds was finished or deleted, and is dropped.""" + held = {item.id: (item, value) for item, value in scored} + position = {item.id: index for index, (item, _) in enumerate(scored)} + for item, _ in scored: + for blocker in item.blocked_by: + if blocker in held and held[blocker][0].release > item.release: + later, earlier = version(held[blocker][0].release), version(item.release) + return Failure(f"item {item.id}, in release {earlier}, is blocked by item {blocker}, in later release {later}; move item {blocker} to release {earlier} or earlier, or item {item.id} to release {later} or later") + if loop := blocking_loop(held): + return Failure(f"items {', '.join(map(str, loop[:-1]))} and {loop[-1]} block each other in a loop; drop one of the blockers") + placed: set[int] = set() + return [entry for item, _ in scored for entry in place(item.id, held, position, placed)] + + +def blocking_loop(held: dict[int, tuple[Item, float]]) -> list[int] | None: + """The IDs of items that block each other in a loop, sorted; None where there is no loop.""" + graph = {id_: {blocker for blocker in item.blocked_by if blocker in held} for id_, (item, _) in held.items()} + try: + graphlib.TopologicalSorter(graph).prepare() + except graphlib.CycleError as cycle: + return sorted(set(cycle.args[1])) + return None + + +def place(id_: int, held: dict[int, tuple[Item, float]], position: dict[int, int], placed: set[int]) -> list[tuple[Item, float]]: + """The item id_, unless placed holds it, preceded by those of its blockers placed doesn't hold yet, each in score order, and theirs before them. Each item it returns joins placed. blocking_loop has ruled out a loop.""" + if id_ in placed: + return [] + placed.add(id_) + item, value = held[id_] + blockers = sorted((blocker for blocker in set(item.blocked_by) if blocker in held), key=position.__getitem__) + before = [entry for blocker in blockers for entry in place(blocker, held, position, placed)] + return [*before, (dataclasses.replace(item, blocked_by=tuple(sorted(blockers))), value)] + + +def check_citations(items: list[Item], decisions: str) -> Failure | None: + """Holds todo.md and docs/decisions.md to each other: a cited item is exempt, a decision row is cited.""" + cited = set(cited_items(decisions)) + if gone := sorted(cited - {item.id for item in items}): + return Failure(f"docs/decisions.md cites \"`todo.md` item {gone[0]}\", which todo.md no longer holds; revise that decision to say what holds now") + for item in sorted(items, key=lambda item: item.id): + if item.id in cited and not item.exempt: + return Failure(f"docs/decisions.md cites \"`todo.md` item {item.id}\"; mark it decision, or another reason the bar does not apply") + if item.exempt == "decision" and item.id not in cited: + return Failure(f"item {item.id} is marked decision, but docs/decisions.md does not cite \"`todo.md` item {item.id}\"; cite it there, or mark it with another reason the bar does not apply") + return None + + +def readme_goals(readme: str) -> list[tuple[str, Mark]] | Failure: + """README.md's goals in reading order: each one's number, a sub-goal as 4.1, and its mark, Maintain, Achieve or None.""" + found = sections(readme).get("Goals", []) + if len(found) != 1: + return Failure(f"README.md has ## Goals {len(found)} times; it needs it once") + goals: list[tuple[str, Mark]] = [] + path: list[tuple[int, str]] = [] + for indent, position, mark in re.findall(r"^([ \t]*)(\d+)\. (?:\*\*(Maintain|Achieve):\*\*)?", found[0].expandtabs(4), re.M): + while path and path[-1][0] >= len(indent): + path.pop() + path.append((len(indent), position)) + goals.append((".".join(part for _, part in path), typing.cast(Mark, mark or None))) + numbers = [number for number, _ in goals] + if not goals: + return Failure("README.md's ## Goals has no numbered goal") + if len(set(numbers)) < len(numbers): + return Failure(f"README.md's ## Goals numbers {', '.join(numbers)}; number each goal by its position") + return goals + + +def goal_weights(goals: list[tuple[str, Mark]], overall: decimal.Decimal | None) -> dict[str, float] | Failure: + """Each achieve goal's weight: the one ranked k of n weighs GOAL_STEP ** (k - 1) / (1 + GOAL_STEP + ... + GOAL_STEP ** (n - 1)), so the weights sum to 1. Code health, where goals holds it, then weighs UNDER_FLOOR times that while the overall is under FLOOR or None, and the other goals keep their weights. Each maintain goal weighs as the heaviest achieve goal, since a broken one outranks any achieve goal; only a defect that restores it may name it. Every weight is 0 where goals holds no achieve goal, as where README.md voids code health and marks no goal **Achieve:**, so every item scores V 0 and only an exempt one passes the bar.""" + if unmarked := [number for number, mark in goals if mark is None]: + return Failure(f"README.md's goal {unmarked[0]} is marked neither **Maintain:** nor **Achieve:**; mark it, as ~/.claude/rules/goals-and-audience.md says, so rank_todo.py knows which goals score") + achieve = [number for number, mark in goals if mark == "Achieve"] + total = sum(GOAL_STEP**rank for rank in range(len(achieve))) + weights = {number: GOAL_STEP**rank / total for rank, number in enumerate(achieve)} + if CODE_HEALTH in weights and (overall is None or overall < FLOOR): + weights[CODE_HEALTH] *= UNDER_FLOOR + heaviest = max(weights.values(), default=0.0) + return weights | {number: heaviest for number, mark in goals if mark == "Maintain"} + + +def cited_items(decisions: str) -> list[int]: + return [int(id_) for cited in re.findall(r"`todo\.md` items? (\d+(?:(?:, | and )\d+)*)", decisions) for id_ in re.findall(r"\d+", cited)] + + +def stated(text: str, name: str) -> str | Failure: + found = re.findall(rf"^`{name} = ([^`]+)`$", text, re.M) + if len(found) != 1: + return Failure(f"todo.md states `{name} = ...` {len(found)} times; state it once, on a line of its own under ## Scoring") + return found[0] + + +def parse_formula(source: str | Failure, variables: tuple[str, ...]) -> ast.Expression | Failure: + if isinstance(source, Failure): + return source + # Deep nesting makes the parser itself run out of memory before LARGEST_FORMULA can count the parts. + if len(source) > LONGEST_FORMULA: + return Failure(f"the formula {source[:40]!r}... holds more than {LONGEST_FORMULA} characters") + try: + tree = ast.parse(source, mode="eval") + except (SyntaxError, ValueError): + return Failure(f"the formula {source!r} does not parse") + nodes = list(ast.walk(tree)) + if len(nodes) > LARGEST_FORMULA: + return Failure(f"the formula {source!r} holds more than {LARGEST_FORMULA} parts") + for node in nodes: + numeric = isinstance(node, ast.Constant) and isinstance(node.value, (int, float)) and not isinstance(node.value, bool) and abs(node.value) < 1e300 + if not (isinstance(node, OPERATORS) or numeric or (isinstance(node, ast.Name) and node.id in variables)): + return Failure(f"the formula {source!r} may hold only numbers, {', '.join(variables)}, + - * / ** and parentheses") + return tree + + +def evaluate(node: ast.AST, values: dict[str, float]) -> float: + """Evaluates a tree parse_formula accepted; a division by zero, and a power that overflows or has no real value, give nan.""" + match node: + case ast.Expression(body): + return evaluate(body, values) + case ast.Constant(value) if isinstance(value, (int, float)): + return float(value) + case ast.Name(name): + return values[name] + case ast.UnaryOp(ast.USub(), operand): + return -evaluate(operand, values) + case ast.UnaryOp(ast.UAdd(), operand): + return evaluate(operand, values) + case ast.BinOp(left, ast.Add(), right): + return evaluate(left, values) + evaluate(right, values) + case ast.BinOp(left, ast.Sub(), right): + return evaluate(left, values) - evaluate(right, values) + case ast.BinOp(left, ast.Mult(), right): + return evaluate(left, values) * evaluate(right, values) + case ast.BinOp(left, ast.Div(), right): + divisor = evaluate(right, values) + return evaluate(left, values) / divisor if divisor else math.nan + case ast.BinOp(left, ast.Pow(), right): + # math.pow raises on a negative base with a fractional exponent, zero to a negative power, and overflow; one catch covers all three. + base, exponent = evaluate(left, values), evaluate(right, values) + # A nan from a zero divisor stays nan, though math.pow(1, nan) and math.pow(nan, 0) give 1. + if math.isnan(base) or math.isnan(exponent): + return math.nan + try: + return math.pow(base, exponent) + except (OverflowError, ValueError): + return math.nan + return math.nan + + +def goal_term(shape: Shape) -> str: + """The name of the formula's goal term, which score builds: W in OLD_SHAPE, V in the current shape.""" + return "W" if shape is OLD_SHAPE else "V" + + +def variables(shape: Shape) -> tuple[str, ...]: + """The names the formula may use: the shape's scores but C, which stays out of the formula, and its goal term.""" + return tuple(sorted({*shape.score_columns} - {"C"} | {goal_term(shape)})) + + +def score(formula: ast.Expression, item: Item, scoring: Scoring) -> float | Failure: + if goal_term(scoring.shape) == "W": + # The old shape weighs an item by its heaviest cited goal. + term = max(scoring.weights[goal] for goal, _ in item.moves) + else: + # Only an OLD_SHAPE item names a goal without a move. + term = sum(scoring.weights[goal] * (by or 0) for goal, by in item.moves) + value = evaluate(formula, {**item.scores, goal_term(scoring.shape): term}) + return value if math.isfinite(value) else Failure(f"the formula gives item {item.id} no finite score") + + +def number(text: str | Failure, what: str) -> float | Failure: + if isinstance(text, Failure): + return text + try: + value = float(text) + except ValueError: + value = math.nan + return value if math.isfinite(value) else Failure(f"{what} {text!r} is not a finite number") + + +def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float] | Failure: + table = table_rows(lines, WEIGHTS_HEADER) + if isinstance(table, Failure): + return table + weights: dict[str, float] = {} + for row in table.rows: + found = cells(row, 2) + if isinstance(found, Failure): + return found + weight = number(found[1], f"goal {found[0]}'s weight") + if isinstance(weight, Failure): + return weight + if found[0] in weights: + return Failure(f"the goal weights list goal {found[0]} twice") + weights[found[0]] = weight + if list(weights) != goals: + default = "\n".join(f"| {goal} | {(len(goals) - index) / len(goals):.2f} |" for index, goal in enumerate(goals)) + return Failure(f"the goal weights list {', '.join(weights) or 'no goal'}, but README.md's goals are {', '.join(goals)}; by position they weigh:\n{WEIGHTS_HEADER}\n|---|---|\n{default}") + return weights + + +def parse_item(row: str, scoring: Scoring, table: Table) -> Item | Failure: + """The row as an item, refused where it names a goal it may not; in SHAPE, with the R its L, E and I give.""" + item = parse_row(row, table) + if isinstance(item, Failure): + return item + if broken := cited_goals_failure(item, scoring): + return broken + if scoring.shape is OLD_SHAPE: + return item + # R is written here, as the Score is, so --check finds a stale one, and a reader keeps the R the table stored. + return dataclasses.replace(item, scores=item.scores | {"R": risk(item.scores["L"], item.scores["E"], item.scores["I"])}) + + +def cited_goals_failure(item: Item, scoring: Scoring) -> Failure | None: + """Why the item may not name one of the goals it names, such as one README.md voids or does not number; None when it may name each. todo_table's parse_moves holds the rules a Moves cell keeps on its own.""" + if scoring.shape is OLD_SHAPE: + unknown = [goal for goal, _ in item.moves if goal not in scoring.weights] + return Failure(f"item {item.id} cites goal {', '.join(unknown)}, which the goal weights do not list") if unknown else None + for goal, _ in item.moves: + if goal == CODE_HEALTH and goal not in scoring.goals: + return Failure(f"item {item.id} names {CODE_HEALTH}, which README.md voids; drop it from the item's {MOVES}, or the void from README.md") + if goal not in scoring.goals: + return Failure(f"item {item.id} cites goal {goal}, which README.md's ## Goals does not number") + if scoring.goals[goal] == "Maintain" and item.exempt != "defect": + return Failure(f"item {item.id} cites goal {goal}, a maintain goal, which only a defect that restores it may name; name the achieve goals the item moves") + return None + + +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}"} + return "| " + " | ".join(written[column] for column in columns) + " |" + + +def rank_details(text: str, items: list[Item]) -> str | Failure: + section = DETAILS.search(text) + details = item_details(text) + if section is None or isinstance(details, 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] + 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.py b/bin/release_plan/release.py similarity index 98% rename from bin/release.py rename to bin/release_plan/release.py index e1be9bd3..5444a47a 100644 --- a/bin/release.py +++ b/bin/release_plan/release.py @@ -2,7 +2,7 @@ import re from failure import Failure -import git_repo +from git_cli import git_repo Release = tuple[int, int, int] VERSION = r"[0-9]+\.[0-9]+\.[0-9]+" diff --git a/bin/release_standing.py b/bin/release_plan/release_standing.py similarity index 97% rename from bin/release_standing.py rename to bin/release_plan/release_standing.py index cf6461ee..d0fd4001 100644 --- a/bin/release_standing.py +++ b/bin/release_plan/release_standing.py @@ -1,11 +1,11 @@ """How the plan stands to the last release cut: the next release, whether work has landed towards it, and whether it is to be planned, reviewed or cut; and, from that standing, the item the next chunk takes first, with what the default branch holds for the pick.""" import dataclasses -from git_repo import commits_since, file_at, git -from release import dated, dated_heading_pattern, newest_tag, parsed, Release, tagged +from git_cli.git_repo import commits_since, file_at, git +from release_plan.release import dated, dated_heading_pattern, newest_tag, parsed, Release, tagged from failure import Failure -from todo_table import Item, items, next_item, renames -from markdown_text import sections +from release_plan.todo_table import Item, items, next_item, renames +from records.markdown_text import sections # The version a branch with no v* tag and no dated CHANGELOG.md heading counts as cut: below every release, 0.0.0 included, so that every release todo.md names comes after it. BEFORE_FIRST_RELEASE = (-1, 0, 0) diff --git a/bin/release_plan/test_ranking.py b/bin/release_plan/test_ranking.py new file mode 100644 index 00000000..7cef6cb2 --- /dev/null +++ b/bin/release_plan/test_ranking.py @@ -0,0 +1,579 @@ +import contextlib +import io +import pathlib +import re +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from failure import Failure +from release_plan import ranking +from repo_checks import ROOT +from release_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" + +README = "# P\n\n## Goals\n\n" + VOID + "1. **Achieve:** Fast.\n2. **Maintain:** Correct.\n 1. **Achieve:** Tested.\n\n## Audience\n\nMe.\n" + +DECISIONS = "## A choice\n\nStands until `todo.md` item 5 ends it.\n" + +TODO = """# todo + +## Scoring + +`Score = 100 * V / 2**S` + +`Bar = 2` + +`Next ID = 6` + +## Items + +| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | +|---|---|---|---|---|---|---|---|---|---|---|---| +| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 0 | +| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 0 | +| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 | 0 | +| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 0 | +| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 0 | + +## Details + +### 1. stale heading + +Later detail. + +### 3. Make it fast. + +Fast detail. + +## Notes + +Kept as written. +""" + +OLD_SHAPE = """# todo + +## Scoring + +`Score = -R - S/4 + 2*A + 2*G*W` + +`Bar = 9` + +`Next ID = 6` + +| Goal | W | +|---|---| +| 1 | 1.00 | +| 2 | 0.67 | +| 2.1 | 0.33 | + +## Items + +| ID | Release | Blocked by | Exempt | Item | R | S | C | A | G | Goals | Score | +|---|---|---|---|---|---|---|---|---|---|---|---| +| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 3 | 9 | 9 | 1 | 0 | +| 2 | 0.1.0 | | | **Tighten the tests.** | 2 | 4 | 3 | 5 | 5 | 2.1 | 0 | +| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 3 | 8 | 3 | 6 | 8 | 2.1, 1 | 0 | +| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 9 | 2 | 3 | 1 | 1 | 2.1 | 0 | +| 5 | 0.1.0 | | decision | **Move the writes out.** | 5 | 5 | 3 | 4 | 5 | 2.1 | 0 | + +## Details + +### 1. stale heading + +Later detail. + +### 3. Make it fast. + +Fast detail. + +## Notes + +Kept as written. +""" + + +class Rank(unittest.TestCase): + def ranked(self, todo=TODO, readme=README, decisions=DECISIONS): + return ranking.rank(todo, readme, decisions, "") + + def test_scores_and_sorts_by_release_then_security_then_score_and_orders_the_details_to_match(self): + ranked = self.ranked() + self.assertIn("""| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 12.3 | +| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 | 5.5 | +| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 3.1 | +| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 1.5 | +| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 228.4 | +""", ranked.text) + self.assertTrue(ranked.text.endswith("## Details\n\n### 3. Make it fast, `a | b`.\n\nFast detail.\n\n### 1. Ship the later thing.\n\nLater detail.\n\n## Notes\n\nKept as written.\n")) + self.assertEqual(ranked.under_bar, []) + self.assertEqual(ranked.notes, []) + self.assertEqual(self.ranked(ranked.text), ranked) + + def test_keeps_a_detail_that_opens_with_markdown_quoted_by_four_spaces(self): + quoting = TODO.replace("Fast detail.", " ## Goals\n\nFast detail.") + self.assertIn("### 3. Make it fast, `a | b`.\n\n ## Goals\n\nFast detail.\n", self.ranked(quoting).text) + + def test_weighs_each_achieve_goal_97_percent_of_the_one_above_and_a_defects_maintain_goal_as_the_first(self): + readme = "## Goals\n\n1. **Achieve:** A.\n 1. **Maintain:** B.\n 2. **Achieve:** C.\n2. **Achieve:** D.\n" + self.assertEqual({goal: round(weight, 4) for goal, weight in ranking.goal_weights(ranking.readme_goals(readme), None).items()}, {"1": 0.3435, "1.1": 0.3435, "1.2": 0.3332, "2": 0.3232}) + + def test_weighs_5_achieve_goals_from_0212_to_0188_and_15_from_0082_to_0053(self): + for count, first, last in ((5, 0.212, 0.188), (15, 0.082, 0.053)): + with self.subTest(count=count): + goals = ranking.readme_goals("## Goals\n\n" + "".join(f"{number}. **Achieve:** G.\n" for number in range(1, count + 1))) + weights = list(ranking.goal_weights(goals, None).values()) + self.assertEqual((round(weights[0], 3), round(weights[-1], 3), round(sum(weights), 6)), (first, last, 1)) + + def test_scores_an_item_by_the_weights_of_the_goals_it_moves(self): + readme = "## Goals\n\n" + VOID + "1. **Achieve:** A.\n 1. **Maintain:** B.\n 2. **Achieve:** C.\n2. **Achieve:** D.\n" + todo = TODO.replace("2.1 by 8, 1 by 6", "1.2 by 2, 2 by 3").replace("| 2.1 by 1 |", "| 1 by 1 |") + self.assertIn("| **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 1.2 by 2, 2 by 3 | 1.3 |", self.ranked(todo, readme).text) + + def test_scores_an_item_that_moves_no_goal_zero(self): + ranked = self.ranked(TODO.replace("| 1 | 2 | 1 | 2 | 4 | 2.1 by 1 |", "| 1 | 2 | 1 | 2 | 4 | |")) + self.assertIn("| **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | | 0.0 |", ranked.text) + self.assertEqual(ranked.under_bar, ["item 2 scores 0.0, under the bar 2; delete it, or mark it with a reason the bar does not apply"]) + + def test_holds_each_item_a_decision_cites_and_says_how_to_settle_a_finished_one(self): + self.assertIsInstance(self.ranked(decisions=DECISIONS + "Until `todo.md` item 4 lands.\n"), ranking.Ranked) + gone = self.ranked(TODO.replace("| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 0 |\n", "")) + self.assertEqual(gone.reason, "docs/decisions.md cites \"`todo.md` item 5\", which todo.md no longer holds; revise that decision to say what holds now") + + def test_names_each_item_under_the_bar_that_is_not_exempt(self): + ranked = self.ranked(TODO.replace("`Bar = 2`", "`Bar = 3.5`")) + self.assertEqual(ranked.under_bar, ["item 2 scores 3.1, under the bar 3.5; delete it, or mark it with a reason the bar does not apply"]) + self.assertEqual(self.ranked(TODO.replace("`Bar = 2`", "`Bar = 3.1`")).under_bar, []) + blocking = self.ranked(TODO.replace("`Bar = 2`", "`Bar = 3.5`").replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 2 |").replace("| 5 | 0.1.0 | |", "| 5 | 0.1.0 | 3 |")) + self.assertEqual(blocking.under_bar, ["item 2 scores 3.1, under the bar 3.5; delete it and the items it blocks, directly or through another (3, 5), or mark it with a reason the bar does not apply"]) + self.assertEqual(self.ranked(ranked.text.replace("| 2 | 0.1.0 | | |", "| 2 | 0.1.0 | | principle |")).under_bar, []) + self.assertEqual(self.ranked(ranked.text.replace("| 2 | 0.1.0 | | |", "| 2 | 0.1.0 | | owner |")).under_bar, []) + + def test_reads_goals_and_sub_goals_in_reading_order(self): + self.assertEqual(ranking.readme_goals(README), [("1", "Achieve"), ("2", "Maintain"), ("2.1", "Achieve")]) + self.assertEqual(ranking.readme_goals(README.replace(" 1.", "\t1.")), [("1", "Achieve"), ("2", "Maintain"), ("2.1", "Achieve")]) + self.assertEqual(ranking.readme_goals(README.replace("2. **Maintain:** Correct.", "```\n## Goals\n```\n2. Correct.")), [("1", "Achieve"), ("2", None), ("2.1", "Achieve")]) + self.assertEqual(ranking.readme_goals(README.replace("2. **Maintain:**", "1. **Maintain:**")), Failure("README.md's ## Goals numbers 1, 1, 1.1; number each goal by its position")) + self.assertEqual(ranking.readme_goals("## Goals\n\n1. **Achieve:** A.\n 1. **Achieve:** B.\n\t2. **Achieve:** C.\n"), [("1", "Achieve"), ("1.1", "Achieve"), ("1.2", "Achieve")]) + + def test_refuses_a_goal_it_cannot_weigh(self): + cases = { + (TODO.replace("2.1 by 8, 1 by 6", "1 by 8, 2 by 6"), README): "item 3 cites goal 2, a maintain goal, which only a defect that restores it may name; name the achieve goals the item moves", + (TODO.replace("2.1 by 8, 1 by 6", "2.1 by 8, 3 by 6"), README): "item 3 cites goal 3, which README.md's ## Goals does not number", + (TODO.replace("2.1 by 8, 1 by 6", "2.1 by 8, 2.1 by 6"), README): "item 3 cites goal 2.1 twice; name each goal once", + (TODO, README.replace("**Maintain:** Correct", "Correct")): "README.md's goal 2 is marked neither **Maintain:** nor **Achieve:**; mark it, as ~/.claude/rules/goals-and-audience.md says, so rank_todo.py knows which goals score", + } + for (todo, readme), reason in cases.items(): + with self.subTest(reason=reason): + self.assertEqual(self.ranked(todo, readme), Failure(reason)) + + def test_ranks_questions_first_then_security_whatever_they_score_and_a_defect_by_its_score(self): + todo = TODO.replace("| 2 | 0.1.0 | | |", "| 2 | 0.1.0 | | defect |").replace("| 3 | 3 | 5 | 9 | 2 | 2.1 by 1 |", "| 3 | 3 | 5 | 9 | 8 | 2.1 by 1 |").replace("| 5 | 0.1.0 | | decision |", "| 5 | 0.1.0 | | question |") + rows = [line.split(" | ")[0] for line in self.ranked(todo, decisions="").text.splitlines() if line.startswith("| ") and " | 0." in line] + self.assertEqual(rows, ["| 5", "| 4", "| 3", "| 2", "| 1"]) + + def test_weighs_the_maintain_goal_a_defect_restores_as_the_heaviest_achieve_goal(self): + ranked = self.ranked(TODO.replace("| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 |", "| 2 | 0.1.0 | | defect | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2 by 3 |")) + self.assertIn("| **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2 by 3 | 9.5 |", ranked.text) + + def test_refuses_a_goal_named_beside_its_own_sub_goal(self): + readme = "## Goals\n\n" + VOID + "1. **Achieve:** A.\n 1. **Maintain:** B.\n 2. **Achieve:** C.\n2. **Achieve:** D.\n" + todo = TODO.replace("2.1 by 8, 1 by 6", "1.2 by 2, 1 by 3").replace("| 2.1 by 1 |", "| 2 by 1 |") + self.assertEqual(self.ranked(todo, readme), Failure("item 3 names goal 1 and its sub-goal 1.2; name one, never both: the sub-goal where the move serves it, else the parent")) + self.assertIsInstance(self.ranked(todo.replace("1.2 by 2, 1 by 3", "1.2 by 2, 2 by 3"), readme), ranking.Ranked) + + def test_scores_every_item_zero_where_readme_marks_no_goal_achieve(self): + ranked = self.ranked(TODO.replace("2.1 by 8, 1 by 6", "").replace("| 2.1 by 1 |", "| |").replace("| 1 by 9 |", "| |"), README.replace("**Achieve:**", "**Maintain:**")) + self.assertEqual([line.split(" scores ")[0] for line in ranked.under_bar], ["item 2", "item 3", "item 1"]) + self.assertEqual(ranked.notes, ["README.md voids code health and marks no goal **Achieve:**, so every item scores V 0"]) + + def test_accepts_a_move_of_ten_and_a_variable_base(self): + ranked = self.ranked(TODO.replace("| 1 by 9 |", "| 1 by 10 |").replace("100 * V / 2**S", "V * S ** 2")) + self.assertIn("| **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 10 | 5.1 |", ranked.text) + + def test_asks_to_drop_a_goal_weights_table_from_a_table_with_moves(self): + weighted = TODO.replace("## Items\n", "| Goal | W |\n|---|---|\n| 1 | 1.00 |\n\n## Items\n") + self.assertEqual(self.ranked(weighted), Failure("todo.md holds a goal weights table beside a Moves column; drop the table, since rank_todo.py weighs the goals itself, as its --help says")) + + def test_refuses_a_formula_that_is_more_than_arithmetic_over_the_scores(self): + for formula in ("__import__('os')", "R.real", "X + 1", "C + 1", "A + V", "G + V", "W * V", "R ^ 2", "R +", "R / (S - 2)", "R\x00", "1" * 400, " + ".join(["R"] * 300), "-" * 100000 + "R", "10 ** 10 ** 10", "(-8) ** (1 / 3)", "0 ** -1"): + with self.subTest(formula=formula): + self.assertIsInstance(self.ranked(TODO.replace("100 * V / 2**S", formula)), Failure) + self.assertIn("| 1 by 9 | 2.0 |", self.ranked(TODO.replace("100 * V / 2**S", "R + S / S")).text) + self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "1 ** (1 / (S - S))")), Failure("the formula gives item 1 no finite score")) + self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "(1 / (S - S)) ** 0")), Failure("the formula gives item 1 no finite score")) + self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "W")), Failure("the formula 'W' may hold only numbers, E, I, L, R, S, V, + - * / ** and parentheses")) + self.assertEqual(self.ranked(TODO.replace("2.1 by 8, 1 by 6", "2.1: 8, 1: 6")), Failure("item 3's Moves '2.1: 8, 1: 6' is not empty or goals such as `1.1 by 8, code health by 5`, each moved by a whole number from 1 to 10")) + + def test_refuses_a_file_off_the_format(self): + row = "| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 0 |" + broken = { + row: row.replace("0.1.0", "0.1"), + "| 1 | 2 | 1 | 2 | 4 | 2.1 by 1 |": "| 5 | 2 | 1 | 2 | 4 | 2.1 by 1 |", + "Tighten the tests.** | 1 | 2 | 1 | 2 | 4 |": "Tighten the tests.** | 1 | 4 | 1 | 2 | 4 |", + "Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1": "Tighten the tests.** | 1 | 2 | 6 | 2 | 4 | 2.1", + "Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by": "Tighten the tests.** | 0 | 2 | 1 | 2 | 4 | 2.1 by", + "| 2 | 4 | 2.1 by 1 | 0 |\n| 3": "| 2 | 11 | 2.1 by 1 | 0 |\n| 3", + "Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1": "Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 11", + "Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1": "Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 0", + "2.1 by 8, 1 by 6": "2.1: 8, 1: 6", + "2.1 by 8, 1 by 6 ": "2.1 by 8,1 by 6 ", + "| 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 |": "| 2 | 1 | 2 | 3 | 7 | 2.1, 1 |", + row + "\n": row.replace("2 | 4 |", "2 | ² |") + "\n", + "| 2.1 by 1 | 0 |\n\n## Details": "| 2.1 by 1 | 0 |\n\n| 9 | 0.1.0 | | | **Stray.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 0 |\n\n## Details", + "| 4 | 0.1.0 | | security |": "| 4 | 0.1.0 | | later |", + "| 5 | 0.1.0 | | decision |": "| 5 | 0.1.0 | | |", + "`Next ID = 6`": "`Next ID = 5`", + "`Next ID = 6`\n": "`Next ID = 6.5`\n", + "| 4 | 0.1.0 | | security | **Rotate": "| 4 | 0.1.0 | | decision | **Rotate", + "Fast detail.": "```\n## Goals\n```", + "### 3. Make it fast.": "### 7. Make it fast.", + "`Bar = 2`": "`Bar = nan`", + "## Items\n\n| ID | Release | Blocked by |": "## Plan\n\n| ID | Release |", + } + for old, new in broken.items(): + with self.subTest(new=new): + self.assertIn(old, TODO) + self.assertIsInstance(self.ranked(TODO.replace(old, new)), Failure) + + +# A scoring run of the project whose overall mean is {overall}. +SCORED = "# Comprehension history\n\n## 2026-10-08T12:00:00Z, PR #1 at aaaaaaa\n\n| Seat | Overall |\n|---|---|\n| Mid A | 6 |\n| Mean | {overall} |\n" + + +class CodeHealth(unittest.TestCase): + readme = "## Goals\n\n1. **Achieve:** A.\n" + todo = TODO.split("| 1 | 0.2.0", 1)[0].replace("`Bar = 2`", "`Bar = 0.1`") + "| 1 | 0.1.0 | | | **Read easier.** | 1 | 1 | 1 | 1 | 1 | code health by 1 | 0 |\n| 2 | 0.1.0 | | | **Do A.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 0 |\n" + + def scores(self, history, readme=readme): + ranked = ranking.rank(self.todo, readme, "", history) + return ranked if isinstance(ranked, Failure) else {line.split(" | ")[0]: line.rsplit(" | ", 1)[1].rstrip(" |") for line in ranked.text.splitlines() if line.startswith("| ") and " 0.1.0 " in line} + + def entry(self, overall, at="2026-10-08T12", read="PR #1 at aaaaaaa"): + """A scoring run's entry, without the history's title.""" + return SCORED.format(overall=overall).removeprefix("# Comprehension history\n\n").replace("2026-10-08T12", at).replace("PR #1 at aaaaaaa", read) + + def test_ranks_code_health_first_among_the_achieve_goals_at_an_overall_of_7_or_above(self): + # Code health, then goal 1: weights 1 / 1.97 and 0.97 / 1.97, an item moving one by 1 at S 1 scoring 50 times its weight. + self.assertEqual(self.scores(SCORED.format(overall="7.00")), {"| 1": "25.4", "| 2": "24.6"}) + + def test_weighs_code_health_four_times_as_much_under_an_overall_of_7_and_before_any_scoring_run(self): + for history in (SCORED.format(overall="6.99"), "", "# Comprehension history\n\n## 2026-10-09T12:00:00Z, PR #2 at bbbbbbb, against aaaaaaa\n\nRuling: better\n"): + with self.subTest(history=history): + self.assertEqual(self.scores(history), {"| 1": "101.5", "| 2": "24.6"}) + + def test_weighs_by_the_newest_scored_commit_wherever_the_file_holds_it(self): + older = self.entry("6.50") + newer = self.entry("7.25", "2026-10-10T12", "PR #1 at bbbbbbb") + for history in (f"{older}\n{newer}", f"{newer}\n{older}"): + with self.subTest(history=history): + self.assertEqual(self.scores(history)["| 1"], "25.4") + + def test_weighs_by_the_mean_overall_of_every_run_on_the_newest_scored_commit(self): + # 7.13 and 6.88 average 7.005, at the floor or above; 7.10 and 6.80 average 6.95, under it. + for first, rerun, value in (("7.13", "6.88", "25.4"), ("7.10", "6.80", "101.5")): + with self.subTest(first=first, rerun=rerun): + self.assertEqual(self.scores(f"{self.entry(first)}\n{self.entry(rerun, '2026-10-08T13', 'PR #1 rerun at aaaaaaa')}")["| 1"], value) + later = self.entry("6.50", "2026-10-09T12", "PR #2 at bbbbbbb") + self.assertEqual(self.scores(f"{self.entry('7.13')}\n{self.entry('6.88', '2026-10-08T13', 'PR #1 rerun at aaaaaaa')}\n{later}")["| 1"], "101.5") + + def test_matches_a_commit_whichever_length_a_heading_writes_it_at(self): + full = "aaaaaaa" + "0" * 33 + # As runs of one commit, 7.13 and 6.88 average 7.005; the newer alone is under the floor. + for first, rerun in (("aaaaaaa", full), (full, "aaaaaaa")): + with self.subTest(first=first, rerun=rerun): + self.assertEqual(self.scores(f"{self.entry('7.13', read=f'PR #1 at {first}')}\n{self.entry('6.88', '2026-10-08T13', f'PR #1 rerun at {rerun}')}")["| 1"], "25.4") + + def test_weighs_by_a_ruling_that_holds_scoring_seats_places(self): + # A ruling recorded before PR #255 scored the project too: below its votes, a scores table with a Mean row, and each scoring seat's places. + ruling = "## 2026-10-10T12:00:00Z, PR #2 at bbbbbbb, against aaaaaaa\n\nRuling: better\n\n| Seat | Overall |\n|---|---|\n| Mid A | better |\n\n| Seat | Overall |\n|---|---|\n| Mid A | 7.5 |\n| Mean | 7.25 |\n\nJunior A, hardest first:\n\n- `bin/a.py:1` `f`: long\n" + self.assertEqual(self.scores(f"{self.entry('6.50')}\n{ruling}")["| 1"], "25.4") + + def test_refuses_a_newest_scoring_run_with_no_overall_mean(self): + for history in (SCORED.format(overall="high"), SCORED.split("| Mean")[0]): + with self.subTest(history=history): + self.assertEqual(self.scores(history), Failure("docs/comprehension-history.md's scoring run 2026-10-08T12:00:00Z, PR #1 at aaaaaaa has no Mean row ending in its overall, which sets code health's weight")) + + def test_drops_code_health_where_readme_voids_it(self): + voided = "## Goals\n\n**Void:** code health, since it is a one-off script.\n\n1. **Achieve:** A.\n" + self.assertEqual(self.scores("", voided), Failure("item 1 names code health, which README.md voids; drop it from the item's Moves, or the void from README.md")) + ranked = ranking.rank(self.todo.replace("code health by 1", "1 by 2"), voided, "", "") + self.assertIn("| **Read easier.** | 1 | 1 | 1 | 1 | 1 | 1 by 2 | 100.0 |", ranked.text) + + def test_weighs_a_defects_maintain_goal_as_code_health_four_times_over_under_an_overall_of_7(self): + readme = "## Goals\n\n1. **Achieve:** A.\n2. **Maintain:** B.\n" + todo = self.todo.replace("| 2 | 0.1.0 | | | **Do A.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 |", "| 2 | 0.1.0 | | defect | **Restore B.** | 1 | 1 | 1 | 1 | 1 | 2 by 1 |") + for history, value in (("", "101.5"), (SCORED.format(overall="7.00"), "25.4")): + with self.subTest(history=history): + self.assertIn(f"| **Restore B.** | 1 | 1 | 1 | 1 | 1 | 2 by 1 | {value} |", ranking.rank(todo, readme, "", history).text) + + def test_refuses_a_plan_whose_project_opts_out_of_the_comprehension_check_yet_keeps_code_health(self): + opted_out = "## review opt-out: the architect and the comprehension check\n\nCosts rounds.\n" + self.assertEqual(ranking.rank(self.todo, self.readme, opted_out, ""), Failure("docs/decisions.md opts out of the comprehension check, so code health has no signal; void it in README.md's ## Goals with `**Void:** code health, since .`, as ~/.claude/CLAUDE.md → 'Shared goal' says")) + self.assertIsInstance(ranking.rank(self.todo, self.readme, opted_out.replace(" and the comprehension check", ""), ""), ranking.Ranked) + voided = "## Goals\n\n**Void:** code health, since nobody reads the probes.\n\n1. **Achieve:** A.\n" + self.assertIsInstance(ranking.rank(self.todo.replace("code health by 1", "1 by 2"), voided, opted_out, ""), ranking.Ranked) + + def test_ranks_a_project_that_voids_code_health_whatever_its_history_holds(self): + voided = "## Goals\n\n**Void:** code health, since it is a one-off script.\n\n1. **Achieve:** A.\n" + self.assertIsInstance(ranking.rank(self.todo.replace("code health by 1", "1 by 2"), voided, "", SCORED.format(overall="high")), ranking.Ranked) + + def test_refuses_a_void_of_anything_but_code_health(self): + self.assertEqual(self.scores("", "## Goals\n\n**Void:** speed, since nobody waits.\n\n1. **Achieve:** A.\n"), Failure("README.md's ## Goals voids `speed, since nobody waits.`; only code health may be voided, as `**Void:** code health, since .`")) + + def test_shows_the_spelling_of_a_void_of_code_health_that_misses_it(self): + for void in ("code health.", "Code health, since it is a one-off script.", "code health since it is a one-off script."): + with self.subTest(void=void): + self.assertEqual(self.scores("", f"## Goals\n\n**Void:** {void}\n\n1. **Achieve:** A.\n"), Failure(f"README.md's ## Goals voids code health as `{void}`; spell the void exactly `**Void:** code health, since .`")) + + def test_parses_code_health_in_a_moves_cell(self): + self.assertEqual(todo_table.parse_moves("1", "code health by 4, 1.1 by 2"), (("code health", 4), ("1.1", 2))) + self.assertIsInstance(todo_table.parse_moves("1", "code health by 11"), Failure) + self.assertIsInstance(todo_table.parse_moves("1", "health by 4"), Failure) + + def test_reads_the_history_beside_todo_md(self): + with tempfile.TemporaryDirectory() as temp: + todo = pathlib.Path(temp, "todo.md") + todo.write_text(self.todo) + pathlib.Path(temp, "README.md").write_text(self.readme) + 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 = ranking.rank_file(todo) + self.assertIsInstance(ranked, ranking.Ranked) + self.assertEqual(ranked.under_bar, []) + self.assertIn("| code health by 1 | 25.4 |", todo.read_text()) + + +class Risk(unittest.TestCase): + """R is L + E + I - 2, which rank_todo.py writes, at least 7 when I is 5 and at least 5 when I is 4.""" + def ranked(self, todo): + return ranking.rank(todo, README, DECISIONS, "") + + def test_writes_r_from_l_e_and_i_over_a_stale_or_missing_r(self): + ranked = self.ranked(TODO).text + for levels, risk in (("| 1 | 1 | 1 |", 1), ("| 2 | 1 | 2 |", 3), ("| 1 | 2 | 1 |", 2)): + with self.subTest(levels=levels): + self.assertIn(f"{levels} {risk} |", ranked) + stale = TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 2 | 1 | 2 | 10 | 7 |") + self.assertEqual(self.ranked(stale).text, ranked) + without_r = TODO.replace("| I | R | S |", "| I | S |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|") + without_r = re.sub(r"(\*\* \| \d+ \| \d+ \| \d+) \| \d+ \|", r"\1 |", without_r) + self.assertEqual(self.ranked(without_r).text, ranked) + + def test_writes_r_into_a_blank_r_cell(self): + blank = TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 2 | 1 | 2 | | 7 |") + self.assertEqual(self.ranked(blank).text, self.ranked(TODO).text) + + def test_leaves_a_stale_r_to_ranking_so_a_reader_keeps_the_r_the_table_stored(self): + stale = TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 2 | 1 | 2 | 10 | 7 |") + self.assertEqual(next(item for item in todo_table.items(stale) if item.id == 3).scores["R"], 10) + self.assertNotEqual(self.ranked(stale).text, stale) + + def test_holds_r_at_7_when_i_is_5_and_at_5_when_i_is_4(self): + cases = {"| 1 | 1 | 5 |": 7, "| 1 | 1 | 4 |": 5, "| 2 | 2 | 4 |": 6, "| 4 | 3 | 5 |": 10, "| 3 | 3 | 3 |": 7} + for levels, risk in cases.items(): + with self.subTest(levels=levels): + ranked = self.ranked(TODO.replace("| 1 | 2 | 1 | 2 | 4 |", f"{levels} 1 | 4 |")) + self.assertIn(f"**Tighten the tests.** {levels} {risk} | 4 |", ranked.text) + + def test_routes_a_worker_on_l_and_its_reviewers_on_e_plus_i(self): + item = next(item for item in todo_table.items(TODO) if item.id == 4) + self.assertEqual((item.likelihood, item.escape_and_impact), (3, 8)) + + def test_names_the_one_level_column_a_table_lacks(self): + without_i = TODO.replace("| E | I | R |", "| E | R |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|") + without_i = re.sub(r"(\*\* \| \d+ \| \d+) \| \d+ \|", r"\1 |", without_i) + self.assertEqual(self.ranked(without_i), Failure("todo.md's items table has no I column; add it, scoring each item's L, E and I as rank_todo.py --help shows")) + + def test_asks_a_table_from_before_l_e_and_i_for_them_yet_reads_its_rows(self): + before = TODO.replace("| L | E | I | R | S | Moves |", "| R | S | C | Moves |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|") + before = re.sub(r"(\*\* \|) \d+ \| \d+ \| \d+ \| (\d+) \| (\d+) \|", r"\1 \2 | \3 | 3 |", before) + self.assertEqual(self.ranked(before), Failure("todo.md's items table has no L, E and I columns; add them, scoring each item's L, E and I as rank_todo.py --help shows, and drop C")) + items = todo_table.items(before) + self.assertEqual([(item.scores, item.likelihood, item.escape_and_impact) for item in items][1], ({"R": 2, "S": 4}, 0, 0)) + + +class OldShape(unittest.TestCase): + """A table with A, G and Goals, from before the Moves column, ranks by the formula and goal weights it states until its project reshapes it.""" + def ranked(self, todo=OLD_SHAPE, readme=README): + return ranking.rank(todo, readme, DECISIONS, "") + + def test_scores_by_the_stated_weights_and_says_to_reshape(self): + ranked = self.ranked() + self.assertIn("""| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 9 | 2 | 3 | 1 | 1 | 2.1 | -6.8 | +| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 3 | 8 | 3 | 6 | 8 | 2.1, 1 | 23.0 | +| 2 | 0.1.0 | | | **Tighten the tests.** | 2 | 4 | 3 | 5 | 5 | 2.1 | 10.3 | +| 5 | 0.1.0 | | decision | **Move the writes out.** | 5 | 5 | 3 | 4 | 5 | 2.1 | 5.1 | +| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 3 | 9 | 9 | 1 | 34.8 | +""", ranked.text) + self.assertEqual(ranked.notes, [ranking.RESHAPE]) + self.assertEqual(self.ranked(ranked.text), ranked) + unmarked = "# P\n\n## Goals\n\n1. Fast.\n2. Correct.\n 1. Tested.\n" + self.assertEqual(self.ranked(readme=unmarked), ranked) + + def test_prints_the_positional_weights_when_they_stop_listing_the_readmes_goals(self): + failure = self.ranked(readme=README.replace(" 1. **Achieve:** Tested.", " 1. **Achieve:** Tested.\n3. Small.")) + self.assertIn("| 1 | 1.00 |\n| 2 | 0.75 |\n| 2.1 | 0.50 |\n| 3 | 0.25 |", failure.reason) + + def test_refuses_an_item_citing_a_goal_the_weights_do_not_list(self): + self.assertEqual(self.ranked(OLD_SHAPE.replace("| 2.1, 1 | 0 |", "| 2.1, 9 | 0 |")), Failure("item 3 cites goal 9, which the goal weights do not list")) + + def test_refuses_a_formula_over_v(self): + self.assertEqual(self.ranked(OLD_SHAPE.replace("-R - S/4 + 2*A + 2*G*W", "V")), Failure("the formula 'V' may hold only numbers, A, G, R, S, W, + - * / ** and parentheses")) + + def test_ranks_a_table_from_before_c_joined_and_says_to_reshape_it(self): + legacy = OLD_SHAPE.split("## Items")[0] + "## Items\n\n| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|\n| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 |\n" + self.assertEqual(ranking.rank(legacy, README, "", "").notes, [ranking.RESHAPE]) + + def test_refuses_a_table_with_both_moves_and_goals(self): + both = OLD_SHAPE.replace("| Goals | Score |\n|---|", "| Goals | Moves | Score |\n|---|---|").replace(" | 0 |\n", " | 1 by 1 | 0 |\n") + self.assertEqual(self.ranked(both), Failure("todo.md's items table has no L, E and I columns; add them, scoring each item's L, E and I as rank_todo.py --help shows, and drop C, A, G and Goals")) + one = TODO.replace("| Moves | Score |\n|---|", "| Moves | G | Score |\n|---|---|").replace(" | 0 |\n", " | 1 | 0 |\n") + self.assertEqual(self.ranked(one), Failure("todo.md's items table has G, a column of an older shape; drop it, as rank_todo.py --help shows")) + + def test_names_the_goals_column_a_table_misspells_by_its_shape(self): + misspelt = TODO.replace("| S | Moves |", "| S | Move |") + self.assertEqual(ranking.rank(misspelt, README, DECISIONS, ""), Failure("todo.md's items table has no Moves column; rank_todo.py --help shows a valid one")) + self.assertEqual(todo_table.items(misspelt), Failure("todo.md's items table has no Moves column; rank_todo.py --help shows a valid one")) + self.assertEqual(self.ranked(OLD_SHAPE.replace("| G | Goals |", "| G | Goal |")), Failure("todo.md's items table has no Goals column; rank_todo.py --help shows a valid one")) + + +class Blockers(unittest.TestCase): + def ranked(self, todo): + return ranking.rank(todo, README, DECISIONS, "") + + def test_ranks_each_blocker_just_above_the_first_item_it_blocks(self): + ranked = self.ranked(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5, 2 |")) + self.assertIn("""| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 12.3 | +| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 3.1 | +| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 1.5 | +| 3 | 0.1.0 | 2, 5 | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 | 5.5 | +| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 228.4 | +""", ranked.text) + self.assertEqual(self.ranked(ranked.text), ranked) + + def test_ranks_an_items_blockers_in_score_order(self): + rows = [line.split(" | ")[0] for line in self.ranked(TODO.replace("| 4 | 0.1.0 | |", "| 4 | 0.1.0 | 2, 3 |")).text.splitlines() if re.match(r"\| \d \| 0\.\d\.0 \|", line)] + self.assertEqual(rows, ["| 3", "| 2", "| 4", "| 5", "| 1"]) + + def test_ranks_a_blocker_above_its_blockers_blocker_and_takes_one_in_an_earlier_release_as_it_is(self): + chained = TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 5 | 0.1.0 | |", "| 5 | 0.1.0 | 2 |").replace("| 1 | 0.2.0 | |", "| 1 | 0.2.0 | 3 |") + rows = [line.split(" | ")[0] for line in self.ranked(chained).text.splitlines() if re.match(r"\| \d \| 0\.\d\.0 \|", line)] + self.assertEqual(rows, ["| 4", "| 2", "| 5", "| 3", "| 1"]) + + def test_bundles_with_the_next_item_each_item_of_its_release_that_no_question_or_item_outside_the_chunk_blocks(self): + # Item 2 is the next item. Item 5 is a question, 3 waits on 5, and 4 waits on 3; item 1 is in a later release. + waits = todo_table.items(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 4 | 0.1.0 | | security |", "| 4 | 0.1.0 | 3 | security |").replace("| 5 | 0.1.0 | | decision |", "| 5 | 0.1.0 | | question |")) + self.assertEqual(todo_table.bundle_candidates(waits, todo_table.next_item(waits)), []) + answered = todo_table.items(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 4 | 0.1.0 | | security |", "| 4 | 0.1.0 | 3 | security |")) + self.assertEqual([item.id for item in todo_table.bundle_candidates(answered, todo_table.next_item(answered))], [3, 5]) + + def test_ships_an_item_above_r_5_alone(self): + # Item 4 has R 9: it joins no chunk, and none joins it. Item 5, at R 5, still joins. + found = todo_table.items(TODO) + self.assertNotIn(4, [item.id for item in todo_table.bundle_candidates(found, todo_table.next_item(found))]) + self.assertIn(5, [item.id for item in todo_table.bundle_candidates(found, todo_table.next_item(found))]) + self.assertEqual(todo_table.bundle_candidates(found, next(item for item in found if item.id == 4)), []) + # At R 6, item 3 ships alone too. + riskier = todo_table.items(TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 3 | 2 | 3 | 6 | 7 |")) + self.assertNotIn(3, [item.id for item in todo_table.bundle_candidates(riskier, todo_table.next_item(riskier))]) + # Before rank_todo.py fills its R cell, item 3's L 3, E 2 and I 3 still make R 6. + unranked = todo_table.items(TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 3 | 2 | 3 | | 7 |")) + self.assertNotIn(3, [item.id for item in todo_table.bundle_candidates(unranked, todo_table.next_item(unranked))]) + + def test_drops_a_blocker_the_table_no_longer_holds_as_finished(self): + finished = TODO.replace("| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 0 |\n", "").replace("| 2 | 0.1.0 | |", "| 2 | 0.1.0 | 4 |") + ranked = self.ranked(finished) + self.assertIn("| 2 | 0.1.0 | | | **Tighten the tests.**", ranked.text) + self.assertEqual(ranked.notes, ["item 2: dropped 4 from its Blocked by; the table no longer holds it"]) + self.assertEqual(self.ranked(ranked.text).notes, []) + + def test_refuses_a_blocker_in_a_later_release_a_loop_and_an_id_past_next_id(self): + cases = { + "| 3 | 0.1.0 | 1 |": "item 3, in release 0.1.0, is blocked by item 1, in later release 0.2.0; move item 1 to release 0.1.0 or earlier, or item 3 to release 0.2.0 or later", + "| 3 | 0.1.0 | 3 |": "item 3 is blocked by itself; drop 3 from its Blocked by", + "| 3 | 0.1.0 | 9 |": "item 3 is blocked by item 9, which is not under Next ID 6; name an item the table holds or held", + "| 3 | 0.1.0 | 6 |": "item 3 is blocked by item 6, which is not under Next ID 6; name an item the table holds or held", + } + for cell, reason in cases.items(): + with self.subTest(cell=cell): + self.assertEqual(self.ranked(TODO.replace("| 3 | 0.1.0 | |", cell)), Failure(reason)) + looped = TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 2 |").replace("| 2 | 0.1.0 | |", "| 2 | 0.1.0 | 5 |").replace("| 5 | 0.1.0 | |", "| 5 | 0.1.0 | 3 |") + self.assertEqual(self.ranked(looped), Failure("items 2, 3 and 5 block each other in a loop; drop one of the blockers")) + self.assertEqual(self.ranked(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 2 and 5 |")), Failure("item 3's Blocked by '2 and 5' is not empty or IDs separated by \", \"")) + + def test_adds_the_column_to_a_table_without_it(self): + without = TODO.replace("| Blocked by ", "").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|") + without = re.sub(r"\| (\d) \| (0\.[12]\.0) \| \| ", r"| \1 | \2 | ", without) + self.assertEqual(self.ranked(without), self.ranked(TODO)) + unscored = TODO.replace(" | Score |", " |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|").replace(" | 0 |\n", " |\n") + self.assertEqual(self.ranked(unscored), self.ranked(TODO)) + + def test_refuses_a_column_it_does_not_know_rather_than_drop_it_and_one_an_older_shape_held(self): + extra = TODO.replace("| Moves | Score |\n|---|", "| Moves | Score | Later |\n|---|---|").replace(" | 0 |\n", " | 0 | x |\n") + self.assertEqual(self.ranked(extra), Failure("todo.md's items table has the column Later, which this rank_todo.py does not know; the columns it knows are ID, Release, Blocked by, Exempt, Item, L, E, I, R, S, Moves, Score. Rename it, or move this machine to the release that added it")) + self.assertEqual([item.id for item in todo_table.items(extra)], [1, 2, 3, 4, 5]) + with_c = TODO.replace("| S | Moves |", "| S | C | Moves |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|---|---|") + with_c = re.sub(r"(\*\* \| \d+ \| \d+ \| \d+ \| \d+ \| \d+) \|", r"\1 | 3 |", with_c) + self.assertEqual(self.ranked(with_c), Failure("todo.md's items table has C, a column of an older shape; drop it, as rank_todo.py --help shows")) + + def test_refuses_text_under_items_beside_the_table(self): + last = TODO.split("\n## Details")[0] + "\n" + self.assertIsInstance(self.ranked(last), ranking.Ranked) + beside = Failure("## Items holds text beside its table; an order goes in the scores or the Blocked by column, and a note in the item's detail") + for ordered in (TODO.replace("## Items\n\n", "## Items\n\nRelease 0.1.0 takes item 5 first.\n\n"), TODO.replace("## Items\n\n", "## Items\nTake item 5 first.\n\n"), TODO.replace("| 2.1 by 1 | 0 |\n\n## Details", "| 2.1 by 1 | 0 |\n\nTake item 5 first.\n\n## Details"), last + "\nTake item 5 first.\n"): + with self.subTest(ordered=ordered[-60:]): + self.assertEqual(self.ranked(ordered), beside) + + def test_refuses_an_items_table_outside_items_a_second_one_and_a_repeated_column(self): + self.assertEqual(self.ranked(TODO.replace("## Items\n", "## Plan\n")).reason, "todo.md is not in the scored-table format; rank_todo.py --help shows a valid one") + outside = TODO.replace("## Items\n\n", "## Items\n\n## Rows\n\n") + self.assertEqual(self.ranked(outside).reason, "the items table sits under ## Rows, not ## Items; move it under ## Items") + table = TODO[TODO.index("| ID | Release |"):TODO.index("\n\n## Details")] + "\n" + above = table + "\n" + TODO.replace(table, "") + self.assertEqual(self.ranked(above).reason, "the items table sits under no ## heading; move it under ## Items") + header = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n" + self.assertEqual(todo_table.items(TODO + "\n" + header.replace("| Score |", "| Later |")), Failure("todo.md holds 2 tables whose header opens | ID | Release |; keep one items table")) + repeated = TODO.replace("| Moves | Score |\n|---|", "| Moves | Score | Exempt |\n|---|---|").replace(" | 0 |\n", " | 0 | x |\n") + self.assertEqual(todo_table.items(repeated), Failure("todo.md's items table names the column Exempt twice; keep one")) + + def test_reads_an_empty_table_and_fails_on_a_header_with_no_divider(self): + header = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |" + self.assertEqual(todo_table.items(f"## Items\n\n{header}\n|---|---|---|---|---|---|---|---|---|---|---|---|\n\n## Details\n"), []) + self.assertEqual(todo_table.items(f"## Items\n\n{header}"), Failure(f"the table under {header} has no |---| divider line")) + + +class Renamed(unittest.TestCase): + def test_reads_the_releases_the_renamed_section_names(self): + self.assertEqual(todo_table.renames("## Items\n\n## Details\n"), set()) + self.assertEqual(todo_table.renames("## Renamed\n\n- 0.2.1 renamed to 0.3.0\n- 0.3.0 renamed to 0.4.0\n\n## Details\n"), {(0, 2, 1), (0, 3, 0)}) + self.assertEqual(todo_table.renames("## Renamed\n\n- 0.2.1 renamed to 0.3.0 \n"), {(0, 2, 1)}) + for bad in ("soon", "- 0.2.1 is now 0.3.0", "- 0.2 renamed to 0.3.0", "- 0.2.1 renamed to 0.3.0 later", "- 0.2.1 renamed to 0.2.1"): + with self.subTest(bad): + self.assertIsInstance(todo_table.renames(f"## Renamed\n\n{bad}\n"), Failure) + + def test_fails_on_a_renamed_section_that_does_not_parse(self): + failed = ranking.rank(TODO + "\n## Renamed\n\nsoon\n", README, DECISIONS, "") + self.assertIsInstance(failed, Failure) + self.assertIn("## Renamed", failed.reason) + + def test_ranks_a_plan_with_a_valid_renamed_section(self): + self.assertIsInstance(ranking.rank(TODO + "\n## Renamed\n\n- 0.3.0 renamed to 0.4.0\n", README, DECISIONS, ""), ranking.Ranked) + + def test_fails_on_an_item_filed_under_a_release_the_plan_marks_renamed(self): + live = ranking.rank(TODO + "\n## Renamed\n\n- 0.2.0 renamed to 0.3.0\n", README, DECISIONS, "") + self.assertIsInstance(live, Failure) + self.assertIn("marks release 0.2.0 renamed but files item 1 under it", live.reason) + + + +class ThisRepo(unittest.TestCase): + def test_todo_md_is_ranked_with_nothing_under_the_bar(self): + text = (ROOT / "todo.md").read_text(encoding="utf-8") + ranked = ranking.rank(text, *((ROOT / name).read_text(encoding="utf-8") for name in ("README.md", "docs/decisions.md", "docs/comprehension-history.md"))) + self.assertEqual(ranked, ranking.Ranked(text, [], [])) diff --git a/bin/test_release.py b/bin/release_plan/test_release.py similarity index 91% rename from bin/test_release.py rename to bin/release_plan/test_release.py index 670415f4..d49dd2f8 100644 --- a/bin/test_release.py +++ b/bin/release_plan/test_release.py @@ -4,10 +4,10 @@ import sys import tempfile import unittest -sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from test_env import isolated_env -from release import newest_tag, tagged +from release_plan.release import newest_tag, tagged class NewestTag(unittest.TestCase): diff --git a/bin/test_release_standing.py b/bin/release_plan/test_release_standing.py similarity index 98% rename from bin/test_release_standing.py rename to bin/release_plan/test_release_standing.py index 119fa20c..7b6108f0 100644 --- a/bin/test_release_standing.py +++ b/bin/release_plan/test_release_standing.py @@ -4,13 +4,13 @@ import sys import tempfile import unittest -sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from failure import Failure from test_env import isolated_env -import release_standing -import todo_table -from release import version +from release_plan import release_standing +from release_plan import todo_table +from release_plan.release import version HEADER = "## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n" diff --git a/bin/todo_table.py b/bin/release_plan/todo_table.py similarity index 98% rename from bin/todo_table.py rename to bin/release_plan/todo_table.py index a52dbfce..ac5f9a41 100644 --- a/bin/todo_table.py +++ b/bin/release_plan/todo_table.py @@ -3,8 +3,8 @@ import re import typing from failure import Failure -from markdown_text import FENCE, sections -from release import parsed, Release, release_of, VERSION +from records.markdown_text import FENCE, sections +from release_plan.release import parsed, Release, release_of, 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 @@ -58,7 +58,7 @@ class Shape: def parse_moves(id_: str, cell: str) -> Moves | Failure: - """A Moves cell: empty, or each goal the item moves, named once, and how far. rank_todo.py's cited_goals_failure holds the rules that need README.md.""" + """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 README.md.""" 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): diff --git a/bin/repo_checks/test_reviewer_launches.py b/bin/repo_checks/test_reviewer_launches.py index 74546109..22c5d089 100644 --- a/bin/repo_checks/test_reviewer_launches.py +++ b/bin/repo_checks/test_reviewer_launches.py @@ -5,7 +5,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from review_passes import PASS_AGENTS, PASSES +from review_rules.review_passes import PASS_AGENTS, PASSES from repo_checks import ROOT from rule_hook.reviewer_rung import SEAT, SECURITY_OPENER diff --git a/bin/repo_checks/test_settings.py b/bin/repo_checks/test_settings.py index 6af60d51..566e0082 100644 --- a/bin/repo_checks/test_settings.py +++ b/bin/repo_checks/test_settings.py @@ -6,7 +6,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from settings_filter import cleaned -from git_repo import git +from git_cli.git_repo import git from repo_checks import ROOT INSTALL = "git config filter.settings.clean bin/settings_filter.py" diff --git a/bin/repo_checks/test_types.py b/bin/repo_checks/test_types.py index eb72cefa..2ad7d203 100644 --- a/bin/repo_checks/test_types.py +++ b/bin/repo_checks/test_types.py @@ -30,5 +30,5 @@ class Types(unittest.TestCase): self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr) def test_mypy_checks_run_heavy_and_each_root_module(self): - self.assertLessEqual({("-p", "run_heavy"), ("-p", "machine_load"), ("-m", "release_standing"), ("-m", "docker_command")}, set(zip(tools()[::2], tools()[1::2]))) + self.assertLessEqual({("-p", "run_heavy"), ("-p", "machine_load"), ("-p", "release_plan"), ("-m", "failure")}, set(zip(tools()[::2], tools()[1::2]))) self.assertNotIn("repo_checks", tools()) diff --git a/bin/review_replay/main.py b/bin/review_replay/main.py index 13c76b48..75e7a30f 100644 --- a/bin/review_replay/main.py +++ b/bin/review_replay/main.py @@ -41,7 +41,7 @@ import typing from transcript_archive.location import archive_root from rung_replay.command import arguments_or_exit, down_from, failed, limited_exit, projects_on from review_replay.rounds import authored_by, lost_inputs, report, reviewed_path, Round, round_from, sample, stamp_seconds -from project_key import checkout_of +from transcript_archive.project_key import checkout_of from claude_code.reply import claude_reply, Limited from loop_claude.effects import Effects from failure import Failure @@ -49,8 +49,8 @@ from rung_replay.search import first_reply, replayed from claude_code.transcript import first_timestamped_line, read_transcript from model_routing.ladder import LADDER, project_rung, Rung from claude_code.entries import parse_entry, structured_output -from review_folder import REPORTS, review_folder -from review_passes import ReviewedPass, REVIEWERS +from review_rules.review_folder import REPORTS, review_folder +from review_rules.review_passes import ReviewedPass, REVIEWERS TOOL = "review-replay" USAGE = f"{TOOL} , one of {', '.join(REVIEWERS)} and a model on the routing ladder" diff --git a/bin/review_replay/test_review_replay.py b/bin/review_replay/test_review_replay.py index bab66361..8a1ebf82 100644 --- a/bin/review_replay/test_review_replay.py +++ b/bin/review_replay/test_review_replay.py @@ -19,7 +19,7 @@ from loop_claude.effects import Effects, system_effects from failure import Failure from review_replay import main from rung_replay.search import Miss, Replay, Tried -from review_passes import REVIEWERS +from review_rules.review_passes import REVIEWERS from model_routing.ladder import Rung TOOL = pathlib.Path(__file__).resolve().parents[1] / "review-replay" diff --git a/bin/review_rules/__init__.py b/bin/review_rules/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/comprehension_history.py b/bin/review_rules/comprehension_history.py similarity index 99% rename from bin/comprehension_history.py rename to bin/review_rules/comprehension_history.py index 122f1186..83b467bd 100644 --- a/bin/comprehension_history.py +++ b/bin/review_rules/comprehension_history.py @@ -3,8 +3,8 @@ import decimal import re from failure import Failure -from markdown_text import sections -from utc_stamp import utc +from records.markdown_text import sections +from records.utc_stamp import utc ARCHITECT = "Inherited architect" DECIDED_BY = "decided by" diff --git a/bin/review_folder.py b/bin/review_rules/review_folder.py similarity index 100% rename from bin/review_folder.py rename to bin/review_rules/review_folder.py diff --git a/bin/review_passes.py b/bin/review_rules/review_passes.py similarity index 100% rename from bin/review_passes.py rename to bin/review_rules/review_passes.py diff --git a/bin/round_titles.py b/bin/review_rules/round_titles.py similarity index 99% rename from bin/round_titles.py rename to bin/review_rules/round_titles.py index e705d6f4..312f19e3 100644 --- a/bin/round_titles.py +++ b/bin/review_rules/round_titles.py @@ -2,7 +2,7 @@ import dataclasses import re -from review_passes import PASSES +from review_rules.review_passes import PASSES # The most rounds a pass takes per chunk, per `docs/decisions.md` → `review: a pass gets at most two rounds per chunk, …`. rule-hook's `round-cap` refuses a round commit that `past_cap` finds takes its pass past it, and `larv-review round-count` marks a pass that reached it. CAP = 2 diff --git a/bin/test_review_folder.py b/bin/review_rules/test_review_folder.py similarity index 83% rename from bin/test_review_folder.py rename to bin/review_rules/test_review_folder.py index 8f9676dc..bd0c5e56 100644 --- a/bin/test_review_folder.py +++ b/bin/review_rules/test_review_folder.py @@ -2,9 +2,9 @@ import pathlib import sys import unittest -sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from review_folder import review_folder +from review_rules.review_folder import review_folder class ReviewFolder(unittest.TestCase): diff --git a/bin/test_review_passes.py b/bin/review_rules/test_review_passes.py similarity index 83% rename from bin/test_review_passes.py rename to bin/review_rules/test_review_passes.py index 3778491c..2a63de79 100644 --- a/bin/test_review_passes.py +++ b/bin/review_rules/test_review_passes.py @@ -3,9 +3,9 @@ import sys import typing import unittest -sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from review_passes import PASS_AGENTS, PASSES, prose, ReviewedPass, REVIEWERS +from review_rules.review_passes import PASS_AGENTS, PASSES, prose, ReviewedPass, REVIEWERS class ReviewPasses(unittest.TestCase): @@ -14,7 +14,7 @@ class ReviewPasses(unittest.TestCase): self.assertEqual(list(REVIEWERS), [name for name in PASSES if PASS_AGENTS[name]]) def test_names_each_agent_under_agents(self): - agents = pathlib.Path(__file__).resolve().parents[1] / "agents" + agents = pathlib.Path(__file__).resolve().parents[2] / "agents" self.assertEqual(sorted(REVIEWERS.values()), sorted(path.stem for path in agents.glob("*.md"))) def test_counts_markdown_an_agent_follows_as_config_and_the_rest_as_prose(self): diff --git a/bin/test_round_titles.py b/bin/review_rules/test_round_titles.py similarity index 96% rename from bin/test_round_titles.py rename to bin/review_rules/test_round_titles.py index b878646e..da90ed9f 100644 --- a/bin/test_round_titles.py +++ b/bin/review_rules/test_round_titles.py @@ -2,9 +2,9 @@ import pathlib import sys import unittest -sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from round_titles import Findings, lacks_counts, past_cap, round_counts, round_findings, rounds_past_first +from review_rules.round_titles import Findings, lacks_counts, past_cap, round_counts, round_findings, rounds_past_first class Rounds(unittest.TestCase): diff --git a/bin/routing_figures/archive.py b/bin/routing_figures/archive.py index cbe54206..011178e7 100644 --- a/bin/routing_figures/archive.py +++ b/bin/routing_figures/archive.py @@ -10,12 +10,12 @@ import typing from transcript_archive.read import archived_outcomes, chunk_outcomes, finished_chunks from branch_chunks.read import branch_chunks from branch_chunks.cut import BranchChunk -from project_key import checkout_of +from transcript_archive.project_key import checkout_of from routing_figures.chunk import Chunk, chunk_figures, ChunkFigures, Subagent -from git_repo import default_ref, Git +from git_cli.git_repo import default_ref, Git from failure import Failure from claude_code.entries import parse_entry -from file_writes import replace_file +from records.file_writes import replace_file from transcript_archive.outcomes import VERDICT_AT FIGURES = "routing-figures.md" diff --git a/bin/routing_figures/chunk.py b/bin/routing_figures/chunk.py index 274fcad0..eba0a933 100644 --- a/bin/routing_figures/chunk.py +++ b/bin/routing_figures/chunk.py @@ -5,13 +5,13 @@ import re from claude_code.entries import assistant_parts, parts, tool_call, tool_result from branch_chunks.cut import BranchChunk -from git_command import commits +from git_cli.git_command import commits from routing_figures.dollars import costed, Dollars, Message, messages, recorded_costs, Spent from model_routing.route import ESCALATION_MARKER, Route, route_from from transcript_archive.outcomes import judge_costs, UNFINISHED_AT, workers -from round_titles import rounds_past_first +from review_rules.round_titles import rounds_past_first from model_routing.ladder import Rung -from shell_command import simple_commands +from command_lines.shell_command import simple_commands ESCALATION = re.compile(rf"{ESCALATION_MARKER} ([0-9]+):") diff --git a/bin/routing_figures/state.py b/bin/routing_figures/state.py index 9f88146a..129b2e04 100644 --- a/bin/routing_figures/state.py +++ b/bin/routing_figures/state.py @@ -8,8 +8,8 @@ import re from routing_figures.calls import Call, SENTENCES from failure import Failure -from file_writes import replace_file, replace_json -from utc_stamp import STAMPED +from records.file_writes import replace_file, replace_json +from records.utc_stamp import STAMPED CYCLES_PER_CHECK = 20 RAISED = "routing-calls-raised.md" diff --git a/bin/routing_figures/test_routing_figures.py b/bin/routing_figures/test_routing_figures.py index 60b80713..e4afcd2f 100644 --- a/bin/routing_figures/test_routing_figures.py +++ b/bin/routing_figures/test_routing_figures.py @@ -20,9 +20,9 @@ from routing_figures.calls import Call, calls, totals from routing_figures.chunk import Chunk, chunk_figures, ChunkFigures, Reports, Subagent from routing_figures.state import due from failure import Failure -import git_repo +from git_cli import git_repo from test_env import isolated_env -from todo_table import Item +from release_plan.todo_table import Item from model_routing.ladder import LADDER, Rung from transcript_archive import outcomes, write from routing_figures.render import render diff --git a/bin/rule_hook/git.py b/bin/rule_hook/git.py index 5ce47cd6..f041d2f6 100644 --- a/bin/rule_hook/git.py +++ b/bin/rule_hook/git.py @@ -1,7 +1,7 @@ import pathlib from failure import Failure -import git_repo +from git_cli import git_repo def guarded_git(directory: str, *args: str) -> str | Failure: diff --git a/bin/rule_hook/heavy_command.py b/bin/rule_hook/heavy_command.py index 106b61a7..83ee29e8 100644 --- a/bin/rule_hook/heavy_command.py +++ b/bin/rule_hook/heavy_command.py @@ -1,6 +1,6 @@ """Whether a simple command is a heavy one, for the `run-heavy` rule: a docker build, or a run of a mutation tool.""" -from docker_command import docker_subcommand -from shell_command import launched, tool_name +from command_lines.docker_command import docker_subcommand +from command_lines.shell_command import launched, tool_name # Each mutation tool, and the words that make its call a mutation run when one of them follows it within two words; where the set is empty, every call is one. MUTATORS = {"cargo": {"mutants"}, "infection": set(), "mutmut": {"run"}, "stryker": {"run"}} diff --git a/bin/rule_hook/main.py b/bin/rule_hook/main.py index 485aed7e..5d7ede86 100644 --- a/bin/rule_hook/main.py +++ b/bin/rule_hook/main.py @@ -38,14 +38,14 @@ import typing from rule_hook.call import applied, Call, FILE_TOOLS, parsed_call, text from rule_hook.rules import Breach, check, Checked, command_breaches, file_breaches, rules_help -from git_command import commits +from git_cli.git_command import commits from failure import Failure from rule_hook.override_log import Log, log_path, logged, print_overrides, write_override from rule_hook.repeat_read import read_breaches from rule_hook.reviewer_report import report_breaches from rule_hook.reviewer_rung import reviewer_breaches, skill_breaches from rule_hook.round_cap import round_cap_breaches -from shell_command import simple_commands +from command_lines.shell_command import simple_commands from rule_hook.todo_check import todo_breaches diff --git a/bin/rule_hook/override_log.py b/bin/rule_hook/override_log.py index 29926a85..9a5f6c90 100644 --- a/bin/rule_hook/override_log.py +++ b/bin/rule_hook/override_log.py @@ -6,10 +6,10 @@ import sys import typing from rule_hook.rules import Breach -from git_repo import default_ref +from git_cli.git_repo import default_ref from rule_hook.git import existing, guarded_git from failure import Failure -from utc_stamp import utc +from records.utc_stamp import utc LOG = "rule-overrides.tsv" diff --git a/bin/rule_hook/repeat_read.py b/bin/rule_hook/repeat_read.py index df76b449..1cdd8c05 100644 --- a/bin/rule_hook/repeat_read.py +++ b/bin/rule_hook/repeat_read.py @@ -14,7 +14,7 @@ from rule_hook.call import Call, FILE_TOOLS, text from claude_code.transcript import current_thread, read_transcript from failure import Failure from claude_code.entries import parts, tool_call, tool_result, tool_use_id -from shell_command import resolved, simple_commands +from command_lines.shell_command import resolved, simple_commands # The lines a Read without a limit returns. READ_LIMIT = 2000 diff --git a/bin/rule_hook/reviewer_report.py b/bin/rule_hook/reviewer_report.py index 9c1119bc..7f6ba792 100644 --- a/bin/rule_hook/reviewer_report.py +++ b/bin/rule_hook/reviewer_report.py @@ -4,7 +4,7 @@ import pathlib from rule_hook.rules import Breach from rule_hook.call import Call -from review_folder import REPORTS +from review_rules.review_folder import REPORTS # Each agent under agents/, read from the folder, so an agent the routing tables miss is still confined. AGENT_FILES = frozenset(path.stem for path in (pathlib.Path(__file__).resolve().parents[2] / "agents").glob("*.md")) diff --git a/bin/rule_hook/reviewer_rung.py b/bin/rule_hook/reviewer_rung.py index 73de2f5d..c6075997 100644 --- a/bin/rule_hook/reviewer_rung.py +++ b/bin/rule_hook/reviewer_rung.py @@ -5,11 +5,11 @@ from rule_hook.rules import Breach from rule_hook.call import Call, text from claude_code.entries import content from failure import Failure -import git_repo +from git_cli import git_repo from rule_hook.git import guarded_git from model_routing.worker_rungs import handed from model_routing.ladder import position, review_rung, ReviewKind, Rung -from review_passes import prose, REVIEWERS +from review_rules.review_passes import prose, REVIEWERS from claude_code.transcript import read_transcript # The pass each agent under agents/ reviews. diff --git a/bin/rule_hook/round_cap.py b/bin/rule_hook/round_cap.py index 9d654a56..9232a910 100644 --- a/bin/rule_hook/round_cap.py +++ b/bin/rule_hook/round_cap.py @@ -1,9 +1,9 @@ from rule_hook.rules import Breach -from round_titles import cap, past_cap, round_counts, round_pass -from git_command import CommitCall +from review_rules.round_titles import cap, past_cap, round_counts, round_pass +from git_cli.git_command import CommitCall from failure import Failure -import git_repo -from review_passes import PASSES +from git_cli import git_repo +from review_rules.review_passes import PASSES def round_cap_breaches(commit: CommitCall) -> list[Breach]: diff --git a/bin/rule_hook/rules.py b/bin/rule_hook/rules.py index 2338f907..4893f01b 100644 --- a/bin/rule_hook/rules.py +++ b/bin/rule_hook/rules.py @@ -3,13 +3,13 @@ import posixpath import re import typing -from round_titles import CAP, lacks_counts, RELEASE_REVIEW_CAP -from git_command import commits +from review_rules.round_titles import CAP, lacks_counts, RELEASE_REVIEW_CAP +from git_cli.git_command import commits from run_heavy.capped_docker import finds_this_docker from rule_hook.heavy_command import heavy -from shell_command import launched, Simple -from review_folder import REPORTS -from docker_command import unlimited +from command_lines.shell_command import launched, Simple +from review_rules.review_folder import REPORTS +from command_lines.docker_command import unlimited RuleName = typing.Literal["action-pin", "commit-one-line", "docker-run-memory", "ignorefile-sorted", "image-pin", "no-ai-attribution", "repeat-read", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "run-heavy", "todo-rank-check"] diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index 530fd5c1..98f3086e 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -15,13 +15,13 @@ from rule_hook.repeat_read import Asked, modified, read_breaches, result_lines from rule_hook.rules import blocks, Breach, check, command_breaches, file_breaches, overrides from rule_hook.main import breaches_of from rule_hook.call import Call, parsed_call -from git_command import commit_message, CommitCall, commits -from test_rank_todo import DECISIONS, README, TODO +from git_cli.git_command import commit_message, CommitCall, commits +from release_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 from rule_hook.reviewer_rung import reviewer_breaches, skill_breaches -from shell_command import segments, simple_commands +from command_lines.shell_command import segments, simple_commands HOOK = pathlib.Path(__file__).resolve().parents[1] / "rule-hook" # Built from parts, so this file carries no attribution of its own. diff --git a/bin/rule_hook/todo_check.py b/bin/rule_hook/todo_check.py index 476f54e8..6bdf5aac 100644 --- a/bin/rule_hook/todo_check.py +++ b/bin/rule_hook/todo_check.py @@ -4,7 +4,7 @@ import pathlib from rule_hook.rules import Breach from failure import Failure from rule_hook.git import guarded_git -import rank_todo +from release_plan import ranking def todo_breaches(directory: str) -> list[Breach]: @@ -12,7 +12,7 @@ def todo_breaches(directory: str) -> list[Breach]: if isinstance(top, Failure) or not (pathlib.Path(top) / "todo.md").is_file(): return [] todo = pathlib.Path(top) / "todo.md" - return [Breach("todo-rank-check", line, top) for line in rank_todo.check_failures(todo)] if changed(top, todo) else [] + return [Breach("todo-rank-check", line, top) for line in ranking.check_failures(todo)] if changed(top, todo) else [] def changed(top: str, todo: pathlib.Path) -> bool: diff --git a/bin/run_heavy/capped_docker.py b/bin/run_heavy/capped_docker.py index b253d9df..0dc5f1e8 100644 --- a/bin/run_heavy/capped_docker.py +++ b/bin/run_heavy/capped_docker.py @@ -5,8 +5,8 @@ import shutil import sys import typing -from docker_command import capped -from shell_command import tool_name +from command_lines.docker_command import capped +from command_lines.shell_command import tool_name # The folder run-heavy puts first on its command's PATH, holding the docker that runs main. PATH_ENTRY = pathlib.Path(__file__).resolve().parent / "path_entry" diff --git a/bin/score_outcomes/anchors.py b/bin/score_outcomes/anchors.py index ade9ff29..f1929b32 100644 --- a/bin/score_outcomes/anchors.py +++ b/bin/score_outcomes/anchors.py @@ -1,6 +1,6 @@ import re -from todo_table import cells, LEVELS, parse_ids +from release_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 f973b7ca..c0bcc5cb 100644 --- a/bin/score_outcomes/main.py +++ b/bin/score_outcomes/main.py @@ -79,11 +79,11 @@ import sys from score_outcomes.anchors import anchor_lines, Anchors, ANCHORS_PATH, parse_anchors from branch_chunks.read import branch_chunks -from git_repo import default_branch, full_history, git, top +from git_cli.git_repo import default_branch, full_history, git, top from failure import Failure from score_outcomes.results import fixed_later, misreads, nearest, render, report, Result, results_of -from todo_table import LEVELS, risk, TOP_SCORE -from markdown_text import listed +from release_plan.todo_table import LEVELS, risk, TOP_SCORE +from records.markdown_text import listed # The scores score-outcomes takes, in order. GIVEN = ("L", "E", "I", "S") diff --git a/bin/score_outcomes/results.py b/bin/score_outcomes/results.py index f48293a7..dec2362c 100644 --- a/bin/score_outcomes/results.py +++ b/bin/score_outcomes/results.py @@ -3,9 +3,9 @@ import statistics import typing from branch_chunks.cut import BranchChunk, Landing, NOT_WORK -from round_titles import Findings, round_findings, rounds_past_first -from todo_table import Item -from markdown_text import listed +from review_rules.round_titles import Findings, round_findings, rounds_past_first +from release_plan.todo_table import Item +from records.markdown_text import listed # 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 4ac6a8d0..3793ff7b 100644 --- a/bin/score_outcomes/test_score_outcomes.py +++ b/bin/score_outcomes/test_score_outcomes.py @@ -10,9 +10,9 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from score_outcomes.anchors import anchor_lines, parse_anchors from branch_chunks.cut import BranchChunk, Landing from failure import Failure -from round_titles import Findings +from review_rules.round_titles import Findings from test_env import isolated_env -from todo_table import Item +from release_plan.todo_table import Item from score_outcomes.results import nearest, rank_correlation, render, report, Result, results_of from score_outcomes.main import report_text diff --git a/bin/statusline.py b/bin/statusline.py index 104af09a..69d28800 100755 --- a/bin/statusline.py +++ b/bin/statusline.py @@ -7,7 +7,7 @@ import os import sys from failure import Failure -import git_repo +from git_cli import git_repo CYAN = "\033[36m" DIM = "\033[2m" diff --git a/bin/subagent_rung/main.py b/bin/subagent_rung/main.py index f27aba2c..f76f6ff1 100644 --- a/bin/subagent_rung/main.py +++ b/bin/subagent_rung/main.py @@ -15,7 +15,7 @@ Exit 1, saying why, on bad arguments. import re import sys -from todo_table import LEVELS +from release_plan.todo_table import LEVELS from model_routing.ladder import planning_rung, project_rung, worker_rung USAGE = f"usage: subagent-rung [--plan] , L a level from 1 to {LEVELS['L']}" diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py index 17499bd6..e2e53208 100644 --- a/bin/test_rank_todo.py +++ b/bin/test_rank_todo.py @@ -1,576 +1,15 @@ import contextlib import io import pathlib -import re import sys import tempfile import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from failure import Failure +from release_plan.test_ranking import DECISIONS, OLD_SHAPE, README, TODO import rank_todo -from repo_checks import ROOT -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" - -README = "# P\n\n## Goals\n\n" + VOID + "1. **Achieve:** Fast.\n2. **Maintain:** Correct.\n 1. **Achieve:** Tested.\n\n## Audience\n\nMe.\n" - -DECISIONS = "## A choice\n\nStands until `todo.md` item 5 ends it.\n" - -TODO = """# todo - -## Scoring - -`Score = 100 * V / 2**S` - -`Bar = 2` - -`Next ID = 6` - -## Items - -| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | -|---|---|---|---|---|---|---|---|---|---|---|---| -| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 0 | -| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 0 | -| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 | 0 | -| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 0 | -| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 0 | - -## Details - -### 1. stale heading - -Later detail. - -### 3. Make it fast. - -Fast detail. - -## Notes - -Kept as written. -""" - -OLD_SHAPE = """# todo - -## Scoring - -`Score = -R - S/4 + 2*A + 2*G*W` - -`Bar = 9` - -`Next ID = 6` - -| Goal | W | -|---|---| -| 1 | 1.00 | -| 2 | 0.67 | -| 2.1 | 0.33 | - -## Items - -| ID | Release | Blocked by | Exempt | Item | R | S | C | A | G | Goals | Score | -|---|---|---|---|---|---|---|---|---|---|---|---| -| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 3 | 9 | 9 | 1 | 0 | -| 2 | 0.1.0 | | | **Tighten the tests.** | 2 | 4 | 3 | 5 | 5 | 2.1 | 0 | -| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 3 | 8 | 3 | 6 | 8 | 2.1, 1 | 0 | -| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 9 | 2 | 3 | 1 | 1 | 2.1 | 0 | -| 5 | 0.1.0 | | decision | **Move the writes out.** | 5 | 5 | 3 | 4 | 5 | 2.1 | 0 | - -## Details - -### 1. stale heading - -Later detail. - -### 3. Make it fast. - -Fast detail. - -## Notes - -Kept as written. -""" - - -class Rank(unittest.TestCase): - def ranked(self, todo=TODO, readme=README, decisions=DECISIONS): - return rank_todo.rank(todo, readme, decisions, "") - - def test_scores_and_sorts_by_release_then_security_then_score_and_orders_the_details_to_match(self): - ranked = self.ranked() - self.assertIn("""| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 12.3 | -| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 | 5.5 | -| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 3.1 | -| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 1.5 | -| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 228.4 | -""", ranked.text) - self.assertTrue(ranked.text.endswith("## Details\n\n### 3. Make it fast, `a | b`.\n\nFast detail.\n\n### 1. Ship the later thing.\n\nLater detail.\n\n## Notes\n\nKept as written.\n")) - self.assertEqual(ranked.under_bar, []) - self.assertEqual(ranked.notes, []) - self.assertEqual(self.ranked(ranked.text), ranked) - - def test_keeps_a_detail_that_opens_with_markdown_quoted_by_four_spaces(self): - quoting = TODO.replace("Fast detail.", " ## Goals\n\nFast detail.") - self.assertIn("### 3. Make it fast, `a | b`.\n\n ## Goals\n\nFast detail.\n", self.ranked(quoting).text) - - def test_weighs_each_achieve_goal_97_percent_of_the_one_above_and_a_defects_maintain_goal_as_the_first(self): - readme = "## Goals\n\n1. **Achieve:** A.\n 1. **Maintain:** B.\n 2. **Achieve:** C.\n2. **Achieve:** D.\n" - self.assertEqual({goal: round(weight, 4) for goal, weight in rank_todo.goal_weights(rank_todo.readme_goals(readme), None).items()}, {"1": 0.3435, "1.1": 0.3435, "1.2": 0.3332, "2": 0.3232}) - - def test_weighs_5_achieve_goals_from_0212_to_0188_and_15_from_0082_to_0053_as_the_help_says(self): - for count, first, last in ((5, 0.212, 0.188), (15, 0.082, 0.053)): - with self.subTest(count=count): - goals = rank_todo.readme_goals("## Goals\n\n" + "".join(f"{number}. **Achieve:** G.\n" for number in range(1, count + 1))) - weights = list(rank_todo.goal_weights(goals, None).values()) - self.assertEqual((round(weights[0], 3), round(weights[-1], 3), round(sum(weights), 6)), (first, last, 1)) - for figure in (rank_todo.GOAL_STEP, first, last): - self.assertIn(str(figure), rank_todo.__doc__) - self.assertIn(f"While it is under {rank_todo.FLOOR}, or the history holds no scoring run, code health weighs {rank_todo.UNDER_FLOOR} times its weight by position, and the other goals keep theirs.", " ".join(rank_todo.__doc__.split())) - - def test_scores_an_item_by_the_weights_of_the_goals_it_moves(self): - readme = "## Goals\n\n" + VOID + "1. **Achieve:** A.\n 1. **Maintain:** B.\n 2. **Achieve:** C.\n2. **Achieve:** D.\n" - todo = TODO.replace("2.1 by 8, 1 by 6", "1.2 by 2, 2 by 3").replace("| 2.1 by 1 |", "| 1 by 1 |") - self.assertIn("| **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 1.2 by 2, 2 by 3 | 1.3 |", self.ranked(todo, readme).text) - - def test_scores_an_item_that_moves_no_goal_zero(self): - ranked = self.ranked(TODO.replace("| 1 | 2 | 1 | 2 | 4 | 2.1 by 1 |", "| 1 | 2 | 1 | 2 | 4 | |")) - self.assertIn("| **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | | 0.0 |", ranked.text) - self.assertEqual(ranked.under_bar, ["item 2 scores 0.0, under the bar 2; delete it, or mark it with a reason the bar does not apply"]) - - def test_holds_each_item_a_decision_cites_and_says_how_to_settle_a_finished_one(self): - self.assertIsInstance(self.ranked(decisions=DECISIONS + "Until `todo.md` item 4 lands.\n"), rank_todo.Ranked) - gone = self.ranked(TODO.replace("| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 0 |\n", "")) - self.assertEqual(gone.reason, "docs/decisions.md cites \"`todo.md` item 5\", which todo.md no longer holds; revise that decision to say what holds now") - - def test_names_each_item_under_the_bar_that_is_not_exempt(self): - ranked = self.ranked(TODO.replace("`Bar = 2`", "`Bar = 3.5`")) - self.assertEqual(ranked.under_bar, ["item 2 scores 3.1, under the bar 3.5; delete it, or mark it with a reason the bar does not apply"]) - self.assertEqual(self.ranked(TODO.replace("`Bar = 2`", "`Bar = 3.1`")).under_bar, []) - blocking = self.ranked(TODO.replace("`Bar = 2`", "`Bar = 3.5`").replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 2 |").replace("| 5 | 0.1.0 | |", "| 5 | 0.1.0 | 3 |")) - self.assertEqual(blocking.under_bar, ["item 2 scores 3.1, under the bar 3.5; delete it and the items it blocks, directly or through another (3, 5), or mark it with a reason the bar does not apply"]) - self.assertEqual(self.ranked(ranked.text.replace("| 2 | 0.1.0 | | |", "| 2 | 0.1.0 | | principle |")).under_bar, []) - self.assertEqual(self.ranked(ranked.text.replace("| 2 | 0.1.0 | | |", "| 2 | 0.1.0 | | owner |")).under_bar, []) - - def test_reads_goals_and_sub_goals_in_reading_order(self): - self.assertEqual(rank_todo.readme_goals(README), [("1", "Achieve"), ("2", "Maintain"), ("2.1", "Achieve")]) - self.assertEqual(rank_todo.readme_goals(README.replace(" 1.", "\t1.")), [("1", "Achieve"), ("2", "Maintain"), ("2.1", "Achieve")]) - self.assertEqual(rank_todo.readme_goals(README.replace("2. **Maintain:** Correct.", "```\n## Goals\n```\n2. Correct.")), [("1", "Achieve"), ("2", None), ("2.1", "Achieve")]) - self.assertEqual(rank_todo.readme_goals(README.replace("2. **Maintain:**", "1. **Maintain:**")), Failure("README.md's ## Goals numbers 1, 1, 1.1; number each goal by its position")) - self.assertEqual(rank_todo.readme_goals("## Goals\n\n1. **Achieve:** A.\n 1. **Achieve:** B.\n\t2. **Achieve:** C.\n"), [("1", "Achieve"), ("1.1", "Achieve"), ("1.2", "Achieve")]) - - def test_refuses_a_goal_it_cannot_weigh(self): - cases = { - (TODO.replace("2.1 by 8, 1 by 6", "1 by 8, 2 by 6"), README): "item 3 cites goal 2, a maintain goal, which only a defect that restores it may name; name the achieve goals the item moves", - (TODO.replace("2.1 by 8, 1 by 6", "2.1 by 8, 3 by 6"), README): "item 3 cites goal 3, which README.md's ## Goals does not number", - (TODO.replace("2.1 by 8, 1 by 6", "2.1 by 8, 2.1 by 6"), README): "item 3 cites goal 2.1 twice; name each goal once", - (TODO, README.replace("**Maintain:** Correct", "Correct")): "README.md's goal 2 is marked neither **Maintain:** nor **Achieve:**; mark it, as ~/.claude/rules/goals-and-audience.md says, so rank_todo.py knows which goals score", - } - for (todo, readme), reason in cases.items(): - with self.subTest(reason=reason): - self.assertEqual(self.ranked(todo, readme), Failure(reason)) - - def test_ranks_questions_first_then_security_whatever_they_score_and_a_defect_by_its_score(self): - todo = TODO.replace("| 2 | 0.1.0 | | |", "| 2 | 0.1.0 | | defect |").replace("| 3 | 3 | 5 | 9 | 2 | 2.1 by 1 |", "| 3 | 3 | 5 | 9 | 8 | 2.1 by 1 |").replace("| 5 | 0.1.0 | | decision |", "| 5 | 0.1.0 | | question |") - rows = [line.split(" | ")[0] for line in self.ranked(todo, decisions="").text.splitlines() if line.startswith("| ") and " | 0." in line] - self.assertEqual(rows, ["| 5", "| 4", "| 3", "| 2", "| 1"]) - - def test_weighs_the_maintain_goal_a_defect_restores_as_the_heaviest_achieve_goal(self): - ranked = self.ranked(TODO.replace("| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 |", "| 2 | 0.1.0 | | defect | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2 by 3 |")) - self.assertIn("| **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2 by 3 | 9.5 |", ranked.text) - - def test_refuses_a_goal_named_beside_its_own_sub_goal(self): - readme = "## Goals\n\n" + VOID + "1. **Achieve:** A.\n 1. **Maintain:** B.\n 2. **Achieve:** C.\n2. **Achieve:** D.\n" - todo = TODO.replace("2.1 by 8, 1 by 6", "1.2 by 2, 1 by 3").replace("| 2.1 by 1 |", "| 2 by 1 |") - self.assertEqual(self.ranked(todo, readme), Failure("item 3 names goal 1 and its sub-goal 1.2; name one, never both: the sub-goal where the move serves it, else the parent")) - self.assertIsInstance(self.ranked(todo.replace("1.2 by 2, 1 by 3", "1.2 by 2, 2 by 3"), readme), rank_todo.Ranked) - - def test_scores_every_item_zero_where_readme_marks_no_goal_achieve(self): - ranked = self.ranked(TODO.replace("2.1 by 8, 1 by 6", "").replace("| 2.1 by 1 |", "| |").replace("| 1 by 9 |", "| |"), README.replace("**Achieve:**", "**Maintain:**")) - self.assertEqual([line.split(" scores ")[0] for line in ranked.under_bar], ["item 2", "item 3", "item 1"]) - self.assertEqual(ranked.notes, ["README.md voids code health and marks no goal **Achieve:**, so every item scores V 0"]) - - def test_accepts_a_move_of_ten_and_a_variable_base(self): - ranked = self.ranked(TODO.replace("| 1 by 9 |", "| 1 by 10 |").replace("100 * V / 2**S", "V * S ** 2")) - self.assertIn("| **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 10 | 5.1 |", ranked.text) - - def test_asks_to_drop_a_goal_weights_table_from_a_table_with_moves(self): - weighted = TODO.replace("## Items\n", "| Goal | W |\n|---|---|\n| 1 | 1.00 |\n\n## Items\n") - self.assertEqual(self.ranked(weighted), Failure("todo.md holds a goal weights table beside a Moves column; drop the table, since rank_todo.py weighs the goals itself, as its --help says")) - - def test_refuses_a_formula_that_is_more_than_arithmetic_over_the_scores(self): - for formula in ("__import__('os')", "R.real", "X + 1", "C + 1", "A + V", "G + V", "W * V", "R ^ 2", "R +", "R / (S - 2)", "R\x00", "1" * 400, " + ".join(["R"] * 300), "-" * 100000 + "R", "10 ** 10 ** 10", "(-8) ** (1 / 3)", "0 ** -1"): - with self.subTest(formula=formula): - self.assertIsInstance(self.ranked(TODO.replace("100 * V / 2**S", formula)), Failure) - self.assertIn("| 1 by 9 | 2.0 |", self.ranked(TODO.replace("100 * V / 2**S", "R + S / S")).text) - self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "1 ** (1 / (S - S))")), Failure("the formula gives item 1 no finite score")) - self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "(1 / (S - S)) ** 0")), Failure("the formula gives item 1 no finite score")) - self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "W")), Failure("the formula 'W' may hold only numbers, E, I, L, R, S, V, + - * / ** and parentheses")) - self.assertEqual(self.ranked(TODO.replace("2.1 by 8, 1 by 6", "2.1: 8, 1: 6")), Failure("item 3's Moves '2.1: 8, 1: 6' is not empty or goals such as `1.1 by 8, code health by 5`, each moved by a whole number from 1 to 10")) - - def test_refuses_a_file_off_the_format(self): - row = "| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 0 |" - broken = { - row: row.replace("0.1.0", "0.1"), - "| 1 | 2 | 1 | 2 | 4 | 2.1 by 1 |": "| 5 | 2 | 1 | 2 | 4 | 2.1 by 1 |", - "Tighten the tests.** | 1 | 2 | 1 | 2 | 4 |": "Tighten the tests.** | 1 | 4 | 1 | 2 | 4 |", - "Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1": "Tighten the tests.** | 1 | 2 | 6 | 2 | 4 | 2.1", - "Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by": "Tighten the tests.** | 0 | 2 | 1 | 2 | 4 | 2.1 by", - "| 2 | 4 | 2.1 by 1 | 0 |\n| 3": "| 2 | 11 | 2.1 by 1 | 0 |\n| 3", - "Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1": "Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 11", - "Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1": "Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 0", - "2.1 by 8, 1 by 6": "2.1: 8, 1: 6", - "2.1 by 8, 1 by 6 ": "2.1 by 8,1 by 6 ", - "| 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 |": "| 2 | 1 | 2 | 3 | 7 | 2.1, 1 |", - row + "\n": row.replace("2 | 4 |", "2 | ² |") + "\n", - "| 2.1 by 1 | 0 |\n\n## Details": "| 2.1 by 1 | 0 |\n\n| 9 | 0.1.0 | | | **Stray.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 0 |\n\n## Details", - "| 4 | 0.1.0 | | security |": "| 4 | 0.1.0 | | later |", - "| 5 | 0.1.0 | | decision |": "| 5 | 0.1.0 | | |", - "`Next ID = 6`": "`Next ID = 5`", - "`Next ID = 6`\n": "`Next ID = 6.5`\n", - "| 4 | 0.1.0 | | security | **Rotate": "| 4 | 0.1.0 | | decision | **Rotate", - "Fast detail.": "```\n## Goals\n```", - "### 3. Make it fast.": "### 7. Make it fast.", - "`Bar = 2`": "`Bar = nan`", - "## Items\n\n| ID | Release | Blocked by |": "## Plan\n\n| ID | Release |", - } - for old, new in broken.items(): - with self.subTest(new=new): - self.assertIn(old, TODO) - self.assertIsInstance(self.ranked(TODO.replace(old, new)), Failure) - - -# A scoring run of the project whose overall mean is {overall}. -SCORED = "# Comprehension history\n\n## 2026-10-08T12:00:00Z, PR #1 at aaaaaaa\n\n| Seat | Overall |\n|---|---|\n| Mid A | 6 |\n| Mean | {overall} |\n" - - -class CodeHealth(unittest.TestCase): - readme = "## Goals\n\n1. **Achieve:** A.\n" - todo = TODO.split("| 1 | 0.2.0", 1)[0].replace("`Bar = 2`", "`Bar = 0.1`") + "| 1 | 0.1.0 | | | **Read easier.** | 1 | 1 | 1 | 1 | 1 | code health by 1 | 0 |\n| 2 | 0.1.0 | | | **Do A.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 0 |\n" - - def scores(self, history, readme=readme): - ranked = rank_todo.rank(self.todo, readme, "", history) - return ranked if isinstance(ranked, Failure) else {line.split(" | ")[0]: line.rsplit(" | ", 1)[1].rstrip(" |") for line in ranked.text.splitlines() if line.startswith("| ") and " 0.1.0 " in line} - - def entry(self, overall, at="2026-10-08T12", read="PR #1 at aaaaaaa"): - """A scoring run's entry, without the history's title.""" - return SCORED.format(overall=overall).removeprefix("# Comprehension history\n\n").replace("2026-10-08T12", at).replace("PR #1 at aaaaaaa", read) - - def test_ranks_code_health_first_among_the_achieve_goals_at_an_overall_of_7_or_above(self): - # Code health, then goal 1: weights 1 / 1.97 and 0.97 / 1.97, an item moving one by 1 at S 1 scoring 50 times its weight. - self.assertEqual(self.scores(SCORED.format(overall="7.00")), {"| 1": "25.4", "| 2": "24.6"}) - - def test_weighs_code_health_four_times_as_much_under_an_overall_of_7_and_before_any_scoring_run(self): - for history in (SCORED.format(overall="6.99"), "", "# Comprehension history\n\n## 2026-10-09T12:00:00Z, PR #2 at bbbbbbb, against aaaaaaa\n\nRuling: better\n"): - with self.subTest(history=history): - self.assertEqual(self.scores(history), {"| 1": "101.5", "| 2": "24.6"}) - - def test_weighs_by_the_newest_scored_commit_wherever_the_file_holds_it(self): - older = self.entry("6.50") - newer = self.entry("7.25", "2026-10-10T12", "PR #1 at bbbbbbb") - for history in (f"{older}\n{newer}", f"{newer}\n{older}"): - with self.subTest(history=history): - self.assertEqual(self.scores(history)["| 1"], "25.4") - - def test_weighs_by_the_mean_overall_of_every_run_on_the_newest_scored_commit(self): - # 7.13 and 6.88 average 7.005, at the floor or above; 7.10 and 6.80 average 6.95, under it. - for first, rerun, value in (("7.13", "6.88", "25.4"), ("7.10", "6.80", "101.5")): - with self.subTest(first=first, rerun=rerun): - self.assertEqual(self.scores(f"{self.entry(first)}\n{self.entry(rerun, '2026-10-08T13', 'PR #1 rerun at aaaaaaa')}")["| 1"], value) - later = self.entry("6.50", "2026-10-09T12", "PR #2 at bbbbbbb") - self.assertEqual(self.scores(f"{self.entry('7.13')}\n{self.entry('6.88', '2026-10-08T13', 'PR #1 rerun at aaaaaaa')}\n{later}")["| 1"], "101.5") - - def test_matches_a_commit_whichever_length_a_heading_writes_it_at(self): - full = "aaaaaaa" + "0" * 33 - # As runs of one commit, 7.13 and 6.88 average 7.005; the newer alone is under the floor. - for first, rerun in (("aaaaaaa", full), (full, "aaaaaaa")): - with self.subTest(first=first, rerun=rerun): - self.assertEqual(self.scores(f"{self.entry('7.13', read=f'PR #1 at {first}')}\n{self.entry('6.88', '2026-10-08T13', f'PR #1 rerun at {rerun}')}")["| 1"], "25.4") - - def test_weighs_by_a_ruling_that_holds_scoring_seats_places(self): - # A ruling recorded before PR #255 scored the project too: below its votes, a scores table with a Mean row, and each scoring seat's places. - ruling = "## 2026-10-10T12:00:00Z, PR #2 at bbbbbbb, against aaaaaaa\n\nRuling: better\n\n| Seat | Overall |\n|---|---|\n| Mid A | better |\n\n| Seat | Overall |\n|---|---|\n| Mid A | 7.5 |\n| Mean | 7.25 |\n\nJunior A, hardest first:\n\n- `bin/a.py:1` `f`: long\n" - self.assertEqual(self.scores(f"{self.entry('6.50')}\n{ruling}")["| 1"], "25.4") - - def test_refuses_a_newest_scoring_run_with_no_overall_mean(self): - for history in (SCORED.format(overall="high"), SCORED.split("| Mean")[0]): - with self.subTest(history=history): - self.assertEqual(self.scores(history), Failure("docs/comprehension-history.md's scoring run 2026-10-08T12:00:00Z, PR #1 at aaaaaaa has no Mean row ending in its overall, which sets code health's weight")) - - def test_drops_code_health_where_readme_voids_it(self): - voided = "## Goals\n\n**Void:** code health, since it is a one-off script.\n\n1. **Achieve:** A.\n" - self.assertEqual(self.scores("", voided), Failure("item 1 names code health, which README.md voids; drop it from the item's Moves, or the void from README.md")) - ranked = rank_todo.rank(self.todo.replace("code health by 1", "1 by 2"), voided, "", "") - self.assertIn("| **Read easier.** | 1 | 1 | 1 | 1 | 1 | 1 by 2 | 100.0 |", ranked.text) - - def test_weighs_a_defects_maintain_goal_as_code_health_four_times_over_under_an_overall_of_7(self): - readme = "## Goals\n\n1. **Achieve:** A.\n2. **Maintain:** B.\n" - todo = self.todo.replace("| 2 | 0.1.0 | | | **Do A.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 |", "| 2 | 0.1.0 | | defect | **Restore B.** | 1 | 1 | 1 | 1 | 1 | 2 by 1 |") - for history, value in (("", "101.5"), (SCORED.format(overall="7.00"), "25.4")): - with self.subTest(history=history): - self.assertIn(f"| **Restore B.** | 1 | 1 | 1 | 1 | 1 | 2 by 1 | {value} |", rank_todo.rank(todo, readme, "", history).text) - - def test_refuses_a_plan_whose_project_opts_out_of_the_comprehension_check_yet_keeps_code_health(self): - opted_out = "## review opt-out: the architect and the comprehension check\n\nCosts rounds.\n" - self.assertEqual(rank_todo.rank(self.todo, self.readme, opted_out, ""), Failure("docs/decisions.md opts out of the comprehension check, so code health has no signal; void it in README.md's ## Goals with `**Void:** code health, since .`, as ~/.claude/CLAUDE.md → 'Shared goal' says")) - self.assertIsInstance(rank_todo.rank(self.todo, self.readme, opted_out.replace(" and the comprehension check", ""), ""), rank_todo.Ranked) - voided = "## Goals\n\n**Void:** code health, since nobody reads the probes.\n\n1. **Achieve:** A.\n" - self.assertIsInstance(rank_todo.rank(self.todo.replace("code health by 1", "1 by 2"), voided, opted_out, ""), rank_todo.Ranked) - - def test_ranks_a_project_that_voids_code_health_whatever_its_history_holds(self): - voided = "## Goals\n\n**Void:** code health, since it is a one-off script.\n\n1. **Achieve:** A.\n" - self.assertIsInstance(rank_todo.rank(self.todo.replace("code health by 1", "1 by 2"), voided, "", SCORED.format(overall="high")), rank_todo.Ranked) - - def test_refuses_a_void_of_anything_but_code_health(self): - self.assertEqual(self.scores("", "## Goals\n\n**Void:** speed, since nobody waits.\n\n1. **Achieve:** A.\n"), Failure("README.md's ## Goals voids `speed, since nobody waits.`; only code health may be voided, as `**Void:** code health, since .`")) - - def test_shows_the_spelling_of_a_void_of_code_health_that_misses_it(self): - for void in ("code health.", "Code health, since it is a one-off script.", "code health since it is a one-off script."): - with self.subTest(void=void): - self.assertEqual(self.scores("", f"## Goals\n\n**Void:** {void}\n\n1. **Achieve:** A.\n"), Failure(f"README.md's ## Goals voids code health as `{void}`; spell the void exactly `**Void:** code health, since .`")) - - def test_parses_code_health_in_a_moves_cell(self): - self.assertEqual(todo_table.parse_moves("1", "code health by 4, 1.1 by 2"), (("code health", 4), ("1.1", 2))) - self.assertIsInstance(todo_table.parse_moves("1", "code health by 11"), Failure) - self.assertIsInstance(todo_table.parse_moves("1", "health by 4"), Failure) - - def test_reads_the_history_beside_todo_md(self): - with tempfile.TemporaryDirectory() as temp: - todo = pathlib.Path(temp, "todo.md") - todo.write_text(self.todo) - pathlib.Path(temp, "README.md").write_text(self.readme) - 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()): - self.assertEqual(rank_todo.main([str(todo)]), 0) - self.assertIn("| code health by 1 | 25.4 |", todo.read_text()) - - -class Risk(unittest.TestCase): - """R is L + E + I - 2, which rank_todo.py writes, at least 7 when I is 5 and at least 5 when I is 4.""" - def ranked(self, todo): - return rank_todo.rank(todo, README, DECISIONS, "") - - def test_writes_r_from_l_e_and_i_over_a_stale_or_missing_r(self): - ranked = self.ranked(TODO).text - for levels, risk in (("| 1 | 1 | 1 |", 1), ("| 2 | 1 | 2 |", 3), ("| 1 | 2 | 1 |", 2)): - with self.subTest(levels=levels): - self.assertIn(f"{levels} {risk} |", ranked) - stale = TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 2 | 1 | 2 | 10 | 7 |") - self.assertEqual(self.ranked(stale).text, ranked) - without_r = TODO.replace("| I | R | S |", "| I | S |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|") - without_r = re.sub(r"(\*\* \| \d+ \| \d+ \| \d+) \| \d+ \|", r"\1 |", without_r) - self.assertEqual(self.ranked(without_r).text, ranked) - - def test_writes_r_into_a_blank_r_cell(self): - blank = TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 2 | 1 | 2 | | 7 |") - self.assertEqual(self.ranked(blank).text, self.ranked(TODO).text) - - def test_leaves_a_stale_r_to_ranking_so_a_reader_keeps_the_r_the_table_stored(self): - stale = TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 2 | 1 | 2 | 10 | 7 |") - self.assertEqual(next(item for item in todo_table.items(stale) if item.id == 3).scores["R"], 10) - self.assertNotEqual(self.ranked(stale).text, stale) - - def test_holds_r_at_7_when_i_is_5_and_at_5_when_i_is_4(self): - cases = {"| 1 | 1 | 5 |": 7, "| 1 | 1 | 4 |": 5, "| 2 | 2 | 4 |": 6, "| 4 | 3 | 5 |": 10, "| 3 | 3 | 3 |": 7} - for levels, risk in cases.items(): - with self.subTest(levels=levels): - ranked = self.ranked(TODO.replace("| 1 | 2 | 1 | 2 | 4 |", f"{levels} 1 | 4 |")) - self.assertIn(f"**Tighten the tests.** {levels} {risk} | 4 |", ranked.text) - - def test_routes_a_worker_on_l_and_its_reviewers_on_e_plus_i(self): - item = next(item for item in todo_table.items(TODO) if item.id == 4) - self.assertEqual((item.likelihood, item.escape_and_impact), (3, 8)) - - def test_names_the_one_level_column_a_table_lacks(self): - without_i = TODO.replace("| E | I | R |", "| E | R |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|") - without_i = re.sub(r"(\*\* \| \d+ \| \d+) \| \d+ \|", r"\1 |", without_i) - self.assertEqual(self.ranked(without_i), Failure("todo.md's items table has no I column; add it, scoring each item's L, E and I as rank_todo.py --help shows")) - - def test_asks_a_table_from_before_l_e_and_i_for_them_yet_reads_its_rows(self): - before = TODO.replace("| L | E | I | R | S | Moves |", "| R | S | C | Moves |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|") - before = re.sub(r"(\*\* \|) \d+ \| \d+ \| \d+ \| (\d+) \| (\d+) \|", r"\1 \2 | \3 | 3 |", before) - self.assertEqual(self.ranked(before), Failure("todo.md's items table has no L, E and I columns; add them, scoring each item's L, E and I as rank_todo.py --help shows, and drop C")) - items = todo_table.items(before) - self.assertEqual([(item.scores, item.likelihood, item.escape_and_impact) for item in items][1], ({"R": 2, "S": 4}, 0, 0)) - - -class OldShape(unittest.TestCase): - """A table with A, G and Goals, from before the Moves column, ranks by the formula and goal weights it states until its project reshapes it.""" - def ranked(self, todo=OLD_SHAPE, readme=README): - return rank_todo.rank(todo, readme, DECISIONS, "") - - def test_scores_by_the_stated_weights_and_says_to_reshape(self): - ranked = self.ranked() - self.assertIn("""| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 9 | 2 | 3 | 1 | 1 | 2.1 | -6.8 | -| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 3 | 8 | 3 | 6 | 8 | 2.1, 1 | 23.0 | -| 2 | 0.1.0 | | | **Tighten the tests.** | 2 | 4 | 3 | 5 | 5 | 2.1 | 10.3 | -| 5 | 0.1.0 | | decision | **Move the writes out.** | 5 | 5 | 3 | 4 | 5 | 2.1 | 5.1 | -| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 3 | 9 | 9 | 1 | 34.8 | -""", ranked.text) - self.assertEqual(ranked.notes, [rank_todo.RESHAPE]) - self.assertEqual(self.ranked(ranked.text), ranked) - unmarked = "# P\n\n## Goals\n\n1. Fast.\n2. Correct.\n 1. Tested.\n" - self.assertEqual(self.ranked(readme=unmarked), ranked) - - def test_prints_the_positional_weights_when_they_stop_listing_the_readmes_goals(self): - failure = self.ranked(readme=README.replace(" 1. **Achieve:** Tested.", " 1. **Achieve:** Tested.\n3. Small.")) - self.assertIn("| 1 | 1.00 |\n| 2 | 0.75 |\n| 2.1 | 0.50 |\n| 3 | 0.25 |", failure.reason) - - def test_refuses_an_item_citing_a_goal_the_weights_do_not_list(self): - self.assertEqual(self.ranked(OLD_SHAPE.replace("| 2.1, 1 | 0 |", "| 2.1, 9 | 0 |")), Failure("item 3 cites goal 9, which the goal weights do not list")) - - def test_refuses_a_formula_over_v(self): - self.assertEqual(self.ranked(OLD_SHAPE.replace("-R - S/4 + 2*A + 2*G*W", "V")), Failure("the formula 'V' may hold only numbers, A, G, R, S, W, + - * / ** and parentheses")) - - def test_ranks_a_table_from_before_c_joined_and_says_to_reshape_it(self): - legacy = OLD_SHAPE.split("## Items")[0] + "## Items\n\n| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|\n| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 |\n" - self.assertEqual(rank_todo.rank(legacy, README, "", "").notes, [rank_todo.RESHAPE]) - - def test_refuses_a_table_with_both_moves_and_goals(self): - both = OLD_SHAPE.replace("| Goals | Score |\n|---|", "| Goals | Moves | Score |\n|---|---|").replace(" | 0 |\n", " | 1 by 1 | 0 |\n") - self.assertEqual(self.ranked(both), Failure("todo.md's items table has no L, E and I columns; add them, scoring each item's L, E and I as rank_todo.py --help shows, and drop C, A, G and Goals")) - one = TODO.replace("| Moves | Score |\n|---|", "| Moves | G | Score |\n|---|---|").replace(" | 0 |\n", " | 1 | 0 |\n") - self.assertEqual(self.ranked(one), Failure("todo.md's items table has G, a column of an older shape; drop it, as rank_todo.py --help shows")) - - def test_names_the_goals_column_a_table_misspells_by_its_shape(self): - misspelt = TODO.replace("| S | Moves |", "| S | Move |") - self.assertEqual(rank_todo.rank(misspelt, README, DECISIONS, ""), Failure("todo.md's items table has no Moves column; rank_todo.py --help shows a valid one")) - self.assertEqual(todo_table.items(misspelt), Failure("todo.md's items table has no Moves column; rank_todo.py --help shows a valid one")) - self.assertEqual(self.ranked(OLD_SHAPE.replace("| G | Goals |", "| G | Goal |")), Failure("todo.md's items table has no Goals column; rank_todo.py --help shows a valid one")) - - -class Blockers(unittest.TestCase): - def ranked(self, todo): - return rank_todo.rank(todo, README, DECISIONS, "") - - def test_ranks_each_blocker_just_above_the_first_item_it_blocks(self): - ranked = self.ranked(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5, 2 |")) - self.assertIn("""| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 12.3 | -| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 3.1 | -| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 1.5 | -| 3 | 0.1.0 | 2, 5 | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 | 5.5 | -| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 228.4 | -""", ranked.text) - self.assertEqual(self.ranked(ranked.text), ranked) - - def test_ranks_an_items_blockers_in_score_order(self): - rows = [line.split(" | ")[0] for line in self.ranked(TODO.replace("| 4 | 0.1.0 | |", "| 4 | 0.1.0 | 2, 3 |")).text.splitlines() if re.match(r"\| \d \| 0\.\d\.0 \|", line)] - self.assertEqual(rows, ["| 3", "| 2", "| 4", "| 5", "| 1"]) - - def test_ranks_a_blocker_above_its_blockers_blocker_and_takes_one_in_an_earlier_release_as_it_is(self): - chained = TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 5 | 0.1.0 | |", "| 5 | 0.1.0 | 2 |").replace("| 1 | 0.2.0 | |", "| 1 | 0.2.0 | 3 |") - rows = [line.split(" | ")[0] for line in self.ranked(chained).text.splitlines() if re.match(r"\| \d \| 0\.\d\.0 \|", line)] - self.assertEqual(rows, ["| 4", "| 2", "| 5", "| 3", "| 1"]) - - def test_bundles_with_the_next_item_each_item_of_its_release_that_no_question_or_item_outside_the_chunk_blocks(self): - # Item 2 is the next item. Item 5 is a question, 3 waits on 5, and 4 waits on 3; item 1 is in a later release. - waits = todo_table.items(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 4 | 0.1.0 | | security |", "| 4 | 0.1.0 | 3 | security |").replace("| 5 | 0.1.0 | | decision |", "| 5 | 0.1.0 | | question |")) - self.assertEqual(todo_table.bundle_candidates(waits, todo_table.next_item(waits)), []) - answered = todo_table.items(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 4 | 0.1.0 | | security |", "| 4 | 0.1.0 | 3 | security |")) - self.assertEqual([item.id for item in todo_table.bundle_candidates(answered, todo_table.next_item(answered))], [3, 5]) - - def test_ships_an_item_above_r_5_alone(self): - # Item 4 has R 9: it joins no chunk, and none joins it. Item 5, at R 5, still joins. - found = todo_table.items(TODO) - self.assertNotIn(4, [item.id for item in todo_table.bundle_candidates(found, todo_table.next_item(found))]) - self.assertIn(5, [item.id for item in todo_table.bundle_candidates(found, todo_table.next_item(found))]) - self.assertEqual(todo_table.bundle_candidates(found, next(item for item in found if item.id == 4)), []) - # At R 6, item 3 ships alone too. - riskier = todo_table.items(TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 3 | 2 | 3 | 6 | 7 |")) - self.assertNotIn(3, [item.id for item in todo_table.bundle_candidates(riskier, todo_table.next_item(riskier))]) - # Before rank_todo.py fills its R cell, item 3's L 3, E 2 and I 3 still make R 6. - unranked = todo_table.items(TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 3 | 2 | 3 | | 7 |")) - self.assertNotIn(3, [item.id for item in todo_table.bundle_candidates(unranked, todo_table.next_item(unranked))]) - - def test_drops_a_blocker_the_table_no_longer_holds_as_finished(self): - finished = TODO.replace("| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 0 |\n", "").replace("| 2 | 0.1.0 | |", "| 2 | 0.1.0 | 4 |") - ranked = self.ranked(finished) - self.assertIn("| 2 | 0.1.0 | | | **Tighten the tests.**", ranked.text) - self.assertEqual(ranked.notes, ["item 2: dropped 4 from its Blocked by; the table no longer holds it"]) - self.assertEqual(self.ranked(ranked.text).notes, []) - - def test_refuses_a_blocker_in_a_later_release_a_loop_and_an_id_past_next_id(self): - cases = { - "| 3 | 0.1.0 | 1 |": "item 3, in release 0.1.0, is blocked by item 1, in later release 0.2.0; move item 1 to release 0.1.0 or earlier, or item 3 to release 0.2.0 or later", - "| 3 | 0.1.0 | 3 |": "item 3 is blocked by itself; drop 3 from its Blocked by", - "| 3 | 0.1.0 | 9 |": "item 3 is blocked by item 9, which is not under Next ID 6; name an item the table holds or held", - "| 3 | 0.1.0 | 6 |": "item 3 is blocked by item 6, which is not under Next ID 6; name an item the table holds or held", - } - for cell, reason in cases.items(): - with self.subTest(cell=cell): - self.assertEqual(self.ranked(TODO.replace("| 3 | 0.1.0 | |", cell)), Failure(reason)) - looped = TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 2 |").replace("| 2 | 0.1.0 | |", "| 2 | 0.1.0 | 5 |").replace("| 5 | 0.1.0 | |", "| 5 | 0.1.0 | 3 |") - self.assertEqual(self.ranked(looped), Failure("items 2, 3 and 5 block each other in a loop; drop one of the blockers")) - self.assertEqual(self.ranked(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 2 and 5 |")), Failure("item 3's Blocked by '2 and 5' is not empty or IDs separated by \", \"")) - - def test_adds_the_column_to_a_table_without_it(self): - without = TODO.replace("| Blocked by ", "").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|") - without = re.sub(r"\| (\d) \| (0\.[12]\.0) \| \| ", r"| \1 | \2 | ", without) - self.assertEqual(self.ranked(without), self.ranked(TODO)) - unscored = TODO.replace(" | Score |", " |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|").replace(" | 0 |\n", " |\n") - self.assertEqual(self.ranked(unscored), self.ranked(TODO)) - - def test_refuses_a_column_it_does_not_know_rather_than_drop_it_and_one_an_older_shape_held(self): - extra = TODO.replace("| Moves | Score |\n|---|", "| Moves | Score | Later |\n|---|---|").replace(" | 0 |\n", " | 0 | x |\n") - self.assertEqual(self.ranked(extra), Failure("todo.md's items table has the column Later, which this rank_todo.py does not know; the columns it knows are ID, Release, Blocked by, Exempt, Item, L, E, I, R, S, Moves, Score. Rename it, or move this machine to the release that added it")) - self.assertEqual([item.id for item in todo_table.items(extra)], [1, 2, 3, 4, 5]) - with_c = TODO.replace("| S | Moves |", "| S | C | Moves |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|---|---|") - with_c = re.sub(r"(\*\* \| \d+ \| \d+ \| \d+ \| \d+ \| \d+) \|", r"\1 | 3 |", with_c) - self.assertEqual(self.ranked(with_c), Failure("todo.md's items table has C, a column of an older shape; drop it, as rank_todo.py --help shows")) - - def test_refuses_text_under_items_beside_the_table(self): - last = TODO.split("\n## Details")[0] + "\n" - self.assertIsInstance(self.ranked(last), rank_todo.Ranked) - beside = Failure("## Items holds text beside its table; an order goes in the scores or the Blocked by column, and a note in the item's detail") - for ordered in (TODO.replace("## Items\n\n", "## Items\n\nRelease 0.1.0 takes item 5 first.\n\n"), TODO.replace("## Items\n\n", "## Items\nTake item 5 first.\n\n"), TODO.replace("| 2.1 by 1 | 0 |\n\n## Details", "| 2.1 by 1 | 0 |\n\nTake item 5 first.\n\n## Details"), last + "\nTake item 5 first.\n"): - with self.subTest(ordered=ordered[-60:]): - self.assertEqual(self.ranked(ordered), beside) - - def test_refuses_an_items_table_outside_items_a_second_one_and_a_repeated_column(self): - self.assertEqual(self.ranked(TODO.replace("## Items\n", "## Plan\n")).reason, "todo.md is not in the scored-table format; rank_todo.py --help shows a valid one") - outside = TODO.replace("## Items\n\n", "## Items\n\n## Rows\n\n") - self.assertEqual(self.ranked(outside).reason, "the items table sits under ## Rows, not ## Items; move it under ## Items") - table = TODO[TODO.index("| ID | Release |"):TODO.index("\n\n## Details")] + "\n" - above = table + "\n" + TODO.replace(table, "") - self.assertEqual(self.ranked(above).reason, "the items table sits under no ## heading; move it under ## Items") - header = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n" - self.assertEqual(todo_table.items(TODO + "\n" + header.replace("| Score |", "| Later |")), Failure("todo.md holds 2 tables whose header opens | ID | Release |; keep one items table")) - repeated = TODO.replace("| Moves | Score |\n|---|", "| Moves | Score | Exempt |\n|---|---|").replace(" | 0 |\n", " | 0 | x |\n") - self.assertEqual(todo_table.items(repeated), Failure("todo.md's items table names the column Exempt twice; keep one")) - - def test_reads_an_empty_table_and_fails_on_a_header_with_no_divider(self): - header = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |" - self.assertEqual(todo_table.items(f"## Items\n\n{header}\n|---|---|---|---|---|---|---|---|---|---|---|---|\n\n## Details\n"), []) - self.assertEqual(todo_table.items(f"## Items\n\n{header}"), Failure(f"the table under {header} has no |---| divider line")) - - -class Renamed(unittest.TestCase): - def test_reads_the_releases_the_renamed_section_names(self): - self.assertEqual(todo_table.renames("## Items\n\n## Details\n"), set()) - self.assertEqual(todo_table.renames("## Renamed\n\n- 0.2.1 renamed to 0.3.0\n- 0.3.0 renamed to 0.4.0\n\n## Details\n"), {(0, 2, 1), (0, 3, 0)}) - self.assertEqual(todo_table.renames("## Renamed\n\n- 0.2.1 renamed to 0.3.0 \n"), {(0, 2, 1)}) - for bad in ("soon", "- 0.2.1 is now 0.3.0", "- 0.2 renamed to 0.3.0", "- 0.2.1 renamed to 0.3.0 later", "- 0.2.1 renamed to 0.2.1"): - with self.subTest(bad): - self.assertIsInstance(todo_table.renames(f"## Renamed\n\n{bad}\n"), Failure) - - def test_fails_on_a_renamed_section_that_does_not_parse(self): - failed = rank_todo.rank(TODO + "\n## Renamed\n\nsoon\n", README, DECISIONS, "") - self.assertIsInstance(failed, Failure) - self.assertIn("## Renamed", failed.reason) - - def test_ranks_a_plan_with_a_valid_renamed_section(self): - self.assertIsInstance(rank_todo.rank(TODO + "\n## Renamed\n\n- 0.3.0 renamed to 0.4.0\n", README, DECISIONS, ""), rank_todo.Ranked) - - def test_fails_on_an_item_filed_under_a_release_the_plan_marks_renamed(self): - live = rank_todo.rank(TODO + "\n## Renamed\n\n- 0.2.0 renamed to 0.3.0\n", README, DECISIONS, "") - self.assertIsInstance(live, Failure) - self.assertIn("marks release 0.2.0 renamed but files item 1 under it", live.reason) - +from release_plan import ranking class Main(unittest.TestCase): @@ -613,20 +52,18 @@ class Main(unittest.TestCase): pathlib.Path(temp, "README.md").write_text(README) pathlib.Path(temp, "docs").mkdir() pathlib.Path(temp, "docs", "decisions.md").write_text(DECISIONS) - self.assertEqual(self.run_main(str(todo)), (0, f"{todo}: {rank_todo.RESHAPE}\n")) + self.assertEqual(self.run_main(str(todo)), (0, f"{todo}: {ranking.RESHAPE}\n")) self.assertEqual(self.run_main("--check", str(todo)), (0, "")) def test_shows_a_valid_file_in_help_and_names_arguments_it_cannot_read(self): self.assertEqual(self.run_main("--help")[0], 0) skeleton = "\n".join(line[4:] for line in rank_todo.__doc__.split("\n") if line.startswith(" ")) - ranked = rank_todo.rank(skeleton, "## Goals\n\n1. **Achieve:** Work.\n", "", "") - self.assertIsInstance(ranked, rank_todo.Ranked) + ranked = ranking.rank(skeleton, "## Goals\n\n1. **Achieve:** Work.\n", "", "") + self.assertIsInstance(ranked, ranking.Ranked) self.assertEqual((ranked.under_bar, ranked.notes), ([], [])) self.assertEqual(self.run_main("--fix"), (1, "rank_todo.py: cannot read the arguments --fix; usage: rank_todo.py [--check] [todo.md]\n")) - -class ThisRepo(unittest.TestCase): - def test_todo_md_is_ranked_with_nothing_under_the_bar(self): - text = (ROOT / "todo.md").read_text(encoding="utf-8") - ranked = rank_todo.rank(text, *((ROOT / name).read_text(encoding="utf-8") for name in ("README.md", "docs/decisions.md", "docs/comprehension-history.md"))) - self.assertEqual(ranked, rank_todo.Ranked(text, [], [])) + def test_states_the_goal_weights_the_ranking_computes(self): + for figure in (ranking.GOAL_STEP, 0.212, 0.188, 0.082, 0.053): + self.assertIn(str(figure), rank_todo.__doc__) + self.assertIn(f"While it is under {ranking.FLOOR}, or the history holds no scoring run, code health weighs {ranking.UNDER_FLOOR} times its weight by position, and the other goals keep theirs.", " ".join(rank_todo.__doc__.split())) diff --git a/bin/transcript_archive/location.py b/bin/transcript_archive/location.py index 170fcceb..508a2cd1 100644 --- a/bin/transcript_archive/location.py +++ b/bin/transcript_archive/location.py @@ -3,7 +3,7 @@ import pathlib import typing from claude_code.transcript import first_timestamped_line -from project_key import project_key +from transcript_archive.project_key import project_key # What an outcomes file's name ends with, in place of its transcript copy's .jsonl. FILE_SUFFIX = ".outcomes.md" diff --git a/bin/transcript_archive/outcomes.py b/bin/transcript_archive/outcomes.py index d54e33d2..86e6ff11 100644 --- a/bin/transcript_archive/outcomes.py +++ b/bin/transcript_archive/outcomes.py @@ -1,7 +1,7 @@ import re -from markdown_text import quoted -from utc_stamp import STAMPED +from records.markdown_text import quoted +from records.utc_stamp import STAMPED from model_routing.route import WorkerLine TASK = "Task: " diff --git a/bin/project_key.py b/bin/transcript_archive/project_key.py similarity index 100% rename from bin/project_key.py rename to bin/transcript_archive/project_key.py diff --git a/bin/transcript_archive/test_transcript_archive.py b/bin/transcript_archive/test_transcript_archive.py index 24b63f6f..ba97e967 100644 --- a/bin/transcript_archive/test_transcript_archive.py +++ b/bin/transcript_archive/test_transcript_archive.py @@ -8,11 +8,11 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from project_key import checkout_of, project_key +from transcript_archive.project_key import checkout_of, project_key from failure import Failure from transcript_archive import outcomes, read, write from transcript_archive.location import project_archive -from utc_stamp import utc +from records.utc_stamp import utc NOW = 1790000000 diff --git a/bin/transcript_archive/write.py b/bin/transcript_archive/write.py index 8d382294..cfa42183 100644 --- a/bin/transcript_archive/write.py +++ b/bin/transcript_archive/write.py @@ -5,10 +5,10 @@ import typing from transcript_archive.location import chunk_folder, outcomes_of from failure import Failure -from file_writes import make_private, replace_file +from records.file_writes import make_private, replace_file from claude_code.session import session_files from transcript_archive.outcomes import TASK -from utc_stamp import utc +from records.utc_stamp import utc def archive(project_archive: pathlib.Path, path: str, task: str, outcome: str, at: float, note: typing.Callable[[str], None] = lambda text: None) -> Failure | None: diff --git a/docs/decisions.md b/docs/decisions.md index a9b611ad..fe9050a0 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -22,7 +22,7 @@ Valid while the archive's file names, the Vocabulary and the panel keep these wo 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/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/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. ## comprehension floor: every dimension and the overall at 7.0 or above is the target, and blocks no merge or release @@ -34,13 +34,13 @@ The cap is 5, `bin/todo_table.py`'s `BUNDLE_MAX_R`, from the same chunks: by the ## deploy: `deploy-release --cut` cuts a release through a pull request merged fast-forward only, then tags the merged commit and moves `~/.claude` to it; the human runs it -2026-11-08, lilleman, todo item 271. Serves goal 1.5 and goal 2. Nobody can push to `main` on the remote, and it merges only by fast-forward, so a cut that commits on `main` and pushes no longer works. The tool cuts only the release `chunk-preflight` would call ready to cut, through `bin/release_standing.py`, so the two never disagree on which release is next or whether it is ready; the version is that release's, never the tool's choice. It builds the cut commit in a worktree of its own, so the clone's checkout stays as it is. It finds the merged commit on `main` by its title, `Cut release `, since GitHub's nearest merge, a rebase merge, may give the commit a new hash. It takes only a pull request from origin's own branch whose head is the commit that branch points at, and has the forge merge it only while its head is still that commit, so a fork's pull request from a branch of the same name, or a push after the checks passed, is never merged and deployed. Each step first checks whether an earlier run did it, so a rerun continues. Releases stay the human's, so the human runs it, and the forge credentials stay theirs. Valid while `main` takes changes only through a pull request. +2026-11-08, lilleman, todo item 271. Serves goal 1.5 and goal 2. Nobody can push to `main` on the remote, and it merges only by fast-forward, so a cut that commits on `main` and pushes no longer works. The tool cuts only the release `chunk-preflight` would call ready to cut, through `bin/release_plan/release_standing.py`, so the two never disagree on which release is next or whether it is ready; the version is that release's, never the tool's choice. It builds the cut commit in a worktree of its own, so the clone's checkout stays as it is. It finds the merged commit on `main` by its title, `Cut release `, since GitHub's nearest merge, a rebase merge, may give the commit a new hash. It takes only a pull request from origin's own branch whose head is the commit that branch points at, and has the forge merge it only while its head is still that commit, so a fork's pull request from a branch of the same name, or a push after the checks passed, is never merged and deployed. Each step first checks whether an earlier run did it, so a rerun continues. Releases stay the human's, so the human runs it, and the forge credentials stay theirs. Valid while `main` takes changes only through a pull request. ## larv-review: within a chunk lifting a project towards the comprehension floor, work on the project's lowest-scoring dimension comes first, and the floor doesn't block anything 2026-09-20, lilleman. Serves goal 1. Across six projects scored with the four seats, Locality or Self-sufficiency was the lowest dimension at every seat and Navigation at none, so a layout fix would not lift a project under the floor. Valid while the scoring run keeps those four seats. -2026-10-15, lilleman, set by PR #283 on 2026-10-16: an item that lifts the lowest dimension moves each goal it cites by 9, since the lowest dimension caps the overall and lifting it is worth the most to the floor. Within a chunk its work comes first; in the plan, lilleman answering that PR's review, such items compete with the others like any item and don't rank first. PR #257's scoring run found Shape lowest, at 6.25, and two items were to lift it: `todo.md` item 124, and the one PR #367 shipped, which gave "record", "outcome" and "place" one meaning each in `bin/`. Release 0.3.0's scoring runs found Locality lowest, at 5.75 and 5.88, so the 9 moved from those items to the ones lifting Locality. +2026-10-15, lilleman, set by PR #283 on 2026-10-16: an item that lifts the lowest dimension moves each goal it cites by 9, since the lowest dimension caps the overall and lifting it is worth the most to the floor. Within a chunk its work comes first; in the plan, lilleman answering that PR's review, such items compete with the others like any item and don't rank first. PR #257's scoring run found Shape lowest, at 6.25, and two items were to lift it: one, shipped by PR #367, gave "record", "outcome" and "place" one meaning each in `bin/`; the other, shipped by PR #432, grouped `bin/`'s root modules into packages named by purpose. Release 0.3.0's scoring runs found Locality lowest, at 5.75 and 5.88, so the 9 moved from those items to the ones lifting Locality. ## loop-claude: a `claude` that cannot start is a failed worker run, retried @@ -248,7 +248,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 blocks no 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 changed nothing (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/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 changed nothing (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-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. @@ -298,7 +298,7 @@ On 2026-10-16 lilleman routed the reviewers on their item's E + I as well, on ei Valid until the trial on real chunks shows whether a worker below the project's rung holds quality. -2026-10-29, lilleman. Serves goals 1.4 and 1.5. A branch that changes only Markdown no agent follows reviews on the project's rung, whatever its items' E + I. E + I scores an item before its chunk starts, by the change the item asks for, so one project's item, filed to build a control on a CI runner, kept its E + I of 7 when the chunk found no control the repo could build and shipped a README paragraph: five reviewers read prose on Opus 5.5 at xhigh. rule-hook's `reviewer-rung` reads the branch's files, committed or not, against the default branch as last fetched. Markdown an agent follows counts as config: `CLAUDE.md`, `AGENTS.md`, `workflow-bench/*-prompt.md` and files under `agents/`, `principles/`, `rules/` or `skills/`. On 2026-11-04 lilleman added the workflow bench's prompts, which an agent follows like a skill. `bin/review_passes.py` holds the lists, and the worker's prompt renders them. Valid while a README or docs defect costs a reader no more than review on the project's rung lets through. +2026-10-29, lilleman. Serves goals 1.4 and 1.5. A branch that changes only Markdown no agent follows reviews on the project's rung, whatever its items' E + I. E + I scores an item before its chunk starts, by the change the item asks for, so one project's item, filed to build a control on a CI runner, kept its E + I of 7 when the chunk found no control the repo could build and shipped a README paragraph: five reviewers read prose on Opus 5.5 at xhigh. rule-hook's `reviewer-rung` reads the branch's files, committed or not, against the default branch as last fetched. Markdown an agent follows counts as config: `CLAUDE.md`, `AGENTS.md`, `workflow-bench/*-prompt.md` and files under `agents/`, `principles/`, `rules/` or `skills/`. On 2026-11-04 lilleman added the workflow bench's prompts, which an agent follows like a skill. `bin/review_rules/review_passes.py` holds the lists, and the worker's prompt renders them. Valid while a README or docs defect costs a reader no more than review on the project's rung lets through. ## routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds, and only where the E + I steps no review up and the worker runs no higher than the project's rung, then even below the worker's; no pass has such a rung @@ -472,7 +472,7 @@ Valid while the worker writes the tests that larv-review's reviewers hold to the 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/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/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. ## 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 diff --git a/docs/reading-cost.md b/docs/reading-cost.md index bcb74be3..c9948d76 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -1119,3 +1119,20 @@ Read most (opens and searches): - `bin/branch_chunks/read.py` 1 ## Reading cost reset, 2026-11-08T19:18:18Z + +## Reading cost, chunk f28f7a6f2eab, finished 2026-11-08T19:24:37Z + +71167 new input tokens before the first commit. + +Read most (opens and searches): + +- `todo.md` 10 +- `bin/loop_claude/loop/main.py` 9 +- `bin/loop_claude/loop/usage.py` 7 +- `AGENTS.md` 6 +- `README.md` 6 +- `bin/loop_claude/test_loop_claude.py` 3 +- `docs/decisions.md` 3 +- `docs/reading-cost.md` 2 +- `CHANGELOG.md` 1 +- `bin/loop-claude` 1 diff --git a/todo.md b/todo.md index 7c356322..bbf6b434 100644 --- a/todo.md +++ b/todo.md @@ -6,15 +6,13 @@ `Bar = 0.1` -`Next ID = 276` +`Next ID = 277` ## Items | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| | 1 | 0.7.0 | | question | **Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 1 | 2 | 1 | 2 | 1 | | 0.0 | -| 221 | 0.7.0 | | | **Parse each transcript entry once, where `bin/claude_code/transcript.py` reads it, into a typed value naming its kind, so no consumer works out an entry's kind from a raw `dict`.** | 3 | 1 | 3 | 5 | 5 | code health by 4 | 4.5 | -| 124 | 0.7.0 | | decision | **Group the shared modules at `bin/`'s root into packages named by purpose, so the root holds only launchers and stand-alone tools.** | 4 | 1 | 3 | 6 | 6 | code health by 5, 1.4 by 3 | 4.2 | | 262 | 0.7.0 | | | **Let a worker take its own recommendation on a choice no rule reserves for the human, record it in the item or a decision, and interrupt only for a reserved choice or an ask it has no recommendation for.** | 3 | 2 | 3 | 6 | 4 | 1.2 by 7, 1.5 by 5 | 4.0 | | 230 | 0.7.0 | | | **Have larv-review file one ambitious refactor item, aimed at the lowest-scoring dimension, whenever a scoring run leaves any score under 7.0, so such a project always holds a plan item meant to reach 7.0.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 7, 1.2 by 4 | 3.8 | | 215 | 0.7.0 | | | **Decode a reload's handed JSON with a decoder for `LoopRun` and its `Route`, in place of `decoded_as`'s generic one with its two sentinels and `Route.fits` hook.** | 2 | 1 | 3 | 4 | 3 | code health by 2 | 3.6 | @@ -23,16 +21,18 @@ | 113 | 0.7.0 | | | **Compute an item's S from the code it names, where it names any, and show it beside the finished items `score-outcomes` lists.** | 3 | 2 | 2 | 5 | 4 | 1.1 by 5, 1.4 by 5 | 3.4 | | 263 | 0.7.0 | | | **Have the judge reject an interrupt that re-asks what the human answered earlier in the chunk, unless the ask quotes what that answer left open.** | 2 | 2 | 3 | 5 | 3 | 1.2 by 6, 1.5 by 2 | 3.2 | | 162 | 0.7.0 | | owner | **Script each step that 0.2.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 4, 1.5 by 4 | 3.1 | +| 221 | 0.7.0 | | | **Parse each transcript entry once, where `bin/claude_code/transcript.py` reads it, into a typed value naming its kind, so no consumer works out an entry's kind from a raw `dict`.** | 4 | 1 | 3 | 6 | 6 | code health by 4 | 3.0 | | 105 | 0.7.0 | | decision | **Compare review rounds per pass and reading cost for the five chunks before and after the `worker:` decision moved the principles out of the worker's context, and file an item if either rose.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 6 | 2.7 | | 175 | 0.7.0 | | | **Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, and file an item where the preflight did not pay off.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 2.6 | | 112 | 0.7.0 | | | **Count an item as shipped only where its chunk built it, so an item a chunk dropped from the plan gets no outcome.** | 3 | 2 | 2 | 5 | 3 | 1.1 by 6 | 2.5 | +| 276 | 0.7.0 | | | **Let a worker fix on its own rung a `standards/quality.md` finding whose fix changes only prose, so escalation trigger 4 calls for a higher rung only where code or config must change.** | 2 | 2 | 3 | 5 | 3 | 1.2 by 4, 1.4 by 2 | 2.4 | | 116 | 0.7.0 | | | **Report L by the share of chunks with a 🔴, once 10 chunks that each shipped one item record finding counts and most record no 🔴.** | 1 | 1 | 2 | 2 | 2 | 1.1 by 5 | 2.3 | | 101 | 0.7.0 | | principle | **Have `larv_review/history_commands.py`'s `read_seats` take the time, the commit check and the history as inputs, so it parses and decides without effects.** | 2 | 1 | 2 | 3 | 3 | 1.1 by 5 | 2.1 | | 12 | 0.7.0 | | | **Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.** | 3 | 2 | 1 | 4 | 4 | 1.1 by 6 | 2.1 | | 81 | 0.7.0 | | principle | **Have `workflow-bench/bench.py` return each run's failure as a value, so one failed clone does not hide the later runs' results.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 4 | 1.9 | | 173 | 0.7.0 | | | **Have rule-hook's `todo-rank-check` run a worktree's own `bin/rank_todo.py` when the worktree is of this repo, so a branch that changes `todo.md`'s shape commits without an override.** | 2 | 1 | 3 | 4 | 2 | 1.1 by 2, 1.4 by 2 | 1.8 | | 272 | 0.7.0 | | owner | **Make `deploy-release --cut` say when each step finishes, end on one line saying the release is cut and `~/.claude` is on it, and delete the merged release branch.** | 1 | 1 | 1 | 1 | 2 | 1.5 by 3 | 1.3 | -| 274 | 0.7.0 | | | **Let an item name a maintain goal it raises confidence in, such as a test leg that guards it, and weigh that move against the achieve goals in `bin/rank_todo.py`.** | 2 | 2 | 3 | 5 | 4 | 1 by 3 | 1.1 | +| 274 | 0.7.0 | | | **Let an item name a maintain goal it raises confidence in, such as a test leg that guards it, and weigh that move against the achieve goals in `bin/release_plan/ranking.py`.** | 2 | 2 | 3 | 5 | 4 | 1 by 3 | 1.1 | | 275 | 0.7.0 | | | **Make the `Main` tests of `judge-replay` and `review-replay` fail when the replays ignore the project's model, its lowest worker rung or the round's checkout.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 2 | 0.9 | | 77 | 0.8.0 | | | **Teach `bin/metric-bench` Go and TypeScript, rerun it once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel.** | 4 | 2 | 1 | 5 | 6 | 1.1 by 7, 1.4 by 7 | 2.4 | | 273 | 0.8.0 | | decision | **Re-tune the E + I steps of `REVIEW_STEPS` for 6 to 8 once 10 finished chunks have scored an E + I of 6 or more, from how well E + I orders their review rounds and 🔴 findings.** | 1 | 2 | 2 | 3 | 2 | 1.1 by 2, 1.4 by 3 | 2.3 | @@ -78,14 +78,6 @@ It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost The README line covers the bench's transcripts in `workflow-bench/logs/` too (goal 3). -### 221. Parse each transcript entry once, where `bin/claude_code/transcript.py` reads it, into a typed value naming its kind, so no consumer works out an entry's kind from a raw `dict`. - -"Validate data and build DTOs as early as possible", in `principles/technical-principles.md`, raised 🟢 by the principles audit of item 210's PR. `read_transcript` (`bin/claude_code/transcript.py:16`) returns raw `dict`s, so each consumer, such as `render` beside it and `since_step` in `bin/loop_claude/escalation_mark.py`, calls the helpers in `bin/claude_code/entries.py` (`human_text`, `loop_text`, `assistant_parts`, `tool_call`) to work out an entry's kind again. Parse each line once into types such as a human turn, a loop-claude prompt and an assistant turn, and have every consumer of `claude_code.entries` under `bin/` take those types. The change touches the escalation mark, which the comprehension seats found hard at `bin/loop_claude/cycle/judge.py:153` `escalation_mark` before item 210 moved it: make `since_step` in `bin/loop_claude/escalation_mark.py`, and `Grounds.since_step` and `judge_prompt` in `bin/loop_claude/cycle/judge.py`, easier to read. - -### 124. Group the shared modules at `bin/`'s root into packages named by purpose, so the root holds only launchers and stand-alone tools. - -Shape scored 6.25 in PR #257's run. `bin/` held about 30 entries then: 6 launchers, 6 tool packages, 3 shared packages and 15 root modules. Two root modules are tools (`rank_todo.py`, `statusline.py`) and 13 are shared libraries, and nothing in the layout tells them apart; only README's import-root paragraph maps them. Candidate packages: git running and parsing, the todo table with `rank_todo.py`'s formula language and goal weighing, and the comprehension history with round titles. `rank_todo.py` keeps its path, which every project's rules name. The `.gitignore` allowlist and README follow the move. Release 0.3.0's inherited architect named `bin/git_repo.py:8` `git` in the rerun (PR #324 rerun at c713910): "bin/'s root holds about 43 entries, with 13 loose modules … not grouped by purpose". In the first run (PR #324 at c713910) it named `bin/rank_todo.py:196` `read_all`: "a 658-line library as well as a tool, imported by rule_hook and larv_review". Make `git` and `read_all` easier to read. - ### 262. Let a worker take its own recommendation on a choice no rule reserves for the human, record it in the item or a decision, and interrupt only for a reserved choice or an ask it has no recommendation for. On 2026-11-08 the human answered yes, with a reserved list: a worker takes its own recommendation on a choice no rule reserves for the human, records it in the item or a decision, and interrupts only for a reserved choice or an ask it has no recommendation for. The reserved choices are a release, a change to the ladder or its steps, and a goal, listed in one place. @@ -132,6 +124,10 @@ lilleman asked, on 2026-10-16, for a standing audit each release, so the loop ke The chunk that ships this item files a copy of it in the release after the one it audits, rewording "0.2.0" to the release that copy audits, and marks the copy `owner`, so the audit recurs each release until lilleman drops it. +### 221. Parse each transcript entry once, where `bin/claude_code/transcript.py` reads it, into a typed value naming its kind, so no consumer works out an entry's kind from a raw `dict`. + +"Validate data and build DTOs as early as possible", in `principles/technical-principles.md`, raised 🟢 by the principles audit of item 210's PR. `read_transcript` (`bin/claude_code/transcript.py:16`) returns raw `dict`s, so each consumer, such as `render` beside it and `since_step` in `bin/loop_claude/escalation_mark.py`, calls the helpers in `bin/claude_code/entries.py` (`human_text`, `loop_text`, `assistant_parts`, `tool_call`) to work out an entry's kind again. Parse each line once into types such as a human turn, a loop-claude prompt and an assistant turn, and have every consumer of `claude_code.entries` under `bin/` take those types. The change touches the escalation mark, which the comprehension seats found hard at `bin/loop_claude/cycle/judge.py:153` `escalation_mark` before item 210 moved it: make `since_step` in `bin/loop_claude/escalation_mark.py`, and `Grounds.since_step` and `judge_prompt` in `bin/loop_claude/cycle/judge.py`, easier to read. + ### 105. Compare review rounds per pass and reading cost for the five chunks before and after the `worker:` decision moved the principles out of the worker's context, and file an item if either rose. The `worker:` decision is valid while review rounds per pass do not rise. Count the rounds from each PR's `Answer round :` commits, and take reading cost from `docs/reading-cost.md`. Run it once five chunks have merged after the one that recorded the decision. @@ -144,6 +140,10 @@ Item 161 put `chunk-preflight`'s facts into a fresh worker's prompt, so the work `score-outcomes` counts every item a merge removed from `todo.md` as shipped. A merge that changed only the plan ships nothing, but one that built an item and also dropped another gives the dropped item the built one's outcome, as PR #253 did with item 69. Mark a dropped item in the change that drops it, such as by the commit or merge title, and leave it out. +### 276. Let a worker fix on its own rung a `standards/quality.md` finding whose fix changes only prose, so escalation trigger 4 calls for a higher rung only where code or config must change. + +On 2026-11-08, PR #432's prose round 1 reported two findings against `standards/quality.md` → "A false claim is a bug": a docstring at `bin/release_plan/todo_table.py:61` that named the wrong module, and a sentence in `docs/decisions.md`. That fired escalation trigger 4, and the worker asked to hand both fixes to an opus max subagent. The human answered: "Just prose changes, run the fix on the same rung." Write that into trigger 4 in `CLAUDE.md` → "Working with the codebase", into larv-review's `SKILL.md` §3 → "Rung up", and into the `docs/decisions.md` entry `review: a reviewer or comprehension seat that rules the work below standard…`, whose background says work below standard gets a more capable rung to fix it. A comment or docstring counts as prose, as larv-review §3 says. + ### 116. Report L by the share of chunks with a 🔴, once 10 chunks that each shipped one item record finding counts and most record no 🔴. `score-outcomes` reports the median 🔴 count at each guessed R, and how well L orders chunks by 🔴 findings; the part of R a 🔴 tests is L. Where most chunks have no 🔴, every median reads 0 and the rank correlation rests on the few that have one, which tells a scorer little. No round title held counts before PR #254, so how often a chunk has a 🔴 is not yet known. @@ -164,13 +164,13 @@ When CI runs a rule check, such as one of `bin/rule-hook`'s, let `