Answer architecture round 1: 5 🔴, 8 🟡; one Shape per table shape, one moves field, end item 156 for the old shape
This commit is contained in:
+73
-52
@@ -70,8 +70,9 @@ import math
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from todo_table import BLOCKED_BY, cells, COLUMNS, HEADER_START, Item, items_table, MOVES, OLD_COLUMNS, parse_row, Table, table_rows
|
||||
from todo_table import BLOCKED_BY, cells, HEADER_START, Item, items_table, MOVES, OLD_SHAPE, parse_row, Shape, shape_of, Table, table_rows
|
||||
from failure import Failure
|
||||
from markdown_text import FENCE, sections
|
||||
from file_writes import replace_file
|
||||
@@ -79,30 +80,30 @@ 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.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"
|
||||
# How README.md marks a goal; None where it marks it neither way.
|
||||
Mark = typing.Literal["Maintain", "Achieve"] | None
|
||||
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, after marking README.md's goals **Maintain:** or **Achieve:**, is a chunk of its own"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Scoring:
|
||||
shape: Shape
|
||||
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.
|
||||
# README.md's goal numbers, in reading order.
|
||||
goals: list[str]
|
||||
# The weight of each goal an item may name: in OLD_SHAPE every goal, at the weight todo.md states; else each achieve goal, by its rank in README.md.
|
||||
weights: dict[str, float]
|
||||
old_shape: bool
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Ranked:
|
||||
text: str
|
||||
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
|
||||
# The lines ranking prints and --check does not: that an old-shape table wants reshaping, and each blocker ID dropped because the table no longer holds it, since a mistyped ID is dropped the same way.
|
||||
notes: list[str]
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
@@ -128,7 +129,7 @@ def main(argv: list[str]) -> int:
|
||||
unwritten = write(todo, ranked.text)
|
||||
if unwritten:
|
||||
return fail(unwritten)
|
||||
for line in [RESHAPE] * ranked.old_shape + ranked.dropped + ranked.under_bar:
|
||||
for line in ranked.notes + ranked.under_bar:
|
||||
print(f"{todo}: {line}", file=sys.stderr)
|
||||
return 1 if ranked.under_bar else 0
|
||||
|
||||
@@ -181,15 +182,14 @@ def write(path: pathlib.Path, text: str) -> Failure | None:
|
||||
|
||||
def rank(text: str, readme: str, decisions: str) -> Ranked | Failure:
|
||||
lines = text.split("\n")
|
||||
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)
|
||||
table = read_table(lines)
|
||||
if isinstance(table, Failure):
|
||||
return table
|
||||
shape = shape_of(table.columns)
|
||||
scoring = read_scoring(text, lines, readme, shape)
|
||||
if isinstance(scoring, Failure):
|
||||
return scoring
|
||||
items = read_items(found, scoring)
|
||||
items = read_items(table, scoring)
|
||||
if isinstance(items, Failure):
|
||||
return items
|
||||
if uncited := check_citations(items, decisions):
|
||||
@@ -197,17 +197,26 @@ def rank(text: str, readme: str, decisions: str) -> Ranked | Failure:
|
||||
scored = ordered(items, scoring)
|
||||
if isinstance(scored, Failure):
|
||||
return 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])
|
||||
ranked = rank_details(rewrite_table(lines, table, 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, shape))
|
||||
|
||||
|
||||
def rewrite_table(lines: list[str], table: Table, scored: list[tuple[Item, float]]) -> str:
|
||||
"""lines with the table's rows in scored's order, under a header naming every column of its shape, so a table from before BLOCKED_BY joined gains the column."""
|
||||
shape = shape_of(table.columns)
|
||||
columns = shape.columns
|
||||
header = ["| " + " | ".join(columns) + " |", "|" + "---|" * len(columns)]
|
||||
rows = [render_item(item, value, shape) for item, value in scored]
|
||||
return "\n".join(lines[:table.header] + header + rows + lines[table.start + len(table.rows):])
|
||||
|
||||
|
||||
def notes(items: list[Item], shape: Shape) -> 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))]
|
||||
return Ranked(ranked, under_bar, dropped, scoring.old_shape)
|
||||
return ([RESHAPE] if shape is OLD_SHAPE else []) + dropped
|
||||
|
||||
|
||||
def blocked_through(id_: int, items: list[Item]) -> set[int]:
|
||||
@@ -238,11 +247,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, old_shape: bool) -> Scoring | Failure:
|
||||
def read_scoring(text: str, lines: list[str], readme: str, shape: Shape) -> Scoring | Failure:
|
||||
goals = readme_goals(readme)
|
||||
if isinstance(goals, Failure):
|
||||
return goals
|
||||
formula = parse_formula(stated(text, "Score"), OLD_VARIABLES if old_shape else VARIABLES)
|
||||
formula = parse_formula(stated(text, "Score"), variables(shape))
|
||||
if isinstance(formula, Failure):
|
||||
return formula
|
||||
bar = number(stated(text, "Bar"), "the bar")
|
||||
@@ -252,7 +261,7 @@ def read_scoring(text: str, lines: list[str], readme: str, old_shape: bool) -> S
|
||||
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")
|
||||
numbers = [number for number, _ in goals]
|
||||
if old_shape:
|
||||
if shape is 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")
|
||||
@@ -260,11 +269,13 @@ def read_scoring(text: str, lines: list[str], readme: str, old_shape: bool) -> S
|
||||
weights = achieve_weights(goals)
|
||||
if isinstance(weights, Failure):
|
||||
return weights
|
||||
return Scoring(formula, bar, int(next_id), numbers, weights, old_shape)
|
||||
return Scoring(shape, formula, bar, int(next_id), numbers, weights)
|
||||
|
||||
|
||||
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")
|
||||
@@ -273,17 +284,24 @@ def read_table(lines: list[str]) -> Table | Failure:
|
||||
# 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 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 unknown_columns(table) or outside_items(lines, table) or table
|
||||
|
||||
|
||||
def unknown_columns(table: Table) -> 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."""
|
||||
known = shape_of(table.columns).columns
|
||||
unknown = [column for column in table.columns if column not in known]
|
||||
if old := [column for column in unknown if column in OLD_SHAPE.columns]:
|
||||
return Failure(f"todo.md's items table has the column {', '.join(old)}, a column of the old shape, which {MOVES} replaced; drop it")
|
||||
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(known)}. Rename it, or move this machine to the release that added it")
|
||||
return outside_items(lines, table) or table
|
||||
return None
|
||||
|
||||
|
||||
def read_items(table: Table, scoring: Scoring) -> list[Item] | Failure:
|
||||
items = []
|
||||
for row in table.rows:
|
||||
item = parse_item(row, scoring, table.columns)
|
||||
item = parse_item(row, scoring, table)
|
||||
if isinstance(item, Failure):
|
||||
return item
|
||||
items.append(item)
|
||||
@@ -365,18 +383,18 @@ def check_citations(items: list[Item], decisions: str) -> Failure | None:
|
||||
return None
|
||||
|
||||
|
||||
def readme_goals(readme: str) -> list[tuple[str, str | None]] | Failure:
|
||||
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, str | None]] = []
|
||||
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), mark or None))
|
||||
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")
|
||||
@@ -385,7 +403,7 @@ def readme_goals(readme: str) -> list[tuple[str, str | None]] | Failure:
|
||||
return goals
|
||||
|
||||
|
||||
def achieve_weights(goals: list[tuple[str, str | None]]) -> dict[str, float] | Failure:
|
||||
def achieve_weights(goals: list[tuple[str, Mark]]) -> 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")
|
||||
@@ -450,6 +468,7 @@ def evaluate(node: ast.AST, values: dict[str, float]) -> float:
|
||||
divisor = evaluate(right, values)
|
||||
return evaluate(left, values) / divisor if divisor else math.nan
|
||||
case ast.BinOp(left, ast.Pow(), right):
|
||||
# Caught in place of checking first: a negative base with a fractional exponent, zero to a negative power and an overflow each raise, and three checks would read worse than one catch.
|
||||
try:
|
||||
return math.pow(evaluate(left, values), evaluate(right, values))
|
||||
except (OverflowError, ValueError):
|
||||
@@ -457,12 +476,18 @@ def evaluate(node: ast.AST, values: dict[str, float]) -> float:
|
||||
return math.nan
|
||||
|
||||
|
||||
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 the goal term score builds, W in OLD_SHAPE and V in the current shape."""
|
||||
return tuple(sorted({*shape.score_columns} - {"C"} | {"W" if shape is OLD_SHAPE else "V"}))
|
||||
|
||||
|
||||
def score(formula: ast.Expression, item: Item, scoring: Scoring) -> float | Failure:
|
||||
if scoring.old_shape:
|
||||
if scoring.shape is 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)}
|
||||
variables = {**item.scores, "W": max(scoring.weights[goal] for goal, _ in item.moves)}
|
||||
else:
|
||||
variables = {**item.scores, "V": sum(scoring.weights[goal] * move for goal, move in zip(item.goals, item.moves))}
|
||||
# Only an OLD_SHAPE item names a goal without a move.
|
||||
variables = {**item.scores, "V": sum(scoring.weights[goal] * (by or 0) for goal, by in item.moves)}
|
||||
value = evaluate(formula, variables)
|
||||
return value if math.isfinite(value) else Failure(f"the formula gives item {item.id} no finite score")
|
||||
|
||||
@@ -498,30 +523,26 @@ def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float] | Fail
|
||||
return weights
|
||||
|
||||
|
||||
def parse_item(row: str, scoring: Scoring, columns: tuple[str, ...]) -> Item | Failure:
|
||||
item = parse_row(row, columns)
|
||||
def parse_item(row: str, scoring: Scoring, table: Table) -> Item | Failure:
|
||||
item = parse_row(row, table)
|
||||
if isinstance(item, Failure):
|
||||
return item
|
||||
if scoring.old_shape:
|
||||
if unknown := [goal for goal in item.goals if goal not in scoring.weights]:
|
||||
if scoring.shape is OLD_SHAPE:
|
||||
if 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")
|
||||
return item
|
||||
for goal in item.goals:
|
||||
for goal, _ in item.moves:
|
||||
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, 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 render_item(item: Item, value: float, shape: Shape) -> str:
|
||||
"""The item's row, each cell under its column of shape."""
|
||||
written = {"ID": str(item.id), "Release": release_name(item), BLOCKED_BY: ", ".join(map(str, item.blocked_by)), "Exempt": item.exempt, "Item": item.tagline, **{name: str(item.scores[name]) for name in shape.score_columns}, shape.goals_column: shape.write_goals(item.moves), "Score": f"{value:.1f}"}
|
||||
return "| " + " | ".join(written[column] for column in shape.columns) + " |"
|
||||
|
||||
|
||||
def rank_details(text: str, items: list[Item]) -> str | Failure:
|
||||
|
||||
Reference in New Issue
Block a user