Answer the fourth round: citation check on its own, fences close on their own marker, atomic write, prose

This commit is contained in:
2026-10-02 21:54:06 +02:00
parent b712076144
commit 89c88b5163
6 changed files with 55 additions and 30 deletions
+36 -22
View File
@@ -46,8 +46,9 @@ A valid todo.md; ## Details and each item's detail are optional:
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 or written, 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, 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
--check finding the file unranked.
"""
import ast
import dataclasses
@@ -56,8 +57,9 @@ import pathlib
import re
import sys
# loop_claude's leaf modules, so both tools share one error type and one README parser.
# Kept inside loop_claude/ so reload's fingerprint covers them; this tool shares the error type and README parser.
from loop_claude.failure import Failure
from loop_claude.file_writes import replace_file
from loop_claude.project.premises import FENCE, sections
EXEMPTIONS = ("", "decision", "defect", "question", "security")
@@ -88,7 +90,7 @@ class Scoring:
@dataclasses.dataclass(frozen=True)
class Table:
"""Body rows of a markdown table, and the index of the first in the file's lines."""
"""Body rows of a markdown table, and the index of the first row in the file's lines."""
start: int
rows: list[str]
@@ -152,11 +154,8 @@ def read_all(todo: pathlib.Path) -> tuple[str, str, str] | Failure:
def write(path: pathlib.Path, text: str) -> Failure | None:
try:
path.write_text(text, encoding="utf-8")
except OSError as failure:
return Failure(f"{path}: {failure.strerror}")
return None
unwritten = replace_file(path, text.encode("utf-8"))
return Failure(f"{path}: {unwritten.reason}") if unwritten else None
def rank(text: str, readme: str, decisions: str) -> Ranked | Failure:
@@ -164,10 +163,12 @@ def rank(text: str, readme: str, decisions: str) -> Ranked | Failure:
scoring = read_scoring(text, lines, readme)
if isinstance(scoring, Failure):
return scoring
table = read_items(lines, scoring, decisions)
table = read_items(lines, scoring)
if isinstance(table, Failure):
return table
items, start = table
if uncited := check_citations(items, decisions):
return uncited
scored = []
for item in items:
value = score(scoring.formula, item, scoring.weights)
@@ -204,13 +205,12 @@ def read_scoring(text: str, lines: list[str], readme: str) -> Scoring | Failure:
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."""
def read_items(lines: list[str], scoring: Scoring) -> tuple[list[Item], int] | Failure:
"""The items, and the index of the first row in lines."""
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))]):
if stray_row(lines[table.start + len(table.rows):]):
return Failure("## Items holds a row outside its table; keep the rows together under the header")
items = []
for row in table.rows:
@@ -223,16 +223,28 @@ def read_items(lines: list[str], scoring: Scoring, decisions: str) -> tuple[list
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 stray_row(after: list[str]) -> bool:
"""Whether a table row follows the table before the next ## heading."""
section = after[:next((index for index, line in enumerate(after) if line.startswith("## ")), len(after))]
return any(line.startswith("|") for line in section)
def check_citations(items: list[Item], decisions: str) -> Failure | None:
"""Holds todo.md and docs/decisions.md to each other: a cited item is exempt, a decision row is cited."""
cited = set(cited_items(decisions))
if gone := sorted(cited - {item.id for item in items}):
return Failure(f"docs/decisions.md cites \"`todo.md` item {gone[0]}\", which todo.md no longer holds; revise that decision to say what holds now")
for item in sorted(items, key=lambda item: item.id):
if item.id in cited and not item.exempt:
return Failure(f"docs/decisions.md cites \"`todo.md` item {item.id}\"; mark it decision, or another reason the bar does not apply")
if item.exempt == "decision" and item.id not in cited:
return Failure(f"item {item.id} is marked decision, but docs/decisions.md does not cite \"`todo.md` item {item.id}\"; cite it there, or mark it with another reason the bar does not apply")
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."""
found = sections(readme).get("Goals", [])
@@ -266,6 +278,9 @@ def stated(text: str, name: str) -> str | Failure:
def parse_formula(source: str | Failure) -> 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.
if len(source) > 4 * LARGEST_FORMULA:
return Failure(f"the formula {source[:40]!r}... holds more than {4 * LARGEST_FORMULA} characters")
try:
tree = ast.parse(source, mode="eval")
except (SyntaxError, ValueError):
@@ -360,7 +375,6 @@ 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