Files
claude-config/bin/rank_todo.py
T

371 lines
15 KiB
Python
Executable File

#!/usr/bin/env python3
"""Score and rank todo.md's items by the formula, bar and goal weights it states.
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.
A valid todo.md, every line shown required:
# todo
## Scoring
`Score = -R - S/4 + 2*A + 2*G*W`
`Bar = 9`
`Next ID = 2`
| Goal | W |
|---|---|
| 1 | 1.00 |
## Items
| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 0.1.0 | | **Make the first thing work.** | 2 | 3 | 8 | 9 | 1 | 0 |
## Details
### 1. Make the first thing work.
What the tagline cannot say.
- 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.
- 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.
- 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.
"""
import ast
import dataclasses
import math
import pathlib
import re
import sys
from loop_claude.failure import Failure
from loop_claude.project.premises import sections
EXEMPTIONS = ("", "decision", "defect", "question", "security")
ITEMS_HEADER = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |"
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 |"
@dataclasses.dataclass(frozen=True)
class Item:
id: int
release: tuple[int, int, int]
exempt: str
tagline: str
scores: dict[str, int]
goals: tuple[str, ...]
@dataclasses.dataclass(frozen=True)
class Ranked:
text: str
under_bar: list[str]
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)
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")
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:
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")
except OSError as failure:
return Failure(f"{path}: {failure.strerror}")
except UnicodeDecodeError:
return Failure(f"{path}: not UTF-8")
def rank(text: str, readme: str, decisions: str) -> Ranked | Failure:
lines = text.split("\n")
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)
if isinstance(goals, Failure):
return goals
formula = parse_formula(stated(text, "Score"))
if isinstance(formula, Failure):
return formula
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
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)
def readme_goals(readme: str) -> list[str] | Failure:
"""The numbers of README.md's goals in reading order, a sub-goal as 4.1."""
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[str] = []
path: list[tuple[int, str]] = []
for indent, number 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))
goals.append(".".join(part for _, part in path))
if not goals:
return Failure("README.md's ## Goals has no numbered goal")
if len(set(goals)) < len(goals):
return Failure(f"README.md's ## Goals numbers {', '.join(goals)}; number each goal by its position")
return goals
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) -> ast.Expression | Failure:
if isinstance(source, Failure):
return source
try:
tree = ast.parse(source, mode="eval")
except SyntaxError:
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)
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 gives 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
return math.nan
def score(formula: ast.Expression, item: Item, weights: dict[str, float]) -> float | Failure:
# An item serving several goals is weighed by the heaviest; summing them would reward citing more.
value = evaluate(formula, {**item.scores, "W": max(weights[goal] for goal in item.goals)})
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:
rows = table_rows(lines, WEIGHTS_HEADER)
if isinstance(rows, Failure):
return rows
weights: dict[str, float] = {}
for row in 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
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_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."""
if lines.count(header) != 1:
return Failure(f"todo.md needs the table header {header} once")
start = lines.index(header) + 2
if start > len(lines) or not re.fullmatch(r"\|(-+\|)+", lines[start - 1].replace(" ", "")):
return Failure(f"the table under {header} has no |---| divider line")
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))]
def cells(row: str, count: int) -> list[str] | Failure:
found = [cell.strip() for cell in re.split(r"(?<!\\)\|", row.strip())[1:-1]]
return found if len(found) == count else Failure(f"this row needs {count} cells: {row}")
def parse_item(row: str, weights: dict[str, float]) -> Item | Failure:
found = cells(row, 10)
if isinstance(found, Failure):
return found
id_, release, exempt, tagline, r, s, a, g, goals, _ = found
if not re.fullmatch(r"[0-9]+", id_) or int(id_) < 1:
return Failure(f"the ID {id_!r} is not a positive whole number: {row}")
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", release):
return Failure(f"item {id_}'s release {release!r} is not a semver version")
if exempt not in EXEMPTIONS:
return Failure(f"item {id_}'s Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
if not re.fullmatch(r"\*\*[^*].*[^*]\*\*", tagline):
return Failure(f"item {id_}'s Item cell is not one bold tagline: {tagline}")
scores = {}
for name, value in zip("RSAG", (r, s, a, g)):
if not re.fullmatch(r"[0-9]+", value) or not 1 <= int(value) <= 10:
return Failure(f"item {id_}'s {name} {value!r} is not a whole number from 1 to 10")
scores[name] = int(value)
cited = tuple(goal.strip() for goal in goals.split(","))
if unknown := [goal for goal in cited if goal not in weights]:
return Failure(f"item {id_} cites goal {', '.join(unknown)}, which the goal weights do not list")
major, minor, patch = (int(part) for part in release.split("."))
return Item(int(id_), (major, minor, patch), exempt, tagline, scores, cited)
def render_item(item: Item, value: float) -> str:
release = ".".join(str(part) for part in item.release)
scores = " | ".join(str(item.scores[name]) for name in "RSAG")
return f"| {item.id} | {release} | {item.exempt} | {item.tagline} | {scores} | {', '.join(item.goals)} | {value:.1f} |"
def rank_details(text: str, items: list[Item]) -> str | Failure:
section = re.search(r"^## Details\n(.*?)(?=^## |\Z)", text, re.M | re.S)
if section is None:
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):
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():
return Failure("## Details holds text before its first ### <ID>. heading")
details: dict[int, str] = {}
for id_, detail in zip(parts[1::2], parts[2::2]):
if int(id_) in details:
return Failure(f"## Details holds item {id_} twice")
details[int(id_)] = detail.strip("\n")
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:]))