Score and rank todo.md in one table by the formula, bar and goal weights it states

This commit is contained in:
2026-10-02 19:38:31 +02:00
parent 9aa0e0bb3d
commit c12a4109f9
11 changed files with 473 additions and 68 deletions
+1
View File
@@ -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/
+1
View File
@@ -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
+1
View File
@@ -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.
+11 -3
View File
@@ -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.
+1
View File
@@ -29,6 +29,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, and tag that co
## Tools
- `loop-claude <task>` 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'`
+239
View File
@@ -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 = <formula>` under ## Scoring, sorts the ## Items table by release, then score from highest,
then ID, and orders ## Details to match, each heading `### <ID>. <tagline>`. --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 = <number>` 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"(?<!\\)\|", row.strip())[1:-1]]
if len(found) != count:
raise Malformed(f"this row needs {count} cells: {row}")
return found
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:
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 ### <ID>. 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:]))
+105
View File
@@ -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, []))
+1 -1
View File
@@ -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)
+4
View File
@@ -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.
+1 -1
View File
@@ -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.
+108 -63
View File
@@ -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 `<key>/` 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 `<key>/` 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 `<key>/` 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`.