Answer the third round: split rank, check decision citations both ways, one fence rule, prose fixes

This commit is contained in:
2026-10-02 20:28:13 +02:00
parent 798dfd781e
commit b712076144
8 changed files with 181 additions and 121 deletions
+4 -1
View File
@@ -1,7 +1,10 @@
import pathlib
import re
from loop_claude.stop import Stop
FENCE = re.compile(r"^ {0,3}(```|~~~)", re.M)
def read_premises(root: str) -> str | Stop:
try:
@@ -26,7 +29,7 @@ def sections(text: str) -> dict[str, list[str]]:
blocks: list[tuple[str | None, list[str]]] = []
fenced = False
for line in text.splitlines():
fenced ^= line.startswith("```")
fenced ^= bool(FENCE.match(line))
if not fenced and line.startswith("## "):
blocks.append((line.strip()[3:], []))
elif not fenced and line.startswith("# "):
+147 -98
View File
@@ -1,14 +1,14 @@
#!/usr/bin/env python3
"""Score and rank todo.md's items by the formula, bar and goal weights it states.
"""Score todo.md's items by the formula and goal weights it states, and hold them to its bar.
usage: rank_todo.py [--check] [todo.md]
Reads todo.md (default: ./todo.md), the README.md beside it, and docs/decisions.md when there is
one. Rewrites each item's Score from the formula, sorts the items by release, then security rows,
then score from highest, then ID, and orders the details to match. --check writes nothing and fails
when the file is not ranked as it would be.
one. Rewrites each item's Score from the formula and sorts the items by release; within a release,
security rows come first, then the rest by score from highest, then by ID. Orders the details to
match. --check writes nothing and fails when the file is not ranked as it would be.
A valid todo.md, every line shown required:
A valid todo.md; ## Details and each item's detail are optional:
# todo
@@ -38,15 +38,16 @@ A valid todo.md, every line shown required:
- The formula holds numbers, + - * / and parentheses over R, S, A, G and W.
- The bar is judged on the Score as shown, to one decimal.
- A new item takes Next ID, and Next ID then counts up; no row may reach it.
- A new item takes Next ID, and Next ID then goes up by one; every ID stays below it.
- The goal weights list README.md's numbered goals in order, a sub-goal such as 1.1 included.
- An item's R, S, A and G are whole numbers from 1 to 10; Goals lists goal numbers, comma separated.
- An item's Exempt cell is empty, or names why the bar does not apply: decision, defect, question
or security. An item docs/decisions.md cites as "`todo.md` item N" is marked decision.
or security. An item docs/decisions.md cites as "`todo.md` item N" must be exempt, and a row
marked decision must be cited there.
- An item's Item cell is one bold tagline; its detail, if any, sits under its ID in ## Details.
Exit 1, saying why, when a file cannot be read, todo.md breaks the format, an item that is not
exempt scores under the bar, or --check finds the file unranked.
Exit 1, saying why, when a file cannot be read or written, todo.md breaks the format, an item that is
not exempt scores under the bar, or --check finds the file unranked.
"""
import ast
import dataclasses
@@ -55,11 +56,13 @@ import pathlib
import re
import sys
# loop_claude's leaf modules, so both tools share one error type and one README parser.
from loop_claude.failure import Failure
from loop_claude.project.premises import sections
from loop_claude.project.premises import FENCE, sections
EXEMPTIONS = ("", "decision", "defect", "question", "security")
ITEMS_HEADER = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |"
LARGEST_FORMULA = 200
OPERATORS = (ast.Add, ast.BinOp, ast.Div, ast.Expression, ast.Load, ast.Mult, ast.Sub, ast.UAdd, ast.UnaryOp, ast.USub)
VARIABLES = ("A", "G", "R", "S", "W")
WEIGHTS_HEADER = "| Goal | W |"
@@ -75,6 +78,21 @@ class Item:
goals: tuple[str, ...]
@dataclasses.dataclass(frozen=True)
class Scoring:
formula: ast.Expression
bar: float
next_id: int
weights: dict[str, float]
@dataclasses.dataclass(frozen=True)
class Table:
"""Body rows of a markdown table, and the index of the first in the file's lines."""
start: int
rows: list[str]
@dataclasses.dataclass(frozen=True)
class Ranked:
text: str
@@ -85,46 +103,87 @@ def main(argv: list[str]) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
check = "--check" in argv
paths = [arg for arg in argv if arg != "--check"]
if len(paths) > 1 or any(path.startswith("-") for path in paths):
print(f"rank_todo.py: cannot read the arguments {' '.join(argv)}; usage: rank_todo.py [--check] [todo.md]", file=sys.stderr)
return 1
todo = pathlib.Path(paths[0] if paths else "todo.md")
decisions = todo.parent / "docs" / "decisions.md"
read_in = [read(todo), read(todo.parent / "README.md"), read(decisions) if decisions.exists() else ""]
unread = next((found for found in read_in if isinstance(found, Failure)), None)
if unread:
print(unread.reason, file=sys.stderr)
return 1
text, readme, cited = (str(found) for found in read_in)
ranked = rank(text, readme, cited)
args = parse_args(argv)
if isinstance(args, Failure):
return fail(args)
check, todo = args
texts = read_all(todo)
if isinstance(texts, Failure):
return fail(texts)
ranked = rank(*texts)
if isinstance(ranked, Failure):
print(ranked.reason, file=sys.stderr)
return 1
if ranked.text != text:
if check:
print(f"{todo}: not ranked; run rank_todo.py on it", file=sys.stderr)
return 1
todo.write_text(ranked.text, encoding="utf-8")
return fail(ranked)
if ranked.text != texts[0]:
unwritten = Failure(f"{todo}: not ranked; run rank_todo.py on it") if check else write(todo, ranked.text)
if unwritten:
return fail(unwritten)
for line in ranked.under_bar:
print(f"{todo}: {line}", file=sys.stderr)
return 1 if ranked.under_bar else 0
def read(path: pathlib.Path) -> str | Failure:
def fail(failure: Failure) -> int:
print(failure.reason, file=sys.stderr)
return 1
def parse_args(argv: list[str]) -> tuple[bool, pathlib.Path] | Failure:
paths = [arg for arg in argv if arg != "--check"]
if len(paths) > 1 or any(path.startswith("-") for path in paths):
return Failure(f"rank_todo.py: cannot read the arguments {' '.join(argv)}; usage: rank_todo.py [--check] [todo.md]")
return "--check" in argv, pathlib.Path(paths[0] if paths else "todo.md")
def read_all(todo: pathlib.Path) -> tuple[str, str, str] | Failure:
"""todo.md, the README.md beside it, and its docs/decisions.md, 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)):
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]
def write(path: pathlib.Path, text: str) -> Failure | None:
try:
return path.read_text(encoding="utf-8")
except FileNotFoundError:
return Failure(f"{path}: not found; every project keeps a todo.md beside its README.md, and rank_todo.py --help shows one")
path.write_text(text, encoding="utf-8")
except OSError as failure:
return Failure(f"{path}: {failure.strerror}")
except UnicodeDecodeError:
return Failure(f"{path}: not UTF-8")
return None
def rank(text: str, readme: str, decisions: str) -> Ranked | Failure:
lines = text.split("\n")
scoring = read_scoring(text, lines, readme)
if isinstance(scoring, Failure):
return scoring
table = read_items(lines, scoring, decisions)
if isinstance(table, Failure):
return table
items, start = table
scored = []
for item in items:
value = score(scoring.formula, item, scoring.weights)
if isinstance(value, Failure):
return value
scored.append((item, value))
scored.sort(key=lambda pair: (pair[0].release, pair[0].exempt != "security", -pair[1], pair[0].id))
lines[start:start + len(scored)] = [render_item(item, value) for item, value in scored]
ranked = rank_details("\n".join(lines), [item for item, _ in scored])
if isinstance(ranked, Failure):
return ranked
under_bar = [f"item {item.id} scores {value:.1f}, under the bar {scoring.bar:g}; delete it and any item that needs it, or mark it with a reason the bar does not apply" for item, value in scored if not item.exempt and round(value, 1) < scoring.bar]
return Ranked(ranked, under_bar)
def read_scoring(text: str, lines: list[str], readme: str) -> Scoring | Failure:
if ITEMS_HEADER not in lines and "## Items" not in lines:
return Failure("todo.md is not in the scored-table format; rank_todo.py --help shows a valid one")
goals = readme_goals(readme)
@@ -136,35 +195,42 @@ def rank(text: str, readme: str, decisions: str) -> Ranked | Failure:
bar = number(stated(text, "Bar"), "the bar")
if isinstance(bar, Failure):
return bar
next_id = number(stated(text, "Next ID"), "Next ID")
if isinstance(next_id, Failure):
return next_id
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 = parse_weights(lines, goals)
if isinstance(weights, Failure):
return weights
items = parse_items(lines, weights)
if isinstance(items, Failure):
return items
ids = [item.id for item in items]
if ids and max(ids) >= next_id:
return Failure(f"item {max(ids)} is not under Next ID {next_id:g}; raise Next ID past every ID")
marked = {item.id for item in items if item.exempt == "decision"}
if unmarked := sorted(set(cited_items(decisions)) - marked):
return Failure(f"docs/decisions.md cites todo.md item {', '.join(map(str, unmarked))}, which no row marked decision holds")
scored = []
for item in items:
value = score(formula, item, weights)
if isinstance(value, Failure):
return value
scored.append((item, value))
scored.sort(key=lambda pair: (pair[0].release, pair[0].exempt != "security", -pair[1], pair[0].id))
start = lines.index(ITEMS_HEADER) + 2
lines[start:start + len(scored)] = [render_item(item, value) for item, value in scored]
ranked = rank_details("\n".join(lines), [item for item, _ in scored])
if isinstance(ranked, Failure):
return ranked
under_bar = [f"item {item.id} scores {value:.1f}, under the bar {bar:g}; delete it and any item that needs it, or mark it with a reason the bar does not apply" for item, value in scored if not item.exempt and round(value, 1) < bar]
return Ranked(ranked, under_bar)
return Scoring(formula, bar, int(next_id), weights)
def read_items(lines: list[str], scoring: Scoring, decisions: str) -> tuple[list[Item], int] | Failure:
"""The items, and the index of the first row, checked against Next ID and the decisions citing them."""
table = table_rows(lines, ITEMS_HEADER)
if isinstance(table, Failure):
return table
after = lines[table.start + len(table.rows):]
if any(line.startswith("|") for line in after[:next((index for index, line in enumerate(after) if line.startswith("## ")), len(after))]):
return Failure("## Items holds a row outside its table; keep the rows together under the header")
items = []
for row in table.rows:
item = parse_item(row, scoring.weights)
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")
cited = set(cited_items(decisions))
if gone := sorted(cited - ids):
return Failure(f"docs/decisions.md cites todo.md item {', '.join(map(str, gone))}, which todo.md no longer holds; revise that decision to say what holds now")
if unexempt := sorted(item.id for item in items if item.id in cited and not item.exempt):
return Failure(f"docs/decisions.md cites item {', '.join(map(str, unexempt))}; mark it decision, or another reason the bar does not apply")
if uncited := sorted(item.id for item in items if item.exempt == "decision" and item.id not in cited):
return Failure(f"item {', '.join(map(str, uncited))} is marked decision, but docs/decisions.md does not cite it as `todo.md` item N")
return items, table.start
def readme_goals(readme: str) -> list[str] | Failure:
@@ -174,10 +240,10 @@ def readme_goals(readme: str) -> list[str] | Failure:
return Failure(f"README.md has ## Goals {len(found)} times; it needs it once")
goals: list[str] = []
path: list[tuple[int, str]] = []
for indent, number in re.findall(r"^([ \t]*)(\d+)\. ", found[0].expandtabs(4), re.M):
for indent, position in re.findall(r"^([ \t]*)(\d+)\. ", found[0].expandtabs(4), re.M):
while path and path[-1][0] >= len(indent):
path.pop()
path.append((len(indent), number))
path.append((len(indent), position))
goals.append(".".join(part for _, part in path))
if not goals:
return Failure("README.md's ## Goals has no numbered goal")
@@ -202,10 +268,13 @@ def parse_formula(source: str | Failure) -> ast.Expression | Failure:
return source
try:
tree = ast.parse(source, mode="eval")
except SyntaxError:
except (SyntaxError, ValueError):
return Failure(f"the formula {source!r} does not parse")
for node in ast.walk(tree):
numeric = isinstance(node, ast.Constant) and type(node.value) in (int, float)
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
@@ -253,17 +322,19 @@ def number(text: str | Failure, what: str) -> float | Failure:
def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float] | Failure:
rows = table_rows(lines, WEIGHTS_HEADER)
if isinstance(rows, Failure):
return rows
table = table_rows(lines, WEIGHTS_HEADER)
if isinstance(table, Failure):
return table
weights: dict[str, float] = {}
for row in rows:
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))
@@ -271,26 +342,7 @@ def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float] | Fail
return weights
def parse_items(lines: list[str], weights: dict[str, float]) -> list[Item] | Failure:
rows = table_rows(lines, ITEMS_HEADER)
if isinstance(rows, Failure):
return rows
after = lines[lines.index(ITEMS_HEADER) + 2 + len(rows):]
if any(line.startswith("|") for line in section_lines(after)):
return Failure("## Items holds a row outside its table; keep the rows together under the header")
items = []
for row in rows:
item = parse_item(row, weights)
if isinstance(item, Failure):
return item
items.append(item)
if len({item.id for item in items}) < len(items):
return Failure("two items share an ID")
return items
def table_rows(lines: list[str], header: str) -> list[str] | Failure:
"""A table's body rows, below its header and divider."""
def table_rows(lines: list[str], header: str) -> Table | Failure:
if lines.count(header) != 1:
return Failure(f"todo.md needs the table header {header} once")
start = lines.index(header) + 2
@@ -299,11 +351,7 @@ def table_rows(lines: list[str], header: str) -> list[str] | Failure:
end = start
while end < len(lines) and lines[end].startswith("|"):
end += 1
return lines[start:end]
def section_lines(lines: list[str]) -> list[str]:
return lines[:next((index for index, line in enumerate(lines) if line.startswith("## ")), len(lines))]
return Table(start, lines[start:end])
def cells(row: str, count: int) -> list[str] | Failure:
@@ -312,6 +360,7 @@ def cells(row: str, count: int) -> list[str] | Failure:
def parse_item(row: str, weights: dict[str, float]) -> Item | Failure:
"""Checks one row cell by cell, in the order the header names them."""
found = cells(row, 10)
if isinstance(found, Failure):
return found
@@ -348,7 +397,7 @@ def rank_details(text: str, items: list[Item]) -> str | Failure:
return text
body = section.group(1)
# A fenced line such as "## Goals" or "### 2. x" would read as a heading and split a detail.
if re.search(r"^ {0,3}(```|~~~)", body, re.M):
if FENCE.search(body):
return Failure("## Details holds a fenced code block; indent quoted markdown by four spaces instead")
parts = re.split(r"^### (\d+)\. [^\n]*\n", body, flags=re.M)
if parts[0].strip():
+9 -2
View File
@@ -73,6 +73,11 @@ class Rank(unittest.TestCase):
self.assertEqual(ranked.under_bar, [])
self.assertEqual(self.ranked(ranked.text), ranked)
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.** | 5 | 5 | 4 | 5 | 2.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 = 9`", "`Bar = 11`"))
self.assertEqual(ranked.under_bar, ["item 2 scores 10.3, under the bar 11; delete it and any item that needs it, or mark it with a reason the bar does not apply"])
@@ -88,7 +93,7 @@ class Rank(unittest.TestCase):
self.assertIn("| 1 | 1.00 |\n| 2 | 0.75 |\n| 2.1 | 0.50 |\n| 3 | 0.25 |", failure.reason)
def test_refuses_a_formula_that_is_more_than_arithmetic_over_the_scores(self):
for formula in ("__import__('os')", "R.real", "X + 1", "R ** 2", "R +", "R / (S - 2)"):
for formula in ("__import__('os')", "R.real", "X + 1", "R ** 2", "R +", "R / (S - 2)", "R\x00", "1" * 400, " + ".join(["R"] * 300)):
with self.subTest(formula=formula):
self.assertIsInstance(self.ranked(TODO.replace("-R - S/4 + 2*A + 2*G*W", formula)), Failure)
@@ -101,6 +106,8 @@ class Rank(unittest.TestCase):
"| 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 |": "| 4 | 0.1.0 | decision |",
"Fast detail.": "```\n## Goals\n```",
"### 3. Make it fast.": "### 7. Make it fast.",
"`Bar = 9`": "`Bar = nan`",
@@ -131,7 +138,7 @@ class Main(unittest.TestCase):
pathlib.Path(temp, "README.md").write_bytes(b"\xff")
self.assertEqual(self.run_main(str(todo)), (1, f"{temp}/README.md: not UTF-8\n"))
pathlib.Path(temp, "README.md").unlink()
self.assertIn("README.md: not found", self.run_main(str(todo))[1])
self.assertEqual(self.run_main(str(todo)), (1, f"{temp}/README.md: not found; rank_todo.py weighs goals from the README.md beside todo.md\n"))
def test_shows_a_valid_file_in_help_and_names_arguments_it_cannot_read(self):
self.assertEqual(self.run_main("--help")[0], 0)