Name each entry shape written_by_human checks, and annotate every parameter in loop_claude #183

Merged
lilleman merged 2 commits from readable-types into main 2026-10-01 23:51:49 +02:00
24 changed files with 122 additions and 88 deletions
+2 -1
View File
@@ -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:
+38 -28
View File
@@ -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": "<local-command-caveat>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": "<command-name>/model</command-name>\n..."}}
# {"type": "user", "promptSource": "system", "message": {"content": "<task-notification>..."}}
# {"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 string_by_human(entry, text) if isinstance(text, str) else blocks_by_human(parts(entry))
# {"type": "user", "isMeta": true, "message": {"content": "<local-command-caveat>Caveat: ..."}}
# {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; ..."}}
# {"type": "user", "promptSource": "system", "message": {"content": "<task-notification>..."}}
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": "<command-name>/model</command-name>\n..."}}
def string_by_human(entry: dict, text: str) -> bool:
# Without promptSource, nothing else says who wrote the entry, so a leading < counts as 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 blocks_by_human(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:
+5 -3
View File
@@ -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)
# <claude_code_transcripts>/-home-me-code-log/<session id>.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
+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) -> 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):
+2 -1
View File
@@ -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)
+2 -1
View File
@@ -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:
+3 -1
View File
@@ -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
+6 -6
View File
@@ -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())
+1 -1
View File
@@ -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
+7 -7
View File
@@ -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))
+3 -2
View File
@@ -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:
+1 -1
View File
@@ -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]:
+5 -3
View File
@@ -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
+2 -2
View File
@@ -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")
+6 -3
View File
@@ -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"):
+4 -3
View File
@@ -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:
+2 -1
View File
@@ -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",
+5 -3
View File
@@ -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("/")
+8 -5
View File
@@ -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}\": \"<model>\"}} 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:
+2 -2
View File
@@ -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():
+4 -3
View File
@@ -223,10 +223,10 @@ class ModelPrompt(unittest.TestCase):
def test_asks_again_until_an_answer_picks_a_model(self):
with tempfile.TemporaryDirectory() as empty:
fake = FakeEffects(inputs=["", "my-model"])
self.assertEqual(models.ask_model("proj", "/m.json", pathlib.Path(empty), fake.effects()), "my-model")
self.assertEqual(models.ask_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), fake.effects()), "my-model")
self.assertEqual(len(fake.made("input")), 2)
fake = FakeEffects(inputs=[EOFError()])
self.assertEqual(models.ask_model("proj", "/m.json", pathlib.Path(empty), fake.effects()), Stop(2, "the human is needed to pick proj's model, but the input ended"))
self.assertEqual(models.ask_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), fake.effects()), Stop(2, "the human is needed to pick proj's model, but the input ended"))
class WorkerArgs(unittest.TestCase):
@@ -271,6 +271,7 @@ class HumanTurns(unittest.TestCase):
human("<command-name>/model</command-name>"),
{**human("<3 merge it"), "promptSource": "typed"},
{**human("<task-notification>done</task-notification>"), "promptSource": "system"},
{**human([{"type": "text", "text": "<task-notification>done</task-notification>"}]), "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"])
+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", "-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)
+1 -1
View File
@@ -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. 2026-10-01, lilleman: the suite also passes `--disallow-untyped-defs`, so every def carries full annotations and a reader learns a parameter's type at its def without tracing callers (goal 4.1). Valid while the suite fetches mypy through `uv`.
## review: an ask no user answers leaves the PR unmerged
+8 -5
View File
@@ -4,14 +4,17 @@
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").
### Under the 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.
The panels on `rebuild` at 8585257 and on PR #182 named these under Self-sufficiency and Locality, the two dimensions under the floor. Scores: `docs/decisions.md` → "comprehension floor".
- **Make a failed session delete stop the loop, and give the session one owner.** `delete_session` 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.
- **State in `reload.py` why a loop reloads its own script, and tie each exit-1 clause of `--help` to the `Stop` that produces it.** Two seats found the reload's purpose nowhere in the code, and one could keep the exit contract true only by grepping every `Stop(1`. Name what a reload could not read, and its likely cause, in both `--help` and the reload's error: "loop run" is defined nowhere a reader looks. Goal 4.1.
### The rest
- **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 "a judge decides interrupts, not the worker's self-report" to match. Goal 4.2.
- **Archive the transcript as each cycle ends.** Today only an interrupt or a finished chunk archives it, so after a failed exit or Ctrl-C the transcript stays unarchived until the chunk finishes, and is never archived if it does not. 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_name` 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.
@@ -55,4 +58,4 @@ The first six items are the places the panels on `rebuild` at 8585257 and on PR
- 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 the 2026-09-30 bench's scripts: `~/code/claude-handoffs/claude-config/2026-09-30/bench/`. Needs the stats line. Goals 4.1 and 4.4.
- **Bring the project to the comprehension floor on the four-seat panel.** Every dimension and the overall must reach 7.0, and none may fall below its best run on `rebuild`. A dimension under the floor gets its places filed above this item.
- **Bring the project to the comprehension floor on the four-seat panel.** Every dimension and the overall must reach 7.0, and none may fall below its best run on `rebuild`. A dimension under the floor gets its places filed under "Under the comprehension floor".