From 89c88b51634138d3a60864ce054b5a87536b4b86 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 2 Oct 2026 21:54:06 +0200 Subject: [PATCH] Answer the fourth round: citation check on its own, fences close on their own marker, atomic write, prose --- CLAUDE.md | 2 +- bin/loop_claude/project/premises.py | 13 +++++-- bin/rank_todo.py | 58 ++++++++++++++++++----------- bin/test_loop_claude.py | 4 ++ bin/test_rank_todo.py | 6 +-- docs/decisions.md | 2 +- 6 files changed, 55 insertions(+), 30 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 07442560..9cbc2085 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -26,7 +26,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The - **A** — its value to the audience in `README.md` → `## Audience`. - **G** — its value to the goals it cites in the Goals column; W is the weight of the heaviest of them. - **An item scoring under the bar is deleted, with every item that needs it, and a finding under the bar is not filed.** The chunk's summary names each, with its score. -- **The Exempt cell keeps an item whatever its score:** `security` for a security finding, `defect` for a 🔴 finding, `question` for a question only the human can answer, `decision` for an item `docs/decisions.md` cites. +- **The Exempt cell keeps an item whatever its score:** `security` for a security finding, `defect` for a 🔴 finding, `question` for a question only the human can answer, `decision` for an item only `docs/decisions.md` keeps. An item `docs/decisions.md` cites carries one of these reasons. - Open each item with a bold one-sentence tagline, so the taglines alone say what a release holds. The tagline states the target state, checkable when done: an imperative verb plus what holds afterwards. A present-tense fact reads as the current state and says nothing about what to do. Add "today X" only where the direction is otherwise ambiguous. GOOD: `**Accept undefined in MetadataValue and drop such keys on output.**` BANNED: `MetadataValue accepts undefined; such keys are dropped on output`. - A security finding — a leaked credential, secret or PII, an auth bypass, an injection — is filed the moment it is found, under the next release, marked `security`, naming the exposure and the path it reaches. `rank_todo.py` ranks it first in its release. Never among additive or nice-to-have items, never only in a chunk's summary, and never as a question about where it belongs: file it, say you did, and I will unmark it if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius. - **Unless the project has a reason to differ, weigh goals by position, the first heaviest.** When the weights stop listing the README's goals, `rank_todo.py` fails and prints those weights. diff --git a/bin/loop_claude/project/premises.py b/bin/loop_claude/project/premises.py index 41768a5a..77b375eb 100644 --- a/bin/loop_claude/project/premises.py +++ b/bin/loop_claude/project/premises.py @@ -3,7 +3,7 @@ import re from loop_claude.stop import Stop -FENCE = re.compile(r"^ {0,3}(```|~~~)", re.M) +FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})", re.M) def read_premises(root: str) -> str | Stop: @@ -27,9 +27,16 @@ def read_premises(root: str) -> str | Stop: def sections(text: str) -> dict[str, list[str]]: blocks: list[tuple[str | None, list[str]]] = [] - fenced = False + opener = "" for line in text.splitlines(): - fenced ^= bool(FENCE.match(line)) + # A fence closes only on the opener's character, at least as long. + if fence := FENCE.match(line): + marker = fence.group(1) + if not opener: + opener = marker + elif marker[0] == opener[0] and len(marker) >= len(opener): + opener = "" + fenced = bool(opener or fence) if not fenced and line.startswith("## "): blocks.append((line.strip()[3:], [])) elif not fenced and line.startswith("# "): diff --git a/bin/rank_todo.py b/bin/rank_todo.py index c17b01c0..65541c5c 100755 --- a/bin/rank_todo.py +++ b/bin/rank_todo.py @@ -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 diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 53f38c5f..94320fd0 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -307,6 +307,10 @@ class Sections(unittest.TestCase): text = "# Title\n\nintro\n\n## Goals\n\n1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority\n\n## Empty\n\n## Audience\nme\n## Audience\nagain\n# Appendix\nnot audience\n" self.assertEqual(premises.sections(text), {"Goals": ["1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority"], "Empty": [""], "Audience": ["me", "again"]}) + def test_closes_a_fence_only_on_its_own_marker(self): + text = "## Goals\n````md\n~~~\n## Quoted\n```\n````\n ~~~\n## Also quoted\n ~~~\n1. one\n## Audience\nme\n" + self.assertEqual(list(premises.sections(text)), ["Goals", "Audience"]) + class Render(unittest.TestCase): def test_joins_assistant_text_and_tool_calls_and_human_turns_and_skips_the_rest(self): diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py index 6731d81d..1f967e48 100644 --- a/bin/test_rank_todo.py +++ b/bin/test_rank_todo.py @@ -76,7 +76,7 @@ class Rank(unittest.TestCase): def test_holds_each_item_a_decision_cites_and_says_how_to_settle_a_finished_one(self): self.assertIsInstance(self.ranked(decisions=DECISIONS + "Until `todo.md` item 4 lands.\n"), rank_todo.Ranked) gone = self.ranked(TODO.replace("| 5 | 0.1.0 | decision | **Move the writes out.** | 5 | 5 | 4 | 5 | 2.1 | 0 |\n", "")) - self.assertEqual(gone.reason, "docs/decisions.md cites todo.md item 5, which todo.md no longer holds; revise that decision to say what holds now") + self.assertEqual(gone.reason, "docs/decisions.md cites \"`todo.md` item 5\", which todo.md no longer holds; revise that decision to say what holds now") def test_names_each_item_under_the_bar_that_is_not_exempt(self): ranked = self.ranked(TODO.replace("`Bar = 9`", "`Bar = 11`")) @@ -93,7 +93,7 @@ class Rank(unittest.TestCase): self.assertIn("| 1 | 1.00 |\n| 2 | 0.75 |\n| 2.1 | 0.50 |\n| 3 | 0.25 |", failure.reason) def test_refuses_a_formula_that_is_more_than_arithmetic_over_the_scores(self): - for formula in ("__import__('os')", "R.real", "X + 1", "R ** 2", "R +", "R / (S - 2)", "R\x00", "1" * 400, " + ".join(["R"] * 300)): + for formula in ("__import__('os')", "R.real", "X + 1", "R ** 2", "R +", "R / (S - 2)", "R\x00", "1" * 400, " + ".join(["R"] * 300), "-" * 100000 + "R"): with self.subTest(formula=formula): self.assertIsInstance(self.ranked(TODO.replace("-R - S/4 + 2*A + 2*G*W", formula)), Failure) @@ -107,7 +107,7 @@ class Rank(unittest.TestCase): "| 5 | 0.1.0 | decision |": "| 5 | 0.1.0 | |", "`Next ID = 6`": "`Next ID = 5`", "`Next ID = 6`\n": "`Next ID = 6.5`\n", - "| 4 | 0.1.0 | security |": "| 4 | 0.1.0 | decision |", + "| 4 | 0.1.0 | security | **Rotate": "| 4 | 0.1.0 | decision | **Rotate", "Fast detail.": "```\n## Goals\n```", "### 3. Make it fast.": "### 7. Make it fast.", "`Bar = 9`": "`Bar = nan`", diff --git a/docs/decisions.md b/docs/decisions.md index 9fb679da..8ccd9dd9 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -78,4 +78,4 @@ ## todo.md: one table of items scored by the formula and goal weights it states, held to its bar, ranked by `bin/rank_todo.py` -2026-10-02, lilleman. Serves goal 4: findings were filed faster than chunks closed them, so the plan grew without telling what mattered. Each item is scored as `CLAUDE.md` → "Todo items" says; this repo's formula counts value highest and size least. An item under the bar is not kept; this repo's bar started at 10 and was set to 9 the same day, purging the 17 items under it. An Exempt cell keeps a row past the bar where a rule needs it kept. lilleman retired the two decisions whose plans the purge removed: the stats line in the transcript archive, and three benches before a workflow change merges. A finding under the bar is recorded nowhere, so a later review may raise it again and the run rescores it: one score's cost, where a ledger of dropped findings would regrow the list the bar caps. `rank_todo.py --check` is part of larv-review's gate, since only a check keeps the stored Score from going stale. The format is mandatory in every project, as the premises are (goal 4.3); the formula, bar and weights are each project's own. A script ranks the table so a re-rank after each addition or edit is deterministic and cheap. Valid while one human sets the bar and reads the ranking. +2026-10-02, lilleman. Serves goal 4: findings were filed faster than chunks closed them, so the plan grew without telling what mattered. Each item is scored as `CLAUDE.md` → "Todo items" says; this repo's formula counts value highest and size least. An item under the bar is not kept; this repo's bar started at 10 and was set to 9 the same day, purging the 17 items under it. An Exempt cell keeps a row past the bar where a rule needs it kept. lilleman retired the two decisions whose plans the purge removed: the stats line in the transcript archive, and three benches before a workflow change merges. A finding under the bar is recorded nowhere, so a later review may raise it again, and the run rescores it. That costs one scoring; a ledger of dropped findings would regrow the list the bar caps. larv-review's Round cap rule 5 counts a finding named under the bar as settled, so one raised again holds no pass open. `rank_todo.py --check` is part of larv-review's gate, since only a check keeps the stored Score from going stale. The format is mandatory in every project, as the premises are (goal 4.3); the formula, bar and weights are each project's own. A script ranks the table so a re-rank after each addition or edit is deterministic and cheap. Valid while one human sets the bar and reads the ranking.