diff --git a/bin/loop_claude/claude_code/catalog.py b/bin/loop_claude/claude_code/catalog.py index da9ec815..909a396b 100644 --- a/bin/loop_claude/claude_code/catalog.py +++ b/bin/loop_claude/claude_code/catalog.py @@ -1,9 +1,10 @@ import json +import pathlib from loop_claude.claude_code.formats import models_in -def offered_models(folder) -> list[tuple[str, object]]: +def offered_models(folder: pathlib.Path) -> list[tuple[str, object]]: files = [] for path in folder.glob("*.json"): try: diff --git a/bin/loop_claude/claude_code/formats.py b/bin/loop_claude/claude_code/formats.py index 031d97e8..1acd7f86 100644 --- a/bin/loop_claude/claude_code/formats.py +++ b/bin/loop_claude/claude_code/formats.py @@ -4,7 +4,7 @@ import json from loop_claude.outcome import Failure -def parse(raw) -> dict | None: +def parse(raw: str | bytes) -> dict | None: try: entry = json.loads(raw) except ValueError: @@ -12,41 +12,52 @@ def parse(raw) -> dict | None: return entry if isinstance(entry, dict) else None -def content(entry) -> object: +def content(entry: dict) -> object: message = entry.get("message") return message.get("content") if isinstance(message, dict) else None -def parts(entry) -> list: +def parts(entry: dict) -> 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) -> list: +def assistant_parts(entry: dict) -> list: return parts(entry) if entry.get("type") == "assistant" else [] -def written_by_human(entry) -> bool: +def written_by_human(entry: dict) -> bool: """Whether the human wrote a "user" entry; Claude Code writes the rest.""" - # {"type": "user", "isMeta": true, "message": {"content": "Caveat: ..."}} - # {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; ..."}} - if entry.get("isMeta") or entry.get("promptSource") == "sdk": + if tagged_as_injected(entry): return False - # {"type": "user", "message": {"content": "/model\n..."}} - # {"type": "user", "promptSource": "system", "message": {"content": "..."}} - # {"type": "user", "promptSource": "typed", "message": {"content": "merge it"}} - # Claude Code tags what it injects, and an entry without promptSource carries no other mark, so a leading < is its own. - if isinstance(text := content(entry), str): - source = entry.get("promptSource") - return source != "system" and (source == "typed" or not text.startswith("<")) - 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]"}]}} + text = content(entry) + return typed_string(entry, text) if isinstance(text, str) else typed_blocks(parts(entry)) + + +# {"type": "user", "isMeta": true, "message": {"content": "Caveat: ..."}} +# {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; ..."}} +# {"type": "user", "promptSource": "system", "message": {"content": "..."}} +def tagged_as_injected(entry: dict) -> bool: + return bool(entry.get("isMeta")) or entry.get("promptSource") in ("sdk", "system") + + +# {"type": "user", "promptSource": "typed", "message": {"content": "merge it"}} +# {"type": "user", "message": {"content": "/model\n..."}} +def typed_string(entry: dict, text: str) -> bool: + # An entry without promptSource carries no other mark, so a leading < is Claude Code's. + return entry.get("promptSource") == "typed" or not text.startswith("<") + + +# {"type": "user", "message": {"content": [{"type": "text", "text": "merge it"}]}} +# {"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]"}]}} +def typed_blocks(blocks: list) -> bool: + texts = [part_text(block) for block in blocks] 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: +def human_text(entry: dict) -> 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 +69,7 @@ def human_text(entry) -> str | None: # 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) -> str | None: +def queued_human_text(entry: dict) -> 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,29 +77,28 @@ def queued_human_text(entry) -> str | None: # {"type": "text", "text": "ok"} -def part_text(part) -> str | None: +def part_text(part: object) -> 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) -> tuple[object, object] | None: +def tool_call(part: object) -> 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) -> bool: +def ends_stream(event: dict) -> bool: return event.get("type") == "result" # {"type": "result", "structured_output": {"evidence": "...", ...}, ...} -def structured_output(stdout) -> object: +def structured_output(stdout: str) -> object: return (parse(stdout) or {}).get("structured_output") # Claude Code's config: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...} -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): +def mark_trusted(config: object, roots: list[str]) -> tuple[dict, list[str]] | Failure: + if not isinstance(config, dict) or not isinstance(projects := config.get("projects", {}), dict): return Failure('not an object whose "projects" is an object') if (wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None)) is not None: return Failure(f"projects[{json.dumps(wrong)}] is not an object") @@ -98,7 +108,7 @@ 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]]: +def models_in(files: list[object]) -> list[tuple[str, object]]: """The (id, name) of each model in the newest of the parsed catalog files.""" newest: dict = {} for data in files: diff --git a/bin/loop_claude/claude_code/session.py b/bin/loop_claude/claude_code/session.py index a54b97c4..2df3e1bf 100644 --- a/bin/loop_claude/claude_code/session.py +++ b/bin/loop_claude/claude_code/session.py @@ -6,6 +6,8 @@ import shutil import sys import uuid +from loop_claude.paths import Paths + NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") @@ -17,19 +19,19 @@ class Session: name: str -def session_for(project, paths) -> Session: +def session_for(project: str, paths: 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) # /-home-me-code-log/.jsonl -def transcript_file(session) -> str: +def transcript_file(session: 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) -> None: +def delete_session(session: Session) -> None: path = transcript_file(session) if not path: return diff --git a/bin/loop_claude/claude_code/transcript.py b/bin/loop_claude/claude_code/transcript.py index 5d5fbb79..b110bc1d 100644 --- a/bin/loop_claude/claude_code/transcript.py +++ b/bin/loop_claude/claude_code/transcript.py @@ -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) -> list[dict] | Failure: +def read(path: str) -> 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) -> list[dict] | Failure: return Failure(f"could not read the transcript {path}: {failure.strerror}") -def human_turns(entries) -> int: +def human_turns(entries: list[dict]) -> int: return sum(1 for entry in entries if human_text(entry) is not None) -def render(entries) -> str: +def render(entries: list[dict]) -> 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) -> str: return "\n\n".join(lines) -def part_line(part, limit=400) -> str: +def part_line(part: object, limit: int = 400) -> str: if (text := part_text(part)) and text.strip(): return text if call := tool_call(part): diff --git a/bin/loop_claude/claude_code/trust.py b/bin/loop_claude/claude_code/trust.py index 10072ce4..ed1ba6ba 100644 --- a/bin/loop_claude/claude_code/trust.py +++ b/bin/loop_claude/claude_code/trust.py @@ -1,4 +1,5 @@ import json +import pathlib import sys from loop_claude.claude_code.formats import mark_trusted @@ -7,7 +8,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) -> None: +def trust(config: pathlib.Path, roots: list[str]) -> None: try: with open(config, encoding="utf-8") as handle: data = json.load(handle) diff --git a/bin/loop_claude/cycle/archive.py b/bin/loop_claude/cycle/archive.py index 77febd34..b862d050 100644 --- a/bin/loop_claude/cycle/archive.py +++ b/bin/loop_claude/cycle/archive.py @@ -3,9 +3,10 @@ import sys from loop_claude.file_writes import make_private, replace_file from loop_claude.outcome import Failure +from loop_claude.paths import Paths -def archive(project, path, note, paths) -> Failure | None: +def archive(project: str, path: str, note: str, paths: Paths) -> Failure | None: folder = paths.archive / project try: with open(path, "rb") as handle: diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index 2bbe6e26..53514085 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -1,16 +1,18 @@ import sys +import uuid from loop_claude import human_needed from loop_claude.claude_code.transcript import human_turns, read from loop_claude.claude_code.trust import trust from loop_claude.effects import Effects from loop_claude.outcome import Failure, Stop +from loop_claude.paths import Paths from loop_claude.project.checkout import checkouts TO = "answer the question above" -def interrupt(root, session_id, model, path, question, paths, effects: Effects) -> Stop | None: +def interrupt(root: str, session_id: uuid.UUID, model: str, path: str, question: str, paths: Paths, effects: Effects) -> Stop | None: print(f"\n{question}", file=sys.stderr) if stop := human_needed.off_terminal(TO, effects.on_terminal()): return stop diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index acf07502..f40f834c 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -45,7 +45,7 @@ JUDGE_SCHEMA = { } -def judge(root, task, premises, transcript, model, effects: Effects) -> Verdict | Stop: +def judge(root: str, task: str, premises: str, transcript: str, model: str, effects: Effects) -> 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", @@ -60,7 +60,7 @@ def judge(root, task, premises, transcript, model, effects: Effects) -> Verdict return retried("judge", lambda: run_judge(root, args, prompt, transcript, effects), effects) -def run_judge(root, args, prompt, transcript, effects: Effects) -> Verdict | Failure: +def run_judge(root: str, args: list[str], prompt: str, transcript: str, effects: Effects) -> Verdict | Failure: try: proc = effects.claude(args, root, prompt) except OSError as failure: @@ -75,7 +75,7 @@ def run_judge(root, args, prompt, transcript, effects: Effects) -> Verdict | Fai return verdict -def judge_prompt(task, premises, transcript) -> str: +def judge_prompt(task: str, premises: str, transcript: str) -> str: return ( f"From README.md:\n{premises}\n\n" f"The task an agent was given:\n{task}\n\n" @@ -85,7 +85,7 @@ def judge_prompt(task, premises, transcript) -> str: ) -def verdict_from(output) -> Verdict | Failure: +def verdict_from(output: object) -> Verdict | Failure: if not isinstance(output, dict): return Failure("the judge returned no verdict") for name, kind in REPLY_TYPES.items(): @@ -99,11 +99,11 @@ def verdict_from(output) -> Verdict | Failure: return Finished(output["evidence"]) if output["finished"] else Unfinished(output["evidence"]) -def grounded(evidence, transcript) -> bool: +def grounded(evidence: str, transcript: str) -> bool: quoted = plain(evidence) return quoted != "" and quoted in plain(transcript) -def plain(text) -> str: +def plain(text: str) -> str: # The judge drops markdown emphasis and reflows whitespace when it quotes. return " ".join(text.replace("*", "").replace("_", "").split()) diff --git a/bin/loop_claude/cycle/retry.py b/bin/loop_claude/cycle/retry.py index 4253177c..12606c56 100644 --- a/bin/loop_claude/cycle/retry.py +++ b/bin/loop_claude/cycle/retry.py @@ -7,7 +7,7 @@ from loop_claude.outcome import Failure, Stop T = typing.TypeVar("T") -def retried(who, attempt: typing.Callable[[], T | Failure], effects: Effects) -> T | Stop: +def retried(who: str, attempt: typing.Callable[[], T | Failure], effects: Effects) -> T | Stop: failures = 0 while True: failures += 1 diff --git a/bin/loop_claude/cycle/steps.py b/bin/loop_claude/cycle/steps.py index c386395a..c6d315d3 100644 --- a/bin/loop_claude/cycle/steps.py +++ b/bin/loop_claude/cycle/steps.py @@ -27,7 +27,7 @@ class Cycle: task: str -def run_cycle(cycle) -> Stop | None: +def run_cycle(cycle: Cycle) -> Stop | None: state: State = Working() while not isinstance(state, Ended): event = step(cycle, state) @@ -37,7 +37,7 @@ def run_cycle(cycle) -> Stop | None: return None -def step(cycle, state: Active) -> Event | Stop: +def step(cycle: Cycle, state: Active) -> Event | Stop: match state: case Working(): return work(cycle) @@ -51,7 +51,7 @@ def step(cycle, state: Active) -> Event | Stop: typing.assert_never(state) -def work(cycle) -> WorkerRan | Stop: +def work(cycle: Cycle) -> WorkerRan | Stop: # session_open runs inside the lambda: a failed attempt may have opened the session. if stop := retried("worker", lambda: run_worker(cycle.root, worker_args(cycle.task, cycle.session, cycle.models.worker, session_open(cycle.session)), cycle.effects), cycle.effects): return stop @@ -59,7 +59,7 @@ def work(cycle) -> WorkerRan | Stop: return WorkerRan(path) if path else Stop(1, f"claude left no transcript for session {cycle.session.id}") -def rule(cycle, transcript_path) -> Ruled | Stop: +def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop: entries = read(transcript_path) if isinstance(entries, Failure): return Stop(1, entries.reason) @@ -67,19 +67,19 @@ def rule(cycle, transcript_path) -> Ruled | Stop: return verdict if isinstance(verdict, Stop) else Ruled(verdict) -def ask(cycle, transcript_path, question) -> Answered | Stop: +def ask(cycle: Cycle, transcript_path: str, question: str) -> Answered | Stop: # The interrupt appends to this transcript, so it is archived at each question. if failure := archive(cycle.project, transcript_path, f"Task: {cycle.task}\n\nVerdict: interrupt\n\n{question}", cycle.paths): return Stop(1, failure.reason) return interrupt(cycle.root, cycle.session.id, cycle.models.worker, transcript_path, question, cycle.paths, cycle.effects) or Answered() -def close(cycle, transcript_path) -> Archived | Stop: +def close(cycle: Cycle, transcript_path: str) -> Archived | Stop: if failure := archive(cycle.project, transcript_path, f"Task: {cycle.task}\n\nVerdict: finished", cycle.paths): return Stop(1, failure.reason) delete_session(cycle.session) return Archived() -def session_open(session) -> bool: +def session_open(session: Session) -> bool: return bool(transcript_file(session)) diff --git a/bin/loop_claude/cycle/worker.py b/bin/loop_claude/cycle/worker.py index 058090fd..97a6a033 100644 --- a/bin/loop_claude/cycle/worker.py +++ b/bin/loop_claude/cycle/worker.py @@ -1,10 +1,11 @@ from loop_claude.claude_code.formats import assistant_parts, ends_stream, parse +from loop_claude.claude_code.session import Session from loop_claude.claude_code.transcript import part_line from loop_claude.effects import Effects from loop_claude.outcome import Failure -def run_worker(root, args, effects: Effects) -> Failure | None: +def run_worker(root: str, args: list[str], effects: Effects) -> Failure | None: try: proc = effects.stream_claude(args, root) except OSError as failure: @@ -24,7 +25,7 @@ def run_worker(root, args, effects: Effects) -> Failure | None: return None if done else Failure("claude exited 0 without a result event") -def worker_args(task, session, model, resuming) -> list[str]: +def worker_args(task: str, session: Session, model: str, resuming: bool) -> list[str]: if resuming: start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", str(session.id)] else: diff --git a/bin/loop_claude/effects.py b/bin/loop_claude/effects.py index 20f1b03b..79384e47 100644 --- a/bin/loop_claude/effects.py +++ b/bin/loop_claude/effects.py @@ -28,7 +28,7 @@ class Effects: class Popened: - def __init__(self, args, cwd): + def __init__(self, args: list[str], cwd: str) -> None: self.proc = subprocess.Popen(["claude", *args], cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, stdout=subprocess.PIPE) def lines(self) -> typing.Iterable[str]: diff --git a/bin/loop_claude/file_writes.py b/bin/loop_claude/file_writes.py index f0099901..33b89103 100644 --- a/bin/loop_claude/file_writes.py +++ b/bin/loop_claude/file_writes.py @@ -1,10 +1,12 @@ import json import os +import pathlib +import typing from loop_claude.outcome import Failure -def make_private(folder) -> None: +def make_private(folder: pathlib.Path) -> None: mask = os.umask(0o077) try: os.makedirs(folder, exist_ok=True) @@ -12,11 +14,11 @@ def make_private(folder) -> None: os.umask(mask) -def replace_json(path, data, **dump) -> Failure | None: +def replace_json(path: pathlib.Path, data: object, **dump: typing.Any) -> Failure | None: return replace_file(path, json.dumps(data, **dump).encode()) -def replace_file(path, data) -> Failure | None: +def replace_file(path: pathlib.Path, data: bytes) -> Failure | None: staged = f"{path}.{os.getpid()}" try: mode = os.stat(path).st_mode & 0o7777 if os.path.exists(path) else 0o600 diff --git a/bin/loop_claude/human_needed.py b/bin/loop_claude/human_needed.py index 4ad9d301..2fd7e2c7 100644 --- a/bin/loop_claude/human_needed.py +++ b/bin/loop_claude/human_needed.py @@ -1,11 +1,11 @@ from loop_claude.outcome import Stop -def stop(to, but) -> Stop: +def stop(to: str, but: str) -> Stop: return Stop(2, f"the human is needed to {to}, but {but}") -def off_terminal(to, on_terminal: bool) -> Stop | None: +def off_terminal(to: str, on_terminal: bool) -> Stop | None: if on_terminal: return None return stop(to, "stdin or stdout is not a terminal; rerun loop-claude on a terminal") diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 52f932af..71f43961 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -35,19 +35,22 @@ A change to bin/loop-claude or bin/loop_claude/**/*.py takes effect at the next loop-claude --help succeeds. """ import dataclasses +import pathlib import sys +import typing from loop_claude.claude_code.session import session_for from loop_claude.cycle.steps import Cycle, run_cycle from loop_claude.effects import Effects from loop_claude.loop.reload import RELOAD_FLAG, LoopRun, decode_handed, exec_if_edited, fingerprint from loop_claude.outcome import Stop +from loop_claude.paths import Paths from loop_claude.project.checkout import checkout_root, project_name from loop_claude.project.models import project_models from loop_claude.project.premises import read_premises -def main(argv, env, paths, launcher, cwd, effects: Effects) -> int: +def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int: try: stop = run_loop(argv, env, paths, launcher, cwd, effects) except KeyboardInterrupt: @@ -57,7 +60,7 @@ def main(argv, env, paths, launcher, cwd, effects: Effects) -> int: return stop.code -def run_loop(argv, env, paths, launcher, cwd, effects: Effects) -> Stop: +def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> Stop: loop_run = loop_run_from(argv, cwd, effects) if isinstance(loop_run, Stop): return loop_run @@ -79,7 +82,7 @@ def run_loop(argv, env, paths, launcher, cwd, effects: Effects) -> Stop: return stop -def loop_run_from(argv, cwd, effects: Effects) -> LoopRun | Stop: +def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopRun | Stop: if argv[:1] != [RELOAD_FLAG]: task = " ".join(argv) if task in ("", "-h", "--help"): diff --git a/bin/loop_claude/loop/reload.py b/bin/loop_claude/loop/reload.py index 33ca164f..2813f1ee 100644 --- a/bin/loop_claude/loop/reload.py +++ b/bin/loop_claude/loop/reload.py @@ -1,6 +1,7 @@ import dataclasses import hashlib import json +import pathlib import sys import typing @@ -20,7 +21,7 @@ class LoopRun: task: str -def decode_handed(handed, kind: type[T]) -> T | None: +def decode_handed(handed: str, kind: type[T]) -> T | None: try: fields = json.loads(handed) except ValueError: @@ -33,7 +34,7 @@ def decode_handed(handed, kind: type[T]) -> T | None: return kind(**fields) -def fingerprint(launcher) -> str: +def fingerprint(launcher: pathlib.Path) -> str: digest = hashlib.sha256() for path in [launcher, *sorted((launcher.parent / "loop_claude").rglob("*.py"))]: try: @@ -44,7 +45,7 @@ def fingerprint(launcher) -> str: return digest.hexdigest() -def exec_if_edited(launcher, baseline, loop_run, effects: Effects) -> Stop | None: +def exec_if_edited(launcher: pathlib.Path, baseline: str, loop_run: LoopRun, effects: Effects) -> Stop | None: if fingerprint(launcher) == baseline: return None try: diff --git a/bin/loop_claude/paths.py b/bin/loop_claude/paths.py index b0a1dd28..dfd3d10e 100644 --- a/bin/loop_claude/paths.py +++ b/bin/loop_claude/paths.py @@ -1,5 +1,6 @@ import dataclasses import pathlib +import typing @dataclasses.dataclass(frozen=True) @@ -12,7 +13,7 @@ class Paths: models_file: pathlib.Path -def paths_from(home, env) -> Paths: +def paths_from(home: pathlib.Path, env: typing.Mapping[str, str]) -> 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", diff --git a/bin/loop_claude/project/checkout.py b/bin/loop_claude/project/checkout.py index a9b86d17..f63df11c 100644 --- a/bin/loop_claude/project/checkout.py +++ b/bin/loop_claude/project/checkout.py @@ -1,8 +1,10 @@ +import pathlib + from loop_claude.effects import Effects from loop_claude.outcome import Stop -def checkout_root(cwd, effects: Effects) -> str | Stop: +def checkout_root(cwd: pathlib.Path, effects: Effects) -> str | Stop: try: found = effects.git(["rev-parse", "--show-toplevel"], str(cwd)) except OSError as failure: @@ -12,7 +14,7 @@ def checkout_root(cwd, effects: Effects) -> str | Stop: return found.stdout.strip() -def checkouts(root, effects: Effects) -> list[str]: +def checkouts(root: str, effects: Effects) -> list[str]: found = [root] try: listing = effects.git(["worktree", "list", "--porcelain"], root) @@ -23,5 +25,5 @@ def checkouts(root, effects: Effects) -> list[str]: return sorted(set(found)) -def project_name(root, code) -> str: +def project_name(root: str, code: pathlib.Path) -> str: return root.removeprefix(f"{code}/").lstrip("/") diff --git a/bin/loop_claude/project/models.py b/bin/loop_claude/project/models.py index c2f9f237..4897c134 100644 --- a/bin/loop_claude/project/models.py +++ b/bin/loop_claude/project/models.py @@ -1,12 +1,15 @@ import dataclasses import json +import pathlib import sys +import typing from loop_claude import human_needed from loop_claude.claude_code.catalog import offered_models from loop_claude.effects import Effects from loop_claude.file_writes import replace_json from loop_claude.outcome import Failure, Stop +from loop_claude.paths import Paths @dataclasses.dataclass(frozen=True) @@ -15,7 +18,7 @@ class Models: worker: str -def project_models(project, paths, env, effects: Effects) -> Models | Stop: +def project_models(project: str, paths: Paths, env: typing.Mapping[str, str], effects: Effects) -> Models | Stop: judge, worker = env.get("LOOP_CLAUDE_JUDGE_MODEL"), env.get("LOOP_CLAUDE_WORKER_MODEL") if judge and worker: return Models(judge, worker) @@ -25,7 +28,7 @@ def project_models(project, paths, env, effects: Effects) -> Models | Stop: return Models(judge or chosen, worker or chosen) -def project_model(name, paths, effects: Effects) -> str | Stop: +def project_model(name: str, paths: Paths, effects: Effects) -> str | Stop: saved = paths.models_file models = read_models(saved) if isinstance(models, Stop): @@ -45,7 +48,7 @@ def project_model(name, paths, effects: Effects) -> str | Stop: return chosen -def read_models(saved) -> dict[str, str] | Stop: +def read_models(saved: pathlib.Path) -> dict[str, str] | Stop: try: with open(saved, encoding="utf-8") as handle: models = json.load(handle) @@ -58,7 +61,7 @@ def read_models(saved) -> dict[str, str] | Stop: return models -def ask_model(name, saved, folder, effects: Effects) -> str | Stop: +def ask_model(name: str, saved: pathlib.Path, folder: pathlib.Path, effects: Effects) -> str | Stop: if stop := human_needed.off_terminal(f"pick {name}'s model, or merge {{\"{name}\": \"\"}} into {saved}", effects.on_terminal()): return stop offered = offered_models(folder) @@ -80,7 +83,7 @@ def ask_model(name, saved, folder, effects: Effects) -> str | Stop: return picked -def model_picked(answer, offered) -> str | Failure | None: +def model_picked(answer: str, offered: list[tuple[str, object]]) -> str | Failure | None: """The model the answer picks, a Failure naming the numbers to pick from, or None to ask again.""" answer = answer.strip() if not answer: diff --git a/bin/loop_claude/project/premises.py b/bin/loop_claude/project/premises.py index f9f2ee8c..27e7a55a 100644 --- a/bin/loop_claude/project/premises.py +++ b/bin/loop_claude/project/premises.py @@ -3,7 +3,7 @@ import pathlib from loop_claude.outcome import Stop -def read_premises(root) -> str | Stop: +def read_premises(root: str) -> 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) -> str | Stop: return f"## Goals\n{found['Goals'][0]}\n\n## Audience\n{found['Audience'][0]}" -def sections(text) -> dict[str, list[str]]: +def sections(text: str) -> dict[str, list[str]]: blocks: list[tuple[str | None, list[str]]] = [] fenced = False for line in text.splitlines(): diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 4e7e2478..ca065a5e 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -271,6 +271,7 @@ class HumanTurns(unittest.TestCase): human("/model"), {**human("<3 merge it"), "promptSource": "typed"}, {**human("done"), "promptSource": "system"}, + {**human([{"type": "text", "text": "done"}]), "promptSource": "system"}, {**human("peer message"), "isMeta": True}, {**human("the loop's own prompt"), "promptSource": "sdk"}, human([{"type": "text", "text": "[Request interrupted by user]"}]), @@ -362,7 +363,7 @@ class ReplaceFile(unittest.TestCase): def test_removes_what_it_staged_when_the_replace_fails(self): with tempfile.TemporaryDirectory() as root: os.mkdir(os.path.join(root, "in-the-way")) - self.assertEqual(file_writes.replace_file(os.path.join(root, "in-the-way"), b"data"), Failure("Is a directory")) + self.assertEqual(file_writes.replace_file(pathlib.Path(root, "in-the-way"), b"data"), Failure("Is a directory")) self.assertEqual(os.listdir(root), ["in-the-way"]) diff --git a/bin/test_types.py b/bin/test_types.py index 0098a6c3..17500139 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", "-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", "-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 1e8e5be0..94a51dd2 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -78,7 +78,7 @@ ## 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. +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. On 2026-10-01 mypy also came to require an annotation on every parameter, so a reader learns a parameter's type at its `def`, without tracing callers (goal 4.1). Valid while `loop_claude` carries annotations. ## review: an ask no user answers leaves the PR unmerged diff --git a/todo.md b/todo.md index 6bb3b2b3..7d6bf5d7 100644 --- a/todo.md +++ b/todo.md @@ -4,10 +4,8 @@ The rebuild's design sketches, the blind judges' verdicts on them and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -The first six items are the places the panels on `rebuild` at 8585257 and on PR #182 named under Self-sufficiency and Locality, the dimensions under the floor (scores: `docs/decisions.md` → "comprehension floor"). +The first four items are the places the panels on `rebuild` at 8585257 and on PR #182 named under Self-sufficiency and Locality, the dimensions under the floor (scores: `docs/decisions.md` → "comprehension floor"). -- **Split `written_by_human`'s boolean into one named check per entry shape.** `formats.py:42` packs three tests into one line, one seat learnt the cases only from `HumanTurns` in the tests, and another could not confirm them without `HumanTurns`. Three seats named it the unit they least wanted to modify, and the architect named it where the project rots first. -- **Annotate the parameter types in `bin/loop_claude/`.** Whether `root` or `path` is a `str` or a `Path` is learnt by tracing callers back to `bin/loop-claude`. - **Make a failed session delete stop the loop, and give the session one owner.** `delete_session` (`session.py:32`) only prints a failed removal, so `close` reports `Archived` and the next chunk resumes the finished chunk's session without its own task prompt. Return a `Failure` and stop on it; move `session_open` into `session.py`; have `transcript_file` return `str | None`. Goal 4.1. - **Give larv-review §3's rules one home per rule.** Every seat of the 2026-10-01 panel needed `SKILL.md`, `review-findings.md` and `CLAUDE.md` open to apply one rule of "Round cap" or "Re-entry". Goal 4.1. - **Name `loop_claude`'s modules and words by what each holds.** The 2026-10-01 panel misread `formats.py` (it holds every Claude Code shape, `mark_trusted` and `models_in` included), `steps.py`, `outcome.py` and `human_needed.py`. "Project", "transcripts", "verdict" and "model" each name two or three things. Goal 4.1.