Annotate the return type of every function in loop_claude #141

Merged
lilleman merged 2 commits from annotate-returns into rebuild 2026-09-29 12:25:42 +02:00
20 changed files with 63 additions and 58 deletions
+1 -1
View File
@@ -3,7 +3,7 @@ import json
from loop_claude.claude_code.formats import models_in
def offered_models(folder):
def offered_models(folder) -> list[tuple[str, object]]:
files = []
for path in folder.glob("*.json"):
try:
+13 -13
View File
@@ -4,7 +4,7 @@ import json
from loop_claude.outcome import Failure
def parse(raw):
def parse(raw) -> dict | None:
try:
entry = json.loads(raw)
except ValueError:
@@ -12,22 +12,22 @@ def parse(raw):
return entry if isinstance(entry, dict) else None
def content(entry):
def content(entry) -> object:
message = entry.get("message")
return message.get("content") if isinstance(message, dict) else None
def parts(entry):
def parts(entry) -> list:
found = content(entry)
return found if isinstance(found, list) else []
# Alike in the transcript and in stream-json: {"type": "assistant", "message": {"content": [{"type": "text", "text": "ok"}]}}
def assistant_parts(entry):
def assistant_parts(entry) -> list:
return parts(entry) if entry.get("type") == "assistant" else []
def written_by_human(entry):
def written_by_human(entry) -> bool:
"""Whether the human wrote a "user" entry; Claude Code writes the rest."""
# {"type": "user", "isMeta": true, "message": {"content": "<local-command-caveat>Caveat: ..."}}
# {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; ..."}}
@@ -46,7 +46,7 @@ def written_by_human(entry):
return bool(texts) and None not in texts and not any(text.startswith("[Request interrupted") for text in texts)
def human_text(entry):
def human_text(entry) -> str | None:
"""What the human wrote in the entry, or None where Claude Code wrote it."""
if (queued := queued_human_text(entry)) is not None:
return queued
@@ -58,7 +58,7 @@ def human_text(entry):
# What the human types while claude works, written only as this entry:
# {"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "prompt", "origin": {"kind": "human"}, "prompt": "B"}}
def queued_human_text(entry):
def queued_human_text(entry) -> str | None:
attachment = entry.get("attachment") if entry.get("type") == "attachment" else None
if not isinstance(attachment, dict) or attachment.get("type") != "queued_command" or not isinstance(origin := attachment.get("origin"), dict) or origin.get("kind") != "human":
return None
@@ -66,27 +66,27 @@ def queued_human_text(entry):
# {"type": "text", "text": "ok"}
def part_text(part):
def part_text(part) -> str | None:
return part["text"] if isinstance(part, dict) and part.get("type") == "text" and isinstance(part.get("text"), str) else None
# {"type": "tool_use", "name": "Bash", "input": {"command": "echo hi"}}
def tool_call(part):
def tool_call(part) -> tuple[object, object] | None:
return (part.get("name"), part.get("input")) if isinstance(part, dict) and part.get("type") == "tool_use" else None
# stream-json's last line: {"type": "result", "subtype": "success", ...}
def ends_stream(event):
def ends_stream(event) -> bool:
return event.get("type") == "result"
# {"type": "result", "structured_output": {"evidence": "...", ...}, ...}
def structured_output(stdout):
def structured_output(stdout) -> object:
return (parse(stdout) or {}).get("structured_output")
# Claude Code's config: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...}
def mark_trusted(config, roots):
def mark_trusted(config, roots) -> tuple[dict, list[str]] | Failure:
projects = config.get("projects", {}) if isinstance(config, dict) else None
if not isinstance(projects, dict):
return Failure('not an object whose "projects" is an object')
@@ -98,7 +98,7 @@ def mark_trusted(config, roots):
# A model catalog file: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}}
def models_in(files):
def models_in(files) -> list[tuple[str, object]]:
"""The (id, name) of each model in the newest of the parsed catalog files."""
newest = {}
for data in files:
+3 -3
View File
@@ -17,19 +17,19 @@ class Session:
name: str
def session_for(project, paths):
def session_for(project, paths) -> Session:
# "A " is the human's cue in the session picker that the session is the loop's.
name = f"A {project} loop-claude"
return Session(id=uuid.uuid5(NAMESPACE, name), claude_code_transcripts=paths.claude_code_transcripts, name=name)
# <claude_code_transcripts>/-home-me-code-log/<session id>.jsonl
def transcript_file(session):
def transcript_file(session) -> str:
hit = glob.glob(os.path.join(glob.escape(str(session.claude_code_transcripts)), "*", f"{session.id}.jsonl"))
return hit[0] if hit else ""
def delete_session(session):
def delete_session(session) -> None:
path = transcript_file(session)
if not path:
return
+4 -4
View File
@@ -4,7 +4,7 @@ from loop_claude.claude_code.formats import assistant_parts, human_text, parse,
from loop_claude.outcome import Failure
def read(path):
def read(path) -> list[dict] | Failure:
try:
with open(path, "rb") as handle:
return [entry for raw in handle if (entry := parse(raw))]
@@ -12,11 +12,11 @@ def read(path):
return Failure(f"could not read the transcript {path}: {failure.strerror}")
def human_turns(entries):
def human_turns(entries) -> int:
return sum(1 for entry in entries if human_text(entry) is not None)
def render(entries):
def render(entries) -> str:
lines = []
for entry in entries:
lines += [line for part in assistant_parts(entry) if (line := part_line(part))]
@@ -25,7 +25,7 @@ def render(entries):
return "\n\n".join(lines)
def part_line(part, limit=400):
def part_line(part, limit=400) -> str:
if (text := part_text(part)) and text.strip():
return text
if call := tool_call(part):
+1 -1
View File
@@ -7,7 +7,7 @@ from loop_claude.outcome import Failure
# A failure only warns: the interrupt still runs, and the human answers Claude Code's trust dialog.
def trust(config, roots):
def trust(config, roots) -> None:
try:
with open(config, encoding="utf-8") as handle:
data = json.load(handle)
+1 -1
View File
@@ -5,7 +5,7 @@ from loop_claude.file_writes import make_private, replace_file
from loop_claude.outcome import Failure
def archive(project, path, note, paths):
def archive(project, path, note, paths) -> Failure | None:
folder = paths.archive / project
try:
with open(path, "rb") as handle:
+1 -1
View File
@@ -10,7 +10,7 @@ from loop_claude.project.checkout import checkouts
TO = "answer the question above"
def interrupt(root, session_id, model, path, question, paths):
def interrupt(root, session_id, model, path, question, paths) -> Stop | None:
print(f"\n{question}", file=sys.stderr)
if stop := human_needed.off_terminal(TO):
return stop
+6 -6
View File
@@ -5,7 +5,7 @@ import typing
from loop_claude.claude_code.formats import structured_output
from loop_claude.cycle.retry import retried
from loop_claude.outcome import Failure
from loop_claude.outcome import Failure, Stop
JUDGE_RULES = (
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
@@ -44,7 +44,7 @@ JUDGE_SCHEMA = {
}
def judge(root, task, premises, transcript, model):
def judge(root, task, premises, transcript, model) -> Verdict | Stop:
# No tools, so the verdict rests on the transcript grounded() checks it against; no persistence, so its runs stay out of the session picker.
args = [
"-p",
@@ -59,7 +59,7 @@ def judge(root, task, premises, transcript, model):
return retried("judge", lambda: run_judge(root, args, prompt, transcript))
def run_judge(root, args, prompt, transcript):
def run_judge(root, args, prompt, transcript) -> Verdict | Failure:
try:
proc = subprocess.run(["claude", *args], capture_output=True, cwd=root, input=prompt, text=True)
except OSError as failure:
@@ -72,7 +72,7 @@ def run_judge(root, args, prompt, transcript):
return verdict
def judge_prompt(task, premises, transcript):
def judge_prompt(task, premises, transcript) -> str:
return (
f"From README.md:\n{premises}\n\n"
f"The task an agent was given:\n{task}\n\n"
@@ -82,7 +82,7 @@ def judge_prompt(task, premises, transcript):
)
def verdict_from(output):
def verdict_from(output) -> Verdict | Failure:
if not isinstance(output, dict):
return Failure("the judge returned no verdict")
for name, kind in VERDICT_TYPES.items():
@@ -93,5 +93,5 @@ def verdict_from(output):
return Verdict(**{name: output[name] for name in VERDICT_TYPES})
def grounded(verdict, transcript):
def grounded(verdict, transcript) -> bool:
return verdict.evidence.strip() != "" and verdict.evidence in transcript
+4 -1
View File
@@ -1,11 +1,14 @@
import itertools
import sys
import time
import typing
from loop_claude.outcome import Failure, Stop
T = typing.TypeVar("T")
def retried(who, attempt):
def retried(who, attempt: typing.Callable[[], T | Failure]) -> T | Stop:
for failures in itertools.count(1):
result = attempt()
if not isinstance(result, Failure):
+4 -3
View File
@@ -4,7 +4,7 @@ from loop_claude.claude_code.session import Session, delete_session, transcript_
from loop_claude.claude_code.transcript import read, render
from loop_claude.cycle.archive import archive
from loop_claude.cycle.interrupt import interrupt
from loop_claude.cycle.judge import judge
from loop_claude.cycle.judge import Verdict, judge
from loop_claude.cycle.retry import retried
from loop_claude.cycle.worker import run_worker, worker_args
from loop_claude.outcome import Failure, Stop
@@ -23,7 +23,7 @@ class Cycle:
task: str
def run_cycle(cycle):
def run_cycle(cycle) -> Stop | None:
if stop := retried("worker", lambda: run_worker(cycle.root, worker_args(cycle.task, cycle.session, cycle.models.worker, bool(transcript_file(cycle.session))))):
return stop
path = transcript_file(cycle.session)
@@ -36,9 +36,10 @@ def run_cycle(cycle):
if failure := archive(cycle.project, path, f"Task: {cycle.task}\n\nVerdict: finished", cycle.paths):
return Stop(1, failure.reason)
delete_session(cycle.session)
return None
def judge_through_interrupts(cycle, path):
def judge_through_interrupts(cycle, path) -> Verdict | Stop:
# The interrupt appends to this transcript, so each pass judges and archives it anew.
while True:
entries = read(path)
+2 -2
View File
@@ -5,7 +5,7 @@ from loop_claude.claude_code.transcript import part_line
from loop_claude.outcome import Failure
def run_worker(root, args):
def run_worker(root, args) -> Failure | None:
try:
proc = subprocess.Popen(["claude", *args], cwd=root, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, stdout=subprocess.PIPE)
except OSError as failure:
@@ -26,7 +26,7 @@ def run_worker(root, args):
return None if done else Failure("claude exited 0 without a result event")
def worker_args(task, session, model, resuming):
def worker_args(task, session, model, resuming) -> list[str]:
if resuming:
start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", str(session.id)]
else:
+3 -3
View File
@@ -4,7 +4,7 @@ import os
from loop_claude.outcome import Failure
def make_private(folder):
def make_private(folder) -> None:
mask = os.umask(0o077)
try:
os.makedirs(folder, exist_ok=True)
@@ -12,11 +12,11 @@ def make_private(folder):
os.umask(mask)
def replace_json(path, data, **dump):
def replace_json(path, data, **dump) -> Failure | None:
return replace_file(path, json.dumps(data, **dump).encode())
def replace_file(path, data):
def replace_file(path, data) -> Failure | None:
staged = f"{path}.{os.getpid()}"
try:
mode = os.stat(path).st_mode & 0o7777 if os.path.exists(path) else 0o600
+2 -2
View File
@@ -3,11 +3,11 @@ import sys
from loop_claude.outcome import Stop
def stop(to, but):
def stop(to, but) -> Stop:
return Stop(2, f"the human is needed to {to}, but {but}")
def off_terminal(to):
def off_terminal(to) -> Stop | None:
if sys.stdin.isatty() and sys.stdout.isatty():
return None
return stop(to, "stdin or stdout is not a terminal; rerun loop-claude on a terminal")
+3 -3
View File
@@ -45,7 +45,7 @@ from loop_claude.project.models import project_models
from loop_claude.project.premises import read_premises
def main(argv, env, paths, launcher, cwd):
def main(argv, env, paths, launcher, cwd) -> int:
try:
stop = run_loop(argv, env, paths, launcher, cwd)
except KeyboardInterrupt:
@@ -55,7 +55,7 @@ def main(argv, env, paths, launcher, cwd):
return stop.code
def run_loop(argv, env, paths, launcher, cwd):
def run_loop(argv, env, paths, launcher, cwd) -> Stop:
state = loop_state(argv, cwd)
if isinstance(state, Stop):
return state
@@ -76,7 +76,7 @@ def run_loop(argv, env, paths, launcher, cwd):
return stop
def loop_state(argv, cwd):
def loop_state(argv, cwd) -> LoopState | Stop:
if argv[:1] != [RELOAD_FLAG]:
task = " ".join(argv)
if task in ("", "-h", "--help"):
+4 -3
View File
@@ -7,6 +7,7 @@ import sys
import typing
RELOAD_FLAG = "--reloaded"
T = typing.TypeVar("T")
# A field change stops a running loop at its next reload: the new script rejects the old fields.
@@ -17,7 +18,7 @@ class LoopState:
task: str
def decode_state(handed, kind):
def decode_state(handed, kind: type[T]) -> T | None:
try:
fields = json.loads(handed)
except ValueError:
@@ -30,7 +31,7 @@ def decode_state(handed, kind):
return kind(**fields)
def fingerprint(launcher):
def fingerprint(launcher) -> str:
digest = hashlib.sha256()
for path in [launcher, *sorted((launcher.parent / "loop_claude").rglob("*.py"))]:
try:
@@ -41,7 +42,7 @@ def fingerprint(launcher):
return digest.hexdigest()
def exec_if_edited(launcher, baseline, state):
def exec_if_edited(launcher, baseline, state) -> None:
if fingerprint(launcher) == baseline:
return
trial = subprocess.run([sys.executable, launcher, "--help"], capture_output=True, text=True)
+1 -1
View File
@@ -12,7 +12,7 @@ class Paths:
models_file: pathlib.Path
def paths_from(home, env):
def paths_from(home, env) -> Paths:
claude = home / ".claude"
return Paths(
archive=pathlib.Path(env["LOOP_CLAUDE_TRANSCRIPTS"]).expanduser() if env.get("LOOP_CLAUDE_TRANSCRIPTS") else claude / "loop-claude-transcripts",
+3 -3
View File
@@ -3,14 +3,14 @@ import subprocess
from loop_claude.outcome import Stop
def checkout_root(cwd):
def checkout_root(cwd) -> str | Stop:
found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, cwd=cwd, text=True)
if found.returncode != 0:
return Stop(1, found.stderr.strip())
return found.stdout.strip()
def checkouts(root):
def checkouts(root) -> list[str]:
found = [root]
listing = subprocess.run(["git", "worktree", "list", "--porcelain"], capture_output=True, cwd=root, text=True)
if listing.returncode == 0:
@@ -18,5 +18,5 @@ def checkouts(root):
return sorted(set(found))
def project_name(root, code):
def project_name(root, code) -> str:
return root.removeprefix(f"{code}/").lstrip("/")
+4 -4
View File
@@ -14,7 +14,7 @@ class Models:
worker: str
def project_models(project, paths, env):
def project_models(project, paths, env) -> Models | Stop:
judge, worker = env.get("LOOP_CLAUDE_JUDGE_MODEL"), env.get("LOOP_CLAUDE_WORKER_MODEL")
if judge and worker:
return Models(judge, worker)
@@ -24,7 +24,7 @@ def project_models(project, paths, env):
return Models(judge or chosen, worker or chosen)
def project_model(name, paths):
def project_model(name, paths) -> str | Stop:
saved = paths.models_file
models = read_models(saved)
if isinstance(models, Stop):
@@ -44,7 +44,7 @@ def project_model(name, paths):
return chosen
def read_models(saved):
def read_models(saved) -> dict[str, str] | Stop:
try:
with open(saved, encoding="utf-8") as handle:
models = json.load(handle)
@@ -57,7 +57,7 @@ def read_models(saved):
return models
def ask_model(name, saved, folder):
def ask_model(name, saved, folder) -> str | Stop:
if stop := human_needed.off_terminal(f"pick {name}'s model, or merge {{\"{name}\": \"<model>\"}} into {saved}"):
return stop
offered = offered_models(folder)
+2 -2
View File
@@ -3,7 +3,7 @@ import pathlib
from loop_claude.outcome import Stop
def read_premises(root):
def read_premises(root) -> str | Stop:
try:
found = sections(pathlib.Path(root, "README.md").read_text(encoding="utf-8"))
except OSError as failure:
@@ -22,7 +22,7 @@ def read_premises(root):
return f"## Goals\n{found['Goals'][0]}\n\n## Audience\n{found['Audience'][0]}"
def sections(text):
def sections(text) -> dict[str, list[str]]:
blocks, fenced = [], False
for line in text.splitlines():
fenced ^= line.startswith("```")
+1 -1
View File
@@ -8,7 +8,6 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens
The places the panel on `rebuild` at 2c74bbc named (`docs/decisions.md`), capping dimension first:
- **Annotate the return type of every function in `bin/loop_claude/`.** No function carries one, so `str | Stop`, `T | Stop` and `mark_trusted`'s `Failure | tuple` are learnt by reading each body.
- **Name larv-review's pass table's condition column "Trigger", gloss Stage 0 where larv-review first uses it, and define "pass" in `CLAUDE.md` → "Vocabulary".** Today Stage 0 is defined only in `agents/systems-architect.md`, and the Vocabulary uses "pass" without defining it.
- **Score `rebuild` with the four-seat panel at 7.0 or above on every dimension and the overall, none below the last run, and open its PR into main for the human.** ⚠️ Leave that PR ready and unmerged: only the human merges it, after approving the whole rebuild. A dimension under the floor gets its places filed above this item.
@@ -17,6 +16,7 @@ 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.