From c12a4109f9e5efe489f1cfc2421f18fa12505843 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 2 Oct 2026 19:38:31 +0200 Subject: [PATCH 1/7] Score and rank todo.md in one table by the formula, bar and goal weights it states --- .gitignore | 1 + AGENTS.md | 1 + CHANGELOG.md | 1 + CLAUDE.md | 14 ++- README.md | 1 + bin/rank_todo.py | 239 ++++++++++++++++++++++++++++++++++++ bin/test_rank_todo.py | 105 ++++++++++++++++ bin/test_types.py | 2 +- docs/decisions.md | 4 + skills/larv-review/SKILL.md | 2 +- todo.md | 171 ++++++++++++++++---------- 11 files changed, 473 insertions(+), 68 deletions(-) create mode 100755 bin/rank_todo.py create mode 100644 bin/test_rank_todo.py diff --git a/.gitignore b/.gitignore index da30a316..d1c867d8 100644 --- a/.gitignore +++ b/.gitignore @@ -21,6 +21,7 @@ !bin/loop_claude/ !bin/loop_claude/**/ !bin/loop_claude/**/*.py +!bin/rank_todo.py !bin/statusline.py !bin/test_*.py !docs/ diff --git a/AGENTS.md b/AGENTS.md index f2130607..c6a18497 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,6 +22,7 @@ Decisions live in `docs/decisions.md`: - review: `/security-review` is the security pass of record - review: the premises chunk's whole review is the human's approval - workflow-bench/: the remote may show the bench cases' names and commit SHAs +- todo.md: one table of items scored by the formula, bar and goal weights it states, ranked by `bin/rank_todo.py` ## Scoring run diff --git a/CHANGELOG.md b/CHANGELOG.md index 805952a2..1ac7aaf8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- `bin/rank_todo.py` scores and ranks a project's `todo.md`: one table of items, each scored by the formula, bar and goal weights the file states; it exits 1 on an item under the bar, and `--check` also on an unranked file. - Run `loop-claude` only in a sandbox with no direct access to production: every claude it starts skips every permission prompt. - First release: `README.md` states what the checkout holds and needs, `loop-claude --help` what `loop-claude` does. - `settings.json`, the agents and the status line run unedited on any machine with README → Install's prerequisites; the status line shows reset times in the machine's own time zone. diff --git a/CLAUDE.md b/CLAUDE.md index a8bed7b3..264f8e9a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -7,18 +7,26 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The - **Until `README.md` has a `## Goals` and an `## Audience` section, writing them is the only work.** Not even planning in `todo.md`. Both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count. - **Goals** are the project's aims, not promises: one line each, in priority order, like slogans — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal rarely names an implementation; how a goal is met goes further down the README and names the goal it serves. - **Audience** names who depends on the project and what they may rely on. -- **Plan `todo.md` by semver release:** every item sits under the release that ships it. If `todo.md` has another shape, reshaping it is the chunk, and the human approves it. +- **Plan `todo.md` as one scored table** ("Todo items"): every item names the release that ships it. If `todo.md` has another shape, reshaping it is the chunk, and the human approves it. - **When the next release has no items and no work has landed towards it, plan it as this chunk.** Weigh the unscheduled items against the goals, put them in order, and get the human's approval before writing any code. - **When the next release has no items left and work has landed towards it, it is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix lands, into that release; never start a later release's items or plan a new one. - **Open every chunk with one line:** the last version cut, what is unreleased (`CHANGELOG.md` → `## Unreleased`, or else the log since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once. -- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: one PR title states what they achieve together, without listing them; they sit under one release; and they fire the same review passes (`larv-review` §3). Tiny items, a few lines of change each, need neither a shared purpose nor the same passes: bundle up to ten from one release into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`, under a release. +- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: one PR title states what they achieve together, without listing them; they sit under one release; and they fire the same review passes (`larv-review` §3). Tiny items, a few lines of change each, need neither a shared purpose nor the same passes: bundle up to ten from one release into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`, scored, unless it scores under the bar. - **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in a comment at the one place it governs, or in `docs/decisions.md` once made in more than one place. If an answer is a goal and something else too, write the goal, and record a choice only for what the goal leaves open. - **Ship every chunk with `/larv-review`.** -- **Remove a finished item from `todo.md`; keep its release heading until the version is cut.** If the repo publishes something others consume — a package, an image, an API — reword the line for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete the line; git history is the record. +- **Remove a finished item's row and detail from `todo.md`.** If the repo publishes something others consume — a package, an image, an API — reword the item for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete it; git history is the record. - **Releases are the human's.** The version bump and the publishing credentials are theirs, whatever another rule says. Prepare everything else, so cutting a release is one decision. - **Releases follow semver read strictly** (`~/.claude/principles/technical-principles.md`). ### Todo items (`todo.md`, tickets, plans) +- **`todo.md` is mandatory in every project, in one shape**, which `~/.claude/bin/rank_todo.py` checks and ranks (its `--help` states the format): `## Scoring` holds the formula, the bar and the goal weights; `## Items` is one table of every item; `## Details` holds each item's detail under its ID. The formula, bar and weights are the project's own to tune. +- **Score an item when it is filed or edited, then run `rank_todo.py`.** A deletion needs no run. Each score is a whole number from 1 to 10: + - **R** — the risk that the change creates serious bugs or issues. + - **S** — the size of the change. + - **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 not kept:** a finding under it is named in the chunk's summary, not filed, and an item that falls under it is deleted. +- **Goal weights default to position:** W = (n + 1 − p) / n for the goal on line p of n numbered goals and sub-goals under `## Goals`. `rank_todo.py` prints that table whenever the weights stop listing the README's goals. - Open each item with a bold one-sentence tagline, so the taglines alone say what a release holds; detail follows it. 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, at the top of the list under its own `## Security` heading, naming the exposure and the path it reaches. 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 move it down if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius. diff --git a/README.md b/README.md index 9ba08ac4..1d415ab6 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, and tag that co ## Tools - `loop-claude ` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract. +- `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`; `rank_todo.py --help` states the format. - `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it. Test on the host, with `uv` on `PATH` to fetch mypy and the Python version Install names (`docs/decisions.md` → `bin/`): `python3 -m unittest discover -s bin -p 'test_*.py'` diff --git a/bin/rank_todo.py b/bin/rank_todo.py new file mode 100755 index 00000000..e16449f9 --- /dev/null +++ b/bin/rank_todo.py @@ -0,0 +1,239 @@ +#!/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 = ` under ## Scoring, sorts the ## Items table by release, then score from highest, +then ID, and orders ## Details to match, each heading `### . `. --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 scores under the `Bar = ` it states, or --check finds it unranked. +""" +import ast +import dataclasses +import pathlib +import re +import sys + +ITEMS_HEADER = "| ID | Release | 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] + 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, Malformed) as failure: + print(f"{todo}: {getattr(failure, 'strerror', None) or 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 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, -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 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"^( *)(\d+)\. ", section.group(1), 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") + 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. + return evaluate(formula, {**item.scores, "W": max(weights[goal] for goal in item.goals)}) + + +def number(text: str, what: str) -> float: + try: + return float(text) + except ValueError: + raise Malformed(f"{what} {text!r} is not a number") from None + + +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 cells(row: str, count: int) -> list[str]: + found = [cell.strip() for cell in re.split(r"(? Item: + id_, release, tagline, r, s, a, g, goals, _ = cells(row, 9) + if not id_.isdigit() 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 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 value.isdigit() 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), 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.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) + parts = re.split(r"^### (\d+)\. [^\n]*\n", body, flags=re.M) + if parts[0].strip(): + raise Malformed("## Details holds text before its first ### . 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:])) diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py new file mode 100644 index 00000000..2ca7a817 --- /dev/null +++ b/bin/test_rank_todo.py @@ -0,0 +1,105 @@ +import pathlib +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +import rank_todo +from test_python_floor import ROOT + +README = "# P\n\n## Goals\n\n1. Fast.\n2. Correct.\n 1. Tested.\n\n## Audience\n\nMe.\n" + +TODO = """# todo + +## Scoring + +`Score = -R - S/4 + 2*A + 2*G*W` + +`Bar = 9` + +| Goal | W | +|---|---| +| 1 | 1.00 | +| 2 | 0.67 | +| 2.1 | 0.33 | + +## Items + +| ID | Release | Item | R | S | A | G | Goals | Score | +|---|---|---|---|---|---|---|---|---| +| 1 | 0.2.0 | **Ship the later thing.** | 1 | 1 | 9 | 9 | 1 | 0 | +| 2 | 0.1.0 | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 | +| 3 | 0.1.0 | **Make it fast.** | 3 | 8 | 6 | 8 | 2.1, 1 | 0 | + +## Details + +### 1. stale heading + +Later detail. + +### 3. Make it fast. + +Fast detail. +""" + + +class Rank(unittest.TestCase): + def ranked(self, todo=TODO, readme=README): + return rank_todo.rank(todo, rank_todo.readme_goals(readme)) + + def test_scores_and_sorts_by_release_then_score_and_orders_the_details_to_match(self): + text, under_bar = self.ranked() + self.assertIn("""| 3 | 0.1.0 | **Make it fast.** | 3 | 8 | 6 | 8 | 2.1, 1 | 23.0 | +| 2 | 0.1.0 | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 10.3 | +| 1 | 0.2.0 | **Ship the later thing.** | 1 | 1 | 9 | 9 | 1 | 34.8 | +""", text) + self.assertTrue(text.endswith("## Details\n\n### 3. Make it fast.\n\nFast detail.\n\n### 1. Ship the later thing.\n\nLater detail.\n")) + self.assertEqual(under_bar, []) + self.assertEqual(self.ranked(text), (text, [])) + + def test_names_each_item_under_the_bar(self): + _, under_bar = self.ranked(TODO.replace("`Bar = 9`", "`Bar = 11`")) + self.assertEqual(under_bar, ["item 2 scores 10.3, under the bar 11; rescore it or delete it"]) + + def test_reads_goals_and_sub_goals_in_reading_order(self): + self.assertEqual(rank_todo.readme_goals(README), ["1", "2", "2.1"]) + + def test_prints_the_positional_weights_when_they_stop_listing_the_readmes_goals(self): + with self.assertRaises(rank_todo.Malformed) as raised: + self.ranked(readme=README.replace(" 1. Tested.", " 1. Tested.\n3. Small.")) + self.assertIn("| 1 | 1.00 |\n| 2 | 0.75 |\n| 2.1 | 0.50 |\n| 3 | 0.25 |", str(raised.exception)) + + 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 +"): + with self.subTest(formula=formula), self.assertRaises(rank_todo.Malformed): + self.ranked(TODO.replace("-R - S/4 + 2*A + 2*G*W", formula)) + + def test_refuses_a_row_or_detail_off_the_format(self): + broken = { + "| 2 | 0.1.0 | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 |": "| 2 | 0.1 | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 |", + "| 3 | 0.1.0 | **Make it fast.** | 3 | 8 | 6 | 8 | 2.1, 1 | 0 |": "| 3 | 0.1.0 | Make it fast. | 3 | 11 | 6 | 8 | 7 | 0 |", + "### 3. Make it fast.": "### 4. Make it fast.", + "`Bar = 9`": "", + } + for old, new in broken.items(): + with self.subTest(new=new), self.assertRaises(rank_todo.Malformed): + self.ranked(TODO.replace(old, new)) + + +class Main(unittest.TestCase): + def test_ranks_the_file_in_place_and_check_writes_nothing(self): + with tempfile.TemporaryDirectory() as temp: + todo = pathlib.Path(temp, "todo.md") + todo.write_text(TODO) + pathlib.Path(temp, "README.md").write_text(README) + self.assertEqual(rank_todo.main(["--check", str(todo)]), 1) + self.assertEqual(todo.read_text(), TODO) + self.assertEqual(rank_todo.main([str(todo)]), 0) + self.assertEqual(rank_todo.main(["--check", str(todo)]), 0) + + +class ThisRepo(unittest.TestCase): + def test_todo_md_is_ranked_with_nothing_under_the_bar(self): + text = (ROOT / "todo.md").read_text(encoding="utf-8") + self.assertEqual(rank_todo.rank(text, rank_todo.readme_goals((ROOT / "README.md").read_text(encoding="utf-8"))), (text, [])) diff --git a/bin/test_types.py b/bin/test_types.py index 8e2c84dc..ccb3160f 100644 --- a/bin/test_types.py +++ b/bin/test_types.py @@ -11,5 +11,5 @@ class Types(unittest.TestCase): self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`") if shutil.which("uv") is None: self.fail("uv on PATH fetches mypy; see README.md's Test line") - ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "-m", "statusline", "-p", "loop_claude"], capture_output=True, cwd=ROOT / "bin", text=True) + ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "-m", "rank_todo", "-m", "statusline", "-p", "loop_claude"], capture_output=True, cwd=ROOT / "bin", text=True) self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr) diff --git a/docs/decisions.md b/docs/decisions.md index 99a5a2e4..c3463c55 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -83,3 +83,7 @@ ## workflow-bench/: the remote may show the bench cases' names and commit SHAs 2026-10-02, lilleman. Serves goal 3, which keeps credentials, transcripts and memory files off the remote; a private project's name and commit ids are none of those. Valid while the bench names only cases and commits, never their code or results. + +## todo.md: one table of items scored by the formula, bar and goal weights it states, 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 scores R (the risk the change creates serious bugs), S (size), A (value to the audience) and G (value to its goals, weighted by goal position); this repo's formula, `-R - S/4 + 2*A + 2*G*W`, 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. 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. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 69b0aac6..3d0ee43c 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -61,7 +61,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Findings.** -1. A finding outside the chunk's change is filed in `todo.md`, under a release, whatever its pass or severity. A verified security HIGH is handled per "Security". +1. A finding outside the chunk's change, whatever its pass or severity, is scored per `~/.claude/CLAUDE.md` → "Todo items" and filed in `todo.md`, unless it scores under the bar; the summary names each one left out, with its score. A verified security HIGH is handled per "Security". 2. A fix that would change a goal, or a decision the repo held before the chunk began, is asked; no user reachable → filed, the goal or decision left as is. 3. A 🔴 is fixed, or shown factually wrong, and what disproved it recorded per `~/.claude/CLAUDE.md` → "Decisions: one home, each linked to a goal or a technical principle": in a comment at the code the finding concerns, or in `docs/decisions.md` when it concerns more than one place. Never declined. 4. A 🟡 is fixed, shown factually wrong like a 🔴, or declined. Decline one only where the reason is sound, consistent with the goals and the technical principles, and confidence is very high; the decline and its reason are recorded the same way. A reason neither speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess"; no user reachable → fix. Never drop one silently, and never decline one for convenience or the size of the fix. diff --git a/todo.md b/todo.md index f6d2279c..36df251a 100644 --- a/todo.md +++ b/todo.md @@ -1,66 +1,111 @@ # todo -## 0.1.0 +## Scoring -- **Copy the transcript archive off the machine, or say in README how it is backed up.** It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost disk loses every unattended run's record. Back it up only to a destination private to me and encrypted at rest: the worker runs with permissions bypassed, so the archived tool results can hold credentials it read. Goals 2 and 3. -- **Add a test that `.gitignore` keeps credentials, transcripts and memory files out.** `test_gitignore.py` checks only that every tracked file is allowlisted; a widened negation such as `!*.json` would un-ignore `.credentials.json`. Goal 3. -- **Wait out a usage limit and retry however long it lasts, without counting it as a failed run.** Today a worker or judge that hits a usage limit fails three times a minute apart, and the loop exits 1, so an unattended loop dies at every limit. The transcript line Claude Code writes for it, marked `"error":"rate_limit"`, holds the reset time: `You've hit your session limit · resets 7:40pm (Europe/Stockholm)`. Sleep until 2 minutes past it. The judge runs without a transcript, so find what its JSON reply carries on a limit. Where no reset time can be read, retry every 10 minutes: a retry before the reset fails (https://platform.claude.com/docs/en/api/rate-limits), so polling sooner only spends requests. Print when the next try is due, and update `--help`'s exit 1. Goal 4. -- **Name each chunk's archive folder by the chunk's start time, so `/` lists chunks in the order they ran.** Today the folder is the SHA-256 of the transcript's first timestamped line, which tells the human nothing; that line carries the start time. Drop the fallback to the first line, which every chunk of a project shares, and give the tests' fake transcripts ISO timestamps. Goal 2. -- **Key a project on its checkout's full path, and refuse to start while another session uses that key.** The key names the project's session, archive folder and models entry. `project_key` drops the leading `/`, so `~/code/a` and `/a` share all three, and one loop can resume or delete the other's session. Goal 4.1. -- **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost. Goal 4.1. -- **Give the judge the project's recorded decisions, and ask it whether anything the project records settles a choice.** Today it reads only the README's Goals and Audience (`premises.py`) and cannot see an answer recorded in `docs/decisions.md` or `AGENTS.md`, so it can interrupt the human again for a question already answered. Revise the decision "loop-claude: a judge decides each interrupt from the transcript and the README's premises; the worker's own account of which goal settles a choice decides nothing" to match. Goal 4.2. -- **Judge a cycle on more than the transcript's last 40,000 characters.** `judge_prompt` cuts the transcript there. The session spans every cycle of the chunk, so a decision made early in a long run is never judged, and the human is not interrupted for it. Larger chunks make runs longer. Goal 4.2. -- **Give principles-auditor and prose-reviewer a way to list the project's files.** In the 2026-09-30 audit run their `tools: Read, Grep, Glob` gave them only Read. Each read the files that imports and `.gitignore` named, and listed the files it could not reach. Goal 4.1. -- **Give the reviewer agents only the tools they need.** `systems-architect.md`, `product-owner-reviewer.md` and `stability-reviewer.md` have no `tools:` line, so each can edit the branch it reviews; `review-findings.md` says a reviewer edits nothing. Goal 4.1. -- **Measure test coverage in the suite, and fail on a drop.** Nothing measures it, so "Test coverage should not decline" cannot be held. Goal 4.1. -- **Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.** The repo has no CI, so larv-review's gate is the local run, and larv-review's Gate skips even that when the last stability round left the suite green: an unattended chunk can merge on the worker's own word. Goal 4.1. -- **Make larv-review §3 applicable on its own, cite its rules by name, and say where a pass's round count is recorded.** Applying one rule of "Round cap", "Re-entry" or "Findings" takes `review-findings.md`, `CLAUDE.md` → "Vocabulary" and the decision log open beside it. The rules cite each other by number ("Round cap" rule 6), so a renumbering breaks a citation silently. Nothing says where a pass's round count is recorded, so a resumed or compacted session loses it. Goal 4.1. -- **Read transcript and stream entries into typed values where they are read.** `read_transcript` and `run_worker` pass raw `dict`s, so about ten accessors in `entries.py` re-check shapes deep inside and mypy cannot check `render`, `human_turns` or `run_worker`. Goal 4.1. -- **Inject output and storage into `Effects`, and test what each step prints.** `print` and `open` are called directly across `bin/loop_claude/`, so the stderr lines of the CLI contract can be checked only through the black-box tests. Goal 4.1. -- **Move the judge's transcript rendering from `claude_code/transcript.py` into `cycle/`.** `render`, `part_line` and `JUDGED_TOOL_INPUT` shape what the judge sees, so what the judge sees is shaped in two packages: those three in `claude_code/`, and `JUDGED_TRANSCRIPT_TAIL` in `cycle/judge.py`; and `claude_code/` no longer holds only Claude Code's shapes as its docstring says. Goal 4.1. -- **Make `JUDGE_RULES` and the Claude Code flags `loop-claude` passes readable without `CLAUDE.md` or Claude Code's docs open.** The 2026-10-02 scoring runs on PR #191 named both under Self-sufficiency: the judge's rules use "chunk" and "a release ready to cut" from `CLAUDE.md` with no link, and `--resume`, `--session-id`, `--no-session-persistence`, `--json-schema` and stream-json's result event go unexplained in `worker.py` and `judge.py`. Goal 4.1. -- **Encode, decode and check the reload handover in `loop/reload.py` alone.** `reload.py` encodes `LoopRun` and decodes it, but `main.py`'s `loop_run_from` checks the decoded fields and words the error, so changing `LoopRun`'s fields means editing both files. The 2026-10-02 scoring runs on PR #191 named it under Locality. Goal 4.1. -- **Give each cycle phase one name across its state, step and event.** Today `Judging` runs `rule` and yields `Ruled`, and `Closing` runs `close`, which also deletes a finished chunk's session, and yields `Archived`. Goal 4.1. -- **Enable the `claude-security` plugin in `settings.json`, or drop larv-review's full-scan row.** No machine has it enabled, so every chunk that fires the pass skips it. Goal 4.1. -- **Give `settings.json`'s model one writer, and sort its keys.** Claude Code rewrites `"model"` in this tracked file whenever a model is picked, so one `/model` dirties the checkout and overrides the synced choice. Goal 4.3. -- **Say in `systems-architect.md` that a REST API's `/v1/` prefix is not versioning machinery to defer.** Its "defer the versioning story" can be read against `principles/rest-apis.md`, which requires the prefix from the start. Goal 4.3. -- **Launch a principles auditor only for a principles file the project shows applies, and rerun only the reviewer whose finding a fix answers.** On this repo the frontend, REST and logging auditors each read the whole project to report "does not apply", and one 🟢 fix reruns ten whole-project reads. Goal 4.4. -- **Cut `systems-architect.md`'s, `stability-reviewer.md`'s and `product-owner-reviewer.md`'s descriptions to one line.** Claude Code loads every agent description into every session; larv-review launches these agents by name, so their worked examples cost tokens in every project and buy nothing. Goal 4.4. -- **Record each finished chunk's cost and review numbers on one stats line.** Goal 4.4. - - Have `loop-claude` write the line to one file at the root of the transcript archive. The line names the project, the commit the chunk started from and the archived transcript's hash. It holds the worker's tokens from the transcript, the judge's from its JSON output, and the chunk's cycles and interrupts, which the loop counts. - - End larv-review with a machine-readable summary, and have `loop-claude` copy it from the transcript onto the line: agents launched and rounds per pass; findings per pass by severity, inside the chunk's diff and outside it; and the comprehension scores when the panel ran. -- **Write a `workflow-review` skill that reads the stats and files each change it proposes to the workflow as a plan item, and have `AGENTS.md` run it on the chunk shipping a release's last item.** The workflow is `CLAUDE.md`, `principles/`, the skills, the agents and `loop-claude`. The skill's signals: findings outside the chunk's diff and comprehension scores per release, both from the stats; fixes after merge, from git; and the human's corrections, from the archived transcripts. Goal 4.4. -- **Bench about one chunk in ten against an open PR that changes the workflow, and have a blind claude rule which run better serves this repo's goal 4.** Redo the chunk under the PR, from the commit it started from. The ruling claude is not told which run is which. `loop-claude` picks the chunk at random, small diffs and big ones alike; with no such PR open, no bench runs. The same outcome with less code and prose, in the chunk or in the workflow, also counts as better. The PR merges only once three benches rule it better. A bench that rules it worse closes the PR and records, in `docs/workflow-learnings.md`, what the PR changed and why it lost. The ruling and both runs' numbers go on the chunk's stats line. Start from `workflow-bench/`, written for the 2026-09-30 bench's four fixed cases. Needs the stats line. Goals 4.1 and 4.4. -- **Make the small fixes filed by the 2026-10-02 principles audit against `workflow-bench/`.** The bench item above starts from `workflow-bench/`. Goals 2 and 4.1. - - Test `judge.py`'s `blind` and `bench.py`'s rate-limit parsing, and run mypy on both. - - Let `judge.py` import `bench` without `BENCH_SOURCES` set; today reading it at import raises a bare `KeyError`. - - Merge `CASES`, `PREFIX` and `TRUTH_END` into one table keyed by case, sorted. - - Report a failed `git` per run; today `check=True` aborts `main` and drops every other run's result. - - Take the model from a flag or env var, and inject the clock, sleep and shuffle. - - Keep the bench's run logs where the transcript archive's backup reaches them. -- **Make the small changes filed against the review's rules.** Goals 4.1 and 4.4. - - Make the contributor a standing member of every project's audience. A project drops them only where its `## Audience` says maintainability does not matter. State that in `CLAUDE.md`'s goals-and-audience rule, and have larv-review's comprehension floor name the contributor as the reader it serves. The floor then gates every chunk while the contributor stands, and a project that drops them skips it. -- **Make the small fixes filed by the 2026-10-01 principles audit against `bin/`.** Goal 4.1. - - Prefix each diagnostic `loop-claude` prints with its level, `warning:` at the least, so a run's output can be grepped for what needs fixing. - - Have `make_private` return a `Failure` like `replace_file` beside it. - - Check the catalog `name` in `newest_catalog_models` as well as `id`. - - Sort `worker_args`' flags and the globs in `model_catalog.py` and `session.py`. - - Write `"bypassPermissions"` once for every claude `loop-claude` starts. - - Keep the judge's evidence and model in each archived `.verdict.md`. - - Move the test helpers `ROOT` and `readme_floor` out of `test_python_floor.py`, which two other tests import them from, and have `test_citations.py` use that `ROOT`. -- **Make the small fixes filed by the 2026-10-02 principles audit against `bin/`.** Goal 4.1. - - Have `Session` carry the project key, so `Cycle` cannot hold a key and a session for different projects. - - Inject the black-box tests' sleep through `Effects.sleep`; today `SITECUSTOMIZE` swaps `time.sleep` in the child process. - - Return a `Failure` from `replace_file` when removing the staged file fails too. - - Say so when a catalog file cannot be read; today the prompt says no catalog is cached. - - Sort `transcript_file`'s glob, and delete a session's files under every project folder that holds its id. - - Warn when `git worktree list` fails; today `worktrees` falls back to the root alone in silence, and the interrupt lands in Claude Code's trust dialog with no line saying why. - - Show the judge's stderr when its `claude` exits 0; today `run_judge` drops it. - - Find Claude Code's files under `CLAUDE_CONFIG_DIR` when it is set; today `paths_from` reads `~/.claude` alone, so every cycle exits 1 with "claude left no transcript". - - Type `decode_handed` for `LoopRun`, its one caller's type, and drop the type variable `T`. -- **Allow stderr in `principles/logging.md` → "Infrastructure": OTLP, stdout or stderr.** A CLI keeps stdout for its output, as `loop-claude` does for the worker's stream; the rule's point is no log files. Goal 4.3. -- **Sort `bin/`'s imports on their first binding, and say in `principles/technical-principles.md` → "Deterministic order" how case sorts and which groups Python has.** Today they sort by path, so moving a module reorders unchanged lines. The principle's "host packages" names no Python group. Goal 4.1. -- **Clean up the rules, skills, agents, plan and decision log.** Goal 4.1. - - `docs/decisions.md`: order the entries and the `AGENTS.md` index by one key. - - `docs/decisions.md`: give the comprehension-floor entry a premise that has not expired. It says "Valid until the next scoring run", and every run since has passed it. Put the floor's rule first and its runs' scores in a table. - - `systems-architect.md`: cut the "one home" line, and break Reasonability Review's steps 4 and 5 into shorter points each. +`Score = -R - S/4 + 2*A + 2*G*W` + +`Bar = 9` + +| Goal | W | +|---|---| +| 1 | 1.00 | +| 2 | 0.89 | +| 3 | 0.78 | +| 4 | 0.67 | +| 4.1 | 0.56 | +| 4.2 | 0.44 | +| 4.3 | 0.33 | +| 4.4 | 0.22 | +| 4.5 | 0.11 | + +## Items + +| ID | Release | Item | R | S | A | G | Goals | Score | +|---|---|---|---|---|---|---|---|---| +| 1 | 0.1.0 | **Copy the transcript archive off the machine, or say in README how it is backed up.** | 3 | 5 | 8 | 9 | 2, 3 | 27.8 | +| 2 | 0.1.0 | **Add a test that `.gitignore` keeps credentials, transcripts and memory files out.** | 1 | 2 | 6 | 9 | 3 | 24.5 | +| 3 | 0.1.0 | **Wait out a usage limit and retry however long it lasts, without counting it as a failed run.** | 4 | 5 | 9 | 8 | 4 | 23.5 | +| 7 | 0.1.0 | **Give the judge the project's recorded decisions, and ask it whether anything the project records settles a choice.** | 3 | 4 | 8 | 8 | 4.2 | 19.0 | +| 9 | 0.1.0 | **Give principles-auditor and prose-reviewer a way to list the project's files.** | 1 | 2 | 5 | 7 | 4.1 | 16.3 | +| 8 | 0.1.0 | **Judge a cycle on more than the transcript's last 40,000 characters.** | 4 | 5 | 7 | 8 | 4.2 | 15.8 | +| 13 | 0.1.0 | **Make larv-review §3 applicable on its own, cite its rules by name, and say where a pass's round count is recorded.** | 3 | 5 | 6 | 7 | 4.1 | 15.6 | +| 23 | 0.1.0 | **Launch a principles auditor only for a principles file the project shows applies, and rerun only the reviewer whose finding a fix answers.** | 3 | 4 | 7 | 8 | 4.4 | 13.5 | +| 10 | 0.1.0 | **Give the reviewer agents only the tools they need.** | 1 | 1 | 4 | 6 | 4.1 | 13.5 | +| 21 | 0.1.0 | **Give `settings.json`'s model one writer, and sort its keys.** | 3 | 3 | 6 | 7 | 4.3 | 12.9 | +| 20 | 0.1.0 | **Enable the `claude-security` plugin in `settings.json`, or drop larv-review's full-scan row.** | 1 | 1 | 4 | 5 | 4.1 | 12.4 | +| 12 | 0.1.0 | **Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.** | 2 | 4 | 4 | 6 | 4.1 | 11.7 | +| 5 | 0.1.0 | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 5 | 5 | 5 | 6 | 4.1 | 10.5 | +| 4 | 0.1.0 | **Name each chunk's archive folder by the chunk's start time, so `/` lists chunks in the order they ran.** | 3 | 2 | 4 | 3 | 2 | 9.8 | +| 26 | 0.1.0 | **Write a `workflow-review` skill that reads the stats and files each change it proposes to the workflow as a plan item, and have `AGENTS.md` run it on the chunk shipping a release's last item.** | 2 | 6 | 5 | 6 | 4.4 | 9.1 | +| 29 | 0.1.0 | **Make the small changes filed against the review's rules.** | 2 | 2 | 3 | 5 | 4.1, 4.4 | 9.1 | +| 17 | 0.1.0 | **Make `JUDGE_RULES` and the Claude Code flags `loop-claude` passes readable without `CLAUDE.md` or Claude Code's docs open.** | 1 | 2 | 3 | 4 | 4.1 | 9.0 | + +## Details + +### 1. Copy the transcript archive off the machine, or say in README how it is backed up. + +It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost disk loses every unattended run's record. Back it up only to a destination private to me and encrypted at rest: the worker runs with permissions bypassed, so the archived tool results can hold credentials it read. + +### 2. Add a test that `.gitignore` keeps credentials, transcripts and memory files out. + +`test_gitignore.py` checks only that every tracked file is allowlisted; a widened negation such as `!*.json` would un-ignore `.credentials.json`. + +### 3. Wait out a usage limit and retry however long it lasts, without counting it as a failed run. + +Today a worker or judge that hits a usage limit fails three times a minute apart, and the loop exits 1, so an unattended loop dies at every limit. The transcript line Claude Code writes for it, marked `"error":"rate_limit"`, holds the reset time: `You've hit your session limit · resets 7:40pm (Europe/Stockholm)`. Sleep until 2 minutes past it. The judge runs without a transcript, so find what its JSON reply carries on a limit. Where no reset time can be read, retry every 10 minutes: a retry before the reset fails (https://platform.claude.com/docs/en/api/rate-limits), so polling sooner only spends requests. Print when the next try is due, and update `--help`'s exit 1. + +### 7. Give the judge the project's recorded decisions, and ask it whether anything the project records settles a choice. + +Today it reads only the README's Goals and Audience (`premises.py`) and cannot see an answer recorded in `docs/decisions.md` or `AGENTS.md`, so it can interrupt the human again for a question already answered. Revise the decision "loop-claude: a judge decides each interrupt from the transcript and the README's premises; the worker's own account of which goal settles a choice decides nothing" to match. + +### 9. Give principles-auditor and prose-reviewer a way to list the project's files. + +In the 2026-09-30 audit run their `tools: Read, Grep, Glob` gave them only Read. Each read the files that imports and `.gitignore` named, and listed the files it could not reach. + +### 8. Judge a cycle on more than the transcript's last 40,000 characters. + +`judge_prompt` cuts the transcript there. The session spans every cycle of the chunk, so a decision made early in a long run is never judged, and the human is not interrupted for it. Larger chunks make runs longer. + +### 13. Make larv-review §3 applicable on its own, cite its rules by name, and say where a pass's round count is recorded. + +Applying one rule of "Round cap", "Re-entry" or "Findings" takes `review-findings.md`, `CLAUDE.md` → "Vocabulary" and the decision log open beside it. The rules cite each other by number ("Round cap" rule 6), so a renumbering breaks a citation silently. Nothing says where a pass's round count is recorded, so a resumed or compacted session loses it. + +### 23. Launch a principles auditor only for a principles file the project shows applies, and rerun only the reviewer whose finding a fix answers. + +On this repo the frontend, REST and logging auditors each read the whole project to report "does not apply", and one 🟢 fix reruns ten whole-project reads. + +### 10. Give the reviewer agents only the tools they need. + +`systems-architect.md`, `product-owner-reviewer.md` and `stability-reviewer.md` have no `tools:` line, so each can edit the branch it reviews; `review-findings.md` says a reviewer edits nothing. + +### 21. Give `settings.json`'s model one writer, and sort its keys. + +Claude Code rewrites `"model"` in this tracked file whenever a model is picked, so one `/model` dirties the checkout and overrides the synced choice. + +### 20. Enable the `claude-security` plugin in `settings.json`, or drop larv-review's full-scan row. + +No machine has it enabled, so every chunk that fires the pass skips it. + +### 12. Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough. + +The repo has no CI, so larv-review's gate is the local run, and larv-review's Gate skips even that when the last stability round left the suite green: an unattended chunk can merge on the worker's own word. + +### 5. Key a project on its checkout's full path, and refuse to start while another session uses that key. + +The key names the project's session, archive folder and models entry. `project_key` drops the leading `/`, so `~/code/a` and `/a` share all three, and one loop can resume or delete the other's session. + +### 4. Name each chunk's archive folder by the chunk's start time, so `/` lists chunks in the order they ran. + +Today the folder is the SHA-256 of the transcript's first timestamped line, which tells the human nothing; that line carries the start time. Drop the fallback to the first line, which every chunk of a project shares, and give the tests' fake transcripts ISO timestamps. + +### 26. Write a `workflow-review` skill that reads the stats and files each change it proposes to the workflow as a plan item, and have `AGENTS.md` run it on the chunk shipping a release's last item. + +The workflow is `CLAUDE.md`, `principles/`, the skills, the agents and `loop-claude`. The skill's signals: findings outside the chunk's diff and comprehension scores per release, both from the stats; fixes after merge, from git; and the human's corrections, from the archived transcripts. + +### 29. Make the small changes filed against the review's rules. + +- Make the contributor a standing member of every project's audience. A project drops them only where its `## Audience` says maintainability does not matter. State that in `CLAUDE.md`'s goals-and-audience rule, and have larv-review's comprehension floor name the contributor as the reader it serves. The floor then gates every chunk while the contributor stands, and a project that drops them skips it. + +### 17. Make `JUDGE_RULES` and the Claude Code flags `loop-claude` passes readable without `CLAUDE.md` or Claude Code's docs open. + +The 2026-10-02 scoring runs on PR #191 named both under Self-sufficiency: the judge's rules use "chunk" and "a release ready to cut" from `CLAUDE.md` with no link, and `--resume`, `--session-id`, `--no-session-persistence`, `--json-schema` and stream-json's result event go unexplained in `worker.py` and `judge.py`. -- 2.52.0 From c0dba6625cc6265a4b38e67421b86b4b47fa8931 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 2 Oct 2026 20:04:19 +0200 Subject: [PATCH 2/7] Answer the architecture and stability reviews' first round: exempt rows, restored item 6, retired decisions --- AGENTS.md | 2 -- CLAUDE.md | 12 +++---- bin/rank_todo.py | 64 ++++++++++++++++++++++++++----------- bin/test_rank_todo.py | 46 ++++++++++++++++++-------- docs/decisions.md | 14 ++------ skills/larv-review/SKILL.md | 8 ++--- todo.md | 46 +++++++++++++------------- 7 files changed, 115 insertions(+), 77 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c6a18497..b53300a9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,8 +17,6 @@ Decisions live in `docs/decisions.md`: - loop-claude: a `claude` that cannot start is a failed worker run, retried - review: an ask no user answers leaves the PR unmerged - loop-claude: every claude it starts bypasses permissions inside its sandbox -- loop-claude: the planned stats line goes in the transcript archive, off the remote -- workflow changes: once the bench runs, a change merges only after three benches rule it better - review: `/security-review` is the security pass of record - review: the premises chunk's whole review is the human's approval - workflow-bench/: the remote may show the bench cases' names and commit SHAs diff --git a/CLAUDE.md b/CLAUDE.md index 264f8e9a..43af8b40 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,10 +5,10 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The *next release* is the earliest one not yet cut. Other words, such as *chunk*, are defined under "Vocabulary" at the end of this file. - **Until `README.md` has a `## Goals` and an `## Audience` section, writing them is the only work.** Not even planning in `todo.md`. Both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count. - - **Goals** are the project's aims, not promises: one line each, in priority order, like slogans — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal rarely names an implementation; how a goal is met goes further down the README and names the goal it serves. + - **Goals** are the project's aims, not promises: one numbered line each, in priority order, a sub-goal indented under its goal, like slogans — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal rarely names an implementation; how a goal is met goes further down the README and names the goal it serves. - **Audience** names who depends on the project and what they may rely on. - **Plan `todo.md` as one scored table** ("Todo items"): every item names the release that ships it. If `todo.md` has another shape, reshaping it is the chunk, and the human approves it. -- **When the next release has no items and no work has landed towards it, plan it as this chunk.** Weigh the unscheduled items against the goals, put them in order, and get the human's approval before writing any code. +- **When the next release has no items and no work has landed towards it, plan it as this chunk.** Move the highest-scoring items of later releases into it, and get the human's approval of that set before writing any code. - **When the next release has no items left and work has landed towards it, it is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix lands, into that release; never start a later release's items or plan a new one. - **Open every chunk with one line:** the last version cut, what is unreleased (`CHANGELOG.md` → `## Unreleased`, or else the log since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once. - **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: one PR title states what they achieve together, without listing them; they sit under one release; and they fire the same review passes (`larv-review` §3). Tiny items, a few lines of change each, need neither a shared purpose nor the same passes: bundle up to ten from one release into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`, scored, unless it scores under the bar. @@ -19,16 +19,16 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The - **Releases follow semver read strictly** (`~/.claude/principles/technical-principles.md`). ### Todo items (`todo.md`, tickets, plans) -- **`todo.md` is mandatory in every project, in one shape**, which `~/.claude/bin/rank_todo.py` checks and ranks (its `--help` states the format): `## Scoring` holds the formula, the bar and the goal weights; `## Items` is one table of every item; `## Details` holds each item's detail under its ID. The formula, bar and weights are the project's own to tune. +- **`todo.md` is mandatory in every project, in one shape**, which `~/.claude/bin/rank_todo.py` checks and ranks (its `--help` states the format): `## Scoring` holds the formula, the bar and the goal weights; `## Items` is one table of every item; `## Details` holds each item's detail under its ID. A new item takes the next unused ID, never a deleted one's; cite an item by its ID. The formula, bar and weights are the project's own to tune. - **Score an item when it is filed or edited, then run `rank_todo.py`.** A deletion needs no run. Each score is a whole number from 1 to 10: - **R** — the risk that the change creates serious bugs or issues. - **S** — the size of the change. - **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 not kept:** a finding under it is named in the chunk's summary, not filed, and an item that falls under it is deleted. -- **Goal weights default to position:** W = (n + 1 − p) / n for the goal on line p of n numbered goals and sub-goals under `## Goals`. `rank_todo.py` prints that table whenever the weights stop listing the README's goals. +- **An item scoring under the bar is not kept, unless its Exempt cell says why:** `security` for a security finding, `question` for a question only the human can answer, `decision` for an item a decision in `docs/decisions.md` names. Otherwise a finding under the bar is named in the chunk's summary, not filed, and an item that falls under it is deleted, together with any item that needs it. +- **Goal weights default to position, the first goal weighing most;** `rank_todo.py` prints that table whenever the weights stop listing the README's goals. - Open each item with a bold one-sentence tagline, so the taglines alone say what a release holds; detail follows it. 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, at the top of the list under its own `## Security` heading, naming the exposure and the path it reaches. 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 move it down if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius. +- A security finding — a leaked credential, secret or PII, an auth bypass, an injection — is filed the moment it is found, as a row marked `security`, which `rank_todo.py` ranks first in its release, naming the exposure and the path it reaches. 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 move it down if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius. ## Quality diff --git a/bin/rank_todo.py b/bin/rank_todo.py index e16449f9..ce9b0c92 100755 --- a/bin/rank_todo.py +++ b/bin/rank_todo.py @@ -4,20 +4,24 @@ 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 = ` under ## Scoring, sorts the ## Items table by release, then score from highest, -then ID, and orders ## Details to match, each heading `### . `. --check writes nothing -and fails when the file is not ranked as it would be. +`Score = ` 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 `### . `. +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 scores under the `Bar = ` it states, or --check finds it unranked. +an item that is not exempt scores under the `Bar = ` 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 -ITEMS_HEADER = "| ID | Release | Item | R | S | A | G | Goals | Score |" +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") @@ -26,6 +30,7 @@ VARIABLES = ("A", "G", "R", "S", "W") class Item: id: int release: tuple[int, int, int] + exempt: str tagline: str scores: dict[str, int] goals: tuple[str, ...] @@ -49,8 +54,8 @@ def main(argv: list[str]) -> int: 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, Malformed) as failure: - print(f"{todo}: {getattr(failure, 'strerror', None) or failure}", file=sys.stderr) + 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) @@ -70,13 +75,15 @@ def rank(text: str, goals: list[str]) -> tuple[str, list[str]]: 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, -pair[1], pair[0].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 round(value, 1) < bar] + 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 @@ -87,13 +94,15 @@ def readme_goals(readme: str) -> list[str]: raise Malformed("README.md has no ## Goals") goals: list[str] = [] path: list[tuple[int, str]] = [] - for indent, number in re.findall(r"^( *)(\d+)\. ", section.group(1), re.M): + 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 @@ -146,14 +155,20 @@ def evaluate(node: ast.AST, values: dict[str, float]) -> float: 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. - return evaluate(formula, {**item.scores, "W": max(weights[goal] for goal in item.goals)}) + 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: - return float(text) + value = float(text) except ValueError: - raise Malformed(f"{what} {text!r} is not a number") from None + 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]: @@ -181,6 +196,14 @@ def table_rows(lines: list[str], header: str) -> tuple[int, int]: 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"(? list[str]: def parse_item(row: str, weights: dict[str, float]) -> Item: - id_, release, tagline, r, s, a, g, goals, _ = cells(row, 9) - if not id_.isdigit() or int(id_) < 1: + 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 value.isdigit() or not 1 <= int(value) <= 10: + 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), tagline, scores, cited) + 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.tagline} | {scores} | {', '.join(item.goals)} | {value:.1f} |" + return f"| {item.id} | {release} | {item.exempt} | {item.tagline} | {scores} | {', '.join(item.goals)} | {value:.1f} |" def rank_details(text: str, items: list[Item]) -> str: @@ -219,6 +244,9 @@ def rank_details(text: str, items: list[Item]) -> str: 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 ### . heading") diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py index 2ca7a817..a49cf8d7 100644 --- a/bin/test_rank_todo.py +++ b/bin/test_rank_todo.py @@ -1,3 +1,5 @@ +import contextlib +import io import pathlib import sys import tempfile @@ -26,11 +28,12 @@ TODO = """# todo ## Items -| ID | Release | Item | R | S | A | G | Goals | Score | -|---|---|---|---|---|---|---|---|---| -| 1 | 0.2.0 | **Ship the later thing.** | 1 | 1 | 9 | 9 | 1 | 0 | -| 2 | 0.1.0 | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 | -| 3 | 0.1.0 | **Make it fast.** | 3 | 8 | 6 | 8 | 2.1, 1 | 0 | +| ID | Release | Exempt | Item | R | S | A | G | Goals | Score | +|---|---|---|---|---|---|---|---|---|---| +| 1 | 0.2.0 | | **Ship the later thing.** | 1 | 1 | 9 | 9 | 1 | 0 | +| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 | +| 3 | 0.1.0 | | **Make it fast, `a \| b`.** | 3 | 8 | 6 | 8 | 2.1, 1 | 0 | +| 4 | 0.1.0 | security | **Rotate the leaked key.** | 9 | 2 | 1 | 1 | 2.1 | 0 | ## Details @@ -41,6 +44,10 @@ Later detail. ### 3. Make it fast. Fast detail. + +## Notes + +Kept as written. """ @@ -50,11 +57,12 @@ class Rank(unittest.TestCase): def test_scores_and_sorts_by_release_then_score_and_orders_the_details_to_match(self): text, under_bar = self.ranked() - self.assertIn("""| 3 | 0.1.0 | **Make it fast.** | 3 | 8 | 6 | 8 | 2.1, 1 | 23.0 | -| 2 | 0.1.0 | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 10.3 | -| 1 | 0.2.0 | **Ship the later thing.** | 1 | 1 | 9 | 9 | 1 | 34.8 | + self.assertIn("""| 4 | 0.1.0 | security | **Rotate the leaked key.** | 9 | 2 | 1 | 1 | 2.1 | -6.8 | +| 3 | 0.1.0 | | **Make it fast, `a \\| b`.** | 3 | 8 | 6 | 8 | 2.1, 1 | 23.0 | +| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 10.3 | +| 1 | 0.2.0 | | **Ship the later thing.** | 1 | 1 | 9 | 9 | 1 | 34.8 | """, text) - self.assertTrue(text.endswith("## Details\n\n### 3. Make it fast.\n\nFast detail.\n\n### 1. Ship the later thing.\n\nLater detail.\n")) + self.assertTrue(text.endswith("## Details\n\n### 3. Make it fast, `a \\| b`.\n\nFast detail.\n\n### 1. Ship the later thing.\n\nLater detail.\n\n## Notes\n\nKept as written.\n")) self.assertEqual(under_bar, []) self.assertEqual(self.ranked(text), (text, [])) @@ -64,6 +72,9 @@ class Rank(unittest.TestCase): def test_reads_goals_and_sub_goals_in_reading_order(self): self.assertEqual(rank_todo.readme_goals(README), ["1", "2", "2.1"]) + self.assertEqual(rank_todo.readme_goals(README.replace(" 1.", "\t1.")), ["1", "2", "2.1"]) + with self.assertRaises(rank_todo.Malformed): + rank_todo.readme_goals(README.replace("2. Correct.", "1. Correct.")) def test_prints_the_positional_weights_when_they_stop_listing_the_readmes_goals(self): with self.assertRaises(rank_todo.Malformed) as raised: @@ -76,11 +87,16 @@ class Rank(unittest.TestCase): self.ranked(TODO.replace("-R - S/4 + 2*A + 2*G*W", formula)) def test_refuses_a_row_or_detail_off_the_format(self): + row = "| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 |" broken = { - "| 2 | 0.1.0 | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 |": "| 2 | 0.1 | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 |", - "| 3 | 0.1.0 | **Make it fast.** | 3 | 8 | 6 | 8 | 2.1, 1 | 0 |": "| 3 | 0.1.0 | Make it fast. | 3 | 11 | 6 | 8 | 7 | 0 |", - "### 3. Make it fast.": "### 4. Make it fast.", - "`Bar = 9`": "", + row: row.replace("0.1.0", "0.1"), + row + "\n": row.replace("5 | 5", "5 | ²") + "\n", + "| 2.1 | 0 |\n\n## Details": "| 2.1 | 0 |\n\n| 9 | 0.1.0 | | **Stray.** | 1 | 1 | 1 | 1 | 1 | 0 |\n\n## Details", + "| 4 | 0.1.0 | security |": "| 4 | 0.1.0 | later |", + "Fast detail.": "```\n## Goals\n```", + "### 3. Make it fast.": "### 5. Make it fast.", + "`Bar = 9`": "`Bar = nan`", + "-R - S/4 + 2*A + 2*G*W": "R / (S - 2)", } for old, new in broken.items(): with self.subTest(new=new), self.assertRaises(rank_todo.Malformed): @@ -97,6 +113,10 @@ class Main(unittest.TestCase): self.assertEqual(todo.read_text(), TODO) self.assertEqual(rank_todo.main([str(todo)]), 0) self.assertEqual(rank_todo.main(["--check", str(todo)]), 0) + pathlib.Path(temp, "README.md").unlink() + with contextlib.redirect_stderr(io.StringIO()) as said: + self.assertEqual(rank_todo.main([str(todo)]), 1) + self.assertIn("README.md", said.getvalue()) class ThisRepo(unittest.TestCase): diff --git a/docs/decisions.md b/docs/decisions.md index c3463c55..d0db04db 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -18,7 +18,7 @@ 2026-09-24, lilleman, extending it to every worktree. `claude --resume` re-enters the worktree the worker last entered, recorded in the transcript's `worktree-state` entry, and Claude Code asks trust per path, so trusting the checkout alone still lands the human in the dialog; trusting every worktree `git worktree list` names spares reading which one from the transcript. Valid while resume re-enters a recorded worktree and trust is kept per path. -2026-09-30, lilleman: Claude Code owns and writes that file, so `loop-claude` is to move out of it, bringing each case that must stay to the human. Stands until `todo.md`'s "Move what `loop-claude` writes out of `~/.claude.json`" ends it. +2026-09-30, lilleman: Claude Code owns and writes that file, so `loop-claude` is to move out of it, bringing each case that must stay to the human. Stands until `todo.md` item 6 ends it. ## bin/: the tests rerun themselves on a `uv`-fetched Python at README Install's floor @@ -30,7 +30,7 @@ ## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run on `rebuild`, 2026-10-01, lilleman. `rebuild` merged into main under the floor at 8585257's scores, 2026-10-01, lilleman. The 2026-10-01 run on PR #182 (the loop state machine) scored 7.5, 6.5, 6.88, 6.25, 6.38; lilleman shipped that PR under the floor and below `rebuild`'s best run the same day, its places filed in `todo.md` under 0.1.0. The 2026-10-02 run on PR #187 (`loop_claude`'s names, the exit contract) scored 7.75, 7.25, 7.38, 6.88, 7.25 at 70362d0, every seat naming larv-review §3 under Self-sufficiency, and 7.63, 7.13, 7.38, 7.0, 7.13 at 1971dba later that day, the first run at the floor, with no dimension or the overall below its best run on `rebuild`. The 2026-10-02 runs on PR #191 (the status line in Python) scored 7.5, 7.0, 7.13, 6.88, 7.13; 7.25, 6.75, 7.25, 6.88, 7.0; 7.63, 6.88, 7.38, 7.0, 7.13; and 7.63, 7.0, 7.25, 6.75, 7.25. Every seat rated the status line easy. The places they named under Locality and Self-sufficiency are filed in `todo.md` under 0.1.0, except `entries.py`'s heuristics over Claude Code's transcript format, which the seats scored as the problem's own difficulty. lilleman decided the same day to ship that PR under the floor. The 2026-10-02 runs on PR #194 (each cycle's transcript archived) scored 8.0, 7.25, 7.38, 7.13, 7.5 at 6ccd5b1 and 7.75, 7.13, 7.25, 7.0, 7.25 at d104ea0, both at the floor, every seat naming `archive` as the unit it would least want to modify. Valid until the next scoring run, which uses the same four seats. +2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run on `rebuild`, 2026-10-01, lilleman. `rebuild` merged into main under the floor at 8585257's scores, 2026-10-01, lilleman. The 2026-10-01 run on PR #182 (the loop state machine) scored 7.5, 6.5, 6.88, 6.25, 6.38; lilleman shipped that PR under the floor and below `rebuild`'s best run the same day, its places filed in `todo.md` under 0.1.0. The 2026-10-02 run on PR #187 (`loop_claude`'s names, the exit contract) scored 7.75, 7.25, 7.38, 6.88, 7.25 at 70362d0, every seat naming larv-review §3 under Self-sufficiency, and 7.63, 7.13, 7.38, 7.0, 7.13 at 1971dba later that day, the first run at the floor, with no dimension or the overall below its best run on `rebuild`. The 2026-10-02 runs on PR #191 (the status line in Python) scored 7.5, 7.0, 7.13, 6.88, 7.13; 7.25, 6.75, 7.25, 6.88, 7.0; 7.63, 6.88, 7.38, 7.0, 7.13; and 7.63, 7.0, 7.25, 6.75, 7.25. Every seat rated the status line easy. The places they named under Locality and Self-sufficiency are filed in `todo.md` under 0.1.0, except `entries.py`'s heuristics over Claude Code's transcript format, which the seats scored as the problem's own difficulty. lilleman decided the same day to ship that PR under the floor. The 2026-10-02 runs on PR #194 (each cycle's transcript archived) scored 8.0, 7.25, 7.38, 7.13, 7.5 at 6ccd5b1 and 7.75, 7.13, 7.25, 7.0, 7.25 at d104ea0, both at the floor, every seat naming `archive` as the unit it would least want to modify. On 2026-10-02 the bar of `todo.md` purged the places these runs filed, except `todo.md` items 13 and 17. Valid until the next scoring run, which uses the same four seats. ## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes @@ -64,14 +64,6 @@ 2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the interrupt run with `bypassPermissions`. The worker may read `~/.claude/.credentials.json`: it holds Claude Code's own credentials, which claude reads to run anyway. Its one seam to production is the forge: what it pushes or merges can publish through CI. Valid while `loop-claude` runs only in the sandbox README → Install names. -## loop-claude: the planned stats line goes in the transcript archive, off the remote - -2026-10-01, lilleman. Serves goals 3 and 4.4. The numbers show whether a change to the workflow raised quality or only cost. Each line names another project and its chunk, so the file stays off this repo's remote. `loop-claude` writes the line: the tokens, cycles and interrupts it counts, and the review's numbers from the summary larv-review ends with. Valid while the transcript archive stays off the remote. - -## workflow changes: once the bench runs, a change merges only after three benches rule it better - -2026-10-01, lilleman. 2026-10-02, lilleman: binding once `todo.md`'s "Bench about one chunk in ten against an open PR that changes the workflow" lands. Serves goals 4.1 and 4.4. The 2026-09-30 bench showed one run cannot tell a workflow's effect from the variance between runs. One bench ruling it worse closes the PR, since quality comes first (goal 4.1), and `docs/workflow-learnings.md` keeps what the PR changed and why it lost. Three is a starting number, to be evaluated against the stats. Valid until that evaluation changes the number. - ## review: `/security-review` is the security pass of record 2026-09-20, lilleman. Serves goal 4.1. Its value is a tuned exclusion list and a ≥0.8 confidence floor, which a hand-written reviewer would reproduce worse. Valid while `/security-review` ships both. @@ -86,4 +78,4 @@ ## todo.md: one table of items scored by the formula, bar and goal weights it states, 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 scores R (the risk the change creates serious bugs), S (size), A (value to the audience) and G (value to its goals, weighted by goal position); this repo's formula, `-R - S/4 + 2*A + 2*G*W`, 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. 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 scores R (the risk the change creates serious bugs), S (size), A (value to the audience) and G (value to its goals, weighted by goal position); this repo's formula, `-R - S/4 + 2*A + 2*G*W`, 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 to reach the human: a security finding, a question for the human, an item a decision names. The purge retired two decisions whose plans it removed: the stats line in the transcript archive, and three benches before a workflow change merges. `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. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 3d0ee43c..a368a275 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -61,11 +61,11 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Findings.** -1. A finding outside the chunk's change, whatever its pass or severity, is scored per `~/.claude/CLAUDE.md` → "Todo items" and filed in `todo.md`, unless it scores under the bar; the summary names each one left out, with its score. A verified security HIGH is handled per "Security". -2. A fix that would change a goal, or a decision the repo held before the chunk began, is asked; no user reachable → filed, the goal or decision left as is. +1. A finding outside the chunk's change, whatever its pass or severity, is scored and filed in `todo.md` per `~/.claude/CLAUDE.md` → "Todo items"; one under the bar and not exempt is named in the summary with its score instead. A verified security HIGH is handled per "Security". +2. A fix that would change a goal, or a decision the repo held before the chunk began, is asked; no user reachable → filed as a `question`, the goal or decision left as is. 3. A 🔴 is fixed, or shown factually wrong, and what disproved it recorded per `~/.claude/CLAUDE.md` → "Decisions: one home, each linked to a goal or a technical principle": in a comment at the code the finding concerns, or in `docs/decisions.md` when it concerns more than one place. Never declined. 4. A 🟡 is fixed, shown factually wrong like a 🔴, or declined. Decline one only where the reason is sound, consistent with the goals and the technical principles, and confidence is very high; the decline and its reason are recorded the same way. A reason neither speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess"; no user reachable → fix. Never drop one silently, and never decline one for convenience or the size of the fix. -5. A 🟢 or ❓ is fixed, answered, declined in the summary with its reason, or filed. Answer one where the code, a test or a record settles it, and quote what in the summary. A ❓ only the user can answer is asked; no user reachable → filed. +5. A 🟢 or ❓ is fixed, answered, declined in the summary with its reason, or filed. Answer one where the code, a test or a record settles it, and quote what in the summary. A ❓ only the user can answer is asked; no user reachable → filed as a `question`. 6. A 🔀 runs the named pass once the current pass is done. 7. Other reviewers map onto this scale: `/security-review`'s HIGH is 🔴, MEDIUM 🟡, LOW 🟢; what a forge's auto-reviewer marks blocking is 🔴. A finding of theirs repeating one declined or filed does not stand. @@ -100,7 +100,7 @@ Launch prose-reviewer with what the diff touched and every section this review c ## 4. Gate -1. Run the project's test suite locally unless the last stability round already left it verified green. +1. Run the project's test suite locally unless the last stability round already left it verified green, and `~/.claude/bin/rank_todo.py --check todo.md`. 2. Watch the forge's checks until every one passes. A red check is a finding. 3. No CI configured → the gate is local tests only; note it in the summary. 4. Everything green → mark the PR ready, dropping any `WIP:`/`Draft:` title prefix. diff --git a/todo.md b/todo.md index 36df251a..9c5496fe 100644 --- a/todo.md +++ b/todo.md @@ -20,28 +20,32 @@ ## Items -| ID | Release | Item | R | S | A | G | Goals | Score | -|---|---|---|---|---|---|---|---|---| -| 1 | 0.1.0 | **Copy the transcript archive off the machine, or say in README how it is backed up.** | 3 | 5 | 8 | 9 | 2, 3 | 27.8 | -| 2 | 0.1.0 | **Add a test that `.gitignore` keeps credentials, transcripts and memory files out.** | 1 | 2 | 6 | 9 | 3 | 24.5 | -| 3 | 0.1.0 | **Wait out a usage limit and retry however long it lasts, without counting it as a failed run.** | 4 | 5 | 9 | 8 | 4 | 23.5 | -| 7 | 0.1.0 | **Give the judge the project's recorded decisions, and ask it whether anything the project records settles a choice.** | 3 | 4 | 8 | 8 | 4.2 | 19.0 | -| 9 | 0.1.0 | **Give principles-auditor and prose-reviewer a way to list the project's files.** | 1 | 2 | 5 | 7 | 4.1 | 16.3 | -| 8 | 0.1.0 | **Judge a cycle on more than the transcript's last 40,000 characters.** | 4 | 5 | 7 | 8 | 4.2 | 15.8 | -| 13 | 0.1.0 | **Make larv-review §3 applicable on its own, cite its rules by name, and say where a pass's round count is recorded.** | 3 | 5 | 6 | 7 | 4.1 | 15.6 | -| 23 | 0.1.0 | **Launch a principles auditor only for a principles file the project shows applies, and rerun only the reviewer whose finding a fix answers.** | 3 | 4 | 7 | 8 | 4.4 | 13.5 | -| 10 | 0.1.0 | **Give the reviewer agents only the tools they need.** | 1 | 1 | 4 | 6 | 4.1 | 13.5 | -| 21 | 0.1.0 | **Give `settings.json`'s model one writer, and sort its keys.** | 3 | 3 | 6 | 7 | 4.3 | 12.9 | -| 20 | 0.1.0 | **Enable the `claude-security` plugin in `settings.json`, or drop larv-review's full-scan row.** | 1 | 1 | 4 | 5 | 4.1 | 12.4 | -| 12 | 0.1.0 | **Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.** | 2 | 4 | 4 | 6 | 4.1 | 11.7 | -| 5 | 0.1.0 | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 5 | 5 | 5 | 6 | 4.1 | 10.5 | -| 4 | 0.1.0 | **Name each chunk's archive folder by the chunk's start time, so `/` lists chunks in the order they ran.** | 3 | 2 | 4 | 3 | 2 | 9.8 | -| 26 | 0.1.0 | **Write a `workflow-review` skill that reads the stats and files each change it proposes to the workflow as a plan item, and have `AGENTS.md` run it on the chunk shipping a release's last item.** | 2 | 6 | 5 | 6 | 4.4 | 9.1 | -| 29 | 0.1.0 | **Make the small changes filed against the review's rules.** | 2 | 2 | 3 | 5 | 4.1, 4.4 | 9.1 | -| 17 | 0.1.0 | **Make `JUDGE_RULES` and the Claude Code flags `loop-claude` passes readable without `CLAUDE.md` or Claude Code's docs open.** | 1 | 2 | 3 | 4 | 4.1 | 9.0 | +| ID | Release | Exempt | Item | R | S | A | G | Goals | Score | +|---|---|---|---|---|---|---|---|---|---| +| 6 | 0.1.0 | decision | **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** | 5 | 5 | 4 | 5 | 4.1 | 7.4 | +| 1 | 0.1.0 | | **Copy the transcript archive off the machine, or say in README how it is backed up.** | 3 | 5 | 8 | 9 | 2, 3 | 27.8 | +| 2 | 0.1.0 | | **Add a test that `.gitignore` keeps credentials, transcripts and memory files out.** | 1 | 2 | 6 | 9 | 3 | 24.5 | +| 3 | 0.1.0 | | **Wait out a usage limit and retry however long it lasts, without counting it as a failed run.** | 4 | 5 | 9 | 8 | 4 | 23.5 | +| 7 | 0.1.0 | | **Give the judge the project's recorded decisions, and ask it whether anything the project records settles a choice.** | 3 | 4 | 8 | 8 | 4.2 | 19.0 | +| 9 | 0.1.0 | | **Give principles-auditor and prose-reviewer a way to list the project's files.** | 1 | 2 | 5 | 7 | 4.1 | 16.3 | +| 8 | 0.1.0 | | **Judge a cycle on more than the transcript's last 40,000 characters.** | 4 | 5 | 7 | 8 | 4.2 | 15.8 | +| 13 | 0.1.0 | | **Make larv-review §3 applicable on its own, cite its rules by name, and say where a pass's round count is recorded.** | 3 | 5 | 6 | 7 | 4.1 | 15.6 | +| 23 | 0.1.0 | | **Launch a principles auditor only for a principles file the project shows applies, and rerun only the reviewer whose finding a fix answers.** | 3 | 4 | 7 | 8 | 4.4 | 13.5 | +| 10 | 0.1.0 | | **Give the reviewer agents only the tools they need.** | 1 | 1 | 4 | 6 | 4.1 | 13.5 | +| 21 | 0.1.0 | | **Give `settings.json`'s model one writer, and sort its keys.** | 3 | 3 | 6 | 7 | 4.3 | 12.9 | +| 20 | 0.1.0 | | **Enable the `claude-security` plugin in `settings.json`, or drop larv-review's full-scan row.** | 1 | 1 | 4 | 5 | 4.1 | 12.4 | +| 12 | 0.1.0 | | **Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.** | 2 | 4 | 4 | 6 | 4.1 | 11.7 | +| 5 | 0.1.0 | | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 5 | 5 | 5 | 6 | 4.1 | 10.5 | +| 4 | 0.1.0 | | **Name each chunk's archive folder by the chunk's start time, so `/` lists chunks in the order they ran.** | 3 | 2 | 4 | 3 | 2 | 9.8 | +| 29 | 0.1.0 | | **Make the small changes filed against the review's rules.** | 2 | 2 | 3 | 5 | 4.1, 4.4 | 9.1 | +| 17 | 0.1.0 | | **Make `JUDGE_RULES` and the Claude Code flags `loop-claude` passes readable without `CLAUDE.md` or Claude Code's docs open.** | 1 | 2 | 3 | 4 | 4.1 | 9.0 | ## Details +### 6. Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay. + +Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost. + ### 1. Copy the transcript archive off the machine, or say in README how it is backed up. It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost disk loses every unattended run's record. Back it up only to a destination private to me and encrypted at rest: the worker runs with permissions bypassed, so the archived tool results can hold credentials it read. @@ -98,10 +102,6 @@ The key names the project's session, archive folder and models entry. `project_k Today the folder is the SHA-256 of the transcript's first timestamped line, which tells the human nothing; that line carries the start time. Drop the fallback to the first line, which every chunk of a project shares, and give the tests' fake transcripts ISO timestamps. -### 26. Write a `workflow-review` skill that reads the stats and files each change it proposes to the workflow as a plan item, and have `AGENTS.md` run it on the chunk shipping a release's last item. - -The workflow is `CLAUDE.md`, `principles/`, the skills, the agents and `loop-claude`. The skill's signals: findings outside the chunk's diff and comprehension scores per release, both from the stats; fixes after merge, from git; and the human's corrections, from the archived transcripts. - ### 29. Make the small changes filed against the review's rules. - Make the contributor a standing member of every project's audience. A project drops them only where its `## Audience` says maintainability does not matter. State that in `CLAUDE.md`'s goals-and-audience rule, and have larv-review's comprehension floor name the contributor as the reader it serves. The floor then gates every chunk while the contributor stands, and a project that drops them skips it. -- 2.52.0 From 798dfd781eb380b4ffa62345440dee2afa95a450 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 2 Oct 2026 20:16:01 +0200 Subject: [PATCH 3/7] Answer the architecture, stability and product-owner rounds: errors as values, security first, defect rows, Next ID, the format in --help --- CHANGELOG.md | 2 +- CLAUDE.md | 8 +- bin/rank_todo.py | 331 +++++++++++++++++++++++------------- bin/test_rank_todo.py | 88 ++++++---- docs/decisions.md | 6 +- skills/larv-review/SKILL.md | 17 +- todo.md | 31 ++-- 7 files changed, 309 insertions(+), 174 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ac7aaf8..81c29df5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- `bin/rank_todo.py` scores and ranks a project's `todo.md`: one table of items, each scored by the formula, bar and goal weights the file states; it exits 1 on an item under the bar, and `--check` also on an unranked file. +- Every project's `todo.md` takes one shape, and larv-review's gate checks it: one table of items, each scored by the formula, bar and goal weights the file states, an item under the bar dropped unless its Exempt cell says why. `bin/rank_todo.py` ranks the table, and `rank_todo.py --help` shows a valid file. - Run `loop-claude` only in a sandbox with no direct access to production: every claude it starts skips every permission prompt. - First release: `README.md` states what the checkout holds and needs, `loop-claude --help` what `loop-claude` does. - `settings.json`, the agents and the status line run unedited on any machine with README → Install's prerequisites; the status line shows reset times in the machine's own time zone. diff --git a/CLAUDE.md b/CLAUDE.md index 43af8b40..c572063f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The - **When the next release has no items and no work has landed towards it, plan it as this chunk.** Move the highest-scoring items of later releases into it, and get the human's approval of that set before writing any code. - **When the next release has no items left and work has landed towards it, it is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix lands, into that release; never start a later release's items or plan a new one. - **Open every chunk with one line:** the last version cut, what is unreleased (`CHANGELOG.md` → `## Unreleased`, or else the log since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once. -- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: one PR title states what they achieve together, without listing them; they sit under one release; and they fire the same review passes (`larv-review` §3). Tiny items, a few lines of change each, need neither a shared purpose nor the same passes: bundle up to ten from one release into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`, scored, unless it scores under the bar. +- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: one PR title states what they achieve together, without listing them; they sit under one release; and they fire the same review passes (`larv-review` §3). Tiny items, a few lines of change each, need neither a shared purpose nor the same passes: bundle up to ten from one release into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md` per "Todo items". A `question` row waits for the human: take the next row. - **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in a comment at the one place it governs, or in `docs/decisions.md` once made in more than one place. If an answer is a goal and something else too, write the goal, and record a choice only for what the goal leaves open. - **Ship every chunk with `/larv-review`.** - **Remove a finished item's row and detail from `todo.md`.** If the repo publishes something others consume — a package, an image, an API — reword the item for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete it; git history is the record. @@ -19,16 +19,16 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The - **Releases follow semver read strictly** (`~/.claude/principles/technical-principles.md`). ### Todo items (`todo.md`, tickets, plans) -- **`todo.md` is mandatory in every project, in one shape**, which `~/.claude/bin/rank_todo.py` checks and ranks (its `--help` states the format): `## Scoring` holds the formula, the bar and the goal weights; `## Items` is one table of every item; `## Details` holds each item's detail under its ID. A new item takes the next unused ID, never a deleted one's; cite an item by its ID. The formula, bar and weights are the project's own to tune. +- **`todo.md` is mandatory in every project, in one shape**, which `~/.claude/bin/rank_todo.py` checks and ranks (its `--help` states the format): `## Scoring` holds the formula, the bar and the goal weights; `## Items` is one table of every item; `## Details` holds each item's detail under its ID. A new item takes the `Next ID` the file states, which then counts up; cite an item by its ID. The formula, bar and weights are the project's own to tune. - **Score an item when it is filed or edited, then run `rank_todo.py`.** A deletion needs no run. Each score is a whole number from 1 to 10: - **R** — the risk that the change creates serious bugs or issues. - **S** — the size of the change. - **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 not kept, unless its Exempt cell says why:** `security` for a security finding, `question` for a question only the human can answer, `decision` for an item a decision in `docs/decisions.md` names. Otherwise a finding under the bar is named in the chunk's summary, not filed, and an item that falls under it is deleted, together with any item that needs it. +- **An item scoring under the bar is not kept, unless its Exempt cell says why:** `security` for a security finding, `defect` for a 🔴 finding that a goal, a principle or correctness is broken, `question` for a question only the human can answer, `decision` for an item a decision in `docs/decisions.md` names. Otherwise a finding under the bar is not filed, and an item that falls under it is deleted, together with any item that needs it; the chunk's summary names each, with its score. - **Goal weights default to position, the first goal weighing most;** `rank_todo.py` prints that table whenever the weights stop listing the README's goals. - Open each item with a bold one-sentence tagline, so the taglines alone say what a release holds; detail follows it. 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, as a row marked `security`, which `rank_todo.py` ranks first in its release, naming the exposure and the path it reaches. 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 move it down if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius. +- 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, as a row marked `security`, which `rank_todo.py` ranks first in its release, naming the exposure and the path it reaches. 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 move it down if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius. ## Quality diff --git a/bin/rank_todo.py b/bin/rank_todo.py index ce9b0c92..a3ac6ee8 100755 --- a/bin/rank_todo.py +++ b/bin/rank_todo.py @@ -3,15 +3,50 @@ 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 = ` 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 `### . `. -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. +Reads todo.md (default: ./todo.md), the README.md beside it, and docs/decisions.md when there is +one. Rewrites each item's Score from the formula, sorts the items by release, then security rows, +then score from highest, then ID, and orders the details to match. --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 = ` it states, judged on the Score as -shown, or --check finds it unranked. +A valid todo.md, every line shown required: + + # todo + + ## Scoring + + `Score = -R - S/4 + 2*A + 2*G*W` + + `Bar = 9` + + `Next ID = 2` + + | Goal | W | + |---|---| + | 1 | 1.00 | + + ## Items + + | ID | Release | Exempt | Item | R | S | A | G | Goals | Score | + |---|---|---|---|---|---|---|---|---|---| + | 1 | 0.1.0 | | **Make the first thing work.** | 2 | 3 | 8 | 9 | 1 | 0 | + + ## Details + + ### 1. Make the first thing work. + + What the tagline cannot say. + +- The formula holds numbers, + - * / and parentheses over R, S, A, G and W. +- The bar is judged on the Score as shown, to one decimal. +- A new item takes Next ID, and Next ID then counts up; no row may reach 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, A and G are whole numbers from 1 to 10; Goals lists goal numbers, comma separated. +- An item's Exempt cell is empty, or names why the bar does not apply: decision, defect, question + or security. An item docs/decisions.md cites as "`todo.md` item N" is marked decision. +- 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, todo.md breaks the format, an item that is not +exempt scores under the bar, or --check finds the file unranked. """ import ast import dataclasses @@ -20,10 +55,14 @@ import pathlib import re import sys -EXEMPTIONS = ("", "decision", "question", "security") +from loop_claude.failure import Failure +from loop_claude.project.premises import sections + +EXEMPTIONS = ("", "decision", "defect", "question", "security") ITEMS_HEADER = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |" -WEIGHTS_HEADER = "| Goal | W |" +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") +WEIGHTS_HEADER = "| Goal | W |" @dataclasses.dataclass(frozen=True) @@ -36,8 +75,10 @@ class Item: goals: tuple[str, ...] -class Malformed(Exception): - pass +@dataclasses.dataclass(frozen=True) +class Ranked: + text: str + under_bar: list[str] def main(argv: list[str]) -> int: @@ -47,87 +88,131 @@ def main(argv: list[str]) -> int: 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) + print(f"rank_todo.py: cannot read the arguments {' '.join(argv)}; usage: rank_todo.py [--check] [todo.md]", 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) + decisions = todo.parent / "docs" / "decisions.md" + read_in = [read(todo), read(todo.parent / "README.md"), read(decisions) if decisions.exists() else ""] + unread = next((found for found in read_in if isinstance(found, Failure)), None) + if unread: + print(unread.reason, file=sys.stderr) return 1 - if check and ranked != text: - print(f"{todo}: not ranked; run rank_todo.py on it", file=sys.stderr) + text, readme, cited = (str(found) for found in read_in) + ranked = rank(text, readme, cited) + if isinstance(ranked, Failure): + print(ranked.reason, file=sys.stderr) return 1 - if not check and ranked != text: - todo.write_text(ranked, encoding="utf-8") - for line in under_bar: + if ranked.text != text: + if check: + print(f"{todo}: not ranked; run rank_todo.py on it", file=sys.stderr) + return 1 + todo.write_text(ranked.text, encoding="utf-8") + for line in ranked.under_bar: print(f"{todo}: {line}", file=sys.stderr) - return 1 if under_bar else 0 + return 1 if ranked.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.""" +def read(path: pathlib.Path) -> str | Failure: + try: + return path.read_text(encoding="utf-8") + except FileNotFoundError: + return Failure(f"{path}: not found; every project keeps a todo.md beside its README.md, and rank_todo.py --help shows one") + except OSError as failure: + return Failure(f"{path}: {failure.strerror}") + except UnicodeDecodeError: + return Failure(f"{path}: not UTF-8") + + +def rank(text: str, readme: str, decisions: str) -> Ranked | Failure: lines = text.split("\n") + if ITEMS_HEADER not in lines and "## Items" not in lines: + return Failure("todo.md is not in the scored-table format; rank_todo.py --help shows a valid one") + goals = readme_goals(readme) + if isinstance(goals, Failure): + return goals formula = parse_formula(stated(text, "Score")) + if isinstance(formula, Failure): + return formula bar = number(stated(text, "Bar"), "the bar") + if isinstance(bar, Failure): + return bar + next_id = number(stated(text, "Next ID"), "Next ID") + if isinstance(next_id, Failure): + return next_id 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 + if isinstance(weights, Failure): + return weights + items = parse_items(lines, weights) + if isinstance(items, Failure): + return items + ids = [item.id for item in items] + if ids and max(ids) >= next_id: + return Failure(f"item {max(ids)} is not under Next ID {next_id:g}; raise Next ID past every ID") + marked = {item.id for item in items if item.exempt == "decision"} + if unmarked := sorted(set(cited_items(decisions)) - marked): + return Failure(f"docs/decisions.md cites todo.md item {', '.join(map(str, unmarked))}, which no row marked decision holds") + scored = [] + for item in items: + value = score(formula, item, weights) + if isinstance(value, Failure): + return value + scored.append((item, value)) + scored.sort(key=lambda pair: (pair[0].release, pair[0].exempt != "security", -pair[1], pair[0].id)) + start = lines.index(ITEMS_HEADER) + 2 + lines[start:start + len(scored)] = [render_item(item, value) for item, value in scored] + ranked = rank_details("\n".join(lines), [item for item, _ in scored]) + if isinstance(ranked, Failure): + return ranked + under_bar = [f"item {item.id} scores {value:.1f}, under the bar {bar:g}; delete it and any item that needs it, or mark it with a reason the bar does not apply" for item, value in scored if not item.exempt and round(value, 1) < bar] + return Ranked(ranked, under_bar) -def readme_goals(readme: str) -> list[str]: +def readme_goals(readme: str) -> list[str] | Failure: """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") + 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] = [] path: list[tuple[int, str]] = [] - for indent, number in re.findall(r"^([ \t]*)(\d+)\. ", section.group(1).expandtabs(4), re.M): + for indent, number in re.findall(r"^([ \t]*)(\d+)\. ", found[0].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") + return Failure("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 Failure(f"README.md's ## Goals numbers {', '.join(goals)}; number each goal by its position") return goals -def stated(text: str, name: str) -> str: +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)] + + +def stated(text: str, name: str) -> str | Failure: 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 Failure(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: +def parse_formula(source: str | Failure) -> ast.Expression | Failure: + if isinstance(source, Failure): + return source try: tree = ast.parse(source, mode="eval") except SyntaxError: - raise Malformed(f"the formula {source!r} does not parse") from None + return Failure(f"the formula {source!r} does not parse") 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") + numeric = isinstance(node, ast.Constant) and type(node.value) in (int, float) + 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.""" match node: case ast.Expression(body): return evaluate(body, values) @@ -139,96 +224,114 @@ def evaluate(node: ast.AST, values: dict[str, float]) -> float: 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)}") + case ast.BinOp(left, ast.Add(), right): + return evaluate(left, values) + evaluate(right, values) + case ast.BinOp(left, ast.Sub(), right): + return evaluate(left, values) - evaluate(right, values) + case ast.BinOp(left, ast.Mult(), right): + return evaluate(left, values) * evaluate(right, values) + case ast.BinOp(left, ast.Div(), right): + divisor = evaluate(right, values) + return evaluate(left, values) / divisor if divisor else math.nan + return math.nan -def score(formula: ast.Expression, item: Item, weights: dict[str, float]) -> float: +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. - 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 + value = evaluate(formula, {**item.scores, "W": max(weights[goal] for goal in item.goals)}) + return value if math.isfinite(value) else Failure(f"the formula gives item {item.id} no finite score") -def number(text: str, what: str) -> float: +def number(text: str | Failure, what: str) -> float | Failure: + if isinstance(text, Failure): + return text 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 + return value if math.isfinite(value) else Failure(f"{what} {text!r} is not a finite number") -def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float]: - start, end = table_rows(lines, WEIGHTS_HEADER) +def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float] | Failure: + rows = table_rows(lines, WEIGHTS_HEADER) + if isinstance(rows, Failure): + return rows weights: dict[str, float] = {} - for row in lines[start:end]: - goal, weight = cells(row, 2) - weights[goal] = number(weight, f"goal {goal}'s weight") + for row in rows: + found = cells(row, 2) + if isinstance(found, Failure): + return found + weight = number(found[1], f"goal {found[0]}'s weight") + if isinstance(weight, Failure): + return weight + weights[found[0]] = 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 Failure(f"the goal weights list {', '.join(weights) or 'no goal'}, but README.md's goals are {', '.join(goals)}; by position 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.""" +def parse_items(lines: list[str], weights: dict[str, float]) -> list[Item] | Failure: + rows = table_rows(lines, ITEMS_HEADER) + if isinstance(rows, Failure): + return rows + after = lines[lines.index(ITEMS_HEADER) + 2 + len(rows):] + if any(line.startswith("|") for line in section_lines(after)): + return Failure("## Items holds a row outside its table; keep the rows together under the header") + items = [] + for row in rows: + item = parse_item(row, weights) + if isinstance(item, Failure): + return item + items.append(item) + if len({item.id for item in items}) < len(items): + return Failure("two items share an ID") + return items + + +def table_rows(lines: list[str], header: str) -> list[str] | Failure: + """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") + return Failure(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") + return Failure(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]: +def section_lines(lines: list[str]) -> list[str]: + return lines[:next((index for index, line in enumerate(lines) if line.startswith("## ")), len(lines))] + + +def cells(row: str, count: int) -> list[str] | Failure: found = [cell.strip() for cell in re.split(r"(? Item: - id_, release, exempt, tagline, r, s, a, g, goals, _ = cells(row, 10) +def parse_item(row: str, weights: dict[str, float]) -> Item | Failure: + found = cells(row, 10) + if isinstance(found, Failure): + return found + id_, release, exempt, tagline, r, s, a, g, goals, _ = found 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") + return Failure(f"the ID {id_!r} is not a positive whole number: {row}") + if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", release): + return Failure(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:])}") + return Failure(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}") + return Failure(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") + return Failure(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") + return Failure(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) @@ -239,25 +342,25 @@ def render_item(item: Item, value: float) -> str: return f"| {item.id} | {release} | {item.exempt} | {item.tagline} | {scores} | {', '.join(item.goals)} | {value:.1f} |" -def rank_details(text: str, items: list[Item]) -> str: +def rank_details(text: str, items: list[Item]) -> str | Failure: 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") + return Failure("## 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 ### . heading") - details = {} + return Failure("## Details holds text before its first ### . heading") + details: dict[int, str] = {} for id_, detail in zip(parts[1::2], parts[2::2]): if int(id_) in details: - raise Malformed(f"## Details holds item {id_} twice") + return Failure(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] + return Failure(f"## Details holds item {', '.join(map(str, unknown))}, which the items table does not") + headed = [f"### {item.id}. {item.tagline.strip('*').replace(chr(92) + '|', '|')}\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():] diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py index a49cf8d7..cc8af755 100644 --- a/bin/test_rank_todo.py +++ b/bin/test_rank_todo.py @@ -8,10 +8,13 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) import rank_todo +from loop_claude.failure import Failure from test_python_floor import ROOT README = "# P\n\n## Goals\n\n1. Fast.\n2. Correct.\n 1. Tested.\n\n## Audience\n\nMe.\n" +DECISIONS = "## A choice\n\nStands until `todo.md` item 5 ends it.\n" + TODO = """# todo ## Scoring @@ -20,6 +23,8 @@ TODO = """# todo `Bar = 9` +`Next ID = 6` + | Goal | W | |---|---| | 1 | 1.00 | @@ -32,8 +37,9 @@ TODO = """# todo |---|---|---|---|---|---|---|---|---|---| | 1 | 0.2.0 | | **Ship the later thing.** | 1 | 1 | 9 | 9 | 1 | 0 | | 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 | -| 3 | 0.1.0 | | **Make it fast, `a \| b`.** | 3 | 8 | 6 | 8 | 2.1, 1 | 0 | +| 3 | 0.1.0 | | **Make it fast, `a \\| b`.** | 3 | 8 | 6 | 8 | 2.1, 1 | 0 | | 4 | 0.1.0 | security | **Rotate the leaked key.** | 9 | 2 | 1 | 1 | 2.1 | 0 | +| 5 | 0.1.0 | decision | **Move the writes out.** | 5 | 5 | 4 | 5 | 2.1 | 0 | ## Details @@ -52,74 +58,92 @@ Kept as written. class Rank(unittest.TestCase): - def ranked(self, todo=TODO, readme=README): - return rank_todo.rank(todo, rank_todo.readme_goals(readme)) + def ranked(self, todo=TODO, readme=README, decisions=DECISIONS): + return rank_todo.rank(todo, readme, decisions) - def test_scores_and_sorts_by_release_then_score_and_orders_the_details_to_match(self): - text, under_bar = self.ranked() + def test_scores_and_sorts_by_release_then_security_then_score_and_orders_the_details_to_match(self): + ranked = self.ranked() self.assertIn("""| 4 | 0.1.0 | security | **Rotate the leaked key.** | 9 | 2 | 1 | 1 | 2.1 | -6.8 | | 3 | 0.1.0 | | **Make it fast, `a \\| b`.** | 3 | 8 | 6 | 8 | 2.1, 1 | 23.0 | | 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 10.3 | +| 5 | 0.1.0 | decision | **Move the writes out.** | 5 | 5 | 4 | 5 | 2.1 | 5.1 | | 1 | 0.2.0 | | **Ship the later thing.** | 1 | 1 | 9 | 9 | 1 | 34.8 | -""", text) - self.assertTrue(text.endswith("## Details\n\n### 3. Make it fast, `a \\| b`.\n\nFast detail.\n\n### 1. Ship the later thing.\n\nLater detail.\n\n## Notes\n\nKept as written.\n")) - self.assertEqual(under_bar, []) - self.assertEqual(self.ranked(text), (text, [])) +""", ranked.text) + self.assertTrue(ranked.text.endswith("## Details\n\n### 3. Make it fast, `a | b`.\n\nFast detail.\n\n### 1. Ship the later thing.\n\nLater detail.\n\n## Notes\n\nKept as written.\n")) + self.assertEqual(ranked.under_bar, []) + self.assertEqual(self.ranked(ranked.text), ranked) - def test_names_each_item_under_the_bar(self): - _, under_bar = self.ranked(TODO.replace("`Bar = 9`", "`Bar = 11`")) - self.assertEqual(under_bar, ["item 2 scores 10.3, under the bar 11; rescore it or delete it"]) + def test_names_each_item_under_the_bar_that_is_not_exempt(self): + ranked = self.ranked(TODO.replace("`Bar = 9`", "`Bar = 11`")) + self.assertEqual(ranked.under_bar, ["item 2 scores 10.3, under the bar 11; delete it and any item that needs it, or mark it with a reason the bar does not apply"]) def test_reads_goals_and_sub_goals_in_reading_order(self): self.assertEqual(rank_todo.readme_goals(README), ["1", "2", "2.1"]) self.assertEqual(rank_todo.readme_goals(README.replace(" 1.", "\t1.")), ["1", "2", "2.1"]) - with self.assertRaises(rank_todo.Malformed): - rank_todo.readme_goals(README.replace("2. Correct.", "1. Correct.")) + self.assertEqual(rank_todo.readme_goals(README.replace("2. Correct.", "```\n## Goals\n```\n2. Correct.")), ["1", "2", "2.1"]) + self.assertIsInstance(rank_todo.readme_goals(README.replace("2. Correct.", "1. Correct.")), Failure) def test_prints_the_positional_weights_when_they_stop_listing_the_readmes_goals(self): - with self.assertRaises(rank_todo.Malformed) as raised: - self.ranked(readme=README.replace(" 1. Tested.", " 1. Tested.\n3. Small.")) - self.assertIn("| 1 | 1.00 |\n| 2 | 0.75 |\n| 2.1 | 0.50 |\n| 3 | 0.25 |", str(raised.exception)) + failure = self.ranked(readme=README.replace(" 1. Tested.", " 1. Tested.\n3. Small.")) + 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 +"): - with self.subTest(formula=formula), self.assertRaises(rank_todo.Malformed): - self.ranked(TODO.replace("-R - S/4 + 2*A + 2*G*W", formula)) + for formula in ("__import__('os')", "R.real", "X + 1", "R ** 2", "R +", "R / (S - 2)"): + with self.subTest(formula=formula): + self.assertIsInstance(self.ranked(TODO.replace("-R - S/4 + 2*A + 2*G*W", formula)), Failure) - def test_refuses_a_row_or_detail_off_the_format(self): + def test_refuses_a_file_off_the_format(self): row = "| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 |" broken = { row: row.replace("0.1.0", "0.1"), row + "\n": row.replace("5 | 5", "5 | ²") + "\n", "| 2.1 | 0 |\n\n## Details": "| 2.1 | 0 |\n\n| 9 | 0.1.0 | | **Stray.** | 1 | 1 | 1 | 1 | 1 | 0 |\n\n## Details", "| 4 | 0.1.0 | security |": "| 4 | 0.1.0 | later |", + "| 5 | 0.1.0 | decision |": "| 5 | 0.1.0 | |", + "`Next ID = 6`": "`Next ID = 5`", "Fast detail.": "```\n## Goals\n```", - "### 3. Make it fast.": "### 5. Make it fast.", + "### 3. Make it fast.": "### 7. Make it fast.", "`Bar = 9`": "`Bar = nan`", - "-R - S/4 + 2*A + 2*G*W": "R / (S - 2)", + "## Items\n\n| ID | Release | Exempt |": "## Plan\n\n| ID | Release |", } for old, new in broken.items(): - with self.subTest(new=new), self.assertRaises(rank_todo.Malformed): - self.ranked(TODO.replace(old, new)) + with self.subTest(new=new): + self.assertIsInstance(self.ranked(TODO.replace(old, new)), Failure) class Main(unittest.TestCase): + def run_main(self, *argv): + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as said: + code = rank_todo.main(list(argv)) + return code, said.getvalue() + def test_ranks_the_file_in_place_and_check_writes_nothing(self): with tempfile.TemporaryDirectory() as temp: todo = pathlib.Path(temp, "todo.md") todo.write_text(TODO) pathlib.Path(temp, "README.md").write_text(README) - self.assertEqual(rank_todo.main(["--check", str(todo)]), 1) + pathlib.Path(temp, "docs").mkdir() + pathlib.Path(temp, "docs", "decisions.md").write_text(DECISIONS) + self.assertEqual(self.run_main("--check", str(todo))[0], 1) self.assertEqual(todo.read_text(), TODO) - self.assertEqual(rank_todo.main([str(todo)]), 0) - self.assertEqual(rank_todo.main(["--check", str(todo)]), 0) + self.assertEqual(self.run_main(str(todo)), (0, "")) + self.assertEqual(self.run_main("--check", str(todo)), (0, "")) + pathlib.Path(temp, "README.md").write_bytes(b"\xff") + self.assertEqual(self.run_main(str(todo)), (1, f"{temp}/README.md: not UTF-8\n")) pathlib.Path(temp, "README.md").unlink() - with contextlib.redirect_stderr(io.StringIO()) as said: - self.assertEqual(rank_todo.main([str(todo)]), 1) - self.assertIn("README.md", said.getvalue()) + self.assertIn("README.md: not found", self.run_main(str(todo))[1]) + + def test_shows_a_valid_file_in_help_and_names_arguments_it_cannot_read(self): + self.assertEqual(self.run_main("--help")[0], 0) + skeleton = "\n".join(line[4:] for line in rank_todo.__doc__.split("\n") if line.startswith(" ")) + ranked = rank_todo.rank(skeleton, "## Goals\n\n1. Work.\n", "") + self.assertIsInstance(ranked, rank_todo.Ranked) + self.assertEqual(ranked.under_bar, []) + self.assertEqual(self.run_main("--fix"), (1, "rank_todo.py: cannot read the arguments --fix; usage: rank_todo.py [--check] [todo.md]\n")) class ThisRepo(unittest.TestCase): def test_todo_md_is_ranked_with_nothing_under_the_bar(self): text = (ROOT / "todo.md").read_text(encoding="utf-8") - self.assertEqual(rank_todo.rank(text, rank_todo.readme_goals((ROOT / "README.md").read_text(encoding="utf-8"))), (text, [])) + ranked = rank_todo.rank(text, (ROOT / "README.md").read_text(encoding="utf-8"), (ROOT / "docs" / "decisions.md").read_text(encoding="utf-8")) + self.assertEqual(ranked, rank_todo.Ranked(text, [])) diff --git a/docs/decisions.md b/docs/decisions.md index d0db04db..9f2949da 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -6,11 +6,11 @@ ## loop-claude: a judge decides each interrupt from the transcript and the README's premises; the worker's own account of which goal settles a choice decides nothing -2026-09-21, lilleman. Serves goal 4. Asked to name the goal behind each choice, the worker cites a real goal for a choice that goal does not settle, and under-reports its own decisions; the judge's bar is whether the README discriminates between the alternatives. On 2026-10-01 lilleman decided the judge is to read `docs/decisions.md` and `AGENTS.md` too, so an answer recorded there is not asked again (goal 4.2); `todo.md`'s "Give the judge the project's recorded decisions" ends the README-only bar. Valid while the worker's self-report stays unreliable. +2026-09-21, lilleman. Serves goal 4. Asked to name the goal behind each choice, the worker cites a real goal for a choice that goal does not settle, and under-reports its own decisions; the judge's bar is whether the README discriminates between the alternatives. On 2026-10-01 lilleman decided the judge is to read `docs/decisions.md` and `AGENTS.md` too, so an answer recorded there is not asked again (goal 4.2); `todo.md` item 7 ends the README-only bar. Valid while the worker's self-report stays unreliable. ## loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it -2026-09-21, lilleman; revised 2026-09-30 by lilleman. Serves goal 4. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. A checkout outside `~/code` mirroring a path inside it shares that id, and a second loop on it is not refused. Once `todo.md`'s "Key a project on its checkout's full path" lands, the id comes from the full path, so no two checkouts share one, and `loop-claude` refuses to start while another session on that id is active. Moving the checkout orphans its open sessions, archive folder and models entry: sessions stay in the picker until the human deletes them, migration code not being worth a one-human audience. Valid while claude takes `--session-id` and resumes by it. +2026-09-21, lilleman; revised 2026-09-30 by lilleman. Serves goal 4. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. A checkout outside `~/code` mirroring a path inside it shares that id, and a second loop on it is not refused. Once `todo.md` item 5 lands, the id comes from the full path, so no two checkouts share one, and `loop-claude` refuses to start while another session on that id is active. Moving the checkout orphans its open sessions, archive folder and models entry: sessions stay in the picker until the human deletes them, migration code not being worth a one-human audience. Valid while claude takes `--session-id` and resumes by it. ## loop-claude: before an interrupt, it marks the checkout and each of its worktrees trusted in `~/.claude.json` @@ -78,4 +78,4 @@ ## todo.md: one table of items scored by the formula, bar and goal weights it states, 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 scores R (the risk the change creates serious bugs), S (size), A (value to the audience) and G (value to its goals, weighted by goal position); this repo's formula, `-R - S/4 + 2*A + 2*G*W`, 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 to reach the human: a security finding, a question for the human, an item a decision names. The purge retired two decisions whose plans it removed: the stats line in the transcript archive, and three benches before a workflow change merges. `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: a security finding, a 🔴 defect, a question for the human, an item a decision names. 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, rather than keep plans scored under the bar. `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. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index a368a275..c2f9df33 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -50,7 +50,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod 2. The architecture pass's round is the architect (unless skipped), the principles audit and the scoring run, so a fix to any of their findings reruns the whole round. 3. The external auto-reviewer (§4) is a pass of its own, each review it posts a round. 4. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. -5. A pass is done when its latest round leaves no 🔴 or 🟡 standing: none was reported, or each was shown factually wrong, declined or filed per "Findings". Resolve that round's 🟢s and ❓s per "Findings" too. +5. A pass is done when its latest round leaves no 🔴 or 🟡 standing: none was reported, or each was shown factually wrong, declined, filed, or named under the bar per "Findings". Resolve that round's 🟢s and ❓s per "Findings" too. 6. A pass takes at most three rounds per chunk. Instead of a fourth, list what is open and ask the user. For the auto-reviewer, ask before the push that would summon its fourth, and hold the fixes unpushed until the answer. 7. A yes grants that pass one more round, after which the ask repeats; a no leaves the PR unmerged. @@ -61,7 +61,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Findings.** -1. A finding outside the chunk's change, whatever its pass or severity, is scored and filed in `todo.md` per `~/.claude/CLAUDE.md` → "Todo items"; one under the bar and not exempt is named in the summary with its score instead. A verified security HIGH is handled per "Security". +1. A finding outside the chunk's change, whatever its pass or severity, is scored and filed in `todo.md` per `~/.claude/CLAUDE.md` → "Todo items", a 🔴 marked `defect`; one under the bar and not exempt is named in the summary with its score instead. A verified security HIGH is handled per "Security". 2. A fix that would change a goal, or a decision the repo held before the chunk began, is asked; no user reachable → filed as a `question`, the goal or decision left as is. 3. A 🔴 is fixed, or shown factually wrong, and what disproved it recorded per `~/.claude/CLAUDE.md` → "Decisions: one home, each linked to a goal or a technical principle": in a comment at the code the finding concerns, or in `docs/decisions.md` when it concerns more than one place. Never declined. 4. A 🟡 is fixed, shown factually wrong like a 🔴, or declined. Decline one only where the reason is sound, consistent with the goals and the technical principles, and confidence is very high; the decline and its reason are recorded the same way. A reason neither speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess"; no user reachable → fix. Never drop one silently, and never decline one for convenience or the size of the fix. @@ -78,7 +78,7 @@ Launch systems-architect: review the system as a whole entered through this chan Then the principles audit: one principles-auditor per file in `~/.claude/principles/` and one for the README's goals, each over the whole project in every round. -Then the comprehension floor: the `comprehension-panel` skill's scoring run (`~/.claude/skills/comprehension-panel/SKILL.md` → "The scoring run") over the whole project, not the diff. With any dimension or the overall below 7.0 the chunk does not merge: fix the places the seats name under the capping dimension, or take the user's explicit decision to ship under the floor, record it in `docs/decisions.md` with the scores, and file the places in `todo.md`. No user reachable → fix. At the floor or above, the scores are still a ratchet — a later chunk may not lower any — and the four dimension scores and the overall go in the summary so the next run can see the direction of travel. +Then the comprehension floor: the `comprehension-panel` skill's scoring run (`~/.claude/skills/comprehension-panel/SKILL.md` → "The scoring run") over the whole project, not the diff. With any dimension or the overall below 7.0 the chunk does not merge: fix the places the seats name under the capping dimension, or take the user's explicit decision to ship under the floor, record it in `docs/decisions.md` with the scores, and file the places in `todo.md` per `~/.claude/CLAUDE.md` → "Todo items". No user reachable → fix. At the floor or above, the scores are still a ratchet — a later chunk may not lower any — and the four dimension scores and the overall go in the summary so the next run can see the direction of travel. ### Security @@ -100,11 +100,12 @@ Launch prose-reviewer with what the diff touched and every section this review c ## 4. Gate -1. Run the project's test suite locally unless the last stability round already left it verified green, and `~/.claude/bin/rank_todo.py --check todo.md`. -2. Watch the forge's checks until every one passes. A red check is a finding. -3. No CI configured → the gate is local tests only; note it in the summary. -4. Everything green → mark the PR ready, dropping any `WIP:`/`Draft:` title prefix. -5. **External auto-reviewer**, when the repo has one — its config file (`.coderabbit.yaml` and the like), or its comments on earlier PRs; none → skip it, say so. Marking the PR ready is what summons it. Wait up to **10 minutes** for its first review, checking about once a minute; nothing by then → note it in the summary and carry on, never waiting twice. Its rounds, §3 → "Round cap". Once it has reviewed, each later return here, after a fix re-entered per §3, waits up to **5 minutes** for its re-review of the new commit. +1. Run `~/.claude/bin/rank_todo.py --check todo.md`. +2. Run the project's test suite locally unless the last stability round already left it verified green. +3. Watch the forge's checks until every one passes. A red check is a finding. +4. No CI configured → the gate is local tests only; note it in the summary. +5. Everything green → mark the PR ready, dropping any `WIP:`/`Draft:` title prefix. +6. **External auto-reviewer**, when the repo has one — its config file (`.coderabbit.yaml` and the like), or its comments on earlier PRs; none → skip it, say so. Marking the PR ready is what summons it. Wait up to **10 minutes** for its first review, checking about once a minute; nothing by then → note it in the summary and carry on, never waiting twice. Its rounds, §3 → "Round cap". Once it has reviewed, each later return here, after a fix re-entered per §3, waits up to **5 minutes** for its re-review of the new commit. ## 5. Goal alignment, then merge diff --git a/todo.md b/todo.md index 9c5496fe..f913eb11 100644 --- a/todo.md +++ b/todo.md @@ -6,6 +6,8 @@ `Bar = 9` +`Next ID = 36` + | Goal | W | |---|---| | 1 | 1.00 | @@ -22,30 +24,27 @@ | ID | Release | Exempt | Item | R | S | A | G | Goals | Score | |---|---|---|---|---|---|---|---|---|---| -| 6 | 0.1.0 | decision | **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** | 5 | 5 | 4 | 5 | 4.1 | 7.4 | | 1 | 0.1.0 | | **Copy the transcript archive off the machine, or say in README how it is backed up.** | 3 | 5 | 8 | 9 | 2, 3 | 27.8 | | 2 | 0.1.0 | | **Add a test that `.gitignore` keeps credentials, transcripts and memory files out.** | 1 | 2 | 6 | 9 | 3 | 24.5 | | 3 | 0.1.0 | | **Wait out a usage limit and retry however long it lasts, without counting it as a failed run.** | 4 | 5 | 9 | 8 | 4 | 23.5 | -| 7 | 0.1.0 | | **Give the judge the project's recorded decisions, and ask it whether anything the project records settles a choice.** | 3 | 4 | 8 | 8 | 4.2 | 19.0 | +| 7 | 0.1.0 | decision | **Give the judge the project's recorded decisions, and ask it whether anything the project records settles a choice.** | 3 | 4 | 8 | 8 | 4.2 | 19.0 | | 9 | 0.1.0 | | **Give principles-auditor and prose-reviewer a way to list the project's files.** | 1 | 2 | 5 | 7 | 4.1 | 16.3 | | 8 | 0.1.0 | | **Judge a cycle on more than the transcript's last 40,000 characters.** | 4 | 5 | 7 | 8 | 4.2 | 15.8 | -| 13 | 0.1.0 | | **Make larv-review §3 applicable on its own, cite its rules by name, and say where a pass's round count is recorded.** | 3 | 5 | 6 | 7 | 4.1 | 15.6 | +| 13 | 0.1.0 | decision | **Make larv-review §3 applicable on its own, cite its rules by name, and say where a pass's round count is recorded.** | 3 | 5 | 6 | 7 | 4.1 | 15.6 | | 23 | 0.1.0 | | **Launch a principles auditor only for a principles file the project shows applies, and rerun only the reviewer whose finding a fix answers.** | 3 | 4 | 7 | 8 | 4.4 | 13.5 | | 10 | 0.1.0 | | **Give the reviewer agents only the tools they need.** | 1 | 1 | 4 | 6 | 4.1 | 13.5 | | 21 | 0.1.0 | | **Give `settings.json`'s model one writer, and sort its keys.** | 3 | 3 | 6 | 7 | 4.3 | 12.9 | | 20 | 0.1.0 | | **Enable the `claude-security` plugin in `settings.json`, or drop larv-review's full-scan row.** | 1 | 1 | 4 | 5 | 4.1 | 12.4 | | 12 | 0.1.0 | | **Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.** | 2 | 4 | 4 | 6 | 4.1 | 11.7 | -| 5 | 0.1.0 | | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 5 | 5 | 5 | 6 | 4.1 | 10.5 | +| 35 | 0.1.0 | question | **Decide whether each project's model choice syncs between machines, so a new machine does not ask again.** | 3 | 3 | 5 | 6 | 4.2 | 11.5 | +| 5 | 0.1.0 | decision | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 5 | 5 | 5 | 6 | 4.1 | 10.5 | | 4 | 0.1.0 | | **Name each chunk's archive folder by the chunk's start time, so `/` lists chunks in the order they ran.** | 3 | 2 | 4 | 3 | 2 | 9.8 | -| 29 | 0.1.0 | | **Make the small changes filed against the review's rules.** | 2 | 2 | 3 | 5 | 4.1, 4.4 | 9.1 | -| 17 | 0.1.0 | | **Make `JUDGE_RULES` and the Claude Code flags `loop-claude` passes readable without `CLAUDE.md` or Claude Code's docs open.** | 1 | 2 | 3 | 4 | 4.1 | 9.0 | +| 29 | 0.1.0 | | **Make the contributor a standing member of every project's audience, unless its `## Audience` says maintainability does not matter.** | 2 | 2 | 3 | 5 | 4.1, 4.4 | 9.1 | +| 17 | 0.1.0 | decision | **Make `JUDGE_RULES` and the Claude Code flags `loop-claude` passes readable without `CLAUDE.md` or Claude Code's docs open.** | 1 | 2 | 3 | 4 | 4.1 | 9.0 | +| 6 | 0.1.0 | decision | **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** | 5 | 5 | 4 | 5 | 4.1 | 7.4 | ## Details -### 6. Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay. - -Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost. - ### 1. Copy the transcript archive off the machine, or say in README how it is backed up. It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost disk loses every unattended run's record. Back it up only to a destination private to me and encrypted at rest: the worker runs with permissions bypassed, so the archived tool results can hold credentials it read. @@ -94,6 +93,10 @@ No machine has it enabled, so every chunk that fires the pass skips it. The repo has no CI, so larv-review's gate is the local run, and larv-review's Gate skips even that when the last stability round left the suite green: an unattended chunk can merge on the worker's own word. +### 35. Decide whether each project's model choice syncs between machines, so a new machine does not ask again. + +The decision "loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes" keeps the choice per machine, so every new machine asks once per project; goal 4.2 says never ask the same thing twice. Syncing it means a tracked file `loop-claude` writes, which dirties the checkout. + ### 5. Key a project on its checkout's full path, and refuse to start while another session uses that key. The key names the project's session, archive folder and models entry. `project_key` drops the leading `/`, so `~/code/a` and `/a` share all three, and one loop can resume or delete the other's session. @@ -102,10 +105,14 @@ The key names the project's session, archive folder and models entry. `project_k Today the folder is the SHA-256 of the transcript's first timestamped line, which tells the human nothing; that line carries the start time. Drop the fallback to the first line, which every chunk of a project shares, and give the tests' fake transcripts ISO timestamps. -### 29. Make the small changes filed against the review's rules. +### 29. Make the contributor a standing member of every project's audience, unless its `## Audience` says maintainability does not matter. -- Make the contributor a standing member of every project's audience. A project drops them only where its `## Audience` says maintainability does not matter. State that in `CLAUDE.md`'s goals-and-audience rule, and have larv-review's comprehension floor name the contributor as the reader it serves. The floor then gates every chunk while the contributor stands, and a project that drops them skips it. +State that in `CLAUDE.md`'s goals-and-audience rule, and have larv-review's comprehension floor name the contributor as the reader it serves. The floor then gates every chunk while the contributor stands, and a project that drops them skips it. ### 17. Make `JUDGE_RULES` and the Claude Code flags `loop-claude` passes readable without `CLAUDE.md` or Claude Code's docs open. The 2026-10-02 scoring runs on PR #191 named both under Self-sufficiency: the judge's rules use "chunk" and "a release ready to cut" from `CLAUDE.md` with no link, and `--resume`, `--session-id`, `--no-session-persistence`, `--json-schema` and stream-json's result event go unexplained in `worker.py` and `judge.py`. + +### 6. Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay. + +Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost. -- 2.52.0 From b7120761445587b8be13574874044d0c1b17799d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 2 Oct 2026 20:28:13 +0200 Subject: [PATCH 4/7] Answer the third round: split rank, check decision citations both ways, one fence rule, prose fixes --- AGENTS.md | 2 +- CHANGELOG.md | 2 +- CLAUDE.md | 21 +-- bin/loop_claude/project/premises.py | 5 +- bin/rank_todo.py | 245 +++++++++++++++++----------- bin/test_rank_todo.py | 11 +- docs/decisions.md | 8 +- skills/larv-review/SKILL.md | 8 +- 8 files changed, 181 insertions(+), 121 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b53300a9..cc88cd8a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,7 +20,7 @@ Decisions live in `docs/decisions.md`: - review: `/security-review` is the security pass of record - review: the premises chunk's whole review is the human's approval - workflow-bench/: the remote may show the bench cases' names and commit SHAs -- todo.md: one table of items scored by the formula, bar and goal weights it states, ranked by `bin/rank_todo.py` +- 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` ## Scoring run diff --git a/CHANGELOG.md b/CHANGELOG.md index 81c29df5..38eda22f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- Every project's `todo.md` takes one shape, and larv-review's gate checks it: one table of items, each scored by the formula, bar and goal weights the file states, an item under the bar dropped unless its Exempt cell says why. `bin/rank_todo.py` ranks the table, and `rank_todo.py --help` shows a valid file. +- Every project's `todo.md` takes one shape, and larv-review's gate checks it: one table of items, each scored by the formula and goal weights the file states and held to its bar, an item under the bar dropped unless its Exempt cell says why. `bin/rank_todo.py` ranks the table, and `rank_todo.py --help` shows a valid file. - Run `loop-claude` only in a sandbox with no direct access to production: every claude it starts skips every permission prompt. - First release: `README.md` states what the checkout holds and needs, `loop-claude --help` what `loop-claude` does. - `settings.json`, the agents and the status line run unedited on any machine with README → Install's prerequisites; the status line shows reset times in the machine's own time zone. diff --git a/CLAUDE.md b/CLAUDE.md index c572063f..07442560 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,30 +5,31 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The *next release* is the earliest one not yet cut. Other words, such as *chunk*, are defined under "Vocabulary" at the end of this file. - **Until `README.md` has a `## Goals` and an `## Audience` section, writing them is the only work.** Not even planning in `todo.md`. Both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count. - - **Goals** are the project's aims, not promises: one numbered line each, in priority order, a sub-goal indented under its goal, like slogans — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal rarely names an implementation; how a goal is met goes further down the README and names the goal it serves. + - **Goals** are the project's aims, not promises: one numbered line each, like slogans, in priority order; a sub-goal is indented under its goal — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal rarely names an implementation; how a goal is met goes further down the README and names the goal it serves. - **Audience** names who depends on the project and what they may rely on. -- **Plan `todo.md` as one scored table** ("Todo items"): every item names the release that ships it. If `todo.md` has another shape, reshaping it is the chunk, and the human approves it. +- **Plan `todo.md` as one scored table**, per "Todo items": every item names the release that ships it. If `todo.md` has another shape, reshaping it is the chunk, and the human approves it. - **When the next release has no items and no work has landed towards it, plan it as this chunk.** Move the highest-scoring items of later releases into it, and get the human's approval of that set before writing any code. - **When the next release has no items left and work has landed towards it, it is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix lands, into that release; never start a later release's items or plan a new one. - **Open every chunk with one line:** the last version cut, what is unreleased (`CHANGELOG.md` → `## Unreleased`, or else the log since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once. -- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: one PR title states what they achieve together, without listing them; they sit under one release; and they fire the same review passes (`larv-review` §3). Tiny items, a few lines of change each, need neither a shared purpose nor the same passes: bundle up to ten from one release into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md` per "Todo items". A `question` row waits for the human: take the next row. +- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: one PR title states what they achieve together, without listing them; they name one release; and they fire the same review passes (`larv-review` §3). Tiny items, a few lines of change each, need neither a shared purpose nor the same passes: bundle up to ten that name one release into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md` per "Todo items". An item marked `question` waits for the human; take the next item. - **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in a comment at the one place it governs, or in `docs/decisions.md` once made in more than one place. If an answer is a goal and something else too, write the goal, and record a choice only for what the goal leaves open. - **Ship every chunk with `/larv-review`.** -- **Remove a finished item's row and detail from `todo.md`.** If the repo publishes something others consume — a package, an image, an API — reword the item for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete it; git history is the record. +- **Remove a finished item's row and detail from `todo.md`, and revise any decision that cites it.** If the repo publishes something others consume — a package, an image, an API — reword the item for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete it; git history is the record. - **Releases are the human's.** The version bump and the publishing credentials are theirs, whatever another rule says. Prepare everything else, so cutting a release is one decision. - **Releases follow semver read strictly** (`~/.claude/principles/technical-principles.md`). ### Todo items (`todo.md`, tickets, plans) -- **`todo.md` is mandatory in every project, in one shape**, which `~/.claude/bin/rank_todo.py` checks and ranks (its `--help` states the format): `## Scoring` holds the formula, the bar and the goal weights; `## Items` is one table of every item; `## Details` holds each item's detail under its ID. A new item takes the `Next ID` the file states, which then counts up; cite an item by its ID. The formula, bar and weights are the project's own to tune. -- **Score an item when it is filed or edited, then run `rank_todo.py`.** A deletion needs no run. Each score is a whole number from 1 to 10: +- **`todo.md` is mandatory in every project, in one shape**, which `~/.claude/bin/rank_todo.py` checks and ranks; its `--help` shows a valid file. `## Scoring` holds the formula, the bar and the goal weights; `## Items` is one table of every item; `## Details` holds each item's detail under its ID. Cite an item by its ID. The formula, bar and weights are the project's own to tune. +- **Score an item when it is filed or edited, then run `rank_todo.py`.** Each of R, S, A and G is a whole number from 1 to 10: - **R** — the risk that the change creates serious bugs or issues. - **S** — the size of the change. - **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 not kept, unless its Exempt cell says why:** `security` for a security finding, `defect` for a 🔴 finding that a goal, a principle or correctness is broken, `question` for a question only the human can answer, `decision` for an item a decision in `docs/decisions.md` names. Otherwise a finding under the bar is not filed, and an item that falls under it is deleted, together with any item that needs it; the chunk's summary names each, with its score. -- **Goal weights default to position, the first goal weighing most;** `rank_todo.py` prints that table whenever the weights stop listing the README's goals. -- Open each item with a bold one-sentence tagline, so the taglines alone say what a release holds; detail follows it. 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, as a row marked `security`, which `rank_todo.py` ranks first in its release, naming the exposure and the path it reaches. 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 move it down if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius. +- **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. +- 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. ## Quality diff --git a/bin/loop_claude/project/premises.py b/bin/loop_claude/project/premises.py index e6289e5c..41768a5a 100644 --- a/bin/loop_claude/project/premises.py +++ b/bin/loop_claude/project/premises.py @@ -1,7 +1,10 @@ import pathlib +import re from loop_claude.stop import Stop +FENCE = re.compile(r"^ {0,3}(```|~~~)", re.M) + def read_premises(root: str) -> str | Stop: try: @@ -26,7 +29,7 @@ def sections(text: str) -> dict[str, list[str]]: blocks: list[tuple[str | None, list[str]]] = [] fenced = False for line in text.splitlines(): - fenced ^= line.startswith("```") + fenced ^= bool(FENCE.match(line)) 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 a3ac6ee8..c17b01c0 100755 --- a/bin/rank_todo.py +++ b/bin/rank_todo.py @@ -1,14 +1,14 @@ #!/usr/bin/env python3 -"""Score and rank todo.md's items by the formula, bar and goal weights it states. +"""Score todo.md's items by the formula and goal weights it states, and hold them to its bar. usage: rank_todo.py [--check] [todo.md] Reads todo.md (default: ./todo.md), the README.md beside it, and docs/decisions.md when there is -one. Rewrites each item's Score from the formula, sorts the items by release, then security rows, -then score from highest, then ID, and orders the details to match. --check writes nothing and fails -when the file is not ranked as it would be. +one. Rewrites each item's Score from the formula and sorts the items by release; within a release, +security rows come first, then the rest by score from highest, then by ID. Orders the details to +match. --check writes nothing and fails when the file is not ranked as it would be. -A valid todo.md, every line shown required: +A valid todo.md; ## Details and each item's detail are optional: # todo @@ -38,15 +38,16 @@ A valid todo.md, every line shown required: - The formula holds numbers, + - * / and parentheses over R, S, A, G and W. - The bar is judged on the Score as shown, to one decimal. -- A new item takes Next ID, and Next ID then counts up; no row may reach it. +- 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, A and G are whole numbers from 1 to 10; Goals lists goal numbers, comma separated. - An item's Exempt cell is empty, or names why the bar does not apply: decision, defect, question - or security. An item docs/decisions.md cites as "`todo.md` item N" is marked decision. + 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. - 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, 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, 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. """ import ast import dataclasses @@ -55,11 +56,13 @@ import pathlib import re import sys +# loop_claude's leaf modules, so both tools share one error type and one README parser. from loop_claude.failure import Failure -from loop_claude.project.premises import sections +from loop_claude.project.premises import FENCE, sections EXEMPTIONS = ("", "decision", "defect", "question", "security") ITEMS_HEADER = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |" +LARGEST_FORMULA = 200 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") WEIGHTS_HEADER = "| Goal | W |" @@ -75,6 +78,21 @@ class Item: goals: tuple[str, ...] +@dataclasses.dataclass(frozen=True) +class Scoring: + formula: ast.Expression + bar: float + next_id: int + weights: dict[str, float] + + +@dataclasses.dataclass(frozen=True) +class Table: + """Body rows of a markdown table, and the index of the first in the file's lines.""" + start: int + rows: list[str] + + @dataclasses.dataclass(frozen=True) class Ranked: text: str @@ -85,46 +103,87 @@ 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(f"rank_todo.py: cannot read the arguments {' '.join(argv)}; usage: rank_todo.py [--check] [todo.md]", file=sys.stderr) - return 1 - todo = pathlib.Path(paths[0] if paths else "todo.md") - decisions = todo.parent / "docs" / "decisions.md" - read_in = [read(todo), read(todo.parent / "README.md"), read(decisions) if decisions.exists() else ""] - unread = next((found for found in read_in if isinstance(found, Failure)), None) - if unread: - print(unread.reason, file=sys.stderr) - return 1 - text, readme, cited = (str(found) for found in read_in) - ranked = rank(text, readme, cited) + args = parse_args(argv) + if isinstance(args, Failure): + return fail(args) + check, todo = args + texts = read_all(todo) + if isinstance(texts, Failure): + return fail(texts) + ranked = rank(*texts) if isinstance(ranked, Failure): - print(ranked.reason, file=sys.stderr) - return 1 - if ranked.text != text: - if check: - print(f"{todo}: not ranked; run rank_todo.py on it", file=sys.stderr) - return 1 - todo.write_text(ranked.text, encoding="utf-8") + return fail(ranked) + if ranked.text != texts[0]: + unwritten = Failure(f"{todo}: not ranked; run rank_todo.py on it") if check else write(todo, ranked.text) + if unwritten: + return fail(unwritten) for line in ranked.under_bar: print(f"{todo}: {line}", file=sys.stderr) return 1 if ranked.under_bar else 0 -def read(path: pathlib.Path) -> str | Failure: +def fail(failure: Failure) -> int: + print(failure.reason, file=sys.stderr) + return 1 + + +def parse_args(argv: list[str]) -> tuple[bool, pathlib.Path] | Failure: + paths = [arg for arg in argv if arg != "--check"] + if len(paths) > 1 or any(path.startswith("-") for path in paths): + return Failure(f"rank_todo.py: cannot read the arguments {' '.join(argv)}; usage: rank_todo.py [--check] [todo.md]") + return "--check" in argv, pathlib.Path(paths[0] if paths else "todo.md") + + +def read_all(todo: pathlib.Path) -> tuple[str, str, str] | Failure: + """todo.md, the README.md beside it, and its docs/decisions.md, empty when there is none.""" + texts = [] + for path, missing in ((todo, "every project keeps a todo.md beside its README.md, and rank_todo.py --help shows one"), (todo.parent / "README.md", "rank_todo.py weighs goals from the README.md beside todo.md"), (todo.parent / "docs" / "decisions.md", None)): + try: + texts.append(path.read_text(encoding="utf-8")) + except FileNotFoundError: + if missing: + return Failure(f"{path}: not found; {missing}") + texts.append("") + except OSError as failure: + return Failure(f"{path}: {failure.strerror}") + except UnicodeDecodeError: + return Failure(f"{path}: not UTF-8") + return texts[0], texts[1], texts[2] + + +def write(path: pathlib.Path, text: str) -> Failure | None: try: - return path.read_text(encoding="utf-8") - except FileNotFoundError: - return Failure(f"{path}: not found; every project keeps a todo.md beside its README.md, and rank_todo.py --help shows one") + path.write_text(text, encoding="utf-8") except OSError as failure: return Failure(f"{path}: {failure.strerror}") - except UnicodeDecodeError: - return Failure(f"{path}: not UTF-8") + return None def rank(text: str, readme: str, decisions: str) -> Ranked | Failure: lines = text.split("\n") + scoring = read_scoring(text, lines, readme) + if isinstance(scoring, Failure): + return scoring + table = read_items(lines, scoring, decisions) + if isinstance(table, Failure): + return table + items, start = table + scored = [] + for item in items: + value = score(scoring.formula, item, scoring.weights) + if isinstance(value, Failure): + return value + scored.append((item, value)) + scored.sort(key=lambda pair: (pair[0].release, pair[0].exempt != "security", -pair[1], pair[0].id)) + lines[start:start + len(scored)] = [render_item(item, value) for item, value in scored] + ranked = rank_details("\n".join(lines), [item for item, _ in scored]) + if isinstance(ranked, Failure): + return ranked + under_bar = [f"item {item.id} scores {value:.1f}, under the bar {scoring.bar:g}; delete it and any item that needs it, or mark it with a reason the bar does not apply" for item, value in scored if not item.exempt and round(value, 1) < scoring.bar] + return Ranked(ranked, under_bar) + + +def read_scoring(text: str, lines: list[str], readme: str) -> Scoring | Failure: if ITEMS_HEADER not in lines and "## Items" not in lines: return Failure("todo.md is not in the scored-table format; rank_todo.py --help shows a valid one") goals = readme_goals(readme) @@ -136,35 +195,42 @@ def rank(text: str, readme: str, decisions: str) -> Ranked | Failure: bar = number(stated(text, "Bar"), "the bar") if isinstance(bar, Failure): return bar - next_id = number(stated(text, "Next ID"), "Next ID") - if isinstance(next_id, Failure): - return next_id + 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) if isinstance(weights, Failure): return weights - items = parse_items(lines, weights) - if isinstance(items, Failure): - return items - ids = [item.id for item in items] - if ids and max(ids) >= next_id: - return Failure(f"item {max(ids)} is not under Next ID {next_id:g}; raise Next ID past every ID") - marked = {item.id for item in items if item.exempt == "decision"} - if unmarked := sorted(set(cited_items(decisions)) - marked): - return Failure(f"docs/decisions.md cites todo.md item {', '.join(map(str, unmarked))}, which no row marked decision holds") - scored = [] - for item in items: - value = score(formula, item, weights) - if isinstance(value, Failure): - return value - scored.append((item, value)) - scored.sort(key=lambda pair: (pair[0].release, pair[0].exempt != "security", -pair[1], pair[0].id)) - start = lines.index(ITEMS_HEADER) + 2 - lines[start:start + len(scored)] = [render_item(item, value) for item, value in scored] - ranked = rank_details("\n".join(lines), [item for item, _ in scored]) - if isinstance(ranked, Failure): - return ranked - under_bar = [f"item {item.id} scores {value:.1f}, under the bar {bar:g}; delete it and any item that needs it, or mark it with a reason the bar does not apply" for item, value in scored if not item.exempt and round(value, 1) < bar] - return Ranked(ranked, under_bar) + 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.""" + 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))]): + return Failure("## Items holds a row outside its table; keep the rows together under the header") + items = [] + for row in table.rows: + item = parse_item(row, scoring.weights) + if isinstance(item, Failure): + return item + items.append(item) + ids = {item.id for item in items} + if len(ids) < len(items): + 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 readme_goals(readme: str) -> list[str] | Failure: @@ -174,10 +240,10 @@ def readme_goals(readme: str) -> list[str] | Failure: return Failure(f"README.md has ## Goals {len(found)} times; it needs it once") goals: list[str] = [] path: list[tuple[int, str]] = [] - for indent, number in re.findall(r"^([ \t]*)(\d+)\. ", found[0].expandtabs(4), re.M): + for indent, position in re.findall(r"^([ \t]*)(\d+)\. ", found[0].expandtabs(4), re.M): while path and path[-1][0] >= len(indent): path.pop() - path.append((len(indent), number)) + path.append((len(indent), position)) goals.append(".".join(part for _, part in path)) if not goals: return Failure("README.md's ## Goals has no numbered goal") @@ -202,10 +268,13 @@ def parse_formula(source: str | Failure) -> ast.Expression | Failure: return source try: tree = ast.parse(source, mode="eval") - except SyntaxError: + except (SyntaxError, ValueError): return Failure(f"the formula {source!r} does not parse") - for node in ast.walk(tree): - numeric = isinstance(node, ast.Constant) and type(node.value) in (int, float) + nodes = list(ast.walk(tree)) + if len(nodes) > LARGEST_FORMULA: + 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") return tree @@ -253,17 +322,19 @@ def number(text: str | Failure, what: str) -> float | Failure: def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float] | Failure: - rows = table_rows(lines, WEIGHTS_HEADER) - if isinstance(rows, Failure): - return rows + table = table_rows(lines, WEIGHTS_HEADER) + if isinstance(table, Failure): + return table weights: dict[str, float] = {} - for row in rows: + for row in table.rows: found = cells(row, 2) if isinstance(found, Failure): return found weight = number(found[1], f"goal {found[0]}'s weight") if isinstance(weight, Failure): return weight + if found[0] in weights: + return Failure(f"the goal weights list goal {found[0]} twice") weights[found[0]] = weight if list(weights) != goals: default = "\n".join(f"| {goal} | {(len(goals) - index) / len(goals):.2f} |" for index, goal in enumerate(goals)) @@ -271,26 +342,7 @@ def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float] | Fail return weights -def parse_items(lines: list[str], weights: dict[str, float]) -> list[Item] | Failure: - rows = table_rows(lines, ITEMS_HEADER) - if isinstance(rows, Failure): - return rows - after = lines[lines.index(ITEMS_HEADER) + 2 + len(rows):] - if any(line.startswith("|") for line in section_lines(after)): - return Failure("## Items holds a row outside its table; keep the rows together under the header") - items = [] - for row in rows: - item = parse_item(row, weights) - if isinstance(item, Failure): - return item - items.append(item) - if len({item.id for item in items}) < len(items): - return Failure("two items share an ID") - return items - - -def table_rows(lines: list[str], header: str) -> list[str] | Failure: - """A table's body rows, below its header and divider.""" +def table_rows(lines: list[str], header: str) -> Table | Failure: if lines.count(header) != 1: return Failure(f"todo.md needs the table header {header} once") start = lines.index(header) + 2 @@ -299,11 +351,7 @@ def table_rows(lines: list[str], header: str) -> list[str] | Failure: end = start while end < len(lines) and lines[end].startswith("|"): end += 1 - return lines[start:end] - - -def section_lines(lines: list[str]) -> list[str]: - return lines[:next((index for index, line in enumerate(lines) if line.startswith("## ")), len(lines))] + return Table(start, lines[start:end]) def cells(row: str, count: int) -> list[str] | Failure: @@ -312,6 +360,7 @@ 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 @@ -348,7 +397,7 @@ def rank_details(text: str, items: list[Item]) -> str | Failure: 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): + if FENCE.search(body): return Failure("## 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(): diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py index cc8af755..6731d81d 100644 --- a/bin/test_rank_todo.py +++ b/bin/test_rank_todo.py @@ -73,6 +73,11 @@ class Rank(unittest.TestCase): self.assertEqual(ranked.under_bar, []) self.assertEqual(self.ranked(ranked.text), ranked) + 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") + def test_names_each_item_under_the_bar_that_is_not_exempt(self): ranked = self.ranked(TODO.replace("`Bar = 9`", "`Bar = 11`")) self.assertEqual(ranked.under_bar, ["item 2 scores 10.3, under the bar 11; delete it and any item that needs it, or mark it with a reason the bar does not apply"]) @@ -88,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)"): + for formula in ("__import__('os')", "R.real", "X + 1", "R ** 2", "R +", "R / (S - 2)", "R\x00", "1" * 400, " + ".join(["R"] * 300)): with self.subTest(formula=formula): self.assertIsInstance(self.ranked(TODO.replace("-R - S/4 + 2*A + 2*G*W", formula)), Failure) @@ -101,6 +106,8 @@ class Rank(unittest.TestCase): "| 4 | 0.1.0 | security |": "| 4 | 0.1.0 | later |", "| 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 |", "Fast detail.": "```\n## Goals\n```", "### 3. Make it fast.": "### 7. Make it fast.", "`Bar = 9`": "`Bar = nan`", @@ -131,7 +138,7 @@ class Main(unittest.TestCase): pathlib.Path(temp, "README.md").write_bytes(b"\xff") self.assertEqual(self.run_main(str(todo)), (1, f"{temp}/README.md: not UTF-8\n")) pathlib.Path(temp, "README.md").unlink() - self.assertIn("README.md: not found", self.run_main(str(todo))[1]) + self.assertEqual(self.run_main(str(todo)), (1, f"{temp}/README.md: not found; rank_todo.py weighs goals from the README.md beside todo.md\n")) def test_shows_a_valid_file_in_help_and_names_arguments_it_cannot_read(self): self.assertEqual(self.run_main("--help")[0], 0) diff --git a/docs/decisions.md b/docs/decisions.md index 9f2949da..9fb679da 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -30,11 +30,11 @@ ## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run on `rebuild`, 2026-10-01, lilleman. `rebuild` merged into main under the floor at 8585257's scores, 2026-10-01, lilleman. The 2026-10-01 run on PR #182 (the loop state machine) scored 7.5, 6.5, 6.88, 6.25, 6.38; lilleman shipped that PR under the floor and below `rebuild`'s best run the same day, its places filed in `todo.md` under 0.1.0. The 2026-10-02 run on PR #187 (`loop_claude`'s names, the exit contract) scored 7.75, 7.25, 7.38, 6.88, 7.25 at 70362d0, every seat naming larv-review §3 under Self-sufficiency, and 7.63, 7.13, 7.38, 7.0, 7.13 at 1971dba later that day, the first run at the floor, with no dimension or the overall below its best run on `rebuild`. The 2026-10-02 runs on PR #191 (the status line in Python) scored 7.5, 7.0, 7.13, 6.88, 7.13; 7.25, 6.75, 7.25, 6.88, 7.0; 7.63, 6.88, 7.38, 7.0, 7.13; and 7.63, 7.0, 7.25, 6.75, 7.25. Every seat rated the status line easy. The places they named under Locality and Self-sufficiency are filed in `todo.md` under 0.1.0, except `entries.py`'s heuristics over Claude Code's transcript format, which the seats scored as the problem's own difficulty. lilleman decided the same day to ship that PR under the floor. The 2026-10-02 runs on PR #194 (each cycle's transcript archived) scored 8.0, 7.25, 7.38, 7.13, 7.5 at 6ccd5b1 and 7.75, 7.13, 7.25, 7.0, 7.25 at d104ea0, both at the floor, every seat naming `archive` as the unit it would least want to modify. On 2026-10-02 the bar of `todo.md` purged the places these runs filed, except `todo.md` items 13 and 17. Valid until the next scoring run, which uses the same four seats. +2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run on `rebuild`, 2026-10-01, lilleman. `rebuild` merged into main under the floor at 8585257's scores, 2026-10-01, lilleman. The 2026-10-01 run on PR #182 (the loop state machine) scored 7.5, 6.5, 6.88, 6.25, 6.38; lilleman shipped that PR under the floor and below `rebuild`'s best run the same day, its places filed in `todo.md` under 0.1.0. The 2026-10-02 run on PR #187 (`loop_claude`'s names, the exit contract) scored 7.75, 7.25, 7.38, 6.88, 7.25 at 70362d0, every seat naming larv-review §3 under Self-sufficiency, and 7.63, 7.13, 7.38, 7.0, 7.13 at 1971dba later that day, the first run at the floor, with no dimension or the overall below its best run on `rebuild`. The 2026-10-02 runs on PR #191 (the status line in Python) scored 7.5, 7.0, 7.13, 6.88, 7.13; 7.25, 6.75, 7.25, 6.88, 7.0; 7.63, 6.88, 7.38, 7.0, 7.13; and 7.63, 7.0, 7.25, 6.75, 7.25. Every seat rated the status line easy. The places they named under Locality and Self-sufficiency are filed in `todo.md` under 0.1.0, except `entries.py`'s heuristics over Claude Code's transcript format, which the seats scored as the problem's own difficulty. lilleman decided the same day to ship that PR under the floor. The 2026-10-02 runs on PR #194 (each cycle's transcript archived) scored 8.0, 7.25, 7.38, 7.13, 7.5 at 6ccd5b1 and 7.75, 7.13, 7.25, 7.0, 7.25 at d104ea0, both at the floor, every seat naming `archive` as the unit it would least want to modify. On 2026-10-02, applying `todo.md`'s bar deleted every place these scoring runs filed except `todo.md` items 13 and 17. Valid until the next scoring run, which uses the same four seats. ## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes -2026-09-26, lilleman. Serves goal 4. Claude Code rewrites the user settings' `model` whenever one is picked inside a session, so a loop reading settings runs whatever was picked last; `~/.claude/loop-claude-models.json` has loop-claude as its one writer, and every claude it starts gets that model as `--model`. The file is per machine, outside the synced allowlist, since a tracked file the loop writes would dirty the checkout. 2026-10-02, lilleman: goal 1 shares the setup across machines, and a project's model is not part of it, so each new machine asks once per project. Valid while Claude Code keeps rewriting the settings' model from inside a session. +2026-09-26, lilleman. Serves goal 4. Claude Code rewrites the user settings' `model` whenever one is picked inside a session, so a loop reading settings runs whatever was picked last; `~/.claude/loop-claude-models.json` has loop-claude as its one writer, and every claude it starts gets that model as `--model`. The file is per machine, outside the synced allowlist, since a tracked file the loop writes would dirty the checkout. 2026-10-02, lilleman: goal 1 shares the setup across machines, and a project's model is not part of it, so each new machine asks once per project. Stands until `todo.md` item 35 settles it. Valid while Claude Code keeps rewriting the settings' model from inside a session. ## review: a pass gets at most three rounds per chunk; instead of a fourth, the run asks the human @@ -76,6 +76,6 @@ 2026-10-02, lilleman. Serves goal 3, which keeps credentials, transcripts and memory files off the remote; a private project's name and commit ids are none of those. Valid while the bench names only cases and commits, never their code or results. -## todo.md: one table of items scored by the formula, bar and goal weights it states, ranked by `bin/rank_todo.py` +## 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: a security finding, a 🔴 defect, a question for the human, an item a decision names. 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, rather than keep plans scored under the bar. `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: 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. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index c2f9df33..e4bf0161 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -61,11 +61,11 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Findings.** -1. A finding outside the chunk's change, whatever its pass or severity, is scored and filed in `todo.md` per `~/.claude/CLAUDE.md` → "Todo items", a 🔴 marked `defect`; one under the bar and not exempt is named in the summary with its score instead. A verified security HIGH is handled per "Security". -2. A fix that would change a goal, or a decision the repo held before the chunk began, is asked; no user reachable → filed as a `question`, the goal or decision left as is. +1. A finding outside the chunk's change, whatever its pass or severity, is scored and filed in `todo.md` per `~/.claude/CLAUDE.md` → "Todo items". A 🔴 is marked `defect`. One under the bar and not exempt is named in the summary with its score. A verified security HIGH is handled per "Security". +2. A fix that would change a goal, or a decision the repo held before the chunk began, is asked; no user reachable → filed, marked `question`, the goal or decision left as is. 3. A 🔴 is fixed, or shown factually wrong, and what disproved it recorded per `~/.claude/CLAUDE.md` → "Decisions: one home, each linked to a goal or a technical principle": in a comment at the code the finding concerns, or in `docs/decisions.md` when it concerns more than one place. Never declined. 4. A 🟡 is fixed, shown factually wrong like a 🔴, or declined. Decline one only where the reason is sound, consistent with the goals and the technical principles, and confidence is very high; the decline and its reason are recorded the same way. A reason neither speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess"; no user reachable → fix. Never drop one silently, and never decline one for convenience or the size of the fix. -5. A 🟢 or ❓ is fixed, answered, declined in the summary with its reason, or filed. Answer one where the code, a test or a record settles it, and quote what in the summary. A ❓ only the user can answer is asked; no user reachable → filed as a `question`. +5. A 🟢 or ❓ is fixed, answered, declined in the summary with its reason, or filed. Answer one where the code, a test or a record settles it, and quote what in the summary. A ❓ only the user can answer is asked; no user reachable → filed, marked `question`. 6. A 🔀 runs the named pass once the current pass is done. 7. Other reviewers map onto this scale: `/security-review`'s HIGH is 🔴, MEDIUM 🟡, LOW 🟢; what a forge's auto-reviewer marks blocking is 🔴. A finding of theirs repeating one declined or filed does not stand. @@ -100,7 +100,7 @@ Launch prose-reviewer with what the diff touched and every section this review c ## 4. Gate -1. Run `~/.claude/bin/rank_todo.py --check todo.md`. +1. Run `~/.claude/bin/rank_todo.py --check todo.md`; a failure is a finding. 2. Run the project's test suite locally unless the last stability round already left it verified green. 3. Watch the forge's checks until every one passes. A red check is a finding. 4. No CI configured → the gate is local tests only; note it in the summary. -- 2.52.0 From 89c88b51634138d3a60864ce054b5a87536b4b86 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 2 Oct 2026 21:54:06 +0200 Subject: [PATCH 5/7] 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. -- 2.52.0 From 3f0f329ef99327c7f7914b4f972d0480a28aab99 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 2 Oct 2026 21:57:31 +0200 Subject: [PATCH 6/7] Record PR #196's scoring runs and the decision to ship under the floor --- docs/decisions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/decisions.md b/docs/decisions.md index 8ccd9dd9..d83e843b 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -30,7 +30,7 @@ ## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run on `rebuild`, 2026-10-01, lilleman. `rebuild` merged into main under the floor at 8585257's scores, 2026-10-01, lilleman. The 2026-10-01 run on PR #182 (the loop state machine) scored 7.5, 6.5, 6.88, 6.25, 6.38; lilleman shipped that PR under the floor and below `rebuild`'s best run the same day, its places filed in `todo.md` under 0.1.0. The 2026-10-02 run on PR #187 (`loop_claude`'s names, the exit contract) scored 7.75, 7.25, 7.38, 6.88, 7.25 at 70362d0, every seat naming larv-review §3 under Self-sufficiency, and 7.63, 7.13, 7.38, 7.0, 7.13 at 1971dba later that day, the first run at the floor, with no dimension or the overall below its best run on `rebuild`. The 2026-10-02 runs on PR #191 (the status line in Python) scored 7.5, 7.0, 7.13, 6.88, 7.13; 7.25, 6.75, 7.25, 6.88, 7.0; 7.63, 6.88, 7.38, 7.0, 7.13; and 7.63, 7.0, 7.25, 6.75, 7.25. Every seat rated the status line easy. The places they named under Locality and Self-sufficiency are filed in `todo.md` under 0.1.0, except `entries.py`'s heuristics over Claude Code's transcript format, which the seats scored as the problem's own difficulty. lilleman decided the same day to ship that PR under the floor. The 2026-10-02 runs on PR #194 (each cycle's transcript archived) scored 8.0, 7.25, 7.38, 7.13, 7.5 at 6ccd5b1 and 7.75, 7.13, 7.25, 7.0, 7.25 at d104ea0, both at the floor, every seat naming `archive` as the unit it would least want to modify. On 2026-10-02, applying `todo.md`'s bar deleted every place these scoring runs filed except `todo.md` items 13 and 17. Valid until the next scoring run, which uses the same four seats. +2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run on `rebuild`, 2026-10-01, lilleman. `rebuild` merged into main under the floor at 8585257's scores, 2026-10-01, lilleman. The 2026-10-01 run on PR #182 (the loop state machine) scored 7.5, 6.5, 6.88, 6.25, 6.38; lilleman shipped that PR under the floor and below `rebuild`'s best run the same day, its places filed in `todo.md` under 0.1.0. The 2026-10-02 run on PR #187 (`loop_claude`'s names, the exit contract) scored 7.75, 7.25, 7.38, 6.88, 7.25 at 70362d0, every seat naming larv-review §3 under Self-sufficiency, and 7.63, 7.13, 7.38, 7.0, 7.13 at 1971dba later that day, the first run at the floor, with no dimension or the overall below its best run on `rebuild`. The 2026-10-02 runs on PR #191 (the status line in Python) scored 7.5, 7.0, 7.13, 6.88, 7.13; 7.25, 6.75, 7.25, 6.88, 7.0; 7.63, 6.88, 7.38, 7.0, 7.13; and 7.63, 7.0, 7.25, 6.75, 7.25. Every seat rated the status line easy. The places they named under Locality and Self-sufficiency are filed in `todo.md` under 0.1.0, except `entries.py`'s heuristics over Claude Code's transcript format, which the seats scored as the problem's own difficulty. lilleman decided the same day to ship that PR under the floor. The 2026-10-02 runs on PR #194 (each cycle's transcript archived) scored 8.0, 7.25, 7.38, 7.13, 7.5 at 6ccd5b1 and 7.75, 7.13, 7.25, 7.0, 7.25 at d104ea0, both at the floor, every seat naming `archive` as the unit it would least want to modify. On 2026-10-02, applying `todo.md`'s bar deleted every place these scoring runs filed except `todo.md` items 13 and 17. The 2026-10-02 runs on PR #196 (`todo.md` as one scored table) scored 7.63, 6.88, 7.25, 6.88, 7.13 at c0dba66; 7.5, 6.88, 7.13, 6.75, 7.0 at 798dfd7; and 7.5, 7.0, 7.0, 6.75, 7.0 at b712076, every seat naming under Self-sufficiency larv-review §3 and the agents, which need `CLAUDE.md` open beside them. lilleman decided the same day to ship that PR under the floor, `todo.md` item 13 the place filed. Valid until the next scoring run, which uses the same four seats. ## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes -- 2.52.0 From 6096f7d279458206e6aaf025d5b4244fe72f1edf Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 2 Oct 2026 21:59:57 +0200 Subject: [PATCH 7/7] Answer the final checks: the decision exemption's wording, info strings never close a fence, one formula length limit --- CLAUDE.md | 2 +- bin/loop_claude/project/premises.py | 3 +-- bin/rank_todo.py | 9 +++++---- bin/test_loop_claude.py | 1 + docs/decisions.md | 2 +- 5 files changed, 9 insertions(+), 8 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 9cbc2085..d2774744 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 only `docs/decisions.md` keeps. An item `docs/decisions.md` cites carries one of these reasons. +- **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. Every 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 77b375eb..ba152799 100644 --- a/bin/loop_claude/project/premises.py +++ b/bin/loop_claude/project/premises.py @@ -29,12 +29,11 @@ def sections(text: str) -> dict[str, list[str]]: blocks: list[tuple[str | None, list[str]]] = [] opener = "" for line in text.splitlines(): - # 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): + elif marker[0] == opener[0] and len(marker) >= len(opener) and not line[fence.end():].strip(): opener = "" fenced = bool(opener or fence) if not fenced and line.startswith("## "): diff --git a/bin/rank_todo.py b/bin/rank_todo.py index 65541c5c..5c2b2951 100755 --- a/bin/rank_todo.py +++ b/bin/rank_todo.py @@ -57,7 +57,7 @@ import pathlib import re import sys -# Kept inside loop_claude/ so reload's fingerprint covers them; this tool shares the error type and README parser. +# Kept inside loop_claude/ so reload's fingerprint covers them. from loop_claude.failure import Failure from loop_claude.file_writes import replace_file from loop_claude.project.premises import FENCE, sections @@ -65,6 +65,7 @@ from loop_claude.project.premises import FENCE, sections EXEMPTIONS = ("", "decision", "defect", "question", "security") ITEMS_HEADER = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |" 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") WEIGHTS_HEADER = "| Goal | W |" @@ -154,7 +155,7 @@ def read_all(todo: pathlib.Path) -> tuple[str, str, str] | Failure: def write(path: pathlib.Path, text: str) -> Failure | None: - unwritten = replace_file(path, text.encode("utf-8")) + unwritten = replace_file(path.resolve(), text.encode("utf-8")) return Failure(f"{path}: {unwritten.reason}") if unwritten else None @@ -279,8 +280,8 @@ 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") + if len(source) > LONGEST_FORMULA: + return Failure(f"the formula {source[:40]!r}... holds more than {LONGEST_FORMULA} characters") try: tree = ast.parse(source, mode="eval") except (SyntaxError, ValueError): diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 94320fd0..69bed5d0 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -310,6 +310,7 @@ class Sections(unittest.TestCase): 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"]) + self.assertEqual(list(premises.sections("```\nquoted:\n```python\n## Inside\n```\n## Goals\n1. one\n")), ["Goals"]) class Render(unittest.TestCase): diff --git a/docs/decisions.md b/docs/decisions.md index d83e843b..e4e4803e 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -30,7 +30,7 @@ ## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run on `rebuild`, 2026-10-01, lilleman. `rebuild` merged into main under the floor at 8585257's scores, 2026-10-01, lilleman. The 2026-10-01 run on PR #182 (the loop state machine) scored 7.5, 6.5, 6.88, 6.25, 6.38; lilleman shipped that PR under the floor and below `rebuild`'s best run the same day, its places filed in `todo.md` under 0.1.0. The 2026-10-02 run on PR #187 (`loop_claude`'s names, the exit contract) scored 7.75, 7.25, 7.38, 6.88, 7.25 at 70362d0, every seat naming larv-review §3 under Self-sufficiency, and 7.63, 7.13, 7.38, 7.0, 7.13 at 1971dba later that day, the first run at the floor, with no dimension or the overall below its best run on `rebuild`. The 2026-10-02 runs on PR #191 (the status line in Python) scored 7.5, 7.0, 7.13, 6.88, 7.13; 7.25, 6.75, 7.25, 6.88, 7.0; 7.63, 6.88, 7.38, 7.0, 7.13; and 7.63, 7.0, 7.25, 6.75, 7.25. Every seat rated the status line easy. The places they named under Locality and Self-sufficiency are filed in `todo.md` under 0.1.0, except `entries.py`'s heuristics over Claude Code's transcript format, which the seats scored as the problem's own difficulty. lilleman decided the same day to ship that PR under the floor. The 2026-10-02 runs on PR #194 (each cycle's transcript archived) scored 8.0, 7.25, 7.38, 7.13, 7.5 at 6ccd5b1 and 7.75, 7.13, 7.25, 7.0, 7.25 at d104ea0, both at the floor, every seat naming `archive` as the unit it would least want to modify. On 2026-10-02, applying `todo.md`'s bar deleted every place these scoring runs filed except `todo.md` items 13 and 17. The 2026-10-02 runs on PR #196 (`todo.md` as one scored table) scored 7.63, 6.88, 7.25, 6.88, 7.13 at c0dba66; 7.5, 6.88, 7.13, 6.75, 7.0 at 798dfd7; and 7.5, 7.0, 7.0, 6.75, 7.0 at b712076, every seat naming under Self-sufficiency larv-review §3 and the agents, which need `CLAUDE.md` open beside them. lilleman decided the same day to ship that PR under the floor, `todo.md` item 13 the place filed. Valid until the next scoring run, which uses the same four seats. +2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run on `rebuild`, 2026-10-01, lilleman. `rebuild` merged into main under the floor at 8585257's scores, 2026-10-01, lilleman. The 2026-10-01 run on PR #182 (the loop state machine) scored 7.5, 6.5, 6.88, 6.25, 6.38; lilleman shipped that PR under the floor and below `rebuild`'s best run the same day, its places filed in `todo.md` under 0.1.0. The 2026-10-02 run on PR #187 (`loop_claude`'s names, the exit contract) scored 7.75, 7.25, 7.38, 6.88, 7.25 at 70362d0, every seat naming larv-review §3 under Self-sufficiency, and 7.63, 7.13, 7.38, 7.0, 7.13 at 1971dba later that day, the first run at the floor, with no dimension or the overall below its best run on `rebuild`. The 2026-10-02 runs on PR #191 (the status line in Python) scored 7.5, 7.0, 7.13, 6.88, 7.13; 7.25, 6.75, 7.25, 6.88, 7.0; 7.63, 6.88, 7.38, 7.0, 7.13; and 7.63, 7.0, 7.25, 6.75, 7.25. Every seat rated the status line easy. The places they named under Locality and Self-sufficiency are filed in `todo.md` under 0.1.0, except `entries.py`'s heuristics over Claude Code's transcript format, which the seats scored as the problem's own difficulty. lilleman decided the same day to ship that PR under the floor. The 2026-10-02 runs on PR #194 (each cycle's transcript archived) scored 8.0, 7.25, 7.38, 7.13, 7.5 at 6ccd5b1 and 7.75, 7.13, 7.25, 7.0, 7.25 at d104ea0, both at the floor, every seat naming `archive` as the unit it would least want to modify. On 2026-10-02, applying `todo.md`'s bar deleted every place these scoring runs filed except `todo.md` items 13 and 17. The 2026-10-02 runs on PR #196 (`todo.md` as one scored table) scored 7.63, 6.88, 7.25, 6.88, 7.13 at c0dba66; 7.5, 6.88, 7.13, 6.75, 7.0 at 798dfd7; and 7.5, 7.0, 7.0, 6.75, 7.0 at b712076. Under Self-sufficiency, every seat named larv-review §3 and the agents, which a reader follows only with `CLAUDE.md` open. lilleman decided the same day to ship that PR under the floor; the place filed is `todo.md` item 13. Valid until the next scoring run, which uses the same four seats. ## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes -- 2.52.0