Files
claude-config/bin/rank_todo.py
T

268 lines
11 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) and the README.md beside it. Rewrites each item's Score from
`Score = <formula>` under ## Scoring, sorts the ## Items table by release, then exempt items first,
then score from highest, then ID, and orders ## Details to match, each heading `### <ID>. <tagline>`.
An item's Exempt cell is empty, or names why the bar does not apply to it: security, question or
decision. --check writes nothing and fails when the file is not ranked as it would be.
Exit 1, saying why, when todo.md breaks the format, its goal weights do not list README.md's goals,
an item that is not exempt scores under the `Bar = <number>` it states, judged on the Score as
shown, or --check finds it unranked.
"""
import ast
import dataclasses
import math
import pathlib
import re
import sys
EXEMPTIONS = ("", "decision", "question", "security")
ITEMS_HEADER = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |"
WEIGHTS_HEADER = "| Goal | W |"
VARIABLES = ("A", "G", "R", "S", "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, ...]
class Malformed(Exception):
pass
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(__doc__.strip(), file=sys.stderr)
return 1
todo = pathlib.Path(paths[0] if paths else "todo.md")
try:
text = todo.read_text(encoding="utf-8")
readme = (todo.parent / "README.md").read_text(encoding="utf-8")
ranked, under_bar = rank(text, readme_goals(readme))
except (OSError, UnicodeDecodeError, Malformed) as failure:
print(failure if isinstance(failure, OSError) else f"{todo}: {failure}", file=sys.stderr)
return 1
if check and ranked != text:
print(f"{todo}: not ranked; run rank_todo.py on it", file=sys.stderr)
return 1
if not check and ranked != text:
todo.write_text(ranked, encoding="utf-8")
for line in under_bar:
print(f"{todo}: {line}", file=sys.stderr)
return 1 if under_bar else 0
def rank(text: str, goals: list[str]) -> tuple[str, list[str]]:
"""Returns todo.md ranked, and a line for each item under the bar."""
lines = text.split("\n")
formula = parse_formula(stated(text, "Score"))
bar = number(stated(text, "Bar"), "the bar")
weights = parse_weights(lines, goals)
start, end = table_rows(lines, ITEMS_HEADER)
items = [parse_item(row, weights) for row in lines[start:end]]
if any(line.startswith("|") for line in section_lines(lines, end)):
raise Malformed("## Items holds a row outside its table; keep the rows together under the header")
if len({item.id for item in items}) < len(items):
raise Malformed("two items share an ID")
scored = sorted(((item, score(formula, item, weights)) for item in items), key=lambda pair: (pair[0].release, not pair[0].exempt, -pair[1], pair[0].id))
lines[start:end] = [render_item(item, value) for item, value in scored]
text = "\n".join(lines)
text = rank_details(text, [item for item, _ in scored])
under_bar = [f"item {item.id} scores {value:.1f}, under the bar {bar:g}; rescore it or delete it" for item, value in scored if not item.exempt and round(value, 1) < bar]
return text, under_bar
def readme_goals(readme: str) -> list[str]:
"""The numbers of README.md's goals in reading order, a sub-goal as 4.1."""
section = re.search(r"^## Goals\n(.*?)(?=^## |\Z)", readme, re.M | re.S)
if section is None:
raise Malformed("README.md has no ## Goals")
goals: list[str] = []
path: list[tuple[int, str]] = []
for indent, number in re.findall(r"^([ \t]*)(\d+)\. ", section.group(1).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:
raise Malformed("README.md's ## Goals has no numbered goal")
if len(set(goals)) < len(goals):
raise Malformed(f"README.md's ## Goals numbers {', '.join(goals)}; number each goal by its position")
return goals
def stated(text: str, name: str) -> str:
found = re.findall(rf"^`{name} = ([^`]+)`$", text, re.M)
if len(found) != 1:
raise Malformed(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) -> ast.Expression:
try:
tree = ast.parse(source, mode="eval")
except SyntaxError:
raise Malformed(f"the formula {source!r} does not parse") from None
for node in ast.walk(tree):
allowed = isinstance(node, (ast.Expression, ast.BinOp, ast.UnaryOp, ast.Add, ast.Sub, ast.Mult, ast.Div, ast.USub, ast.UAdd, ast.Load))
allowed = allowed or (isinstance(node, ast.Constant) and type(node.value) in (int, float))
allowed = allowed or (isinstance(node, ast.Name) and node.id in VARIABLES)
if not allowed:
raise Malformed(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:
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, operator, right):
a, b = evaluate(left, values), evaluate(right, values)
match operator:
case ast.Add():
return a + b
case ast.Sub():
return a - b
case ast.Mult():
return a * b
case ast.Div():
return a / b
raise Malformed(f"the formula holds {ast.dump(node)}")
def score(formula: ast.Expression, item: Item, weights: dict[str, float]) -> float:
# An item serving several goals is weighed by the heaviest; summing them would reward citing more.
try:
return evaluate(formula, {**item.scores, "W": max(weights[goal] for goal in item.goals)})
except ZeroDivisionError:
raise Malformed(f"the formula divides by zero for item {item.id}") from None
def number(text: str, what: str) -> float:
try:
value = float(text)
except ValueError:
value = math.nan
if not math.isfinite(value):
raise Malformed(f"{what} {text!r} is not a finite number")
return value
def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float]:
start, end = table_rows(lines, WEIGHTS_HEADER)
weights: dict[str, float] = {}
for row in lines[start:end]:
goal, weight = cells(row, 2)
weights[goal] = number(weight, f"goal {goal}'s weight")
if list(weights) != goals:
default = "\n".join(f"| {goal} | {(len(goals) - index) / len(goals):.2f} |" for index, goal in enumerate(goals))
raise Malformed(f"the goal weights list {', '.join(weights) or 'no goal'}, but README.md's goals are {', '.join(goals)}; by position, (n + 1 - p) / n, they weigh:\n{WEIGHTS_HEADER}\n|---|---|\n{default}")
return weights
def table_rows(lines: list[str], header: str) -> tuple[int, int]:
"""The index range of a table's body rows, below its header and divider."""
if lines.count(header) != 1:
raise Malformed(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(" ", "")):
raise Malformed(f"the table under {header} has no |---| divider line")
end = start
while end < len(lines) and lines[end].startswith("|"):
end += 1
return start, end
def section_lines(lines: list[str], start: int) -> list[str]:
"""The lines from start up to the next ## heading."""
end = start
while end < len(lines) and not lines[end].startswith("## "):
end += 1
return lines[start:end]
def cells(row: str, count: int) -> list[str]:
found = [cell.strip() for cell in re.split(r"(?<!\\)\|", row.strip())[1:-1]]
if len(found) != count:
raise Malformed(f"this row needs {count} cells: {row}")
return found
def parse_item(row: str, weights: dict[str, float]) -> Item:
id_, release, exempt, tagline, r, s, a, g, goals, _ = cells(row, 10)
if not re.fullmatch(r"[0-9]+", id_) or int(id_) < 1:
raise Malformed(f"the ID {id_!r} is not a positive whole number: {row}")
if not re.fullmatch(r"\d+\.\d+\.\d+", release):
raise Malformed(f"item {id_}'s release {release!r} is not a semver version")
if exempt not in EXEMPTIONS:
raise Malformed(f"item {id_}'s Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
if not re.fullmatch(r"\*\*[^*].*[^*]\*\*", tagline):
raise Malformed(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:
raise Malformed(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]:
raise Malformed(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:
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):
raise Malformed("## 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():
raise Malformed("## Details holds text before its first ### <ID>. heading")
details = {}
for id_, detail in zip(parts[1::2], parts[2::2]):
if int(id_) in details:
raise Malformed(f"## Details holds item {id_} twice")
details[int(id_)] = detail.strip("\n")
if unknown := sorted(set(details) - {item.id for item in items}):
raise Malformed(f"## Details holds item {', '.join(map(str, unknown))}, which the items table does not")
headed = [f"### {item.id}. {item.tagline.strip('*')}\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:]))