Rank todo.md items by value per cost, with a Moves column naming how far each item moves each achieve goal in place of A and G

This commit is contained in:
2026-10-16 00:10:59 +02:00
parent 450f0b3851
commit 016fbb2441
8 changed files with 524 additions and 363 deletions
+118 -63
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Score todo.md's items by the formula and goal weights it states, and hold them to its bar.
"""Score todo.md's items by the formula it states, weighing each goal by its rank in README.md, and hold them to its bar.
usage: rank_todo.py [--check] [todo.md]
@@ -16,21 +16,17 @@ A valid todo.md; ## Details and each item's detail are optional:
## Scoring
`Score = -R - S/4 + 2*A + 2*G*W`
`Score = 100 * V / 2**S`
`Bar = 9`
`Bar = 1`
`Next ID = 2`
| Goal | W |
|---|---|
| 1 | 1.00 |
## Items
| ID | Release | Blocked by | Exempt | Item | R | S | C | A | G | Goals | Score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 0.1.0 | | | **Make the first thing work.** | 2 | 3 | 4 | 8 | 9 | 1 | 0 |
| ID | Release | Blocked by | Exempt | Item | R | S | C | Moves | Score |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 0.1.0 | | | **Make the first thing work.** | 2 | 3 | 4 | 1 by 9 | 0 |
## Details
@@ -38,12 +34,17 @@ A valid todo.md; ## Details and each item's detail are optional:
What the tagline cannot say.
- The formula holds numbers, + - * / and parentheses over R, S, A, G and W.
- The formula holds numbers, + - * / ** and parentheses over R, S and V.
- V sums, over the goals in an item's Moves cell, each goal's weight times how far the item moves it.
README.md marks each goal **Maintain:** or **Achieve:**; only an achieve goal scores. The one
ranked k of n achieve goals, in reading order, a sub-goal such as 1.1 included, weighs
(1/k) / (1 + 1/2 + ... + 1/n).
- The bar is judged on the Score as shown, to one decimal.
- 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, C, A and G are whole numbers from 1 to 10; Goals lists goal numbers, comma separated.
C, how hard the change is to get right, stays out of the formula.
- An item's R, S and C are whole numbers from 1 to 10. C, how hard the change is to get right, stays
out of the formula.
- An item's Moves cell is empty, or names each achieve goal it moves and how far, a whole number
from 1 to 10, such as `1.1 by 8, 1.2 by 5`. An item that moves no achieve goal scores V 0.
- An item's Exempt cell is empty, or names why the bar does not apply: decision, defect, owner,
principle, question 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.
@@ -55,6 +56,9 @@ A valid todo.md; ## Details and each item's detail are optional:
- ## Items holds the table and nothing else: an order goes in the scores or the Blocked by column.
- The table holds the columns above. A table without Blocked by gains it. One without C fails, and so
does one with a column this version does not know, since writing it would drop that column.
- A table in the old shape, with A, G and Goals columns in place of Moves, still ranks, by a formula
over R, S, A, G and W and a | Goal | W | table that weighs every README goal, W being the heaviest
cited goal's weight; ranking it says to reshape it.
Exit 1, saying why, on bad arguments, a file that cannot be read or written, a todo.md, README.md or
docs/decisions.md that breaks the rules above, an item that is not exempt scoring under the bar, or
@@ -67,16 +71,18 @@ import pathlib
import re
import sys
from todo_table import BLOCKED_BY, cells, COLUMNS, DIVIDER, HEADER_START, Item, ITEMS_HEADER, items_table, parse_row, Table, table_rows
from todo_table import BLOCKED_BY, cells, COLUMNS, HEADER_START, Item, items_table, MOVES, OLD_COLUMNS, parse_row, Table, table_rows
from failure import Failure
from markdown_text import FENCE, sections
from file_writes import replace_file
LARGEST_FORMULA = 200
LONGEST_FORMULA = 4 * LARGEST_FORMULA
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")
OPERATORS = (ast.Add, ast.BinOp, ast.Div, ast.Expression, ast.Load, ast.Mult, ast.Pow, ast.Sub, ast.UAdd, ast.UnaryOp, ast.USub)
VARIABLES = ("R", "S", "V")
OLD_VARIABLES = ("A", "G", "R", "S", "W")
WEIGHTS_HEADER = "| Goal | W |"
RESHAPE = f"the items table scores A and G against goal weights todo.md states, the shape before {MOVES}; reshaping it to the shape rank_todo.py --help shows is a chunk of its own"
@dataclasses.dataclass(frozen=True)
@@ -84,7 +90,10 @@ class Scoring:
formula: ast.Expression
bar: float
next_id: int
# README.md's goal numbers in reading order, and the weight of each goal that scores: in an old-shape table every goal, at the weight todo.md states; else each achieve goal.
goals: list[str]
weights: dict[str, float]
old_shape: bool
@dataclasses.dataclass(frozen=True)
@@ -93,6 +102,7 @@ class Ranked:
under_bar: list[str]
# Blocker IDs the ranking dropped because the table no longer holds them; printed, since a mistyped ID is dropped the same way.
dropped: list[str]
old_shape: bool
def main(argv: list[str]) -> int:
@@ -118,7 +128,7 @@ def main(argv: list[str]) -> int:
unwritten = write(todo, ranked.text)
if unwritten:
return fail(unwritten)
for line in ranked.dropped + ranked.under_bar:
for line in [RESHAPE] * ranked.old_shape + ranked.dropped + ranked.under_bar:
print(f"{todo}: {line}", file=sys.stderr)
return 1 if ranked.under_bar else 0
@@ -171,28 +181,33 @@ def write(path: pathlib.Path, text: str) -> Failure | None:
def rank(text: str, readme: str, decisions: str) -> Ranked | Failure:
lines = text.split("\n")
scoring = read_scoring(text, lines, readme)
if "## Items" not in lines:
return Failure("todo.md is not in the scored-table format; rank_todo.py --help shows a valid one")
found = read_table(lines)
if isinstance(found, Failure):
return found
scoring = read_scoring(text, lines, readme, MOVES not in found.columns)
if isinstance(scoring, Failure):
return scoring
table = read_items(lines, scoring)
if isinstance(table, Failure):
return table
items, found = table
items = read_items(found, scoring)
if isinstance(items, Failure):
return items
if uncited := check_citations(items, decisions):
return uncited
scored = ordered(items, scoring)
if isinstance(scored, Failure):
return scored
# Every table gets the header of COLUMNS, so one from before BLOCKED_BY joined gains the column.
lines[found.header:found.start] = [ITEMS_HEADER, DIVIDER]
lines[found.start:found.start + len(scored)] = [render_item(item, value) for item, value in scored]
# Every table gets the header of all its shape's columns, so one from before BLOCKED_BY joined gains the column.
columns = OLD_COLUMNS if scoring.old_shape else COLUMNS
lines[found.header:found.start] = ["| " + " | ".join(columns) + " |", "|" + "---|" * len(columns)]
lines[found.start:found.start + len(scored)] = [render_item(item, value, scoring.old_shape) for item, value in scored]
ranked = rank_details("\n".join(lines), [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]
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))]
return Ranked(ranked, under_bar, dropped)
return Ranked(ranked, under_bar, dropped, scoring.old_shape)
def blocked_through(id_: int, items: list[Item]) -> set[int]:
@@ -209,7 +224,7 @@ def ordered(items: list[Item], scoring: Scoring) -> list[tuple[Item, float]] | F
"""Each item with its score, by release, then security 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.weights)
value = score(scoring.formula, item, scoring)
if isinstance(value, Failure):
return value
by_score.append((item, value))
@@ -223,13 +238,11 @@ def under_the_bar(item: Item, value: float, bar: float, items: list[Item]) -> st
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) -> Scoring | Failure:
if "## Items" not in lines:
return Failure("todo.md is not in the scored-table format; rank_todo.py --help shows a valid one")
def read_scoring(text: str, lines: list[str], readme: str, old_shape: bool) -> Scoring | Failure:
goals = readme_goals(readme)
if isinstance(goals, Failure):
return goals
formula = parse_formula(stated(text, "Score"))
formula = parse_formula(stated(text, "Score"), OLD_VARIABLES if old_shape else VARIABLES)
if isinstance(formula, Failure):
return formula
bar = number(stated(text, "Bar"), "the bar")
@@ -238,14 +251,20 @@ def read_scoring(text: str, lines: list[str], readme: str) -> Scoring | Failure:
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)
numbers = [number for number, _ in goals]
if old_shape:
weights = parse_weights(lines, numbers)
elif WEIGHTS_HEADER in lines:
weights = Failure(f"todo.md holds a goal weights table beside a {MOVES} column; drop the table, since rank_todo.py weighs each achieve goal by its rank in README.md")
else:
weights = achieve_weights(goals)
if isinstance(weights, Failure):
return weights
return Scoring(formula, bar, int(next_id), weights)
return Scoring(formula, bar, int(next_id), numbers, weights, old_shape)
def read_items(lines: list[str], scoring: Scoring) -> tuple[list[Item], Table] | Failure:
"""The items, and the table they were read from."""
def read_table(lines: list[str]) -> Table | Failure:
"""The items table, held to its shape's columns and alone under ## Items."""
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")
@@ -254,14 +273,17 @@ def read_items(lines: list[str], scoring: Scoring) -> tuple[list[Item], Table] |
# A table without C fails, so no chunk starts on an unscored item.
if "C" not in table.columns:
return Failure("todo.md's items table has no C column; add one after S, and score each item's C from 1 to 10 per rank_todo.py --help")
# Ranking writes COLUMNS, so it would drop a column it does not know.
if unknown := [column for column in table.columns if column not in COLUMNS]:
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(COLUMNS)}. Rename it, or move this machine to the release that added it")
if misplaced := outside_items(lines, table):
return misplaced
# Ranking writes its shape's columns, so it would drop a column it does not know.
known = COLUMNS if MOVES in table.columns else OLD_COLUMNS
if unknown := [column for column in table.columns if column not in known]:
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(known)}. Rename it, or move this machine to the release that added it")
return outside_items(lines, table) or table
def read_items(table: Table, scoring: Scoring) -> list[Item] | Failure:
items = []
for row in table.rows:
item = parse_item(row, scoring.weights, table.columns)
item = parse_item(row, scoring, table.columns)
if isinstance(item, Failure):
return item
items.append(item)
@@ -273,7 +295,7 @@ def read_items(lines: list[str], scoring: Scoring) -> tuple[list[Item], Table] |
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, table
return items
def outside_items(lines: list[str], table: Table) -> Failure | None:
@@ -343,25 +365,37 @@ def check_citations(items: list[Item], decisions: str) -> Failure | None:
return None
def readme_goals(readme: str) -> list[str] | Failure:
"""The numbers of README.md's goals in reading order, a sub-goal as 4.1."""
def readme_goals(readme: str) -> list[tuple[str, str | None]] | 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[str] = []
goals: list[tuple[str, str | None]] = []
path: list[tuple[int, str]] = []
for indent, position in re.findall(r"^([ \t]*)(\d+)\. ", found[0].expandtabs(4), re.M):
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))
goals.append((".".join(part for _, part in path), 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(goals)) < len(goals):
return Failure(f"README.md's ## Goals numbers {', '.join(goals)}; number each goal by its position")
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 achieve_weights(goals: list[tuple[str, str | None]]) -> dict[str, float] | Failure:
"""Each achieve goal's sum-reciprocal weight: the one ranked k of n in reading order weighs (1/k) / (1 + 1/2 + ... + 1/n)."""
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"]
if not achieve:
return Failure("README.md marks no goal **Achieve:**, so no item can score; ~/.claude/rules/goals-and-audience.md says how to mark the goals to pursue")
harmonic = sum(1 / rank for rank in range(1, len(achieve) + 1))
return {number: 1 / rank / harmonic for rank, number in enumerate(achieve, 1)}
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)]
@@ -373,7 +407,7 @@ def stated(text: str, name: str) -> str | Failure:
return found[0]
def parse_formula(source: str | Failure) -> ast.Expression | Failure:
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.
@@ -388,13 +422,13 @@ def parse_formula(source: str | Failure) -> ast.Expression | Failure:
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")
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."""
"""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)
@@ -415,12 +449,21 @@ def evaluate(node: ast.AST, values: dict[str, float]) -> float:
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):
try:
return math.pow(evaluate(left, values), evaluate(right, values))
except (OverflowError, ValueError):
return 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)})
def score(formula: ast.Expression, item: Item, scoring: Scoring) -> float | Failure:
if scoring.old_shape:
# An item serving several goals is weighed by the heaviest; summing them would reward citing more.
variables = {**item.scores, "W": max(scoring.weights[goal] for goal in item.goals)}
else:
variables = {**item.scores, "V": sum(scoring.weights[goal] * move for goal, move in zip(item.goals, item.moves))}
value = evaluate(formula, variables)
return value if math.isfinite(value) else Failure(f"the formula gives item {item.id} no finite score")
@@ -455,18 +498,30 @@ def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float] | Fail
return weights
def parse_item(row: str, weights: dict[str, float], columns: tuple[str, ...]) -> Item | Failure:
def parse_item(row: str, scoring: Scoring, columns: tuple[str, ...]) -> Item | Failure:
item = parse_row(row, columns)
if isinstance(item, Failure):
return item
if unknown := [goal for goal in item.goals if goal not in weights]:
return Failure(f"item {item.id} cites goal {', '.join(unknown)}, which the goal weights do not list")
if scoring.old_shape:
if unknown := [goal for goal in item.goals if goal not in scoring.weights]:
return Failure(f"item {item.id} cites goal {', '.join(unknown)}, which the goal weights do not list")
return item
for goal in item.goals:
if goal not in scoring.goals:
return Failure(f"item {item.id} cites goal {goal}, which README.md's ## Goals does not number")
if goal not in scoring.weights:
return Failure(f"item {item.id} cites goal {goal}, a maintain goal, which vetoes and never scores; name only the achieve goals it moves")
if item.goals.count(goal) > 1:
return Failure(f"item {item.id} cites goal {goal} twice; name each goal once")
return item
def render_item(item: Item, value: float) -> str:
scores = " | ".join(str(item.scores[name]) for name in "RSCAG")
return f"| {item.id} | {release_name(item)} | {', '.join(map(str, item.blocked_by))} | {item.exempt} | {item.tagline} | {scores} | {', '.join(item.goals)} | {value:.1f} |"
def render_item(item: Item, value: float, old_shape: bool) -> str:
if old_shape:
scores, goals = " | ".join(str(item.scores[name]) for name in "RSCAG"), ", ".join(item.goals)
else:
scores, goals = " | ".join(str(item.scores[name]) for name in "RSC"), ", ".join(f"{goal} by {move}" for goal, move in zip(item.goals, item.moves))
return f"| {item.id} | {release_name(item)} | {', '.join(map(str, item.blocked_by))} | {item.exempt} | {item.tagline} | {scores} | {goals} | {value:.1f} |"
def rank_details(text: str, items: list[Item]) -> str | Failure: