Check loop_claude's type annotations with mypy in the tests #142

Merged
lilleman merged 4 commits from type-check into rebuild 2026-09-29 15:50:54 +02:00
14 changed files with 45 additions and 20 deletions
+1
View File
@@ -24,3 +24,4 @@ Decisions live in `docs/decisions.md`:
- loop-claude: a loop running main's script stops once at the cut-over
- rebuild: a chunk into `rebuild` takes no comprehension scoring run
- loop-claude: a `claude` that cannot start is a failed worker run, retried
- bin/: mypy checks `loop_claude`'s types in the tests
+1 -1
View File
@@ -25,7 +25,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, and tag that co
- `loop-claude <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract.
Test on the host, with `uv` on `PATH` to fetch the Python version Install names (`docs/decisions.md` → "bin/: host python, no container", "bin/: the Python floor is README's Install prerequisite"): `python3 -m unittest discover -s bin -p 'test_*.py'`
Test on the host, with `uv` on `PATH` to fetch mypy and the Python version Install names (`docs/decisions.md` → "bin/: host python, no container", "bin/: the Python floor is README's Install prerequisite"): `python3 -m unittest discover -s bin -p 'test_*.py'`
## Tracking a new file
+3 -3
View File
@@ -43,7 +43,7 @@ def written_by_human(entry) -> bool:
texts = [part_text(part) for part in parts(entry)]
# {"type": "user", "message": {"content": [{"tool_use_id": "toolu_01…", "type": "tool_result", "content": "hi"}]}}
# {"type": "user", "message": {"content": [{"type": "text", "text": "[Request interrupted by user]"}]}}
return bool(texts) and None not in texts and not any(text.startswith("[Request interrupted") for text in texts)
return bool(texts) and all(text is not None and not text.startswith("[Request interrupted") for text in texts)
def human_text(entry) -> str | None:
@@ -100,11 +100,11 @@ def mark_trusted(config, roots) -> tuple[dict, list[str]] | Failure:
# A model catalog file: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}}
def models_in(files) -> list[tuple[str, object]]:
"""The (id, name) of each model in the newest of the parsed catalog files."""
newest = {}
newest: dict = {}
for data in files:
if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1):
newest = data
models = newest
models: object = newest
for key in ("catalog", "config", "models"):
models = models.get(key) if isinstance(models, dict) else None
return [(entry["id"], entry.get("name", entry["id"])) for entry in models if isinstance(entry, dict) and isinstance(entry.get("id"), str)] if isinstance(models, list) else []
+2 -2
View File
@@ -21,7 +21,7 @@ def trust(config, roots) -> None:
updated, untrusted = marked
if not untrusted:
return
if failure := replace_json(config, updated, indent=2):
print(f"could not write {config}: {failure.reason}", file=sys.stderr)
if unwritten := replace_json(config, updated, indent=2):
print(f"could not write {config}: {unwritten.reason}", file=sys.stderr)
return
print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr)
+2 -2
View File
@@ -17,7 +17,7 @@ def archive(project, path, note, paths) -> Failure | None:
# The copy lands last, so a copy on disk always has its verdict beside it.
if not copy.exists():
for dest, data in ((copy.with_suffix(".verdict.md"), f"{note}\n".encode()), (copy, raw)):
if failure := replace_file(dest, data):
return Failure(f"could not archive the transcript: {dest}: {failure.reason}")
if unwritten := replace_file(dest, data):
return Failure(f"could not archive the transcript: {dest}: {unwritten.reason}")
print(f"transcript: {copy}", file=sys.stderr)
return None
+3 -2
View File
@@ -1,4 +1,3 @@
import itertools
import sys
import time
import typing
@@ -9,7 +8,9 @@ T = typing.TypeVar("T")
def retried(who, attempt: typing.Callable[[], T | Failure]) -> T | Stop:
for failures in itertools.count(1):
failures = 0
while True:
failures += 1
result = attempt()
if not isinstance(result, Failure):
return result
+1 -1
View File
@@ -12,7 +12,7 @@ def run_worker(root, args) -> Failure | None:
return Failure(f"could not start claude: {failure.strerror}")
with proc:
done = False
for raw in proc.stdout:
for raw in proc.stdout or ():
event = parse(raw) or {}
done = done or ends_stream(event)
for part in assistant_parts(event):
+1 -1
View File
@@ -27,5 +27,5 @@ def replace_file(path, data) -> Failure | None:
except OSError as failure:
if os.path.exists(staged):
os.remove(staged)
return Failure(failure.strerror)
return Failure(failure.strerror or str(failure))
return None
+2 -2
View File
@@ -29,8 +29,8 @@ def project_model(name, paths) -> str | Stop:
models = read_models(saved)
if isinstance(models, Stop):
return models
if chosen := models.get(name):
return chosen
if saved_model := models.get(name):
return saved_model
chosen = ask_model(name, saved, paths.model_catalog)
if isinstance(chosen, Stop):
return chosen
+3 -2
View File
@@ -23,7 +23,8 @@ def read_premises(root) -> str | Stop:
def sections(text) -> dict[str, list[str]]:
blocks, fenced = [], False
blocks: list[tuple[str | None, list[str]]] = []
fenced = False
for line in text.splitlines():
fenced ^= line.startswith("```")
if not fenced and line.startswith("## "):
@@ -32,7 +33,7 @@ def sections(text) -> dict[str, list[str]]:
blocks.append((None, []))
elif blocks and line.strip():
blocks[-1][1].append(line)
found = {}
found: dict[str, list[str]] = {}
for name, body in blocks:
if name is not None:
found.setdefault(name, []).append("\n".join(body))
+7 -3
View File
@@ -9,11 +9,15 @@ ROOT = pathlib.Path(__file__).resolve().parents[1]
FLOOR = re.compile(r"Python 3\.(\d+) or newer")
def readme_floor() -> tuple[int, int] | None:
named = FLOOR.search((ROOT / "README.md").read_text(encoding="utf-8"))
return (3, int(named.group(1))) if named else None
class PythonFloor(unittest.TestCase):
def test_the_suite_passes_on_the_python_the_readme_names_as_floor(self):
named = FLOOR.search((ROOT / "README.md").read_text(encoding="utf-8"))
self.assertIsNotNone(named, "README.md's Install names `Python 3.N or newer`")
floor = (3, int(named.group(1)))
floor = readme_floor()
self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`")
if sys.version_info[:2] == floor:
self.skipTest("this run is on the floor")
if shutil.which("uv") is None:
+15
View File
@@ -0,0 +1,15 @@
import shutil
import subprocess
import unittest
from test_python_floor import ROOT, readme_floor
class Types(unittest.TestCase):
def test_mypy_passes_on_loop_claude_at_the_floor(self):
floor = readme_floor()
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", "-p", "loop_claude"], capture_output=True, cwd=ROOT / "bin", text=True)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
+4
View File
@@ -79,3 +79,7 @@
## loop-claude: a `claude` that cannot start is a failed worker run, retried
2026-09-28, larv-review, declining a product-owner nit to exit at once when `claude` is missing. Serves goal 4. Claude Code's updater repoints `~/.local/bin/claude` at each new version under running loops, and a start that meets it mid-update fails with the same error as a broken install; the retry costs two minutes on the second and saves an unattended loop on the first. Valid while Claude Code updates by repointing its link.
## bin/: mypy checks `loop_claude`'s types in the tests
2026-09-29, lilleman. Serves goal 4. An unchecked annotation goes stale when a body gains a return type, and a reader trusts it; the suite already needs `uv`, which fetches a pinned mypy. Valid while `loop_claude` carries annotations.
-1
View File
@@ -16,7 +16,6 @@ The places the panel on `rebuild` at 2c74bbc named (`docs/decisions.md`), cappin
- **Sort `bin/`'s imports on their first binding, per `CLAUDE.md` → "Code style", and keep that rule in one place.** Today they sort by path, so a module move reorders unchanged lines; `CLAUDE.md` and `principles/technical-principles.md` each state the sort key, neither says how case sorts, and "host packages" names no Python group.
- **Reword `CLAUDE.md` → "One spelling per goal" so a copy in code is derived from its owner, and drop the README-caveat sentence and the scope list.** A prose pass found "reject at load" fits only copied config, and the scope list reads as excluding internal code.
- **Name CLI flags and exit codes among larv-review's external contracts, or record that they do not fire the architecture pass.** A prose pass found the product-owner row names the CLI and the architecture row does not.
- **Check `bin/loop_claude/`'s annotations in the gate, or record that review checks them by hand.** Nothing verifies them today, so a body gaining a return type leaves its annotation false unnoticed.
- **Show the judge's reply when `loop-claude` rejects its verdict.** Its stdout is discarded, so a judge that failed three times running leaves nothing to diagnose.
- **Back up `loop-claude`'s transcript archive to a destination other than this repo's remote.**
- **Make the contributor a standing member of every project's audience, dropped only where `## Audience` says maintainability does not matter.** `CLAUDE.md`'s premises rule states it; larv-review's comprehension floor names the contributor as the reader it serves, so the floor gates every chunk while the contributor stands and a project that drops them skips it.